Skip to content

Commit 51d3d7e

Browse files
committed
absolute-permutation
1 parent 4102670 commit 51d3d7e

File tree

1 file changed

+99
-0
lines changed

1 file changed

+99
-0
lines changed

absolute-permutation.js

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
2+
// let permutation = [];
3+
// const permutate = (arr) => {
4+
// for (let i = 0; i < arr.length - 1; i++) {
5+
// let current = arr[i];
6+
7+
// let next = arr[i + 1]
8+
// arr[i] = next;
9+
// arr[i + 1] = current;
10+
// permutation.push(arr.map(x=>x));
11+
// arr[i + 1] = next;
12+
// arr[i] = current;
13+
14+
// }
15+
// }
16+
17+
// let arr = [1, 2, 3]
18+
// permutate(arr)
19+
// console.log(permutation);
20+
21+
22+
let permArr = [],
23+
usedChars = [];
24+
function permute(input, diff) {
25+
var i, ch;
26+
for (i = 0; i < input.length; i++) {
27+
// fixed 1, then process [2,3]
28+
ch = input.splice(i, 1)[0];
29+
// usedchars [1]
30+
usedChars.push(ch);
31+
if (input.length == 0) {
32+
let bool = true;
33+
for (let k = 0; k < usedChars.length; k++) {
34+
if (Math.abs((usedChars[k] - (k + 1))) !== diff) {
35+
bool = false;
36+
break;
37+
}
38+
}
39+
// console.log(usedChars);
40+
if (bool) {
41+
return usedChars;
42+
}
43+
}
44+
// processing [2,3]
45+
let res = permute(input, diff)
46+
if (res.length > 0) {
47+
return res;
48+
}
49+
50+
input.splice(i, 0, ch);
51+
usedChars.pop();
52+
}
53+
return [];
54+
};
55+
56+
function validate(arr, diff) {
57+
for (let k = 0; k < arr.length; k++) {
58+
let index = k + 1;
59+
let ithElement = arr[k];
60+
if (Math.abs(index - ithElement) !== diff) {
61+
return [];
62+
}
63+
}
64+
return arr;
65+
}
66+
67+
function permute2(permutation, diff) {
68+
let length = permutation.length,
69+
c = new Array(length).fill(0),
70+
i = 1, k, p;
71+
let arr = permutation.slice();
72+
if (validate(arr, diff).length > 0)
73+
return arr;
74+
75+
while (i < length) {
76+
if (c[i] < i) {
77+
k = i % 2 && c[i];
78+
p = permutation[i];
79+
permutation[i] = permutation[k];
80+
permutation[k] = p;
81+
++c[i];
82+
i = 1;
83+
arr = permutation.slice();
84+
if (validate(arr, diff).length > 0)
85+
return arr;
86+
87+
} else {
88+
c[i] = 0;
89+
++i;
90+
}
91+
}
92+
return [];
93+
}
94+
n = 10;
95+
k = 5;
96+
97+
let numbers = Array.from(Array(n), (_, i) => i + 1);
98+
99+
console.log((permute2(numbers, k)));

0 commit comments

Comments
 (0)