将1添加到ArrayList项

时间:2013-06-16 02:29:25

标签: java

我正在检查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);
                 ...
                 ...
                 ...

      }

4 个答案:

答案 0 :(得分:2)

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]++;

答案 1 :(得分:1)

将频率存储在整数数组中会更有意义。首先,增加特定结果的值会更简单:

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;
}

现在你的频率数组的频率为骰子结果为2,索引为0。

答案 2 :(得分:1)

使用固定大小的数组可获得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]++;
}

答案 3 :(得分:0)

这可能看起来像是一种矫枉过正,但为计数器创建一个包装器,这样你就可以将它存储在地图中,这样可以使代码在eys上更容易一些,并且更容易扩展。

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