Last active
August 16, 2018 19:35
-
-
Save bradbaris/c100c4929b7eadc3bffa36c883c364a3 to your computer and use it in GitHub Desktop.
Spiral Array
This file contains hidden or 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 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