class Dice_Stats::Internal_Utilities::Arbitrary_base_counter
This class defines a counter where each “digit” has a different base. For example, a counter of two digits, the first with base 3 and the second with base 2 may go like this: 0 => [0, 0] 1 => [0, 1] 2 => [1, 0] 3 => [1, 1] 4 => [2, 0] 5 => [2, 1] 5 would be the maximum number the counter could hold.
TODO:
-
Add a “decrement” method
-
Add a “value” method to return the count in base 10
Attributes
A boolean value representing if the result has overflown. Will be false initially, will be set to true if the counter ends up back at [0, 0, …, 0]
Public Class Methods
Define a new counter. maximums
is an array of integers, each specifying the base of its respective digit. For example, to create a counter of 3 base 2 digits, supply [2,2,2]
# File lib/Internal_Utilities/Arbitrary_base_counter.rb, line 32 def initialize(maximums) @overflow = false @index = maximums.map { |i| {:val => 0, :max => i} } end
Public Instance Methods
Overloaded index operator, used to retrieve the number stored in the +i+th digit place
# File lib/Internal_Utilities/Arbitrary_base_counter.rb, line 75 def [](i) @index[i][:val] end
Increase the “value” of the counter by one
# File lib/Internal_Utilities/Arbitrary_base_counter.rb, line 39 def increment #start at the end of the array (i.e. the "lowest" significant digit) i = @index.length - 1 loop do #increment the last value @index[i][:val] += 1 #check if it has "overflown" that digits base if @index[i][:val] >= @index[i][:max] #set it to 0 @index[i][:val] = 0 if (i == 0) @overflow = true end #move to the next digit to the "left" i -= 1 else #done break end end end
Return an integer representing how many digits the counter holds
# File lib/Internal_Utilities/Arbitrary_base_counter.rb, line 68 def length @index.length end
Puts the array of digits.
# File lib/Internal_Utilities/Arbitrary_base_counter.rb, line 81 def print puts @index end