37 lines
1.1 KiB
JavaScript
37 lines
1.1 KiB
JavaScript
|
|
|
|
module.exports.solve = function(input, bagConfig) {
|
|
|
|
// I don't think modeling the game like this would have been needed
|
|
// However, it helps my thinking as the domain's model equals the model explained in the assignment.
|
|
const parseGame = (line) => {
|
|
// example line: Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
|
|
const grabs = line.split(":")[1].split(";").map(descr => {
|
|
const descrSeparated = descr.split(",") // e.g. " 1 blue" or " 3 green"
|
|
const descrToInt = (color) => {
|
|
const found = descrSeparated.find(d => d.indexOf(color) >= 0)
|
|
return found === undefined ? 0 : parseInt(found.replace(color, "").trim())
|
|
}
|
|
|
|
return {
|
|
'r': descrToInt("red"),
|
|
'g': descrToInt("green"),
|
|
'b': descrToInt("blue")
|
|
}
|
|
})
|
|
return {
|
|
id: parseInt(line.split(":")[0].replace("Game ", "")),
|
|
grabs
|
|
}
|
|
}
|
|
const isGamePossible = (game) => {
|
|
return !game.grabs.some(grab => grab.r > bagConfig.r || grab.g > bagConfig.g || grab.b > bagConfig.b)
|
|
}
|
|
|
|
return input.split('\n')
|
|
.map(parseGame)
|
|
.filter(isGamePossible)
|
|
.map(game => game.id)
|
|
.reduce((a, b) => a + b)
|
|
}
|