I have written a simple javascript code to print pyramid of stars using for loop. Is it possible to write the code in a simplified manner using map function? Please suggest.
// Program to build a `Pyramid of stars` of given height const buildPyramid = (height) => { // Code to display stars in pyramid format let initialStapce = height; let starCount = 1; let result = ''; for (let line = 1; line <= height; line = line + 1) { for (let leftStace = 0; leftStace < initialStapce; leftStace = leftStace + 1) { result = result + ' '; } for (let starNumber = 0; starNumber < starCount; starNumber = starNumber + 1) { result = result + '* '; } result = result + ' \\n'; initialStapce = initialStapce - 1; starCount = starCount + 1; } return result; };
You can use map
, yes, but I think string repeat
based on the index is the bigger challenge. As you map
, keep track of the index and pad your stars on the left and right accordingly:
function pyramid(h) { return Array(h).fill('*') .map((s, i) => ' '.repeat(h - i - 1) + s.repeat(i + 1).split('').join(' ') + ' '.repeat(h - i - 1)) .join('\\n'); } console.log(pyramid(3)); console.log(pyramid(4)); console.log(pyramid(5));
There could be many solution for this problem. we can use for loop, while loop, even recursive function to solve this problem.
Solution with Recursive function:
This basically treat every row as a string runs the function until row === n
function pyramid(n, row=0, str=''){ if(row === n){ return; } if(str.length === (n * 2) - 1){ console.log(str); pyramid(n, row+1) return; } const midpoint = Math.floor(((n * 2) -1) / 2) let add; if(midpoint - row <= str.length && midpoint + row >= str.length){ add = '*' }else{ add = ' ' } pyramid(n, row, str + add) } pyramid(5)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.