js遍历数组 - 如何在javascript中对角遍历数组




js修改数组 (6)

从左上角到右下角

var array = ["ABCD","EFGH","IJKL"];

var Ylength = array.length;
var Xlength = array[0].length;
var maxLength = Math.max(Xlength, Ylength);
var temp;
for (var k = 0; k <= 2 * (maxLength - 1); ++k) {
    temp = [];
    for (var y = Ylength - 1; y >= 0; --y) {
        var x = k - y;
        if (x >= 0 && x < Xlength) {
            temp.push(array[y][x]);
        }
    }
    if(temp.length > 0) {
        document.body.innerHTML += temp.join('') + '<br>';
    }
}

(另见小提琴

从左下角到右上角

var array = ["ABCD","EFGH","IJKL"];

var Ylength = array.length;
var Xlength = array[0].length;
var maxLength = Math.max(Xlength, Ylength);
var temp;
for (var k = 0; k <= 2 * (maxLength - 1); ++k) {
    temp = [];
    for (var y = Ylength - 1; y >= 0; --y) {
        var x = k - (Ylength - y);
        if (x >= 0 && x < Xlength) {
            temp.push(array[y][x]);
        }
    }
    if(temp.length > 0) {
        document.body.innerHTML += temp.join('') + '<br>';
    }
}

(另见小提琴

综合

由于两者之间只有一条差异线,因此您可以轻松地将它们组合在一个函数中:

var array = ["ABCD","EFGH","IJKL"];

function diagonal(array, bottomToTop) {
    var Ylength = array.length;
    var Xlength = array[0].length;
    var maxLength = Math.max(Xlength, Ylength);
    var temp;
    var returnArray = [];
    for (var k = 0; k <= 2 * (maxLength - 1); ++k) {
        temp = [];
        for (var y = Ylength - 1; y >= 0; --y) {
            var x = k - (bottomToTop ? Ylength - y : y);
            if (x >= 0 && x < Xlength) {
                temp.push(array[y][x]);
            }
        }
        if(temp.length > 0) {
            returnArray.push(temp.join(''));
        }
    }
    return returnArray;
}

document.body.innerHTML = diagonal(array).join('<br>') +
                          '<br><br><br>' +
                          diagonal(array, true).join('<br>');

(另见小提琴

我有一个字符串数组,我想对角线遍历。
假设:

  • 每个字符串的长度相同。
  • 阵列可以是正方形或矩形,水平或垂直。

矩阵看起来像这样:

A B C D
E F G H
I J K L

我想(从左上角到右下角):

A
EB
IFC
JGD
KH
L

和(从左下角到右上角):

I
JE
KFA
LGB
HC
D

我已经有一段代码可以工作3/4,但我似乎无法弄清楚我在做什么(错误)。

//the array
var TheArray = ['ABCD','EFGH','IJKL'];

//amount of rows
var RowLength = TheArray.length;
//amount of colums
var ColumnLength = TheArray[0].length;

我的代码将对角线切入这些循环中的4个以获得所有对角线。 对于循环,它看起来是2,而if不循环未绑定的值。 伪代码看起来有点像这样:

for(loop rows){
 var outputarray = [];
   for(loop columns){
      if(delimit for out of bound){
       var temprow = TheArray[something?];
       var tempvalue = temprow[something?];
       outputarray.push(tempvalue);
       }
   }
 //use values
document.getElementById("theDiv").innerHTML += outputarray.join("")+"<br>";
}

我希望有人可以帮助我。


使用指数:

[i][j-i]

我从0到M-1的地方

j从0到i

而j ++ <N

对于矩阵

类型数组[M] [N]

但是,如果矩阵是矩形的话,这可能会错过右下角的一些,并且您可能需要第二个嵌套for循环,其中i和j用于捕获它们。


对角线的完整解决方案:

var TheArray = ['ABCD', 'EFGH', 'IJKL'];
var RowLength = TheArray.length;
var ColumnLength = TheArray[0].length;

// Diagonals
var diagonal = [[], []];
for (var i = 0; i < Math.min(RowLength, ColumnLength); i++) {
    diagonal[0].push({'row': 0-i, 'col': i});
    diagonal[1].push({'row': 0-i, 'col': 0-i});
}

// Entry points
// 1///
// 2///
// 3456
var points = [[], []];
for (var y = 0; y < RowLength; y++) {
    points[0].push({'row': y, 'col': 0});
}
for (var x = 1; x < ColumnLength; x++) {
    points[0].push({'row': RowLength - 1, 'col': x});
}

// Entry points
// \\\6
// \\\5
// 1234
for (var x = 0; x < ColumnLength; x++) {
    points[1].push({'row': RowLength - 1, 'col': x});
}
for (var y = RowLength - 2; y >= 0; y--) {
    points[1].push({'row': y, 'col': ColumnLength - 1});
}

var strings = [[], []];
for (var line = 0; line < diagonal.length; line++) {
    for (var point = 0; point < points[line].length; point++) {
        var inside = true;
        var index = 0;
        var string = '';
        while (inside && index < diagonal[line].length) {
            var row = points[line][point]['row'] + diagonal[line][index]['row'];
            var col = points[line][point]['col'] + diagonal[line][index]['col'];
            if (row >= 0 && row < RowLength && col >= 0 && col < ColumnLength) {
                string += TheArray[row][col];
                index++;
            } else {
                inside = false;
            }
        }
        strings[line].push(string);
    }
}

console.log(strings);

尝试这个

var TheArray = ['ABCD', 'EFGH', 'IJKL'];
    //amount of rows
    var RowLength = TheArray.length;
    //amount of colums
    var ColumnLength = TheArray[0].length;

    var totalNoComb = RowLength + ColumnLength - 1;
    var combArr = new Array(totalNoComb);
    for (var i = 0; i < totalNoComb; i++) {
        combArr[i] = "";
        for (var j = RowLength-1; j >-1; j--) {
            if (i - j > -1 && i - j < ColumnLength)
                combArr[i] += TheArray[j][i-j];
        }
    }
    alert(combArr);

    for (var i = 0; i < totalNoComb; i++) {
        combArr[i] = "";
        for (var j = 0; j < RowLength; j++) {
            if (i - j > -1 && i - j < ColumnLength)
                combArr[i] += TheArray[ RowLength -1-j][i - j];
        }
    }
    alert(combArr);


这应该适用于矩形矩阵:

var array = ["ABCD", "EFGH", "IJKL"];
var arrOfArr = [];
var resultArray = [];
for (var i = 0; i < array.length; ++i) {
    arrOfArr.push(array[i].split(''));
}

var rows = arrOfArr.length;
var columns = arrOfArr[0].length;

var index = 0;

for (var i = 0; i < rows; ++i) {
    var k = 0;
    resultArray[index] = new Array();
    for (var j = i; j >= 0; --j) {
        resultArray[index].push(arrOfArr[j][k]);
        ++k;
        if ( k === columns) {
            break;
        }
    }
    resultArray[index] = resultArray[index].join('');
    ++index;
}

for (var j = 1; j < columns; ++j) {
    var k = rows - 1;
    resultArray[index] = new Array();
    for (var i = j; i < columns; ++i) {
        resultArray[index].push(arrOfArr[k][i]);
        --k;
        if ( k === -1) {
            break;
        }
    }
    resultArray[index] = resultArray[index].join('');
    ++index;
}
console.log(JSON.stringify(resultArray));


这是我从'从左上角到右下角'的尝试:

for (i=0; i<nbRows; i++) {
    x = 0; y = i;
    while (x < nbColumns && y >= 0) {
        print(array[x, y]);
        x++; y--;
    }
    print("\n");
}
for (i=1; i<nbColumns; i++) {
    x = i; y = nbRows - 1;
    while (x < nbColumns && y >=0) {
        print(array[x, y]);
        x++; y--;
    }
}

需要进行一些调整以适应JavaScript语法。







iteration