Day 1
This commit is contained in:
1000
day1/data.txt
Normal file
1000
day1/data.txt
Normal file
File diff suppressed because it is too large
Load Diff
6
day1/example.txt
Normal file
6
day1/example.txt
Normal file
@ -0,0 +1,6 @@
|
||||
3 4
|
||||
4 3
|
||||
2 5
|
||||
1 3
|
||||
3 9
|
||||
3 3
|
3
day1/go.mod
Normal file
3
day1/go.mod
Normal file
@ -0,0 +1,3 @@
|
||||
module stevenlr.com/aoc2024/day1
|
||||
|
||||
go 1.22.2
|
89
day1/main.go
Normal file
89
day1/main.go
Normal file
@ -0,0 +1,89 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func IntAbs(a int) int {
|
||||
if a >= 0 {
|
||||
return a
|
||||
}
|
||||
return -a
|
||||
}
|
||||
|
||||
func main() {
|
||||
part2(readData("data.txt"))
|
||||
}
|
||||
|
||||
func readData(fileName string) (list1, list2 []int) {
|
||||
fp, err := os.Open(fileName)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
scanner := bufio.NewScanner(fp)
|
||||
|
||||
list1 = make([]int, 0)
|
||||
list2 = make([]int, 0)
|
||||
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
split := strings.Split(line, " ")
|
||||
if len(split) != 2 {
|
||||
continue
|
||||
}
|
||||
|
||||
value1, err := strconv.Atoi(split[0])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
value2, err := strconv.Atoi(split[1])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
list1 = append(list1, value1)
|
||||
list2 = append(list2, value2)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func part1(list1, list2 []int) {
|
||||
sort.Sort(sort.IntSlice(list1))
|
||||
sort.Sort(sort.IntSlice(list2))
|
||||
|
||||
dist := 0
|
||||
for i := range list1 {
|
||||
dist += IntAbs(list1[i] - list2[i])
|
||||
}
|
||||
|
||||
fmt.Println(dist)
|
||||
}
|
||||
|
||||
func countInstances(list []int) (counts map[int]int) {
|
||||
counts = make(map[int]int)
|
||||
for _, n := range list {
|
||||
counts[n] += 1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func part2(list1, list2 []int) {
|
||||
counts1 := countInstances(list1)
|
||||
counts2 := countInstances(list2)
|
||||
|
||||
total := 0
|
||||
for n, c1 := range counts1 {
|
||||
c2, _ := counts2[n]
|
||||
total += n * c1 * c2
|
||||
}
|
||||
|
||||
fmt.Println(total)
|
||||
}
|
Reference in New Issue
Block a user