「C♯で配列やコレクションをシャッフルする」の版間の差分

提供: MonoBook
ナビゲーションに移動 検索に移動
(ページの作成:「C#にもPHPのshuffle(&Array)のパクリが欲しい。 ググると出てきたLINQ使ったやつ。 <source lang="csharp"> public static class IEnumerabl…」)
 
3行目: 3行目:
 
[[ググる]]と出てきた[[LINQ]]使ったやつ。
 
[[ググる]]と出てきた[[LINQ]]使ったやつ。
 
<source lang="csharp">
 
<source lang="csharp">
 +
    using System;
 +
    using System.Collections.Generic;
 +
    using System.Linq;
 +
 
     public static class IEnumerableExtension
 
     public static class IEnumerableExtension
 
     {
 
     {
12行目: 16行目:
 
</source>
 
</source>
  
乱数生成器が指定できたほうがよくね?Randomクラスはアルゴリズムがよろしくないらしいが、シールドクラスではないのでメルセンヌ・ツイスタあたりを実装すればいい。
+
 
 +
乱数生成器が指定できたほうがよくね?Randomクラスは[[アルゴリズム]]がよろしくないらしいが、シールドクラスではないのでメルセンヌ・ツイスタあたりを実装すればいい。
 
* [[C♯でメルセンヌ・ツイスタ乱数]]
 
* [[C♯でメルセンヌ・ツイスタ乱数]]
 
<source lang="csharp">
 
<source lang="csharp">
     public static class IEnumerableExtensions
+
    using System;
 +
    using System.Collections.Generic;
 +
    using System.Linq;
 +
 
 +
     public static class IEnumerableExtension
 
     {
 
     {
         public static IEnumerable<TSource> Shuffle<TSource>(this IEnumerable<TSource> source, Random random)
+
         public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> collection, Random random)
 
         {
 
         {
             var copy = source.ToList();
+
             return collection.OrderBy(i => random.Next());
 
 
            int count = 0;
 
            while (0 < (count = copy.Count))
 
            {
 
                int index = random.Next(count);
 
                yield return copy[index];
 
                copy.RemoveAt(index);
 
            }
 
 
         }
 
         }
  

2019年11月26日 (火) 08:13時点における版

C#にもPHPのshuffle(&Array)のパクリが欲しい。

ググると出てきたLINQ使ったやつ。

    using System;
    using System.Collections.Generic;
    using System.Linq;

    public static class IEnumerableExtension
    {
        public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> collection)
        {
            return collection.OrderBy(i => Guid.NewGuid());
        }
    }


乱数生成器が指定できたほうがよくね?Randomクラスはアルゴリズムがよろしくないらしいが、シールドクラスではないのでメルセンヌ・ツイスタあたりを実装すればいい。

    using System;
    using System.Collections.Generic;
    using System.Linq;

    public static class IEnumerableExtension
    {
        public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> collection, Random random)
        {
            return collection.OrderBy(i => random.Next());
        }

        public static IEnumerable<TSource> Shuffle<TSource>(this IEnumerable<TSource> source)
        {
            return source.Shuffle<TSource>(new Random());
        }
    }