Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
153 changes: 153 additions & 0 deletions DataStructures.Tests/BagTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
using System.Collections.Generic;
using System.Linq;
using DataStructures.Bag;
using FluentAssertions;
using NUnit.Framework;

namespace DataStructures.Tests;

internal class BagTests
{
[Test]
public void Add_ShouldIncreaseCount()
{
// Arrange & Act
var bag = new Bag<int>
{
1,
2,
1
};

// Assert
bag.Count.Should().Be(3);
}

[Test]
public void Add_ShouldHandleDuplicates()
{
// Arrange & Act
var bag = new Bag<string>
{
"apple",
"apple"
};

// Assert
bag.Count.Should().Be(2);
bag.Should().Contain("apple");
}

[Test]
public void Clear_ShouldEmptyTheBag()
{
// Arrange
var bag = new Bag<int>
{
1,
2
};

// Act
bag.Clear();

// Assert
bag.IsEmpty().Should().BeTrue();
bag.Count.Should().Be(0);
}

[Test]
public void IsEmpty_ShouldReturnTrueForEmptyBag()
{
// Arrange
var bag = new Bag<int>();

// Act & Assert
bag.IsEmpty().Should().BeTrue();
}

[Test]
public void IsEmpty_ShouldReturnFalseForNonEmptyBag()
{
// Arrange
var bag = new Bag<int>
{
1
};

// Act & Assert
bag.IsEmpty().Should().BeFalse();
}

[Test]
public void GetEnumerator_ShouldIterateAllItems()
{
// Arrange
var bag = new Bag<int>
{
1,
2,
1
};

// Act
var items = bag.ToList();

// Assert
items.Count.Should().Be(3);
items.Should().Contain(1);
items.Should().Contain(2);
}

[Test]
public void Count_ShouldReturnZeroForEmptyBag()
{
// Arrange
var bag = new Bag<int>();

// Act & Assert
bag.Count.Should().Be(0);
}

[Test]
public void Count_ShouldReturnCorrectCount()
{
// Arrange
var bag = new Bag<int>
{
1,
2,
1
};

// Act & Assert
bag.Count.Should().Be(3);
}

[Test]
public void IEnumerableGetEnumerator_YieldsAllItemsWithCorrectMultiplicity()
{
// Arrange
var bag = new Bag<string>
{
"apple",
"banana",
"apple"
};
var genericBag = bag as System.Collections.IEnumerable;

// Act
var enumerator = genericBag.GetEnumerator();
var items = new List<object>();
while (enumerator.MoveNext())
{
items.Add(enumerator.Current!);
}

// Assert
items.Count(i => (string)i == "apple").Should().Be(2);
items.Count(i => (string)i == "banana").Should().Be(1);
items.Count.Should().Be(3);
items.Should().BeEquivalentTo(["apple", "apple", "banana"]);
}
}
106 changes: 106 additions & 0 deletions DataStructures/Bag/Bag.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
using System.Collections;
using System.Collections.Generic;

namespace DataStructures.Bag;

/// <summary>
/// Implementation of a Bag (or multiset) data structure using a basic linked list.
/// </summary>
/// <remarks>
/// A bag (or multiset, or mset) is a modification of the concept of a set that, unlike a set, allows for multiple instances for each of its elements.
/// The number of instances given for each element is called the multiplicity of that element in the multiset.
/// As a consequence, an infinite number of multisets exist that contain only elements a and b, but vary in the multiplicities of their elements.
/// See https://en.wikipedia.org/wiki/Multiset for more information.
/// </remarks>
/// <typeparam name="T">Generic Type.</typeparam>
public class Bag<T> : IEnumerable<T> where T : notnull
{
private BagNode<T>? head;
private int totalCount;

/// <summary>
/// Initializes a new instance of the <see cref="Bag{T}" /> class.
/// </summary>
public Bag()
{
head = null;
totalCount = 0;
}

/// <summary>
/// Adds an item to the bag. If the item already exists, increases its multiplicity.
/// </summary>
public void Add(T item)
{
// If the bag is empty, create the first node
if (head == null)
{
head = new BagNode<T>(item);
totalCount = 1;
return;
}

// Check if item already exists
var current = head;
BagNode<T>? previous = null;

while (current != null)
{
if (EqualityComparer<T>.Default.Equals(current.Item, item))
{
current.Multiplicity++;
totalCount++;
return;
}

previous = current;
current = current.Next;
}

previous!.Next = new BagNode<T>(item);
totalCount++;
}

/// <summary>
/// Clears the bag.
/// </summary>
public void Clear()
{
head = null;
totalCount = 0;
}

/// <summary>
/// Gets the number of items in the bag.
/// </summary>
public int Count => totalCount;

/// <summary>
/// Returns a boolean indicating whether the bag is empty.
/// </summary>
public bool IsEmpty() => head == null;

/// <summary>
/// Returns an enumerator that iterates through the bag.
/// </summary>
public IEnumerator<T> GetEnumerator()
{
var current = head;

while (current != null)
{
// Yield the item as many times as its multiplicity, pretending they are separate items
for (var i = 0; i < current.Multiplicity; i++)
{
yield return current.Item;
}

current = current.Next;
}
}

/// <summary>
/// Returns an enumerator that iterates through the bag.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
14 changes: 14 additions & 0 deletions DataStructures/Bag/BagNode.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace DataStructures.Bag;

/// <summary>
/// Generic node class for Bag.
/// </summary>
/// <typeparam name="T">A type for node.</typeparam>
public class BagNode<T>(T item)
{
public T Item { get; } = item;

public int Multiplicity { get; set; } = 1;

public BagNode<T>? Next { get; set; }
}
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,7 @@ find more than one implementation for the same objective but using different alg
* [Levenshtein Distance](./Algorithms/Problems/DynamicProgramming/LevenshteinDistance/LevenshteinDistance.cs)

* [Data Structures](./DataStructures)
* [Bag](./DataStructures/Bag)
* [Bit Array](./DataStructures/BitArray.cs)
* [Timeline](./DataStructures/Timeline.cs)
* [Segment Trees](./DataStructures/SegmentTrees)
Expand Down