Colored cubes (red, green, blue) are drawn from a bag with replacement. Several iterations compose a game. The task is to identify all games being possible if the bag contained
12 red cubes
13 green cubes
14 blue cubes
The solution is the sum of the ids of these games.
Overall, the iterations per game do not matter here. The problem simplifies to identify games where the number of cubes drawn in a particular color exceeds the given amount of cubes in this color.
replace the prefix “Game X:” from every vector element as the game id is equal to the index
split the game into single cubes
get the maximum number of cubes per colors and per game
identify games where the maximum number of cubes in at least one color exceeds the given amount of cubes
splitgame =function( x){ x =gsub("^.*?:", replacement ="", x = x)unlist(strsplit(x, split =";|,") )}maxcubes =function( x , colors =c("red", "green", "blue")){vapply( colors , FUN = \(c){ v =grep(c, x = x, value =TRUE) v =gsub(c, replacement ="", x = v) v =trimws(v)max(0L, as.integer(v)) } , FUN.VALUE =integer(1L) )} games =Map( splitgame , x = txt) |>unname()cubes =Map( maxcubes , x = games)possible =lapply( cubes , FUN = \(i){all(i <=c(12, 13, 14)) }) |>unlist() sum(which(possible))
[1] 2913
Approach:
split each game into single cubes, drop prefix “Game X:”
get the maximum number of cubes per colors and per game
identify games where the maximum number of cubes in at least one color exceeds the given amount of cubes
import reimport numpy as npdef maxcubes(x: str): x = re.split(',|;|:', x)[1:] cbs = []for col in ['red', 'green', 'blue']: c = [int(g.replace(col, '')) for g in x if col in g] cbs.append(max(c))return cbs cubes =map(maxcubes, r.txt)cubes =list(cubes)cubes = np.array(cubes)idx =0for i, x inenumerate(cubes):ifall(cubes[i] <= np.array([12, 13, 14])): idx += i +1idx
2913
Part II
Per game, determine the minimum number of cubes per color required to play that game. Calculate the power of the game, i.e. multiply the numbers of the minimum set.