-
Notifications
You must be signed in to change notification settings - Fork 0
/
Permutations_v2.java
54 lines (51 loc) · 1.37 KB
/
Permutations_v2.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Java program to print all permutations of a
// given string.
public class Permutations_v2
{
public static void main(String[] args)
{
String str = "ABC";
int n = str.length();
Permutations_v2 permutation = new Permutations_v2();
permutation.permute(str, 0, n-1);
}
/**
* permutation function
* @param str string to calculate permutation for
* @param l starting index
* @param r end index
*/
private void permute(String str, int l, int r)
{
System.out.println(l + "" + r);
if (l == r)
System.out.println("print" + str);
else
{
for (int i = l; i <= r; i++)
{
str = swap(str,l,i);
System.out.println(str + " " + l + "" + i + "" + r);
permute(str, l+1, r);
System.out.println(l + "" + i + "" + r);
str = swap(str,l,i);
}
}
}
/**
* Swap Characters at position
* @param a string value
* @param i position 1
* @param j position 2
* @return swapped string
*/
public String swap(String a, int i, int j)
{
char temp;
char[] charArray = a.toCharArray();
temp = charArray[i] ;
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
}