CodeWars符号化問題2021/01/22-シーケンス収束


[質問]


Consider the following series:1, 2, 4, 8, 16, 22, 26, 38, 62, 74, 102, 104, 108, 116, 122It 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, 122Notice 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に設定される.

    [回答]

    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);
    }
    まず、returnを作成し、0を除くすべての要素の積を求めます.makeNumは、base1を含み、testを第1の要素として含む.
    その後、nの最後の要素がtestになるまで、繰り返し文が回転する.
    最後はbaseの中の元素なので、baseを除いて残りの個数はpopです.