require'set'bag_descriptions=[]File.readlines('07.txt').eachdo|line|bag_type=line.match('\A(.*?) bags')[1]contents=[]unlessline.match('contain no other bags')line.scan(/(\d+) (.*?) bags?/).eachdo|count,color|contents.push[color,count]endendbag_descriptions.push({"bag_type"=>bag_type,"contents"=>contents.to_h})enddefscan_for_possible_containers(bag_descriptions,previous_possible_containers)new_containers=Set.newbag_descriptions.eachdo|bag_description|# Direct container of shiny gold bagsifbag_description['contents'].include?'shiny gold'# Don't need to check if already present because Set class is usednew_containers.addbag_description['bag_type']end# Indirect containers of shiny gold bagsunlessprevious_possible_containers.intersection(Set.newbag_description['contents'].keys).empty?# Again, no need to check if already presentnew_containers.addbag_description['bag_type']endendnew_containersendprevious_possible_containers=Set.new# Initial scancurrent_possible_containers=scan_for_possible_containers(bag_descriptions,previous_possible_containers)# Keep iterating until all possible choices are exhausteduntilprevious_possible_containers==current_possible_containersprevious_possible_containers=current_possible_containerscurrent_possible_containers=scan_for_possible_containers(bag_descriptions,previous_possible_containers)endputscurrent_possible_containers.length
I start to like parsing these kind of rules in Haskell, it's very intuitive to me.
The association list was a nice fit for this problem; had I done it in Java, I would have used a Map with Lists as a value. Even though it's not the most time efficient approach, it was allright for this size problem.
solve1::String->Intsolve1input=letassocList=createInvertedMap$mapparseRule$linesinputrecursion=recurse1assocList"shinygold"inlength$nubrecursionrecurse1::[(String,String)]->String->[String]recurse1assocListsearch=letcurrent=lookupAllassocListsearchnext=concatMap(recurse1assocList)currentincurrent++nextsolve2::String->Intsolve2input=letassocList=mapparseRule$linesinputrecursion=recurse2assocList"shinygold"inrecursionrecurse2::[(String,[(String,Int)])]->String->Intrecurse2assocListsearch=letcurrent=concat$lookupAllassocListsearchnext=sum$maprecurseValuecurrentinsum(mapsndcurrent)+nextwhererecurseValue(bag,multiplier)=multiplier*recurse2assocListbag-- parse one line into an association listparseRule::String->(String,[(String,Int)])parseRulea=letkeyValue=splitOn" contain "akey=concat$take2$words$headkeyValuevalue=mapparseContains$splitOn","$keyValue!!1in(key,value)-- "contain 2 shiny gold bags." -> ("shinygold", 2)parseContains::String->(String,Int)parseContains"no other bags."=("none",0)parseContainsa=letremovePeriod=filter(/='.')anoBags=filter(\x->x/="bags"&&x/="bag")$wordsremovePeriodin(concat$tailnoBags,read$headnoBags)-- unwrap the association listcreateInvertedMap::[(String,[(String,b)])]->[(String,String)]createInvertedMap=concatMapinvertwhereinvert(outer,inner)=map((,outer).fst)inner-- a lookup that returns more than one resultlookupAll::[(String,b)]->String->[b]lookupAllassocListkey=mapsnd$filter(\(k,_)->k==key)assocList
Oh dear, I didn't look at the input and assumed there were just the nine colours in the example. Modelled them in an enum and wrote parsers for them all, which failed on the first line of input text. Lesson: look at the real data!
The problem is a directed acyclic graph one. I modelled the graph as a Vec of edges with the start and end nodes, which meant quite expensive searching. It only took 10 or 20 seconds to run but I knew it was a mistake. Reworked to a HashMap where the key is the start of each edge and the value is the Vec of possible end nodes.
The actual graph traversals are the bread and butter of my day job. Those were easy. I wasted a lot of time today on parsing and bad modelling.
usestd::collections::HashMap;usestd::fs::File;usestd::io::prelude::*;modparser;useparser::*;// --- file readfnread_file(filename:&str)->std::io::Result<String>{letmutfile=File::open(filename)?;letmutcontents=String::new();file.read_to_string(&mutcontents)?;Ok(contents)}// --- model#[derive(Debug,Clone,Eq,Hash,PartialEq)]structBagColor(String,String);implBagColor{fnof(adj:&str,col:&str)->Self{BagColor(String::from(adj),String::from(col))}}#[derive(Debug,Eq,PartialEq)]structContent{color:BagColor,count:usize}#[derive(Debug,Eq,PartialEq)]structContainsRule{container:BagColor,contents:Vec<Content>}#[derive(Debug)]structRuleSet{rules:HashMap<BagColor,Vec<Content>>}fnparse_rule<'a>()->implParser<'a,ContainsRule>{fnbag_color<'b>()->implParser<'b,BagColor>{letadjective=one_or_more(letter).map(|ls|ls.into_iter().collect());letcolor=one_or_more(letter).map(|ls|ls.into_iter().collect());pair(first(adjective,whitespace),color).map(|(a,c)|BagColor(a,c))}fncontainer<'b>()->implParser<'b,BagColor>{first(bag_color(),string(" bags contain "))}letbag_or_bags=string(" bags, ").or(string(" bag, ")).or(string(" bags.")).or(string(" bag."));letcontained=pair(first(integer,whitespace),first(bag_color(),bag_or_bags));letcontents_rule=pair(container(),one_or_more(contained)).map(|(color,contents)|ContainsRule{container:color.clone(),contents:contents.iter().map(|(n,c)|Content{color:c.clone(),count:*nasusize}).collect()});letno_contents_rule=first(container(),string("no other bags.")).map(|color|ContainsRule{container:color,contents:vec![]});contents_rule.or(no_contents_rule)}fnparse_input(input:&str)->ParseResult<RuleSet>{letrule_set=one_or_more(first(parse_rule(),whitespace));rule_set.parse(input).map(|(rest,rules)|{letrule_set=RuleSet{rules:rules.into_iter().map(|r|(r.container,r.contents)).collect()};(rest,rule_set)})}implRuleSet{fncan_contain(&self,from:&BagColor,to:&BagColor)->bool{self.rules.get(from).map(|contents|contents.iter().any(|c|&c.color==to)).unwrap_or(false)}fncan_contain_indirectly(&self,from:&BagColor,to:&BagColor)->bool{self.can_contain(from,to)||self.rules.get(from).map(|contents|contents.iter().any(|c|self.can_contain_indirectly(&c.color,to))).unwrap_or(false)}fnnumber_of_contained_bags(&self,from:&BagColor)->usize{self.rules.get(from).map(|contents|contents.iter().map(|c|c.count*(1+self.number_of_contained_bags(&c.color))).sum()).unwrap_or(0)}// --- problems fnpart1(&self)->usize{self.rules.keys().filter(|color|self.can_contain_indirectly(&color,&BagColor::of("shiny","gold"))).count()}fnpart2(&self)->usize{self.number_of_contained_bags(&BagColor::of("shiny","gold"))}}fnmain(){letinput=read_file("./input.txt").unwrap();letrules:RuleSet=parse_input(&input).unwrap().1;println!("part1 {}",rules.part1());println!("part2 {}",rules.part2());}#[cfg(test)]modtests{usesuper::*;#[test]fntest_parse_with_single_clause(){assert_eq!(parse_rule().parse("light red bags contain 1 bright white bag."),Ok(("",ContainsRule{container:BagColor::of("light","red"),contents:vec![Content{color:BagColor::of("bright","white"),count:1}]})));}#[test]fntest_parse_with_two_clauses(){assert_eq!(parse_rule().parse("light red bags contain 1 bright white bag, 2 muted yellow bags."),Ok(("",ContainsRule{container:BagColor::of("light","red"),contents:vec![Content{color:BagColor::of("bright","white"),count:1},Content{color:BagColor::of("muted","yellow"),count:2}]})));}#[test]fntest_parse_with_many_clauses(){assert_eq!(parse_rule().parse("dotted silver bags contain 2 dotted orange bags, 3 bright fuchsia bags, 5 bright tomato bags, 3 faded turquoise bags."),Ok(("",ContainsRule{container:BagColor::of("dotted","silver"),contents:vec![Content{color:BagColor::of("dotted","orange"),count:2},Content{color:BagColor::of("bright","fuchsia"),count:3},Content{color:BagColor::of("bright","tomato"),count:5},Content{color:BagColor::of("faded","turquoise"),count:3}]})));}#[test]fntest_parse_with_no_contents(){assert_eq!(parse_rule().parse("faded blue bags contain no other bags."),Ok(("",ContainsRule{container:BagColor::of("faded","blue"),contents:vec![]})));}#[test]fntest_parse_records_separated_by_lines(){letp=one_or_more(first(letter,whitespace));assert_eq!(p.parse("a\nb\nc\n"),Ok(("",vec!['a','b','c'])));}}
I found a graph library to model the actual structure of the nested bags. Spent more time trying to reason out the graph structure and figure out what I was doing, than I did actually getting the problem solved.
A fun exercise, to be sure, but not the fastest way to row the boat.
Struggled on this one more than I probably should have. I started with a recursion bug that was right in front of my eyes, then went on to part2 to realize that I would need to re-think my model (can't say I didn't see that one coming).
Part 1
publicclassPart1:Puzzle<Dictionary<string,Node<Bag>>,long>{protectedconststringTarget="shiny gold";publicoverridelongSampleAnswer=>4;publicoverrideDictionary<string,Node<Bag>>ParseInput(stringrawInput)=>rawInput.Split(Environment.NewLine).Where(line=>line.Length>0).Select(ParseBagDescription).ToDictionary(node=>node.Name,node=>node);Node<Bag>ParseBagDescription(stringdescription){varparts=description.Split(" bags contain ");varname=parts[0];varnode=newNode<Bag>(name,newBag(name));varinnerBagNodes=parts[1].Split(',').Where(description=>description!="no other bags.").Select(bag=>bag.TrimStart()).Select(bag=>ParseBagContents(bag)).Select(bag=>newNode<Bag>(bag.Name,bag));node.AddChildren(innerBagNodes);returnnode;}BagParseBagContents(stringcontents){intspace=contents.IndexOf(' ');stringname=contents[(space+1)..contents.LastIndexOf(' ')];int.TryParse(contents[..space],outintcount);returnnewBag(name,count);}publicoverridelongSolve(Dictionary<string,Node<Bag>>input)=>input.Count(x=>HasDescendent(input,Target,x.Value));boolHasDescendent(Dictionary<string,Node<Bag>>allNodes,stringname,Node<Bag>node)=>node.Children.Any(n=>n.Name==Target||HasDescendent(allNodes,name,allNodes[n.Name]));}
Part2
publicclassPart2:Part1{publicoverridelongSampleAnswer=>32;publicoverridelongSolve(Dictionary<string,Node<Bag>>input)=>CountInnerBagsRecursive(input,input[Target])-1;// We counted the target bag, reduce count by 1.longCountInnerBagsRecursive(Dictionary<string,Node<Bag>>allNodes,Node<Bag>node)=>node.Children.Aggregate(1L,(acc,cur)=>acc+=cur.Value.Count*CountInnerBagsRecursive(allNodes,allNodes[cur.Name]));}
Solution for C# (part 2).
Just wanted to finish it, so don't expect any beauty :) :
usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Text;namespaceAdventOfCode2020{staticclassDay7Part2{staticList<string>input=newList<string>(File.ReadAllLines("//inputfile"));staticList<Bag>bagtypes=newList<Bag>();staticintcountbags=0;publicstaticvoidExecute(){//First make a list of the Bag classforeach(varruleininput){bagtypes.Add(DefineColorsForBag(rule));}//Get the shinygoldbagvarshinygoldbag=bagtypes.Where(x=>x.OwnColor=="shinygold").FirstOrDefault();//And then count the bagsCountBags(shinygoldbag,1);Console.WriteLine($"Answer: {countbags}");}privatestaticvoidCountBags(Bagbag,inttimes){foreach(varruleinbag.ContainerRules){//Count is used to add to the total and to set the times in the next recursionvarcount=rule.number*times;countbags+=count;vargetBagForRuleColor=bagtypes.Where(x=>x.OwnColor==rule.color).ToList();if(getBagForRuleColor.Count()==1)CountBags(getBagForRuleColor[0],count);}}privatestaticBagDefineColorsForBag(stringrule){varsplitrule1=rule.Split('');varbag=newBag(splitrule1[0]+splitrule1[1]);varsplitrule2=rule.Split('').Skip(3).ToArray();inti=0;while(true){varstringToCompare=splitrule2[i];if(stringToCompare.Contains(".")||string.Equals("no",stringToCompare))returnbag;if(stringToCompare.Contains(',')||stringToCompare.Contains("bag")||string.Equals("contain",stringToCompare)){i++;stringToCompare=splitrule2[i];if(string.Equals("no",stringToCompare)||string.Equals("0",stringToCompare))returnbag;int.TryParse(stringToCompare,outintt);bag.ContainerRules.Add(newRule(t,splitrule2[i+1]+splitrule2[i+2]));i+=3;}}returnbag;}}}
Urgh this was horrible. I should have taken the opportunity to learn some kind of graph library to do this, but I've spent way enough time looking at it now.
fromcollectionsimportdefaultdictclassRuleParser():def__init__(self):self.containment_tree=defaultdict(lambda:defaultdict(list))defparse_row(self,row):ifrow.strip()=="":returnrow=row.replace(' bags','').replace(' bag','').replace('.','').strip()outer,contents=row.split(' contain ')content_rules=contents.split(', ')forcontained_ruleincontent_rules:words=contained_rule.split(' ')n=0ifwords[0]=="no"elseint(words[0])colour=" ".join(words[1:])colour=colourifn>0else"no other"self.containment_tree[outer][colour]=ndeffind_in_subtree(self,target_color):outers=set()defsearch_subtree(for_colour):forouterinself.containment_tree:iffor_colourinself.containment_tree[outer]:outers.add(outer)search_subtree(outer)search_subtree(target_color)returnlen(outers)def_n_in_subtree(self,outer_bag):total_children=1forinner_baginparser.containment_tree[outer_bag]:n_this_colour=parser.containment_tree[outer_bag][inner_bag]n_children=self._n_in_subtree(inner_bag)total_children+=n_this_colour*n_childrenreturntotal_childrendefn_in_children(self,outer_bag):returnself._n_in_subtree(outer_bag)-1parser=RuleParser()withopen("input.txt","r")asinput:forrowininput:parser.parse_row(row)goal_colour='shiny gold'part_1=parser.find_in_subtree(goal_colour)print(f"Part 1 solution: {part_1} colours can ultimately contain a {goal_colour} bag")part_2=parser.n_in_children(goal_colour)print(f"Part 2 solution: a {goal_colour} bag has to contain {part_2} other bags")
I pull out that PEG parser again to handle my input, I feel it's more readable than a full regex solution, since you define the entire syntax of the input file up-front for everyone to see. But it's not as compact as a pure regex solution, and there's a lot of extra nodes (could probably golf it, but it would be less readable). One benefit is the NodeVisitor is already doing a depth-first visit of the generated AST, so you can piggy back the graph generation in there to save a loop or two.
I used the NetworkX graph library in Python to get the ancestors for free, but unfortunately still had to write a recursive traversal of the DAG to get the sums for Part 2.
Made some nice graphs while I was at it too, more on my post
fromparsimonious.grammarimportGrammar,NodeVisitorimportnetworkxasnxgrammar=Grammar(r"""
DOCUMENT = LINE+
LINE = (ENTRY / TERMINAL)
TERMINAL = PARENT "no other bags." "\n"?
ENTRY = PARENT CHILDREN "." "\n"?
PARENT = COLOR " bags contain "
CHILDREN = CHILD+
CHILD = NUMBER " " COLOR " " BAGBAGS SEPARATOR
NUMBER = ~r"\d+"
COLOR = ~r"\w+ \w+"
BAGBAGS = ("bags" / "bag")
SEPARATOR = ~r"(, |(?=\.))"
""")classBagVisitor(NodeVisitor):defparse(self,*args,**kwargs):self.graph=nx.DiGraph()super().parse(*args,**kwargs)returnself.graphdefvisit_ENTRY(self,node,visited_children):parent,children,*_=visited_childrenforcount,childinchildren:self.graph.add_edge(parent,child,count=count)defvisit_PARENT(self,node,visited_children):returnvisited_children[0]defvisit_CHILD(self,node,visited_children):return(visited_children[0],visited_children[2])defvisit_COLOR(self,node,visited_children):self.graph.add_node(node.text)returnnode.textdefvisit_NUMBER(self,node,visited_children):returnint(node.text)defgeneric_visit(self,node,visited_children):returnvisited_childrenornodebv=BagVisitor()bv.grammar=grammargraph=bv.parse(open("input.txt").read())# Part 1
print("ancestor bags",len(nx.ancestors(graph,"shiny gold")))# Part 2
defget_count(parent):return1+sum(get_count(child)*graph.edges[parent,child]["count"]forchildingraph.neighbors(parent))print("total bags",get_count("shiny gold")-1)
openSystem.IOtypeInnerBag={InnerBagName:stringInnerBagQuantity:int}letrecparseInnerBagsacc=function|[]|"no"::"other"::["bags."]->acc|innerQuantity::innerAdj::innerColor::_::rest->letbagName=sprintf"%s %s"innerAdjinnerColorletbag={InnerBagName=bagName;InnerBagQuantity=intinnerQuantity}parseInnerBags(bag::acc)rest|pattern->failwithf"cannot parse inner pattern %A"patternletparseLineacc(s:string)=matchList.ofArray<|s.Split('')with|adj::color::_::_::"no"::"other"::["bags."]->letbagName=sprintf"%s %s"adjcolorMap.addbagName[]acc|adj::color::_::_::rest->letbagName=sprintf"%s %s"adjcolorMap.addbagName(parseInnerBags[]rest)acc|pattern->failwithf"cannot parse pattern %A"patternletrecfindAllBagsContainingsoughtBagallBags=allBags|>Map.filter(fun_innerBags->innerBags|>List.exists(funbag->bag.InnerBagName=soughtBag))|>Map.toList|>List.collect(fst>>funbagName->bagName::findAllBagsContainingbagNameallBags)letreccountBagsInsideOfbagNameallBags=matchMap.tryFindbagNameallBagswith|SomeinnerBags->innerBags|>List.sumBy(funinnerBag->innerBag.InnerBagQuantity+countBagsInsideOfinnerBag.InnerBagNameallBags*innerBag.InnerBagQuantity)|None->0// this should never happenletbags=File.ReadAllLines"input.txt"|>Array.foldparseLineMap.empty// Part 1findAllBagsContaining"shiny gold"bags|>Set.ofList|>Set.count|>printfn"%d"// Part2countBagsInsideOf"shiny gold"bags|>printfn"%d"
Sweet mother of everything, I've walked a graph in COBOL.
IDENTIFICATION DIVISION.
PROGRAM-ID. AOC-2020-07-1.
AUTHOR. ANNA KOSIERADZKA.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT INPUTFILE ASSIGN TO "d07.input"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD INPUTFILE
RECORD IS VARYING IN SIZE FROM 1 to 128
DEPENDING ON REC-LEN.
01 INPUTRECORD PIC X(128).
WORKING-STORAGE SECTION.
01 FILE-STATUS PIC 9 VALUE 0.
01 REC-LEN PIC 9(2) COMP.
01 WS-BUFFER PIC X(32) OCCURS 32 TIMES.
01 WS-BAG PIC X(32).
01 WS-BAGS OCCURS 594 TIMES.
05 WS-BAG-COLOR PIC X(32).
05 WS-BAG-DONE PIC 9 VALUE 0.
05 WS-BAG-BAGS-NUMBER PIC 99 VALUE 0.
05 WS-BAG-BAGS PIC X(32) OCCURS 32 TIMES.
01 WS-BAGS-QUEUE PIC X(32) OCCURS 9999 TIMES.
LOCAL-STORAGE SECTION.
01 N UNSIGNED-INT VALUE 0.
01 RESULT UNSIGNED-INT VALUE 0.
01 BAG-IDX UNSIGNED-INT VALUE 1.
01 I UNSIGNED-INT VALUE 1.
01 J UNSIGNED-INT VALUE 1.
01 K UNSIGNED-INT VALUE 1.
01 STRING-PTR UNSIGNED-INT VALUE 1.
01 Q1 UNSIGNED-INT VALUE 1.
01 Q2 UNSIGNED-INT VALUE 1.
PROCEDURE DIVISION.
001-MAIN.
OPEN INPUT INPUTFILE.
PERFORM 002-READ UNTIL FILE-STATUS = 1.
CLOSE INPUTFILE.
PERFORM 005-WALK-GRAPH.
PERFORM 008-COUNT-RESULT.
DISPLAY Q2.
DISPLAY RESULT.
STOP RUN.
002-READ.
READ INPUTFILE
AT END MOVE 1 TO FILE-STATUS
NOT AT END PERFORM 003-PARSE-RECORD
END-READ.
003-PARSE-RECORD.
ADD 1 TO N.
MOVE 1 TO STRING-PTR.
PERFORM VARYING J FROM 1 BY 1 UNTIL J > 32
UNSTRING INPUTRECORD DELIMITED BY SPACE
INTO WS-BUFFER(J)
WITH POINTER STRING-PTR
END-PERFORM.
STRING
WS-BUFFER(1) DELIMITED BY SPACE
' ' DELIMITED BY SIZE
WS-BUFFER(2) DELIMITED BY SPACE
INTO WS-BAG-COLOR(I)
END-STRING.
IF NOT WS-BUFFER(5) = "no" THEN
PERFORM 004-PARSE-SUB-BAGS
END-IF.
ADD 1 TO I.
004-PARSE-SUB-BAGS.
* 1, 2 are color, 3=bags, 4=contains
MOVE 1 TO K.
PERFORM VARYING J FROM 5 BY 4 UNTIL J > 32
IF NOT WS-BUFFER(J)(1:1) = " " THEN
STRING
WS-BUFFER(J + 1) DELIMITED BY SPACE
' ' DELIMITED BY SIZE
WS-BUFFER(J + 2) DELIMITED BY SPACE
INTO WS-BAG-BAGS(I, K)
END-STRING
ADD 1 TO K
END-IF
END-PERFORM.
COMPUTE WS-BAG-BAGS-NUMBER(I) = K - 1.
005-WALK-GRAPH.
* Queue starts containing 'shiny gold', Q1 = 1, Q2 = 1
MOVE 'shiny gold' TO WS-BAGS-QUEUE(1).
PERFORM 006-WALK-GRAPH-LOOP UNTIL Q1 > Q2.
006-WALK-GRAPH-LOOP.
MOVE WS-BAGS-QUEUE(Q1) TO WS-BAG.
ADD 1 TO Q1.
PERFORM 007-FIND-BAG-INDEX.
MOVE 1 TO WS-BAG-DONE(BAG-IDX).
PERFORM VARYING I FROM 1 BY 1 UNTIL I > N
* Find bags with WS-BAG among sub-bags
IF WS-BAG-DONE(I) = 0 THEN
PERFORM VARYING J FROM 1 by 1
UNTIL J > WS-BAG-BAGS-NUMBER(I)
IF WS-BAG = WS-BAG-BAGS(I, J)
ADD 1 TO Q2
MOVE WS-BAG-COLOR(I) TO WS-BAGS-QUEUE(Q2)
EXIT PERFORM
END-IF
END-PERFORM
END-IF
END-PERFORM.
* Note: no hashtables in COBOL, so linear lookup
007-FIND-BAG-INDEX.
PERFORM VARYING K FROM 1 BY 1 UNTIL K > N
IF WS-BAG = WS-BAG-COLOR(K) THEN
MOVE K TO BAG-IDX
END-IF
END-PERFORM.
008-COUNT-RESULT.
PERFORM VARYING I FROM 1 BY 1 UNTIL I > N
IF WS-BAG-DONE(I) = 1 THEN
ADD 1 TO RESULT
END-IF
END-PERFORM.
* Shiny gold bag doesn't count
SUBTRACT 1 FROM RESULT.
Ruby, part 2. Oddly much easier than part 1. Parsing modified to suit the problem better:
require'set'bag_descriptions={}File.readlines('07.txt').eachdo|line|bag_type=line.match('\A(.*?) bags')[1]contents=[]unlessline.match('contain no other bags')line.scan(/(\d+) (.*?) bags?/).eachdo|count,color|contents.push[color,count.to_i]endendbag_descriptions[bag_type]=contents.to_henddeftotal_bag_count(bag_descriptions,bag_type)# Count this bagcount=1bag_descriptions[bag_type].eachdo|inner_bag,bag_count|count+=bag_count*total_bag_count(bag_descriptions,inner_bag)endcountend# Subtract one as the shiny gold bag itself is not countedputstotal_bag_count(bag_descriptions,'shiny gold')-1
Today's puzzle was a little bit more complicated. However, like every other day before, I've created a step-by-step tutorial for my fellow TypeScript and JavaScript developers:
I'm a Staff Software Engineer at Cisco. I specialize in Python and Go, building functional, practical, and maintainable web systems leveraging Kubernetes and the cloud. Blog opinions are my own.
I caved, I'm sorry. I fought with the parsing in C for long enough and I didn't want to get bogged down and behind a day, so I knocked it out in Python.
"""Day 7: Handy Haversacks
Figure out which and how many luggage pieces in various colors
are contained inside other ones.
"""defparse(filename):"""Parse the input file to form two digraphs: one showing
which bags are able to be contained in which and the other
showing which bags contain what numbers of which other bags.
"""parents=dict()children=dict()withopen(filename,"r")asf:lines=f.readlines()# Figure out which colors we have
forlineinlines:color=" ".join(line.split()[:2])parents[color]=[]children[color]=[]# Fill in the digraphs
forlineinlines:words=line.split()if"no other"inline:continueparent_color=" ".join(words[:2])child_words=iter(words[4:])whileTrue:count=int(next(child_words))child_adj=next(child_words)child_color=next(child_words)child_name=f"{child_adj}{child_color}"parents[child_name].append(parent_color)children[parent_color].append((child_name,count))ifnext(child_words)[-1]==".":breakreturnparents,childrendefholders(color,parents_graph):"""Build a set of all unique bags which can contain the
requested bag color.
"""result=set(parents_graph[color])forcinparents_graph[color]:result|=holders(c,parents_graph)returnresultdefcount_contents(color,children_graph):"""Add up the bags inside a given bag plus all of the bags within
each of each child bags.
"""returnsum(count+count*count_contents(child_color,children_graph)forchild_color,countinchildren_graph[color])defpart1(parents_graph):gold_holders=len(holders("shiny gold",parents_graph))print(f"{gold_holders} different colors can contain 'shiny gold.'")defpart2(children_graph):print(f"{count_contents('shiny gold',children_graph)} bags are in a 'shiny gold.'")if__name__=="__main__":parents,children=parse("data/day7.txt")part1(parents)part2(children)
importreadj={}visited={}withopen("Problem-7/Day 7: Handy Haversacks.txt")asfile:forlineinfile:# Every line in the input was in the format outerbags contain x innerbags, y innerbags, so on..
# So we can split every line into two parts using the word "contain " as separator.
# As split funtion returns a list, we now have outerbag name as first element and it's dependencies as second element. Unpacked them into two variables as shown below.
outer_bag,innerbags=line.split("contain ")# Now the outer_bag variable has outerbagname with suffix bags in it. We can just slice the string to remove the suffix
# Similarly, innerbags will now has a string in the format x innerbags, y innerbags, so on..
# We can extract the count and the innerbag name using regex and grouping as shown below
innerbags=re.findall(r"(\d{1,}) ([a-z ]+) bag|bags",innerbags)# visited list is useful when we are exploring the graph to avoid cycles. Initially we should mark every bag as not visited
visited[outer_bag[:-6]]=Falseifouter_bag[:-6]notinadj:adj[outer_bag[:-6]]={}# Adding edges from outer bag to each inner bag
forcount,bagininnerbags:ifcountandbag:ifbagnotinadj:adj[bag]={}adj[outer_bag[:-6]][bag]=int(count)# Now we have our adjacency list ready for our directed graph
defpart_one(adj,visited,bag_name):# dfs of a graph
defdfs(adj,visited,start,count):foredgeinadj[start].keys():ifnotvisited[edge]:visited[edge]=Truecount=dfs(adj,visited,edge,count+1)returncount# reverse the graph
adj_reverse={}forouter,innerinadj.items():ifouternotinadj_reverse:adj_reverse[outer]={}forkey,countininner.items():ifkeyinadj_reverse:adj_reverse[key][outer]=countelse:adj_reverse[key]={outer:count}# Now as the graph is reversed, we can find the vertices that previously had a directed edge towards the shiny gold bag now in new adjacency list at shiny gold vertex.
# Simply exploring and counting the number of vertices explored from shiny gold bag vertex will be the result
returndfs(adj_reverse,visited,bag_name,0)defpart_two(adj,start,count):ifnotadj[start]:return0temp=0foredge,cinadj[start].items():temp+=c+c*part_two(adj,edge,count)count+=tempreturncountprint("Part 1: Total number of bag colors that contain at least one shiny gold bag :",part_one(adj,visited,"shiny gold"))print("Part 2: Shiny gold bag contains total {} number of bags".format(part_two(adj,"shiny gold",0)))
moar rust. My brain ran into so many fence post errors on this one. I should have drank more coffee before attempting.
Part 1 is a reachability problem, Part 2 is a Depth first search. But instead of building a graph, I was lazy and kept a Map of edges.
Here's Ruby:
Ruby, part 1. Kinda ugly, but effective:
I start to like parsing these kind of rules in Haskell, it's very intuitive to me.
The association list was a nice fit for this problem; had I done it in Java, I would have used a Map with Lists as a value. Even though it's not the most time efficient approach, it was allright for this size problem.
Oh dear, I didn't look at the input and assumed there were just the nine colours in the example. Modelled them in an enum and wrote parsers for them all, which failed on the first line of input text. Lesson: look at the real data!
The problem is a directed acyclic graph one. I modelled the graph as a
Vecof edges with the start and end nodes, which meant quite expensive searching. It only took 10 or 20 seconds to run but I knew it was a mistake. Reworked to aHashMapwhere the key is the start of each edge and the value is theVecof possible end nodes.The actual graph traversals are the bread and butter of my day job. Those were easy. I wasted a lot of time today on parsing and bad modelling.
I went way overboard with my Rust solution.
I found a graph library to model the actual structure of the nested bags. Spent more time trying to reason out the graph structure and figure out what I was doing, than I did actually getting the problem solved.
A fun exercise, to be sure, but not the fastest way to row the boat.
As always, available on Github.
Struggled on this one more than I probably should have. I started with a recursion bug that was right in front of my eyes, then went on to part2 to realize that I would need to re-think my model (can't say I didn't see that one coming).
Part 1
Part2
Node
Python
My cleanest solution! Wrote more about it, even tested networkx in my blogpost.
Solution for C# (part 2).
Just wanted to finish it, so don't expect any beauty :) :
`
Urgh this was horrible. I should have taken the opportunity to learn some kind of graph library to do this, but I've spent way enough time looking at it now.
I pull out that PEG parser again to handle my input, I feel it's more readable than a full regex solution, since you define the entire syntax of the input file up-front for everyone to see. But it's not as compact as a pure regex solution, and there's a lot of extra nodes (could probably golf it, but it would be less readable). One benefit is the NodeVisitor is already doing a depth-first visit of the generated AST, so you can piggy back the graph generation in there to save a loop or two.
I used the NetworkX graph library in Python to get the
ancestorsfor free, but unfortunately still had to write a recursive traversal of the DAG to get the sums for Part 2.Made some nice graphs while I was at it too, more on my post

F#:
Sweet mother of everything, I've walked a graph in COBOL.
Ruby, part 2. Oddly much easier than part 1. Parsing modified to suit the problem better:
Today's puzzle was a little bit more complicated. However, like every other day before, I've created a step-by-step tutorial for my fellow TypeScript and JavaScript developers:
[Advent of Code 2020] Day 7 Step-by-Step Tutorial (TypeScript)
Kai ・ Dec 7 ・ 8 min read
Thanks for reading! :)
I caved, I'm sorry. I fought with the parsing in C for long enough and I didn't want to get bogged down and behind a day, so I knocked it out in Python.
I'm not happy with this javascript solution. Part 1 is very slow, and part 2 is not regexy enough. I'll hide it behind this gist.
My JavaScript walkthrough: