Unravelling the Matrix Array.

Recently I had a code challenge where I had to unroll a NxN matrix array. I’m going to go through my thought process in hopes of reinforcing my thinking or finding a more efficient solution.

Rules of the Challenge

// Sample Array (4 x 4 matrix)
// 1 2 3 4
// 12 13 14 5
// 11 16 15 6
// 10 9 8 7
matrix = [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]// expected output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

At first I asked, can i flatten the array and sort it? The answer was a no. Couldn’t hurt to ask lol.

Step 1

The way I saw it was, I need to get the top row. Then the right side. Followed by the bottom. Up the left. Repeat.

Step 2

function unrollMatrix(matrix){    // grab top row    // grab right column    // grab bottom row and reverse it    // grab left column and reverse it}

Step 3

I know the top row is the first index in the array. So I’ll move that row into a new array and mutate it at the same time.

function unrollMatrix(matrix){   let unrolled = []// grab top row   unrolled = [...unrolled, matrix.shift()]// grab right column// grab bottom row and reverse it// grab left column and reverse it}

Step 4

My thought was to iterate through each remaining set of arrays and grab the last item while also mutating it.

function unrollMatrix(matrix){    let unrolled = []// grab top row    unrolled = [...unrolled, matrix.shift()]// grab right column    unrolled = [...unrolled, matrix.map(row => row.pop())]// grab bottom row and reverse it// grab left column and reverse it}

Step 5

function unrollMatrix(matrix){    let unrolled = []// grab top row    unrolled = [...unrolled, matrix.shift()]// grab right column    unrolled = [...unrolled, matrix.map(row => row.pop())]// grab bottom row and reverse it
unrolled = [...unrolled, matrix.pop().reverse()]
// grab left column and reverse it}

Step 6

function unrollMatrix(matrix){    let unrolled = []// grab top row    unrolled = [...unrolled, matrix.shift()]// grab right column    unrolled = [...unrolled, matrix.map(row => row.pop())]// grab bottom row and reverse it    unrolled = [...unrolled, matrix.pop().reverse()]// grab left column and reverse it     unrolled = [...unrolled, matrix.map(row => row.shift()).reverse()]}

Step 7

function unrollMatrix(matrix){let unrolled = []while (matrix.length > 0) {// grab top row    unrolled = [...unrolled, matrix.shift()]// grab right column    unrolled = [...unrolled, matrix.map(row => row.pop())]// grab bottom row and reverse it    unrolled = [...unrolled, matrix.pop().reverse()]// grab left column and reverse it    unrolled = [...unrolled, matrix.map(row => row.shift()).reverse()]
}
return unrolled.flat()}

With the while loop, the function should be able to complete any size matrix the same way.

Fullstack Software Engineer