Advertisement
Spiritreader

Untitled

Feb 19th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. import java.security.SecureRandom;
  2. import java.time.Instant;
  3. import java.util.*;
  4.  
  5. public class Main {
  6. private final static int counterOutput = 1000;
  7.  
  8. public static void main(String[] args) {
  9. int[] ary = {3,2,5,9,10,1,6,5,8,7,4,0};
  10. //int[] ary = {3,2,5,9,10};
  11. ary = bestBogo(ary);
  12. }
  13.  
  14. public static int[] bestBogo(int[] ary) {
  15. SecureRandom sr = new SecureRandom();
  16. List<Integer> permutations = new ArrayList<>();
  17. int[] shuffledArray = new int[ary.length];
  18. List<String> knownPermutations = new ArrayList<>();
  19. int count = 0;
  20. int permutationCount = 0;
  21. long before = 0;
  22. long after = 0;
  23. for (int i = 0; i < ary.length; i++) {
  24. permutations.add(i);
  25. }
  26. do {
  27. if ((count % counterOutput) == 0) {
  28. before = System.currentTimeMillis();
  29. }
  30. StringBuilder sb = new StringBuilder();
  31. do {
  32. sb.setLength(0);
  33. Collections.shuffle(permutations, sr);
  34. permutations.forEach(sb::append);
  35. ++permutationCount;
  36. } while (knownPermutations.contains(sb.toString()));
  37. for (int i = 0; i < ary.length; i++) {
  38. shuffledArray[i] = ary[permutations.get(i)];
  39. }
  40. if ((count++ % counterOutput) == (counterOutput - 1)) {
  41. after = System.currentTimeMillis();
  42. System.out.println("Iteration/Permutations " + count + " / " + permutationCount + ": " + Arrays.toString(shuffledArray));
  43. System.out.println("Time spent checking per " + counterOutput + " permutations: " + (after - before) + "ms");
  44. }
  45. knownPermutations.add(sb.toString());
  46. } while (!isSorted(shuffledArray));
  47. return shuffledArray;
  48. }
  49.  
  50. public static boolean isSorted(int ary[]) {
  51. for (int i = 1; i < ary.length; i++) {
  52. if (ary[i] < ary[i-1]) {
  53. return false;
  54. }
  55. }
  56. return true;
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement