[英]adding 1 to an ArrayList item
3600萬次擲骰后,我正在檢查骰子總數的頻率。 我計划制作一個arrayList,並在11個結果中的任何一個出現時將其用作計數系統。 如何將1加到列表中的一項?
int die1, die2, dicetotal;
ArrayList<Integer> results = new ArrayList<Integer>();
results.add(0); //for the 11th
for(int i = 0; i < 36000000; i++){
die1 = (int)(Math.random() * 6) + 1
die2 = (int)(Math.random() * 6) + 1
dicetotal = die1 + die2;
Switch (dicetotal){
case 2: results.set(0, CURRENT + 1);
...
...
...
}
ArrayList
對此可能會過大。 但是,如果必須,(未經測試的代碼)
首先,將數組初始化為包含13個元素(0到12),以使不會彈出IndexOutOfBoundsException
。 它們將被初始化為零。
results = new ArrayList<Integer>(13);
然后獲取元素,添加一個,然后進行設置
results.set(dicetotal, results.get(dicetotal) + 1);
確實,如果您事先知道數組的大小,並且在程序執行期間不會更改,則應該只使用int[]
。 它們比ArrayList
快。
// initialize
results = new int[13];
// could be new int[11]; if you put results in array elements 0 to 10.
// ...
// add to tally
results[dicetotal]++;
// or, instead, pack the array because dice roll results can only be in 2 to 12.
// Put such results in array element 0 to 10,
// by subtracting 2 to the index before putting in
results[dicetotal - 2]++;
將頻率存儲在整數數組中會更有意義。 首先,增加特定結果的值會更簡單:
int[] frequencies = new int[11]; // sum of two dice can be 2-12
for(int i = 0; i < 36000000; i++){
die1 = (int)(Math.random() * 6) + 1
die2 = (int)(Math.random() * 6) + 1
dicetotal = die1 + die2;
// increment frequency:
frequencies[dicetotal-2] = frequencies[dicetotal-2]+1;
}
現在,您的頻率數組在索引0處的骰子結果頻率為2。
使用固定大小的數組可獲得11個可能的分數:
int die1, die2, dicetotal;
int[] totals= new int[11];
for(int i = 0; i < 36000000; i++){
die1 = (int)(Math.random() * 6) + 1
die2 = (int)(Math.random() * 6) + 1
dicetotal = die1 + die2;
//just increment the right position
totals[dicetotal-2]++;
}
這似乎有點過分,但是為計數器創建包裝器以便將其存儲在地圖中將使代碼更容易實現,也更易於擴展。
public static class Count {
private int count = 0;
public int getCount() {
return count;
}
public void increment() {
count++;
}
@Override
public String toString() {
return "" + count;
}
}
public static void main(String[] args) {
Map<Integer, Count> diceHistogram = new HashMap<>();
for (int i = 2; i <= 12; i++) {
diceHistogram.put(i, new Count());
}
for (int i = 0; i < (1E+6); i++) {
int diceOne = rnd.nextInt(6) + 1;
int diceTwo = rnd.nextInt(6) + 1;
int sum = diceOne + diceTwo;
diceHistogram.get(sum).increment();
}
System.out.println(diceHistogram);
}
輸出每個骰子組合的出現次數。
2=28043, 3=55745, 4=83489, 5=110517, 6=138823, 7=166928, 8=138466, 9=111321, 10=83532, 11=55469, 12=27667
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.