fork(6) download
  1. // Permutation of a String with duplicates
  2. /**
  3.  * @author Prateek
  4.  */
  5. class Permutation{
  6.  
  7. private char[] str=null; // to hold string data
  8.  
  9. /**
  10. * Takes the initial input
  11. */
  12. public void printPermutations(String text){
  13. str=text.toCharArray();
  14. permutate(0,text.length()-1);
  15. }
  16.  
  17. /**
  18. * Subroutine to compute permutations
  19. * @param index
  20. * @param len
  21. */
  22. private void permutate( int index, int len )
  23. {
  24. if( index == len )
  25. System.out.println((str));
  26.  
  27. for(int i = index; i <= len; i++ )
  28. {
  29. if(!match(index, i)){
  30. swap(index, i );
  31. permutate(index + 1 , len);
  32. swap( index, i );
  33. }
  34. }
  35. }
  36.  
  37. /**
  38. * to check if any character matches between i and j
  39. * @return if any characted match found
  40. */
  41. private boolean match(int i, int j) {
  42. if(i == j)
  43. return false;
  44. else
  45. for(;i<j ; i++)
  46. if(str[i]==str[j])
  47. return true;
  48. return false;
  49. }
  50.  
  51. public static void main(String[] a) {
  52. String text="ABCD";
  53. Permutation obj=new Permutation();
  54. obj.printPermutations(text) ;
  55. }
  56.  
  57. private void swap(int a, int b) {
  58. char temp=str[a];
  59. str[a]=str[b];
  60. str[b]=temp;
  61. }
  62. }
Success #stdin #stdout 0.06s 380224KB
stdin
Standard input is empty
stdout
ABCD
ABDC
ACBD
ACDB
ADCB
ADBC
BACD
BADC
BCAD
BCDA
BDCA
BDAC
CBAD
CBDA
CABD
CADB
CDAB
CDBA
DBCA
DBAC
DCBA
DCAB
DACB
DABC