-
Notifications
You must be signed in to change notification settings - Fork 1
/
YourCombinations.js
52 lines (40 loc) · 1.28 KB
/
YourCombinations.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
/*
* Name: Your Combinations JavaScript
* Author: Max Base
* Date: 2022/10/04
* Repository: https://github.com/basemax/YourCombinationsJS
*/
class YourCombinations {
constructor(elements) {
this.elements = elements;
}
*powerSet() {
const size = 2n ** BigInt(this.elements.length);
for (let i = 0; i < size; i++) {
const cur = [];
for(let j = 0; j < this.elements.length; j++) if((i & (1 << j)) > 0) cur.push(this.elements[j]);
yield cur;
}
}
*combinations(length, with_repetition = false, position = 0, elements = []) {
const size = this.elements.length;
for (let i = position; i < size; i++) {
elements.push(this.elements[i]);
if (elements.length === length) yield elements;
else yield* this.combinations(length, with_repetition, (with_repetition === true ? i : i + 1), elements);
elements.pop();
}
}
*permutations(length, with_repetition = false, elements = [], keys = []) {
for (const key in this.elements) {
const value = this.elements[key];
if (with_repetition === false) if (keys.indexOf(key) !== -1) continue;
keys.push(key);
elements.push(value);
if (elements.length === length) yield elements;
else yield* this.permutations(length, with_repetition, elements, keys);
keys.pop();
elements.pop();
}
}
}