diff options
author | Tomasz Chojnacki <tomaszchojnacki2001@gmail.com> | 2023-04-30 19:57:57 +0200 |
---|---|---|
committer | Tomasz Chojnacki <tomaszchojnacki2001@gmail.com> | 2023-04-30 19:57:57 +0200 |
commit | 27f5de1ac9b08db01045feabe75650f373238422 (patch) | |
tree | 3e0e43724e0938a3ec0afab3257c3ce0f19cd1c6 /aoc-2020-gleam/src/days | |
parent | ca7b077e7c9ed778f4000c64add81df02bf1667c (diff) | |
download | gleam_aoc2020-27f5de1ac9b08db01045feabe75650f373238422.tar.gz gleam_aoc2020-27f5de1ac9b08db01045feabe75650f373238422.zip |
Finish day 15
Diffstat (limited to 'aoc-2020-gleam/src/days')
-rw-r--r-- | aoc-2020-gleam/src/days/day15.gleam | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/aoc-2020-gleam/src/days/day15.gleam b/aoc-2020-gleam/src/days/day15.gleam new file mode 100644 index 0000000..55ef0b4 --- /dev/null +++ b/aoc-2020-gleam/src/days/day15.gleam @@ -0,0 +1,65 @@ +import gleam/io +import gleam/int +import gleam/list +import gleam/map +import gleam/string as str +import gleam/function as fun +import gleam/iterator as iter +import ext/resultx as resx +import ext/iteratorx as iterx + +fn solve(input: String, nth: Int) -> Int { + let starting = + input + |> str.split(on: ",") + |> list.map(with: fun.compose(int.parse, resx.assert_unwrap)) + + let history = + starting + |> list.index_map(fn(index, number) { #(number, index + 1) }) + |> map.from_list + let turn = list.length(starting) + let assert Ok(last) = list.last(starting) + + iterx.unfold_infinitely( + from: #(history, turn, last), + with: fn(state) { + let #(history, turn, last) = state + #( + map.insert(into: history, for: last, insert: turn), + turn + 1, + case map.get(history, last) { + Ok(previous) -> turn - previous + Error(Nil) -> 0 + }, + ) + }, + ) + |> iter.filter(fn(state) { state.1 == nth }) + |> iter.map(fn(state) { state.2 }) + |> iter.first + |> resx.assert_unwrap +} + +fn part1(input: String) -> Int { + solve(input, 2020) +} + +fn part2(input: String) -> Int { + solve(input, 30_000_000) +} + +pub fn main() -> Nil { + let assert 436 = part1("0,3,6") + let assert 1 = part1("1,3,2") + let assert 27 = part1("1,2,3") + let assert 78 = part1("2,3,1") + let assert 438 = part1("3,2,1") + let assert 1836 = part1("3,1,2") + + let input = "12,20,0,6,1,17,7" + io.debug(part1(input)) + io.debug(part2(input)) + + Nil +} |