「C♯で配列やコレクションをシャッフルする」を編集中
ナビゲーションに移動
検索に移動
この編集を取り消せます。 下記の差分を確認して、本当に取り消していいか検証してください。よろしければ変更を保存して取り消しを完了してください。
最新版 | 編集中の文章 | ||
3行目: | 3行目: | ||
[[ググる]]と出てきた[[LINQ]]使ったやつ。 | [[ググる]]と出てきた[[LINQ]]使ったやつ。 | ||
<source lang="csharp"> | <source lang="csharp"> | ||
− | |||
− | |||
− | |||
− | |||
public static class IEnumerableExtension | public static class IEnumerableExtension | ||
{ | { | ||
16行目: | 12行目: | ||
</source> | </source> | ||
− | + | 乱数生成器が指定できたほうがよくね?Randomクラスはアルゴリズムがよろしくないらしいが、シールドクラスではないのでメルセンヌ・ツイスタあたりを実装すればいい。 | |
− | |||
* [[C♯でメルセンヌ・ツイスタ乱数]] | * [[C♯でメルセンヌ・ツイスタ乱数]] | ||
<source lang="csharp"> | <source lang="csharp"> | ||
− | + | public static class IEnumerableExtensions | |
− | |||
− | |||
− | |||
− | public static class | ||
{ | { | ||
− | public static IEnumerable< | + | public static IEnumerable<TSource> Shuffle<TSource>(this IEnumerable<TSource> source, Random random) |
{ | { | ||
− | + | var copy = source.ToList(); | |
+ | |||
+ | int count = 0; | ||
+ | while (0 < (count = copy.Count)) | ||
+ | { | ||
+ | int index = random.Next(count); | ||
+ | yield return copy[index]; | ||
+ | copy.RemoveAt(index); | ||
+ | } | ||
} | } | ||