ruby-nuggets 0.0.5.179 → 0.0.5.180
Sign up to get free protection for your applications and to get access to all the features.
- data/lib/nuggets/integer/factorial.rb +28 -1
- metadata +1 -1
@@ -27,14 +27,30 @@
|
|
27
27
|
|
28
28
|
class Integer
|
29
29
|
|
30
|
+
# Memoization container: integer => factorial(integer)
|
31
|
+
FACTORIAL = { 0 => 1 }
|
32
|
+
|
30
33
|
# call-seq:
|
31
34
|
# int.factorial => anInteger
|
32
35
|
#
|
33
|
-
# Calculate the factorial of +int+.
|
36
|
+
# Calculate the factorial of +int+. To use the memoized version:
|
37
|
+
# <tt>Integer.send(:alias_method, :factorial, :factorial_memoized)</tt>
|
34
38
|
def factorial
|
35
39
|
(1..self).inject { |f, i| f * i }
|
36
40
|
end
|
37
41
|
|
42
|
+
# call-seq:
|
43
|
+
# int.factorial_memoized => anInteger
|
44
|
+
#
|
45
|
+
# Calculate the factorial of +int+ with the help of memoization (Which gives
|
46
|
+
# a considerable speedup for repeated calculations -- at the cost of memory).
|
47
|
+
#
|
48
|
+
# WARNING: Don't try to calculate the factorial this way for a too large
|
49
|
+
# integer! This might well bring your system down to its knees... ;-)
|
50
|
+
def factorial_memoized
|
51
|
+
FACTORIAL[self] ||= (1..self).inject { |f, i| FACTORIAL[i] ||= f * i }
|
52
|
+
end
|
53
|
+
|
38
54
|
alias_method :fac, :factorial
|
39
55
|
alias_method :f!, :factorial
|
40
56
|
|
@@ -44,4 +60,15 @@ if $0 == __FILE__
|
|
44
60
|
1.upto(8) { |i|
|
45
61
|
puts "#{i}: #{i.factorial}"
|
46
62
|
}
|
63
|
+
|
64
|
+
require 'benchmark'
|
65
|
+
|
66
|
+
Benchmark.bm(19) { |x|
|
67
|
+
[20000, 800, 300, 700, 130, 480, 9999, 9999, 25000].each { |i|
|
68
|
+
puts "#{i}:"
|
69
|
+
|
70
|
+
x.report('factorial') { i.factorial }
|
71
|
+
x.report('factorial_memoized') { i.factorial_memoized }
|
72
|
+
}
|
73
|
+
}
|
47
74
|
end
|