简体   繁体   中英

Nested Array: How to use && operator properly to skip some loops?

I'm trying to get an "hourglass" array out from a nested array.

Say that this array is

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0

I have to get this "hourglass" array out and add it all up:

1 1 1
  1
1 1 1

Therefore, here's my attempt:

for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
        if ((i === 1 && j === 0) && (i === 1 && j === 2)) {
            continue;
        } else {
            newArr.push(arr[i][j]);
        }
    }
}

I noticed that if I use this condition: i === 1 && j === 0 , it was able to skip over the position at i = 1 and j = 0 but when I added j = 2 , I couldn't get it to skip over the first and third positions. Therefore, I was trying out various options to get it to work but I couldn't get it to work. Such, I was wondering if I'm doing the && operator correctly?

You could add spaces for the zeros (0) and for the ones (1) or maybe any other number just accumulate them;

 const arr = [ [1, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0], ] let printRow = ''; for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[i].length; j++) { if (arr[i][j] === 0) { printRow += ' '; } else { printRow += arr[i][j]; } } console.log(printRow); printRow = ''; }

Solution

To find every hourglass in this grid 3 rows 6 columns grid with only one loop
Notice : When the Grid becomes larger you have to use an inner for loop

 const arr = [ [1, 1, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0], ] // format is [row][column] let result; let topp; let mid; let bottom; for (let i = 0; i < 4; i++) { // this ist the filter defining what we are looking for if (arr[0][i] === 1 && arr[0][i+1] === 1 && arr[0][i + 2] === 1 && arr[1][i] === 0 && arr[1][i+1] === 1 && arr[1][i + 2] === 0 && arr[2][i] === 1 && arr[2][i+1] === 1 && arr[2][i + 2] === 1) { // here we build the string topp = arr[0][i] + " " + arr[0][i+1] + " " + arr[0][i+2]; mid = arr[1][i] + " " + arr[1][i+1] + " " + arr[1][i+2]; bottom = arr[2][i] + " " + arr[2][i+1] + " " + arr[2][i + 2]; result = topp + "\n" + mid + "\n" + bottom; } } console.log(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM