aboutsummaryrefslogtreecommitdiff
path: root/aoc-2020-gleam/src/days/day06.gleam
blob: 6c3481cc9443656fb9971cf0cb9f275a9bfc24fe (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
86
87
88
89
90
91
92
import gleam/io
import gleam/int
import gleam/string
import gleam/list
import gleam/set.{Set}
import ext/resultx
import util/parser as p
import util/input_util

type Answers =
  Set(String)

type Group =
  List(Answers)

type Input =
  List(Group)

fn alphabet() -> Set(String) {
  set.from_list(string.to_graphemes("abcdefghijklmnopqrstuvwxyz"))
}

fn parse_input(text: String) -> Input {
  let answers_parser =
    p.str1_until_ws()
    |> p.map(fn(answer_string) {
      answer_string
      |> string.to_graphemes
      |> set.from_list
    })
    |> p.labeled(with: "answers")

  let group_parser =
    answers_parser
    |> p.sep1(by: p.ws_gc())
    |> p.labeled(with: "group")

  let input_parser =
    group_parser
    |> p.sep1(by: p.literal("\n\n"))
    |> p.then_skip(p.opt(p.ws_gc()))
    |> p.labeled(with: "input")

  text
  |> p.parse_entire(with: input_parser)
  |> resultx.force_unwrap
}

fn fold_group(
  over group: Group,
  from initial: Set(String),
  with fun: fn(Set(String), Set(String)) -> Set(String),
) -> Int {
  group
  |> list.fold(from: initial, with: fun)
  |> set.size
}

fn answered_by_anyone(in group: Group) -> Int {
  fold_group(over: group, from: set.new(), with: set.union)
}

fn answered_by_everyone(in group: Group) -> Int {
  fold_group(over: group, from: alphabet(), with: set.intersection)
}

fn solve(text: String, with folder: fn(Group) -> Int) -> Int {
  text
  |> parse_input
  |> list.map(with: folder)
  |> int.sum
}

fn part1(text: String) -> Int {
  solve(text, with: answered_by_anyone)
}

fn part2(text: String) -> Int {
  solve(text, with: answered_by_everyone)
}

pub fn run() -> Nil {
  let test = input_util.read_text("test06")
  assert 11 = part1(test)
  assert 6 = part2(test)

  let input = input_util.read_text("day06")
  io.debug(part1(input))
  io.debug(part2(input))

  Nil
}