idk
day1.gleam
65 lines 1.4 kB view raw
1import util 2import gleam/list 3import gleam/int 4import gleam/dict.{type Dict} 5import gleam/result.{unwrap} 6 7fn read_file(filepath: String) -> List(List(Int)) { 8 filepath 9 |> util.slurp() 10 |> util.parse_with(util.splarse) 11} 12 13pub fn solve(filepath: String) { 14 let parsed_file = read_file(filepath) 15 16 #(solve_part1(parsed_file), solve_part2(parsed_file)) 17} 18 19fn calc_diff(num_list: List(Int)) -> Int { 20 case num_list { 21 [a, b] -> int.absolute_value(b - a) 22 _ -> 0 23 } 24} 25 26fn calc_all_diffs(number_lists: List(List(Int)), res: List(Int)) -> List(Int) { 27 case number_lists { 28 [[a, ..rest_a], [b, ..rest_b]] -> calc_all_diffs([rest_a, rest_b], [int.absolute_value(b - a), ..res]) 29 [[], []] -> res 30 _ -> [0] 31 } 32} 33 34pub fn solve_part1(parsed_file: List(List(Int))) { 35 parsed_file 36 |> list.transpose 37 |> list.map(with: fn(x) { list.sort(x, by: int.compare) }) 38 |> calc_all_diffs([]) 39 |> list.reduce(fn(a, b) { a + b}) 40} 41 42pub fn solve_part2(parsed_file: List(List(Int))) { 43 let number_sets = list.transpose(parsed_file) 44 45 let occurences: Dict(Int, Int) = { 46 case number_sets { 47 [_, b] -> util.frequencies(b) 48 _ -> dict.new() 49 } 50 } 51 52 let first_nums = { 53 case list.first(number_sets) { 54 Ok(v) -> v 55 Error(_) -> [] 56 } 57 } 58 59 list.fold(first_nums, 0, fn(acc, a) { 60 case dict.get(occurences, a) { 61 Ok(v) -> acc + a * v 62 Error(_) -> acc 63 } 64 }) 65}