Ryan is an engineer in the Sacramento Area with a focus in Python, Ruby, and Rust. Bash/Python Exercism mentor. Coding, physics, calculus, music, woodworking. Looking for work!
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)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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.