forked from bsimpson/superpermutation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsuperpermutation.js
73 lines (64 loc) · 1.89 KB
/
superpermutation.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
module.exports = (() => {
function calc(val) {
let i = 1;
const a = Array.from({length: val}, () => i++);
const products = permutations(a).map((x) => x.join('')); // ["12", "21"]
const permutationsOfProducts = permutations(products); // [['12', '21'], ['21', '12']]
let shortestString = null;
let testString = '';
permutationsOfProducts.forEach((products) => { // ['12', '21']
testString = products.reduce((sum, product) => { // '12'
if (sum.search(product) > -1) {
// string already contains combination - do nothing
return sum;
} else {
// concat new pattern
sum = sum.concat(product);
// remove adjacent dups
let sumArray = sum.split(''); // ['1','2','2','1']
let uniqueArray = [];
let previousVal = null;
sumArray.forEach((x) => {
if (previousVal !== x) {
uniqueArray.push(x);
}
previousVal = x;
});
sum = uniqueArray.join(''); // '121'
}
return sum;
}, '');
if (shortestString == null || (shortestString.length > testString.length)) {
shortestString = testString;
}
});
return shortestString;
}
function pretty(val) {
return `Shortest string is '${calc(val)}'`;
}
// https://gist.github.com/viebel/5cc67a97903f04036b569c0eb0436e5f
function permutations(arr) {
var permArr = [],
usedChars = [];
function permute(input) {
var i, ch;
for (i = 0; i < input.length; i++) {
ch = input.splice(i, 1)[0];
usedChars.push(ch);
if (input.length == 0) {
permArr.push(usedChars.slice());
}
permute(input);
input.splice(i, 0, ch);
usedChars.pop();
}
return permArr;
};
return permute(arr);
};
return {
calc: calc,
pretty: pretty
}
})();