|
| 1 | +using System.Collections; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | + |
| 5 | +namespace DataStructures; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// Implementation of a Bag data structure using a hashmap that allows adding items and iterating through them. |
| 9 | +/// Items with the same value are stored as a single entry with a count. |
| 10 | +/// </summary> |
| 11 | +/// <typeparam name="T">Generic Type.</typeparam> |
| 12 | +public class Bag<T> : IEnumerable<T> where T : notnull |
| 13 | +{ |
| 14 | + private readonly Dictionary<T, int> items; |
| 15 | + |
| 16 | + /// <summary> |
| 17 | + /// Initializes a new instance of the <see cref="Bag{T}" /> class. |
| 18 | + /// </summary> |
| 19 | + public Bag() |
| 20 | + { |
| 21 | + items = []; |
| 22 | + } |
| 23 | + |
| 24 | + /// <summary> |
| 25 | + /// Adds an item to the bag. |
| 26 | + /// </summary> |
| 27 | + public void Add(T item) |
| 28 | + { |
| 29 | + if (items.TryGetValue(item, out var count)) |
| 30 | + { |
| 31 | + items[item] = count + 1; |
| 32 | + } |
| 33 | + else |
| 34 | + { |
| 35 | + items[item] = 1; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + /// <summary> |
| 40 | + /// Clears the bag. |
| 41 | + /// </summary> |
| 42 | + public void Clear() => items.Clear(); |
| 43 | + |
| 44 | + /// <summary> |
| 45 | + /// Gets the number of items in the bag. |
| 46 | + /// </summary> |
| 47 | + public int Count => items.Values.Sum(); |
| 48 | + |
| 49 | + /// <summary> |
| 50 | + /// Returns a boolean indicating whether the bag is empty. |
| 51 | + /// </summary> |
| 52 | + public bool IsEmpty() => items.Count == 0; |
| 53 | + |
| 54 | + /// <summary> |
| 55 | + /// Returns an enumerator that iterates through the bag. |
| 56 | + /// </summary> |
| 57 | + public IEnumerator<T> GetEnumerator() |
| 58 | + { |
| 59 | + foreach (var pair in items) |
| 60 | + { |
| 61 | + for (var i = 0; i < pair.Value; i++) |
| 62 | + { |
| 63 | + yield return pair.Key; |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + /// <summary> |
| 69 | + /// Returns an enumerator that iterates through the bag. |
| 70 | + /// </summary> |
| 71 | + IEnumerator IEnumerable.GetEnumerator() |
| 72 | + { |
| 73 | + return GetEnumerator(); |
| 74 | + } |
| 75 | +} |
0 commit comments