Skip to content

Instantly share code, notes, and snippets.

@leodr
Created June 21, 2021 08:32
Show Gist options
  • Save leodr/be85479525931cafe327a4094f8cb83a to your computer and use it in GitHub Desktop.
Save leodr/be85479525931cafe327a4094f8cb83a to your computer and use it in GitHub Desktop.
Print an ASCII-Art-cube for a given height
function printCube(height) {
const width = height * 2;
const depth = Math.ceil(height / 2);
const canvas = [];
const canvasWidth = width + 2 + depth + 1;
const canvasHeight = height + 2 + depth + 1;
for (let i = 0; i < canvasHeight; i++) {
canvas[i] = Array(canvasWidth).fill(" ");
}
canvas[canvasHeight - 1][1 + width] =
canvas[canvasHeight - 2 - height][1 + width] =
canvas[canvasHeight - 1][0] =
canvas[canvasHeight - 2 - height][0] =
canvas[0][canvasWidth - width - 2] =
canvas[0][canvasWidth - 1] =
canvas[height + 1][canvasWidth - 1] =
"+";
for (let i = 0; i < width; i++) {
canvas[canvasHeight - height - 2][1 + i] =
canvas[canvasHeight - 1][1 + i] =
canvas[0][canvasWidth - 2 - i] =
"-";
}
for (let i = 0; i < height; i++) {
canvas[canvasHeight - height - 1 + i][0] =
canvas[canvasHeight - height - 1 + i][width + 1] =
canvas[i + 1][canvasWidth - 1] =
"|";
}
for (let i = 0; i < depth; i++) {
canvas[1 + i][canvasWidth - width - 3 - i] =
canvas[1 + i][canvasWidth - 2 - i] =
canvas[canvasHeight - 2 - i][canvasWidth - depth - 1 + i] =
"/";
}
console.log("");
for (const row of canvas) {
console.log(` ${row.join("")} `);
}
console.log("");
}
printCube(5);
+----------+
/ /|
/ / |
/ / |
+----------+ |
| | |
| | +
| | /
| | /
| |/
+----------+
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment