What I came up with 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.bmbm do |x| x.report do valids = lines.count do |line| PasswordPolicy.from_line(line).valid? end end end puts valids
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) }
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
What I came up with in Ruby:
And for comparison, here is the inlined version: