Skip to content

Instantly share code, notes, and snippets.

@cwayfinder
Last active January 8, 2017 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwayfinder/06a58715c4bbb0abac6548b1ff761497 to your computer and use it in GitHub Desktop.
Save cwayfinder/06a58715c4bbb0abac6548b1ff761497 to your computer and use it in GitHub Desktop.
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