2

重複の可能性:
偏った乱数ジェネレーター

一度は、他の数値よりも確率の高い数値を少なくとも 2 つ持つ乱数ジェネレーターが必要です。

つまり、例: 1000 のシーケンスでランダムな 1->10。数値 A=3 および B=7。

A - 約繰り返す必要があります。少なくとも 20% の時間。B - 約繰り返す必要があります。時間の少なくとも 30%。

これは、1000 シーケンスの少なくとも 50% をカバーする必要があります。また、A と B の挿入は、それ自体がある程度確率的/ランダムである必要があります。NステップごとにAとBを追加するだけではありません。完全/正確な制御は必要ありません。

何か案は?

私は初心者です - C++ スタイルのコードは大歓迎です!

4

2 に答える 2

2

これを行う 1 つの方法は、0.0 から 1.0 の間の数値をランダムに生成し、その数値に基づいて生成する数値を選択することです。たとえば、サンプル シナリオ (疑似コード) を実装するには、次のようにします。

let "result" be an array of 1000 integers
let "i" be an integer
for i = 1 to 1000:
    let "j" be a random number between 0.0 and 1.0
    if j < 0.2:
        let result[i] be 3
    else if j < 0.5:
        let result[i] be 7
    else:
        let "k" be an integer
        do, while k = 3 or k = 7:
            let "k" be a random number in the range 1 to 10
        let result[i] be k
end

基本的に、jは範囲 1 から 10 を 3 つの部分に分割するために使用されます。1 つは範囲の 0% から 20% をカバーし (最初の部分if)、2 番目は範囲の 20% から 50% をカバーします (つまり、30% 幅、 2 番目if)、最後に残りの 50% をカバーします。ランダムに分類される部分に応じて、生成する数を適切に選択しました。

于 2012-07-04T22:49:51.013 に答える
1

<random>これにはライブラリを使用する必要があります。

#include <random>

#include <iostream>
#include <algorithm>
#include <iterator>

int main() {
    // create a discrete distribution where the third object has 20% probability and
    //   the seventh has 30%
    std::vector<double> probabilities(10, 5.0/8.0);
    probabilities[2] = 2.0;
    probabilities[6] = 3.0;
    std::discrete_distribution<int> dist(begin(probabilities),end(probabilities));

    // our underlying source of randomness
    std::random_device r;
    std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
    std::mt19937 eng(seed);

    // create a function object that uses the distribution and source of randomness to
    //   produce values from 1 to 10
    auto rand = [&]{ return dist(eng) + 1; };

    std::vector<int> x;

    // store 1000 random values
    for (int i=0;i<1000;++i)
        x.push_back(rand());

    // count how many of each value, to verify that 3 comes out ~200 times and 7 comes
    //   out ~300 times
    for (int i=1;i<=10;++i)
        std::cout << i << ": " << count(begin(x),end(x),i) << '\n';

    // print all the values
    copy(begin(x),end(x),std::ostream_iterator<int>(std::cout, " "));
}
于 2012-07-04T23:34:18.723 に答える