counterEffect.js (7kyu 91)

Codewars 알고리즘 풀이


Problem

  • You have decided to create a function that will produce a multi-dimensional array out of the hit count value.
    • hit count 값의 다차원 배열을 생성하는 함수를 작성한다.
  • Each inner dimension of the array represents an individual digit in the hit count, and will include all numbers that come before it, going back to 0.
    • 각 내부 차원은 hit count의 각 숫자를 나타낸다.
    • 그 앞에 오는 모든 숫자를 포함하고, 0으로 되돌아간다.
  • The function will take one argument which will be a four character string representing hit count.
    • hit count를 나타내는 네 글자의 문자열 인수를 사용한다.
  • The function must return a multi-dimensional array containing four inner arrays.
    • 네 개의 내부 배열을 포함하는 다차원 배열을 반환한다.
  • Values returned in the array must be of the type number.
    • 배열에 반환되는 값은 number 타입이어야 한다.


Solution

function counterEffect(str) {
  let result = [];
  
  for (let i = 0; i < str.length; i++) {
    let inner = [];
    
    for (let j = 0; j <= Number(str[i]); j++) {
      inner.push(j);
    }
    result.push(inner);
  }
  return result;
}

counterEffect('0000');  // [[0], [0], [0], [0]]
counterEffect('0040');  // [[0], [0], [0, 1, 2, 3, 4], [0]]
counterEffect('1234');  // [[0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]

push(): 배열의 끝에 새 element를 추가하고, 새로운 길이를 반환한다.