LoginSignup
12
7

More than 3 years have passed since last update.

配列とリストのシャッフル

Posted at

シャッフルのアルゴリズムは、計算量$ O(n) $で効率が良いことで有名な Fisher-Yates shuffle アルゴリズムを使います。

配列とリスト(List<T>)は IList<T> インターフェースを実装しているので、そこに拡張メソッドを定義すると両方で使えるようになります。

C# 2.0 以降、下限が 0 の一次元配列は自動的に IList<T> を実装します。 これにより、同じコードで配列や他のコレクション型を反復処理できるジェネリック メソッドを作成できます。
ジェネリックと配列 (C# プログラミング ガイド)

using System.Collections.Generic;
using UnityEngine;

public static class Extensions
{
    public static void Shuffle<T>(this IList<T> list) {
        for (int i = list.Count - 1; i > 0; i--) {
            int j = Random.Range(0, i + 1);
            var tmp = list[i];
            list[i] = list[j];
            list[j] = tmp;
        }
    }
}
12
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
7