Created
March 11, 2012 14:36
-
-
Save naush/2016629 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
module PrimeFactor | |
def self.new | |
@memoized = {} | |
Hash.new do |h, index| | |
@memoized[index] ||= memoize(h, index) | |
h[index] = @memoized[index] | |
end | |
end | |
def self.memoize(h, number) | |
divisor = 2 | |
while divisor < number | |
while number % divisor == 0 | |
number = number / divisor | |
return [divisor] + h[number] | |
end | |
divisor = divisor + 1 | |
end | |
return [number] if number > 1 | |
return [] | |
end | |
end | |
describe PrimeFactor do | |
it "factors 1 through 9" do | |
@factors = PrimeFactor.new | |
(1..9).each { |number| @factors[number] } | |
@factors.should == { | |
1 => [], | |
2 => [2], | |
3 => [3], | |
4 => [2, 2], | |
5 => [5], | |
6 => [2, 3], | |
7 => [7], | |
8 => [2, 2, 2], | |
9 => [3, 3] | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have gone that direction briefly, but it was slightly more verbose because you're essentially delegating to a hash. But that did get rid of the vexing inheritance. I think what I might try next time is to pass in PrimeFactor to Hash.new instead (ie., Hash.new { |h, index| PrimeFactor.of(h, index) }.