this repo has no description
1<!-- vim:set ft=markdown: -->
2
3<!-- livebook:{"persist_outputs":true} -->
4
5# Day 2
6
7## Load input
8
9We do parsing there, as it will help us with the latter tasks. Pattern matching
10is the simplest approach there, as input is in form of:
11
12```
13forward 10
14up 20
15down 30
16```
17
18We need to `trim/1` input to make sure that the last newline will not interrupt
19`String.to_integer/1` calls.
20
21```elixir
22stream =
23 File.stream!("day2.txt")
24 |> Stream.map(fn input ->
25 case String.trim(input) do
26 "forward " <> n -> {:forward, String.to_integer(n)}
27 "up " <> n -> {:up, String.to_integer(n)}
28 "down " <> n -> {:down, String.to_integer(n)}
29 end
30 end)
31```
32
33```output
34#Stream<[
35 enum: %File.Stream{
36 line_or_bytes: :line,
37 modes: [:raw, :read_ahead, :binary],
38 path: "day2.txt",
39 raw: true
40 },
41 funs: [#Function<47.58486609/1 in Stream.map/2>]
42]>
43```
44
45## Task 1
46
47```elixir
48{h, d} =
49 stream
50 |> Enum.reduce({0, 0}, fn
51 {:forward, n}, {h, d} -> {h + n, d}
52 {:up, n}, {h, d} -> {h, d - n}
53 {:down, n}, {h, d} -> {h, d + n}
54 end)
55
56h * d
57```
58
59```output
601499229
61```
62
63## Task 2
64
65```elixir
66{h, d, _} =
67 stream
68 |> Enum.reduce({0, 0, 0}, fn
69 {:forward, n}, {h, d, a} -> {h + n, d + a * n, a}
70 {:up, n}, {h, d, a} -> {h, d, a - n}
71 {:down, n}, {h, d, a} -> {h, d, a + n}
72 end)
73
74h * d
75```
76
77```output
781340836560
79```