Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.54 KB | None | 0 0
  1. package com.example.scrap;
  2.  
  3. import java.util.Random;
  4. import java.util.function.Consumer;
  5. import java.util.stream.IntStream;
  6.  
  7. public class Shuffle {
  8.  
  9. private static final Random r = new Random();
  10. private static final int TRIALS = 100000;
  11. private static final int LEN = 3;
  12.  
  13. private static void swap(int[] array, int i, int j) {
  14. int temp = array[i];
  15. array[i] = array[j];
  16. array[j] = temp;
  17. }
  18.  
  19. public static void naive(int[] array) {
  20. for (int i = array.length - 1; i >= 0; i--) {
  21. swap(array, i, r.nextInt(array.length));
  22. }
  23. }
  24.  
  25. public static void fisher_yates(int[] array) {
  26. for (int i = array.length - 1; i >= 1; i--) {
  27. swap(array, i, r.nextInt(i + 1));
  28. }
  29. }
  30.  
  31. public static class Histo {
  32. final int len;
  33. final int[][] buckets;
  34. int total;
  35.  
  36. public Histo(int len) {
  37. this.len = len;
  38. buckets = new int[len][];
  39. for (int i = 0; i < len; i++) {
  40. buckets[i] = new int[len];
  41. }
  42. }
  43.  
  44. public void accept(int[] array) {
  45. assert array.length == len;
  46. for (int i = 0; i < len; i++) {
  47. buckets[i][array[i]]++;
  48. }
  49. total++;
  50. }
  51.  
  52. @Override
  53. public String toString() {
  54. StringBuilder sb = new StringBuilder(" ");
  55. for (int i = 0; i < len; i++) {
  56. sb.append(String.format("%6d", i));
  57. }
  58. sb.append('\n');
  59. for (int i = 0; i < len; i++) {
  60. sb.append(String.format("a[%d]", i));
  61. for (int j = 0; j < len; j++) {
  62. sb.append(String.format("%6.1f", 100. * buckets[i][j]/total));
  63. }
  64. sb.append('\n');
  65. }
  66. return sb.toString();
  67. }
  68. }
  69.  
  70. public static void testDistriubtion(int length, Consumer<int[]> algo, String name) {
  71. int[] ref = IntStream.range(0, length).toArray(), array = new int[ref.length];
  72.  
  73. Histo histo = new Histo(length);
  74. for (int i = 0; i < TRIALS; i++) {
  75. System.arraycopy(ref, 0, array, 0, ref.length);
  76. algo.accept(array);
  77. histo.accept(array);
  78. }
  79.  
  80. System.out.println(name + ":\n" + histo);
  81. }
  82.  
  83. public static void main(String[] args) {
  84. testDistriubtion(LEN, (a) -> fisher_yates(a), "fisher_yates");
  85. testDistriubtion(LEN, (a) -> naive(a), "naive");
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement