Skip to content
Advertisement

how to generate spiral matrix in javascript?

I am trying to generate sprial matrix in javascript.

question Given an integer A, generate a square matrix filled with elements from 1 to A^2 in spiral order.

input : 3

 [   [ 1, 2, 3 ],
     [ 8, 9, 4 ],
     [ 7, 6, 5 ]   ]

when input is 4

 [   [1, 2, 3, 4],
     [12, 13, 14, 5],
     [11, 16, 15, 6],
     [10, 9, 8, 7]   ]

my approach is to create 2d array with 0 value and after that they will fill values.

let generateMatrix = function(A) {
  let arr = [], counter = 1;
  for (let i = 0; i < A; i++) {
    let items = []
    for (let j = 0; j < A; j++) {
      items.push(0)
    }
    arr.push(items)
  }

  var spiralMatrix = function(arr) {
    if (arr.length > 1) {
      for (let i = 0; i < arr[0].length; i++) {
        arr[0][i] = counter++;
      }
    }
    return arr
  }
  return spiralMatrix(arr)
}
console.log(generateMatrix(2))

Advertisement

Answer

You could take loops for each edges and loop until no more ranges are avaliable.

function spiral(length) {
    var upper = 0,
        lower = length - 1,
        left = 0,
        right = length - 1,
        i = 0,
        j = 0,
        result = Array.from({ length }, _ => []),
        value = 1;

    while (true) {
        if (upper++ > lower) break;

        for (; j < right; j++) result[i][j] = value++;
        if (right-- < left) break;

        for (; i < lower; i++) result[i][j] = value++;

        if (lower-- < upper) break;

        for (; j > left; j--) result[i][j] = value++;
        if (left++ > right) break;

        for (; i > upper; i--) result[i][j] = value++;
    }

    result[i][j] = value++;
    return result;
}

var target = document.getElementById('out'),
    i = 10;

while (--i) target.innerHTML += spiral(i).map(a => a.map(v => v.toString().padStart(2)).join(' ')).join('n') + 'nn';
<pre id="out"></pre>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement