Harmlezz

Random Array of Integers

Feb 17th, 2012
105
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.Collections;
  2. import java.util.List;
  3.  
  4. import com.google.common.collect.Lists;
  5. import com.google.common.primitives.Ints;
  6.  
  7. public class IntArray {
  8.  
  9.     public static int[] ofSize(int size) {
  10.         if (size < 0) throw new IllegalArgumentException(
  11.                 String.format("Expected a size [%d] to be at least 0", size));
  12.         List<Integer> ints = Lists.newArrayList();
  13.         for (int n = 0; n < size; n++) ints.add(n);
  14.         Collections.shuffle(ints);
  15.         return Ints.toArray(ints);
  16.     }
  17. }
  18.  
  19. import java.util.Random;
  20.  
  21. import org.junit.Test;
  22.  
  23. public class IntArrayTest {
  24.  
  25.     @Test public void ofSizeIsRandom() {
  26.         Random randomizer = new Random();
  27.         int size = randomizer.nextInt(1000) + 2;
  28.         int index1 = randomizer.nextInt(size), index2;
  29.         do index2 = randomizer.nextInt(size); while (index1 == index2);
  30.         int value1 = randomizer.nextInt(size), value2;
  31.         do value2 = randomizer.nextInt(size); while (value1 == value2);
  32.         int round = 1;
  33.         do {
  34.             int[] ints = IntArray.ofSize(size);
  35.             if (ints[index1] == value1 && ints[index2] == value2) break;
  36.             int threshold = size * (size - 1);
  37.             if (round % threshold == 0) {
  38.                 System.out.println("perhaps the function does not produce random arrays");
  39.             }
  40.             round++;
  41.  
  42.         } while (true);
  43.     }
  44. }
RAW Paste Data