Skip to content

Instantly share code, notes, and snippets.

@devNoiseConsulting
Created February 23, 2018 21:20
Show Gist options
  • Select an option

  • Save devNoiseConsulting/b9fbe56413c577d72fcffd1acc576cb5 to your computer and use it in GitHub Desktop.

Select an option

Save devNoiseConsulting/b9fbe56413c577d72fcffd1acc576cb5 to your computer and use it in GitHub Desktop.
Alphabet Spiral- PhillyDev Slack #daily_programmer - 20180222
let getSideSize = function(size) {
if (size < 1) {
return 0;
} else if (size == 1) {
return 2;
} else {
return size + getSideSize(size - 1);
}
};
let fillSpiral = function(level, startLetter, spiral) {
let side = getSideSize(level);
let length = (side - 1) * 4;
let i = startLetter;
let x = 0;
let y = 0;
let direction = [0, 1, 0, -1];
let dX = 0;
let dY = 1;
for (let i = 0; i < 4; i++) {
for (let j = 0; j < side; j++) {
if (spiral[x][y] == ' ') {
spiral[x][y] = String.fromCharCode(65 + startLetter++);
}
x += direction[dX];
y += direction[dY];
startLetter %= 26;
}
// Back up the last position move
x -= direction[dX];
y -= direction[dY];
dX = ++dX % 4;
dY = ++dY % 4;
}
return [startLetter, spiral];
};
let alphabetSpiral = function(size) {
let spiralLength = getSideSize(size);
let spiral = new Array(spiralLength)
.fill(0)
.map(v => new Array(spiralLength).fill(' '));
let startLetter = 0;
for (let i = 1; i <= size; i++) {
[startLetter, spiral] = fillSpiral(i, startLetter, spiral);
}
return spiral.map(v => v.join('')).join('\n');
};
let test = 3;
let result = alphabetSpiral(3);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment