본문 바로가기
👩‍💻 Programming/Coding Test 문제 풀이

[Programmers] level 1: 소수 만들기 by JavaScript

by codingBear 2022. 7. 2.
728x90
반응형

 이번 글은 아래 링크의 글들을 참조하여 작성하였습니다.

 

JavaScript로 순열과 조합 알고리즘 구현하기

1. 조합 서로 다른 n개의 물건에서 순서를 생각하지 않고 r개를 택할 때, 이것은 n개에서 r개를 택하는 조합이라 하고, 이 조합의 수를 기호로 nCr와 같이 나타낸다. 바로 예를 살펴보도록 하자. 4Com

velog.io

 

[Javascript] '소수 찾기' 문제풀이

예제 원본 링크는 아래에 있습니다. (출처 : 프로그래머스) programmers.co.kr/learn/courses/30/lessons/12921 코딩테스트 연습 - 소수 찾기 1부터 입력받은 숫자 n 사이에 있는 소수의 개수를 반환하는 함수, so

bibi6666667.tistory.com


 이번 문제에 대한 자세한 사항은 다음 링크를 참조하길 바란다.

 

 주어진 배열의 요소를 3개씩 조합해서 다 더한 다음 소수가 되는 수의 개수를 반환하면 되는 문제이다. 따라서 3가지 수를 조합할 수 있는 경우의 수와 소수인지 판별하는 알고리즘이 필요하다. 두 개 다 작성할 줄 몰라서 다른 사람들의 코드를 참고하여 문제를 풀어보았다.

 

Solutions

Solution 1.
const input = [1, 2, 3, 4];
// const input = [1,2,7,6,4]

console.log(solution(input));

function solution(nums) {
  const result = getCombinations(nums, 3);
  const combinations = [...result];
  const answer = [];

  for (let i = 0; i < combinations.length; i++) {
    let sum = 0;

    for (let j = 0; j < combinations[i].length; j++) {
      sum += combinations[i][j];
    }

    let remain = 0;
    for (let j = 1; j <= sum; j++) {
      if (sum % j === 0) {
        remain++;
      }
    }
    if (remain === 2) answer.push(sum);
  }
  return answer.length;
}

function getCombinations(arr, selectNumber) {
  const results = [];
  if (selectNumber === 1) return arr.map((value) => [value]);
  // 1개씩 택할 때, 바로 모든 배열의 원소 return

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

  return results; // 결과 담긴 results return
}
728x90
반응형

댓글