I'm in need of assistance in writing a function that can generate a hexagon pattern within a 2D array. I only have the column size of the array, and the rest of the dimensions must be calculated.
https://i.sstatic.net/WHuYF.png
Unfortunately, I'm facing difficulties with the mathematical aspects required for this task.
This is the code I've managed to come up with so far:
function deg2rad(degrees) {
const pi = Math.PI;
return degrees * (pi / 180);
}
function getCos(deg) {
return Math.cos(deg2rad(deg));
}
function drawHexagon(cols) {
// upper left corner
const rows = parseInt(cols * getCos(30), 10);
const arr = [...Array(rows)].map(() => Array(cols).fill(''));
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
if (j > Math.floor(cols / 4) - 1 && j < (cols - Math.round(10 / 4))) { // middle section (square)
arr[i][j] = 1;
continue;
}
if (i < Math.floor(rows / 2)) { // top half
if (j < Math.floor(cols / 4)) { // left side (triangle)
if (rows / 2 / (i + 1) < cols / 4 / (cols / 4 - j)) { // seems to be right
arr[i][j] = 2;
}
} else { // right side (triangle)
if (rows / (i + 1) < cols / (j / 4 + 1)) { // wrong
arr[i][j] = 2;
}
}
} else { // bottom half
if (j < Math.floor(cols / 4)) { // Left side
if (rows / (i + 1) > cols / 4 / (j + 1)) { // seems to be right
arr[i][j] = 2;
}
} else { // bottom right
if (rows / 2 / (i + 1) > cols / 4 / (cols - j)) { // wrong
arr[i][j] = 2;
}
}
}
}
}
console.log(arr); // console.table() not available in snippet
return arr;
}
drawHexagon(8)
Upon outputting the array, the result appears as depicted here:
https://i.sstatic.net/GcQKT.jpg
It seems like the left side and middle section are correct.
I would greatly appreciate any help in solving this matter.