Skip to content

Commit 996eb9f

Browse files
committed
Add backtracking solution
1 parent f839a05 commit 996eb9f

File tree

3 files changed

+55
-1
lines changed

3 files changed

+55
-1
lines changed

day10/JavaScript/sol.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,4 @@ function permut(string) {
2424
return permutations;
2525
}
2626

27-
permut('123');
27+
console.log(permut('1234'));

day10/JavaScript/stringPermute.js

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
function stringPermutations (str) {
2+
let permutations = [];
3+
4+
if (str.length <= 1) {
5+
permutations.push (str);
6+
return permutations;
7+
} else {
8+
for (let i=0; i<str.length; i++) {
9+
let start = str[i],
10+
remainingString= str.slice(0, i) + str.slice(i+1),
11+
permutationsforRemainingString = stringPermutations(remainingString);
12+
13+
for (let j=0; j<permutationsforRemainingString.length; j++) {
14+
permutations.push (start + permutationsforRemainingString[j]);
15+
}
16+
}
17+
}
18+
19+
return permutations;
20+
}
21+
22+
console.log (stringPermutations('123'));

day10/JavaScript/stringPermute2.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* METHOD -- Backtracking
3+
* Algorithm taken from GeeksForGeeks (https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/)
4+
* Implemented in JS by @MadhavBahlMD
5+
* @date 02/01/2019
6+
*/
7+
8+
function swap (str, pos1, pos2) {
9+
// console.log (`pos1 = ${pos1}, pos2 = ${pos2} old`, str);
10+
str = str.split('');
11+
let temp = str[pos1];
12+
str[pos1] = str[pos2];
13+
str[pos2] = temp;
14+
str = str.join('');
15+
// console.log ('new str', str);
16+
return str;
17+
}
18+
19+
function stringPermutations (str, start, end) {
20+
if (start === end) {
21+
console.log (str);
22+
} else {
23+
for (let i=start; i<end; i++) {
24+
str = swap (str, start, i);
25+
stringPermutations (str, start+1, end);
26+
str = swap (str, i, start);
27+
}
28+
}
29+
}
30+
31+
let inputStr = '123';
32+
stringPermutations (inputStr, 0, inputStr.length);

0 commit comments

Comments
 (0)