JSFiddle - React, Tailwind, and code Playground
JavaScript
function rotateDirectionClockwise(direction) {
return (direction + 1) % 4;
}
function nextCoordinate(coordinate, direction) {
return {
row: coordinate.row + [0, 1, 0, -1][direction],
col: coordinate.col + [1, 0, -1, 0][direction]
};
}
function matrixFilledOfZeros(size) {
return Array.from(Array(size), () => Array.from(Array(size), () => 0));
}
class SpiralMatrix {
constructor(size) {
this.size = size;
this.matrix = matrixFilledOfZeros(size);
this.currentCoordinate = {
row: Math.floor(size / 2),
col: Math.floor(size / 2)
}
this.currentValue = 1;
}
fillNextPosition(direction) {
this.matrix[this.currentCoordinate.row][this.currentCoordinate.col] = this.currentValue++;
this.currentCoordinate =nextCoordinate(this.currentCoordinate, direction)
}
canContinueInSameDirection(direction) {
let newCoordinate = nextCoordinate(this.currentCoordinate, rotateDirectionClockwise(direction));
return this.matrix[newCoordinate.row][newCoordinate.col];
}
spiralNotCompleted() {
const square = this.size * this.size;
return this.currentValue <= square;
}
}
function paintSpiral(size, matrix) {
let line;
const maxWidth = (size * size).toString().length + 1;
for (let row = 0; row < size; row++) {
line = "";
for (let col = 0; col < size; col++)
line += matrix[row][col].toString().padStart(maxWidth, ' ')
console.log(line);
}
}
function getSpiralMatrix(size) {
let direction = 0;
const spiralMatrix = new SpiralMatrix(size);
while (spiralMatrix.spiralNotCompleted()) {
do {
spiralMatrix.fillNextPosition(direction);
} while (spiralMatrix.canContinueInSameDirection(direction));
direction = rotateDirectionClockwise(direction);
}
return spiralMatrix.matrix;
}
function isEvenNumber(size) {
return size % 2 ===...