diff options
Diffstat (limited to 'day1/main.go')
-rw-r--r-- | day1/main.go | 89 |
1 files changed, 89 insertions, 0 deletions
diff --git a/day1/main.go b/day1/main.go new file mode 100644 index 0000000..03f738f --- /dev/null +++ b/day1/main.go @@ -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) +} |