~aasg/aoc2020

2c04d586ef0e73227c20da1fb489f007a73fafed — Aluísio Augusto Silva Gonçalves 2 months ago d792773
Record inputs and program for day 4, task 2
3 files changed, 67 insertions(+), 0 deletions(-)

A 4-2.nix
A 4-sample-invalid.txt
A 4-sample-valid.txt
A 4-2.nix => 4-2.nix +42 -0
@@ 0,0 1,42 @@
# SPDX-FileCopyrightText: 2020 Aluísio Augusto Silva Gonçalves <https://aasg.name>
#
# SPDX-License-Identifier: CC0-1.0

{ pkgs ? import <nixpkgs> { }
, aasg-nixexprs ? fetchTarball "https://git.sr.ht/~aasg/nixexprs/archive/master.tar.gz"
}:
with import "${aasg-nixexprs}/lib/extension.nix" { inherit (pkgs) lib; };
let requiredFields = [ "byr" "iyr" "eyr" "hgt" "hcl" "ecl" "pid" ];
in
pipe ./4-input.txt [
  readFile
  (splitString "\n")
  # Group up lines separated by blank lines.
  (flip foldl' { result = [ ]; current = [ ]; } (acc: line:
    if line == ""
    then { result = acc.result ++ [ acc.current ]; current = [ ]; }
    else { result = acc.result; current = acc.current ++ [ line ]; }
  ))
  ({ result, ... }: map (lines: concatStringsSep " " lines) result)
  # Convert each line into an attrset, with key-value pairs separated
  # by a single space and keys separated from values by a colon.
  (map (flip pipe [
    (splitString " ")
    (map (kv:
      let pair = splitString ":" kv; in nameValuePair (elemAt pair 0) (elemAt pair 1)))
    listToAttrs
  ]))
  (count (passport: all id [
    # To validate that each line contains the required fields, verify that
    # the list of required attributes is a subset of the attributes in the
    # line.
    (isSubsetOf (attrNames passport) requiredFields)
    (builtins.match "19[2-9][0-9]|200[0-2]" passport.byr != null)
    (builtins.match "20(1[0-9]|20)" passport.iyr != null)
    (builtins.match "20(2[0-9]|30)" passport.eyr != null)
    (builtins.match "(1[5-8][0-9]|19[0-3])cm|(59|6[0-9]|7[0-6])in" passport.hgt != null)
    (builtins.match "#[[:xdigit:]]{6}" passport.hcl != null)
    (builtins.match "amb|blu|brn|gry|grn|hzl|oth" passport.ecl != null)
    (builtins.match "[[:digit:]]{9}" passport.pid != null)
  ]))
]

A 4-sample-invalid.txt => 4-sample-invalid.txt +13 -0
@@ 0,0 1,13 @@
eyr:1972 cid:100
hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926

iyr:2019
hcl:#602927 eyr:1967 hgt:170cm
ecl:grn pid:012533040 byr:1946

hcl:dab227 iyr:2012
ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277

hgt:59cm ecl:zzz
eyr:2038 hcl:74454a iyr:2023
pid:3556412378 byr:2007

A 4-sample-valid.txt => 4-sample-valid.txt +12 -0
@@ 0,0 1,12 @@
pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980
hcl:#623a2f

eyr:2029 ecl:blu cid:129 byr:1989
iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm

hcl:#888785
hgt:164cm byr:2001 iyr:2015 cid:88
pid:545766238 ecl:hzl
eyr:2022

iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719