Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Shuffle List


Here is a class ListExtension with a Shuffle extension method:

using System;
using System.Collections.Generic;

public static class ListExtension{

  public static void Shuffle<T>(this List<T> lst){
   Random randomSupplier = new Random(unchecked((int)DateTime.Now.Ticks)); 
   for(int i = 0; i < lst.Count - 1; i++){
     int r = randomSupplier.Next(i+1, lst.Count);

     // Swap list element i and r in lst:
     T remember = lst[r];
     lst[r] = lst[i];
     lst[i] = remember;
    }
  }
}

class App{
    public static void Main(){
     List<int> list = new List<int>(new int[]{5, 3, 2, 7, -4, 0});

     ReportList(list);

     list.Sort();
     ReportList(list);
     Console.WriteLine();

     for(int i = 1; i < 10; i++){
       list.Shuffle();
       ReportList(list);
       Console.WriteLine();
     }
  }

  public static void ReportList<T>(List<T> list){
    foreach(T el in list)
      Console.Write("{0, 3}", el);
    Console.WriteLine();
  }

}

Shuffle is a void method, which mutates the list by use of the indexer of the list. The Shuffle method mutates the list: It changes the order of the elements in the list. (Alternatively, we could have programmed a non-mutating variant that returns a new list which is shuffled relative to the original list). In a for-loop it swaps element number i and a random element - say number r - where i < r < this.Count.

In the App class, which contains a Main method, we shuffle a sample list of integers nine times in a row. Before each shuffling, we sort the list.

In a sample execution, I got the following output:

  5  3  2  7 -4  0
 -4  0  2  3  5  7

  5  7  0 -4  2  3

  2  5  7  3 -4  0

  7  2  0  5  3 -4

  3  5 -4  0  2  7

  7  0  3 -4  5  2

 -4  3  2  0  7  5

  2  7  5 -4  0  3

  5  3  0  2  7 -4

  7  0  5  3 -4  2