JSFiddle - React, Tailwind, and code Playground
by Denys Biliaiev
JavaScript
"use strict"
class Matrix {
constructor(n) {
this.matrix = [];
this.n = n;
var num = 1;
for (var i = 0; i < n; i++){
this.matrix[i] = [];
for (var j = 0; j < n; j++, num++){
this.matrix[i][j] = num;
}
}
if (this._isPrimeNumber()) {
this.y = Math.floor(n / 2);
} else {
this.y = Math.floor(n / 2 - 1);
}
this.centerLine = this.matrix[this.y];
this.x = Math.floor(this.centerLine.length / 2);
this.countSteps = {
left: 1,
right: 2,
top: 2,
down: 1,
}
}
read() {
var result = [];
result.push(this.centerLine[this.x]);
while (true) {
//left
for (step = 1; step <= this.countSteps.left; step++) {
this.x--;
if (!this.matrix[this.y][this.x]) break;
result.push(this.matrix[this.y][this.x]);
}
this.countSteps.left += 2;
if (!this.matrix[this.y][this.x]) break;
//down
for (var step = 1; step <= this.countSteps.down; step++) {
this.y++;
if (!this.matrix[this.y][this.x]) break;
result.push(this.matrix[this.y][this.x]);
}
this.countSteps.down += 2;
if (!this.matrix[this.y][this.x]) break;
//right
for (var step = 1; step <= this.countSteps.right; step++) {
this.x++;
if (!this.matrix[this.y][this.x]) break;
result.push(this.matrix[this.y][this.x]);
}
this.countSteps.right += 2;
if (!this.matrix[this.y][this.x]) break;
//top
for (var step = 1; step <= this.countSteps.top; step++) {
this.y--;
if (!this.matrix[this.y][this.x]) break;
...