fork(2) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. int[] hgram = new int[9];
  13. Random rng = new Random();
  14. for (int i = 0; i < 30000; i++) {
  15. int[] a = getRandomSelection( 2, 3, rng );
  16. hgram[3*a[0] + a[1]]++;
  17. }
  18. for (int i = 0; i < hgram.length; i++) {
  19. if (i > 0) System.out.print(", ");
  20. System.out.print(hgram[i]);
  21. }
  22. }
  23.  
  24. public static int[] getRandomSelection (int k, int n, Random rng) {
  25. if (k > n) throw new IllegalArgumentException(
  26. "Cannot choose " + k + " elements out of " + n + "."
  27. );
  28.  
  29. HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>(2 * k);
  30. int[] output = new int[k];
  31.  
  32. for (int i = 0; i < k; i++) {
  33. int j = i + rng.nextInt(n - i);
  34. output[i] = (hash.containsKey(j) ? hash.remove(j) : j);
  35. if (j > i) hash.put(j, hash.containsKey(i) ? hash.remove(i) : i);
  36. }
  37. return output;
  38. }
  39. }
Success #stdin #stdout 0.13s 320256KB
stdin
Standard input is empty
stdout
0, 4954, 5017, 4976, 0, 4961, 4958, 5134, 0