Search code examples
javascriptarraysloopsmultidimensional-arraynested-loops

Javascript - How to generate a "staggered" grid of numbers


I'm not really sure how to title this one, so if someone knows better, be my guest.

Basically, using nested for-loops, I'm trying to generate a 2-d array where each row starts at one number higher than the previous row, and then loops around on itself, so that the total of each row remains equal. Let me rather just show you what I mean:

[
  [1, 2, 3], // 1 + 2 + 3 = 6
  [2, 3, 1], // 2 + 3 + 1 = 6
  [3, 1, 2], // 3 + 1 + 2 = 6
]

See how every row is just 1, 2, 3 but every following row starts at i + 1 and when it reaches 3 it "resets" back to 1? That's what I'm trying to achieve.

Here's what I have so far:

const grid = []
const gridSize = 3

for(let i = 0; i < gridSize; i++) {
  const row = []

  for(let j = 0; j < gridSize; j++) {
    row.push(/* what goes here?? this is where I get stuck */)
  }

  grid.push(row)
}

Solution

  • You can add the row and column index together and mod by the size. If you want the values to start at 1 (offset), just add 1 to the result of each cell when mapping.

    const generateMatrix = (size, offset = 1) =>
      Array.from({ length: size }, (_, rowIndex) =>
        Array.from({ length: size }, (__, colIndex) =>
          ((rowIndex + colIndex) % size) + offset));
    
    const formatMatrix = (matrix) => matrix.map(row => row.join(' ')).join('\n');
    
    console.log(formatMatrix(generateMatrix(2)));
    console.log(formatMatrix(generateMatrix(3)));
    console.log(formatMatrix(generateMatrix(4)));
    .as-console-wrapper { top: 0; max-height: 100% !important; }

    Here is a version with traditional for-loops:

    const generateMatrix = (size, offset = 1) => {
      const matrix = [];
      for (let rowIndex = 0; rowIndex < size; rowIndex++) {
        const row = [];
        for (let colIndex = 0; colIndex < size; colIndex++) {
          row.push(((rowIndex + colIndex) % size) + offset);
        }
        matrix.push(row);
      }
      return matrix;
    };
    
    const formatMatrix = (matrix) => matrix.map(row => row.join(' ')).join('\n');
    
    console.log(formatMatrix(generateMatrix(2)));
    console.log(formatMatrix(generateMatrix(3)));
    console.log(formatMatrix(generateMatrix(4)));
    .as-console-wrapper { top: 0; max-height: 100% !important; }