Last active
August 29, 2015 14:00
-
-
Save amcaplan/11356768 to your computer and use it in GitHub Desktop.
Collatz Conjecture (aka Project Euler Problem 14) using Benchmark library - don't copy, the point is to solve it yourself!
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
require 'benchmark' | |
class Collatz | |
@@collatzes = {1 => 1} | |
def self.max_chain_starter_under(highest) | |
(1...highest).max_by { |option| Collatz.new(option).length } | |
end | |
def initialize(num) | |
@num = num | |
end | |
def length | |
collatz(@num) | |
end | |
def collatz(num) | |
@@collatzes[num] ||= 1 + (num.even? ? collatz(num/2) : collatz(num*3 + 1)) | |
end | |
private :collatz | |
end | |
benchmark_results = Benchmark.measure do | |
puts Collatz.max_chain_starter_under(1_000_000) | |
end | |
benchmark_results2 = Benchmark.measure do | |
puts Collatz.max_chain_starter_under(1_000_000) | |
end | |
puts "First time running: #{benchmark_results}" | |
puts "Second time running: #{benchmark_results2}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment