taesik

diamond with * 본문

functions and trick/typescript_javascript

diamond with *

taesikk 2022. 1. 24. 21:05

my solution:

function diamond(n){
  if(n ===1) return '*\n';
  if(n <1) return null;
  if(n %2 ===0) return null;
  
  let arr =[];
  let count =1;
  arr.push(`${'*'.repeat(n)}\n`);
    while(n>2) {
      arr.unshift(`${' '.repeat(count)}${'*'.repeat(n-2)}\n`);
      arr.push(`${' '.repeat(count)}${'*'.repeat(n-2)}\n`);
      n=n-2;
      count=count+1;
    }
  return arr.join(',');

 

 

function diamond (n) {
  if (n <= 0 || n % 2 === 0) return null
  str = ''
  for (let i = 0; i < n; i++) { 
    let len = Math.abs((n-2*i-1)/2)
    str += ' '.repeat(len)
    str += '*'.repeat(n-2*len)
    str += '\n'
  }
  return str
}

 

function diamond(n){
  if( n%2==0 || n<1 ) return null
  var x=0, add, diam = line(x,n);
  while( (x+=2) < n ){
    add = line(x/2,n-x);
    diam = add+diam+add;
  }
  return diam;
}//z.

function repeat(str,x){return Array(x+1).join(str); }
function line(spaces,stars){ return repeat(" ",spaces)+repeat("*",stars)+"\n"; }