Created
March 14, 2017 21:00
-
-
Save ilyakrasnov/62f229fd74c0a8e4a7dc9021c1ca33d2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Collatz | |
def initialize(n) | |
@current_number = n | |
@sequence = [] | |
end | |
def compute_next_collatz | |
@sequence << @current_number | |
if @current_number == 1 | |
return @sequence | |
elsif @current_number % 2 == 0 | |
@current_number = @current_number / 2 | |
compute_next_collatz | |
else | |
@current_number = @current_number * 3 + 1 | |
compute_next_collatz | |
end | |
end | |
end | |
def longest_collatz(n) | |
longest_sequence = { number: 0, length: 0 } | |
1.upto(n) do |ceiling| | |
sequence = Collatz.new(ceiling).compute_next_collatz | |
# ceiling 1 -> sequence: [1] | |
# compare to current longest_sequence: | |
# longest_sequence = { number: 1, length: 1 } | |
# | |
# ceiling 2 -> sequence: [2, 1] | |
# compare to current longest_sequence: | |
# longest_sequence = { number: 2, length: 2 } | |
# | |
# ceiling 3 -> sequence: [3, 10, 5, 16, 8, 4, 2, 1] | |
# compare to current longest_sequence: | |
# longest_sequence = { number: 3, length: 8 } | |
# | |
# code to write | |
end | |
puts "The longest collatz sequence from 1 to #{n} is the sequence for the number #{longest_sequence[:number]} and has the length of #{longest_sequence[:length]}" | |
end | |
longest_collatz(5) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment