Skip to content

Commit b09935a

Browse files
committed
Add a basic Bag data structure
1 parent f1fde96 commit b09935a

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

DataStructures/Bag.cs

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
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+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,7 @@ find more than one implementation for the same objective but using different alg
247247
* [Levenshtein Distance](./Algorithms/Problems/DynamicProgramming/LevenshteinDistance/LevenshteinDistance.cs)
248248

249249
* [Data Structures](./DataStructures)
250+
* [Bag](./DataStructures/Bag.cs)
250251
* [Bit Array](./DataStructures/BitArray.cs)
251252
* [Timeline](./DataStructures/Timeline.cs)
252253
* [Segment Trees](./DataStructures/SegmentTrees)

0 commit comments

Comments
 (0)