Class: RubyDataStructures::MultiDimensionalArray
- Inherits:
-
Object
- Object
- RubyDataStructures::MultiDimensionalArray
- Defined in:
- lib/RubyDataStructures/multi_dimensional_array.rb
Instance Method Summary collapse
- #[](*indices) ⇒ Object
- #[]=(*indices_and_value) ⇒ Object
- #get_offset(indices) ⇒ Object
-
#initialize(*dimensions) ⇒ MultiDimensionalArray
constructor
A new instance of MultiDimensionalArray.
Constructor Details
#initialize(*dimensions) ⇒ MultiDimensionalArray
Returns a new instance of MultiDimensionalArray.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# File 'lib/RubyDataStructures/multi_dimensional_array.rb', line 2 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 |
Instance Method Details
#[](*indices) ⇒ Object
33 34 35 |
# File 'lib/RubyDataStructures/multi_dimensional_array.rb', line 33 def [](*indices) @data[self.get_offset(indices)] end |
#[]=(*indices_and_value) ⇒ Object
37 38 39 40 |
# File 'lib/RubyDataStructures/multi_dimensional_array.rb', line 37 def []=(*indices_and_value) value = indices_and_value.pop @data[self.get_offset(indices_and_value)] = value end |
#get_offset(indices) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/RubyDataStructures/multi_dimensional_array.rb', line 18 def get_offset(indices) raise IndexError if indices.length != @dimensions.length offset = 0 (0..(@dimensions.length - 1)).each do |i| raise IndexError if indices[i] < 0 || indices[i] >= @dimensions[i] offset += @factors[i]*indices[i] end return offset end |