Click here to Skip to main content
15,896,118 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been struggling to print a diamond shaped string with Javscript. I would like to know how I can insert spaces in the correct order. First, I was trying to print out a triangle and then I would turn it upside down and join them.
But I was stuck while trying to print the triangle.

What I have tried:

JavaScript
function diamond(arg) {
  if(arg === 1) {return "*"}
  var str = ""
  
   for(var j = arg; j > 1; j--) {
     str += Array(j).join(' ') + Array(j).join('*') + '\n'
    }
     
  
  return str
}
diamond(5) ->

    ****
   ***
  **
 *

But I would like it to print this

JavaScript
 **
****
Posted
Updated 13-Aug-16 8:16am
Comments
Mehdi Gholam 13-Aug-16 8:43am    
Try harder...
Richard MacCutchan 13-Aug-16 11:21am    
Draw the shape on a piece of paper. Now figure out how many spaces and stars are on each line, and how those numbers relate to each line number. Now you have the makings of your algorithm. So convert your algorithm to code and you should have what you want.

1 solution

Advice:
- Take a sheet of paper (with squares)
- Draw the shape you want
- Analyze line by line what you need to do (number of spaces and number of stars)
- Compare how the needs change from a line to the next.

If it can simplify for you, make a piece of code for top half and anothe one for bottom half.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900