Jelajahi Sumber

day 5 part 1 & 2

Abderrahmane Faiz 2 minggu lalu
induk
melakukan
c8122c44ec
3 mengubah file dengan 112 tambahan dan 1 penghapusan
  1. 46 0
      5/solve_1.go
  2. 65 0
      5/solve_2.go
  3. 1 1
      README.md

+ 46 - 0
5/solve_1.go

@@ -0,0 +1,46 @@
+package main
+
+import (
+	"bufio"
+	"fmt"
+	"os"
+	"strconv"
+	"strings"
+)
+
+type interval struct {
+	lb,ub int64
+}
+
+func main(){
+	fmt.Println("Advent of Code 2025 - Day 5 - Part 1")
+	f,_:= os.Open("5/input")
+	defer f.Close()
+	scanner := bufio.NewScanner(f)
+
+	var ranges []interval;
+	
+	for scanner.Scan(){
+		line := scanner.Text()
+		if (len(line) == 0){
+			break
+		}
+		line_split := strings.Split(line, "-")
+		lb,_ := strconv.ParseInt(line_split[0],10,64)
+		ub,_ := strconv.ParseInt(line_split[1],10,64)
+		ranges = append(ranges, interval{lb,ub})
+	}
+
+	res := 0
+	for scanner.Scan(){
+		line := scanner.Text()
+		id,_ := strconv.ParseInt(line,10,64)
+		for _, itvl := range ranges {
+			if (itvl.lb <= id  && id <= itvl.ub) {
+				res++
+				break
+			}
+		}
+	}
+	fmt.Println(res)
+}

+ 65 - 0
5/solve_2.go

@@ -0,0 +1,65 @@
+package main
+
+import (
+	"bufio"
+	"fmt"
+	"os"
+	"sort"
+	"strconv"
+	"strings"
+)
+
+type interval struct {
+	lb,ub int64
+}
+
+type sinterval []interval
+
+func (a sinterval) Len() int { return len(a)}
+func (a sinterval) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
+func (a sinterval) Less(i, j int) bool { return a[i].lb < a[j].lb }
+
+func main(){
+	fmt.Println("Advent of Code 2025 - Day 5 - Part 2")
+	f,_:= os.Open("5/input")
+	defer f.Close()
+	scanner := bufio.NewScanner(f)
+
+	var ranges []interval;
+	
+	for scanner.Scan(){
+		line := scanner.Text()
+		if (len(line) == 0){
+			break
+		}
+		line_split := strings.Split(line, "-")
+		lb,_ := strconv.ParseInt(line_split[0],10,64)
+		ub,_ := strconv.ParseInt(line_split[1],10,64)
+		ranges = append(ranges, interval{lb,ub})
+	}
+
+	res := int64(0)
+	sort.Sort(sinterval(ranges))
+
+	var compressed_ranges []interval;
+	for _, itvl := range ranges{
+		if (len(compressed_ranges)==0){
+			compressed_ranges = append(compressed_ranges, itvl)
+		} else {
+			last_compressed := &compressed_ranges[len(compressed_ranges)-1]
+			if (last_compressed.ub >= itvl.lb){
+				last_compressed.ub = max(itvl.ub, last_compressed.ub)
+			} else {
+				compressed_ranges = append(compressed_ranges, itvl)				
+			}
+		}
+	}
+
+	for _,itvl := range compressed_ranges{
+		res += itvl.ub - itvl.lb + 1
+	}
+	
+	fmt.Println(res)
+}
+
+

+ 1 - 1
README.md

@@ -24,7 +24,7 @@ Each day's folder is named after the day number (`1` to `12`). Inside each folde
 | 2   | ✅     | ✅     |
 | 3   | ✅     | ✅     |
 | 4   | ✅     | ✅     |
-| 5   | ⬜     | ⬜     |
+| 5   | ✅     | ✅     |
 | 6   | ⬜     | ⬜     |
 | 7   | ⬜     | ⬜     |
 | 8   | ⬜     | ⬜     |