Last active
August 29, 2015 14:06
-
-
Save EderRoger/a3a784a7cd0f94f8e79d to your computer and use it in GitHub Desktop.
Ruby Conjectura de Collatz
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 Conjectura | |
attr_reader :elements | |
def initialize | |
@elements = Hash.new | |
end | |
def calc(range) | |
range.each{ |i| calc_seq_cache i } | |
end | |
def calc_seq_cache(n) | |
@elements[n] = calc_seq(n,1) | |
end | |
def calc_seq(n,s) | |
if @elements[n] | |
return @elements[n] + s -1 | |
elsif n == 1 | |
return s | |
elsif n & 1 == 0 | |
return calc_seq(n/2,s+1) | |
else | |
return calc_seq(3*n+1,s+1) | |
end | |
end | |
end |
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 'spec_helper' | |
require 'benchmark' | |
describe Conjectura do | |
it 'do calc 999.999 get hightest sequence' do | |
conjectura = Conjectura.new | |
Benchmark.bm do |x| | |
x.report { conjectura.calc(1..999_999) } | |
end | |
expect(conjectura.elements.values.max).to eq(525) | |
end | |
end |
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_relative '../lib/conjectura' | |
require 'yaml' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment