-
Notifications
You must be signed in to change notification settings - Fork 3
/
day02.ex
48 lines (41 loc) · 1.1 KB
/
day02.ex
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
defmodule Elixir2020.Day02 do
def parse(filename) do
File.stream!(filename)
|> Enum.map(&String.trim/1)
|> Enum.map(&parse_rules/1)
end
def parse_rules(string) do
[_, lower, upper, letter, password] = Regex.run(~r/^(\d+)-(\d+) (\w+): (\w+)$/, string)
%{
lower: String.to_integer(lower),
upper: String.to_integer(upper),
letter: letter,
password: password
}
end
def test1(%{lower: lower, upper: upper, letter: letter, password: password}) do
count =
password
|> String.graphemes()
|> Enum.filter(fn x -> x == letter end)
|> Enum.count()
lower <= count and count <= upper
end
def test2(%{lower: lower, upper: upper, letter: letter, password: password}) do
lower_match = String.at(password, lower - 1) == letter
upper_match = String.at(password, upper - 1) == letter
lower_match != upper_match
end
def part1(filename) do
filename
|> parse()
|> Enum.filter(&test1/1)
|> Enum.count()
end
def part2(filename) do
filename
|> parse()
|> Enum.filter(&test2/1)
|> Enum.count()
end
end