diff options
author | J.J <thechairman@thechairman.info> | 2023-12-01 12:59:15 -0500 |
---|---|---|
committer | J.J <thechairman@thechairman.info> | 2023-12-01 12:59:15 -0500 |
commit | d8a9e1520f51c1021a0eba589a8716621a8e5893 (patch) | |
tree | 8243093fcd2a6dfc2da64c4ceae7761c681bab23 /aoc2023/src/day1/solve.gleam | |
parent | e6623bd6c19db62ca17556fc16e5c4c874ae7509 (diff) | |
parent | a2bcd6b53e5b94ad4d6b9eb3e847dae210db1704 (diff) | |
download | gleam_aoc-d8a9e1520f51c1021a0eba589a8716621a8e5893.tar.gz gleam_aoc-d8a9e1520f51c1021a0eba589a8716621a8e5893.zip |
Merge branch 'main' of https://github.com/hunkyjimpjorps/AdventOfCode
Diffstat (limited to 'aoc2023/src/day1/solve.gleam')
-rw-r--r-- | aoc2023/src/day1/solve.gleam | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/aoc2023/src/day1/solve.gleam b/aoc2023/src/day1/solve.gleam new file mode 100644 index 0000000..fbc160f --- /dev/null +++ b/aoc2023/src/day1/solve.gleam @@ -0,0 +1,70 @@ +import adglent.{First, Second} +import gleam/io +import gleam/list +import gleam/string +import gleam/regex.{type Match, Match} +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) + + let assert Ok(Match(content: first, ..)) = list.first(matches) + let assert Ok(Match(content: last, ..)) = list.last(matches) + + int.parse(first <> last) + }) +} + +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 + } +} |