Created
December 4, 2020 12:16
-
-
Save ynonp/f931e3e8c3b16162678efddd8a50cc28 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Day4 do | |
def read_input do | |
File.read!("input/day4.txt") | |
|> String.split("\n\n", trim: true) | |
|> Enum.map(&to_passport/1) | |
end | |
def to_passport(str) do | |
str | |
|> String.split(~r{\s+}, trim: true) | |
|> Enum.map(fn pair -> String.split(pair, ":") end) | |
|> Enum.map(&List.to_tuple/1) | |
|> Enum.into(%{}) | |
end | |
def validate_numeric(key, min, max) do | |
fn %{^key => value} -> | |
val = String.to_integer(value) | |
val >= min and val <= max | |
end | |
end | |
def validate_regexp(key, regexp) do | |
fn %{^key => value} -> | |
String.match?(value, regexp) | |
end | |
end | |
def validate_height(key) do | |
fn %{^key => value} -> | |
case Integer.parse(value) do | |
{val, "cm"} -> (val >= 150) and (val <= 193) | |
{val, "in"} -> (val >= 59) and (val <= 76) | |
_ -> false | |
end | |
end | |
end | |
def check_passport_2(passport) do | |
[ | |
&check_passport/1, | |
validate_numeric("byr", 1920, 2002), | |
validate_numeric("iyr", 2010, 2020), | |
validate_numeric("eyr", 2020, 2030), | |
validate_height("hgt"), | |
validate_regexp("hcl", ~r/^#[0-9a-f]{6}$/), | |
validate_regexp("ecl", ~r/^(amb|blu|brn|gry|grn|hzl|oth)$/), | |
validate_regexp("pid", ~r/^[0-9]{9}$/) | |
] | |
|> Enum.all?(fn validator -> validator.(passport) end) | |
end | |
def check_passport(passport) do | |
["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"] | |
|> Enum.all?(fn key -> | |
Map.has_key?(passport, key) | |
end) | |
end | |
def part1 do | |
read_input() | |
|> Enum.filter(&check_passport/1) | |
|> Enum.count | |
|> IO.inspect | |
end | |
def part2 do | |
read_input() | |
|> Enum.filter(&check_passport_2/1) | |
|> Enum.count | |
|> IO.inspect | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment