Sunday, 19 March 2017

Permutation of String

Hi Folks, 

This is very common problem which you might face while solving a big complex problem. Lot of time we need to find the possible permutations of digits or string or objects. I am writing code to find permutations of string you can do customization according to your requirement.

String Permutation means all possible arrangement of characters.

Number of all permutation = factorial(number of characters in String)

 

 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
package com.javasuitor;

public class StringPermutation {

 public static void main(String[] args) {
       String inputString = "abcd";
  char arr[] = inputString.toCharArray();  
  permutation(arr, 0, arr.length);
 }

 public static void permutation(char[] arr, int k, int n) {
  
  if (k == n) {
   display(arr);
   return;
  }
  
  for (int i = k; i < n; i++) {
   swap(arr ,i,k);
   permutation(arr, k + 1, n);
   swap(arr ,i , k);
  }
  
 }
 
 public static void display(char[] arr){
   for(char c:arr)
    System.out.print(c);
   
   System.out.println();
 }
 
 public static void swap(char[] arr,int i,int k){
  char temp = arr[i];
  arr[i] = arr[k];
  arr[k] = temp;
 }

}

Output :

abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc