我正在写这个小彩票应用程序。
现在的计划是,在彩票的每次迭代中计算每个号码被抽奖的频率,并将其存储在某个地方。
我的猜测是,我将需要使用具有6个键的HashMap,并在每次绘制相应键号时将值增加1。
但是我该怎么做呢?
到目前为止,我的代码:
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));
}
也许有人可以告诉我我是否有正确的想法,或者甚至如何正确实施地图?
最佳答案
HashMap或任何类型的地图在这里都太复杂了。计算一个数字出现所需要的只是一个数组。
假设您有49个可能的数字,则声明一个数组:
int counts = new int[49];
Arrays.fill(counts,0);
然后为每个抽奖做:
int drawnumbers[6]; // put the numbers for this draw in the array
for (int i=0;i<6;++i) {
counts[drawnumbers[i]-1]++;
}
最后打印结果:
for (int i=0;i<49;++i) {
System.out.println("Number "+(i+1)+" occurred "+counts[i]+" times.");
}
关于java - 如何计算彩票中抽取的每个数字的数量并将其输出到列表中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2951431/