1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
class MultiDimensionalArray
def initialize(*dimensions)
@dimensions = Array.new(dimensions.length)
@factors = Array.new(dimensions.length)
product = 1
i = dimensions.length - 1
while i>=0
@dimensions[i] = dimensions[i]
@factors[i] = product
product *= @dimensions[i]
i -= 1
end
@data = Array.new(product)
end
def getOffset(indices)
if indices.length != @dimensions.length
STDERR.puts "#{$0}: getOffset indices.length = #{indices.length} " +
"!= #{@dimensions.length} = @dimensions.length"
exit 1
end
offset = 0
0.upto(@dimensions.length-1) do |i|
if indices[i] < 0 or indices[i] >= @dimensions[i]
STDERR.puts "#{$0}: illegal value indices[#{i}]=#{indices[i]}"
exit 1
end
offset += @factors[i] * indices[i]
end
return offset
end
def [](*indices)
return @data[self.getOffset(indices)]
end
def []=(*indicesAndValue)
value = indicesAndValue.pop
@data[self.getOffset(indicesAndValue)] = value
end
def enumaccesstubles()
numofwheels = @dimensions.length
wheelspace = Array.new(numofwheels)
idx = numofwheels - 1
0.upto(numofwheels-1) do |i|
wheelspace[i] = 0
end
loop do
wheelspace[idx] += 1
if wheelspace[idx] == @dimensions[idx]
wheelspace[idx] = 0
if idx == 0
break
end
idx -= 1
else
idx = numofwheels-1
yield wheelspace
end
end
end
end
|