Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@noelrappin
Created September 29, 2010 00:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save noelrappin/602076 to your computer and use it in GitHub Desktop.
Save noelrappin/602076 to your computer and use it in GitHub Desktop.
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