[Coding Test]삼총사

이묘·2022년 12월 26일
0

CodingTest

목록 보기
38/41
post-thumbnail
function solution(number) {

  var answer = 0;

  // 중복 없는 서로 다른 사람 3명을 뽑는 것이므로 조합 이용
  const getCombinations = function (arr, selectNumber) {
    const results = [];
    if (selectNumber === 1) return arr.map((el) => [el]); 
    // n개중에서 1개 선택할 때(nC1), 바로 모든 배열의 원소 return

    arr.forEach((fixed, index, origin) => {
      const rest = origin.slice(index + 1); 
      // 해당하는 fixed를 제외한 나머지 뒤
      const combinations = getCombinations(rest, selectNumber - 1); 
      // 나머지에 대해서 조합을 구한다.
      const attached = combinations.map((el) => [fixed, ...el]); 
      //  돌아온 조합에 떼 놓은(fixed) 값 붙이기
      results.push(...attached); 
      // 배열 spread syntax 로 모두다 push
    });

    return results; // 결과 담긴 results return
}

  combinationResult = getCombinations(number, 3);
  // forEach문을 돌면서 3명의 번호 합이 0이면 answer에 1씩 더함
  combinationResult.forEach(array => { 
    if(array[0] + array[1] + array[2] === 0){
      answer++;
    }
  })

  return answer;
}
profile
본질을 공부해야 응용도 하지 않을까

0개의 댓글