-
-
Save cwayfinder/06a58715c4bbb0abac6548b1ff761497 to your computer and use it in GitHub Desktop.
Solution for https://www.hackerrank.com/contests/coding-test-1-bits-hyderabad/challenges/spiral-matrix-1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function processData(input) { | |
const [size, ...matrixAsLine] = input.trim().split(/[\s]+/); | |
// prepare matrix as 2-dimensional array | |
const matrix = []; | |
for(let rowIndex = 0; rowIndex < size; rowIndex++) { | |
const start = size * rowIndex; | |
const end = start + size; | |
matrix.push(matrixAsLine.slice(start, end)); | |
} | |
// perform size/2 iterations to collect spiral | |
let spiral = []; | |
for(let circleIndex = 0; circleIndex < size/2; circleIndex++) { | |
const firstRowIndex = firstColIndex = circleIndex; | |
const lastRowIndex = lastColIndex = size - circleIndex - 1; | |
const firstRow = matrix[firstRowIndex].slice(firstColIndex, lastColIndex + 1); | |
const lastRow = firstRowIndex != lastRowIndex | |
? matrix[lastRowIndex].slice(firstColIndex, lastColIndex + 1) | |
: []; | |
const firstCol = []; | |
const lastCol = []; | |
for(let rowIndex = firstRowIndex + 1; rowIndex < lastRowIndex; rowIndex++) { | |
const row = matrix[rowIndex]; | |
firstCol.push(row[firstColIndex]); | |
lastCol.push(row[lastColIndex]); | |
} | |
const circle = [...firstRow, ...lastCol, ...lastRow.reverse(), ...firstCol.reverse()]; | |
spiral = spiral.concat(circle); | |
} | |
console.log(spiral.join(' ')); | |
} | |
process.stdin.resume(); | |
process.stdin.setEncoding("ascii"); | |
_input = ""; | |
process.stdin.on("data", function (input) { | |
_input += input; | |
}); | |
process.stdin.on("end", function () { | |
processData(_input); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment