2024/day1/puzzle2.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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 }