<- back

advent of code - day 2

2023-12-02

See the puzzle here.

See my full solution here.

I think this one should have been the day 1 challenge. It was much easier than the previous one and only took me like 15 minutes to solve.

Part 1

Here's the main chunk of code that runs on each line of input:

 const MAX_RED = 12;
 const MAX_GREEN = 13;
 const MAX_BLUE = 14;
 const id = parseInt(line.substring(0, line.indexOf(':')).split(' ')[1]);
 const afterGameId = line.substring(line.indexOf(':')+1);
 const sets = afterGameId.split(';');
 let validGame = true;
 sets.forEach((set) => {
  let reds = 0;
  let greens = 0;
  let blues = 0;
  if(set.indexOf('red') > -1) {
   const redStr = set.split('red')[0].split(' ');
   reds = parseInt(redStr[redStr.length-2]);
  }
  if(set.indexOf('green') > -1) {
   const greenStr = set.split('green')[0].split(' ');
   greens = parseInt(greenStr[greenStr.length-2]);
  }
  if(set.indexOf('blue') > -1) {
   const blueStr = set.split('blue')[0].split(' ');
   blues = parseInt(blueStr[blueStr.length-2]);
  }
  if(reds > MAX_RED || greens > MAX_GREEN || blues > MAX_BLUE) {
   validGame = false;
  }
 });
 if(validGame) {
  sum += id;
 }

There might be a fancy regex way of solving this, but I resorted to just splitting the string to find the ID, the count of reds, greens, and blues, and then compared with the maximum avaiailable to determine if it was a valid game or not.

As long as you're comfortable with slicing and dicing strings there wasn't much to this part.

Part 2

Honestly, part 2 wasn't even really that much harder, just a bit of a twist.

Here's the main chunk of code that runs on each line of input:

 const afterGameId = line.substring(line.indexOf(':')+1);
 const sets = afterGameId.split(';');
 let maxRed = 0;
 let maxBlue = 0;
 let maxGreen = 0;
 sets.forEach((set) => {
  let reds = 0;
  let greens = 0;
  let blues = 0;
  if(set.indexOf('red') > -1) {
   const redStr = set.split('red')[0].split(' ');
   reds = parseInt(redStr[redStr.length-2]);
  }
  if(set.indexOf('green') > -1) {
   const greenStr = set.split('green')[0].split(' ');
   greens = parseInt(greenStr[greenStr.length-2]);
  }
  if(set.indexOf('blue') > -1) {
   const blueStr = set.split('blue')[0].split(' ');
   blues = parseInt(blueStr[blueStr.length-2]);
  }
  if(reds > maxRed) {
   maxRed = reds;
  }
  if(greens > maxGreen) {
   maxGreen = greens;
  }
  if(blues > maxBlue) {
   maxBlue = blues;
  }
 });
 const power = maxRed * maxGreen * maxBlue;
 sum += power;
 });

This one was just a matter of keeping track of the maximum number of reds, greens, and blues in each set and then multiplying them to find the "power" of each game.