Ame M Ame M - 4 months ago 7
HTML Question

Function to create diamond shape given a value

I'm having trouble trying to create a diamond shape without manipulating html css or centering(It will be smart enough to add spaces). Been spending few hours trying out but still no success. Is this an impossible task without manipulating html or css? Any help would appreciated. Thanks.

The current state

Below are the functions for code:

function slope(val){

document.write('function slope('+val+')<br>');
doubleit = val*2;

for(i=0; i<doubleit; i++){
if (i < val){
for(j=0; j<i; j++){
document.write('*');
}
}
if (i >= val){
for(j=doubleit; j>i; j--){
document.write('*');
}
}

document.write('<br>');
}
}

function diamond(val){

doubleit = val*2;
document.write('<center>');
document.write('function diamond('+val+')<br>');
for(i=0; i<doubleit; i++){
if (i < val){
for(j=0; j<i; j++){
document.write('*');
}
}
if (i >= val){
for(j=doubleit; j>i; j--){
document.write('*');
}
}

document.write('<br>');
}

document.write('</center>');
}

Answer

If you want to get rid of the <center> tag, you'll have to:

  • use a fixed-width font
  • do the correct left justification
  • insert spaces between the '*' characters

Example:

  *
 * *
* * *
 * *
  *

You can think of it as the ASCII version of the Nine-Ball starting position.

Let's give it a try:

function diamond(val){
  var y, w, shape = '';

  for(y = 0; y < val * 2 - 1; y++) {
    w = y < val ? y : val * 2 - y - 2;
    shape += Array(val - w).join(' ') + Array(w + 1).join('* ') + '*\n';
  }
  document.write('<pre>' + shape + '</pre>');
}

diamond(7);