Answers for "Unity Shuffle list"

C#
0

Unity Shuffle list

"https://stackoverflow.com/a/63348412"

public static class ListUtils {  
  public static void Shuffle<T>(this IList<T> list, Random rnd)
  {
      for (var i = list.Count-1; i > 0; i--)
      {
          var randomIndex = rnd.Next(i + 1); //maxValue (i + 1) is EXCLUSIVE
          list.Swap(i, randomIndex); 
      }
  }

  public static void Swap<T>(this IList<T> list, int indexA, int indexB)
  {
     var temp = list[indexA];
     list[indexA] = list[indexB];
     list[indexB] = temp;
  }
}

//Usage
List<int> list = new List<int> { 1, 2, 3, 4};
list.Shuffle();
Posted by: Guest on July-02-2021

C# Answers by Framework

Browse Popular Code Answers by Language