Class: Integer
- Includes:
- Nuggets::Integer::LengthMixin
- Defined in:
- lib/nuggets/integer/factorial.rb,
lib/nuggets/integer/length.rb,
lib/nuggets/integer/to_binary_s.rb,
lib/nuggets/util/dotted_decimal.rb
Overview
–
#
A component of ruby-nuggets, some extensions to the Ruby programming # language. #
#
Copyright © 2007-2008 Jens Wille #
#
Authors: #
Jens Wille <jens.wille@uni-koeln.de> #
#
ruby-nuggets is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation; either version 3 of the License, or (at your option) # any later version. #
#
ruby-nuggets is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. #
#
You should have received a copy of the GNU General Public License along # with ruby-nuggets. If not, see <www.gnu.org/licenses/>. #
#
++
Constant Summary collapse
- FACTORIAL =
Memoization container: integer => factorial(integer)
{ 0 => 1 }
Instance Method Summary collapse
-
#factorial ⇒ Object
(also: #fac, #f!)
call-seq: int.factorial => anInteger.
-
#factorial_memoized ⇒ Object
call-seq: int.factorial_memoized => anInteger.
-
#to_binary_s(length = nil) ⇒ Object
call-seq: int.to_binary_s => aString int.to_binary_s(length) => aString.
-
#to_dotted_decimal ⇒ Object
call-seq: int.to_dotted_decimal => aString.
Methods included from Nuggets::Integer::LengthMixin
Instance Method Details
#factorial ⇒ Object Also known as: fac, f!
call-seq:
int.factorial => anInteger
Calculate the factorial of int. To use the memoized version: Integer.send(:alias_method, :factorial, :factorial_memoized)
38 39 40 |
# File 'lib/nuggets/integer/factorial.rb', line 38 def factorial (1..self).inject { |f, i| f * i } end |
#factorial_memoized ⇒ Object
call-seq:
int.factorial_memoized => anInteger
Calculate the factorial of int with the help of memoization (Which gives a considerable speedup for repeated calculations – at the cost of memory).
WARNING: Don’t try to calculate the factorial this way for “large” integers! This might well bring your system down to its knees… ;-)
50 51 52 |
# File 'lib/nuggets/integer/factorial.rb', line 50 def factorial_memoized FACTORIAL[self] ||= (1..self).inject { |f, i| FACTORIAL[i] ||= f * i } end |
#to_binary_s(length = nil) ⇒ Object
call-seq:
int.to_binary_s => aString
int.to_binary_s(length) => aString
Returns int as binary number string; optionally zero-padded to length.
35 36 37 |
# File 'lib/nuggets/integer/to_binary_s.rb', line 35 def to_binary_s(length = nil) "%0#{length}d" % to_s(2) end |
#to_dotted_decimal ⇒ Object
call-seq:
int.to_dotted_decimal => aString
Converts int to dotted-decimal notation.
36 37 38 |
# File 'lib/nuggets/util/dotted_decimal.rb', line 36 def to_dotted_decimal to_binary_s(32).unpack('a8' * 4).map { |s| s.to_i(2) }.join('.') end |