Skip to content

Instantly share code, notes, and snippets.

Created May 23, 2013 19:13
Show Gist options
  • Save anonymous/e278165308b1091c1559 to your computer and use it in GitHub Desktop.
Save anonymous/e278165308b1091c1559 to your computer and use it in GitHub Desktop.
class CollatzSequence
include Enumerable
def initialize(n)
@n = n
end
def each
n = @n
yield n
while n > 1
# n = n.even? ? n / 2 : n * 3 + 1
if n.even?
n = n / 2
else
n = n * 3 + 1
end
yield n
end
end
end
class Foo < Struct.new(:start, :length, :sequence)
include Comparable
def <=>(other)
self.length <=> other.length
end
def self.create_without_sequence(n)
Foo.new(n, CollatzSequence.new(n).count)
end
def self.create(n)
seq = CollatzSequence.new(n).to_a
Foo.new(n, seq.length, seq)
end
end
longest = (1 .. 1e6).map{|i| Foo.create_without_sequence(i)}.sort.last
p CollatzSequence.new(longest.start).to_a
puts longest.length
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment