6

特定の範囲を除外しながら、範囲内で乱数を生成するにはどうすればよいですか。例えば。範囲は1〜10ですが、2〜4または7ではありません。これまでに使用したソリューション:

  • 許可されていない範囲内にある場合、ランダムなテストを生成します。結果に基づいて、数値を出力するか、再試行します。
  • 許可範囲を均一範囲にマップします。1 から 6 の間でランダムに取得し、マップを戻します (つまり、6 が 10 になります)。
  • 許容範囲 (1-1,5-6,8-10) を作成します。範囲 (オプションで重みを使用) と選択した範囲内の数値をランダムに選択します。

あなたの解決策は何ですか?

4

5 に答える 5

8

(b) 単一の範囲を使用し、許可された値にマップします。

(a) 適切な範囲の数値が得られるまで待たなければならないため、遅く、実行時間が非決定論的です。広い範囲をスキップすると、うんざりします。

(c) (b) よりも複雑です。必要でない場合は複雑にしないでください。

于 2008-10-12T20:11:48.490 に答える
1

Map them to the total of the ranges you expect. then distribute them between the ranges.

E.g. if you need a random between 0..10 and 100..110

Generate a random-number between 20. The lower 10 get assigned to the 0..10 range, the rest to the other interval (or something like that - I may be off by one.. Interval arithmetic is one of these things that I never get right on the first try).

The reason behind this is that you often deal with non perfect random generators. These start to behave strange if you distribute successive random-number variables over several dimensions (e.g. first choose a random interval, then choose a random inside the chosen interval). That can lead to a very obvious non-random behavior.

If you start with a better random number generator that gets it's data from true random sources you may end up wasting precious random bits. If you do it just once every second it may not be a problem. If you do it to often though you program might get stalled because the pure random sources have to catch up with your random-bit consume.

于 2008-10-12T20:16:22.583 に答える
1

除外範囲の数/大きさによって異なります。許可されていない範囲 (オプション 1) のテストは、小さなセットでは問題なく機能します。簡単な問題の解決策を複雑にする必要はありません。解決策 3 は、除外セットの数が多い場合に適しています。解決策 2 が最も手間がかかりますが、おそらく最も正しい理論上の解決策です。

于 2008-10-12T20:12:38.427 に答える
1

私は通常、上記の箇条書き 2 で説明した手法を使用します。特に、許容される数のセットがかなり小さい場合は特にそうです。統計的な観点からすると、結果のランダム性を台無しにしたり、結果をフラットな分布から歪めたりするのは簡単です。

これには、単一の選択 (カードの配りやビンゴ ボールの選択など) を許可するという追加の利点があります。既に選択されている値をマップから削除するだけです。

于 2008-10-12T20:13:07.300 に答える
0

It sounds like your algorithm can benefit from a slight redesign that will make creating the random numbers implicit rather than explicitly finding them using a random number generator.

For instance if you want to get a random series of the numbers from 1 to 10, its better to start from an ordered series, mix it in some fashion for instance via swapping (there was a question about this I think) and take the numbers one after the other.

于 2008-10-12T20:16:04.597 に答える