JSFiddle - React, Tailwind, and code Playground
JavaScript
var xIncrement = 0;
var yIncrement = 0;
var xCount = 0;
var yCount = 0;
var curValue = 1;
var size = 17;
var array = [];
for(var i = 0; i < size; ++i){
array.push([]);
for(var j = 0; j < size; ++j){
array[i].push(0);
}
}
for(var i = Math.floor(size / 2); i < size;) {
for(var j = Math.floor(size / 2); j < size;) {
if(xIncrement == 0 && yIncrement == 0){
array[i][j] = curValue++;
xIncrement = -1;
xCount = -1;
j += xIncrement;
}
else{
array[i][j] = curValue++;
xCount += xIncrement;
yCount += yIncrement;
if(curValue > size * size) break;
if((Math.abs(xCount) >= Math.ceil(Math.sqrt(curValue)) && xIncrement != 0) || (Math.abs(yCount) >= Math.ceil(Math.sqrt(curValue)) && yIncrement != 0)){
if(xIncrement == -1) { xCount = 0; yCount = 1; xIncrement = 0; yIncrement = 1; }
else if(xIncrement == 1) { xCount = 0; yCount = -1; xIncrement = 0; yIncrement = -1; }
else if(yIncrement == -1) { xCount = -1; yCount = 0; xIncrement = -1; yIncrement = 0; }
else if(yIncrement == 1) { xCount = 1; yCount = 0; xIncrement = 1; yIncrement = 0; }
}
j += xIncrement;
i -= yIncrement;
}
}
if(curValue > size * size) break;
}
function createTable(tableData) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.body.appendChild(table);
}
createTable(array)