From 2e17bfb03417ab1e01d31e1f5d09e94d1cdebdd9 Mon Sep 17 00:00:00 2001 From: Wesley Moore Date: Sat, 3 Dec 2022 16:34:01 +1000 Subject: [PATCH] Day 3 part 2 --- 2022/src/days/day_3.gleam | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/2022/src/days/day_3.gleam b/2022/src/days/day_3.gleam index 33545e8..4eed40d 100644 --- a/2022/src/days/day_3.gleam +++ b/2022/src/days/day_3.gleam @@ -1,6 +1,7 @@ import gleam/int import gleam/set import gleam/list.{map} +import gleam/iterator import gleam/string type Rucksack = @@ -8,15 +9,21 @@ type Rucksack = pub fn pt_1(input: String) -> Int { string.split(input, on: "\n") - |> list.map(string.to_graphemes) - |> list.map(split_in_half) - |> list.map(common_item) - |> list.map(priority) + |> map(string.to_graphemes) + |> map(split_in_half) + |> map(common_item) + |> map(priority) |> int.sum } pub fn pt_2(input: String) -> Int { - todo + string.split(input, on: "\n") + |> map(string.to_graphemes) + |> iterator.from_list + |> iterator.sized_chunk(3) + |> iterator.map(common_item_pt2) + |> iterator.map(priority) + |> iterator.fold(0, fn(sum, prio) { sum + prio }) } fn split_in_half(l: List(String)) -> Rucksack { @@ -35,6 +42,19 @@ fn common_item(rucksack: Rucksack) -> String { common } +fn common_item_pt2(sacks: List(List(String))) -> String { + assert Ok(inter) = + sacks + |> map(set.from_list) + |> list.reduce(set.intersection) + assert 1 = set.size(inter) + assert Ok(common) = + inter + |> set.to_list + |> list.first + common +} + // Lowercase item types a through z have priorities 1 through 26. // Uppercase item types A through Z have priorities 27 through 52. // I can't find a way to get a codepoint or match on a range with Gleam so this