70 lines
1.9 KiB
JavaScript
70 lines
1.9 KiB
JavaScript
import fs from 'node:fs'
|
|
const numberphiles = new Map([
|
|
["red", 12],
|
|
["blue", 14],
|
|
["green", 13],
|
|
])
|
|
|
|
fs.readFile('input.txt', ({ encoding: 'utf-8' }), (err, data) => {
|
|
let result = 0
|
|
for (let line of data.split('\n')) {
|
|
const game_id = parseInt(String(line.split(':')[0]).substring(5))
|
|
const game = line.split(':')[1].split(',')
|
|
result += isGamePossible(game) ? game_id : 0
|
|
}
|
|
console.log(`
|
|
|
|
Part 1 now....
|
|
|
|
`)
|
|
console.log(result)
|
|
|
|
function isGamePossible(game) {
|
|
let possible = true
|
|
game.forEach(game => {
|
|
const rounds = game.trim().split(";")
|
|
//console.log(rounds)
|
|
rounds.forEach(round => {
|
|
const [number, color] = round.trim().split(" ")
|
|
if (number > numberphiles.get(color)) possible = false
|
|
})
|
|
})
|
|
return possible
|
|
}
|
|
})
|
|
|
|
// ---- part 2 -----
|
|
|
|
fs.readFile('input.txt', ({ encoding: 'utf-8' }), (err, data) => {
|
|
let result = 0
|
|
for (let line of data.split('\n')) {
|
|
const game_id = parseInt(String(line.split(':')[0]).substring(5))
|
|
const game = line.split(':')[1].split(',')
|
|
result += ([...leastPossible(game).values()].reduce((cur, next) => cur * next))
|
|
}
|
|
console.log(`
|
|
|
|
Part 2 now....
|
|
|
|
`)
|
|
console.log(result)
|
|
|
|
function leastPossible(game) {
|
|
let possible = true
|
|
let GameMap = new Map()
|
|
game.forEach(game => {
|
|
|
|
const rounds = game.trim().split(";")
|
|
//console.log(rounds)
|
|
rounds.forEach(round => {
|
|
const [number, color] = round.trim().split(" ")
|
|
let leastNumber = parseInt(number)
|
|
if (GameMap.has(color)) {
|
|
leastNumber = GameMap.get(color) > number ? GameMap.get(color) : leastNumber
|
|
}
|
|
GameMap.set(color, leastNumber)
|
|
})
|
|
})
|
|
return GameMap
|
|
}
|
|
}) |