Algorithm/codewars

Sum by Factors 답안

Bonita SY 2021. 3. 30. 19:09
728x90
반응형

문제) 

www.codewars.com/kata/54d496788776e49e6b00052f/train/javascript

 

Codewars: Achieve mastery through challenge

Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.

www.codewars.com

 

내가 푼 답)

function sumOfDivided(lst) {
  const factors = [];
  
  for (let l of lst) {
    let tmp_value = l < 0 ? l * -1 : l;
    const tmp_l = tmp_value;
    for (let i=2; i<=tmp_l; i++) {
      if (tmp_value === 0) {
        break;
      }
      
      tmp_value = getRemainder(tmp_value, i, factors);
    }
  }
    
  const result = [];
  for (let factor of factors) {
    let cnt = 0;
    for (let l of lst) {
      let minusFlag = false;
      let tmpL = l;
      if (l < 0) {
        minusFlag = true;
        tmpL *= -1;
      }
      if (tmpL % factor === 0) {
        if (minusFlag) {
          cnt -= (tmpL/factor)
        } else {
          cnt += (tmpL/factor)
        }
      }
    }
    result.push([factor, factor*cnt]);
  }
  
  return result.sort((a, b) => a[0] - b[0]);
}

function getRemainder(num, n, factors) {
  if (num < n || (num % n !== 0)) {
    return num;
  }
  
  if (!factors.includes(n)) {
    factors.push(n);
  }
  
  return getRemainder(num/n, n, factors);
}
 

 

테스트 결과)

 

마음에 드는 다른 사람이 푼 소스)

728x90
반응형

'Algorithm > codewars' 카테고리의 다른 글

Adding Big Numbers 답안  (0) 2021.03.30
Directions Reduction 답안  (0) 2021.03.30
Number of trailing zeros of N! 답안  (0) 2021.03.29
Permutations 답안  (0) 2021.03.29
Recover a secret string from random triplets 답안  (0) 2021.03.29