Skip to content

Instantly share code, notes, and snippets.

@bradbaris
Last active August 16, 2018 19:35
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 bradbaris/c100c4929b7eadc3bffa36c883c364a3 to your computer and use it in GitHub Desktop.
Save bradbaris/c100c4929b7eadc3bffa36c883c364a3 to your computer and use it in GitHub Desktop.
Spiral Array
function createSpiral(dimension) {
console.time();
// square array generator
const matrix = (dimension) => {
return new Array(dimension).fill(0).map((obj, idx) => {
return obj[idx] = new Array(dimension).fill(0);
});
}
let square = matrix(dimension);
let x,y;
// fill in top/bot edges with 1, concentrically
x = 0;
y = dimension;
while(x < y) {
square[x].fill(1,x,y);
square[y-1].fill(1,x,y);
// fill in left/right edges with 1, concentrically
for(let i = x; i < y; i++) {
square[i][x] = 1;
square[i][y-1] = 1;
}
x+=2;
y-=2;
}
// diagonal XOR that bitflips from top-left to center-center
x = 0;
y = 0;
// if a 2x2 square is possible, round the upper bound downward to prevent it
let wtf = (dimension % 4 == 0) ? Math.floor((dimension-1)/2) : Math.ceil((dimension-1)/2);
while(x < wtf) {
x++;
square[x][y] ^= 1;
y++;
continue;
}
console.timeEnd();
console.log(`\nGenerating spiral array of size ${dimension}`);
console.log(square);
console.log(`\n`);
}
/* IGNORE EVERYTHING BELOW THIS LINE */
const readline = require('readline');
let rl = readline.createInterface(process.stdin, process.stdout);
console.log("Spiral Array Generator. Enter a number, or enter 0 to quit.\n");
rl.prompt();
rl.on('line', (line) => {
if (/^\d+$/.test(line.trim())) {
switch(line.trim()) {
case '0':
rl.close();
break;
default:
createSpiral(Number(line.trim()));
break;
}
} else {
console.log("Bad input. Try again.");
}
}).on('close', () => {
console.log("Have a nice day!");
process.exit(0);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment