-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerateCombinations.js
89 lines (69 loc) · 2.48 KB
/
generateCombinations.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const buildArray = require('./utils/buildArray');
const { fixedPremi } = require('./italia-serale/constants');
const { random, sampleSize, get, sample } = require('lodash');
function generateAllCombinations(numbers, n) {
const combinations = [];
function combine(start, prefix) {
if (prefix.length === n) {
combinations.push(prefix);
return;
}
for (let i = start; i < numbers.length; i++) {
combine(i + 1, [...prefix, numbers[i]]);
}
}
combine(0, []);
return combinations;
}
const combine = (numbers, combinationLength, guaranteedMatches) => {
console.log(
`${combinationLength} din ${numbers.length} cu ${guaranteedMatches} numere garantate`
);
const allCombinations = generateAllCombinations(numbers, combinationLength);
if (guaranteedMatches === 0 || guaranteedMatches === combinationLength) {
return allCombinations;
}
const combinationsWithGuaranteedMatches = allCombinations.filter((combination, i) => {
const subSequentCombinations = allCombinations.slice(i + 1);
const combinationSubsets = generateAllCombinations(combination, guaranteedMatches);
const isRedundant = combinationSubsets.every((subset) => {
return subSequentCombinations.some((subSequentCombination) => {
return subset.every((number) => subSequentCombination.includes(number));
});
});
return !isRedundant;
});
console.log({
allCombinations: allCombinations.length,
combinationsWithGuaranteedMatches: combinationsWithGuaranteedMatches.length,
});
test(allCombinations, combinationsWithGuaranteedMatches, guaranteedMatches);
return combinationsWithGuaranteedMatches;
};
module.exports = combine;
const test = (allCombinations, combinationsWithGuaranteedMatches, guaranteedMatches) => {
return;
try {
allCombinations.forEach((combination) => {
const hasMatches = combinationsWithGuaranteedMatches.some(
(combinationWithGuaranteedMatches) => {
let matchesCount = 0;
combination.forEach((number) => {
if (combinationWithGuaranteedMatches.includes(number)) {
matchesCount++;
}
});
return matchesCount >= guaranteedMatches;
}
);
if (!hasMatches) {
console.log('No matches for combination', combination);
throw new Error('No matches for combination');
}
});
console.log('Test passed');
} catch (e) {
console.log('Test failed', e);
}
};
combine(buildArray(1, 9), 2, 2);