From 4b3fc7eb73cff42d187d5f0a28e688b20cd76392 Mon Sep 17 00:00:00 2001 From: xuu Date: Sun, 1 Dec 2024 11:37:27 -0700 Subject: [PATCH] chore: make reduce more iter.Seq --- aoc2023/day14/main.go | 3 ++- aoc2023/day15/main.go | 4 ++-- itertools.go | 16 ++++++++++++++-- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/aoc2023/day14/main.go b/aoc2023/day14/main.go index 1d1d135..963d2d2 100644 --- a/aoc2023/day14/main.go +++ b/aoc2023/day14/main.go @@ -4,6 +4,7 @@ import ( "bufio" _ "embed" "fmt" + "slices" "strings" aoc "go.sour.is/advent-of-code" @@ -62,7 +63,7 @@ func run(scan *bufio.Scanner) (*result, error) { func(i int, v int, counts [3]int) [3]int { counts[v]++ return counts - }, [3]int{}, maps.Values(memo)...) + }, [3]int{}, slices.Values(maps.Values(memo))) // fmt.Println(i, counts) i = 1_000_000_000 - (1_000_000_000-counts[0]-counts[1])%counts[2] diff --git a/aoc2023/day15/main.go b/aoc2023/day15/main.go index fa35168..14365df 100644 --- a/aoc2023/day15/main.go +++ b/aoc2023/day15/main.go @@ -32,14 +32,14 @@ func run(scan *bufio.Scanner) (*result, error) { r.valuePT1 = aoc.Reduce(func(i int, t string, sum int) int { sum += hash(t) return sum - }, 0, ops...) + }, 0, slices.Values(ops)) } var boxen boxes boxen = aoc.Reduce(func(i int, op string, b boxes) boxes { return b.Op(op) - }, boxen, ops...) + }, boxen, slices.Values(ops)) r.valuePT2 = boxen.Sum() diff --git a/itertools.go b/itertools.go index 6736518..3631055 100644 --- a/itertools.go +++ b/itertools.go @@ -1,6 +1,7 @@ package aoc import ( + "iter" "strconv" ) @@ -17,8 +18,8 @@ func Repeat[T any](s T, i int) []T { return lis } -func Reduce[T, U any](fn func(int, T, U) U, u U, list ...T) U { - for i, t := range list { +func Reduce[T, U any](fn func(int, T, U) U, u U, list iter.Seq[T]) U { + for i, t := range Enumerate(list) { u = fn(i, t, u) } return u @@ -54,3 +55,14 @@ func Pairwise[T any](arr []T) [][2]T { } return pairs } + +func Enumerate[T any](arr iter.Seq[T]) iter.Seq2[int, T] { + return func(yield func(int, T) bool) { + i := 0 + for v := range arr { + if !yield(i, v) { + return + } + } + } +}