-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpermutate.js
95 lines (81 loc) · 2.27 KB
/
permutate.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
90
91
92
93
94
95
// Length is set
// Order matters
// Items can repeat
function permutate1 (chars = '') {
const permutations = [];
(function inner (prefix = '') {
// Base case: String is complete
if (prefix.length === chars.length) {
permutations.push(prefix)
return
}
// Recursive case: More chars to add
for (const char of chars) {
inner(prefix + char)
}
}())
return permutations
}
// Length is set
// Order matters
// Items are unique
function permutate2 (chars = '') {
const permutations = [];
(function inner (prefix = '', remain = '') {
// Base case: String is complete
if (prefix.length === chars.length) {
permutations.push(prefix)
return
}
// Recursive case: More chars to add
for (let index = 0; index < remain.length; index += 1) {
const nextRemain = remain.slice(0, index) + remain.slice(index + 1)
inner(prefix + remain[index], nextRemain)
}
}('', chars))
return permutations
}
// Length is three chars
// Order matters
// Items can repeat
function permutateLoop1 (chars = 'aaa') {
const threeChars = chars.slice(0, 3)
const permutations = []
for (const charA of threeChars) {
for (const charB of threeChars) {
for (const charC of threeChars) {
const permutation = charA + charB + charC
permutations.push(permutation)
}
}
}
return permutations
}
// Length is three chars
// Order matters
// Items are unique
function permutateLoop2 (chars = 'aaa') {
const permutations = []
const remain3 = chars.slice(0, 3)
for (let a = 0; a < remain3.length; a += 1) {
const remain2 = remain3.slice(0, a) + remain3.slice(a + 1)
for (let b = 0; b < remain2.length; b += 1) {
const remain1 = remain2.slice(0, b) + remain2.slice(b + 1)
for (let c = 0; c < remain1.length; c += 1) {
const permutation = remain3[a] + remain2[b] + remain1[c]
permutations.push(permutation)
}
}
}
return permutations
}
// console.log(permutate1());
// console.log(permutate2());
// console.log(permutate1('A'));
// console.log(permutate2('A'));
// console.log(permutate1('AB'));
// console.log(permutate2('AB'));
console.log(permutate1('ABC'))
console.log(permutate2('ABC'))
console.log(permutateLoop1('ABC'))
console.log(permutateLoop2('ABC'))