How many individual bags are required inside your single shiny gold bag?
# function to add rows to our collection dataframeadd_bags <-function(df, item, multi) {# exit earlyif (item =="no other bags.") return(df)# get the number from the string, but also the other number of bags containing this one bb =parse_number(item) * multi# split the string (trusting the strings are all the same) cc =str_split(item, " ")# combine 2nd and 3rd parts, again, trust in the system clr =paste(cc[[1]][2], cc[[1]][3])# the next row for our counter df rw =list(bags = bb, colour = clr)# otherwise if adding a number, add it to search for later df =rbind(df, rw)# return, of coursereturn(df)}
Start some things
# initiate some variablesbag_current <-"1 shiny gold bag"keep_going <-TRUEbag_level <-1# blank dataframecount_bags_df <-tribble(~bags, ~colour)# this is the main part of the pattern# loop through bags countercount_bags_df <-add_bags(count_bags_df, bag_current, 1)# splitlugg_part2 <-separate(lugg, V1, into =c("first", "other"), sep =" bags contain ") %>%mutate(others =as.vector(str_split(other, ", ")))
Now, loop
# loop all of the loopswhile (keep_going) {# how many bags we are getting in the current one multi = count_bags_df$bags[[bag_level]]# current colour of the bag this_bag = count_bags_df$colour[[bag_level]]# look for bags srch_list <- lugg_part2 %>%filter(first == this_bag) %>%select(others) %>%unlist(use.names =FALSE)# add the found bags into our search for (x inseq_along(srch_list)) { count_bags_df =add_bags(count_bags_df, srch_list[[x]], multi) }# iterate bag_level = bag_level +1# stop if we have no more bags to search forif (bag_level >nrow(count_bags_df)) {break }}# minus one because we don't count shiny goldsum(count_bags_df$bags) -1