Alexander Avery
1 month ago
commit
70bc75ea0e
6 changed files with 1109 additions and 0 deletions
@ -0,0 +1,65 @@ |
|||||
|
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)) |
||||
|
} |
File diff suppressed because it is too large
@ -0,0 +1,25 @@ |
|||||
|
package main |
||||
|
|
||||
|
import ( |
||||
|
"strings" |
||||
|
"testing" |
||||
|
) |
||||
|
|
||||
|
func TestDay01(t *testing.T) { |
||||
|
input := `3 4 |
||||
|
4 3 |
||||
|
2 5 |
||||
|
1 3 |
||||
|
3 9 |
||||
|
3 3` |
||||
|
|
||||
|
p1, p2 := strings.NewReader(input), strings.NewReader(input) |
||||
|
|
||||
|
if got, expected := part1(p1), "11"; got != expected { |
||||
|
t.Errorf("day01 part 1 = %s; expected %s", got, expected) |
||||
|
} |
||||
|
|
||||
|
if got, expected := part2(p2), "31"; got != expected { |
||||
|
t.Errorf("day01 part 2 = %s; expected %s", got, expected) |
||||
|
} |
||||
|
} |
@ -0,0 +1,9 @@ |
|||||
|
package main |
||||
|
|
||||
|
func abs(i int) int { |
||||
|
r := i |
||||
|
if r < 0 { |
||||
|
r = -r |
||||
|
} |
||||
|
return r |
||||
|
} |
@ -0,0 +1,7 @@ |
|||||
|
package main |
||||
|
|
||||
|
import "fmt" |
||||
|
|
||||
|
func printi(i int) string { |
||||
|
return fmt.Sprintf("%d", i) |
||||
|
} |
@ -0,0 +1,3 @@ |
|||||
|
module adventoc |
||||
|
|
||||
|
go 1.19 |
Loading…
Reference in new issue