Ruby 2019 day 4
This commit is contained in:
parent
888afda9d7
commit
b004c936f0
8
ruby/2019/4/bin/problem
Normal file
8
ruby/2019/4/bin/problem
Normal file
@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env ruby
|
||||
|
||||
require "secure_container"
|
||||
low, high = STDIN.read.chomp.split("-").map(&:to_i)
|
||||
range = low..high
|
||||
|
||||
puts "Part 1: #{range.count(&:valid_part_1_password?)}"
|
||||
puts "Part 2: #{range.count(&:valid_part_2_password?)}"
|
||||
25
ruby/2019/4/lib/secure_container.rb
Normal file
25
ruby/2019/4/lib/secure_container.rb
Normal file
@ -0,0 +1,25 @@
|
||||
class Integer
|
||||
def valid_part_1_password?
|
||||
has_two_adjacent_digits? and digits_never_decrease?
|
||||
end
|
||||
|
||||
def valid_part_2_password?
|
||||
has_exactly_two_adjacent_digits? and digits_never_decrease?
|
||||
end
|
||||
|
||||
def digits_never_decrease?
|
||||
digits.reverse == digits.sort
|
||||
end
|
||||
|
||||
def has_two_adjacent_digits?
|
||||
digits[..-2].zip(digits[1..]).any? { |x, y| x == y }
|
||||
end
|
||||
|
||||
def has_exactly_two_adjacent_digits?
|
||||
threes = digits[..-3].zip(digits[1..-2]).zip(digits[2..]).map{ |x| x.flatten(1) }
|
||||
triple_indices = threes.each_with_index.select{ |trip, index| trip[0] == trip[1] && trip[0] == trip[2] }.map(&:last)
|
||||
pairs = digits[..-2].zip(digits[1..])
|
||||
pair_indices = pairs.each_with_index.select{ |pair, index| pair[0] == pair[1]}.map(&:last)
|
||||
pair_indices.any? { |pair_index| !triple_indices.include?(pair_index) && !triple_indices.include?(pair_index - 1) }
|
||||
end
|
||||
end
|
||||
Loading…
Reference in New Issue
Block a user