0

宿題。ダイスゲーム。サイコロを 5 回振ることを表す配列があります。考慮してください: diceRoll[] = {6,3,3,4,5}. に含まれる 1 から 6 までの値のカウントを持つ SECOND 配列を作成したいと思いますdiceRoll[](たとえば、occurence[] = {0,0,2,1,1,1}上記のdiceRoll[]場合)。私は~はず~戻ってきます。occurence[]はグローバル変数であり、その意図は、配列に 6 つの値が含まれることです...1 の数 (インデックス [0])、2 の数 ([1])、3 の数 ([2]) などです。

これまでのところ:

 for(i=1;i<7;i++)   /* die values 1 - 6
    {
       for(j=0;j<diceRoll.length;j++)  /* number of dice
       {
          if (diceRoll[j] == i)  /* increment occurences when die[j] equals 1, then 2, etc.
             occurence = occurence + 1;
       }
    }
    return occurence;
    }

ただし、occurence=occurence+1 を機能させることはできません。bad operand types for binary operator私の最も一般的なエラーです。occurencefor ループの 1 つまたは両方の OUTSIDEをインクリメントする必要があると思われますが、迷っています。

ガイダンス?それとも、これを行うための1行の簡単な方法ですか? d

4

1 に答える 1

4

これを行う最も簡単な方法は、2 番目の配列を順番に作成して、occurrence[0] = 1 の数、occurrence[1] = 2 の数などとなるようにすることです。すると、これは 1 ループのメソッドになります。

//method to return number of occurrences of the numbers in diceRolls
int[] countOccurrences(int[] diceRolls) {
    int occurrence[] = new int[6]; //to hold the counts

    for(int i = 0; i < diceRolls.length; i++) { //Loop over the dice rolls array
       int value = diceRolls[i]; //Get the value of the next roll
       occurence[value]++; //Increment the value in the count array this is equivalent to occurrence[value] = occurrence[value] + 1;
       //occurrence[diceRolls[i]]++; I broke this into two lines for explanation purposes
    }

    return occurrence; //return the counts 
} 

編集:

次に、特定の値の使用のカウントを取得するにはoccurrence[value-1]

于 2012-03-20T00:31:56.367 に答える