CoDEVIANT #21 (10/11/20) — Spiral Motion

You spin me right round, baby, right round like algorithm, baby right right round… XD
[
[1, 2, 3, 4],
[12, 13, 14, 5],
[11, 16, 15, 6],
[10, 9, 8, 7]
]

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

function spiralTraverse(array) {
// Write your code here.
let results = []
let startCol = 0
let startRow = 0
//endRow signifies the start places of each row up and down the verticle side of the block
let endRow = array.length - 1
//endCol signifies the start places of each column across the top of the block
let endCol = array[0].length - 1

while(startCol <= endCol && startRow <= endRow) {
//top
for(let col = startCol; col <= endCol ; col++) {
results.push(array[startRow][col])
console.log('top', results)
}

//right
for(let row = startRow + 1; row <= endRow; row++) {
results.push(array[row][endCol])
console.log('right', results)
}

//bottom
for(let column = endCol - 1; column >= startCol; column --) {
if(startRow === endRow) break
results.push(array[endRow][column])
console.log('bottom', results)
}

//left
for(let row = endRow - 1; row > startRow; row --) {
if(startCol === endCol) break
results.push(array[row][startCol])
console.log(results)
}

startCol++
startRow++
endCol--
endRow--
}
return results
}
let results = []
let startCol = 0
let startRow = 0
//endRow signifies the start places of each row up and down the verticle side of the block
let endRow = array.length - 1
//endCol signifies the start places of each column across the top of the block
let endCol = array[0].length - 1
startColumn (sC) is 0 to start. startRow (sR) is 0 to start. endColumn (eC) is the length of the first array in the 2D array “1,2,3,4” minus one -3-. endRow (eR) is the length of the 2D array “1,12,11,10”. The value is 3 as well.
while(startCol <= endCol && startRow <= endRow) {
...
startCol++
startRow++
endCol--
endRow--
}
for(let col = startCol; col <= endCol; col++) {
results.push(array[startRow][col])
}
for(let row = startRow + 1; row <= endRow; row++) {
results.push(array[row][endCol])
}
for(let column = endCol - 1; column >= startCol; column --) {
if(startRow === endRow) break
results.push(array[endRow][column])
console.log('bottom', results)
}
for(let row = endRow - 1; row > startRow; row --) {
if(startCol === endCol) break
results.push(array[row][startCol])
console.log(results)
}
Just like Shrek, our 2D array has layers.
Mmmm…frosty

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store