File tree 3 files changed +55
-1
lines changed
3 files changed +55
-1
lines changed Original file line number Diff line number Diff line change @@ -24,4 +24,4 @@ function permut(string) {
24
24
return permutations ;
25
25
}
26
26
27
- permut ( '123' ) ;
27
+ console . log ( permut ( '1234' ) ) ;
Original file line number Diff line number Diff line change
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' ) ) ;
Original file line number Diff line number Diff line change
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 ) ;
You can’t perform that action at this time.
0 commit comments