You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
931 B
66 lines
931 B
3 weeks ago
|
package main
|
||
|
|
||
|
import (
|
||
|
"bufio"
|
||
|
"fmt"
|
||
|
"io"
|
||
|
"log"
|
||
|
"os"
|
||
|
"sort"
|
||
|
)
|
||
|
|
||
|
func part1(r io.Reader) string {
|
||
|
s := bufio.NewScanner(r)
|
||
|
var sum int
|
||
|
var left, right []int
|
||
|
|
||
|
var lft, rgh int
|
||
|
for s.Scan() {
|
||
|
fmt.Sscanf(s.Text(), "%d %d", &lft, &rgh)
|
||
|
left, right = append(left, lft), append(right, rgh)
|
||
|
}
|
||
|
|
||
|
sort.Ints(left)
|
||
|
sort.Ints(right)
|
||
|
|
||
|
for i := range right {
|
||
|
sum += abs(left[i] - right[i])
|
||
|
}
|
||
|
|
||
|
return printi(sum)
|
||
|
}
|
||
|
|
||
|
func part2(r io.Reader) string {
|
||
|
s := bufio.NewScanner(r)
|
||
|
var sum int
|
||
|
var left []int
|
||
|
right := make(map[int]int)
|
||
|
|
||
|
var lft, rgh int
|
||
|
for s.Scan() {
|
||
|
fmt.Sscanf(s.Text(), "%d %d", &lft, &rgh)
|
||
|
left = append(left, lft)
|
||
|
right[rgh]++
|
||
|
}
|
||
|
|
||
|
sort.Ints(left)
|
||
|
|
||
|
for i := range left {
|
||
|
sum += left[i] * right[left[i]]
|
||
|
}
|
||
|
|
||
|
return printi(sum)
|
||
|
}
|
||
|
|
||
|
func main() {
|
||
|
f, err := os.Open("day01.txt")
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
defer f.Close()
|
||
|
|
||
|
fmt.Println(part1(f))
|
||
|
f.Seek(0, 0)
|
||
|
fmt.Println(part2(f))
|
||
|
}
|