Advertisement
Guest User

Untitled

a guest
Sep 26th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class Exercise2 {
  4. public static void main(String[] args) {
  5. for (String s: permute("catdog"))
  6.  
  7. System.out.println(s);
  8. }
  9.  
  10. public static ArrayList<String> permute(String letters) {
  11.  
  12. ArrayList<String> perms = new ArrayList<String>();
  13.  
  14. if (letters.length() == 1) {
  15. perms.add(letters);
  16. } else {
  17.  
  18. for (int i=0; i<letters.length(); i++) {
  19. //choose a character out of the letters
  20. //So for "cat" this would be "c"
  21. char character = letters.charAt(i);
  22.  
  23. //Grab remaining letters, i is excluded
  24. //So for "cat" this would be "at"
  25. String substring = letters.substring(0, i) + letters.substring(i+1);
  26.  
  27. //Recursive
  28. //So it would permute("at")
  29. ArrayList<String> subperms = permute(substring);
  30.  
  31. for (String tail : subperms) {
  32. perms.add(character + tail);
  33. }
  34. }
  35. }
  36. return perms;
  37. }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement