This articles shows few ways of writing a java program for finding all permutations of characters in a string.
This article only focusses only on the recursive approaches.
Java programs for string permutations using recursion :
Program 1 : Heap’s algorithm
package com.topjavatutorial; import java.util.Arrays; import java.util.Scanner; public class ExampleAllPermutationOfString { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a String : "); String str = sc.next(); generate(str.toCharArray(),str.length()); } public static void generate(char[] arr, int n) { if (n == 1) { System.out.println(Arrays.toString(arr)); } else { for (int i = 0; i < n-1; i++) { generate(arr, n - 1); // odd or even if (n % 2 == 1) { swap(arr, 0, n - 1); } else { swap(arr, i, n - 1); } } generate(arr, n - 1); } } private static void swap(char[] arr, int right, int left) { char temp = arr[right]; arr[right] = arr[left]; arr[left] = temp; } }
Output
Enter a String :
abc
[a, b, c]
[b, a, c]
[c, a, b]
[a, c, b]
[b, c, a]
[c, b, a]
Program 2
package com.topjavatutorial; import java.util.Scanner; public class ExampleAllPermutationOfString { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a String : "); String str = sc.next(); permutation(str); } public static void permutation(String str) { permutation("", str); } private static void permutation(String prefix, String str) { int n = str.length(); if (n == 0) System.out.println(prefix); else { for (int i = 0; i < n; i++) permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n)); } } }
Output
Enter a String :
abc
abc
acb
bac
bca
cab
cba
Reference
https://en.wikipedia.org/wiki/Heap%27s_algorithm
http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post
#