Skip to content

Instantly share code, notes, and snippets.

@steven-terrana
Created December 3, 2023 03:45
Show Gist options
  • Save steven-terrana/484722ab88cdba18b4cf1783b78e0254 to your computer and use it in GitHub Desktop.
Save steven-terrana/484722ab88cdba18b4cf1783b78e0254 to your computer and use it in GitHub Desktop.
an awful "one-liner" solution
console.log(
require('fs').readFileSync('input.txt', 'utf-8').split('\n').map( game => Object.values(Array.from(game.matchAll(new RegExp(/(?<red>\d+(?=\sred))|(?<green>\d+(?=\sgreen))|(?<blue>\d+(?=\sblue))/g))).reduce( (m, n) => {
return {
red: n.groups.red ? Math.max(m.red, Number(n.groups.red)) : m.red,
blue: n.groups.blue ? Math.max(m.blue, Number(n.groups.blue)) : m.blue,
green: n.groups.green ? Math.max(m.green, Number(n.groups.green)) : m.green
}
}, { red: 0, green: 0, blue: 0 })).reduce( (p, v) => p *= v, 1 )).reduce( (s, v) => s += v, 0)
)
@steven-terrana
Copy link
Author

[1]

// read the input and split it up per line (game)
require('fs').readFileSync('input.txt', 'utf-8').split('\n')

[2]

// create an array of all cube numbers in the game
// and group them by color
.map( game => Object.values(Array.from(game.matchAll(new RegExp(/(?<red>\d+(?=\sred))|(?<green>\d+(?=\sgreen))|(?<blue>\d+(?=\sblue))/g)))

[3]

// iterate over the cube numbers, and build up an object of the
// max value for each color
.reduce( (m, n) => {
    return { 
      red: n.groups.red ? Math.max(m.red, Number(n.groups.red)) : m.red, 
      blue: n.groups.blue ? Math.max(m.blue, Number(n.groups.blue)) : m.blue, 
      green: n.groups.green ? Math.max(m.green, Number(n.groups.green)) : m.green
    } 
  }, { red: 0, green: 0, blue: 0 }))

[4]

// up in [2] we said "Object.values" to iterate over the colors max values so we can
// multiple them to calculate the power of this game
.reduce( (p, v) => p *= v, 1 ))

[5]

// finally, we have an array of all the game powers,
// so sum them up
.reduce( (s, v) => s += v, 0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment