DEV Community

Cover image for Advent of code - Day 2
Quentin Ménoret
Quentin Ménoret

Posted on

Advent of code - Day 2

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
  // 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)
Enter fullscreen mode Exit fullscreen mode

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

Discussion (1)

sleeplessbyte profile image
Derk-Jan Karrenbeld • Edited on

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:

require 'benchmark'

class PasswordPolicy
  def self.from_line(line)
    length, char, password = line.split(' ')
    first, second = length.split('-').map(&:to_i)
    char = char.delete(':') [first - 1, second - 1], char: char, password: password)

  def initialize(positions:, char:, password:)
    self.positions = positions
    self.char = char
    self.password = password

  def valid?
    positions.count { |i| password[i] == char } == 1


  attr_accessor :positions, :char, :password

lines = File.readlines('input.txt')

valids = 0 do |x| do
    valids = lines.count do |line|

puts valids
Enter fullscreen mode Exit fullscreen mode

And for comparison, here is the inlined version:

entries = File.readlines('input.txt').map do |line|
  positions, char, password = line.split
  left, right = positions.split(?-).map(&:to_i)
  [left, right, char.first, password.chomp]

puts entries.count do |left, right, char, password|
  (password[left - 1] == char) != (password[right - 1] == char)
Enter fullscreen mode Exit fullscreen mode