Class: DS::Array2D

Inherits:
Object
  • Object
show all
Defined in:
lib/ds/arrays/array_2d.rb

Overview

Implements two dimensional array.

Instance Method Summary collapse

Constructor Details

#initialize(size = 1, init = 0) ⇒ Array2D

Creates new two dimensional array. Init is the default value of the array.



5
6
7
8
# File 'lib/ds/arrays/array_2d.rb', line 5

def initialize(size = 1, init = 0)
  @init = init
  @store = Array.new(size) { Array.new(size) { init } }
end

Instance Method Details

#[](x, y) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/ds/arrays/array_2d.rb', line 10

def [](x, y)
  if @store[x].nil?
    @store[x] = []
    @init
  elsif @store[x][y].nil?
    @init
  else
    @store[x][y]
  end
end

#[]=(x, y, v) ⇒ Object



21
22
23
24
# File 'lib/ds/arrays/array_2d.rb', line 21

def []=(x, y, v)
  @store[x] = [] if @store[x].nil?
  @store[x][y] = v
end

#flattenObject



30
31
32
# File 'lib/ds/arrays/array_2d.rb', line 30

def flatten
  @store.flatten
end

#sizeObject



34
35
36
# File 'lib/ds/arrays/array_2d.rb', line 34

def size
  @store.size
end

#to_aObject



26
27
28
# File 'lib/ds/arrays/array_2d.rb', line 26

def to_a
  @store
end