Create Two-Dimensional Arrays and Access Sub-Arrays in Ruby

Create two-dimensional arrays and access sub-arrays in Ruby

There are some problems with 2 dimensional Arrays the way you implement them.

a= [[1,2],[3,4]]
a[0][2]= 5 # works
a[2][0]= 6 # error

Hash as Array

I prefer to use Hashes for multi dimensional Arrays

a= Hash.new
a[[1,2]]= 23
a[[5,6]]= 42

This has the advantage, that you don't have to manually create columns or rows. Inserting into hashes is almost O(1), so there is no drawback here, as long as your Hash does not become too big.

You can even set a default value for all not specified elements

a= Hash.new(0)

So now about how to get subarrays

(3..5).to_a.product([2]).collect { |index| a[index] }
[2].product((3..5).to_a).collect { |index| a[index] }

(a..b).to_a runs in O(n). Retrieving an element from an Hash is almost O(1), so the collect runs in almost O(n). There is no way to make it faster than O(n), as copying n elements always is O(n).

Hashes can have problems when they are getting too big. So I would think twice about implementing a multidimensional Array like this, if I knew my amount of data is getting big.

How to declare an empty 2-dimensional array in Ruby?

You can do:

width = 2
height = 3
Array.new(height){Array.new(width)} #=> [[nil, nil], [nil, nil], [nil, nil]]

Creating and iterating a 2d array in Ruby

irb(main):001:0> a = []
=> []
irb(main):002:0> a1 = [1, 2]
=> [1, 2]
irb(main):003:0> a2 = [3, 4]
=> [3, 4]
irb(main):004:0> a.push a1
=> [[1, 2]]
irb(main):005:0> a.push a2
=> [[1, 2], [3, 4]]
irb(main):006:0> a
=> [[1, 2], [3, 4]]
irb(main):007:0> a[0]
=> [1, 2]
irb(main):008:0> a[0][1]
=> 2

Ruby change value in two dimensional array

The array @double actually contains four references to the same array @single, which is why you're getting the behavior you describe.

Initialize @double = [@single.clone, @single.clone, @single.clone, @single.clone] to get independent (but initially identical) sub-arrays.

Ruby multidimensional array

Strictly speaking it is not possible to create multi dimensional arrays in Ruby. But it is possible to put an array in another array, which is almost the same as a multi dimensional array.

This is how you could create a 2D array in Ruby:

a = [[1,2,3], [4,5,6], [7,8,9]]



As stated in the comments, you could also use NArray which is a Ruby numerical array library:

require 'narray'
b = NArray[ [1,2,3], [4,5,6], [7,8,9] ]

Use a[i][j] to access the elements of the array. Basically a[i] returns the 'sub array' stored on position i of a and thus a[i][j] returns element number j from the array that is stored on position i.

How to declare a two-dimensional array in Ruby

A simple implementation for a sparse 2-dimensional array using nested Hashes,

class SparseArray
attr_reader :hash

def initialize
@hash = {}
end

def [](key)
hash[key] ||= {}
end

def rows
hash.length
end

alias_method :length, :rows
end

Usage:

sparse_array = SparseArray.new
sparse_array[1][2] = 3
sparse_array[1][2] #=> 3

p sparse_array.hash
#=> {1=>{2=>3}}

#
# dimensions
#
sparse_array.length #=> 1
sparse_array.rows #=> 1

sparse_array[0].length #=> 0
sparse_array[1].length #=> 1

Ruby, 2 dimensional arrays, make 2d array with size MxN plus change created lines

Accept simplicity.
Use matrix class in Ruby.

require 'matrix'
m = 3
n = 4
#considering 1-indexed array/matrices and reversing even/odd conditions
Matrix.build(m, n) do |r, c|
r.even? ? (m > c ? c+1 : 0) : m - c
# if r.even? and m > c
# c+1
# elsif r.even?
# 0
# else
# m-c
# end
end
#=> Matrix[[1, 2, 3, 0], [3, 2, 1, 0], [1, 2, 3, 0]]

Here, whenever n > m, those cells will retain the default value, which is 0 in this case.

Commented the alternative implementation of ternary operation with if/else.



Related Topics



Leave a reply



Submit