Skip to content

Instantly share code, notes, and snippets.

@stellard
Created May 25, 2011 00:45
Show Gist options
  • Save stellard/990087 to your computer and use it in GitHub Desktop.
Save stellard/990087 to your computer and use it in GitHub Desktop.
Counter of mixed base
class RolloverIndex
attr_accessor :max, :count
def initialize max, start = 0
self.max = max
self.count = start
end
def inc
if (self.count + 1) == max
self.count = 0
true
else
self.count = self.count + 1
false
end
end
def to_i
count
end
end
class ArrayCounter
attr_accessor :indices
def initialize max_array
self.indices = max_array.map{|max| RolloverIndex.new max }
end
def inc
indices.length.times do |i|
return indices unless indices[i].inc
end
end
end
@acounter = ArrayCounter.new [2,5]
10.times do |variable|
puts @acounter.indices.map(&:to_i).inspect
@acounter.inc
end
# =>
#[0, 0]
#[1, 0]
#[0, 1]
#[1, 1]
#[0, 2]
#[1, 2]
#[0, 3]
#[1, 3]
#[0, 4]
#[1, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment