Function to create diamond shape given a value

javascript html css

2691 просмотра

3 ответа

15 Репутация автора

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>');
}
Автор: Ame M Источник Размещён: 19.07.2016 03:30

Ответы (3)


1 плюс

4148 Репутация автора

Решение

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);

Автор: Arnauld Размещён: 19.07.2016 04:23

0 плюса

1 Репутация автора

for(i=1;i<=5;i++){
  txt = "";
  for(j=i;j<10;j++){
    txt += " ";
  }
  for(k=0;k<(i*2)-1;k++){
    txt += "*";
  }
  console.log(txt);
}
var txt = "";
for(i=5-1;i>=1;i--){
  txt = "";
  for(j=i;j<10;j++){
    txt += " ";
  }
  for(k=0;k<(i*2)-1;k++){
    txt += "*";
  }
  console.log(txt);
}
Автор: AnDy Размещён: 20.07.2018 11:09

0 плюса

3 Репутация автора

i did it this way.


var width = 11;  
var num = (width+1)/2;  
for (let i = num-1; i >-num; i--) {
    for (let j = num-Math.abs(i); j < num; j++) {
        stars+=' '
    }
    for (let j = 0; j < 2*(num-Math.abs(i))-1; j++) { //2*num-(2*Math.abs(i) +1) simplified to 2*(num-Math.abs(i))-1
        stars+="*";
    }
    stars+="\n";
}
console.log(stars);

Автор: Saifullah Rahman Размещён: 14.08.2019 03:54
32x32