aboutsummaryrefslogtreecommitdiff
path: root/aoc2017-gleam/src/aoc_2017/day_2.gleam
blob: 6a5e85d1c50367b1f841a9d7b01b3be6a2eb006b (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
import gleam/int
import gleam/list
import gleam/result
import gleam/string

pub fn parse(input: String) {
  use row <- list.map(string.split(input, "\n"))
  use val <- list.map(string.split(row, "\t"))
  let assert Ok(n) = int.parse(val)
  n
}

pub fn pt_1(input: List(List(Int))) {
  use acc, row <- list.fold(input, 0)
  acc + max(row) - min(row)
}

pub fn pt_2(input: List(List(Int))) {
  use acc, row <- list.fold(input, 0)
  let assert [val] =
    row |> list.combination_pairs() |> list.map(test_pair) |> result.values()
  acc + val
}

fn max(xs) {
  let assert Ok(result) = list.reduce(xs, int.max)
  result
}

fn min(xs) {
  let assert Ok(result) = list.reduce(xs, int.min)
  result
}

fn test_pair(tup) {
  case tup {
    #(a, b) if a > b -> check_divisibility(a, b)
    #(b, a) -> check_divisibility(a, b)
  }
}

fn check_divisibility(a, b) {
  case a % b {
    0 -> Ok(a / b)
    _ -> Error(Nil)
  }
}