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

Exercise solution:
Comparable Dice


We show a solution which relies on the non-generic version of class IComparable

The listing below is relatively long. You should focus on the method CompareTo in class Die. Notice the necessary casting of other to Die in the body of CompareTo.

Also notice the use of Array.Sort(Array) at the very bottom of the client class App. There are many overloaded Sort methods in class Array. According to the documentation, the method Array.Sort(Array) relies on Icomparable elements.

using System;

public class Die: IComparable {
  private int numberOfEyes;
  private Random randomNumberSupplier; 
  private const int maxNumberOfEyes = 6;

  public Die(){
    randomNumberSupplier = Random.Instance();
    numberOfEyes = NewTossHowManyEyes();
  }   
    
  public void Toss(){
    numberOfEyes = NewTossHowManyEyes();
  }

  private int NewTossHowManyEyes (){
    return randomNumberSupplier.Next(1,maxNumberOfEyes + 1);
  }

  public int NumberOfEyes() {
    return numberOfEyes;
  }

  public override String ToString(){
    return String.Format("[{0}]", numberOfEyes);
  }

  public int CompareTo(Object other){
    return this.numberOfEyes.CompareTo(((Die)other).numberOfEyes);
  }
}

public class Random {

  // Singleton pattern:
  // Keeps track of unique instance of this class
  private static Random uniqueInstance = null;

  // Holds the instance of System.Random
  private System.Random systemRandom;

  // Singleton pattern: Private constructor.
  private Random(){
    systemRandom = new System.Random(unchecked((int)DateTime.Now.Ticks));
  }

  public static Random Instance(){
    if (uniqueInstance == null)
      uniqueInstance = new Random();
    return uniqueInstance;
  }

  public int Next(int lower, int upper){
    // delegate to systemRandom
    return systemRandom.Next(lower,upper);
  }

}

class App{

  public static void Main(){

    Die[] dice = new Die[]{new Die(), new Die(), new Die(), new Die(),
                           new Die(), new Die(), new Die(), new Die(),
                          };
    Console.WriteLine("Before sorting");
    foreach(Die d in dice)
      Console.Write("{0} ", d);
    
    Console.WriteLine();

    Console.WriteLine("After sorting");
    Array.Sort(dice);
    foreach(Die d in dice)
      Console.Write("{0} ", d);

  }

}

The following output appears when I run the program:

 Before sorting
 [3] [6] [3] [6] [5] [3] [1] [1] 
 After sorting
 [1] [1] [3] [3] [3] [5] [6] [6]

You do probably not get the same output if you run the program, because randomness is involved in the class Die.