aboutsummaryrefslogtreecommitdiff
path: root/aoc2023/src/day1/solve.gleam
blob: a1092b1ce82bb92b0d8f42a95659f85d52995061 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
  }
}