Skip to content

Commit 4eb1d07

Browse files
committed
added 5kyu - Prime Fun #1
1 parent 6c0e38b commit 4eb1d07

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

5kyu_PrimeFun#1.js

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// 5kyu - Prime Fun #1
2+
3+
// When no more interesting kata can be resolved, I just choose to create the new kata, to solve their own, to enjoy the process --myjinxin2015 said
4+
5+
// Input
6+
// An integer array nums that contains n*2 elements:
7+
8+
// [1,2,3,4,5,6]
9+
10+
// Output
11+
// A 2D array that contains n elements. Each element is an subarray that contains two integers, and their sum must be a prime:
12+
13+
// [[1,2],[3,4],[5,6]]
14+
15+
// Note:
16+
// You can assume that the length of nums always be an even number or 0(an empty array) and it always less than 20.
17+
// All the integers are positive integers and less than or equals to 1000.
18+
// You don't need to worry about the order of the output array. that is, There may be many kinds of combinations and sequences, you just need to return one of the effective combinations.
19+
// If there is no possible solution, return []
20+
// Examples
21+
// primeSumPair([1,2,3,4,5,6]) can returns: [[1,2],[3,4],[5,6]]
22+
// or: [[3,4],[5,6],[1,2]]
23+
// or: [[1,4],[5,6],[2,3]]
24+
// or ....
25+
// primeSumPair([11,22,33,44,55,66]) should return []
26+
// tip: don;t mutate the input
27+
28+
function primes(n) {
29+
let sieve = Array(n + 1).fill(true);
30+
let m = Math.floor(Math.sqrt(n));
31+
for (let i = 3; i <= m; i += 2) {
32+
if (sieve[i]) {
33+
let step = 2 * i;
34+
for (let j = i * i; j <= n; j += step)
35+
sieve[j] = false;
36+
}
37+
}
38+
let primes = [2];
39+
for (let i = 3; i <= n; i += 2)
40+
if (sieve[i])
41+
primes.push(i);
42+
return primes;
43+
}
44+
45+
const PRIMES = new Set(primes(2000));
46+
47+
function primeSumPair(nums) {
48+
function search(nums, result = []) {
49+
const k = nums.length;
50+
if (k <= 1)
51+
return result;
52+
const a = nums[k - 1];
53+
for (let i = k - 2; i >= 0; i--) {
54+
const b = nums[i];
55+
if (PRIMES.has(a + b)) {
56+
result.push([a, b]);
57+
const r = search(nums.filter((_, j) => j !== i && j !== k - 1), result);
58+
if (r)
59+
return r;
60+
result.pop();
61+
}
62+
}
63+
}
64+
const result = search(nums);
65+
return result ? result : [];
66+
}

0 commit comments

Comments
 (0)