CodeWars 코딩 문제 2021/01/22 - Sequence convergence

이호현·2021년 1월 22일
0

Algorithm

목록 보기
61/138

[문제]

Consider the following series:

1, 2, 4, 8, 16, 22, 26, 38, 62, 74, 102, 104, 108, 116, 122

It is generated as follows:

  • For single digit integers, add the number to itself to get the next element.
  • For other integers, multiply all the non-zero digits and add the result to the original number to get the next element.

For example: 16 + (6 * 1) = 22 and 104 + (4 * 1) = 108.

Let's begin the same series with a seed value of 3 instead of 1:

3, 6, 12, 14, 18, 26, 38, 62, 74, 102, 104, 108, 116, 122

Notice that the two sequences converge at 26 and are identical therefter. We will call the series seeded by a value of 1 the "base series" and the other series the "test series".

You will be given a seed value for the test series and your task will be to return the number of integers that have to be generated in the test series before it converges to the base series. In the case above:

convergence(3) = 5, the length of [3, 6, 12, 14, 18].

(요약) 현재 요소에서 0을 제외한 숫자들의 곱을 더한것을 다음 요소로 하는 배열이 있다.
1부터 시작하는 배열을 base, 그 외의 숫자로 시작하는 배열을 test라 한다.
이 때 test의 배열 요소 중 base에 있을때까지 배열 길이를 return.

[풀이]

function convergence(n){
  const base = [1];
  const test = [n];

  while(!base.includes(test[test.length - 1])) {
    const baseLen = base.length;
    const testLen = test.length;

    base[baseLen - 1] > test[testLen - 1] 
      ? test.push(makeNum(test[testLen - 1], testLen - 1))
      : base.push(makeNum(base[baseLen - 1], baseLen - 1))
  }

  test.pop();
  return test.length;
}

function makeNum(num, index) {
  return num + `${num}`.split('').filter(str => str * 1).reduce((acc, str) => acc *= str, 1);
}

우선 0을 제외한 각 요소들의 곱을 구하는 함수 makeNum을 만들고,
base에는 1, test에는 n 첫 번째 요소로 넣음.
그리고 test의 마지막 요소가 base에 있을때까지 반복문을 돌림.
마지막에는 base에 있는 요소이므로 pop으로 빼내고 나머지 개수를 return.

profile
평생 개발자로 살고싶습니다

0개의 댓글