# Problem with recursive multidimensional matrix

4

I need to make a recursive multidimensional array in javascript. I have made a function that clones an array, and I thought what the function of the matrix would be, but I do not know what I'm doing wrong.

I want, for example, `matrix([2,3,4])` to return this to me:

[[[0,1,2,3]], [0,1,2,3], [0,1,2,3]], [[0,1,2,3], [0, 1,2,3], [0,1,2,3]]]

This means that the length of the array entered is the number of dimensions, and the numbers are the value of the dimensions, having a 3D matrix of 2x3x4 (height, width and height).

This is my code:

``````function copiarArray(A)
{
var B=[]
for(var i=0;i<A.length;i++)
{
B[i]=A[i]
}
return B
}
function matriz(dims)
{
var I=dims
dims.shift()
var A=[]
A.length=I
for(var i=0;i<I;i++)
{
var dims2=copiarArray(dims)
A[i]=matriz(dims)
dims=dims2
}
return A
}
``````

Currently the error he gives me is:

Uncaught RangeError: Invalid array length (...)

Edit:

If possible, I would like `matriz(dims)` to only receive one argument, that is, not allow more than one ... Otherwise, instead of `[0,1,2,3]` , let all values be in `0` , in this way, `[0,0,0,0]` .

asked by ArtEze 23.11.2016 в 02:43
source

2

In addition to the response from @jcarrenog , you could also do so:

• `Array(length)` , to create a `array` of the indicated length.

• `.shift()` , to remove the first element of `array` .

• `dims.length ?` , to know if you still have to execute the recursive function.

• `dims.slice(0)` , to clone the `array` that is passed to the function.

Example:

``````function matrix(dims) {
var arr = Array(dims.shift() || 0);
for (var idx = 0; idx < arr.length; idx++) {
arr[idx] = dims.length ? matrix(dims.slice(0)) : idx;
}
return arr;
}

console.log(JSON.stringify(matrix([])));
console.log(JSON.stringify(matrix()));
console.log(JSON.stringify(matrix([2,3])));
console.log(JSON.stringify(matrix([2,3,4])));``````

source
2
``````//x = alto, y = ancho, z = profundidad. Visto desde el 3D :D
function matriz(x, y, z){
var array = [];
var i = 0;
for(var xi = 0; xi <= x-1; xi++){
array.push(new Array());
for(var yi = 0; yi <= y-1; yi++){
array[xi].push(new Array());
for(var zi = 0; zi <= z-1; zi++){
array[xi][yi].push(new Array());
array[xi][yi][zi] = i;
i++;
}
i = 0;
}
}
return array;
}

console.log(matriz(2, 2, 2));
``````

I hope it works for you and that you understand: D

2

As you ask for recursive, I think you mean this:

``````function matrix(dims) {
if (dims.length === 0) return 0;
var res = [],
dimension = dims;
for (var i = 0; i < dimension; i++) {
res[i] = matrix(dims.slice(1)) || res.length;
}
return res;
}

var res = matrix([2, 3, 4]);
document.getElementById('res').innerText = JSON.stringify(res);
``````

I leave you here a jsfiddle: link