的JavaScript。从计算中创建多维数组

时间:2013-04-29 23:15:38

标签: javascript multidimensional-array

我正在尝试根据另一个3D数组的计算创建一个多维数组。

输入数组的格式为[shift,start Num,end num]

我应该清楚“,”只是出于视觉目的。 我需要在其自己的数组位置中的每个值,即[value1]=location 0,0 [value2]=location 0,1 [value3]=location 0,2等。

示例:

aInput looks like this
[0,1,5]
[1,1,3]
[2,1,2]

aOutput should look like this
[1,1,1]
[1,1,2]
[1,2,1]
[1,2,2]
[1,3,1]
[1,3,2]
[2,1,1]
[2,1,2]
[2,2,1]
[2,2,2]
[2,3,1]
[2,3,2]
[1,3,2]
[3,1,1]
[3,1,2]
[3,2,1]
[3,2,2]
[3,3,1]
[3,3,2]
[etc]

需要根据班次增加数组中的项目数。即0 =移位为1列,shift = 1为2列,shift = 3为3列,依此类推。这就是我到目前为止所做的,但我无法弄清楚如何计算任何有班次的东西。

var aInput = new Array();
aInput[0] = new Array("0", "1","5");
aInput[1] = new Array("1", "1","3");
aInput[2] = new Array("2", "1","2");

for (var x=0; x < aInput[x].length; x++){
    //Calculate out number
    if (aInput[x][0] == 0){ // Im sure this should be a loop of some sort, just not sure how to do it
        var i=Number(aInput[x][1]);
        while (i <= Number(aInput[x][2])){
            //Write to output array
            aOutput.push(i);
            i++;
        }
    }
}

在此先感谢您的帮助,我真的很难过这个。

2 个答案:

答案 0 :(得分:0)

var aOutput = [];
for (var i in aInput) {
    var y = parseInt(aInput[i][1])
    for (var x = y; x <= parseInt(aInput[i][2]); x++) {
        aOutput.push([i, y, x]);
    }
}

答案 1 :(得分:0)

var aInput = new Array();
aInput[0] = new Array("0", "1", "5");
aInput[1] = new Array("1", "1", "3");
aInput[2] = new Array("2", "1", "2");

var input_indexed = [],
    elem = []; // elem holds the row to be added to the output

// Get aInput[] into a more useful arrangement
for (var i = 0; i < aInput.length; i++) {
    // Save the range of each column
    input_indexed[parseInt(aInput[i][0])] = {
        start: parseInt(aInput[i][1]),
        end: parseInt(aInput[i][2])
    };
    // Initialize elem with the start value of each column
    elem[aInput[i][0]] = parseInt(aInput[i][1]);
}

// Produce the output
aOutput = [];
done = false;
while (!done) {
    aOutput.push(elem.slice(0)); // push a copy of elem into result
    for (i = elem.length - 1;; i--) { // Increment elements from right to left
        if (i == -1) { // We've run out of columns
            done = true;
            break;
        }
        elem[i]++; // Increment the current column
        if (elem[i] <= input_indexed[i].end) {
            // If it doesn't overflow, we're done
            break;
        }
        // When it overflows, return to start value and loop around to next column
        elem[i] = input_indexed[i].start;
    }
}

FIDDLE