~aasg/aoc2020

a46cf0f179f888992dbeb16e1596b3778f7e96e1 — Aluísio Augusto Silva Gonçalves 2 months ago 950b259
Record inputs and program for day 7, task 2
2 files changed, 38 insertions(+), 0 deletions(-)

A 7-2.nix
A 7-sample2.txt
A 7-2.nix => 7-2.nix +31 -0
@@ 0,0 1,31 @@
# 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
  containedBags = bag: rules:
    foldl' add 0
      (mapAttrsToList (contained: qty: qty * (1 + (containedBags contained rules))) rules.${bag});
in
pipe ./7-input.txt [
  readFile
  (splitString "\n")
  (filter (s: s != ""))
  (map (builtins.match "(.+) bags contain (.+)\."))
  (map (matches: {
    name = elemAt matches 0;
    value = pipe (elemAt matches 1) [
      (splitString ", ")
      (map (builtins.match ("([[:digit:]]+) (.+) bags?")))
      (remove null)
      (map (matches: nameValuePair (elemAt matches 1) (toInt (elemAt matches 0))))
      listToAttrs
    ];
  }))
  listToAttrs
  (containedBags "shiny gold")
]

A 7-sample2.txt => 7-sample2.txt +7 -0
@@ 0,0 1,7 @@
shiny gold bags contain 2 dark red bags.
dark red bags contain 2 dark orange bags.
dark orange bags contain 2 dark yellow bags.
dark yellow bags contain 2 dark green bags.
dark green bags contain 2 dark blue bags.
dark blue bags contain 2 dark violet bags.
dark violet bags contain no other bags.