-
Notifications
You must be signed in to change notification settings - Fork 0
/
choseBestDistance.js
54 lines (48 loc) · 1.23 KB
/
choseBestDistance.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const chooseBestDistance = (t, k, ls) => {
let sum = 0, tempSum = 0;
if (ls.length >= 1 && t >= 0 && k >= 1) {
function* generateCombinations(arr, size) {
function* doGenerateCombinations(offset, combo) {
if (combo.length == size) {
yield combo;
} else {
for (let i = offset; i < arr.length; i++) {
yield* doGenerateCombinations(i + 1, combo.concat(arr[i]));
}
}
}
yield* doGenerateCombinations(0, []);
}
for (let combo of generateCombinations(ls, k)) {
for (i = 0; i < combo.length; i++) {
tempSum += combo[i]
if (tempSum > sum && tempSum < t) {
sum = tempSum;
tempSum = 0;
}
}
}
return sum
} else {
return null
}
}
chooseBestDistance(174, 3, [51, 56, 58, 59, 61]); //173
chooseBestDistance(163, 3, []); // null
const chooseBestDistance = (t, k, ls) => { //chooseBestDistance for 3 iteration
sum = 0;
for (i = 0; i < ls.length; i++) {
for (j = i + 1; j < ls.length; j++) {
for (k = j + 1; k < ls.length; k++) {
temp = ls[i] + ls[j] + ls[k]
if ( temp >= sum && temp <= t) {
sum = temp;
}
}
}
}
return sum
return null
}
console.log(chooseBestDistance(174, 3, [51, 56, 58, 59, 61])); //173
console.log(chooseBestDistance(163, 3, [50])); // null