public void RandomAddDelete() { const int SIZE = 5000; var count = new int[SIZE]; var rand = new Random(3); var bag1 = new Bag <int>(); bool b; // Add and delete values at random. for (int i = 0; i < SIZE * 100; ++i) { int v = rand.Next(SIZE); Assert.AreEqual(count[v], bag1.NumberOfCopies(v)); if (count[v] > 0) { Assert.IsTrue(bag1.Contains(v)); } if (count[v] == 0 || rand.Next(2) == 1) { // Add to the bag. bag1.Add(v); count[v] += 1; } else { // Remove from the bag. b = bag1.Remove(v); Assert.IsTrue(b); count[v] -= 1; } } // Make sure the bag has all the correct values, not necessarily in order. int c = count.Sum(); Assert.AreEqual(c, bag1.Count); foreach (var v in bag1) { --count[v]; } foreach (var x in count) { Assert.AreEqual(0, x); } }