I need to to generate 6 unique random numbers from 1 to 37; At first I used a simple array mapping:
private int k=6, n=37;
public int[] Results ()
{
// fill an array with numbers 1 2 3 . . . n
int[] numbers = new int[n];
for (int i = 0; i < numbers.length; i++)
numbers[i] = i + 1;
// draw k numbers and put them into a second array
int result[] = new int[k];
for (int i = 0; i < result.length; i++)
{
// make a random index between 0 and n - 1
int r = (int) (Math.random() * n);
// pick the element at the random location
result[i] = numbers[r];
// move the last element into the random location
numbers[r] = numbers[n - 1];
n--;
}
return result;
}
The problem was that in a lot of the cases I got a near uniformic distribution (escpicially when I make less then 10 draws) i.e.: 1,9,16,18,24,30 or 5,16,18,22,26,29
What I really need is a TRUE randomizer that can give me results like: 11,16,25,29,30,32 or 4,8,9,15,18,19 in LESS then 10 draws.
I saw also a HashMap implementation of something similar:
import java.util.*;
public class RandomHash
{
HashMap numbers = new HashMap() ;
Random rnd_gen = new Random() ;
RandomHash()
{
for(;;)
{
int rnd_num = rnd_gen.nextInt() ;
Integer rnd_num_obj = new Integer(rnd_num) ;
if (! numbers.containsKey(rnd_num_obj) )
{
numbers.put(rnd_num_obj, rnd_num_obj) ;
/* Do whatever with the number */
break ;
} /* else loop and get another rnadom num */
} /*end for*/
}
}
The problem is that I currently don't know how to bound the randomizer and the hashmap to 6 and 32 respectively. Will the hashmap give more scrambled results ?