aboutsummaryrefslogtreecommitdiff
path: root/aoc2023-gleam/src/day6/solve.gleam
blob: 88044c4706ec8da50e7d01671014d20c6d995bab (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
79
80
81
82
83
84
85
import adglent.{First, Second}
import gleam/io
import gleam/string
import gleam/int
import gleam/list
import gleam/result

type Race {
  Race(time: Int, distance: Int)
}

fn parse_with_bad_kerning(input: String) {
  input
  |> string.split("\n")
  |> list.map(fn(str) {
    str
    |> string.split(" ")
    |> list.map(int.parse)
    |> result.values
  })
  |> list.transpose
  |> list.map(fn(ns) {
    let assert [t, d] = ns
    Race(t, d)
  })
}

fn find_bound(race: Race, button_time: Int, step: Int) {
  let travel_time = race.time - button_time
  case button_time * travel_time > race.distance {
    True -> button_time
    False -> find_bound(race, button_time + step, step)
  }
}

fn lower_bound(race: Race) {
  find_bound(race, 1, 1)
}

fn upper_bound(race: Race) {
  find_bound(race, race.time, -1)
}

pub fn part1(input: String) {
  {
    use acc, race <- list.fold(parse_with_bad_kerning(input), 1)
    acc * { upper_bound(race) - lower_bound(race) + 1 }
  }
  |> string.inspect
}

fn parse_properly(input: String) {
  input
  |> string.replace(" ", "")
  |> string.split("\n")
  |> list.flat_map(string.split(_, ":"))
  |> list.map(int.parse)
  |> result.values
}

pub fn part2(input: String) {
  let assert [time, distance] =
    input
    |> parse_properly

  let race = Race(time, distance)

  upper_bound(race) - lower_bound(race) + 1
  |> string.inspect
}

pub fn main() {
  let assert Ok(part) = adglent.get_part()
  let assert Ok(input) = adglent.get_input("6")
  case part {
    First ->
      part1(input)
      |> adglent.inspect
      |> io.println
    Second ->
      part2(input)
      |> adglent.inspect
      |> io.println
  }
}