*
Jes Olson j3s@c3f.net
Sun, 01 Dec 2024 13:20:25 -0500
1 files changed,
52 insertions(+),
0 deletions(-)
jump to
A
2024/day1/puzzle2.go
@@ -0,0 +1,52 @@
+package main + +import ( + "bufio" + "fmt" + "os" + "slices" + "strconv" + "strings" +) + +func main() { + var left []int + var right []int + + file, _ := os.Open("input1.txt") + defer file.Close() + + scanner := bufio.NewScanner(file) + for scanner.Scan() { + line := scanner.Text() + fields := strings.Split(line, " ") + + l, _ := strconv.Atoi(fields[0]) + left = append(left, l) + r, _ := strconv.Atoi(fields[1]) + right = append(right, r) + + slices.Sort(left) + slices.Sort(right) + } + + var total int + for i := range left { + d := similarity(left[i], right) + total += d + } + fmt.Println(total) +} + +// calculate similarity score based on +// how many times n appears in the list +func similarity(n int, list []int) int { + count := 0 + for _, l := range list { + if n == l { + count++ + } + } + + return n * count +}