To UML Examples
Urn Class, source code file Urn1.cs
/// <summary> /// Simulate drawing balls from an urn (jar) without replacement. /// Use a bool array to keep track of the balls. /// </summary> public class Urn { // Private instance variables. private bool[] balls; private int _totalBalls; private Random r = new Random(); // Parameterized constructor. public Urn(int initialNumBalls) { // _totalBalls must be nonnegative. if (initialNumBalls > 0) { _totalBalls = initialNumBalls; } else { _totalBalls = 0; } // Initialize array of balls. balls = new bool[_totalBalls + 1]; for (int i = 0; i < _totalBalls; i++) { balls[i] = true; } } // Public read-only method. public int TotalBalls { get { return _totalBalls; } } // Public methods: // Return number of balls remaining. public int BallsRemaining() { int count = 0; for (int i = 0; i < _totalBalls; i++) { if (balls[i]) { count++; } } return count; } // Return true if all entries // in the balls array are false. public bool IsEmpty { get { for (int i = 0; i < _totalBalls; i++) { if (balls[i]) { return false; } } return true; } } // Draw a ball from urn. public int Draw() { int n = r.Next(0, _totalBalls); if (balls[n]) { balls[n] = false; return n + 1; } else { for (int i = (n + 1) % _totalBalls; i != n; i = (i + 1) % _totalBalls) { if (balls[i]) { balls[i] = false; return i + 1; } } return -1; } } // Print remaining balls in array. public override string ToString() { string b = ""; for (int i = 0; i < _totalBalls; i++) { if (balls[i]) { b += (i + 1).ToString() + " "; } } return "Remaining balls are " + b; } }