0

The following code will generate 10 arrays, each with 10 subarrays, each with 10 subarrays, each with 10 subarrays.

paths = [];

for (var i = 0, len_i = 10; i < len_i; ++i) { // 1st dimension
    paths.push([]);
    for (var j = 0, len_j = 10; j < len_j; ++j) { // 2nd dimension
        paths[i].push([]);
        for (var k = 0, len_k = 10; k < len_k; ++k) { // 3rd dimension
            paths[i][j].push([]);
            for (var l = 0, len_l = 10; l < len_l; ++l) { // 4th dimension
                paths[i][j][k].push([]);
                paths[i][j][k][l] = [];
            }
        }
    }
}

I will eventually need to do this with more dimensions and am curious to know if any ingenious developers out there can accomplish this with a function of the form:

function makePaths(quantityInEachArray, dimensions) {

  paths = [];

   quantityInEachArray = (typeof quantityInEachArray === "undefined") ? 10 : quantityInEachArray;
   dimensions = (typeof dimensions === "undefined") ? 4 : dimensions;

   // Do some magic

   return paths;

 }

That function, in its default form, would return the same thing as the for loops I demonstrated above.

I understand that this is not a standard practice but I am doing it for a very specific reason and need to test the performance of it.

How do I modify this code to produce nth dimensional arrays?

George Stocker
  • 57,289
  • 29
  • 176
  • 237
SaltedBlowfish
  • 105
  • 2
  • 9

2 Answers2

4

You can use recursive function:

function nthArray(n, l) {
    if(n < 1) return;
    var arr = new Array(l);
    for(var i=0; i<l; ++i)
        arr[i] = nthArray(n-1, l);
    return arr;
}
Oriol
  • 274,082
  • 63
  • 437
  • 513
0

A simple magic would be (without recursion):

paths = []
arrays = [paths]
for (var i = 0; i < dimensions; i++) {
    tmpArr = []
    for (var k = 0; k < arrays.length; k++) {
        for (var j = 0; j < size; j++) {
            val = []
            tmpArr.push(val)
            arrays[k].push(val)
        }
    }
    arrays = tmpArr
}

(I am not very fluent in javascript, you probably need to declare vars at the beginning and every thing, but that's the idea)

njzk2
  • 38,969
  • 7
  • 69
  • 107