feat: add day 1 2024
This commit is contained in:
parent
4b3fc7eb73
commit
b1e4c4d634
|
@ -0,0 +1,6 @@
|
|||
3 4
|
||||
4 3
|
||||
2 5
|
||||
1 3
|
||||
3 9
|
||||
3 3
|
File diff suppressed because it is too large
Load Diff
|
@ -4,6 +4,9 @@ import (
|
|||
"bufio"
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"iter"
|
||||
"slices"
|
||||
"sort"
|
||||
|
||||
aoc "go.sour.is/advent-of-code"
|
||||
)
|
||||
|
@ -20,11 +23,64 @@ type result struct {
|
|||
func (r result) String() string { return fmt.Sprintf("%#v", r) }
|
||||
|
||||
func run(scan *bufio.Scanner) (*result, error) {
|
||||
var (
|
||||
left []int
|
||||
right []int
|
||||
)
|
||||
|
||||
for scan.Scan() {
|
||||
_ = scan.Text()
|
||||
txt := scan.Text()
|
||||
|
||||
var l, r int
|
||||
_, err := fmt.Sscanf(txt, "%d %d", &l, &r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &result{}, nil
|
||||
left = append(left, l)
|
||||
right = append(right, r)
|
||||
}
|
||||
|
||||
sort.Ints(left)
|
||||
sort.Ints(right)
|
||||
|
||||
result := &result{}
|
||||
|
||||
result.valuePT1 = aoc.Reduce(func(i int, z pair[int, int], sum int) int {
|
||||
return sum + aoc.ABS(z.L-z.R)
|
||||
}, 0, zip(slices.Values(left), slices.Values(right)))
|
||||
|
||||
rmap := aoc.Reduce(func(i int, z int, m map[int]int) map[int]int {
|
||||
m[z]++
|
||||
return m
|
||||
}, make(map[int]int), slices.Values(right))
|
||||
|
||||
for _, v := range left {
|
||||
if r, ok := rmap[v]; ok {
|
||||
result.valuePT2 += v*r
|
||||
}
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type pair[L, R any] struct {
|
||||
L L
|
||||
R R
|
||||
}
|
||||
|
||||
func zip[L, R any](l iter.Seq[L], r iter.Seq[R]) iter.Seq[pair[L,R]] {
|
||||
return func(yield func(pair[L, R]) bool) {
|
||||
pullR, stop := iter.Pull(r)
|
||||
defer stop()
|
||||
|
||||
for l := range l {
|
||||
r, _ := pullR()
|
||||
|
||||
if !yield(pair[L, R]{L: l, R: r}) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -24,8 +24,8 @@ func TestExample(t *testing.T) {
|
|||
is.NoErr(err)
|
||||
|
||||
t.Log(result)
|
||||
is.Equal(result.valuePT1, 0)
|
||||
is.Equal(result.valuePT2, 0)
|
||||
is.Equal(result.valuePT1, 11)
|
||||
is.Equal(result.valuePT2, 31)
|
||||
}
|
||||
|
||||
func TestSolution(t *testing.T) {
|
||||
|
@ -36,6 +36,6 @@ func TestSolution(t *testing.T) {
|
|||
is.NoErr(err)
|
||||
|
||||
t.Log(result)
|
||||
is.Equal(result.valuePT1, 0)
|
||||
is.Equal(result.valuePT2, 0)
|
||||
is.Equal(result.valuePT1, 2756096)
|
||||
is.Equal(result.valuePT2, 23117829)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue
Block a user