EgonMilanVotrubec

Array Shuffle Exgtension

Jul 7th, 2019
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.63 KB | None | 0 0
  1. namespace Test
  2. {
  3.     public class Test : MonoBehaviour
  4.     {
  5.         // Change this to your Images.
  6.         public string [ ] ImageNames = { "One", "Two", "Three", "Four" };
  7.         private int [ ] order;
  8.  
  9.         private void Awake ( )
  10.         {
  11.             var count = ImageNames.Length;
  12.  
  13.             // Create an order array that we will shuffle, leaving the original array intact.
  14.             order = new int [ ImageNames.Length ];
  15.             for ( int i = 0; i < count; i++ )
  16.                 order [ i ] = i;
  17.  
  18.             // Shuffle the order array, so that you can then select the right Images.
  19.             // This order array now holds a reference to the original Image array.
  20.             order.Shuffle ( );
  21.  
  22.             // Demonstrate that the order has been shuffled.
  23.             System.Text.StringBuilder sb = new System.Text.StringBuilder ( );
  24.             for ( int i = 0; i < order.Length; i++ )
  25.             {
  26.                 sb.Append ( ImageNames [ order[i] ] );
  27.                 if ( i < order.Length - 1 )
  28.                     sb.Append ( ", " );
  29.             }
  30.             Debug.Log ( sb.ToString ( ) );
  31.         }
  32.     }
  33.  
  34.     public static class ArrayExtension
  35.     {
  36.         private static readonly System.Random rng = new System.Random ( );
  37.         public static void Shuffle<T> ( this T [ ] array )
  38.         {
  39.             int n = array.Length;
  40.             while ( n > 1 )
  41.             {
  42.                 n--;
  43.                 int k = rng.Next ( n + 1 );
  44.                 T value = array [ k ];
  45.                 array [ k ] = array [ n ];
  46.                 array [ n ] = value;
  47.  
  48.             }
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment