-
Notifications
You must be signed in to change notification settings - Fork 1
/
day-2.js
86 lines (72 loc) · 2.18 KB
/
day-2.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const fs = require('fs');
const fileName = "day-2-test.txt";
const target = {
"red": 12,
"green": 13,
"blue": 14
}
function parseGame(game) {
let gameInfo = {
max: {},
power: 0,
rounds: []
};
let colonIndex = game.indexOf(":");
let rawRounds = game.substring(colonIndex + 1);
let rounds = rawRounds.split(";");
for(let i =0; i < rounds.length; i++) {
let results = rounds[i].split(",");
let outcomes = {
"red": 0,
"green": 0,
"blue": 0
}
for(let j = 0; j < results.length; j++) {
let result = results[j].trim().split(" ");
let count = Number(result[0]);
outcomes[result[1]] = count;
if (gameInfo.max[result[1]]) {
if (count > gameInfo.max[result[1]]) {
gameInfo.max[result[1]] = count;
}
} else {
gameInfo.max[result[1]] = count;
}
}
gameInfo.rounds.push(outcomes);
}
gameInfo.power = gameInfo.max.red * gameInfo.max.green * gameInfo.max.blue;
return gameInfo;
}
function isGamePossible(game, target) {
let possible = true;
for (let key in target) {
if (game.max[key] > target[key]) {
possible = false;
break;
}
}
return possible;
}
//Read each line in the file named fileName
let file = fs.readFileSync(fileName, 'utf8');
const games = file.split(/\r?\n/);
let possibleGames = [];
let totalPower = [];
let impossibleGames = [];
for (let i = 0; i < games.length; i++) {
let game = parseGame(games[i]);
totalPower.push(game.power);
let gamePossible = isGamePossible(game, target);
if (gamePossible) {
possibleGames.push(i + 1);
} else {
impossibleGames.push(i + 1);
}
}
let sumPossibleGames = possibleGames.reduce((a, b) => a + b, 0);
let sumTotalPower = totalPower.reduce((a, b) => a + b, 0);
let sumImpossibleGames = impossibleGames.reduce((a, b) => a + b, 0);
console.log(`Possible games sum: ${sumPossibleGames}`);
console.log(`Total power sum: ${sumTotalPower}`);
console.log(`Impossible games sum: ${sumImpossibleGames}`);