-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathstringPermute2.js
More file actions
32 lines (29 loc) · 878 Bytes
/
stringPermute2.js
File metadata and controls
32 lines (29 loc) · 878 Bytes
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
/**
* METHOD -- Backtracking
* Algorithm taken from GeeksForGeeks (https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/)
* Implemented in JS by @MadhavBahl
* @date 02/01/2019
*/
function swap (str, pos1, pos2) {
// console.log (`pos1 = ${pos1}, pos2 = ${pos2} old`, str);
str = str.split('');
let temp = str[pos1];
str[pos1] = str[pos2];
str[pos2] = temp;
str = str.join('');
// console.log ('new str', str);
return str;
}
function stringPermutations (str, start, end) {
if (start === end) {
console.log (str);
} else {
for (let i=start; i<end; i++) {
str = swap (str, start, i);
stringPermutations (str, start+1, end);
str = swap (str, i, start);
}
}
}
let inputStr = '123';
stringPermutations (inputStr, 0, inputStr.length);