tags:

views:

82

answers:

3

I am writing this little Lottery application. Now the plan is, to count how often each number has been drawn during each iteration of the Lottery, and store this somewhere. My guess is that I would need to use a HashMap, that has 6 keys and increments the value by one everytime the respective keys number is drawn. But how would I accomplish this? My code so far:

public void numberCreator()
{
    // creating and initializing a Random generator
   Random rand = new Random();
   // A HashMap to store the numbers picked. 
   HashMap hashMap = new HashMap();
   // A TreeMap to sort the numbers picked.
   TreeMap treeMap = new TreeMap();

    // creating an ArrayList which will store the pool of availbale Numbers
    List<Integer>numPool = new ArrayList<Integer>();

    for (int i=1; i<50; i++){
    // add the available Numbers to the pool
    numPool.add(i); 
    hashMap.put(nums[i], 0);
    }

    // array to store the lotto numbers
    int [] nums = new int [6];

    for (int i =0; i < nums.length; i++){
    int numPoolIndex = rand.nextInt(numPool.size());
    nums[i] = numPool.get(numPoolIndex);

    // check how often a number has been called and store the new amount in the Map
    int counter =  hashMap.get

    numPool.remove(numPoolIndex);
    }

    System.out.println(Arrays.toString(nums));

    }

Maybe someone can tell me if I have the right idea, or even how I would implement the map properly?

A: 
hashMap.put(nums[i], hashMap.get(nums[i])+1);

Although I have no idea what you are trying to accomplish here. There is no need for counting the elements, since there is no way to retrieve a number more than once. This is because you throw away any number that you 'draw' out of the list that you created at the beginning.

Marc
+1  A: 

Yes, a hashmap is a good idea to keep such information.

A hashmap with as a key value consecutives integers feels weird. In this specific case I would prefer a simple integer array and increment the element corresponding to the drawn ball.

I would check your logic for drawing balls from the pool. I think the get method does not do what you expect it to do. Maybe a using a Set for the numPool and removing the balls which are chosen fits closer.

Peter Tillemans
+3  A: 

A HashMap, or any kind of map, is far too complicated here. All you need to count the occurrences of a number is an array.

Assuming you have 49 possible numbers, declare an array:

int counts = new int[49];
Arrays.fill(counts,0);

Then for each lottery draw do:

int drawnumbers[6]; // put the numbers for this draw in the array
for (int i=0;i<6;++i) {
  counts[drawnumbers[i]-1]++;
}

At the end print the results:

for (int i=0;i<49;++i) {
  System.out.println("Number "+(i+1)+" occurred "+counts[i]+" times.");
}
DJClayworth