Are you participating in the Advent of code this year?
If you don't know what the advent of code is, it's a website where you'll find a daily challenge (every day it gets harder). It's a really fun event, you should participate!
I try to solve the exercises using either JavaScript or TypeScript and will share my solutions daily (with one day delay so no one can cheat!). I only share the solution for the second part.
Here is my solution for day #2:
// I completed this one directly in the console of the website
$('body > pre')
// get text line by line
.textContent.split(/\r?\n/)
.filter(Boolean)
// differentiate the definition from the string
.map((definition) => definition.split(': '))
.filter(([definition, password]) => {
const [minMax, letter] = definition.split(' ')
const [min, max] = minMax.split('-').map((x) => parseInt(x) - 1)
return (
(password[min] === letter && password[max] !== letter) ||
(password[max] === letter && password[min] !== letter)
)
})
.length
The code doesn't look pretty, but it does the trick.
Feel free to share yours in the comments!
Photo by Markus Spiske on Unsplash
Top comments (1)
It doesn't need to be pretty! As long as it does the job right? It was a fun exercise. Here is mine in Ruby:
And for comparison, here is the inlined version: