Give me a Diamond ( 6 kyu )

문제

You need to return a string that displays a diamond shape on the screen using asterisk (“*”) characters. Please see provided test cases for exact output format.

The shape that will be returned from print method resembles a diamond, where the number provided as input represents the number of ’s printed on the middle line. The line above and below will be centered and will have 2 less ’s than the middle line. This reduction by 2 ’s for each line continues until a line with a single is printed at the top and bottom of the figure.

Return null if input is even number or negative (as it is not possible to print diamond with even number or negative number).

Please see provided test case(s) for examples.

다이아몬드 별찍기, n이 0이하거나 짝수면 null을 리턴

풀이

function diamond(n){
  if ( n < 1 || n%2 === 0 ) return null
  let result = '', mid = Math.ceil(n/2);
  for ( let i = 1; i <= n; i++ ) {
    if ( i <= mid ) {
      result += ' '.repeat(mid-i) + '*'.repeat(2*i-1) + '\n'
    } else {
      result += ' '.repeat(i-mid) + '*'.repeat(2*(n-i)+1) + '\n'
    }
  }
  return result;
}

mid를 기준점으로 잡고, repeat으로 별찍기 구성

어렵지는 않은데 2*(n-i)+1 생각해내는데 시간이 걸림 ㅋㅋ;

다른 사람의 풀이

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"; }

좋은풀이인지는 잘모르겠지만 신기하게 풀어서 가져옴


+ Recent posts