diff options
author | HJ <thechairman@thechairman.info> | 2023-12-01 08:37:21 -0500 |
---|---|---|
committer | HJ <thechairman@thechairman.info> | 2023-12-01 08:37:21 -0500 |
commit | e3c88c124a61248e0b17fad34df167d40464d946 (patch) | |
tree | a56c86ad58a949463fe3effefad20093bc92f769 /aoc2023/src/day1/solve.gleam | |
parent | f4b97fff364ded9667eca6a1870b2bd0fc53b853 (diff) | |
download | gleam_aoc-e3c88c124a61248e0b17fad34df167d40464d946.tar.gz gleam_aoc-e3c88c124a61248e0b17fad34df167d40464d946.zip |
day 1 complete
Diffstat (limited to 'aoc2023/src/day1/solve.gleam')
-rw-r--r-- | aoc2023/src/day1/solve.gleam | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/aoc2023/src/day1/solve.gleam b/aoc2023/src/day1/solve.gleam new file mode 100644 index 0000000..a1092b1 --- /dev/null +++ b/aoc2023/src/day1/solve.gleam @@ -0,0 +1,78 @@ +import adglent.{First, Second} +import gleam/io +import gleam/list +import gleam/string +import gleam/regex +import gleam/result +import gleam/int + +fn parse_digits(input: String) { + let assert Ok(re) = regex.from_string("[0-9]") + + input + |> string.split("\n") + |> list.map(fn(s) { + let matches = + regex.scan(s, with: re) + |> list.map(fn(m) { m.content }) + + case matches { + [one] -> int.parse(one <> one) + _ -> + int.parse( + result.unwrap(list.first(matches), "") <> result.unwrap( + list.last(matches), + "", + ), + ) + } + }) +} + +pub fn part1(input: String) { + input + |> parse_digits + |> result.values + |> int.sum + |> string.inspect +} + +const substitutions = [ + #("one", "o1e"), + #("two", "t2o"), + #("three", "t3e"), + #("four", "4"), + #("five", "5e"), + #("six", "6"), + #("seven", "7n"), + #("eight", "e8t"), + #("nine", "n9e"), + #("zero", "0o"), +] + +pub fn part2(input: String) { + list.fold( + over: substitutions, + from: input, + with: fn(acc, sub) { + let #(from, to) = sub + string.replace(in: acc, each: from, with: to) + }, + ) + |> part1 +} + +pub fn main() { + let assert Ok(part) = adglent.get_part() + let assert Ok(input) = adglent.get_input("1") + case part { + First -> + part1(input) + |> adglent.inspect + |> io.println + Second -> + part2(input) + |> adglent.inspect + |> io.println + } +} |