3 declare -A contained_by
9 while read -u 3 line; do
10 bag_name=${line% bags contain *}
11 contain=${line#* bags contain }
13 while [ ${#contain} -gt 0 ]; do
14 next_bag=${contain%%,*}
15 if [ ${#next_bag} -eq 0 ]; then
16 next_bag=${contain%%.}
18 contain=${contain#"$next_bag"}
19 contain=${contain#[,.]}
22 bag_count=${next_bag%% *}
23 next_bag=${next_bag#$bag_count }
24 next_bag=${next_bag% bag*}
25 next_bag=${next_bag#,}
27 if [ ${contains[$bag_name]+a} ]; then
28 contains[$bag_name]+=":$bag_count,$next_bag"
30 contains[$bag_name]="$bag_count,$next_bag"
33 if [ ${contained_by[$next_bag]+a} ]; then
34 contained_by[$next_bag]+=",$bag_name"
36 contained_by[$next_bag]="$bag_name"
43 declare -a new_new_bags
45 looking_for="shiny gold"
46 bag_name="$looking_for"
49 for bag in ${contained_by["$bag_name"]}; do
50 if ! [ ${temp["$bag"]+a} ]; then
56 while [ ${#new_bags[@]} -gt 0 ]; do
57 for bag in "${new_bags[@]}"; do
58 if [ ${contained_by["$bag"]+a} ]; then
59 for bag2 in ${contained_by["$bag"]}; do
60 if ! [ ${temp["$bag2"]+a} ]; then
61 new_new_bags+=("$bag2")
68 new_bags=("${new_new_bags[@]}")
70 declare -a new_new_bags
73 echo "Found ${#temp[@]} bags that hold ${looking_for}"
78 if ! [ ${contains[$bag_name]+a} ]; then
83 for bag_details in ${contains[$bag_name]}; do
86 addcount=$((($(get_count $bag)+1)*num))
87 count=$((count+$addcount))
93 # now looking for how many bags in bags we're looking for
94 echo "Contains $(get_count $looking_for) bags"
105 for rule in open("input.txt", "r"):
107 print("Rule: {}".format(rule))
108 m=re.match("^(.*?) bag(s|) contain (.*)$", rule)
111 contain=m.group(3).split(", ")
112 for contained in contain:
113 m2=re.match('^([0-9]*) (.*?) bag(s|).*$', contained)
115 bag_count=int(m2.group(1))
117 if not bag in contains:
119 contains[bag].append((bag_count, bag_name))
120 if not bag_name in contained_by:
121 contained_by[bag_name] = []
122 if not bag in contained_by[bag_name]:
123 contained_by[bag_name].append(bag)
125 looking_for="shiny gold"
128 for bag in contained_by[looking_for]:
135 new_bag_list=[b for b in bags]
138 for bag1 in new_bag_list:
139 if bag1 not in contained_by:
141 for bag2 in contained_by[bag1]:
143 new_new_bag_list.append(bag2)
145 if (len(new_new_bag_list) > 0):
146 new_bag_list=[b for b in new_new_bag_list]
153 print("Found {} bags that can contain {} bags".format(len(bags), looking_for))
155 def get_count(bag_name):
157 if not bag_name in contains:
159 for (num,bag) in contains[bag_name]:
160 count+=(get_count(bag)+1)*num
163 # now looking for how many bags in bags we're looking for
164 print("Contains {} bags".format(get_count(looking_for)))