DEV Community

loading...
Cover image for Advent of code - Day 2

Advent of code - Day 2

qmenoret profile image Quentin Ménoret ・1 min read

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
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)

pic
Editor guide
Collapse
sleeplessbyte profile image
Derk-Jan Karrenbeld • Edited

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(':')

    PasswordPolicy.new(positions: [first - 1, second - 1], char: char, password: password)
  end

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

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

  private

  attr_accessor :positions, :char, :password
end

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

valids = 0

Benchmark.bm do |x|
  x.report do
    valids = lines.count do |line|
      PasswordPolicy.from_line(line).valid?
    end
  end
end

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