diamond.js

Codewars 알고리즘 풀이


Problem

  • You need to return a string that looks like a diamond shape when printed on the screen, using asterist(*) characters.
    • 별표(*)를 사용해서 다이아몬드 모양의 문자열을 반환한다.
  • Trailing spaces should be removed, and every line must be terminated with a newline character(\n).
    • 후행 공백(trailing spaces)을 제거하고, 개행 문자(\n)로 끝나야 한다.
  • Return ‘null’ if the input is an even number or negative, as it is not possible to print a diamond of even or negative size.
    • 입력(input)이 짝수 또는 음수인 경우 ‘null’을 반환한다.



Solution 01

function diamond(n) {
  if (n <= 0 || n % 2 === 0) return null;
  
  let mid = Math.ceil(n / 2);
  let result = '';
  
  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;
}

diamond(-1);  // null
diamond(0);   // null
diamond(1);   // '*\n'
diamond(2);   // null
diamond(3);   // ' *\n***\n *\n'
diamond(4);   // null
diamond(5);   // '  *\n ***\n*****\n ***\n *\n'


Solution 02

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

diamond(-1);  // null
diamond(0);   // null
diamond(1);   // '*\n'
diamond(2);   // null
diamond(3);   // ' *\n***\n *\n'
diamond(4);   // null
diamond(5);   // '  *\n ***\n*****\n ***\n *\n'