如何在javascript中对角遍历数组

时间:2021-10-15 18:06:15

I have an array with strings that I would like to traverse diagonally.
Assumptions:

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

  • Each string is the same length.
  • 每根弦的长度都是一样的。
  • Arrays could be square or rectangular, horizontally or vertically.
  • 数组可以是正方形或矩形,水平或垂直。

The matrix looks like this:

矩阵是这样的:

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

I Would like to get (from top left to bottom right):

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

A
EB
IFC
JGD
KH
L

and (from the bottom left to top right):

(从左下至右上):

I
JE
KFA
LGB
HC
D

I already have a piece of code that works 3/4 of the way, but i cant seem to figure out what I am doing (wrong).

我已经有了一段3/4的代码,但是我似乎不知道我在做什么(错了)。

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

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

The code I have chops up the diagonals into 4 of these loops to get all the diagonals. It looks as 2 for loops with an if to not loop over unbound values. The pseudo code looks a bit like this:

为了得到所有的对角线,我把对角线分割成4个循环。它看起来像2个for循环,带有if - to循环未绑定的值。伪代码看起来有点像这样:

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 hope somebody can help me with this.

我希望有人能帮助我。

9 个解决方案

#1


16  

From top left to bottom right

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

(see also this Fiddle)

(参见本小提琴)


From the bottom left to top right

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

(see also this Fiddle)

(参见本小提琴)


Combined

As there's but a single line of difference between both, you can easily combine them in a single function :

由于两者之间只有一行的区别,你可以很容易地将它们合并到一个函数中:

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

(see also this Fiddle)

(参见本小提琴)

#2


5  

This does the trick, and outputs the desired results to the screen:

这样就可以达到目的,并将期望的结果输出到屏幕上:

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

Result:

结果:

A
EB
IFC
JGD
KH
L

#3


3  

Yet another solution:

另一个解决方案:

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

#4


2  

Try this

试试这个

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

#5


1  

Use indices:

使用指数:

[i][j-i]

Where i goes from 0 to M-1

从0到M-1

j goes from 0 to i

j从0到i

While j++ < N

虽然j + + < N

for the matrix

的矩阵

type Array[M][N]

数组类型[M][N]

However this may miss a few at the bottom right if the matrix is rectangular, and you might need a second nested for loop with i and j to capture those.

但是,如果矩阵是矩形的,这可能会在右下角漏掉一些,您可能需要第二个嵌套for循环,其中包含i和j。

#6


1  

This should work even for rectangular matrices:

这甚至适用于矩形矩阵:

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  

Note: This assumes that all strings are the same size, or at least are as large as the first string.

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

In a 2D array (or in this case, an array of strings), a diagonal's indexes add up to the diagonal's number (like a row-number). 00, 01 10, 02 11 20, etc.

在二维数组(在本例中是字符串数组)中,对角线的索引加起来等于对角线的数字(如行号)。00, 01 10, 02 11 20,等等。

Using this method, the number of diagonal "rows" (starting at zero) is equal to the sum of the largest indexes, or the sum of (columnlength+rowlength-2).

使用这种方法,对角线“行”的数目(从0开始)等于最大索引的和,或(列长+行长-2)的和。

Therefore, my solution is to iterate through the diagonal row numbers and print all index pairs whose sum is equal to the current diagonal row.

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

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

var text = ''
for (i = 0; i <= (RowLength+ColumnLength-2); i++){
    for (x = 0; x<=i; x++){
    if (TheArray[i-x] && TheArray[i-x][x]){
        text += TheArray[i-x][x];
    }
  }
  text += "<br/>";
}

document.getElementById('text').innerHTML = text;

JSFiddle Link

JSFiddle链接

#8


1  

Here is my try for 'from top left to bottom right':

下面是我的“从左到右”的尝试:

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

Needs a few adaptations to fit JavaScript syntax.

需要一些适应来适应JavaScript语法。

#9


1  

Full solution for both diagonals:

两个对角线的完全解:

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

#1


16  

From top left to bottom right

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

(see also this Fiddle)

(参见本小提琴)


From the bottom left to top right

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

(see also this Fiddle)

(参见本小提琴)


Combined

As there's but a single line of difference between both, you can easily combine them in a single function :

由于两者之间只有一行的区别,你可以很容易地将它们合并到一个函数中:

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

(see also this Fiddle)

(参见本小提琴)

#2


5  

This does the trick, and outputs the desired results to the screen:

这样就可以达到目的,并将期望的结果输出到屏幕上:

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

Result:

结果:

A
EB
IFC
JGD
KH
L

#3


3  

Yet another solution:

另一个解决方案:

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

#4


2  

Try this

试试这个

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

#5


1  

Use indices:

使用指数:

[i][j-i]

Where i goes from 0 to M-1

从0到M-1

j goes from 0 to i

j从0到i

While j++ < N

虽然j + + < N

for the matrix

的矩阵

type Array[M][N]

数组类型[M][N]

However this may miss a few at the bottom right if the matrix is rectangular, and you might need a second nested for loop with i and j to capture those.

但是,如果矩阵是矩形的,这可能会在右下角漏掉一些,您可能需要第二个嵌套for循环,其中包含i和j。

#6


1  

This should work even for rectangular matrices:

这甚至适用于矩形矩阵:

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  

Note: This assumes that all strings are the same size, or at least are as large as the first string.

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

In a 2D array (or in this case, an array of strings), a diagonal's indexes add up to the diagonal's number (like a row-number). 00, 01 10, 02 11 20, etc.

在二维数组(在本例中是字符串数组)中,对角线的索引加起来等于对角线的数字(如行号)。00, 01 10, 02 11 20,等等。

Using this method, the number of diagonal "rows" (starting at zero) is equal to the sum of the largest indexes, or the sum of (columnlength+rowlength-2).

使用这种方法,对角线“行”的数目(从0开始)等于最大索引的和,或(列长+行长-2)的和。

Therefore, my solution is to iterate through the diagonal row numbers and print all index pairs whose sum is equal to the current diagonal row.

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

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

var text = ''
for (i = 0; i <= (RowLength+ColumnLength-2); i++){
    for (x = 0; x<=i; x++){
    if (TheArray[i-x] && TheArray[i-x][x]){
        text += TheArray[i-x][x];
    }
  }
  text += "<br/>";
}

document.getElementById('text').innerHTML = text;

JSFiddle Link

JSFiddle链接

#8


1  

Here is my try for 'from top left to bottom right':

下面是我的“从左到右”的尝试:

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

Needs a few adaptations to fit JavaScript syntax.

需要一些适应来适应JavaScript语法。

#9


1  

Full solution for both diagonals:

两个对角线的完全解:

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