私が取り組んでいる C++ プロジェクトにKnuth シャッフルを実装しています。私はシャッフルから最も偏りのない結果を得ようとしています (そして、私は (疑似) 乱数生成の専門家ではありません)。これが最も偏りのないシャッフルの実装であることを確認したいだけです。
draw_t
はバイト型です ( typedef
'd to unsigned char
)。items
リスト内のアイテムの数です。以下のコードを含めましたrandom::get( draw_t max )
。
for( draw_t pull_index = (items - 1); pull_index > 1; pull_index-- )
{
draw_t push_index = random::get( pull_index );
draw_t push_item = this->_list[push_index];
draw_t pull_item = this->_list[pull_index];
this->_list[push_index] = pull_item;
this->_list[pull_index] = push_item;
}
私が使用しているランダム関数は、モジュロ バイアスを排除するように変更されています。RAND_MAX
に割り当てられrandom::_internal_max
ます。
draw_t random::get( draw_t max )
{
if( random::_is_seeded == false )
{
random::seed( );
}
int rand_value = random::_internal_max;
int max_rand_value = random::_internal_max - ( max - ( random::_internal_max % max ) );
do
{
rand_value = ::rand( );
} while( rand_value >= max_rand_value );
return static_cast< draw_t >( rand_value % max );
}