如何在javascript中对角遍历数组

时间:2016-03-10 13:20:24

标签: javascript arrays loops matrix iteration

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

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

矩阵看起来像这样:

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>";
}

我希望有人能帮助我。

9 个答案:

答案 0 :(得分:17)

从左上角到右下角

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>';
    }
}

(另见this Fiddle

从左下角到右上角

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>';
    }
}

(另见this Fiddle

联合

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

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>');

(另见this Fiddle

答案 1 :(得分:5)

这样做,并将所需的结果输出到屏幕:

var array = ['ABCD','EFGH','IJKL'];
var rows = array.length;
var cols = array[0].length;
for (var n = 0; n < cols + rows - 1; n += 1)
{
  var r = n;
  var c = 0;
  var str = '';
  while (r >= 0 && c < cols)
  {
    if (r < rows)
      str += array[r][c];
    r -= 1;
    c += 1;
  }
  document.write(str+"<br>");
}

结果:

A
EB
IFC
JGD
KH
L

答案 2 :(得分:3)

又一个解决方案:

function getAllDiagonal(array) {
    function row(offset) {
        var i = array.length, a = '';
        while (i--) {
            a += array[i][j + (offset ? offset - i : i)] || '';
        }
        return a;
    }

    var result = [[], []], j;
    for (j = 1 - array.length; j < array[0].length; j++) {
        result[0].push(row(0));
        result[1].push(row(array.length - 1));
    }
    return result;
}

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

document.write('<pre>' + JSON.stringify(getAllDiagonal(array), 0, 4) + '</pre>');

答案 3 :(得分:2)

试试这个

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 4 :(得分:1)

使用指数:

[i][j-i]

我从0到M-1

j从0到i

虽然j ++&lt; Ñ

表示矩阵

type Array [M] [N]

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

答案 5 :(得分:1)

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

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语法。

答案 6 :(得分:1)

这甚至适用于矩形矩阵:

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));

答案 7 :(得分:1)

注意:这假定所有字符串的大小相同,或者至少与第一个字符串一样大。

在2D数组中(或者在这种情况下,是一个字符串数组),对角线的索引加起来对角线的数字(就像一个行号)。 00,01,10,02 11 20等

使用此方法,对角线&#34;行数#34; (从零开始)等于最大索引的总和,或者(columnlength + rowlength-2)的总和。

因此,我的解决方案是遍历对角行数并打印所有索引对,其总和等于当前对角行。

error: reinterpret_cast from type 'const char*' to type 'zidrecord2_t* {aka zidrecord2*}' casts away qualifiers
     amostra = reinterpret_cast<zidrecord2_t*>(recordData);

JSFiddle Link

答案 8 :(得分:1)

两种对角线的完整解决方案:

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);