[Solved] Matrix snake array [closed]


There are several ways to do this. But since the size of the array is always 6×7, you can actually create a kind of template array as an array literal, which starts with 0.

Then the rest is a piece of cake: just add the argument to all the values:

function snakeArray(start) {
    return [
        [ 0,  1,  2,  3,  4,  5,  6],
        [21, 22, 23, 24, 25, 26,  7],
        [20, 35, 36, 37, 38, 27,  8],
        [19, 34, 41, 40, 39, 28,  9],
        [18, 33, 32, 31, 30, 29, 10],
        [17, 16, 15, 14, 13, 12, 11]
    ].map(row => row.map(val => val + start));
}

let result = snakeArray(-10);
for (let row of result) console.log(...row);

So the [...] array literal creates the array as if the value to start with was 0. Then we iterate over the rows of that array with map, and then we iterate over each value in that row with a nested map. Then we add the start value to that value and return that. The inner map builds a new row with those new values, which is returned in the callback to the outer map. And that outer map returns the new rows as a new matrix, where every value will have been increased with start.

2

solved Matrix snake array [closed]