๋ฌธ์ ๋งํฌ
์ฝ๋ฉํ ์คํธ ์ฐ์ต - ์์ ๋ง๋ค๊ธฐ
์ฃผ์ด์ง ์ซ์ ์ค 3๊ฐ์ ์๋ฅผ ๋ํ์ ๋ ์์๊ฐ ๋๋ ๊ฒฝ์ฐ์ ๊ฐ์๋ฅผ ๊ตฌํ๋ ค๊ณ ํฉ๋๋ค. ์ซ์๋ค์ด ๋ค์ด์๋ ๋ฐฐ์ด nums๊ฐ ๋งค๊ฐ๋ณ์๋ก ์ฃผ์ด์ง ๋, nums์ ์๋ ์ซ์๋ค ์ค ์๋ก ๋ค๋ฅธ 3๊ฐ๋ฅผ ๊ณจ๋ผ ๋ํ์ ๋
programmers.co.kr
์ ๊ทผ๋ฐฉ๋ฒ
๋ฐฉ๋ฒ 1. nums ๋ฐฐ์ด์ 3๊ฐ์ ์์๋ง ์ ํํ๋ ์กฐํฉ์ ๊ตฌํด์ ๊ตฌํ ์กฐํฉ์ ํฉ์ ๋ฐฐ์ด๋ก ๋ง๋ค๊ธฐ
๋ฐฉ๋ฒ 2. ์์ ํ์์ ํตํด 3์ค for๋ฌธ์ผ๋ก 3๊ฐ๋ฅผ ๋ฝ๋ ๋ชจ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ๊ตฌํ๊ธฐ
๋ฐฉ๋ฒ 2๋ 3์ค for๋ฌธ์ ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ O(n^3)์ด๋ผ ์๊ฐ๋์ด
๋จผ์ ๋ฐฉ๋ฒ 1์ ์ ํํ์ฌ ๋ฌธ์ ๋ฅผ ํ์ดํ์๋ค.
ํ์ง๋ง ํจ์จ์ฑ์์ ๋ฐฉ๋ฒ 2์ ๋ฐฉ์์ด ํจ์ฌ ๋ ๋น ๋ฅธ ์๋๋ฅผ ๋ณด์๋ค.
์ฌ๊ทํจ์์ ๋ฐฐ์ด ๋ด์ฅํจ์๋ค์ ์๊ฐ๋ณต์ก๋์ ๋ํด ๋ค์ ํ์ตํด๋ด์ผ๊ฒ ๋ค.
function solution(nums) {
const sumArr = []
const combinations = getCombinations(nums, 3)
combinations.forEach(e => sumArr.push(e.reduce((a,b) => a+b)))
let count = sumArr.length;
sumArr.forEach(e => {
for(let i = 2; i <= Math.sqrt(e); i++){
if(e % i === 0){
count--;
break;
}
}
})
return count;
}
const getCombinations = function (arr, selectNumber) {
const results = [];
if (selectNumber === 1) return arr.map((el) => [el]);
arr.forEach((fixed, index, origin) => {
const rest = origin.slice(index + 1);
const combinations = getCombinations(rest, selectNumber - 1);
const attached = combinations.map((el) => [fixed, ...el]);
results.push(...attached);
});
return results
}
function solution(nums) {
let answer = 0;
const length = nums.length;
for (let i = 0; i < length; i++) {
for (let j = i + 1; j < length; j++) {
for (let k = j + 1; k < length; k++) {
const sum = nums[i] + nums[j] + nums[k];
if (isPrime(sum)) answer += 1;
}
}
}
return answer;
}
function isPrime(num) {
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return num >= 2;
}
'์ฝ๋ฉํ ์คํธ > ํ๋ก๊ทธ๋๋จธ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Javascript] ํ๊ฒ ๋๋ฒ (43165) (0) | 2022.06.11 |
---|---|
[Javascript] ๊ฐ์ฅ ํฐ ์ (42726) (0) | 2022.06.11 |
[Javascript] 2016๋ (12901) (0) | 2022.06.06 |
[Javascript] ์์ ์ต๋ํ (67257) (0) | 2022.06.03 |
[Javscript] [1์ฐจ] ๋น๋ฐ์ง๋ (17681) (0) | 2022.05.31 |