euler/ruby/euler051.rb

36 lines
998 B
Ruby
Raw Normal View History

2016-09-06 07:08:56 +00:00
require_relative 'euler'
def bitmasks(length)
(1..2**length-1).map { |n| n.to_s(2) }.map { |s| s.rjust(4, '0')}.map { |s| s.split('').map(&:to_i)}
2014-11-19 22:50:42 +00:00
end
2016-09-06 07:08:56 +00:00
def prime_digit_replacement(number, mask)
digits = number.to_digit_list
related_primes = []
('0'..'9').each do |j|
copied_digit_list = Array.new(digits)
mask.each_with_index do |bit, index|
copied_digit_list[index] = j if bit == 1
2014-11-19 22:50:42 +00:00
end
2016-09-06 07:08:56 +00:00
new_num = Euler.from_digit_list(copied_digit_list)
related_primes.push(new_num) if new_num.prime? and !related_primes.include?(new_num) and new_num.to_digit_list.count == digits.count
2014-11-19 22:50:42 +00:00
end
2016-09-06 07:08:56 +00:00
related_primes
2014-11-19 22:50:42 +00:00
end
2016-09-06 07:08:56 +00:00
def solution(family_count)
result = false
Prime.take_while do |p|
digits = p.to_digit_list
bitmasks(digits.count).each do |mask|
related_primes = prime_digit_replacement(p, mask)
if related_primes.count == family_count and related_primes.include?(p)
result = p
break
end
end
result == false
2014-11-19 22:50:42 +00:00
end
2016-09-06 07:08:56 +00:00
result
2014-11-19 22:50:42 +00:00
end