Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class Sequence
class << self
def sequences
Enumerator.new do |y|
sequence = Sequence.new
while sequence
sequence = sequence.next
break unless sequence
y << sequence
end
end
end
end
attr_accessor :elements, :status
def initialize(*elements)
@elements = elements
@status = ""
end
def sum
elements.inject { |sum, n| sum + n }
end
def histogram
@histogram ||= begin
@histogram = Hash.new(0)
elements.each do |digit|
@histogram[digit] += 1
end
@histogram
end
end
def has_digit_pair?
histogram.values.any? { |x| x == 2 }
end
def has_digit_trio?
histogram.values.any? { |x| x > 2 }
end
def valid?
!has_digit_trio? && has_digit_pair? && sum == 15
end
def next
return Sequence.new(1) if elements.empty?
if has_digit_trio?
elements[-1] += 1
return Sequence.new(*elements)
elsif sum < 15
return Sequence.new(*(elements << elements[-1]))
elsif sum >= 15
new_elements = elements[0 .. -2]
if new_elements[-1] == 9
return nil if new_elements.size == 1
new_elements = new_elements[0 .. -2]
end
new_elements[-1] += 1
return Sequence.new(*new_elements)
end
end
end
if __FILE__ == $0
result = Sequence.sequences.select { |s| s.valid? }
p result.size
p result.map(&:elements)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.