15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Unity(C#)でリスト・配列の中身をランダムに並び替え、ランダムに要素を取得

Posted at

###リストの中身をランダムに並び替え、ランダムな要素を取得

Unity関係ありませんが、結構使うので。たまに役に立ちます
ちなみにこの辺の投稿を参考にしています。
http://answers.unity3d.com/questions/486626/how-can-i-shuffle-alist.html

配列の中身を並び替え

public static T[] Shuffle<T>(this T[] array)
{
    var length = array.Length;
    var result = new T[length];
    Array.Copy(array, result, length);

    var random = new System.Random();
    int n = length;
    while (1 < n)
    {
        n--;
        int k = random.Next(n + 1);
        var tmp = result[k];
        result[k] = result[n];
        result[n] = tmp;
    }
    return result;
}

リストの中身を並び替え

public static List<GameObject> Fisher_Yates_CardDeck_Shuffle(List<GameObject> aList,int seed)
{

    System.Random _random = new System.Random(seed);

    GameObject myGO;

    int n = aList.Count;
    for (int i = 0; i < n; i++)
    {
        int r = i + (int)(_random.NextDouble() * (n - i));
        myGO = aList[r];
        aList[r] = aList[i];
        aList[i] = myGO;
    }

    return aList;
}

リストと配列の要素をランダムに取得

ついでに配列とリストの要素をランダムに取得するメソッドです。

配列の要素をランダムに取得

public static T GetRandom<T>(this T[] self)
{
    return self[UnityEngine.Random.Range(0, self.Length)];
}

リストの要素をランダムに取得

public static T GetRandom<T>(this IList<T> self)
{
    return self[UnityEngine.Random.Range(0, self.Count)];
}
15
15
1

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
15
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?