84 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
			
		
		
	
	
			84 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			JavaScript
		
	
	
	
	
	
| const fs = require('fs');
 | |
| 
 | |
| // const inputArray = fs.readFileSync('sample.txt').toString().split("\n");
 | |
| const inputArray = fs.readFileSync('input.txt').toString().split("\n");
 | |
| 
 | |
| let redMax = 0;
 | |
| let greenMax = 0;
 | |
| let blueMax = 0;
 | |
| 
 | |
| // Part One
 | |
| 
 | |
| redMax  = 12;
 | |
| greenMax = 13;
 | |
| blueMax = 14;
 | |
| 
 | |
| const possibleGames = [];
 | |
| 
 | |
| for (i in inputArray) {
 | |
|   let possible = true;
 | |
| 
 | |
|   const contents = inputArray[i].split(":");
 | |
|   const gameID = parseInt(contents[0].split(" ")[1]);
 | |
|   const draws = contents[1].split(";");
 | |
|   for (d in draws) {
 | |
|     const cubes = draws[d].split(",");
 | |
|     for (c in cubes) {
 | |
|       const parts = cubes[c].trim().split(" ");
 | |
|       const val = parseInt(parts[0]);
 | |
|       const color = parts[1];
 | |
|       if (color === "red" && val > redMax) {
 | |
|         possible = false;
 | |
|       } else if (color === "green" && val > greenMax) {
 | |
|         possible = false;
 | |
|       } else if (color === "blue" && val > blueMax) {
 | |
|         possible = false;
 | |
|       }
 | |
|     }
 | |
|   }
 | |
| 
 | |
|   if (possible) {
 | |
|     possibleGames.push(gameID);
 | |
|   }
 | |
| 
 | |
| }
 | |
| 
 | |
| console.log(possibleGames.reduce((a, b) => a + b, 0));
 | |
| 
 | |
| 
 | |
| // Part Two
 | |
| 
 | |
| const powers = [];
 | |
| 
 | |
| for (i in inputArray) {
 | |
|   redMax  = 0;
 | |
|   greenMax = 0;
 | |
|   blueMax = 0;
 | |
| 
 | |
|   const contents = inputArray[i].split(":");
 | |
|   const draws = contents[1].split(";");
 | |
|   for (d in draws) {
 | |
|     const cubes = draws[d].split(",");
 | |
|     for (c in cubes) {
 | |
|       const parts = cubes[c].trim().split(" ");
 | |
|       const val = parseInt(parts[0]);
 | |
|       const color = parts[1];
 | |
|       if (color === "red" && val > redMax) {
 | |
|         redMax = val;
 | |
|       } else if (color === "green" && val > greenMax) {
 | |
|         greenMax = val;
 | |
|       } else if (color === "blue" && val > blueMax) {
 | |
|         blueMax = val;
 | |
|       }
 | |
|     }
 | |
|   }
 | |
| 
 | |
|   powers.push(redMax * greenMax * blueMax);
 | |
| 
 | |
| }
 | |
| 
 | |
| console.log(powers.reduce((a, b) => a + b, 0));
 | |
| 
 | |
| // functions
 | |
| 
 |