Two dimensional array

def get2DArray(oneDarray) #oneDarray is of dimention 1Xn^2
###what will be the code here??
return twoDarray
end

oneDarray is a one dimensional array, and is of dimention 1Xn^2, I would
like to assign this to two dimentional array namd twoDarray so that I
can get the first row as twoDarray[i].

for example:
oneDarray=[1,2,3,4,5,6,7,8,9]
gives
twoDarray=[[1,2,3],[4,5,6],[7,8,9]]
and twoDarray[1]=[4,5,6]

Help me to write code at ###

Hi,

Calculate the square root of the lenght of the original array and then
use Enumerable#each_slice to create an array of “rows”.

For example:

one_d_array = (1…9).to_a
dim = Math.sqrt(one_d_array.length).to_i
two_d_array = one_d_array.each_slice(dim).to_a
p two_d_array

However, if you actually want to do matrix calculations, you should use
the Matrix class instead of an array:

Array#each_slice method is helpful to u.

oneDarray.each_slice(3).to_a
=> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

2012/8/13 ajay paswan [email protected]

oneDarray=[1,2,3,4,5,6,7,8,9]
gives
twoDarray=[[1,2,3],[4,5,6],[7,8,9]]
and twoDarray[1]=[4,5,6]

Help me to write code at ###


Posted via http://www.ruby-forum.com/.

What is not clear? Which method or syntax don’t you understand?

:frowning: not clear.