From 7a5f1983f9189422ad5e12afde11d11bec30a3f1 Mon Sep 17 00:00:00 2001 From: Tomasz Chojnacki Date: Fri, 22 Dec 2023 18:31:14 +0100 Subject: Solve part 1 of day 20 --- aoc-2020-gleam/src/ext/iteratorx.gleam | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) (limited to 'aoc-2020-gleam/src/ext/iteratorx.gleam') diff --git a/aoc-2020-gleam/src/ext/iteratorx.gleam b/aoc-2020-gleam/src/ext/iteratorx.gleam index 0e59f17..6c7838d 100644 --- a/aoc-2020-gleam/src/ext/iteratorx.gleam +++ b/aoc-2020-gleam/src/ext/iteratorx.gleam @@ -1,3 +1,6 @@ +import gleam/int +import gleam/result as res +import gleam/dict.{type Dict} import gleam/iterator.{type Iterator, Next} as iter pub fn length(iterator: Iterator(a)) -> Int { @@ -11,6 +14,19 @@ pub fn count(iterator: Iterator(a), satisfying predicate: fn(a) -> Bool) -> Int |> length } +pub fn counts(iterator: Iterator(a)) -> Dict(a, Int) { + iterator + |> iter.fold(from: dict.new(), with: fn(acc, value) { + acc + |> dict.insert( + value, + dict.get(acc, value) + |> res.unwrap(or: 0) + |> int.add(1), + ) + }) +} + pub fn filter_map( iterator: Iterator(a), with mapper: fn(a) -> Result(b, c), @@ -25,8 +41,5 @@ pub fn filter_map( } pub fn unfold_infinitely(from state: a, with fun: fn(a) -> a) -> Iterator(a) { - iter.unfold( - from: state, - with: fn(s) { Next(element: s, accumulator: fun(s)) }, - ) + iter.unfold(from: state, with: fn(s) { Next(element: s, accumulator: fun(s)) }) } -- cgit v1.2.3