Last active
August 2, 2023 04:00
-
-
Save thekhairul/35df6e3411e46f2ba611447c174d7aa0 to your computer and use it in GitHub Desktop.
Make star diamond with js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// radius (largest row of stars) must be an odd number | |
function makeDiamondWithStars(radius) { // let's say radius is 9 | |
let starsOrder = []; // we list down the number of stars needed to put on each line | |
for (let i = 1; i <= radius; i+=2) { | |
starsOrder.push(i); | |
} | |
// after this loop starsOrder array is [1, 3, 5, 7, 9] | |
starsOrder = starsOrder.concat(starsOrder.slice(0,-1).reverse()); // now starsOrder is [1, 3, 5, 7, 9, 7, 5, 3, 1] | |
const midOfTarget = Math.floor(radius/2); // 4 | |
for (let j=0; j<starsOrder.length; j++) { | |
const space = Math.abs(midOfTarget - j); // space needed before putting stars in a line is absolute difference of midOfTarget and current line which is 'j' | |
const starsNumber = starsOrder[j]; // we get the stars needed in a line from starsOrder array | |
const line = ' '.repeat(space*2) + '* '.repeat(starsNumber); // formulate the line with neccessary space and stars | |
console.log(line + '\n'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment