Advertisement
Nickpips

Java Permutations

Mar 8th, 2016
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. import java.io.FileNotFoundException;
  2. import java.io.PrintWriter;
  3. import java.util.Scanner;
  4.  
  5. public class permutations {
  6. public static void generatePermutations(int[] nums, int[] perm, boolean[] used, int n) {
  7. if (nums.length == n) {
  8. // perm now contains one permutation of nums.
  9. // Perform whatever operation you want. I printed here.
  10. //for (int k : perm)
  11. // System.out.print(k + " ");
  12. //System.out.println();
  13. } else {
  14. // Try shoving every unused number into perm at index n
  15. for (int i = 0; i < nums.length; i++) {
  16. if (used[i])
  17. continue;
  18. perm[n] = nums[i];
  19. used[i] = true;
  20. generatePermutations(nums, perm, used, n + 1);
  21. used[i] = false;
  22. }
  23. }
  24. }
  25. public static void permute(int[] nums)
  26. {
  27. generatePermutations(nums, new int[nums.length], new boolean[nums.length], 0);
  28. }
  29.  
  30. public void run() {
  31. int[] arr = new int[10];
  32. for( int i = 0; i < arr.length; i++ )
  33. arr[i] = i;
  34. permute(arr);
  35. }
  36.  
  37. public void debug(Object n) {
  38. System.out.println(n);
  39. }
  40.  
  41. static Scanner in = new Scanner(System.in);
  42. static PrintWriter out = new PrintWriter(System.out);
  43.  
  44. public static void main(String[] args) throws FileNotFoundException {
  45. // in = new Scanner(new File("permutations.in"));
  46. // out = new PrintWriter(new File("permutations.out"));
  47.  
  48. permutations permutations = new permutations();
  49. permutations.run();
  50. }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement