Class: Dice_Stats::Internal_Utilities::Arbitrary_base_counter

Inherits:
Object
  • Object
show all
Defined in:
lib/Internal_Utilities/Arbitrary_base_counter.rb

Overview

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(maximums) ⇒ Arbitrary_base_counter

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]



32
33
34
35
# File 'lib/Internal_Utilities/Arbitrary_base_counter.rb', line 32

def initialize(maximums)
	@overflow = false
	@index = maximums.map { |i| {:val => 0, :max => i} }
end

Instance Attribute Details

#overflowObject (readonly)

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]



26
27
28
# File 'lib/Internal_Utilities/Arbitrary_base_counter.rb', line 26

def overflow
  @overflow
end

Instance Method Details

#[](i) ⇒ Object

Overloaded index operator, used to retrieve the number stored in the ith digit place



75
76
77
# File 'lib/Internal_Utilities/Arbitrary_base_counter.rb', line 75

def [](i)
	@index[i][:val]
end

#incrementObject

Increase the “value” of the counter by one



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# 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

#lengthObject

Return an integer representing how many digits the counter holds



68
69
70
# File 'lib/Internal_Utilities/Arbitrary_base_counter.rb', line 68

def length
	@index.length
end

Puts the array of digits.



81
82
83
# File 'lib/Internal_Utilities/Arbitrary_base_counter.rb', line 81

def print
	puts @index
end