diff --git a/DataStructures.Tests/AATreeTests.cs b/DataStructures.Tests/AATreeTests.cs index e077a3a1..9a34ad8f 100644 --- a/DataStructures.Tests/AATreeTests.cs +++ b/DataStructures.Tests/AATreeTests.cs @@ -1,297 +1,296 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using DataStructures.AATree; using FluentAssertions; using NUnit.Framework; -namespace DataStructures.Tests +namespace DataStructures.Tests; + +internal class AaTreeTests { - internal class AaTreeTests + [Test] + public void Constructor_UseCustomComparer_FormsCorrectTree() { - [Test] - public void Constructor_UseCustomComparer_FormsCorrectTree() - { - var tree = new AaTree(Comparer.Create((x, y) => y.CompareTo(x))); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.GetMax().Should().Be(1); - tree.GetMin().Should().Be(10); - tree.GetKeysInOrder().SequenceEqual(new[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }).Should().BeTrue(); - Validate(tree.Root); - } + var tree = new AaTree(Comparer.Create((x, y) => y.CompareTo(x))); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.GetMax().Should().Be(1); + tree.GetMin().Should().Be(10); + tree.GetKeysInOrder().SequenceEqual(new[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }).Should().BeTrue(); + Validate(tree.Root); + } - [Test] - public void Add_MultipleKeys_FormsCorrectTree() - { - var tree = new AaTree(); - - foreach (var elem in new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) - { - tree.Add(elem); - tree.Count.Should().Be(elem); - tree.Contains(elem).Should().BeTrue(); - } - - tree.GetKeysInOrder().SequenceEqual(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Should().BeTrue(); - tree.GetKeysPostOrder().SequenceEqual(new[] { 1, 3, 2, 5, 7, 10, 9, 8, 6, 4 }).Should().BeTrue(); - Validate(tree.Root); - } + [Test] + public void Add_MultipleKeys_FormsCorrectTree() + { + var tree = new AaTree(); - [Test] - public void Add_KeyAlreadyInTree_ThrowsException() + foreach (var elem in new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) { - var tree = new AaTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - Assert.Throws(() => tree.Add(1)); + tree.Add(elem); + tree.Count.Should().Be(elem); + tree.Contains(elem).Should().BeTrue(); } - [Test] - public void AddRange_MultipleKeys_FormsCorrectTree() - { - var tree = new AaTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.Count.Should().Be(10); - tree.GetKeysInOrder().SequenceEqual(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Should().BeTrue(); - tree.GetKeysPostOrder().SequenceEqual(new[] { 1, 3, 2, 5, 7, 10, 9, 8, 6, 4 }).Should().BeTrue(); - Validate(tree.Root); - } + tree.GetKeysInOrder().SequenceEqual(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Should().BeTrue(); + tree.GetKeysPostOrder().SequenceEqual(new[] { 1, 3, 2, 5, 7, 10, 9, 8, 6, 4 }).Should().BeTrue(); + Validate(tree.Root); + } - [Test] - public void Remove_MultipleKeys_TreeStillValid() - { - var tree = new AaTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + [Test] + public void Add_KeyAlreadyInTree_ThrowsException() + { + var tree = new AaTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + Assert.Throws(() => tree.Add(1)); + } - Remove(4).Should().NotThrow(); - tree.Contains(4).Should().BeFalse(); - tree.Count.Should().Be(9); + [Test] + public void AddRange_MultipleKeys_FormsCorrectTree() + { + var tree = new AaTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.Count.Should().Be(10); + tree.GetKeysInOrder().SequenceEqual(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Should().BeTrue(); + tree.GetKeysPostOrder().SequenceEqual(new[] { 1, 3, 2, 5, 7, 10, 9, 8, 6, 4 }).Should().BeTrue(); + Validate(tree.Root); + } - Remove(8).Should().NotThrow(); - tree.Contains(8).Should().BeFalse(); - tree.Count.Should().Be(8); + [Test] + public void Remove_MultipleKeys_TreeStillValid() + { + var tree = new AaTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - Remove(1).Should().NotThrow(); - tree.Contains(1).Should().BeFalse(); - tree.Count.Should().Be(7); + Remove(4).Should().NotThrow(); + tree.Contains(4).Should().BeFalse(); + tree.Count.Should().Be(9); - Validate(tree.Root); + Remove(8).Should().NotThrow(); + tree.Contains(8).Should().BeFalse(); + tree.Count.Should().Be(8); - Action Remove(int x) => () => tree.Remove(x); - } + Remove(1).Should().NotThrow(); + tree.Contains(1).Should().BeFalse(); + tree.Count.Should().Be(7); - [Test] - public void Remove_KeyNotInTree_Throws() - { - var tree = new AaTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + Validate(tree.Root); - Action act = () => tree.Remove(999); - act.Should().Throw(); - } + Action Remove(int x) => () => tree.Remove(x); + } - [Test] - public void Remove_EmptyTree_Throws() - { - var tree = new AaTree(); + [Test] + public void Remove_KeyNotInTree_Throws() + { + var tree = new AaTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - Action act = () => tree.Remove(999); - act.Should().Throw(); - } + Action act = () => tree.Remove(999); + act.Should().Throw(); + } - [Test] - public void Contains_NonEmptyTree_ReturnsCorrectAnswer() - { - var tree = new AaTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.Contains(6).Should().BeTrue(); - tree.Contains(999).Should().BeFalse(); - } + [Test] + public void Remove_EmptyTree_Throws() + { + var tree = new AaTree(); - [Test] - public void Contains_EmptyTree_ReturnsFalse() - { - var tree = new AaTree(); - tree.Contains(999).Should().BeFalse(); - } + Action act = () => tree.Remove(999); + act.Should().Throw(); + } - [Test] - public void GetMax_NonEmptyTree_ReturnsCorrectAnswer() - { - var tree = new AaTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.GetMax().Should().Be(10); - } + [Test] + public void Contains_NonEmptyTree_ReturnsCorrectAnswer() + { + var tree = new AaTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.Contains(6).Should().BeTrue(); + tree.Contains(999).Should().BeFalse(); + } - [Test] - public void GetMax_EmptyTree_ThrowsCorrectException() - { - var tree = new AaTree(); - Assert.Throws(() => tree.GetMax()); - } + [Test] + public void Contains_EmptyTree_ReturnsFalse() + { + var tree = new AaTree(); + tree.Contains(999).Should().BeFalse(); + } - [Test] - public void GetMin_NonEmptyTree_ReturnsCorrectAnswer() - { - var tree = new AaTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.GetMin().Should().Be(1); - } + [Test] + public void GetMax_NonEmptyTree_ReturnsCorrectAnswer() + { + var tree = new AaTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.GetMax().Should().Be(10); + } - [Test] - public void GetMin_EmptyTree_ThrowsCorrectException() - { - var tree = new AaTree(); - Assert.Throws(() => tree.GetMin()); - } + [Test] + public void GetMax_EmptyTree_ThrowsCorrectException() + { + var tree = new AaTree(); + Assert.Throws(() => tree.GetMax()); + } - [Test] - public void GetKeysInOrder_NonEmptyTree_ReturnsCorrectAnswer() - { - var tree = new AaTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.GetKeysInOrder().SequenceEqual(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Should().BeTrue(); - } + [Test] + public void GetMin_NonEmptyTree_ReturnsCorrectAnswer() + { + var tree = new AaTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.GetMin().Should().Be(1); + } - [Test] - public void GetKeysInOrder_EmptyTree_ReturnsCorrectAnswer() - { - var tree = new AaTree(); - tree.GetKeysInOrder().ToList().Count.Should().Be(0); - } + [Test] + public void GetMin_EmptyTree_ThrowsCorrectException() + { + var tree = new AaTree(); + Assert.Throws(() => tree.GetMin()); + } - [Test] - public void GetKeysPreOrder_NonEmptyTree_ReturnsCorrectAnswer() - { - var tree = new AaTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.GetKeysPreOrder().SequenceEqual(new[] { 4, 2, 1, 3, 6, 5, 8, 7, 9, 10 }) - .Should().BeTrue(); - } + [Test] + public void GetKeysInOrder_NonEmptyTree_ReturnsCorrectAnswer() + { + var tree = new AaTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.GetKeysInOrder().SequenceEqual(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Should().BeTrue(); + } - [Test] - public void GetKeysPreOrder_EmptyTree_ReturnsCorrectAnswer() - { - var tree = new AaTree(); - tree.GetKeysPreOrder().ToList().Count.Should().Be(0); - } + [Test] + public void GetKeysInOrder_EmptyTree_ReturnsCorrectAnswer() + { + var tree = new AaTree(); + tree.GetKeysInOrder().ToList().Count.Should().Be(0); + } - [Test] - public void GetKeysPostOrder_NonEmptyTree_ReturnsCorrectAnswer() - { - var tree = new AaTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.GetKeysPostOrder().SequenceEqual(new[] { 1, 3, 2, 5, 7, 10, 9, 8, 6, 4 }) - .Should().BeTrue(); - } + [Test] + public void GetKeysPreOrder_NonEmptyTree_ReturnsCorrectAnswer() + { + var tree = new AaTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.GetKeysPreOrder().SequenceEqual(new[] { 4, 2, 1, 3, 6, 5, 8, 7, 9, 10 }) + .Should().BeTrue(); + } - [Test] - public void GetKeysPostOrder_EmptyTree_ReturnsCorrectAnswer() - { - var tree = new AaTree(); - tree.GetKeysPostOrder().ToList().Count.Should().Be(0); - } + [Test] + public void GetKeysPreOrder_EmptyTree_ReturnsCorrectAnswer() + { + var tree = new AaTree(); + tree.GetKeysPreOrder().ToList().Count.Should().Be(0); + } + + [Test] + public void GetKeysPostOrder_NonEmptyTree_ReturnsCorrectAnswer() + { + var tree = new AaTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.GetKeysPostOrder().SequenceEqual(new[] { 1, 3, 2, 5, 7, 10, 9, 8, 6, 4 }) + .Should().BeTrue(); + } - /// - /// Checks various properties to determine if the tree is a valid AA Tree. - /// Throws exceptions if properties are violated. - /// Useful for debugging. - /// - /// - /// The properties that are checked are: - /// - /// The level of every leaf node is one. - /// The level of every left child is exactly one less than that of its parent. - /// The level of every right child is equal to or one less than that of its parent. - /// The level of every right grandchild is strictly less than that of its grandparent. - /// Every node of level greater than one has two children. - /// - /// More information: https://en.wikipedia.org/wiki/AA_tree . - /// - /// The node to check from. - /// true if node passes all checks, false otherwise. - private static bool Validate(AaTreeNode? node) + [Test] + public void GetKeysPostOrder_EmptyTree_ReturnsCorrectAnswer() + { + var tree = new AaTree(); + tree.GetKeysPostOrder().ToList().Count.Should().Be(0); + } + + /// + /// Checks various properties to determine if the tree is a valid AA Tree. + /// Throws exceptions if properties are violated. + /// Useful for debugging. + /// + /// + /// The properties that are checked are: + /// + /// The level of every leaf node is one. + /// The level of every left child is exactly one less than that of its parent. + /// The level of every right child is equal to or one less than that of its parent. + /// The level of every right grandchild is strictly less than that of its grandparent. + /// Every node of level greater than one has two children. + /// + /// More information: https://en.wikipedia.org/wiki/AA_tree . + /// + /// The node to check from. + /// true if node passes all checks, false otherwise. + private static bool Validate(AaTreeNode? node) + { + if (node is null) { - if (node is null) - { - return true; - } + return true; + } - // Check level == 1 if node if a leaf node. - var leafNodeCheck = CheckLeafNode(node); + // Check level == 1 if node if a leaf node. + var leafNodeCheck = CheckLeafNode(node); - // Check level of left child is exactly one less than parent. - var leftCheck = CheckLeftSubtree(node); + // Check level of left child is exactly one less than parent. + var leftCheck = CheckLeftSubtree(node); - // Check level of right child is equal or one less than parent. - var rightCheck = CheckRightSubtree(node); + // Check level of right child is equal or one less than parent. + var rightCheck = CheckRightSubtree(node); - // Check right grandchild level is less than node. - var grandchildCheck = CheckRightGrandChild(node); + // Check right grandchild level is less than node. + var grandchildCheck = CheckRightGrandChild(node); - // Check if node has two children if not leaf. - var nonLeafChildrenCheck = CheckNonLeafChildren(node); + // Check if node has two children if not leaf. + var nonLeafChildrenCheck = CheckNonLeafChildren(node); - var thisNodeResult = leafNodeCheck && leftCheck && rightCheck; - thisNodeResult = thisNodeResult && grandchildCheck && nonLeafChildrenCheck; + var thisNodeResult = leafNodeCheck && leftCheck && rightCheck; + thisNodeResult = thisNodeResult && grandchildCheck && nonLeafChildrenCheck; - return thisNodeResult && Validate(node.Left) && Validate(node.Right); - } + return thisNodeResult && Validate(node.Left) && Validate(node.Right); + } - /// - /// Checks if node is a leaf, and if so if its level is 1. - /// - /// The node to check. - /// true if node passes check, false otherwise. - private static bool CheckLeafNode(AaTreeNode node) - { - var condition = node.Left is null && node.Right is null && node.Level != 1; - return !condition; - } + /// + /// Checks if node is a leaf, and if so if its level is 1. + /// + /// The node to check. + /// true if node passes check, false otherwise. + private static bool CheckLeafNode(AaTreeNode node) + { + var condition = node.Left is null && node.Right is null && node.Level != 1; + return !condition; + } - /// - /// Checks if left node's level is exactly one less than node's level. - /// - /// The node to check. - /// true if node passes check, false otherwise. - private static bool CheckLeftSubtree(AaTreeNode node) - { - var condition = node.Left is not null && node.Level - node.Left.Level != 1; - return !condition; - } + /// + /// Checks if left node's level is exactly one less than node's level. + /// + /// The node to check. + /// true if node passes check, false otherwise. + private static bool CheckLeftSubtree(AaTreeNode node) + { + var condition = node.Left is not null && node.Level - node.Left.Level != 1; + return !condition; + } - /// - /// Checks if right node's level is either equal to or one less than node's level. - /// - /// The node to check. - /// true if node passes check, false otherwise. - private static bool CheckRightSubtree(AaTreeNode node) - { - var condition = node.Right is not null && - node.Level - node.Right.Level != 1 && - node.Level != node.Right.Level; - return !condition; - } + /// + /// Checks if right node's level is either equal to or one less than node's level. + /// + /// The node to check. + /// true if node passes check, false otherwise. + private static bool CheckRightSubtree(AaTreeNode node) + { + var condition = node.Right is not null && + node.Level - node.Right.Level != 1 && + node.Level != node.Right.Level; + return !condition; + } - /// - /// Checks if right grandchild's (right node's right node) level is less than node. - /// - /// The node to check. - /// true if node passes check, false otherwise. - private static bool CheckRightGrandChild(AaTreeNode node) - { - var condition = node.Right?.Right is not null && node.Right.Level < node.Right.Right.Level; - return !condition; - } + /// + /// Checks if right grandchild's (right node's right node) level is less than node. + /// + /// The node to check. + /// true if node passes check, false otherwise. + private static bool CheckRightGrandChild(AaTreeNode node) + { + var condition = node.Right?.Right is not null && node.Right.Level < node.Right.Right.Level; + return !condition; + } - /// - /// Checks if node is not a leaf, and if so if it has two children. - /// - /// The node to check. - /// true if node passes check, false otherwise. - private static bool CheckNonLeafChildren(AaTreeNode node) - { - var condition = node.Level > 1 && (node.Left is null || node.Right is null); - return !condition; - } + /// + /// Checks if node is not a leaf, and if so if it has two children. + /// + /// The node to check. + /// true if node passes check, false otherwise. + private static bool CheckNonLeafChildren(AaTreeNode node) + { + var condition = node.Level > 1 && (node.Left is null || node.Right is null); + return !condition; } } diff --git a/DataStructures.Tests/AVLTreeTests.cs b/DataStructures.Tests/AVLTreeTests.cs index f02d5b78..e3e3fe5e 100644 --- a/DataStructures.Tests/AVLTreeTests.cs +++ b/DataStructures.Tests/AVLTreeTests.cs @@ -6,384 +6,383 @@ using NUnit.Framework; using static FluentAssertions.FluentActions; -namespace DataStructures.Tests +namespace DataStructures.Tests; + +internal class AvlTreeTests { - internal class AvlTreeTests + private static readonly int[] Data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + private static readonly int[] PreOrder = { 4, 2, 1, 3, 8, 6, 5, 7, 9, 10 }; + private static readonly int[] PostOrder = { 1, 3, 2, 5, 7, 6, 10, 9, 8, 4 }; + + [Test] + public void Constructor_UseCustomComparer_FormsCorrectTree() { - private static readonly int[] Data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - private static readonly int[] PreOrder = { 4, 2, 1, 3, 8, 6, 5, 7, 9, 10 }; - private static readonly int[] PostOrder = { 1, 3, 2, 5, 7, 6, 10, 9, 8, 4 }; + var tree = new AvlTree(Comparer.Create((x, y) => y.CompareTo(x))); - [Test] - public void Constructor_UseCustomComparer_FormsCorrectTree() - { - var tree = new AvlTree(Comparer.Create((x, y) => y.CompareTo(x))); + tree.AddRange(Data); - tree.AddRange(Data); + tree.GetMin().Should().Be(10); - tree.GetMin().Should().Be(10); + tree.GetMax().Should().Be(1); - tree.GetMax().Should().Be(1); + tree.GetKeysInOrder() + .Should() + .BeEquivalentTo( + Data.Reverse(), + config => config.WithStrictOrdering()); + } - tree.GetKeysInOrder() - .Should() - .BeEquivalentTo( - Data.Reverse(), - config => config.WithStrictOrdering()); - } + [Test] + public void Add_MultipleKeys_FormsCorrectTree() + { + var tree = new AvlTree(); - [Test] - public void Add_MultipleKeys_FormsCorrectTree() + for (var i = 0; i < Data.Length; ++i) { - var tree = new AvlTree(); - - for (var i = 0; i < Data.Length; ++i) - { - tree.Add(Data[i]); - tree.Count.Should().Be(i + 1); - } - - tree.GetKeysInOrder() - .Should() - .BeEquivalentTo( - Data, - config => config.WithStrictOrdering()); - - tree.GetKeysPreOrder() - .Should() - .BeEquivalentTo( - PreOrder, - config => config.WithStrictOrdering()); - - tree.GetKeysPostOrder() - .Should() - .BeEquivalentTo( - PostOrder, - config => config.WithStrictOrdering()); + tree.Add(Data[i]); + tree.Count.Should().Be(i + 1); } - [Test] - public void Add_KeyAlreadyInTree_ThrowsException() - { - var tree = new AvlTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5 }); + tree.GetKeysInOrder() + .Should() + .BeEquivalentTo( + Data, + config => config.WithStrictOrdering()); + + tree.GetKeysPreOrder() + .Should() + .BeEquivalentTo( + PreOrder, + config => config.WithStrictOrdering()); + + tree.GetKeysPostOrder() + .Should() + .BeEquivalentTo( + PostOrder, + config => config.WithStrictOrdering()); + } - Invoking(() => tree.Add(1)).Should().ThrowExactly(); - } + [Test] + public void Add_KeyAlreadyInTree_ThrowsException() + { + var tree = new AvlTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5 }); - [Test] - public void AddRange_MultipleKeys_FormsCorrectTree() - { - var tree = new AvlTree(); - tree.AddRange(new[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g' }); - - tree.Count.Should().Be(7); - - tree.GetKeysInOrder() - .Should() - .BeEquivalentTo( - new[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g' }, - config => config.WithStrictOrdering()); - - tree.GetKeysPreOrder() - .Should() - .BeEquivalentTo( - new[] { 'd', 'b', 'a', 'c', 'f', 'e', 'g' }, - config => config.WithStrictOrdering()); - - tree.GetKeysPostOrder() - .Should() - .BeEquivalentTo( - new[] { 'a', 'c', 'b', 'e', 'g', 'f', 'd' }, - config => config.WithStrictOrdering()); - } + Invoking(() => tree.Add(1)).Should().ThrowExactly(); + } - [Test] - public void Remove_MultipleKeys_TreeStillValid() - { - var tree = new AvlTree(); - tree.AddRange(Data); - - tree.Remove(7); - - tree.Count.Should().Be(9); - tree.Contains(7).Should().BeFalse(); - - tree.GetKeysInOrder() - .Should() - .BeEquivalentTo( - new[] { 1, 2, 3, 4, 5, 6, 8, 9, 10 }, - config => config.WithStrictOrdering()); - - tree.GetKeysPreOrder() - .Should() - .BeEquivalentTo( - new[] { 4, 2, 1, 3, 8, 6, 5, 9, 10 }, - config => config.WithStrictOrdering()); - - tree.GetKeysPostOrder() - .Should() - .BeEquivalentTo( - new[] { 1, 3, 2, 5, 6, 10, 9, 8, 4 }, - config => config.WithStrictOrdering()); - - tree.Remove(2); - - tree.Count.Should().Be(8); - tree.Contains(2).Should().BeFalse(); - - tree.Remove(1); - - tree.Count.Should().Be(7); - tree.Contains(1).Should().BeFalse(); - - tree.GetKeysInOrder() - .Should() - .BeEquivalentTo( - new[] { 3, 4, 5, 6, 8, 9, 10 }, - config => config.WithStrictOrdering()); - - tree.GetKeysPreOrder() - .Should() - .BeEquivalentTo( - new[] { 8, 4, 3, 6, 5, 9, 10 }, - config => config.WithStrictOrdering()); - - tree.GetKeysPostOrder() - .Should() - .BeEquivalentTo( - new[] { 3, 5, 6, 4, 10, 9, 8 }, - config => config.WithStrictOrdering()); - - tree.Remove(9); - - tree.Count.Should().Be(6); - tree.Contains(9).Should().BeFalse(); - - tree.GetKeysInOrder() - .Should() - .BeEquivalentTo( - new[] { 3, 4, 5, 6, 8, 10 }, - config => config.WithStrictOrdering()); - - tree.GetKeysPreOrder() - .Should() - .BeEquivalentTo( - new[] { 6, 4, 3, 5, 8, 10 }, - config => config.WithStrictOrdering()); - - tree.GetKeysPostOrder() - .Should() - .BeEquivalentTo( - new[] { 3, 5, 4, 10, 8, 6 }, - config => config.WithStrictOrdering()); - - tree.Remove(3); - tree.Remove(4); - tree.Remove(5); - tree.Remove(6); - tree.Remove(8); - tree.Remove(10); - - tree.Count.Should().Be(0); - tree.GetKeysInOrder().Should().BeEmpty(); - } + [Test] + public void AddRange_MultipleKeys_FormsCorrectTree() + { + var tree = new AvlTree(); + tree.AddRange(new[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g' }); + + tree.Count.Should().Be(7); + + tree.GetKeysInOrder() + .Should() + .BeEquivalentTo( + new[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g' }, + config => config.WithStrictOrdering()); + + tree.GetKeysPreOrder() + .Should() + .BeEquivalentTo( + new[] { 'd', 'b', 'a', 'c', 'f', 'e', 'g' }, + config => config.WithStrictOrdering()); + + tree.GetKeysPostOrder() + .Should() + .BeEquivalentTo( + new[] { 'a', 'c', 'b', 'e', 'g', 'f', 'd' }, + config => config.WithStrictOrdering()); + } - [Test] - public void Remove_MultipleKeys_TreeStillValid_Variant2() - { - var tree = new AvlTree(); - tree.AddRange(Data); + [Test] + public void Remove_MultipleKeys_TreeStillValid() + { + var tree = new AvlTree(); + tree.AddRange(Data); + + tree.Remove(7); + + tree.Count.Should().Be(9); + tree.Contains(7).Should().BeFalse(); + + tree.GetKeysInOrder() + .Should() + .BeEquivalentTo( + new[] { 1, 2, 3, 4, 5, 6, 8, 9, 10 }, + config => config.WithStrictOrdering()); + + tree.GetKeysPreOrder() + .Should() + .BeEquivalentTo( + new[] { 4, 2, 1, 3, 8, 6, 5, 9, 10 }, + config => config.WithStrictOrdering()); + + tree.GetKeysPostOrder() + .Should() + .BeEquivalentTo( + new[] { 1, 3, 2, 5, 6, 10, 9, 8, 4 }, + config => config.WithStrictOrdering()); + + tree.Remove(2); + + tree.Count.Should().Be(8); + tree.Contains(2).Should().BeFalse(); + + tree.Remove(1); + + tree.Count.Should().Be(7); + tree.Contains(1).Should().BeFalse(); + + tree.GetKeysInOrder() + .Should() + .BeEquivalentTo( + new[] { 3, 4, 5, 6, 8, 9, 10 }, + config => config.WithStrictOrdering()); + + tree.GetKeysPreOrder() + .Should() + .BeEquivalentTo( + new[] { 8, 4, 3, 6, 5, 9, 10 }, + config => config.WithStrictOrdering()); + + tree.GetKeysPostOrder() + .Should() + .BeEquivalentTo( + new[] { 3, 5, 6, 4, 10, 9, 8 }, + config => config.WithStrictOrdering()); + + tree.Remove(9); + + tree.Count.Should().Be(6); + tree.Contains(9).Should().BeFalse(); + + tree.GetKeysInOrder() + .Should() + .BeEquivalentTo( + new[] { 3, 4, 5, 6, 8, 10 }, + config => config.WithStrictOrdering()); + + tree.GetKeysPreOrder() + .Should() + .BeEquivalentTo( + new[] { 6, 4, 3, 5, 8, 10 }, + config => config.WithStrictOrdering()); + + tree.GetKeysPostOrder() + .Should() + .BeEquivalentTo( + new[] { 3, 5, 4, 10, 8, 6 }, + config => config.WithStrictOrdering()); + + tree.Remove(3); + tree.Remove(4); + tree.Remove(5); + tree.Remove(6); + tree.Remove(8); + tree.Remove(10); + + tree.Count.Should().Be(0); + tree.GetKeysInOrder().Should().BeEmpty(); + } - tree.Remove(10); + [Test] + public void Remove_MultipleKeys_TreeStillValid_Variant2() + { + var tree = new AvlTree(); + tree.AddRange(Data); - tree.Count.Should().Be(9); - tree.Contains(10).Should().BeFalse(); + tree.Remove(10); - tree.Remove(5); + tree.Count.Should().Be(9); + tree.Contains(10).Should().BeFalse(); - tree.Count.Should().Be(8); - tree.Contains(5).Should().BeFalse(); + tree.Remove(5); - tree.Remove(7); + tree.Count.Should().Be(8); + tree.Contains(5).Should().BeFalse(); - tree.Count.Should().Be(7); - tree.Contains(7).Should().BeFalse(); + tree.Remove(7); - tree.Remove(9); + tree.Count.Should().Be(7); + tree.Contains(7).Should().BeFalse(); - tree.Count.Should().Be(6); - tree.Contains(9).Should().BeFalse(); + tree.Remove(9); - tree.Remove(1); + tree.Count.Should().Be(6); + tree.Contains(9).Should().BeFalse(); - tree.Count.Should().Be(5); - tree.Contains(1).Should().BeFalse(); + tree.Remove(1); - tree.Remove(3); + tree.Count.Should().Be(5); + tree.Contains(1).Should().BeFalse(); - tree.Count.Should().Be(4); - tree.Contains(3).Should().BeFalse(); + tree.Remove(3); - tree.Remove(2); + tree.Count.Should().Be(4); + tree.Contains(3).Should().BeFalse(); - tree.Count.Should().Be(3); - tree.Contains(2).Should().BeFalse(); + tree.Remove(2); - tree.GetKeysInOrder() - .Should() - .BeEquivalentTo( - new[] { 4,6,8 }, - config => config.WithStrictOrdering()); + tree.Count.Should().Be(3); + tree.Contains(2).Should().BeFalse(); - tree.GetKeysPreOrder() - .Should() - .BeEquivalentTo( - new[] { 6,4,8 }, - config => config.WithStrictOrdering()); + tree.GetKeysInOrder() + .Should() + .BeEquivalentTo( + new[] { 4,6,8 }, + config => config.WithStrictOrdering()); - tree.GetKeysPostOrder() - .Should() - .BeEquivalentTo( - new[] { 4,8,6 }, - config => config.WithStrictOrdering()); - } + tree.GetKeysPreOrder() + .Should() + .BeEquivalentTo( + new[] { 6,4,8 }, + config => config.WithStrictOrdering()); - [Test] - public void Remove_EmptyTree_ThrowsException() - { - var tree = new AvlTree(); + tree.GetKeysPostOrder() + .Should() + .BeEquivalentTo( + new[] { 4,8,6 }, + config => config.WithStrictOrdering()); + } - Invoking(() => tree.Remove(1)).Should().ThrowExactly(); - } + [Test] + public void Remove_EmptyTree_ThrowsException() + { + var tree = new AvlTree(); - [Test] - public void Remove_KeyNotInTree_ThrowsException() - { - var tree = new AvlTree(); - tree.AddRange(Data); + Invoking(() => tree.Remove(1)).Should().ThrowExactly(); + } - Invoking(() => tree.Remove(24)).Should().ThrowExactly(); - } + [Test] + public void Remove_KeyNotInTree_ThrowsException() + { + var tree = new AvlTree(); + tree.AddRange(Data); - [Test] - public void Contains_CorrectReturn() - { - var tree = new AvlTree(); + Invoking(() => tree.Remove(24)).Should().ThrowExactly(); + } - tree.AddRange(Data); + [Test] + public void Contains_CorrectReturn() + { + var tree = new AvlTree(); - tree.Contains(3).Should().BeTrue(); - tree.Contains(7).Should().BeTrue(); - tree.Contains(24).Should().BeFalse(); - tree.Contains(-1).Should().BeFalse(); - } + tree.AddRange(Data); - [Test] - public void Contains_EmptyTree_ReturnsFalse() - { - var tree = new AvlTree(); + tree.Contains(3).Should().BeTrue(); + tree.Contains(7).Should().BeTrue(); + tree.Contains(24).Should().BeFalse(); + tree.Contains(-1).Should().BeFalse(); + } - tree.Contains(5).Should().BeFalse(); - tree.Contains(-12).Should().BeFalse(); - } + [Test] + public void Contains_EmptyTree_ReturnsFalse() + { + var tree = new AvlTree(); - [Test] - public void GetMin_CorrectReturn() - { - var tree = new AvlTree(); - tree.AddRange(Data); + tree.Contains(5).Should().BeFalse(); + tree.Contains(-12).Should().BeFalse(); + } - tree.GetMin().Should().Be(1); - } + [Test] + public void GetMin_CorrectReturn() + { + var tree = new AvlTree(); + tree.AddRange(Data); - [Test] - public void GetMin_EmptyTree_ThrowsException() - { - var tree = new AvlTree(); + tree.GetMin().Should().Be(1); + } - Invoking(() => tree.GetMin()).Should().ThrowExactly(); - } + [Test] + public void GetMin_EmptyTree_ThrowsException() + { + var tree = new AvlTree(); - [Test] - public void GetMax_CorrectReturn() - { - var tree = new AvlTree(); - tree.AddRange(Data); + Invoking(() => tree.GetMin()).Should().ThrowExactly(); + } - tree.GetMax().Should().Be(10); - } + [Test] + public void GetMax_CorrectReturn() + { + var tree = new AvlTree(); + tree.AddRange(Data); - [Test] - public void GetMax_EmptyTree_ThrowsException() - { - var tree = new AvlTree(); + tree.GetMax().Should().Be(10); + } - Invoking(() => tree.GetMax()).Should().ThrowExactly(); - } + [Test] + public void GetMax_EmptyTree_ThrowsException() + { + var tree = new AvlTree(); - [Test] - public void GetKeysInOrder_CorrectReturn() - { - var tree = new AvlTree(); - tree.AddRange(Data); - - tree.GetKeysInOrder() - .Should() - .BeEquivalentTo( - Data, - config => config.WithStrictOrdering()); - } + Invoking(() => tree.GetMax()).Should().ThrowExactly(); + } - [Test] - public void GetKeysInOrder_EmptyTree_CorrectReturn() - { - var tree = new AvlTree(); + [Test] + public void GetKeysInOrder_CorrectReturn() + { + var tree = new AvlTree(); + tree.AddRange(Data); + + tree.GetKeysInOrder() + .Should() + .BeEquivalentTo( + Data, + config => config.WithStrictOrdering()); + } - tree.GetKeysInOrder().Should().BeEmpty(); - } + [Test] + public void GetKeysInOrder_EmptyTree_CorrectReturn() + { + var tree = new AvlTree(); - [Test] - public void GetKeysPreOrder_CorrectReturn() - { - var tree = new AvlTree(); + tree.GetKeysInOrder().Should().BeEmpty(); + } - tree.AddRange(Data); + [Test] + public void GetKeysPreOrder_CorrectReturn() + { + var tree = new AvlTree(); - tree.GetKeysPreOrder() - .Should() - .BeEquivalentTo( - PreOrder, - config => config.WithStrictOrdering()); - } + tree.AddRange(Data); - [Test] - public void GetKeysPreOrder_EmptyTree_CorrectReturn() - { - var tree = new AvlTree(); + tree.GetKeysPreOrder() + .Should() + .BeEquivalentTo( + PreOrder, + config => config.WithStrictOrdering()); + } - tree.GetKeysPreOrder().Should().BeEmpty(); - } + [Test] + public void GetKeysPreOrder_EmptyTree_CorrectReturn() + { + var tree = new AvlTree(); - [Test] - public void GetKeysPostOrder_CorrectReturn() - { - var tree = new AvlTree(); - tree.AddRange(Data); - - tree.GetKeysPostOrder() - .Should() - .BeEquivalentTo( - PostOrder, - config => config.WithStrictOrdering()); - } + tree.GetKeysPreOrder().Should().BeEmpty(); + } - [Test] - public void GetKeysPostOrder_EmptyTree_CorrectReturn() - { - var tree = new AvlTree(); + [Test] + public void GetKeysPostOrder_CorrectReturn() + { + var tree = new AvlTree(); + tree.AddRange(Data); + + tree.GetKeysPostOrder() + .Should() + .BeEquivalentTo( + PostOrder, + config => config.WithStrictOrdering()); + } - tree.GetKeysPostOrder().Should().BeEmpty(); - } + [Test] + public void GetKeysPostOrder_EmptyTree_CorrectReturn() + { + var tree = new AvlTree(); + + tree.GetKeysPostOrder().Should().BeEmpty(); } } diff --git a/DataStructures.Tests/BinarySearchTreeTests.cs b/DataStructures.Tests/BinarySearchTreeTests.cs index 84408b2e..52870283 100644 --- a/DataStructures.Tests/BinarySearchTreeTests.cs +++ b/DataStructures.Tests/BinarySearchTreeTests.cs @@ -1,284 +1,283 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using DataStructures.BinarySearchTree; using NUnit.Framework; -namespace DataStructures.Tests +namespace DataStructures.Tests; + +public static class BinarySearchTreeTests { - public static class BinarySearchTreeTests + [Test] + public static void Constructor_UseCustomComparer_FormsCorrectTree() + { + var cmpFunc = Comparer.Create((x, y) => x.Length - y.Length); + var tree = new BinarySearchTree(cmpFunc); + var elems = new[] { "z", "yy", "vvv", "bbbb", "fffff", "pppppp" }; + tree.AddRange(elems); + + Assert.IsNotNull(tree.Search("vvv")); + Assert.AreEqual("bbbb", tree.Search("vvv")!.Right!.Key); + } + + [Test] + public static void Add_MultipleKeys_FormsCorrectBST() + { + var tree = new BinarySearchTree(); + + tree.Add(5); + Assert.AreEqual(1, tree.Count); + + tree.Add(3); + Assert.AreEqual(2, tree.Count); + + tree.Add(4); + Assert.AreEqual(3, tree.Count); + + tree.Add(2); + Assert.AreEqual(4, tree.Count); + + var rootNode = tree.Search(5); + Assert.AreEqual(5, rootNode!.Key); + Assert.AreEqual(3, rootNode!.Left!.Key); + Assert.IsNull(rootNode!.Right); + + var threeNode = tree.Search(3); + Assert.AreEqual(3, threeNode!.Key); + Assert.AreEqual(2, threeNode!.Left!.Key); + Assert.AreEqual(4, threeNode!.Right!.Key); + + var twoNode = tree.Search(2); + Assert.IsNull(twoNode!.Left); + Assert.IsNull(twoNode!.Right); + + var fourNode = tree.Search(4); + Assert.IsNull(fourNode!.Left); + Assert.IsNull(fourNode!.Right); + } + + [Test] + public static void Add_KeyAlreadyInTree_ThrowsCorrectException() + { + var tree = new BinarySearchTree(); + tree.AddRange(new List { 5, 3, 4, 2 }); + + _ = Assert.Throws(() => tree.Add(5)); + } + + [Test] + public static void AddRange_MultipleKeys_FormsCorrectBST() + { + var tree = new BinarySearchTree(); + tree.AddRange(new List { 5, 3, 4, 2 }); + + var rootNode = tree.Search(5); + Assert.AreEqual(5, rootNode!.Key); + Assert.AreEqual(3, rootNode!.Left!.Key); + Assert.IsNull(rootNode!.Right); + + var threeNode = tree.Search(3); + Assert.AreEqual(3, threeNode!.Key); + Assert.AreEqual(2, threeNode!.Left!.Key); + Assert.AreEqual(4, threeNode!.Right!.Key); + + var twoNode = tree.Search(2); + Assert.IsNull(twoNode!.Left); + Assert.IsNull(twoNode!.Right); + + var fourNode = tree.Search(4); + Assert.IsNull(fourNode!.Left); + Assert.IsNull(fourNode!.Right); + } + + [Test] + public static void Search_MultipleKeys_FindsAllKeys() + { + var tree = new BinarySearchTree(); + tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); + + Assert.AreEqual(2, tree.Search(2)!.Key); + Assert.AreEqual(3, tree.Search(3)!.Key); + Assert.AreEqual(4, tree.Search(4)!.Key); + Assert.AreEqual(5, tree.Search(5)!.Key); + Assert.AreEqual(6, tree.Search(6)!.Key); + Assert.AreEqual(7, tree.Search(7)!.Key); + Assert.AreEqual(8, tree.Search(8)!.Key); + } + + [Test] + public static void Contains_MultipleKeys_FindsAllKeys() + { + var tree = new BinarySearchTree(); + tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); + + Assert.IsTrue(tree.Contains(2)); + Assert.IsTrue(tree.Contains(3)); + Assert.IsTrue(tree.Contains(4)); + Assert.IsTrue(tree.Contains(5)); + Assert.IsTrue(tree.Contains(6)); + Assert.IsTrue(tree.Contains(7)); + Assert.IsTrue(tree.Contains(8)); + } + + [Test] + public static void Remove_LeafNodes_CorrectlyRemovesNodes() + { + var tree = new BinarySearchTree(); + tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); + + var twoRemoveResult = tree.Remove(2); + Assert.IsTrue(twoRemoveResult); + Assert.IsNull(tree.Search(2)); + Assert.IsNull(tree.Search(3)!.Left); + Assert.IsNotNull(tree.Search(3)!.Right); + Assert.AreEqual(6, tree.Count); + + var fourRemoveResult = tree.Remove(4); + Assert.IsTrue(fourRemoveResult); + Assert.IsNull(tree.Search(4)); + Assert.IsNull(tree.Search(3)!.Left); + Assert.IsNull(tree.Search(3)!.Right); + Assert.AreEqual(5, tree.Count); + } + + [Test] + public static void Remove_NodesWithOneChild_CorrectlyRemovesNodes() + { + var tree = new BinarySearchTree(); + tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); + + tree.Remove(4); + var threeRemoveResult = tree.Remove(3); + Assert.IsTrue(threeRemoveResult); + Assert.IsNull(tree.Search(3)); + Assert.IsNull(tree.Search(2)!.Left); + Assert.IsNull(tree.Search(2)!.Right); + Assert.AreEqual(5, tree.Count); + + tree.Remove(6); + var sevenRemoveResult = tree.Remove(7); + Assert.IsTrue(sevenRemoveResult); + Assert.IsNull(tree.Search(7)); + Assert.IsNull(tree.Search(8)!.Left); + Assert.IsNull(tree.Search(8)!.Right); + Assert.AreEqual(3, tree.Count); + } + + [Test] + public static void Remove_NodesWithTwoChildren_CorrectlyRemovesNodes() + { + var tree = new BinarySearchTree(); + tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); + + var sevenRemoveResult = tree.Remove(7); + Assert.IsTrue(sevenRemoveResult); + Assert.IsNull(tree.Search(7)); + Assert.IsNull(tree.Search(6)!.Left); + Assert.IsNotNull(tree.Search(6)!.Right); + Assert.AreEqual(6, tree.Count); + } + + [Test] + public static void Remove_NonExistentElement_ReturnsFalse() + { + var tree = new BinarySearchTree(); + tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); + + Assert.IsFalse(tree.Remove(999)); + Assert.AreEqual(7, tree.Count); + } + + [Test] + public static void Remove_EmptyTree_ReturnsFalse() { - [Test] - public static void Constructor_UseCustomComparer_FormsCorrectTree() - { - var cmpFunc = Comparer.Create((x, y) => x.Length - y.Length); - var tree = new BinarySearchTree(cmpFunc); - var elems = new[] { "z", "yy", "vvv", "bbbb", "fffff", "pppppp" }; - tree.AddRange(elems); - - Assert.IsNotNull(tree.Search("vvv")); - Assert.AreEqual("bbbb", tree.Search("vvv")!.Right!.Key); - } - - [Test] - public static void Add_MultipleKeys_FormsCorrectBST() - { - var tree = new BinarySearchTree(); - - tree.Add(5); - Assert.AreEqual(1, tree.Count); - - tree.Add(3); - Assert.AreEqual(2, tree.Count); - - tree.Add(4); - Assert.AreEqual(3, tree.Count); - - tree.Add(2); - Assert.AreEqual(4, tree.Count); - - var rootNode = tree.Search(5); - Assert.AreEqual(5, rootNode!.Key); - Assert.AreEqual(3, rootNode!.Left!.Key); - Assert.IsNull(rootNode!.Right); - - var threeNode = tree.Search(3); - Assert.AreEqual(3, threeNode!.Key); - Assert.AreEqual(2, threeNode!.Left!.Key); - Assert.AreEqual(4, threeNode!.Right!.Key); - - var twoNode = tree.Search(2); - Assert.IsNull(twoNode!.Left); - Assert.IsNull(twoNode!.Right); - - var fourNode = tree.Search(4); - Assert.IsNull(fourNode!.Left); - Assert.IsNull(fourNode!.Right); - } - - [Test] - public static void Add_KeyAlreadyInTree_ThrowsCorrectException() - { - var tree = new BinarySearchTree(); - tree.AddRange(new List { 5, 3, 4, 2 }); - - _ = Assert.Throws(() => tree.Add(5)); - } - - [Test] - public static void AddRange_MultipleKeys_FormsCorrectBST() - { - var tree = new BinarySearchTree(); - tree.AddRange(new List { 5, 3, 4, 2 }); - - var rootNode = tree.Search(5); - Assert.AreEqual(5, rootNode!.Key); - Assert.AreEqual(3, rootNode!.Left!.Key); - Assert.IsNull(rootNode!.Right); - - var threeNode = tree.Search(3); - Assert.AreEqual(3, threeNode!.Key); - Assert.AreEqual(2, threeNode!.Left!.Key); - Assert.AreEqual(4, threeNode!.Right!.Key); - - var twoNode = tree.Search(2); - Assert.IsNull(twoNode!.Left); - Assert.IsNull(twoNode!.Right); - - var fourNode = tree.Search(4); - Assert.IsNull(fourNode!.Left); - Assert.IsNull(fourNode!.Right); - } - - [Test] - public static void Search_MultipleKeys_FindsAllKeys() - { - var tree = new BinarySearchTree(); - tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); - - Assert.AreEqual(2, tree.Search(2)!.Key); - Assert.AreEqual(3, tree.Search(3)!.Key); - Assert.AreEqual(4, tree.Search(4)!.Key); - Assert.AreEqual(5, tree.Search(5)!.Key); - Assert.AreEqual(6, tree.Search(6)!.Key); - Assert.AreEqual(7, tree.Search(7)!.Key); - Assert.AreEqual(8, tree.Search(8)!.Key); - } - - [Test] - public static void Contains_MultipleKeys_FindsAllKeys() - { - var tree = new BinarySearchTree(); - tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); - - Assert.IsTrue(tree.Contains(2)); - Assert.IsTrue(tree.Contains(3)); - Assert.IsTrue(tree.Contains(4)); - Assert.IsTrue(tree.Contains(5)); - Assert.IsTrue(tree.Contains(6)); - Assert.IsTrue(tree.Contains(7)); - Assert.IsTrue(tree.Contains(8)); - } - - [Test] - public static void Remove_LeafNodes_CorrectlyRemovesNodes() - { - var tree = new BinarySearchTree(); - tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); - - var twoRemoveResult = tree.Remove(2); - Assert.IsTrue(twoRemoveResult); - Assert.IsNull(tree.Search(2)); - Assert.IsNull(tree.Search(3)!.Left); - Assert.IsNotNull(tree.Search(3)!.Right); - Assert.AreEqual(6, tree.Count); - - var fourRemoveResult = tree.Remove(4); - Assert.IsTrue(fourRemoveResult); - Assert.IsNull(tree.Search(4)); - Assert.IsNull(tree.Search(3)!.Left); - Assert.IsNull(tree.Search(3)!.Right); - Assert.AreEqual(5, tree.Count); - } - - [Test] - public static void Remove_NodesWithOneChild_CorrectlyRemovesNodes() - { - var tree = new BinarySearchTree(); - tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); - - tree.Remove(4); - var threeRemoveResult = tree.Remove(3); - Assert.IsTrue(threeRemoveResult); - Assert.IsNull(tree.Search(3)); - Assert.IsNull(tree.Search(2)!.Left); - Assert.IsNull(tree.Search(2)!.Right); - Assert.AreEqual(5, tree.Count); - - tree.Remove(6); - var sevenRemoveResult = tree.Remove(7); - Assert.IsTrue(sevenRemoveResult); - Assert.IsNull(tree.Search(7)); - Assert.IsNull(tree.Search(8)!.Left); - Assert.IsNull(tree.Search(8)!.Right); - Assert.AreEqual(3, tree.Count); - } - - [Test] - public static void Remove_NodesWithTwoChildren_CorrectlyRemovesNodes() - { - var tree = new BinarySearchTree(); - tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); - - var sevenRemoveResult = tree.Remove(7); - Assert.IsTrue(sevenRemoveResult); - Assert.IsNull(tree.Search(7)); - Assert.IsNull(tree.Search(6)!.Left); - Assert.IsNotNull(tree.Search(6)!.Right); - Assert.AreEqual(6, tree.Count); - } - - [Test] - public static void Remove_NonExistentElement_ReturnsFalse() - { - var tree = new BinarySearchTree(); - tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); - - Assert.IsFalse(tree.Remove(999)); - Assert.AreEqual(7, tree.Count); - } - - [Test] - public static void Remove_EmptyTree_ReturnsFalse() - { - var tree = new BinarySearchTree(); - Assert.IsFalse(tree.Remove(8)); - Assert.AreEqual(0, tree.Count); - } - - [Test] - public static void Remove_RemoveRoot_CorrectlyRemovesRoot() - { - var tree = new BinarySearchTree(); - tree.Add(5); - tree.Remove(5); - - Assert.AreEqual(0, tree.Count); - Assert.IsNull(tree.Search(5)); - - tree.AddRange(new List { 5, 4, 6 }); - tree.Remove(5); - - Assert.AreEqual(2, tree.Count); - Assert.IsNull(tree.Search(5)); - Assert.IsNotNull(tree.Search(4)); - Assert.IsNotNull(tree.Search(6)); - Assert.AreEqual(6, tree.Search(4)!.Right!.Key); - } - - [Test] - public static void GetMax_NonEmptyTree_ReturnsCorrectValue() - { - var tree = new BinarySearchTree(); - tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); - - Assert.AreEqual(8, tree.GetMax()!.Key); - } - - [Test] - public static void GetMax_EmptyTree_ReturnsDefaultValue() - { - var tree = new BinarySearchTree(); - Assert.IsNull(tree.GetMax()); - } - - [Test] - public static void GetMin_NonEmptyTree_ReturnsCorrectValue() - { - var tree = new BinarySearchTree(); - tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); - - Assert.AreEqual(2, tree.GetMin()!.Key); - } - - [Test] - public static void GetMin_EmptyTree_ReturnsDefaultValue() - { - var tree = new BinarySearchTree(); - Assert.IsNull(tree.GetMin()); - } - - [Test] - public static void GetKeysInOrder_MultipleKeys_ReturnsAllKeysInCorrectOrder() - { - var tree = new BinarySearchTree(); - tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); - - var keys = tree.GetKeysInOrder(); - var expected = new List { 2, 3, 4, 5, 6, 7, 8 }; - Assert.IsTrue(keys.SequenceEqual(expected)); - } - - [Test] - public static void GetKeysPreOrder_MultipleKeys_ReturnsAllKeysInCorrectOrder() - { - var tree = new BinarySearchTree(); - tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); - - var keys = tree.GetKeysPreOrder(); - var expected = new List { 5, 3, 2, 4, 7, 6, 8 }; - Assert.IsTrue(keys.SequenceEqual(expected)); - } - - [Test] - public static void GetKeysPostOrder_MultipleKeys_ReturnsAllKeysInCorrectOrder() - { - var tree = new BinarySearchTree(); - tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); - - var keys = tree.GetKeysPostOrder(); - var expected = new List { 2, 4, 3, 6, 8, 7, 5 }; - Assert.IsTrue(keys.SequenceEqual(expected)); - } + var tree = new BinarySearchTree(); + Assert.IsFalse(tree.Remove(8)); + Assert.AreEqual(0, tree.Count); + } + + [Test] + public static void Remove_RemoveRoot_CorrectlyRemovesRoot() + { + var tree = new BinarySearchTree(); + tree.Add(5); + tree.Remove(5); + + Assert.AreEqual(0, tree.Count); + Assert.IsNull(tree.Search(5)); + + tree.AddRange(new List { 5, 4, 6 }); + tree.Remove(5); + + Assert.AreEqual(2, tree.Count); + Assert.IsNull(tree.Search(5)); + Assert.IsNotNull(tree.Search(4)); + Assert.IsNotNull(tree.Search(6)); + Assert.AreEqual(6, tree.Search(4)!.Right!.Key); + } + + [Test] + public static void GetMax_NonEmptyTree_ReturnsCorrectValue() + { + var tree = new BinarySearchTree(); + tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); + + Assert.AreEqual(8, tree.GetMax()!.Key); + } + + [Test] + public static void GetMax_EmptyTree_ReturnsDefaultValue() + { + var tree = new BinarySearchTree(); + Assert.IsNull(tree.GetMax()); + } + + [Test] + public static void GetMin_NonEmptyTree_ReturnsCorrectValue() + { + var tree = new BinarySearchTree(); + tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); + + Assert.AreEqual(2, tree.GetMin()!.Key); + } + + [Test] + public static void GetMin_EmptyTree_ReturnsDefaultValue() + { + var tree = new BinarySearchTree(); + Assert.IsNull(tree.GetMin()); + } + + [Test] + public static void GetKeysInOrder_MultipleKeys_ReturnsAllKeysInCorrectOrder() + { + var tree = new BinarySearchTree(); + tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); + + var keys = tree.GetKeysInOrder(); + var expected = new List { 2, 3, 4, 5, 6, 7, 8 }; + Assert.IsTrue(keys.SequenceEqual(expected)); + } + + [Test] + public static void GetKeysPreOrder_MultipleKeys_ReturnsAllKeysInCorrectOrder() + { + var tree = new BinarySearchTree(); + tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); + + var keys = tree.GetKeysPreOrder(); + var expected = new List { 5, 3, 2, 4, 7, 6, 8 }; + Assert.IsTrue(keys.SequenceEqual(expected)); + } + + [Test] + public static void GetKeysPostOrder_MultipleKeys_ReturnsAllKeysInCorrectOrder() + { + var tree = new BinarySearchTree(); + tree.AddRange(new List { 5, 3, 4, 2, 7, 6, 8 }); + + var keys = tree.GetKeysPostOrder(); + var expected = new List { 2, 4, 3, 6, 8, 7, 5 }; + Assert.IsTrue(keys.SequenceEqual(expected)); } } diff --git a/DataStructures.Tests/BitArrayTests.cs b/DataStructures.Tests/BitArrayTests.cs index 93bc32fa..d99f8b8b 100644 --- a/DataStructures.Tests/BitArrayTests.cs +++ b/DataStructures.Tests/BitArrayTests.cs @@ -1,535 +1,534 @@ -using System; +using System; using FluentAssertions; using NUnit.Framework; -namespace DataStructures.Tests +namespace DataStructures.Tests; + +/// +/// This class contains some tests for the class BitArray. +/// +public static class BitArrayTests { - /// - /// This class contains some tests for the class BitArray. - /// - public static class BitArrayTests + [Test] + public static void TestIndexer() { - [Test] - public static void TestIndexer() - { - // Arrange - var testObj = new BitArray(5); + // Arrange + var testObj = new BitArray(5); - // Act - testObj.Compile(24); + // Act + testObj.Compile(24); - // Assert - Assert.IsTrue(testObj[0]); - Assert.IsTrue(testObj[1]); - Assert.IsFalse(testObj[3]); - } + // Assert + Assert.IsTrue(testObj[0]); + Assert.IsTrue(testObj[1]); + Assert.IsFalse(testObj[3]); + } - [TestCase(19, 3)] - public static void TestNumberOfOneBits(int number, int expected) - { - // Arrange - var testObj = new BitArray(5); + [TestCase(19, 3)] + public static void TestNumberOfOneBits(int number, int expected) + { + // Arrange + var testObj = new BitArray(5); - // Act - testObj.Compile(number); + // Act + testObj.Compile(number); - // Assert - Assert.AreEqual(expected, testObj.NumberOfOneBits()); - } + // Assert + Assert.AreEqual(expected, testObj.NumberOfOneBits()); + } - [TestCase(26, 2)] - public static void TestNumberOfZeroBits(int number, int expected) - { - // Arrange - var testObj = new BitArray(5); + [TestCase(26, 2)] + public static void TestNumberOfZeroBits(int number, int expected) + { + // Arrange + var testObj = new BitArray(5); - // Act - testObj.Compile(number); + // Act + testObj.Compile(number); - // Assert - Assert.AreEqual(expected, testObj.NumberOfZeroBits()); - } + // Assert + Assert.AreEqual(expected, testObj.NumberOfZeroBits()); + } - [TestCase(33, 33)] - public static void TestToInt64(int number, int expected) - { - // Arrange - var testObj = new BitArray(6); + [TestCase(33, 33)] + public static void TestToInt64(int number, int expected) + { + // Arrange + var testObj = new BitArray(6); - // Act - testObj.Compile(number); + // Act + testObj.Compile(number); - // Assert - Assert.AreEqual(expected, testObj.ToInt64()); - } + // Assert + Assert.AreEqual(expected, testObj.ToInt64()); + } - [Test] - public static void TestToInt32MaxValue() - { - // Arrange - var testObj = new BitArray(33); + [Test] + public static void TestToInt32MaxValue() + { + // Arrange + var testObj = new BitArray(33); - // Act + // Act - // Assert - _ = Assert.Throws(() => testObj.ToInt32()); - } + // Assert + _ = Assert.Throws(() => testObj.ToInt32()); + } - [Test] - public static void TestToInt64MaxValue() - { - // Arrange - var testObj = new BitArray(65); + [Test] + public static void TestToInt64MaxValue() + { + // Arrange + var testObj = new BitArray(65); - // Act + // Act - // Assert - _ = Assert.Throws(() => testObj.ToInt64()); - } + // Assert + _ = Assert.Throws(() => testObj.ToInt64()); + } - [TestCase("110")] - public static void TestResetField(string sequence) - { - // Arrange - var testObj = new BitArray(sequence); + [TestCase("110")] + public static void TestResetField(string sequence) + { + // Arrange + var testObj = new BitArray(sequence); - // Act - testObj.ResetField(); + // Act + testObj.ResetField(); - // Assert - Assert.AreEqual(0, testObj.ToInt64()); - } + // Assert + Assert.AreEqual(0, testObj.ToInt64()); + } - [TestCase("101001", 63)] - public static void TestSetAll(string sequence, int expected) - { - // Arrange - var testObj = new BitArray(sequence); + [TestCase("101001", 63)] + public static void TestSetAll(string sequence, int expected) + { + // Arrange + var testObj = new BitArray(sequence); - // Act - testObj.SetAll(true); + // Act + testObj.SetAll(true); - // Assert - Assert.AreEqual(expected, testObj.ToInt64()); - } + // Assert + Assert.AreEqual(expected, testObj.ToInt64()); + } - [Test] - public static void TestCloneEquals() - { - // Arrange - var testObj1 = new BitArray("110"); + [Test] + public static void TestCloneEquals() + { + // Arrange + var testObj1 = new BitArray("110"); - // Act - var testObj2 = (BitArray)testObj1.Clone(); + // Act + var testObj2 = (BitArray)testObj1.Clone(); - // Assert - Assert.IsTrue(testObj1.Equals(testObj2)); - } + // Assert + Assert.IsTrue(testObj1.Equals(testObj2)); + } - [Test] - public static void TestCloneNotEquals() - { - // Arrange - var testObj1 = new BitArray("101"); - var testObj2 = new BitArray(15); - var testObj3 = new BitArray(3); + [Test] + public static void TestCloneNotEquals() + { + // Arrange + var testObj1 = new BitArray("101"); + var testObj2 = new BitArray(15); + var testObj3 = new BitArray(3); - // Act - testObj3.Reset(); + // Act + testObj3.Reset(); - // Assert - testObj1.Equals(testObj2).Should().BeFalse(); - testObj1.Equals(testObj3).Should().BeFalse(); - } + // Assert + testObj1.Equals(testObj2).Should().BeFalse(); + testObj1.Equals(testObj3).Should().BeFalse(); + } - [Test] - public static void TestHasCode() - { - // Arrange - const int num = 5; - var testObj = new BitArray(3); + [Test] + public static void TestHasCode() + { + // Arrange + const int num = 5; + var testObj = new BitArray(3); - // Act - testObj.Compile(num); - var result = testObj.GetHashCode(); + // Act + testObj.Compile(num); + var result = testObj.GetHashCode(); - // Assert - Assert.NotNull(result); - Assert.AreEqual(5, result); - } + // Assert + Assert.NotNull(result); + Assert.AreEqual(5, result); + } - [Test] - public static void TestMoveNextCurrent() - { - var testObj1 = new BitArray("1111010"); + [Test] + public static void TestMoveNextCurrent() + { + var testObj1 = new BitArray("1111010"); - var counterOnes = 0; - var counterZeros = 0; + var counterOnes = 0; + var counterZeros = 0; - foreach (var bit in testObj1) + foreach (var bit in testObj1) + { + if (bit) { - if (bit) - { - counterOnes++; - } - else - { - counterZeros++; - } + counterOnes++; } - - Assert.AreEqual(counterOnes, 5); - Assert.AreEqual(counterZeros, 2); - } - - [Test] - public static void IEnumerable_IterationWorks() - { - var arr = new BitArray("010101010101010101"); - var current = 0; - foreach (var b in arr) + else { - b.Should().Be(arr[current]); - current++; + counterZeros++; } } - [Test] - public static void Equals_NullIsNotEqualToNotNull() + Assert.AreEqual(counterOnes, 5); + Assert.AreEqual(counterZeros, 2); + } + + [Test] + public static void IEnumerable_IterationWorks() + { + var arr = new BitArray("010101010101010101"); + var current = 0; + foreach (var b in arr) { - var arr1 = new BitArray("010101010101010101"); - BitArray? arr2 = null; - arr1.Equals(arr2).Should().BeFalse(); + b.Should().Be(arr[current]); + current++; } + } - #region COMPILE TESTS + [Test] + public static void Equals_NullIsNotEqualToNotNull() + { + var arr1 = new BitArray("010101010101010101"); + BitArray? arr2 = null; + arr1.Equals(arr2).Should().BeFalse(); + } - [TestCase("00100", "00100")] - [TestCase("01101", "01101")] - [TestCase("100", "00100")] - public static void TestCompileToString(string sequence, string expectedSequence) - { - // Arrange - var testObj = new BitArray(5); + #region COMPILE TESTS - // Act - testObj.Compile(sequence); + [TestCase("00100", "00100")] + [TestCase("01101", "01101")] + [TestCase("100", "00100")] + public static void TestCompileToString(string sequence, string expectedSequence) + { + // Arrange + var testObj = new BitArray(5); - // Assert - Assert.AreEqual(expectedSequence, testObj.ToString()); - } + // Act + testObj.Compile(sequence); - [TestCase("klgml", 5)] - [TestCase("klgml", 3)] - public static void TestCompileToStringThorwsException(string sequence, int arrLen) - { - // Arrange - var testObj = new BitArray(arrLen); + // Assert + Assert.AreEqual(expectedSequence, testObj.ToString()); + } - // Act - void Act() => testObj.Compile(sequence); + [TestCase("klgml", 5)] + [TestCase("klgml", 3)] + public static void TestCompileToStringThorwsException(string sequence, int arrLen) + { + // Arrange + var testObj = new BitArray(arrLen); - // Assert - Assert.Throws(Act); - } + // Act + void Act() => testObj.Compile(sequence); - [TestCase(15, "01111")] - [TestCase(17, "10001")] - [TestCase(4, "00100")] - public static void TestCompileLong(int number, string expected) - { - // Arrange - var testObj = new BitArray(5); + // Assert + Assert.Throws(Act); + } - // Act - testObj.Compile((long)number); + [TestCase(15, "01111")] + [TestCase(17, "10001")] + [TestCase(4, "00100")] + public static void TestCompileLong(int number, string expected) + { + // Arrange + var testObj = new BitArray(5); - // Assert - Assert.AreEqual(expected, testObj.ToString()); - } + // Act + testObj.Compile((long)number); - [TestCase(46, 3)] - [TestCase(-46, 5)] - public static void TestCompileLongThrowsException(int number, int arrLen) - { - // Arrange - var testObj = new BitArray(arrLen); + // Assert + Assert.AreEqual(expected, testObj.ToString()); + } - // Act - void Act() => testObj.Compile((long)number); + [TestCase(46, 3)] + [TestCase(-46, 5)] + public static void TestCompileLongThrowsException(int number, int arrLen) + { + // Arrange + var testObj = new BitArray(arrLen); - // Assert - Assert.Throws(Act); - } + // Act + void Act() => testObj.Compile((long)number); - [TestCase(17, "10001")] - [TestCase(25, "11001")] - [TestCase(4, "00100")] - public static void TestCompileInteger(int number, string expected) - { - // Arrange - var testObj = new BitArray(5); + // Assert + Assert.Throws(Act); + } - // Act - testObj.Compile(number); + [TestCase(17, "10001")] + [TestCase(25, "11001")] + [TestCase(4, "00100")] + public static void TestCompileInteger(int number, string expected) + { + // Arrange + var testObj = new BitArray(5); - // Assert - Assert.AreEqual(expected, testObj.ToString()); - } + // Act + testObj.Compile(number); - [TestCase(-8, 5)] - [TestCase(18, 3)] - public static void TestCompileIntegerThrowsException(int number, int arrayLength) - { - // Arrange - var testObj = new BitArray(arrayLength); + // Assert + Assert.AreEqual(expected, testObj.ToString()); + } - // Act - void Act() => testObj.Compile(number); + [TestCase(-8, 5)] + [TestCase(18, 3)] + public static void TestCompileIntegerThrowsException(int number, int arrayLength) + { + // Arrange + var testObj = new BitArray(arrayLength); - // Assert - Assert.Throws(Act); - } + // Act + void Act() => testObj.Compile(number); - #endregion COMPILE TESTS + // Assert + Assert.Throws(Act); + } - #region CONSTRUCTOR TESTS + #endregion COMPILE TESTS - [TestCase("00100", 4)] - public static void TestConstructor(string sequence, int expected) - { - // Arrange - var testObj1 = new BitArray(sequence); + #region CONSTRUCTOR TESTS - // Act + [TestCase("00100", 4)] + public static void TestConstructor(string sequence, int expected) + { + // Arrange + var testObj1 = new BitArray(sequence); - // Assert - Assert.AreEqual(expected, testObj1.ToInt64()); - } + // Act - [TestCase(new[] { true, false, true }, 5)] - public static void TestConstructorBoolArray(bool[] sequence, int expected) - { - // Arrange - var testObj3 = new BitArray(sequence); + // Assert + Assert.AreEqual(expected, testObj1.ToInt64()); + } - // Act + [TestCase(new[] { true, false, true }, 5)] + public static void TestConstructorBoolArray(bool[] sequence, int expected) + { + // Arrange + var testObj3 = new BitArray(sequence); - // Assert - Assert.AreEqual(expected, testObj3.ToInt64()); - } + // Act - [TestCase("000120")] - [TestCase("")] - public static void TestConstructorThrowsException(string sequence) - { - // Arrange + // Assert + Assert.AreEqual(expected, testObj3.ToInt64()); + } - // Act - Action act = () => new BitArray(sequence); + [TestCase("000120")] + [TestCase("")] + public static void TestConstructorThrowsException(string sequence) + { + // Arrange - // Assert - act.Should().Throw(); - } + // Act + Action act = () => new BitArray(sequence); - #endregion CONSTRUCTOR TESTS + // Assert + act.Should().Throw(); + } - #region OPERATOR TESTS + #endregion CONSTRUCTOR TESTS - [TestCase(17, 17, "10001")] - [TestCase(25, 31, "11001")] - public static void TestOperatorAnd(int tObj1, int tObj2, string expected) - { - // Arrange - var testObj1 = new BitArray(5); - var testObj2 = new BitArray(5); + #region OPERATOR TESTS - // Act - testObj1.Compile(tObj1); - testObj2.Compile(tObj2); + [TestCase(17, 17, "10001")] + [TestCase(25, 31, "11001")] + public static void TestOperatorAnd(int tObj1, int tObj2, string expected) + { + // Arrange + var testObj1 = new BitArray(5); + var testObj2 = new BitArray(5); - var result = testObj1 & testObj2; + // Act + testObj1.Compile(tObj1); + testObj2.Compile(tObj2); - // Assert - Assert.AreEqual(expected, result.ToString()); - } + var result = testObj1 & testObj2; - [TestCase(1, 1, 1, 1, "0")] - [TestCase(5, 3, 8, 4, "1101")] - [TestCase(9, 4, 4, 3, "1101")] - public static void TestOperatorXorAndDiffSizes(int t1, int s1, int t2, int s2, string expected) - { - // Arrange - var testObj1 = new BitArray(s1); - var testObj2 = new BitArray(s2); + // Assert + Assert.AreEqual(expected, result.ToString()); + } - // Act - testObj1.Compile(t1); - testObj2.Compile(t2); - var result = testObj1 ^ testObj2; + [TestCase(1, 1, 1, 1, "0")] + [TestCase(5, 3, 8, 4, "1101")] + [TestCase(9, 4, 4, 3, "1101")] + public static void TestOperatorXorAndDiffSizes(int t1, int s1, int t2, int s2, string expected) + { + // Arrange + var testObj1 = new BitArray(s1); + var testObj2 = new BitArray(s2); - // Assert - Assert.AreEqual(expected, result.ToString()); - } + // Act + testObj1.Compile(t1); + testObj2.Compile(t2); + var result = testObj1 ^ testObj2; - [TestCase(9, 4, 4, 3, "1101")] - [TestCase(1, 1, 1, 1, "1")] - [TestCase(5, 3, 8, 4, "1101")] - public static void TestOperatorOrAndDiffSizes(int t1, int s1, int t2, int s2, string expected) - { - // Arrange - var testObj1 = new BitArray(s1); - var testObj2 = new BitArray(s2); + // Assert + Assert.AreEqual(expected, result.ToString()); + } - // Act - testObj1.Compile(t1); - testObj2.Compile(t2); - var result = testObj1 | testObj2; + [TestCase(9, 4, 4, 3, "1101")] + [TestCase(1, 1, 1, 1, "1")] + [TestCase(5, 3, 8, 4, "1101")] + public static void TestOperatorOrAndDiffSizes(int t1, int s1, int t2, int s2, string expected) + { + // Arrange + var testObj1 = new BitArray(s1); + var testObj2 = new BitArray(s2); - // Assert - Assert.AreEqual(expected, result.ToString()); - } + // Act + testObj1.Compile(t1); + testObj2.Compile(t2); + var result = testObj1 | testObj2; - [TestCase(1, 1, 1, 1, "1")] - [TestCase(5, 3, 8, 4, "0000")] - [TestCase(9, 4, 4, 3, "0000")] - public static void TestOperatorAndAndDiffSizes(int t1, int s1, int t2, int s2, string expected) - { - // Arrange - var testObj1 = new BitArray(s1); - var testObj2 = new BitArray(s2); + // Assert + Assert.AreEqual(expected, result.ToString()); + } - // Act - testObj1.Compile(t1); - testObj2.Compile(t2); - var result = testObj1 & testObj2; + [TestCase(1, 1, 1, 1, "1")] + [TestCase(5, 3, 8, 4, "0000")] + [TestCase(9, 4, 4, 3, "0000")] + public static void TestOperatorAndAndDiffSizes(int t1, int s1, int t2, int s2, string expected) + { + // Arrange + var testObj1 = new BitArray(s1); + var testObj2 = new BitArray(s2); - // Assert - Assert.AreEqual(expected, result.ToString()); - } + // Act + testObj1.Compile(t1); + testObj2.Compile(t2); + var result = testObj1 & testObj2; - [TestCase(25, 30, "11111")] - public static void TestOperatorOr(int tObj1, int tObj2, string expected) - { - // Arrange - var testObj1 = new BitArray(5); - var testObj2 = new BitArray(5); + // Assert + Assert.AreEqual(expected, result.ToString()); + } - // Act - testObj1.Compile(tObj1); - testObj2.Compile(tObj2); + [TestCase(25, 30, "11111")] + public static void TestOperatorOr(int tObj1, int tObj2, string expected) + { + // Arrange + var testObj1 = new BitArray(5); + var testObj2 = new BitArray(5); - var result = testObj1 | testObj2; + // Act + testObj1.Compile(tObj1); + testObj2.Compile(tObj2); - // Assert - Assert.AreEqual(expected, result.ToString()); - } + var result = testObj1 | testObj2; - [TestCase(16, "01111")] - public static void TestOperatorNot(int number, string expected) - { - // Arrange - var testObj = new BitArray(5); + // Assert + Assert.AreEqual(expected, result.ToString()); + } - // Act - testObj.Compile(number); - testObj = ~testObj; + [TestCase(16, "01111")] + public static void TestOperatorNot(int number, string expected) + { + // Arrange + var testObj = new BitArray(5); - // Assert - Assert.AreEqual(expected, testObj.ToString()); - } + // Act + testObj.Compile(number); + testObj = ~testObj; - [TestCase(25, 30, 7)] - public static void TestOperatorXor(int testNum, int testNum2, int expected) - { - // Arrange - var testObj1 = new BitArray(5); - var testObj2 = new BitArray(5); + // Assert + Assert.AreEqual(expected, testObj.ToString()); + } - // Act - testObj1.Compile(testNum); - testObj2.Compile(testNum2); + [TestCase(25, 30, 7)] + public static void TestOperatorXor(int testNum, int testNum2, int expected) + { + // Arrange + var testObj1 = new BitArray(5); + var testObj2 = new BitArray(5); - var result = testObj1 ^ testObj2; + // Act + testObj1.Compile(testNum); + testObj2.Compile(testNum2); - // Assert - Assert.AreEqual(expected, result.ToInt32()); - } + var result = testObj1 ^ testObj2; - [TestCase(16, "10000000")] - public static void TestOperatorShiftLeft(int number, string expected) - { - // Arrange - var testObj = new BitArray(5); + // Assert + Assert.AreEqual(expected, result.ToInt32()); + } - // Act - testObj.Compile(number); - testObj <<= 3; + [TestCase(16, "10000000")] + public static void TestOperatorShiftLeft(int number, string expected) + { + // Arrange + var testObj = new BitArray(5); - // Assert - Assert.AreEqual(expected, testObj.ToString()); - } + // Act + testObj.Compile(number); + testObj <<= 3; - [TestCase(24, "110")] - public static void TestOperatorShiftRight(int number, string expected) - { - // Arrange - var testObj = new BitArray(5); + // Assert + Assert.AreEqual(expected, testObj.ToString()); + } - // Act - testObj.Compile(number); - testObj >>= 2; + [TestCase(24, "110")] + public static void TestOperatorShiftRight(int number, string expected) + { + // Arrange + var testObj = new BitArray(5); - // Assert - Assert.AreEqual(expected, testObj.ToString()); - } + // Act + testObj.Compile(number); + testObj >>= 2; - #endregion OPERATOR TESTS + // Assert + Assert.AreEqual(expected, testObj.ToString()); + } - #region COMPARE TESTS + #endregion OPERATOR TESTS - [Test] - public static void TestParity() - { - // Arrange - var testObj = new BitArray(5); + #region COMPARE TESTS - // Act - testObj.Compile(26); + [Test] + public static void TestParity() + { + // Arrange + var testObj = new BitArray(5); - // Assert - Assert.IsFalse(testObj.EvenParity()); - Assert.IsTrue(testObj.OddParity()); - } + // Act + testObj.Compile(26); - [Test] - public static void TestCompare() - { - // Arrange - var testObj1 = new BitArray("110"); - var testObj2 = new BitArray("110"); - var testObj3 = new BitArray("100"); + // Assert + Assert.IsFalse(testObj.EvenParity()); + Assert.IsTrue(testObj.OddParity()); + } - // Act + [Test] + public static void TestCompare() + { + // Arrange + var testObj1 = new BitArray("110"); + var testObj2 = new BitArray("110"); + var testObj3 = new BitArray("100"); - // Assert - Assert.IsTrue(testObj1 == testObj2); - Assert.IsTrue(testObj1 != testObj3); - } + // Act - [Test] - public static void ArraysOfDifferentLengthsAreNotEqual() - { - // Arrange - var testObj1 = new BitArray("110"); - var testObj2 = new BitArray("10101"); + // Assert + Assert.IsTrue(testObj1 == testObj2); + Assert.IsTrue(testObj1 != testObj3); + } - // Act + [Test] + public static void ArraysOfDifferentLengthsAreNotEqual() + { + // Arrange + var testObj1 = new BitArray("110"); + var testObj2 = new BitArray("10101"); - // Assert - Assert.False(testObj1 == testObj2); - } + // Act - #endregion COMPARE TESTS + // Assert + Assert.False(testObj1 == testObj2); } + + #endregion COMPARE TESTS } diff --git a/DataStructures.Tests/Cache/LfuCacheTests.cs b/DataStructures.Tests/Cache/LfuCacheTests.cs index f349cead..f07112f8 100644 --- a/DataStructures.Tests/Cache/LfuCacheTests.cs +++ b/DataStructures.Tests/Cache/LfuCacheTests.cs @@ -1,78 +1,76 @@ -using System; using DataStructures.Cache; -using NUnit.Framework; using FluentAssertions; +using NUnit.Framework; -namespace DataStructures.Tests.Cache +namespace DataStructures.Tests.Cache; + +public static class LfuCacheTests { - public static class LfuCacheTests + [Test] + public static void TestPutGet() + { + var cache = new LfuCache(); + cache.Put(1, "one"); + + cache.Contains(1).Should().BeTrue(); + cache.Get(1).Should().Be("one"); + } + + [Test] + public static void TestCacheMiss() { - [Test] - public static void TestPutGet() - { - var cache = new LfuCache(); - cache.Put(1, "one"); - - cache.Contains(1).Should().BeTrue(); - cache.Get(1).Should().Be("one"); - } - - [Test] - public static void TestCacheMiss() - { - var cache = new LfuCache(); - cache.Put(1, "one"); - - cache.Contains(5).Should().BeFalse(); - cache.Get(5).Should().BeNull(); - } - - [Test] - public static void Evict_ItemWasNotUsed() - { - var cache = new LfuCache(capacity: 1); - cache.Put(1, "one"); - - // Add to the full cache, 1 will be removed - cache.Put(2, "two"); - - cache.Get(1).Should().BeNull(); - cache.Get(2).Should().Be("two"); - } - - [Test] - public static void Evict_OneItemWasUsed() - { - var cache = new LfuCache(capacity: 2); - cache.Put(1, "one"); - cache.Put(2, "two"); - - cache.Put(1, "ONE"); - - // Add to the full cache, 2 will be removed - cache.Put(3, "three"); - - cache.Get(1).Should().Be("ONE"); - cache.Get(2).Should().BeNull(); - cache.Get(3).Should().Be("three"); - } - - [Test] - public static void Evict_LruOrder() - { - var cache = new LfuCache(capacity: 2); - cache.Put(1, "one"); - cache.Put(2, "two"); - - cache.Put(1, "ONE"); - cache.Put(2, "TWO"); - - // Add to the full cache, 1 will be removed - cache.Put(3, "three"); - - cache.Get(1).Should().BeNull(); - cache.Get(2).Should().Be("TWO"); - cache.Get(3).Should().Be("three"); - } + var cache = new LfuCache(); + cache.Put(1, "one"); + + cache.Contains(5).Should().BeFalse(); + cache.Get(5).Should().BeNull(); + } + + [Test] + public static void Evict_ItemWasNotUsed() + { + var cache = new LfuCache(capacity: 1); + cache.Put(1, "one"); + + // Add to the full cache, 1 will be removed + cache.Put(2, "two"); + + cache.Get(1).Should().BeNull(); + cache.Get(2).Should().Be("two"); + } + + [Test] + public static void Evict_OneItemWasUsed() + { + var cache = new LfuCache(capacity: 2); + cache.Put(1, "one"); + cache.Put(2, "two"); + + cache.Put(1, "ONE"); + + // Add to the full cache, 2 will be removed + cache.Put(3, "three"); + + cache.Get(1).Should().Be("ONE"); + cache.Get(2).Should().BeNull(); + cache.Get(3).Should().Be("three"); + } + + [Test] + public static void Evict_LruOrder() + { + var cache = new LfuCache(capacity: 2); + cache.Put(1, "one"); + cache.Put(2, "two"); + + cache.Put(1, "ONE"); + cache.Put(2, "TWO"); + + // Add to the full cache, 1 will be removed + cache.Put(3, "three"); + + cache.Get(1).Should().BeNull(); + cache.Get(2).Should().Be("TWO"); + cache.Get(3).Should().Be("three"); } } diff --git a/DataStructures.Tests/Cache/LruCacheTests.cs b/DataStructures.Tests/Cache/LruCacheTests.cs index e39434d9..20eaec19 100644 --- a/DataStructures.Tests/Cache/LruCacheTests.cs +++ b/DataStructures.Tests/Cache/LruCacheTests.cs @@ -1,71 +1,69 @@ -using System; using DataStructures.Cache; -using NUnit.Framework; using FluentAssertions; +using NUnit.Framework; + +namespace DataStructures.Tests.Cache; -namespace DataStructures.Tests.Cache +public static class LruCacheTests { - public static class LruCacheTests + [Test] + public static void TestPutGet() { - [Test] - public static void TestPutGet() - { - var cache = new LruCache(); - cache.Put(1, "one"); + var cache = new LruCache(); + cache.Put(1, "one"); - cache.Contains(1).Should().BeTrue(); - cache.Get(1).Should().Be("one"); - } + cache.Contains(1).Should().BeTrue(); + cache.Get(1).Should().Be("one"); + } - [Test] - public static void TestCacheMiss() - { - var cache = new LruCache(); - cache.Put(1, "one"); + [Test] + public static void TestCacheMiss() + { + var cache = new LruCache(); + cache.Put(1, "one"); - cache.Contains(5).Should().BeFalse(); - cache.Get(5).Should().BeNull(); - } + cache.Contains(5).Should().BeFalse(); + cache.Get(5).Should().BeNull(); + } - [Test] - public static void TestCacheUpdate() - { - var cache = new LruCache(); - cache.Put(1, "one"); - cache.Put(1, "ONE"); + [Test] + public static void TestCacheUpdate() + { + var cache = new LruCache(); + cache.Put(1, "one"); + cache.Put(1, "ONE"); - cache.Get(1).Should().Be("ONE"); - } + cache.Get(1).Should().Be("ONE"); + } - [Test] - public static void RemoveOldestItem_ItemWasNotUsed() - { - var cache = new LruCache(capacity: 2); - cache.Put(1, "one"); - cache.Put(2, "two"); + [Test] + public static void RemoveOldestItem_ItemWasNotUsed() + { + var cache = new LruCache(capacity: 2); + cache.Put(1, "one"); + cache.Put(2, "two"); - // Add to the full cache, 1 will be removed - cache.Put(3, "three"); + // Add to the full cache, 1 will be removed + cache.Put(3, "three"); - cache.Get(1).Should().BeNull(); - cache.Get(2).Should().Be("two"); - cache.Get(3).Should().Be("three"); - } + cache.Get(1).Should().BeNull(); + cache.Get(2).Should().Be("two"); + cache.Get(3).Should().Be("three"); + } - [Test] - public static void RemoveOldestItem_ItemWasRecentlyUsed() - { - var cache = new LruCache(capacity: 2); - cache.Put(1, "one"); - cache.Put(2, "two"); - cache.Get(1); + [Test] + public static void RemoveOldestItem_ItemWasRecentlyUsed() + { + var cache = new LruCache(capacity: 2); + cache.Put(1, "one"); + cache.Put(2, "two"); + cache.Get(1); - // Add to the full cache, 1 was used, 2 should be removed - cache.Put(3, "three"); + // Add to the full cache, 1 was used, 2 should be removed + cache.Put(3, "three"); - cache.Get(1).Should().Be("one"); - cache.Get(2).Should().BeNull(); - cache.Get(3).Should().Be("three"); - } + cache.Get(1).Should().Be("one"); + cache.Get(2).Should().BeNull(); + cache.Get(3).Should().Be("three"); } -} \ No newline at end of file +} diff --git a/DataStructures.Tests/DisjointSet/DisjointSetTests.cs b/DataStructures.Tests/DisjointSet/DisjointSetTests.cs index 28ed521f..1a9a07f9 100644 --- a/DataStructures.Tests/DisjointSet/DisjointSetTests.cs +++ b/DataStructures.Tests/DisjointSet/DisjointSetTests.cs @@ -1,33 +1,32 @@ -using DataStructures.DisjointSet; +using DataStructures.DisjointSet; using FluentAssertions; using NUnit.Framework; -namespace DataStructures.Tests.DisjointSet +namespace DataStructures.Tests.DisjointSet; + +[TestFixture] +public class DisjointSetTests { - [TestFixture] - public class DisjointSetTests + [Test] + public static void MakeSetDataInitializationTest() + { + DisjointSet ds = new(); + var one = ds.MakeSet(1); + var two = ds.MakeSet(2); + one.Data.Should().Be(1); + two.Data.Should().Be(2); + } + [Test] + public static void UnionTest() { - [Test] - public static void MakeSetDataInitializationTest() - { - DisjointSet ds = new(); - var one = ds.MakeSet(1); - var two = ds.MakeSet(2); - one.Data.Should().Be(1); - two.Data.Should().Be(2); - } - [Test] - public static void UnionTest() - { - DisjointSet ds = new(); - var one = ds.MakeSet(1); - var two = ds.MakeSet(2); - var three = ds.MakeSet(3); - ds.UnionSet(one, two); - ds.FindSet(one).Should().Be(ds.FindSet(two)); - ds.UnionSet(one, three); - ds.FindSet(two).Should().Be(ds.FindSet(three)); - (one.Rank + two.Rank + three.Rank).Should().Be(1); - } + DisjointSet ds = new(); + var one = ds.MakeSet(1); + var two = ds.MakeSet(2); + var three = ds.MakeSet(3); + ds.UnionSet(one, two); + ds.FindSet(one).Should().Be(ds.FindSet(two)); + ds.UnionSet(one, three); + ds.FindSet(two).Should().Be(ds.FindSet(three)); + (one.Rank + two.Rank + three.Rank).Should().Be(1); } } diff --git a/DataStructures.Tests/Fenwick/BinaryIndexedTreeTests.cs b/DataStructures.Tests/Fenwick/BinaryIndexedTreeTests.cs index cb8dbe9e..7de8a8b9 100644 --- a/DataStructures.Tests/Fenwick/BinaryIndexedTreeTests.cs +++ b/DataStructures.Tests/Fenwick/BinaryIndexedTreeTests.cs @@ -1,37 +1,35 @@ using DataStructures.Fenwick; -using NUnit.Framework; using FluentAssertions; -using System; +using NUnit.Framework; + +namespace DataStructures.Tests.Fenwick; -namespace DataStructures.Tests.Fenwick +[TestFixture] +internal class BinaryIndexedTreeTests { - [TestFixture] - internal class BinaryIndexedTreeTests + [Test] + public void GetSum_CreateBITAndRequestSum_ReturnCorrect() { - [Test] - public void GetSum_CreateBITAndRequestSum_ReturnCorrect() - { - int[] array = { 2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9 }; - var tree = new BinaryIndexedTree(array); - var expectedSum = 12; + int[] array = { 2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9 }; + var tree = new BinaryIndexedTree(array); + var expectedSum = 12; - var resultedSum = tree.GetSum(5); + var resultedSum = tree.GetSum(5); - resultedSum.Should().Be(expectedSum); - } + resultedSum.Should().Be(expectedSum); + } - [Test] - public void UpdateTree_UpdateTreeAndRequestSum_GetSum() - { - int[] array = { 2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9 }; - var tree = new BinaryIndexedTree(array); - var expectedSum = 18; + [Test] + public void UpdateTree_UpdateTreeAndRequestSum_GetSum() + { + int[] array = { 2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9 }; + var tree = new BinaryIndexedTree(array); + var expectedSum = 18; - array[3] += 6; - tree.UpdateTree(3, 6); + array[3] += 6; + tree.UpdateTree(3, 6); - var resultedSum = tree.GetSum(5); - resultedSum.Should().Be(expectedSum); - } + var resultedSum = tree.GetSum(5); + resultedSum.Should().Be(expectedSum); } } diff --git a/DataStructures.Tests/Graph/DirectedWeightedGraphTests.cs b/DataStructures.Tests/Graph/DirectedWeightedGraphTests.cs index 41a582d7..182c2d10 100644 --- a/DataStructures.Tests/Graph/DirectedWeightedGraphTests.cs +++ b/DataStructures.Tests/Graph/DirectedWeightedGraphTests.cs @@ -1,217 +1,216 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using DataStructures.Graph; using FluentAssertions; using NUnit.Framework; -namespace DataStructures.Tests.Graph +namespace DataStructures.Tests.Graph; + +[TestFixture] +public class DirectedWeightedGraphTests { - [TestFixture] - public class DirectedWeightedGraphTests + [Test] + [TestCase(-1)] + [TestCase(-2)] + [TestCase(-3)] + public void GraphInitializationTest_ShouldThrowOverflow(int capacity) { - [Test] - [TestCase(-1)] - [TestCase(-2)] - [TestCase(-3)] - public void GraphInitializationTest_ShouldThrowOverflow(int capacity) - { - Func> createGraph = () => new DirectedWeightedGraph(capacity); + Func> createGraph = () => new DirectedWeightedGraph(capacity); - createGraph.Should().Throw() - .WithMessage("Graph capacity should always be a non-negative integer."); - } + createGraph.Should().Throw() + .WithMessage("Graph capacity should always be a non-negative integer."); + } - [Test] - [TestCase(1)] - [TestCase(10)] - [TestCase(20)] - [TestCase(30)] - public void GraphInitializationTest_Success(int capacity) - { - Func> createGraph = () => new DirectedWeightedGraph(capacity); + [Test] + [TestCase(1)] + [TestCase(10)] + [TestCase(20)] + [TestCase(30)] + public void GraphInitializationTest_Success(int capacity) + { + Func> createGraph = () => new DirectedWeightedGraph(capacity); - createGraph.Should().NotThrow(); - } + createGraph.Should().NotThrow(); + } - [Test] - public void GraphAddVertexTest_Success() - { - var graph = new DirectedWeightedGraph(10); + [Test] + public void GraphAddVertexTest_Success() + { + var graph = new DirectedWeightedGraph(10); - graph.AddVertex('A'); - graph.AddVertex('B'); - graph.AddVertex('C'); + graph.AddVertex('A'); + graph.AddVertex('B'); + graph.AddVertex('C'); - graph.Count.Should().Be(3); - } + graph.Count.Should().Be(3); + } - [Test] - public void GraphAddVertexTest_ShouldThrowOverflow() + [Test] + public void GraphAddVertexTest_ShouldThrowOverflow() + { + var graph = new DirectedWeightedGraph(10); + for (var i = 0; i < 10; i++) { - var graph = new DirectedWeightedGraph(10); - for (var i = 0; i < 10; i++) - { - graph.AddVertex('A'); - } - - Action addOverflow = () => graph.AddVertex('A'); - - graph.Count.Should().Be(10); - graph.Vertices.Should().OnlyContain(x => x != null && x.Data == 'A'); - addOverflow.Should().Throw() - .WithMessage("Graph overflow."); + graph.AddVertex('A'); } - [Test] - public void GraphRemoveVertexTest_Success() - { - var graph = new DirectedWeightedGraph(10); - var vertexA = graph.AddVertex('A'); - var vertexB = graph.AddVertex('B'); - var vertexC = graph.AddVertex('C'); - graph.AddEdge(vertexB, vertexA, 5); - graph.AddEdge(vertexC, vertexA, 5); - var neighborsB = graph.GetNeighbors(vertexB).ToList(); - var neighborsC = graph.GetNeighbors(vertexC).ToList(); - - graph.RemoveVertex(vertexA); - - neighborsB.Should().HaveCount(1); - neighborsB[0].Should().Be(vertexA); - neighborsC.Should().HaveCount(1); - neighborsC[0].Should().Be(vertexA); - graph.GetNeighbors(vertexB).Should().HaveCount(0); - graph.GetNeighbors(vertexC).Should().HaveCount(0); - } + Action addOverflow = () => graph.AddVertex('A'); - [Test] - public void GraphRemoveVertexTest_ShouldThrowVertexNotInGraph() - { - var graph = new DirectedWeightedGraph(10); - var vertexA = new Vertex('A', 0); + graph.Count.Should().Be(10); + graph.Vertices.Should().OnlyContain(x => x != null && x.Data == 'A'); + addOverflow.Should().Throw() + .WithMessage("Graph overflow."); + } - Action removeVertex = () => graph.RemoveVertex(vertexA); + [Test] + public void GraphRemoveVertexTest_Success() + { + var graph = new DirectedWeightedGraph(10); + var vertexA = graph.AddVertex('A'); + var vertexB = graph.AddVertex('B'); + var vertexC = graph.AddVertex('C'); + graph.AddEdge(vertexB, vertexA, 5); + graph.AddEdge(vertexC, vertexA, 5); + var neighborsB = graph.GetNeighbors(vertexB).ToList(); + var neighborsC = graph.GetNeighbors(vertexC).ToList(); + + graph.RemoveVertex(vertexA); + + neighborsB.Should().HaveCount(1); + neighborsB[0].Should().Be(vertexA); + neighborsC.Should().HaveCount(1); + neighborsC[0].Should().Be(vertexA); + graph.GetNeighbors(vertexB).Should().HaveCount(0); + graph.GetNeighbors(vertexC).Should().HaveCount(0); + } - removeVertex.Should().Throw() - .WithMessage($"Vertex does not belong to graph: {vertexA}."); - } + [Test] + public void GraphRemoveVertexTest_ShouldThrowVertexNotInGraph() + { + var graph = new DirectedWeightedGraph(10); + var vertexA = new Vertex('A', 0); - [Test] - public void GraphAddEdgeTest_Success() - { - var graph = new DirectedWeightedGraph(10); - var vertexA = graph.AddVertex('A'); - var vertexB = graph.AddVertex('B'); - var vertexC = graph.AddVertex('C'); + Action removeVertex = () => graph.RemoveVertex(vertexA); - graph.AddEdge(vertexA, vertexB, 5); + removeVertex.Should().Throw() + .WithMessage($"Vertex does not belong to graph: {vertexA}."); + } - graph.AreAdjacent(vertexA, vertexB).Should().BeTrue(); - graph.AreAdjacent(vertexA, vertexC).Should().BeFalse(); - } + [Test] + public void GraphAddEdgeTest_Success() + { + var graph = new DirectedWeightedGraph(10); + var vertexA = graph.AddVertex('A'); + var vertexB = graph.AddVertex('B'); + var vertexC = graph.AddVertex('C'); - [Test] - public void GraphAddEdgeTest_ShouldThrowZeroWeight() - { - var graph = new DirectedWeightedGraph(10); - var vertexA = graph.AddVertex('A'); - var vertexB = graph.AddVertex('B'); + graph.AddEdge(vertexA, vertexB, 5); + + graph.AreAdjacent(vertexA, vertexB).Should().BeTrue(); + graph.AreAdjacent(vertexA, vertexC).Should().BeFalse(); + } - Action addZeroEdge = () => graph.AddEdge(vertexA, vertexB, 0); + [Test] + public void GraphAddEdgeTest_ShouldThrowZeroWeight() + { + var graph = new DirectedWeightedGraph(10); + var vertexA = graph.AddVertex('A'); + var vertexB = graph.AddVertex('B'); - addZeroEdge.Should().Throw() - .WithMessage("Edge weight cannot be zero."); - } + Action addZeroEdge = () => graph.AddEdge(vertexA, vertexB, 0); - [Test] - public void GraphAddEdgeTest_ShouldThrowVertexNotInGraph() - { - var graph = new DirectedWeightedGraph(10); - var vertexA = graph.AddVertex('A'); - var vertexB = new Vertex('B', 1); + addZeroEdge.Should().Throw() + .WithMessage("Edge weight cannot be zero."); + } - Action addZeroEdge = () => graph.AddEdge(vertexA, vertexB, 0); + [Test] + public void GraphAddEdgeTest_ShouldThrowVertexNotInGraph() + { + var graph = new DirectedWeightedGraph(10); + var vertexA = graph.AddVertex('A'); + var vertexB = new Vertex('B', 1); - addZeroEdge.Should().Throw() - .WithMessage($"Vertex does not belong to graph: {vertexB}."); - } + Action addZeroEdge = () => graph.AddEdge(vertexA, vertexB, 0); - [Test] - public void GraphAddEdgeTest_ShouldThrowEdgeExists() - { - var graph = new DirectedWeightedGraph(10); - var vertexA = graph.AddVertex('A'); - var vertexB = graph.AddVertex('B'); - const int currentEdgeWeight = 5; - graph.AddEdge(vertexA, vertexB, currentEdgeWeight); + addZeroEdge.Should().Throw() + .WithMessage($"Vertex does not belong to graph: {vertexB}."); + } - Action addZeroEdge = () => graph.AddEdge(vertexA, vertexB, 10); + [Test] + public void GraphAddEdgeTest_ShouldThrowEdgeExists() + { + var graph = new DirectedWeightedGraph(10); + var vertexA = graph.AddVertex('A'); + var vertexB = graph.AddVertex('B'); + const int currentEdgeWeight = 5; + graph.AddEdge(vertexA, vertexB, currentEdgeWeight); - addZeroEdge.Should().Throw() - .WithMessage($"Vertex already exists: {currentEdgeWeight}"); - } + Action addZeroEdge = () => graph.AddEdge(vertexA, vertexB, 10); - [Test] - public void GraphRemoveEdgeTest_Success() - { - var graph = new DirectedWeightedGraph(10); - var vertexA = graph.AddVertex('A'); - var vertexB = graph.AddVertex('B'); - graph.AddEdge(vertexA, vertexB, 5); + addZeroEdge.Should().Throw() + .WithMessage($"Vertex already exists: {currentEdgeWeight}"); + } - graph.RemoveEdge(vertexA, vertexB); + [Test] + public void GraphRemoveEdgeTest_Success() + { + var graph = new DirectedWeightedGraph(10); + var vertexA = graph.AddVertex('A'); + var vertexB = graph.AddVertex('B'); + graph.AddEdge(vertexA, vertexB, 5); - graph.AreAdjacent(vertexA, vertexB).Should().BeFalse(); - } + graph.RemoveEdge(vertexA, vertexB); - [Test] - public void GraphRemoveEdgeTest_ShouldThrowVertexNotInGraph() - { - var graph = new DirectedWeightedGraph(10); - var vertexA = graph.AddVertex('A'); - var vertexB = new Vertex('B', 1); + graph.AreAdjacent(vertexA, vertexB).Should().BeFalse(); + } - Action removeEdge = () => graph.RemoveEdge(vertexA, vertexB); + [Test] + public void GraphRemoveEdgeTest_ShouldThrowVertexNotInGraph() + { + var graph = new DirectedWeightedGraph(10); + var vertexA = graph.AddVertex('A'); + var vertexB = new Vertex('B', 1); - removeEdge.Should().Throw() - .WithMessage($"Vertex does not belong to graph: {vertexB}."); - } + Action removeEdge = () => graph.RemoveEdge(vertexA, vertexB); - [Test] - public void GraphGetNeighborsTest_Success() - { - var graph = new DirectedWeightedGraph(10); - var vertexA = graph.AddVertex('A'); - var vertexB = graph.AddVertex('B'); - var vertexC = graph.AddVertex('C'); - var vertexD = graph.AddVertex('D'); - graph.AddEdge(vertexA, vertexB, 5); - graph.AddEdge(vertexA, vertexC, 5); - graph.AddEdge(vertexA, vertexD, 5); - - var neighborsA = graph.GetNeighbors(vertexA).ToArray(); - - neighborsA.Should().HaveCount(3); - neighborsA[0].Should().Be(vertexB); - neighborsA[1].Should().Be(vertexC); - neighborsA[2].Should().Be(vertexD); - } + removeEdge.Should().Throw() + .WithMessage($"Vertex does not belong to graph: {vertexB}."); + } - [Test] - public void GraphGetNeighborsTest_ShouldThrowVertexNotInGraph() - { - var graph = new DirectedWeightedGraph(10); - var vertexA = new Vertex('A', 0); + [Test] + public void GraphGetNeighborsTest_Success() + { + var graph = new DirectedWeightedGraph(10); + var vertexA = graph.AddVertex('A'); + var vertexB = graph.AddVertex('B'); + var vertexC = graph.AddVertex('C'); + var vertexD = graph.AddVertex('D'); + graph.AddEdge(vertexA, vertexB, 5); + graph.AddEdge(vertexA, vertexC, 5); + graph.AddEdge(vertexA, vertexD, 5); + + var neighborsA = graph.GetNeighbors(vertexA).ToArray(); + + neighborsA.Should().HaveCount(3); + neighborsA[0].Should().Be(vertexB); + neighborsA[1].Should().Be(vertexC); + neighborsA[2].Should().Be(vertexD); + } - Func?>> getNeighbors = () => - { - var enumerable = graph.GetNeighbors(vertexA); - return enumerable.ToList(); - }; + [Test] + public void GraphGetNeighborsTest_ShouldThrowVertexNotInGraph() + { + var graph = new DirectedWeightedGraph(10); + var vertexA = new Vertex('A', 0); - getNeighbors.Should().Throw() - .WithMessage($"Vertex does not belong to graph: {vertexA}."); - } + Func?>> getNeighbors = () => + { + var enumerable = graph.GetNeighbors(vertexA); + return enumerable.ToList(); + }; + + getNeighbors.Should().Throw() + .WithMessage($"Vertex does not belong to graph: {vertexA}."); } } diff --git a/DataStructures.Tests/Hashing/HashTableTests.cs b/DataStructures.Tests/Hashing/HashTableTests.cs index ede5c14b..786d2770 100644 --- a/DataStructures.Tests/Hashing/HashTableTests.cs +++ b/DataStructures.Tests/Hashing/HashTableTests.cs @@ -3,383 +3,382 @@ using DataStructures.Hashing; using NUnit.Framework; -namespace DataStructures.Tests.Hashing +namespace DataStructures.Tests.Hashing; + +[TestFixture] +public class HashTableTests { - [TestFixture] - public class HashTableTests + [Test] + public void Add_ThrowsException_WhenKeyIsNull() { - [Test] - public void Add_ThrowsException_WhenKeyIsNull() - { - var hashTable = new HashTable(); + var hashTable = new HashTable(); - Assert.Throws(() => hashTable.Add(null, 1)); - } + Assert.Throws(() => hashTable.Add(null, 1)); + } - [Test] - public void Add_ThrowsException_WhenKeyAlreadyExists() - { - var hashTable = new HashTable(); + [Test] + public void Add_ThrowsException_WhenKeyAlreadyExists() + { + var hashTable = new HashTable(); - hashTable.Add("a", 1); + hashTable.Add("a", 1); - Assert.Throws(() => hashTable.Add("a", 2)); - } + Assert.Throws(() => hashTable.Add("a", 2)); + } - [Test] - public void Add_IncreasesCount_WhenKeyDoesNotExist() - { - var hashTable = new HashTable(); + [Test] + public void Add_IncreasesCount_WhenKeyDoesNotExist() + { + var hashTable = new HashTable(); - hashTable.Add("a", 1); + hashTable.Add("a", 1); - Assert.AreEqual(1, hashTable.Count); - } + Assert.AreEqual(1, hashTable.Count); + } - [Test] - public void Add_DoesNotIncreaseCount_WhenKeyAlreadyExists() + [Test] + public void Add_DoesNotIncreaseCount_WhenKeyAlreadyExists() + { + var hashTable = new HashTable(); + + hashTable.Add("a", 1); + try { - var hashTable = new HashTable(); - - hashTable.Add("a", 1); - try - { - hashTable.Add("a", 2); - } - catch (ArgumentException) - { - Console.WriteLine("ArgumentException"); - } - Assert.AreEqual(1, hashTable.Count); + hashTable.Add("a", 2); } - - [Test] - public void Add_ThrowsException_WhenValueIsNull() + catch (ArgumentException) { - var hashTable = new HashTable(); - - Assert.Throws(() => hashTable.Add("a", null)); + Console.WriteLine("ArgumentException"); } + Assert.AreEqual(1, hashTable.Count); + } - [Test] - public void Add_IncreasesCount_WhenValueDoesNotExist() - { - var hashTable = new HashTable(); + [Test] + public void Add_ThrowsException_WhenValueIsNull() + { + var hashTable = new HashTable(); - hashTable.Add("a", 1); + Assert.Throws(() => hashTable.Add("a", null)); + } - Assert.AreEqual(1, hashTable.Count); - } + [Test] + public void Add_IncreasesCount_WhenValueDoesNotExist() + { + var hashTable = new HashTable(); - [Test] - public void Add_DoesNotIncreaseCount_WhenValueAlreadyExists() - { - var hashTable = new HashTable(); + hashTable.Add("a", 1); - hashTable.Add("a", 1); + Assert.AreEqual(1, hashTable.Count); + } - try - { - hashTable.Add("b", 1); - } - catch (ArgumentException) - { - Console.WriteLine("ArgumentException"); - } + [Test] + public void Add_DoesNotIncreaseCount_WhenValueAlreadyExists() + { + var hashTable = new HashTable(); - Assert.AreEqual(2, hashTable.Count); - } + hashTable.Add("a", 1); - [Test] - public void Add_IncreasesCount_WhenValueIsNull() + try { - var hashTable = new HashTable(); - - try - { - hashTable.Add("a", null); - } - catch (ArgumentNullException) - { - Console.WriteLine("ArgumentNullException"); - } - Assert.AreEqual(0, hashTable.Count); + hashTable.Add("b", 1); } - - [Test] - public void Add_IncreasesCount_WhenValueAlreadyExists() + catch (ArgumentException) { - var hashTable = new HashTable(); - - hashTable.Add("a", 1); - hashTable.Add("b", 1); - Assert.AreEqual(2, hashTable.Count); + Console.WriteLine("ArgumentException"); } - [Test] - public void Remove_ThrowsException_WhenKeyIsNull() - { - var hashTable = new HashTable(); + Assert.AreEqual(2, hashTable.Count); + } - Assert.Throws(() => hashTable.Remove(null)); - } + [Test] + public void Add_IncreasesCount_WhenValueIsNull() + { + var hashTable = new HashTable(); - [Test] - public void Remove_ReturnsFalse_WhenKeyDoesNotExist() + try { - var hashTable = new HashTable(); - - Assert.IsFalse(hashTable.Remove("a")); + hashTable.Add("a", null); } - - [Test] - public void Remove_ReturnsTrue_WhenKeyExists() + catch (ArgumentNullException) { - var hashTable = new HashTable(); + Console.WriteLine("ArgumentNullException"); + } + Assert.AreEqual(0, hashTable.Count); + } - hashTable.Add("a", 1); + [Test] + public void Add_IncreasesCount_WhenValueAlreadyExists() + { + var hashTable = new HashTable(); - Assert.IsTrue(hashTable.Remove("a")); - } + hashTable.Add("a", 1); + hashTable.Add("b", 1); + Assert.AreEqual(2, hashTable.Count); + } - [Test] - public void Remove_DecreasesCount_WhenKeyExists() - { - var hashTable = new HashTable(); + [Test] + public void Remove_ThrowsException_WhenKeyIsNull() + { + var hashTable = new HashTable(); - hashTable.Add("a", 1); - hashTable.Remove("a"); + Assert.Throws(() => hashTable.Remove(null)); + } - Assert.AreEqual(0, hashTable.Count); - } + [Test] + public void Remove_ReturnsFalse_WhenKeyDoesNotExist() + { + var hashTable = new HashTable(); - [Test] - public void Remove_DoesNotDecreaseCount_WhenKeyDoesNotExist() - { - var hashTable = new HashTable(); + Assert.IsFalse(hashTable.Remove("a")); + } - hashTable.Remove("a"); + [Test] + public void Remove_ReturnsTrue_WhenKeyExists() + { + var hashTable = new HashTable(); - Assert.AreEqual(0, hashTable.Count); - } + hashTable.Add("a", 1); - [Test] - public void ContainsValue_ReturnsFalse_WhenValueDoesNotExist() - { - var hashTable = new HashTable(); + Assert.IsTrue(hashTable.Remove("a")); + } - Assert.IsFalse(hashTable.ContainsValue(1)); - } + [Test] + public void Remove_DecreasesCount_WhenKeyExists() + { + var hashTable = new HashTable(); - [Test] - public void ContainsValue_ReturnsTrue_WhenValueExists() - { - var hashTable = new HashTable(); + hashTable.Add("a", 1); + hashTable.Remove("a"); - hashTable.Add("a", 1); + Assert.AreEqual(0, hashTable.Count); + } - Assert.IsTrue(hashTable.ContainsValue(1)); - } + [Test] + public void Remove_DoesNotDecreaseCount_WhenKeyDoesNotExist() + { + var hashTable = new HashTable(); - [Test] - public void ContainsValue_ReturnsFalse_WhenValueIsNull() - { - var hashTable = new HashTable(); + hashTable.Remove("a"); - Assert.Throws(() => hashTable.ContainsValue(null)); - } + Assert.AreEqual(0, hashTable.Count); + } - [Test] - public void ContainsKey_ReturnsFalse_WhenKeyDoesNotExist() - { - var hashTable = new HashTable(); + [Test] + public void ContainsValue_ReturnsFalse_WhenValueDoesNotExist() + { + var hashTable = new HashTable(); - Assert.IsFalse(hashTable.ContainsKey("a")); - } + Assert.IsFalse(hashTable.ContainsValue(1)); + } - [Test] - public void ContainsKey_ReturnsTrue_WhenKeyExists() - { - var hashTable = new HashTable(); + [Test] + public void ContainsValue_ReturnsTrue_WhenValueExists() + { + var hashTable = new HashTable(); - hashTable.Add("a", 1); + hashTable.Add("a", 1); - Assert.IsTrue(hashTable.ContainsKey("a")); - } + Assert.IsTrue(hashTable.ContainsValue(1)); + } - [Test] - public void ContainsKey_ReturnsFalse_WhenKeyIsNull() - { - var hashTable = new HashTable(); + [Test] + public void ContainsValue_ReturnsFalse_WhenValueIsNull() + { + var hashTable = new HashTable(); - Assert.Throws(() => hashTable.ContainsKey(null)); - } + Assert.Throws(() => hashTable.ContainsValue(null)); + } - [Test] - public void Clear_SetsCountToZero() - { - var hashTable = new HashTable(); + [Test] + public void ContainsKey_ReturnsFalse_WhenKeyDoesNotExist() + { + var hashTable = new HashTable(); - hashTable.Add("a", 1); - hashTable.Clear(); + Assert.IsFalse(hashTable.ContainsKey("a")); + } - Assert.AreEqual(0, hashTable.Count); - } + [Test] + public void ContainsKey_ReturnsTrue_WhenKeyExists() + { + var hashTable = new HashTable(); - [Test] - public void Clear_RemovesAllElements() - { - var hashTable = new HashTable(); + hashTable.Add("a", 1); - hashTable.Add("a", 1); - hashTable.Clear(); + Assert.IsTrue(hashTable.ContainsKey("a")); + } - Assert.IsFalse(hashTable.ContainsKey("a")); - } + [Test] + public void ContainsKey_ReturnsFalse_WhenKeyIsNull() + { + var hashTable = new HashTable(); - [Test] - public void Resize_IncreasesCapacity() - { - var hashTable = new HashTable(4); - - hashTable.Add("one", 1); - hashTable.Add("two", 2); - hashTable.Add("three", 3); - hashTable.Add("four", 4); - hashTable.Add("humour", 5); - - /// Next Prime number after 4 is 5 - /// Capacity should be 5 - /// After resizing, the capacity should be 10 - Assert.AreEqual(10, hashTable.Capacity); - } - [Test] - public void LoadFactor_ReturnsCorrectValue() - { - var hashTable = new HashTable(4); - - hashTable.Add("one", 1); - hashTable.Add("two", 2); - hashTable.Add("three", 3); - hashTable.Add("four", 4); - hashTable.Add("humour", 5); - Assert.AreEqual(0.75f, hashTable.LoadFactor); - } + Assert.Throws(() => hashTable.ContainsKey(null)); + } - [Test] - public void Keys_ReturnsCorrectKeys() - { - var hashTable = new HashTable(); - hashTable.Add(1, "one"); - hashTable.Add(2, "two"); - hashTable.Add(3, "three"); + [Test] + public void Clear_SetsCountToZero() + { + var hashTable = new HashTable(); - var keys = new List { 1,2,3 }; + hashTable.Add("a", 1); + hashTable.Clear(); - CollectionAssert.AreEquivalent(keys, hashTable.Keys); - } + Assert.AreEqual(0, hashTable.Count); + } - [Test] - public void Values_ReturnsCorrectValues() - { - var hashTable = new HashTable(); - hashTable.Add(1, "one"); - hashTable.Add(2, "two"); - hashTable.Add(3, "three"); + [Test] + public void Clear_RemovesAllElements() + { + var hashTable = new HashTable(); - var values = new List { "one", "two", "three" }; + hashTable.Add("a", 1); + hashTable.Clear(); - CollectionAssert.AreEquivalent(values, hashTable?.Values); - } + Assert.IsFalse(hashTable.ContainsKey("a")); + } - [Test] - public void Constructor_ThrowsException_WhenCapacityIsZero() - { - Assert.Throws(() => new HashTable(0)); - } + [Test] + public void Resize_IncreasesCapacity() + { + var hashTable = new HashTable(4); + + hashTable.Add("one", 1); + hashTable.Add("two", 2); + hashTable.Add("three", 3); + hashTable.Add("four", 4); + hashTable.Add("humour", 5); + + /// Next Prime number after 4 is 5 + /// Capacity should be 5 + /// After resizing, the capacity should be 10 + Assert.AreEqual(10, hashTable.Capacity); + } + [Test] + public void LoadFactor_ReturnsCorrectValue() + { + var hashTable = new HashTable(4); + + hashTable.Add("one", 1); + hashTable.Add("two", 2); + hashTable.Add("three", 3); + hashTable.Add("four", 4); + hashTable.Add("humour", 5); + Assert.AreEqual(0.75f, hashTable.LoadFactor); + } - [Test] - public void Constructor_ThrowsException_WhenLoadFactorIsZero() - { - Assert.Throws(() => new HashTable(4, 0)); - } + [Test] + public void Keys_ReturnsCorrectKeys() + { + var hashTable = new HashTable(); + hashTable.Add(1, "one"); + hashTable.Add(2, "two"); + hashTable.Add(3, "three"); - [Test] - public void Constructor_ThrowsException_WhenLoadFactorIsLessThanZero() - { - Assert.Throws(() => new HashTable(4, -1)); - } + var keys = new List { 1,2,3 }; - [Test] - public void Constructor_ThrowsException_WhenLoadFactorIsGreaterThanOne() - { - Assert.Throws(() => new HashTable(4, 2)); - } + CollectionAssert.AreEquivalent(keys, hashTable.Keys); + } - [Test] - public void GetIndex_ThrowsException_WhenKeyIsNull() - { - var hashTable = new HashTable(4); - Assert.Throws(() => hashTable.GetIndex(null)); - } + [Test] + public void Values_ReturnsCorrectValues() + { + var hashTable = new HashTable(); + hashTable.Add(1, "one"); + hashTable.Add(2, "two"); + hashTable.Add(3, "three"); - [Test] - public void FindEntry_ThrowsException_WhenKeyIsNull() - { - var hashTable = new HashTable(4); - Assert.Throws(() => hashTable.FindEntry(null)); - } + var values = new List { "one", "two", "three" }; - [Test] - public void This_Get_ThrowsException_WhenKeyIsNull() - { - var hashTable = new HashTable(4); - Assert.Throws(() => - { - var value = hashTable[null]; - Console.WriteLine(value); - }); - } + CollectionAssert.AreEquivalent(values, hashTable?.Values); + } - [Test] - public void This_Set_ThrowsException_WhenKeyIsNull() - { - var hashTable = new HashTable(4); - Assert.Throws(() => hashTable[null] = 1); - } + [Test] + public void Constructor_ThrowsException_WhenCapacityIsZero() + { + Assert.Throws(() => new HashTable(0)); + } - [Test] - public void This_Get_ReturnsCorrectValue() - { - var hashTable = new HashTable(4); - hashTable.Add("one", 1); - Assert.AreEqual(1, hashTable["one"]); - } + [Test] + public void Constructor_ThrowsException_WhenLoadFactorIsZero() + { + Assert.Throws(() => new HashTable(4, 0)); + } - [Test] - public void This_Set_UpdatesValue() - { - var hashTable = new HashTable(4); - hashTable.Add("one", 1); - hashTable["one"] = 2; - Assert.AreEqual(2, hashTable["one"]); - } + [Test] + public void Constructor_ThrowsException_WhenLoadFactorIsLessThanZero() + { + Assert.Throws(() => new HashTable(4, -1)); + } - [Test] - public void This_Set_KeyNotFoundException_WhenKeyDoesNotExist() - { - var hashTable = new HashTable(4); - Assert.Throws(() => hashTable["one"] = 2); - } + [Test] + public void Constructor_ThrowsException_WhenLoadFactorIsGreaterThanOne() + { + Assert.Throws(() => new HashTable(4, 2)); + } - [Test] - public void This_Get_KeyNotFoundException_WhenKeyDoesNotExist() + [Test] + public void GetIndex_ThrowsException_WhenKeyIsNull() + { + var hashTable = new HashTable(4); + Assert.Throws(() => hashTable.GetIndex(null)); + } + + [Test] + public void FindEntry_ThrowsException_WhenKeyIsNull() + { + var hashTable = new HashTable(4); + Assert.Throws(() => hashTable.FindEntry(null)); + } + + [Test] + public void This_Get_ThrowsException_WhenKeyIsNull() + { + var hashTable = new HashTable(4); + Assert.Throws(() => { - var hashTable = new HashTable(4); - Assert.Throws(() => { - var value = hashTable["one"]; - Console.WriteLine(value); - }); - } + var value = hashTable[null]; + Console.WriteLine(value); + }); + } + + [Test] + public void This_Set_ThrowsException_WhenKeyIsNull() + { + var hashTable = new HashTable(4); + Assert.Throws(() => hashTable[null] = 1); + } + + [Test] + public void This_Get_ReturnsCorrectValue() + { + var hashTable = new HashTable(4); + hashTable.Add("one", 1); + Assert.AreEqual(1, hashTable["one"]); + } + + [Test] + public void This_Set_UpdatesValue() + { + var hashTable = new HashTable(4); + hashTable.Add("one", 1); + hashTable["one"] = 2; + Assert.AreEqual(2, hashTable["one"]); + } + + [Test] + public void This_Set_KeyNotFoundException_WhenKeyDoesNotExist() + { + var hashTable = new HashTable(4); + Assert.Throws(() => hashTable["one"] = 2); + } + + [Test] + public void This_Get_KeyNotFoundException_WhenKeyDoesNotExist() + { + var hashTable = new HashTable(4); + Assert.Throws(() => { + var value = hashTable["one"]; + Console.WriteLine(value); + }); } } diff --git a/DataStructures.Tests/Hashing/NumberTheory/PrimeNumberTests.cs b/DataStructures.Tests/Hashing/NumberTheory/PrimeNumberTests.cs index d0c9db47..d6e11c57 100644 --- a/DataStructures.Tests/Hashing/NumberTheory/PrimeNumberTests.cs +++ b/DataStructures.Tests/Hashing/NumberTheory/PrimeNumberTests.cs @@ -3,110 +3,109 @@ using DataStructures.Hashing.NumberTheory; using NUnit.Framework; -namespace DataStructures.Tests.Hashing.NumberTheory +namespace DataStructures.Tests.Hashing.NumberTheory; + +[TestFixture] +public static class PrimeNumberTests { - [TestFixture] - public static class PrimeNumberTests + private static readonly object[] IsPrimeSource = { - private static readonly object[] IsPrimeSource = - { - new object[] { 0, false }, - new object[] { 1, false }, - new object[] { 2, true }, - new object[] { 3, true }, - new object[] { 4, false }, - new object[] { 5, true }, - new object[] { 6, false }, - new object[] { 7, true }, - new object[] { 8, false }, - new object[] { 9, false }, - new object[] { 10, false }, - new object[] { 11, true }, - new object[] { 12, false }, - new object[] { 13, true }, - new object[] { 14, false }, - new object[] { 15, false }, - new object[] { 16, false }, - new object[] { 17, true }, - new object[] { 18, false }, - new object[] { 19, true }, - new object[] { 20, false }, - new object[] { 21, false }, - new object[] { 22, false }, - new object[] { 23, true }, - new object[] { 24, false }, - new object[] { 25, false }, - new object[] { 26, false }, - new object[] { 27, false }, - new object[] { 28, false }, - new object[] { 29, true }, - new object[] { 30, false }, - new object[] { 31, true }, - new object[] { 32, false }, - new object[] { 33, false }, - new object[] { 34, false }, - new object[] { 35, false }, - new object[] { 36, false }, - new object[] { 37, true }, - new object[] { 38, false }, - new object[] { 39, false }, - new object[] { 40, false }, - }; + new object[] { 0, false }, + new object[] { 1, false }, + new object[] { 2, true }, + new object[] { 3, true }, + new object[] { 4, false }, + new object[] { 5, true }, + new object[] { 6, false }, + new object[] { 7, true }, + new object[] { 8, false }, + new object[] { 9, false }, + new object[] { 10, false }, + new object[] { 11, true }, + new object[] { 12, false }, + new object[] { 13, true }, + new object[] { 14, false }, + new object[] { 15, false }, + new object[] { 16, false }, + new object[] { 17, true }, + new object[] { 18, false }, + new object[] { 19, true }, + new object[] { 20, false }, + new object[] { 21, false }, + new object[] { 22, false }, + new object[] { 23, true }, + new object[] { 24, false }, + new object[] { 25, false }, + new object[] { 26, false }, + new object[] { 27, false }, + new object[] { 28, false }, + new object[] { 29, true }, + new object[] { 30, false }, + new object[] { 31, true }, + new object[] { 32, false }, + new object[] { 33, false }, + new object[] { 34, false }, + new object[] { 35, false }, + new object[] { 36, false }, + new object[] { 37, true }, + new object[] { 38, false }, + new object[] { 39, false }, + new object[] { 40, false }, + }; - private static readonly object[] NextPrimeSource = - { - new object[] { 0, 1, false, 2 }, - new object[] { 1, 1, false, 2 }, - new object[] { 3, 1, false, 5 }, - new object[] { 4, 1, false, 5 }, - new object[] { 5, 1, false, 7 }, - new object[] { 6, 1, false, 7 }, - new object[] { 7, 1, false, 11 }, - new object[] { 8, 1, false, 11 }, - new object[] { 9, 1, false, 11 }, - new object[] { 10, 1, false, 11 }, - new object[] { 11, 1, false, 13 }, - new object[] { 12, 1, false, 13 }, - new object[] { 13, 1, false, 17 }, - new object[] { 14, 1, false, 17 }, - new object[] { 15, 1, false, 17 }, - new object[] { 16, 1, false, 17 }, - new object[] { 17, 1, false, 19 }, - new object[] { 18, 1, false, 19 }, - new object[] { 19, 1, false, 23 }, - new object[] { 20, 1, false, 23 }, - new object[] { 21, 1, false, 23 }, - new object[] { 22, 1, false, 23 }, - new object[] { 23, 1, false, 29 }, - new object[] { 24, 1, false, 29 }, - new object[] { 25, 1, false, 29 }, - new object[] { 26, 1, false, 29 }, - new object[] { 27, 1, false, 29 }, - new object[] { 28, 1, false, 29 }, - new object[] { 29, 1, false, 31 }, - new object[] { 4, 1, true, 3 }, - new object[] { 5, 1, true, 3 }, - new object[] { 6, 1, true, 5 }, - new object[] { 7, 1, true, 5 }, - new object[] { 8, 1, true, 7 }, - new object[] { 9, 1, true, 7 }, - new object[] { 10, 1, true, 7 } - }; + private static readonly object[] NextPrimeSource = + { + new object[] { 0, 1, false, 2 }, + new object[] { 1, 1, false, 2 }, + new object[] { 3, 1, false, 5 }, + new object[] { 4, 1, false, 5 }, + new object[] { 5, 1, false, 7 }, + new object[] { 6, 1, false, 7 }, + new object[] { 7, 1, false, 11 }, + new object[] { 8, 1, false, 11 }, + new object[] { 9, 1, false, 11 }, + new object[] { 10, 1, false, 11 }, + new object[] { 11, 1, false, 13 }, + new object[] { 12, 1, false, 13 }, + new object[] { 13, 1, false, 17 }, + new object[] { 14, 1, false, 17 }, + new object[] { 15, 1, false, 17 }, + new object[] { 16, 1, false, 17 }, + new object[] { 17, 1, false, 19 }, + new object[] { 18, 1, false, 19 }, + new object[] { 19, 1, false, 23 }, + new object[] { 20, 1, false, 23 }, + new object[] { 21, 1, false, 23 }, + new object[] { 22, 1, false, 23 }, + new object[] { 23, 1, false, 29 }, + new object[] { 24, 1, false, 29 }, + new object[] { 25, 1, false, 29 }, + new object[] { 26, 1, false, 29 }, + new object[] { 27, 1, false, 29 }, + new object[] { 28, 1, false, 29 }, + new object[] { 29, 1, false, 31 }, + new object[] { 4, 1, true, 3 }, + new object[] { 5, 1, true, 3 }, + new object[] { 6, 1, true, 5 }, + new object[] { 7, 1, true, 5 }, + new object[] { 8, 1, true, 7 }, + new object[] { 9, 1, true, 7 }, + new object[] { 10, 1, true, 7 } + }; - [Test] - [TestCaseSource("IsPrimeSource")] - public static void IsPrimeTest(int number, bool expected) - { - var actual = PrimeNumber.IsPrime(number); - Assert.AreEqual(expected, actual); - } + [Test] + [TestCaseSource("IsPrimeSource")] + public static void IsPrimeTest(int number, bool expected) + { + var actual = PrimeNumber.IsPrime(number); + Assert.AreEqual(expected, actual); + } - [Test] - [TestCaseSource("NextPrimeSource")] - public static void NextPrimeTest(int number, int factor, bool desc, int expected) - { - var actual = PrimeNumber.NextPrime(number, factor, desc); - Assert.AreEqual(expected, actual); - } + [Test] + [TestCaseSource("NextPrimeSource")] + public static void NextPrimeTest(int number, int factor, bool desc, int expected) + { + var actual = PrimeNumber.NextPrime(number, factor, desc); + Assert.AreEqual(expected, actual); } } diff --git a/DataStructures.Tests/Heap/BinaryHeapTests.cs b/DataStructures.Tests/Heap/BinaryHeapTests.cs index 45a066e8..3ebdf9c6 100644 --- a/DataStructures.Tests/Heap/BinaryHeapTests.cs +++ b/DataStructures.Tests/Heap/BinaryHeapTests.cs @@ -1,156 +1,155 @@ -using System; +using System; using System.Collections.Generic; using DataStructures.Heap; using NUnit.Framework; -namespace DataStructures.Tests.Heap +namespace DataStructures.Tests.Heap; + +internal static class BinaryHeapTests { - internal static class BinaryHeapTests + private static BinaryHeap BuildTestHeap() { - private static BinaryHeap BuildTestHeap() + var heap = new BinaryHeap(); + var elems = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + foreach (var i in elems) { - var heap = new BinaryHeap(); - var elems = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - foreach (var i in elems) - { - heap.Push(i); - } - - return heap; + heap.Push(i); } - [Test] - public static void Constructor_UseCustomComparer_BuildCorrectHeap() + return heap; + } + + [Test] + public static void Constructor_UseCustomComparer_BuildCorrectHeap() + { + var revHeap = new BinaryHeap(Comparer.Create((x, y) => y.CompareTo(x))); + foreach (var i in new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) { - var revHeap = new BinaryHeap(Comparer.Create((x, y) => y.CompareTo(x))); - foreach (var i in new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) - { - revHeap.Push(i); - } - - Assert.AreEqual(10, revHeap.Count); - Assert.AreEqual(1, revHeap.Peek()); - Assert.AreEqual(1, revHeap.Pop()); - Assert.AreEqual(2, revHeap.Peek()); + revHeap.Push(i); } - [Test] - public static void Push_AddElements_BuildCorrectHeap() - { - var heap = BuildTestHeap(); + Assert.AreEqual(10, revHeap.Count); + Assert.AreEqual(1, revHeap.Peek()); + Assert.AreEqual(1, revHeap.Pop()); + Assert.AreEqual(2, revHeap.Peek()); + } - Assert.AreEqual(10, heap.Peek()); - Assert.AreEqual(10, heap.Count); - } + [Test] + public static void Push_AddElements_BuildCorrectHeap() + { + var heap = BuildTestHeap(); - public static void Pop_RemoveElements_HeapStillValid() - { - var heap = BuildTestHeap(); + Assert.AreEqual(10, heap.Peek()); + Assert.AreEqual(10, heap.Count); + } - Assert.AreEqual(10, heap.Peek()); - Assert.AreEqual(10, heap.Count); + public static void Pop_RemoveElements_HeapStillValid() + { + var heap = BuildTestHeap(); - Assert.AreEqual(10, heap.Pop()); - Assert.AreEqual(9, heap.Count); - Assert.IsFalse(heap.Contains(10)); + Assert.AreEqual(10, heap.Peek()); + Assert.AreEqual(10, heap.Count); - Assert.AreEqual(9, heap.Pop()); - Assert.AreEqual(8, heap.Count); - Assert.IsFalse(heap.Contains(9)); - } + Assert.AreEqual(10, heap.Pop()); + Assert.AreEqual(9, heap.Count); + Assert.IsFalse(heap.Contains(10)); - [Test] - public static void Pop_EmptyHeap_ThrowsCorrectException() - { - var heap = new BinaryHeap(); + Assert.AreEqual(9, heap.Pop()); + Assert.AreEqual(8, heap.Count); + Assert.IsFalse(heap.Contains(9)); + } - Assert.Throws(() => heap.Pop()); - } + [Test] + public static void Pop_EmptyHeap_ThrowsCorrectException() + { + var heap = new BinaryHeap(); - [Test] - public static void Peek_NonEmptyHeap_ReturnsCorrectAnswer() - { - var heap = BuildTestHeap(); + Assert.Throws(() => heap.Pop()); + } - Assert.AreEqual(10, heap.Peek()); - } + [Test] + public static void Peek_NonEmptyHeap_ReturnsCorrectAnswer() + { + var heap = BuildTestHeap(); - [Test] - public static void Peek_EmptyHeap_ThrowsCorrectException() - { - var heap = new BinaryHeap(); + Assert.AreEqual(10, heap.Peek()); + } - Assert.Throws(() => heap.Peek()); - } + [Test] + public static void Peek_EmptyHeap_ThrowsCorrectException() + { + var heap = new BinaryHeap(); - [Test] - public static void PushPop_EmptyHeap_ReturnsCorrectAnswer() - { - var heap = new BinaryHeap(); + Assert.Throws(() => heap.Peek()); + } - Assert.AreEqual(10, heap.PushPop(10)); - } + [Test] + public static void PushPop_EmptyHeap_ReturnsCorrectAnswer() + { + var heap = new BinaryHeap(); - [Test] - public static void PushPop_NonEmptyHeap_ReturnsCorrectAnswer() - { - var heap = BuildTestHeap(); + Assert.AreEqual(10, heap.PushPop(10)); + } - Assert.AreEqual(20, heap.PushPop(20)); - Assert.AreEqual(10, heap.PushPop(-10)); - } + [Test] + public static void PushPop_NonEmptyHeap_ReturnsCorrectAnswer() + { + var heap = BuildTestHeap(); - [Test] - public static void Contains_NonEmptyHeap_ReturnsCorrectAnswer() - { - var heap = BuildTestHeap(); + Assert.AreEqual(20, heap.PushPop(20)); + Assert.AreEqual(10, heap.PushPop(-10)); + } - Assert.IsTrue(heap.Contains(1)); - Assert.IsTrue(heap.Contains(5)); - Assert.IsTrue(heap.Contains(10)); - Assert.IsFalse(heap.Contains(11)); - } + [Test] + public static void Contains_NonEmptyHeap_ReturnsCorrectAnswer() + { + var heap = BuildTestHeap(); - [Test] - public static void Contains_EmptyHeap_ReturnsCorrectAnswer() - { - var heap = new BinaryHeap(); + Assert.IsTrue(heap.Contains(1)); + Assert.IsTrue(heap.Contains(5)); + Assert.IsTrue(heap.Contains(10)); + Assert.IsFalse(heap.Contains(11)); + } - Assert.IsFalse(heap.Contains(1)); - Assert.IsFalse(heap.Contains(5)); - Assert.IsFalse(heap.Contains(10)); - Assert.IsFalse(heap.Contains(11)); - } + [Test] + public static void Contains_EmptyHeap_ReturnsCorrectAnswer() + { + var heap = new BinaryHeap(); - [Test] - public static void Remove_NonEmptyHeap_HeapStillValid() - { - var heap = BuildTestHeap(); + Assert.IsFalse(heap.Contains(1)); + Assert.IsFalse(heap.Contains(5)); + Assert.IsFalse(heap.Contains(10)); + Assert.IsFalse(heap.Contains(11)); + } + + [Test] + public static void Remove_NonEmptyHeap_HeapStillValid() + { + var heap = BuildTestHeap(); - heap.Remove(2); - Assert.IsFalse(heap.Contains(2)); - Assert.AreEqual(10, heap.Peek()); - Assert.AreEqual(9, heap.Count); + heap.Remove(2); + Assert.IsFalse(heap.Contains(2)); + Assert.AreEqual(10, heap.Peek()); + Assert.AreEqual(9, heap.Count); - heap.Remove(8); - Assert.IsFalse(heap.Contains(8)); - Assert.AreEqual(10, heap.Peek()); - Assert.AreEqual(8, heap.Count); + heap.Remove(8); + Assert.IsFalse(heap.Contains(8)); + Assert.AreEqual(10, heap.Peek()); + Assert.AreEqual(8, heap.Count); - heap.Remove(5); - Assert.IsFalse(heap.Contains(5)); - Assert.AreEqual(10, heap.Peek()); - Assert.AreEqual(7, heap.Count); + heap.Remove(5); + Assert.IsFalse(heap.Contains(5)); + Assert.AreEqual(10, heap.Peek()); + Assert.AreEqual(7, heap.Count); - Assert.Throws(() => heap.Remove(11)); - } + Assert.Throws(() => heap.Remove(11)); + } - [Test] - public static void Remove_EmptyHeap_ThrowsCorrectException() - { - var heap = new BinaryHeap(); + [Test] + public static void Remove_EmptyHeap_ThrowsCorrectException() + { + var heap = new BinaryHeap(); - Assert.Throws(() => heap.Remove(1)); - } + Assert.Throws(() => heap.Remove(1)); } } diff --git a/DataStructures.Tests/Heap/FibonacciHeaps/FibonacciHeapTests.cs b/DataStructures.Tests/Heap/FibonacciHeaps/FibonacciHeapTests.cs index 124ca31a..300a340f 100644 --- a/DataStructures.Tests/Heap/FibonacciHeaps/FibonacciHeapTests.cs +++ b/DataStructures.Tests/Heap/FibonacciHeaps/FibonacciHeapTests.cs @@ -1,278 +1,277 @@ -using System; +using System; using DataStructures.Heap.FibonacciHeap; using NUnit.Framework; -namespace DataStructures.Tests.Heap.FibonacciHeaps +namespace DataStructures.Tests.Heap.FibonacciHeaps; + +internal class TestFHeap : FibonacciHeap { - internal class TestFHeap : FibonacciHeap + public void RawCut(FHeapNode x, FHeapNode y) { - public void RawCut(FHeapNode x, FHeapNode y) - { - Cut(x, y); - } - - public void RawCascadingCut(FHeapNode y) - { - CascadingCut(y); - } + Cut(x, y); + } - public void RawConsolidate() - { - Consolidate(); - } + public void RawCascadingCut(FHeapNode y) + { + CascadingCut(y); } - internal static class FibonacciHeapTests + public void RawConsolidate() { - private static FibonacciHeap BuildTestHeap() - { - var heap = new FibonacciHeap(); - var elems = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; - foreach (var i in elems) - { - heap.Push(i); - } - - return heap; - } + Consolidate(); + } +} - [Test] - public static void Push_AddElements_BuildCorrectHeap() +internal static class FibonacciHeapTests +{ + private static FibonacciHeap BuildTestHeap() + { + var heap = new FibonacciHeap(); + var elems = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + foreach (var i in elems) { - var heap = BuildTestHeap(); - - Assert.AreEqual(1, heap.Peek()); - Assert.AreEqual(10, heap.Count); + heap.Push(i); } - public static void Pop_RemoveElements_HeapStillValid() - { - var heap = BuildTestHeap(); + return heap; + } - Assert.AreEqual(1, heap.Peek()); - Assert.AreEqual(10, heap.Count); + [Test] + public static void Push_AddElements_BuildCorrectHeap() + { + var heap = BuildTestHeap(); - Assert.AreEqual(1, heap.Pop()); - Assert.AreEqual(9, heap.Count); + Assert.AreEqual(1, heap.Peek()); + Assert.AreEqual(10, heap.Count); + } - Assert.AreEqual(2, heap.Pop()); - Assert.AreEqual(8, heap.Count); - } + public static void Pop_RemoveElements_HeapStillValid() + { + var heap = BuildTestHeap(); - [Test] - public static void Pop_EmptyHeap_ThrowsCorrectException() - { - var heap = new FibonacciHeap(); + Assert.AreEqual(1, heap.Peek()); + Assert.AreEqual(10, heap.Count); - Assert.Throws(() => heap.Pop()); - } + Assert.AreEqual(1, heap.Pop()); + Assert.AreEqual(9, heap.Count); - [Test] - public static void Pop_NonEmptyHeap_ReturnsInSortedOrder() - { - var heap = new FibonacciHeap(); + Assert.AreEqual(2, heap.Pop()); + Assert.AreEqual(8, heap.Count); + } - var rand = new Random(); - var heapSize = 100; + [Test] + public static void Pop_EmptyHeap_ThrowsCorrectException() + { + var heap = new FibonacciHeap(); - for (var i = 0; i < heapSize; i++) - { - heap.Push(rand.Next(1000)); - } + Assert.Throws(() => heap.Pop()); + } - var element = heap.Pop(); + [Test] + public static void Pop_NonEmptyHeap_ReturnsInSortedOrder() + { + var heap = new FibonacciHeap(); - for (var i = 0; i < heapSize - 1; i++) - { - var newElement = heap.Pop(); - Assert.LessOrEqual(element, newElement); - element = newElement; - } + var rand = new Random(); + var heapSize = 100; - Assert.Zero(heap.Count); + for (var i = 0; i < heapSize; i++) + { + heap.Push(rand.Next(1000)); } - [Test] - public static void Peek_EmptyHeap_ThrowsCorrectException() - { - var heap = new FibonacciHeap(); + var element = heap.Pop(); - Assert.Throws(() => heap.Peek()); + for (var i = 0; i < heapSize - 1; i++) + { + var newElement = heap.Pop(); + Assert.LessOrEqual(element, newElement); + element = newElement; } - [Test] - public static void DecreaseKey_NonEmptyHeap_ReturnsCorrectAnswer() - { - var heap = BuildTestHeap(); + Assert.Zero(heap.Count); + } - var node = heap.Push(11); - heap.DecreaseKey(node, -1); + [Test] + public static void Peek_EmptyHeap_ThrowsCorrectException() + { + var heap = new FibonacciHeap(); - Assert.AreEqual(heap.Pop(), -1); - Assert.AreEqual(heap.Pop(), 1); + Assert.Throws(() => heap.Peek()); + } - node = heap.Push(5); - heap.DecreaseKey(node, 1); - Assert.AreEqual(heap.Pop(), 1); + [Test] + public static void DecreaseKey_NonEmptyHeap_ReturnsCorrectAnswer() + { + var heap = BuildTestHeap(); - Assert.AreEqual(heap.Pop(), 2); - Assert.AreEqual(heap.Pop(), 3); - } + var node = heap.Push(11); + heap.DecreaseKey(node, -1); - [Test] - public static void Union_NonEmptyHeap_ReturnsSortedOrder() - { - var oddHeap = new FibonacciHeap(); + Assert.AreEqual(heap.Pop(), -1); + Assert.AreEqual(heap.Pop(), 1); - for (var i = 1; i < 10; i += 2) - { - oddHeap.Push(i); - } + node = heap.Push(5); + heap.DecreaseKey(node, 1); + Assert.AreEqual(heap.Pop(), 1); - var evenHeap = new FibonacciHeap(); + Assert.AreEqual(heap.Pop(), 2); + Assert.AreEqual(heap.Pop(), 3); + } - for (var i = 0; i < 10; i += 2) - { - evenHeap.Push(i); - } + [Test] + public static void Union_NonEmptyHeap_ReturnsSortedOrder() + { + var oddHeap = new FibonacciHeap(); - oddHeap.Union(evenHeap); + for (var i = 1; i < 10; i += 2) + { + oddHeap.Push(i); + } - for (var i = 0; i < 10; i++) - { - Assert.AreEqual(i, oddHeap.Pop()); - } + var evenHeap = new FibonacciHeap(); - Assert.Zero(oddHeap.Count); - Assert.Zero(evenHeap.Count); + for (var i = 0; i < 10; i += 2) + { + evenHeap.Push(i); } - [Test] - public static void Union_EmptyHeap_BecomesOtherHeap() - { - var thisHeap = new FibonacciHeap(); - var otherHeap = BuildTestHeap(); + oddHeap.Union(evenHeap); - var minNode = otherHeap.Peek(); - var otherCount = otherHeap.Count; + for (var i = 0; i < 10; i++) + { + Assert.AreEqual(i, oddHeap.Pop()); + } - Assert.Zero(thisHeap.Count); + Assert.Zero(oddHeap.Count); + Assert.Zero(evenHeap.Count); + } - thisHeap.Union(otherHeap); + [Test] + public static void Union_EmptyHeap_BecomesOtherHeap() + { + var thisHeap = new FibonacciHeap(); + var otherHeap = BuildTestHeap(); - Assert.Zero(otherHeap.Count); - Assert.AreEqual(thisHeap.Peek(), minNode); - Assert.Throws(() => otherHeap.Peek()); + var minNode = otherHeap.Peek(); + var otherCount = otherHeap.Count; - Assert.AreEqual(otherCount, thisHeap.Count); - } + Assert.Zero(thisHeap.Count); - [Test] - public static void Union_FullHeapWithEmptyHeap_Unchanged() - { - var thisHeap = BuildTestHeap(); - var otherHeap = new FibonacciHeap(); + thisHeap.Union(otherHeap); - var previousCount = thisHeap.Count; - var previousMin = thisHeap.Peek(); + Assert.Zero(otherHeap.Count); + Assert.AreEqual(thisHeap.Peek(), minNode); + Assert.Throws(() => otherHeap.Peek()); - thisHeap.Union(otherHeap); + Assert.AreEqual(otherCount, thisHeap.Count); + } - Assert.AreEqual(thisHeap.Count, previousCount); - Assert.AreEqual(thisHeap.Peek(), previousMin); - } + [Test] + public static void Union_FullHeapWithEmptyHeap_Unchanged() + { + var thisHeap = BuildTestHeap(); + var otherHeap = new FibonacciHeap(); - [Test] - public static void DecreaseKey_EmptyHeap_ThrowsCorrectException() - { - var heap = new FibonacciHeap(); - var item = new FHeapNode(1); + var previousCount = thisHeap.Count; + var previousMin = thisHeap.Peek(); - Assert.Throws(() => heap.DecreaseKey(item, 0)); - } + thisHeap.Union(otherHeap); - [Test] - public static void DecreaseKey_TryIncreaseKey_ThrowsCorrectException() - { - var heap = new FibonacciHeap(); - var item = heap.Push(1); + Assert.AreEqual(thisHeap.Count, previousCount); + Assert.AreEqual(thisHeap.Peek(), previousMin); + } - Assert.Throws(() => heap.DecreaseKey(item, 2)); - } + [Test] + public static void DecreaseKey_EmptyHeap_ThrowsCorrectException() + { + var heap = new FibonacciHeap(); + var item = new FHeapNode(1); - [Test] - public static void DecreaseKey_NonEmptyHeap_PreservesHeapStructure() - { - var heap = new FibonacciHeap(); + Assert.Throws(() => heap.DecreaseKey(item, 0)); + } - for (var i = 11; i < 20; i++) - { - heap.Push(i); - } + [Test] + public static void DecreaseKey_TryIncreaseKey_ThrowsCorrectException() + { + var heap = new FibonacciHeap(); + var item = heap.Push(1); - var item = heap.Push(10); + Assert.Throws(() => heap.DecreaseKey(item, 2)); + } - for (var i = 0; i < 10; i++) - { - heap.Push(i); - } + [Test] + public static void DecreaseKey_NonEmptyHeap_PreservesHeapStructure() + { + var heap = new FibonacciHeap(); - var bigItem = heap.Push(20); + for (var i = 11; i < 20; i++) + { + heap.Push(i); + } - heap.DecreaseKey(item, -1); - Assert.AreEqual(heap.Pop(), -1); + var item = heap.Push(10); - var currentVal = -1; - for (var i = 0; i < 10; i++) - { - var newVal = heap.Pop(); - Assert.True(currentVal < newVal); + for (var i = 0; i < 10; i++) + { + heap.Push(i); + } - currentVal = newVal; - } + var bigItem = heap.Push(20); - heap.DecreaseKey(bigItem, -1); - Assert.AreEqual(heap.Pop(), -1); + heap.DecreaseKey(item, -1); + Assert.AreEqual(heap.Pop(), -1); - currentVal = -1; - for (var i = 0; i < 9; i++) - { - var newVal = heap.Pop(); - Assert.True(currentVal < newVal); + var currentVal = -1; + for (var i = 0; i < 10; i++) + { + var newVal = heap.Pop(); + Assert.True(currentVal < newVal); - currentVal = newVal; - } + currentVal = newVal; } - [Test] - public static void Cut_EmptyHeap_ThrowsCorrectExcpetion() + heap.DecreaseKey(bigItem, -1); + Assert.AreEqual(heap.Pop(), -1); + + currentVal = -1; + for (var i = 0; i < 9; i++) { - var heap = new TestFHeap(); - var item1 = new FHeapNode(1); - var item2 = new FHeapNode(2); + var newVal = heap.Pop(); + Assert.True(currentVal < newVal); - Assert.Throws(() => heap.RawCut(item1, item2)); + currentVal = newVal; } + } - [Test] - public static void Cut_FilledHeap_AlteredItem() - { - var heap = new TestFHeap(); - var item1 = heap.Push(1); - var item2 = heap.Push(2); + [Test] + public static void Cut_EmptyHeap_ThrowsCorrectExcpetion() + { + var heap = new TestFHeap(); + var item1 = new FHeapNode(1); + var item2 = new FHeapNode(2); - item2.Degree = -1; + Assert.Throws(() => heap.RawCut(item1, item2)); + } - Assert.Throws(() => heap.RawCut(item1, item2)); - } + [Test] + public static void Cut_FilledHeap_AlteredItem() + { + var heap = new TestFHeap(); + var item1 = heap.Push(1); + var item2 = heap.Push(2); - [Test] - public static void Consolidate_EmptyHeap_DoesNothing() - { - var heap = new TestFHeap(); - heap.RawConsolidate(); + item2.Degree = -1; - Assert.Throws(() => heap.Peek()); - } + Assert.Throws(() => heap.RawCut(item1, item2)); + } + + [Test] + public static void Consolidate_EmptyHeap_DoesNothing() + { + var heap = new TestFHeap(); + heap.RawConsolidate(); + + Assert.Throws(() => heap.Peek()); } } diff --git a/DataStructures.Tests/Heap/MinMaxHeapTests.cs b/DataStructures.Tests/Heap/MinMaxHeapTests.cs index 45053384..7752681a 100644 --- a/DataStructures.Tests/Heap/MinMaxHeapTests.cs +++ b/DataStructures.Tests/Heap/MinMaxHeapTests.cs @@ -1,163 +1,162 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using DataStructures.Heap; using NUnit.Framework; -namespace DataStructures.Tests.Heap +namespace DataStructures.Tests.Heap; + +[TestFixture] +public static class MinMaxHeapTests { - [TestFixture] - public static class MinMaxHeapTests + private static readonly object[] CollectionsSource = { - private static readonly object[] CollectionsSource = - { - new[] { 5, 10, -2, 0, 3, 13, 5, -8, 41, -5, -7, -60, -12 }, - new[] { 'e', '4', 'x', 'D', '!', '$', '-', '_', '2', ')', 'Z', 'q' }, - new[] { "abc", "abc", "xyz", "bcd", "klm", "opq", "ijk" }, - }; + new[] { 5, 10, -2, 0, 3, 13, 5, -8, 41, -5, -7, -60, -12 }, + new[] { 'e', '4', 'x', 'D', '!', '$', '-', '_', '2', ')', 'Z', 'q' }, + new[] { "abc", "abc", "xyz", "bcd", "klm", "opq", "ijk" }, + }; + + [Test] + public static void CustomComparerTest() + { + var arr = new[] { "aaaa", "c", "dd", "bbb" }; + var comparer = Comparer.Create((a, b) => Comparer.Default.Compare(a.Length, b.Length)); - [Test] - public static void CustomComparerTest() + var mmh = new MinMaxHeap(comparer: comparer); + foreach (var s in arr) { - var arr = new[] { "aaaa", "c", "dd", "bbb" }; - var comparer = Comparer.Create((a, b) => Comparer.Default.Compare(a.Length, b.Length)); + mmh.Add(s); + } - var mmh = new MinMaxHeap(comparer: comparer); - foreach (var s in arr) - { - mmh.Add(s); - } + Assert.AreEqual(comparer, mmh.Comparer); + Assert.AreEqual("c", mmh.GetMin()); + Assert.AreEqual("aaaa", mmh.GetMax()); + } - Assert.AreEqual(comparer, mmh.Comparer); - Assert.AreEqual("c", mmh.GetMin()); - Assert.AreEqual("aaaa", mmh.GetMax()); + [Test] + [TestCaseSource("CollectionsSource")] + public static void AddTest(IEnumerable collection) + { + var mmh = new MinMaxHeap(); + foreach (var item in collection) + { + mmh.Add(item); } - [Test] - [TestCaseSource("CollectionsSource")] - public static void AddTest(IEnumerable collection) - { - var mmh = new MinMaxHeap(); - foreach (var item in collection) - { - mmh.Add(item); - } + var minValue = mmh.GetMin(); + var maxValue = mmh.GetMax(); - var minValue = mmh.GetMin(); - var maxValue = mmh.GetMax(); + Assert.AreEqual(collection.Min(), minValue); + Assert.AreEqual(collection.Max(), maxValue); + Assert.AreEqual(collection.Count(), mmh.Count); + } - Assert.AreEqual(collection.Min(), minValue); - Assert.AreEqual(collection.Max(), maxValue); - Assert.AreEqual(collection.Count(), mmh.Count); - } + [Test] + [TestCaseSource("CollectionsSource")] + public static void ExtractMaxTest(IEnumerable collection) + { + var ordered = collection.OrderByDescending(x => x); + var mmh = new MinMaxHeap(collection); + var emptyHeap = new MinMaxHeap(); - [Test] - [TestCaseSource("CollectionsSource")] - public static void ExtractMaxTest(IEnumerable collection) - { - var ordered = collection.OrderByDescending(x => x); - var mmh = new MinMaxHeap(collection); - var emptyHeap = new MinMaxHeap(); + var first = mmh.ExtractMax(); + var second = mmh.GetMax(); - var first = mmh.ExtractMax(); - var second = mmh.GetMax(); + Assert.Throws(() => emptyHeap.ExtractMax()); + Assert.AreEqual(ordered.ElementAt(0), first); + Assert.AreEqual(ordered.ElementAt(1), second); + Assert.AreEqual(collection.Count() - 1, mmh.Count); + } - Assert.Throws(() => emptyHeap.ExtractMax()); - Assert.AreEqual(ordered.ElementAt(0), first); - Assert.AreEqual(ordered.ElementAt(1), second); - Assert.AreEqual(collection.Count() - 1, mmh.Count); - } + [Test] + [TestCaseSource("CollectionsSource")] + public static void ExtractMinTest(IEnumerable collection) + { + var ordered = collection.OrderBy(x => x); + var mmh = new MinMaxHeap(collection); + var emptyHeap = new MinMaxHeap(); - [Test] - [TestCaseSource("CollectionsSource")] - public static void ExtractMinTest(IEnumerable collection) - { - var ordered = collection.OrderBy(x => x); - var mmh = new MinMaxHeap(collection); - var emptyHeap = new MinMaxHeap(); + var first = mmh.ExtractMin(); + var second = mmh.GetMin(); - var first = mmh.ExtractMin(); - var second = mmh.GetMin(); + Assert.Throws(() => emptyHeap.ExtractMin()); + Assert.AreEqual(ordered.ElementAt(0), first); + Assert.AreEqual(ordered.ElementAt(1), second); + Assert.AreEqual(collection.Count() - 1, mmh.Count); + } - Assert.Throws(() => emptyHeap.ExtractMin()); - Assert.AreEqual(ordered.ElementAt(0), first); - Assert.AreEqual(ordered.ElementAt(1), second); - Assert.AreEqual(collection.Count() - 1, mmh.Count); - } + [Test] + [TestCaseSource("CollectionsSource")] + public static void GetMaxTest(IEnumerable collection) + { + var emptyHeap = new MinMaxHeap(); + var mmh = new MinMaxHeap(collection); - [Test] - [TestCaseSource("CollectionsSource")] - public static void GetMaxTest(IEnumerable collection) - { - var emptyHeap = new MinMaxHeap(); - var mmh = new MinMaxHeap(collection); + var maxValue = mmh.GetMax(); - var maxValue = mmh.GetMax(); + Assert.Throws(() => emptyHeap.GetMax()); + Assert.AreEqual(collection.Max(), maxValue); + } - Assert.Throws(() => emptyHeap.GetMax()); - Assert.AreEqual(collection.Max(), maxValue); - } + [Test] + [TestCaseSource("CollectionsSource")] + public static void GetMinTest(IEnumerable collection) + { + var emptyHeap = new MinMaxHeap(); + var mmh = new MinMaxHeap(collection); - [Test] - [TestCaseSource("CollectionsSource")] - public static void GetMinTest(IEnumerable collection) - { - var emptyHeap = new MinMaxHeap(); - var mmh = new MinMaxHeap(collection); + var minValue = mmh.GetMin(); - var minValue = mmh.GetMin(); + Assert.Throws(() => emptyHeap.GetMin()); + Assert.AreEqual(collection.Min(), minValue); + } - Assert.Throws(() => emptyHeap.GetMin()); - Assert.AreEqual(collection.Min(), minValue); - } + [Test] + public static void HeapSortUsingGet( + [ValueSource("CollectionsSource")] IEnumerable collection, + [Values] bool ascending) + { + var ordered = ascending ? collection.OrderBy(x => x) : collection.OrderByDescending(x => x); + var mmh = new MinMaxHeap(collection); + var extracted = new List(); - [Test] - public static void HeapSortUsingGet( - [ValueSource("CollectionsSource")] IEnumerable collection, - [Values] bool ascending) + while (mmh.Count > 0) { - var ordered = ascending ? collection.OrderBy(x => x) : collection.OrderByDescending(x => x); - var mmh = new MinMaxHeap(collection); - var extracted = new List(); - - while (mmh.Count > 0) + T value; + if (ascending) + { + value = mmh.GetMin(); + _ = mmh.ExtractMin(); + } + else { - T value; - if (ascending) - { - value = mmh.GetMin(); - _ = mmh.ExtractMin(); - } - else - { - value = mmh.GetMax(); - _ = mmh.ExtractMax(); - } - - extracted.Add(value); + value = mmh.GetMax(); + _ = mmh.ExtractMax(); } - Assert.IsTrue(ordered.SequenceEqual(extracted)); + extracted.Add(value); } - [Test] - public static void HeapSortUsingExtract( - [ValueSource("CollectionsSource")] IEnumerable collection, - [Values] bool ascending) - { - var ordered = ascending ? collection.OrderBy(x => x) : collection.OrderByDescending(x => x); - var mmh = new MinMaxHeap(collection); - var extracted = new List(); + Assert.IsTrue(ordered.SequenceEqual(extracted)); + } - while (mmh.Count > 0) - { - var value = ascending ? mmh.ExtractMin() : mmh.ExtractMax(); - extracted.Add(value); - } + [Test] + public static void HeapSortUsingExtract( + [ValueSource("CollectionsSource")] IEnumerable collection, + [Values] bool ascending) + { + var ordered = ascending ? collection.OrderBy(x => x) : collection.OrderByDescending(x => x); + var mmh = new MinMaxHeap(collection); + var extracted = new List(); - Assert.IsTrue(ordered.SequenceEqual(extracted)); + while (mmh.Count > 0) + { + var value = ascending ? mmh.ExtractMin() : mmh.ExtractMax(); + extracted.Add(value); } + + Assert.IsTrue(ordered.SequenceEqual(extracted)); } } diff --git a/DataStructures.Tests/Heap/PairingHeap/PairingHeapComparerTests.cs b/DataStructures.Tests/Heap/PairingHeap/PairingHeapComparerTests.cs index c9af781a..1fa1112d 100644 --- a/DataStructures.Tests/Heap/PairingHeap/PairingHeapComparerTests.cs +++ b/DataStructures.Tests/Heap/PairingHeap/PairingHeapComparerTests.cs @@ -1,34 +1,33 @@ -using System.Collections.Generic; +using System.Collections.Generic; using DataStructures.Heap.PairingHeap; using FluentAssertions; using NUnit.Framework; -namespace DataStructures.Tests.Heap.PairingHeap +namespace DataStructures.Tests.Heap.PairingHeap; + +internal class PairingHeapComparerTests { - internal class PairingHeapComparerTests + [Test] + public void Compare_CheckAscending_ReturnNegative() { - [Test] - public void Compare_CheckAscending_ReturnNegative() - { - var minHeap = new PairingNodeComparer(Sorting.Ascending, Comparer.Default); - var node1 = new PairingHeapNode(10); - var node2 = new PairingHeapNode(20); + var minHeap = new PairingNodeComparer(Sorting.Ascending, Comparer.Default); + var node1 = new PairingHeapNode(10); + var node2 = new PairingHeapNode(20); - var items = minHeap.Compare(node1.Value, node2.Value); + var items = minHeap.Compare(node1.Value, node2.Value); - items.Should().Be(-1); - } + items.Should().Be(-1); + } - [Test] - public void Compare_CheckAscending_ReturnPositive() - { - var minHeap = new PairingNodeComparer(Sorting.Descending, Comparer.Default); - var node1 = new PairingHeapNode(10); - var node2 = new PairingHeapNode(20); + [Test] + public void Compare_CheckAscending_ReturnPositive() + { + var minHeap = new PairingNodeComparer(Sorting.Descending, Comparer.Default); + var node1 = new PairingHeapNode(10); + var node2 = new PairingHeapNode(20); - var items = minHeap.Compare(node1.Value, node2.Value); + var items = minHeap.Compare(node1.Value, node2.Value); - items.Should().Be(1); - } + items.Should().Be(1); } } diff --git a/DataStructures.Tests/Heap/PairingHeap/PairingHeapTests.cs b/DataStructures.Tests/Heap/PairingHeap/PairingHeapTests.cs index 09291132..c2a9630d 100644 --- a/DataStructures.Tests/Heap/PairingHeap/PairingHeapTests.cs +++ b/DataStructures.Tests/Heap/PairingHeap/PairingHeapTests.cs @@ -1,157 +1,156 @@ -using System; +using System; using System.Collections; using System.Linq; using DataStructures.Heap.PairingHeap; using FluentAssertions; using NUnit.Framework; -namespace DataStructures.Tests.Heap.PairingHeap +namespace DataStructures.Tests.Heap.PairingHeap; + +internal class PairingHeapTests { - internal class PairingHeapTests + [Test] + public void BuildMinHeap_CheckEnumerator_NotThrowOnEnumerate() + { + var minHeap = new PairingHeap(); + minHeap.Insert(1); + + var items = minHeap.ToList(); + + items.Should().HaveCount(1); + } + + [Test] + public void BuildMinHeap_CheckEnumerable_NotThrowOnEnumerate() + { + var minHeap = new PairingHeap(); + minHeap.Insert(1); + + foreach (var node in (IEnumerable)minHeap) + { + node.Should().NotBe(null); + } + } + + [Test] + public void BuildMinHeap_UpdateNonExistingNode_ThrowException() + { + var minHeap = new PairingHeap(); + minHeap.Insert(1); + minHeap.Extract(); + + Action act = () => minHeap.UpdateKey(1, 10); + + act.Should().Throw(); + } + + [Test] + public void BuildMinHeap_UpdateBadNode_ThrowException() + { + var minHeap = new PairingHeap(); + minHeap.Insert(10); + + Action act = () => minHeap.UpdateKey(10, 11); + + act.Should().Throw(); + } + + [Test] + public void BuildMinHeap_CreateHeap_HeapIsCheked() { - [Test] - public void BuildMinHeap_CheckEnumerator_NotThrowOnEnumerate() + var nodeCount = 1000 * 10; + var minHeap = new PairingHeap(); + for (var i = 0; i <= nodeCount; i++) { - var minHeap = new PairingHeap(); - minHeap.Insert(1); + minHeap.Insert(i); + } - var items = minHeap.ToList(); + for (var i = 0; i <= nodeCount; i++) + { + minHeap.UpdateKey(i, i - 1); + } - items.Should().HaveCount(1); + var min = 0; + for (var i = 0; i <= nodeCount; i++) + { + min = minHeap.Extract(); + Assert.AreEqual(min, i - 1); } - [Test] - public void BuildMinHeap_CheckEnumerable_NotThrowOnEnumerate() + Assert.AreEqual(minHeap.Count, minHeap.Count); + + var rnd = new Random(); + var testSeries = Enumerable.Range(0, nodeCount - 1).OrderBy(_ => rnd.Next()).ToList(); + + foreach (var item in testSeries) { - var minHeap = new PairingHeap(); - minHeap.Insert(1); + minHeap.Insert(item); + } - foreach (var node in (IEnumerable)minHeap) - { - node.Should().NotBe(null); - } + for (var i = 0; i < testSeries.Count; i++) + { + var decremented = testSeries[i] - rnd.Next(0, 1000); + minHeap.UpdateKey(testSeries[i], decremented); + testSeries[i] = decremented; } - [Test] - public void BuildMinHeap_UpdateNonExistingNode_ThrowException() + testSeries.Sort(); + + for (var i = 0; i < nodeCount - 2; i++) { - var minHeap = new PairingHeap(); - minHeap.Insert(1); - minHeap.Extract(); + min = minHeap.Extract(); + Assert.AreEqual(testSeries[i], min); + } - Action act = () => minHeap.UpdateKey(1, 10); + Assert.AreEqual(minHeap.Count, minHeap.Count); + } + + [Test] + public void BuildMaxHeap_CreateHeap_HeapIsCheked() + { + var nodeCount = 1000 * 10; + var maxHeap = new PairingHeap(Sorting.Descending); + for (var i = 0; i <= nodeCount; i++) + { + maxHeap.Insert(i); + } - act.Should().Throw(); + for (var i = 0; i <= nodeCount; i++) + { + maxHeap.UpdateKey(i, i + 1); } - [Test] - public void BuildMinHeap_UpdateBadNode_ThrowException() + Assert.AreEqual(maxHeap.Count, maxHeap.Count); + + var max = 0; + for (var i = nodeCount; i >= 0; i--) { - var minHeap = new PairingHeap(); - minHeap.Insert(10); + max = maxHeap.Extract(); + Assert.AreEqual(max, i + 1); + } - Action act = () => minHeap.UpdateKey(10, 11); + var rnd = new Random(); + var testSeries = Enumerable.Range(0, nodeCount - 1).OrderBy(_ => rnd.Next()).ToList(); - act.Should().Throw(); + foreach (var item in testSeries) + { + maxHeap.Insert(item); } - [Test] - public void BuildMinHeap_CreateHeap_HeapIsCheked() + for (var i = 0; i < testSeries.Count; i++) { - var nodeCount = 1000 * 10; - var minHeap = new PairingHeap(); - for (var i = 0; i <= nodeCount; i++) - { - minHeap.Insert(i); - } - - for (var i = 0; i <= nodeCount; i++) - { - minHeap.UpdateKey(i, i - 1); - } - - var min = 0; - for (var i = 0; i <= nodeCount; i++) - { - min = minHeap.Extract(); - Assert.AreEqual(min, i - 1); - } - - Assert.AreEqual(minHeap.Count, minHeap.Count); - - var rnd = new Random(); - var testSeries = Enumerable.Range(0, nodeCount - 1).OrderBy(_ => rnd.Next()).ToList(); - - foreach (var item in testSeries) - { - minHeap.Insert(item); - } - - for (var i = 0; i < testSeries.Count; i++) - { - var decremented = testSeries[i] - rnd.Next(0, 1000); - minHeap.UpdateKey(testSeries[i], decremented); - testSeries[i] = decremented; - } - - testSeries.Sort(); - - for (var i = 0; i < nodeCount - 2; i++) - { - min = minHeap.Extract(); - Assert.AreEqual(testSeries[i], min); - } - - Assert.AreEqual(minHeap.Count, minHeap.Count); + var incremented = testSeries[i] + rnd.Next(0, 1000); + maxHeap.UpdateKey(testSeries[i], incremented); + testSeries[i] = incremented; } - [Test] - public void BuildMaxHeap_CreateHeap_HeapIsCheked() + testSeries = testSeries.OrderByDescending(x => x).ToList(); + for (var i = 0; i < nodeCount - 2; i++) { - var nodeCount = 1000 * 10; - var maxHeap = new PairingHeap(Sorting.Descending); - for (var i = 0; i <= nodeCount; i++) - { - maxHeap.Insert(i); - } - - for (var i = 0; i <= nodeCount; i++) - { - maxHeap.UpdateKey(i, i + 1); - } - - Assert.AreEqual(maxHeap.Count, maxHeap.Count); - - var max = 0; - for (var i = nodeCount; i >= 0; i--) - { - max = maxHeap.Extract(); - Assert.AreEqual(max, i + 1); - } - - var rnd = new Random(); - var testSeries = Enumerable.Range(0, nodeCount - 1).OrderBy(_ => rnd.Next()).ToList(); - - foreach (var item in testSeries) - { - maxHeap.Insert(item); - } - - for (var i = 0; i < testSeries.Count; i++) - { - var incremented = testSeries[i] + rnd.Next(0, 1000); - maxHeap.UpdateKey(testSeries[i], incremented); - testSeries[i] = incremented; - } - - testSeries = testSeries.OrderByDescending(x => x).ToList(); - for (var i = 0; i < nodeCount - 2; i++) - { - max = maxHeap.Extract(); - Assert.AreEqual(testSeries[i], max); - } - - Assert.AreEqual(maxHeap.Count, maxHeap.Count); + max = maxHeap.Extract(); + Assert.AreEqual(testSeries[i], max); } + + Assert.AreEqual(maxHeap.Count, maxHeap.Count); } } diff --git a/DataStructures.Tests/InvertedIndexTests.cs b/DataStructures.Tests/InvertedIndexTests.cs index 77542e4a..e1274e5f 100644 --- a/DataStructures.Tests/InvertedIndexTests.cs +++ b/DataStructures.Tests/InvertedIndexTests.cs @@ -1,37 +1,36 @@ -using System.Collections.Generic; +using System.Collections.Generic; using FluentAssertions; using NUnit.Framework; -namespace DataStructures.Tests +namespace DataStructures.Tests; + +public class InvertedIndexTests { - public class InvertedIndexTests + [Test] + public void Or_GetSourcesWithAtLeastOneFromList_ReturnAllSources() { - [Test] - public void Or_GetSourcesWithAtLeastOneFromList_ReturnAllSources() - { - var index = new InvertedIndex(); - var source1 = "one star is sparkling bright"; - var source2 = "two stars are sparkling even brighter"; - index.AddToIndex(nameof(source1), source1); - index.AddToIndex(nameof(source2), source2); + var index = new InvertedIndex(); + var source1 = "one star is sparkling bright"; + var source2 = "two stars are sparkling even brighter"; + index.AddToIndex(nameof(source1), source1); + index.AddToIndex(nameof(source2), source2); - var or = index.Or(new List { "star", "sparkling" }); + var or = index.Or(new List { "star", "sparkling" }); - or.Should().BeEquivalentTo(nameof(source1), nameof(source2)); - } + or.Should().BeEquivalentTo(nameof(source1), nameof(source2)); + } - [Test] - public void And_GetSourcesWithAllInsideList_ReturnFirstSource() - { - var index = new InvertedIndex(); - var source1 = "one star is sparkling bright"; - var source2 = "two stars are sparkling even brighter"; - index.AddToIndex(nameof(source1), source1); - index.AddToIndex(nameof(source2), source2); + [Test] + public void And_GetSourcesWithAllInsideList_ReturnFirstSource() + { + var index = new InvertedIndex(); + var source1 = "one star is sparkling bright"; + var source2 = "two stars are sparkling even brighter"; + index.AddToIndex(nameof(source1), source1); + index.AddToIndex(nameof(source2), source2); - var and = index.And(new List { "star", "sparkling" }); + var and = index.And(new List { "star", "sparkling" }); - and.Should().BeEquivalentTo(nameof(source1)); - } + and.Should().BeEquivalentTo(nameof(source1)); } } diff --git a/DataStructures.Tests/LinkedList/DoublyLinkedListTests.cs b/DataStructures.Tests/LinkedList/DoublyLinkedListTests.cs index ba80c407..d8629ddb 100644 --- a/DataStructures.Tests/LinkedList/DoublyLinkedListTests.cs +++ b/DataStructures.Tests/LinkedList/DoublyLinkedListTests.cs @@ -3,133 +3,132 @@ using DataStructures.LinkedList.DoublyLinkedList; using NUnit.Framework; -namespace DataStructures.Tests.LinkedList +namespace DataStructures.Tests.LinkedList; + +public static class DoublyLinkedListTests { - public static class DoublyLinkedListTests + [Test] + public static void TestGetData() + { + var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); + var arr = dll.GetData().ToArray(); + + Assert.AreEqual(dll.Count, 5); + Assert.AreEqual(new[] { 0, 1, 2, 3, 4 }, arr); + } + + [Test] + public static void TestGetAt() { - [Test] - public static void TestGetData() - { - var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); - var arr = dll.GetData().ToArray(); - - Assert.AreEqual(dll.Count, 5); - Assert.AreEqual(new[] { 0, 1, 2, 3, 4 }, arr); - } - - [Test] - public static void TestGetAt() - { - var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); - - var one = dll.GetAt(1); - var three = dll.GetAt(3); - - Assert.AreEqual(one.Data, 1); - Assert.AreEqual(three.Data, 3); - Assert.Throws( - () => dll.GetAt(-1) - ); - Assert.Throws( - () => dll.GetAt(5) - ); - } - - [Test] - public static void TestAddtion() - { - var dll = new DoublyLinkedList(0); - var one = dll.Add(1); - - dll.Add(3); - dll.AddAfter(2, one); - dll.Add(4); - - var arr = dll.GetData().ToArray(); - var reversedArr = dll.GetDataReversed().ToArray(); - - Assert.AreEqual(dll.Count, 5); - Assert.AreEqual(new[] { 0, 1, 2, 3, 4 }, arr); - Assert.AreEqual(new[] { 4, 3, 2, 1, 0 }, reversedArr); - } - - [Test] - public static void TestRemove() - { - var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); - - dll.RemoveNode(dll.Find(2)); - dll.RemoveHead(); - dll.Remove(); - - var arr = dll.GetData().ToArray(); - var reversedArr = dll.GetDataReversed().ToArray(); - - Assert.AreEqual(dll.Count, 2); - Assert.AreEqual(new[] { 1, 3 }, arr); - Assert.AreEqual(new[] { 3, 1 }, reversedArr); - } - - [Test] - public static void TestFind() - { - var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); - - var one = dll.Find(1); - var three = dll.Find(3); - - Assert.AreEqual(one.Data, 1); - Assert.AreEqual(three.Data, 3); - } - - [Test] - public static void TestIndexOf() - { - var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); - - var one = dll.IndexOf(1); - var three = dll.IndexOf(3); - - Assert.AreEqual(one, 1); - Assert.AreEqual(three, 3); - } - - [Test] - public static void TestContains() - { - var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); - - var one = dll.Contains(1); - var six = dll.Contains(6); - - Assert.IsTrue(one); - Assert.IsFalse(six); - } - - [Test] - public static void TestReverse() - { - var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); - dll.Reverse(); - var arr = dll.GetData().ToArray(); - - var empty = new DoublyLinkedList(new int[] { }); - empty.Reverse(); - var emptyArr = empty.GetData().ToArray(); - - Assert.AreEqual(arr, new[] { 4, 3, 2, 1, 0 }); - Assert.AreEqual(emptyArr, new int[] { }); - } - - [Test] - public static void TestGetDataReversed() - { - var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); - var arr = dll.GetData().ToArray(); - var reversedArr = dll.GetDataReversed().ToArray(); - - Assert.AreEqual(arr, new[] { 0, 1, 2, 3, 4 }); - Assert.AreEqual(reversedArr, new[] { 4, 3, 2, 1, 0 }); - } + var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); + + var one = dll.GetAt(1); + var three = dll.GetAt(3); + + Assert.AreEqual(one.Data, 1); + Assert.AreEqual(three.Data, 3); + Assert.Throws( + () => dll.GetAt(-1) + ); + Assert.Throws( + () => dll.GetAt(5) + ); + } + + [Test] + public static void TestAddtion() + { + var dll = new DoublyLinkedList(0); + var one = dll.Add(1); + + dll.Add(3); + dll.AddAfter(2, one); + dll.Add(4); + + var arr = dll.GetData().ToArray(); + var reversedArr = dll.GetDataReversed().ToArray(); + + Assert.AreEqual(dll.Count, 5); + Assert.AreEqual(new[] { 0, 1, 2, 3, 4 }, arr); + Assert.AreEqual(new[] { 4, 3, 2, 1, 0 }, reversedArr); + } + + [Test] + public static void TestRemove() + { + var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); + + dll.RemoveNode(dll.Find(2)); + dll.RemoveHead(); + dll.Remove(); + + var arr = dll.GetData().ToArray(); + var reversedArr = dll.GetDataReversed().ToArray(); + + Assert.AreEqual(dll.Count, 2); + Assert.AreEqual(new[] { 1, 3 }, arr); + Assert.AreEqual(new[] { 3, 1 }, reversedArr); + } + + [Test] + public static void TestFind() + { + var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); + + var one = dll.Find(1); + var three = dll.Find(3); + + Assert.AreEqual(one.Data, 1); + Assert.AreEqual(three.Data, 3); + } + + [Test] + public static void TestIndexOf() + { + var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); + + var one = dll.IndexOf(1); + var three = dll.IndexOf(3); + + Assert.AreEqual(one, 1); + Assert.AreEqual(three, 3); + } + + [Test] + public static void TestContains() + { + var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); + + var one = dll.Contains(1); + var six = dll.Contains(6); + + Assert.IsTrue(one); + Assert.IsFalse(six); + } + + [Test] + public static void TestReverse() + { + var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); + dll.Reverse(); + var arr = dll.GetData().ToArray(); + + var empty = new DoublyLinkedList(new int[] { }); + empty.Reverse(); + var emptyArr = empty.GetData().ToArray(); + + Assert.AreEqual(arr, new[] { 4, 3, 2, 1, 0 }); + Assert.AreEqual(emptyArr, new int[] { }); + } + + [Test] + public static void TestGetDataReversed() + { + var dll = new DoublyLinkedList(new[] { 0, 1, 2, 3, 4 }); + var arr = dll.GetData().ToArray(); + var reversedArr = dll.GetDataReversed().ToArray(); + + Assert.AreEqual(arr, new[] { 0, 1, 2, 3, 4 }); + Assert.AreEqual(reversedArr, new[] { 4, 3, 2, 1, 0 }); } } diff --git a/DataStructures.Tests/LinkedList/LinkedListTests.cs b/DataStructures.Tests/LinkedList/LinkedListTests.cs index 66c61a0a..7cc79db1 100644 --- a/DataStructures.Tests/LinkedList/LinkedListTests.cs +++ b/DataStructures.Tests/LinkedList/LinkedListTests.cs @@ -1,110 +1,109 @@ -using System; +using System; using System.Linq; using DataStructures.LinkedList.SinglyLinkedList; using NUnit.Framework; -namespace DataStructures.Tests.LinkedList +namespace DataStructures.Tests.LinkedList; + +public static class LinkedListTests { - public static class LinkedListTests + [Test] + public static void LengthWorksCorrectly([Random(0, 1000, 100)] int quantity) { - [Test] - public static void LengthWorksCorrectly([Random(0, 1000, 100)] int quantity) + // Arrange + var a = new SinglyLinkedList(); + + // Act + var r = TestContext.CurrentContext.Random; + for (var i = 0; i < quantity; i++) { - // Arrange - var a = new SinglyLinkedList(); - - // Act - var r = TestContext.CurrentContext.Random; - for (var i = 0; i < quantity; i++) - { - _ = a.AddFirst(r.Next()); - } - - // Assert - Assert.AreEqual(quantity, a.Length()); + _ = a.AddFirst(r.Next()); } - [Test] - public static void LengthOnEmptyListIsZero() - { - // Arrange - var a = new SinglyLinkedList(); + // Assert + Assert.AreEqual(quantity, a.Length()); + } - // Act + [Test] + public static void LengthOnEmptyListIsZero() + { + // Arrange + var a = new SinglyLinkedList(); - // Assert - Assert.AreEqual(0, a.Length()); - } + // Act - [Test] - public static void GetItemsFromLinkedList() - { - // Arrange - var testObj = new SinglyLinkedList(); - _ = testObj.AddLast("H"); - _ = testObj.AddLast("E"); - _ = testObj.AddLast("L"); - _ = testObj.AddLast("L"); - _ = testObj.AddLast("O"); - - // Act - var items = testObj.GetListData(); - - // Assert - Assert.AreEqual(5, items.Count()); - Assert.AreEqual("O", testObj.GetElementByIndex(4)); - } + // Assert + Assert.AreEqual(0, a.Length()); + } - [Test] - public static void GetElementByIndex_IndexOutOfRange_ArgumentOutOfRangeExceptionThrown() - { - // Arrange - var list = new SinglyLinkedList(); + [Test] + public static void GetItemsFromLinkedList() + { + // Arrange + var testObj = new SinglyLinkedList(); + _ = testObj.AddLast("H"); + _ = testObj.AddLast("E"); + _ = testObj.AddLast("L"); + _ = testObj.AddLast("L"); + _ = testObj.AddLast("O"); + + // Act + var items = testObj.GetListData(); + + // Assert + Assert.AreEqual(5, items.Count()); + Assert.AreEqual("O", testObj.GetElementByIndex(4)); + } - // Act - _ = list.AddFirst(1); - _ = list.AddFirst(2); - _ = list.AddFirst(3); + [Test] + public static void GetElementByIndex_IndexOutOfRange_ArgumentOutOfRangeExceptionThrown() + { + // Arrange + var list = new SinglyLinkedList(); - // Assert - _ = Assert.Throws(() => list.GetElementByIndex(-1)); - _ = Assert.Throws(() => list.GetElementByIndex(3)); - } + // Act + _ = list.AddFirst(1); + _ = list.AddFirst(2); + _ = list.AddFirst(3); + // Assert + _ = Assert.Throws(() => list.GetElementByIndex(-1)); + _ = Assert.Throws(() => list.GetElementByIndex(3)); + } - [Test] - public static void RemoveItemsFromList() - { - // Arrange - var testObj = new SinglyLinkedList(); - _ = testObj.AddLast("X"); - _ = testObj.AddLast("H"); - _ = testObj.AddLast("E"); - _ = testObj.AddLast("L"); - _ = testObj.AddLast("L"); - _ = testObj.AddLast("I"); - _ = testObj.AddLast("O"); - - // Act - var xRemoveSucess = testObj.DeleteElement("X"); - var oRemoveSucess = testObj.DeleteElement("O"); - var eRemoveSucess = testObj.DeleteElement("E"); - var lRemoveSucess = testObj.DeleteElement("L"); - var l2RemoveSucess = testObj.DeleteElement("L"); - var l3RemoveSucess = testObj.DeleteElement("L"); - var nonExistantRemoveSucess = testObj.DeleteElement("F"); - - var resultString = testObj.GetElementByIndex(0) + testObj.GetElementByIndex(1); - - // Assert - Assert.AreEqual("HI", resultString); - Assert.IsTrue(xRemoveSucess); - Assert.IsTrue(oRemoveSucess); - Assert.IsTrue(eRemoveSucess); - Assert.IsTrue(lRemoveSucess); - Assert.IsTrue(l2RemoveSucess); - Assert.IsFalse(l3RemoveSucess); - Assert.IsFalse(nonExistantRemoveSucess); - } + + [Test] + public static void RemoveItemsFromList() + { + // Arrange + var testObj = new SinglyLinkedList(); + _ = testObj.AddLast("X"); + _ = testObj.AddLast("H"); + _ = testObj.AddLast("E"); + _ = testObj.AddLast("L"); + _ = testObj.AddLast("L"); + _ = testObj.AddLast("I"); + _ = testObj.AddLast("O"); + + // Act + var xRemoveSucess = testObj.DeleteElement("X"); + var oRemoveSucess = testObj.DeleteElement("O"); + var eRemoveSucess = testObj.DeleteElement("E"); + var lRemoveSucess = testObj.DeleteElement("L"); + var l2RemoveSucess = testObj.DeleteElement("L"); + var l3RemoveSucess = testObj.DeleteElement("L"); + var nonExistantRemoveSucess = testObj.DeleteElement("F"); + + var resultString = testObj.GetElementByIndex(0) + testObj.GetElementByIndex(1); + + // Assert + Assert.AreEqual("HI", resultString); + Assert.IsTrue(xRemoveSucess); + Assert.IsTrue(oRemoveSucess); + Assert.IsTrue(eRemoveSucess); + Assert.IsTrue(lRemoveSucess); + Assert.IsTrue(l2RemoveSucess); + Assert.IsFalse(l3RemoveSucess); + Assert.IsFalse(nonExistantRemoveSucess); } } diff --git a/DataStructures.Tests/LinkedList/SkipListTests.cs b/DataStructures.Tests/LinkedList/SkipListTests.cs index 1fe69d17..c8d0873b 100644 --- a/DataStructures.Tests/LinkedList/SkipListTests.cs +++ b/DataStructures.Tests/LinkedList/SkipListTests.cs @@ -4,120 +4,119 @@ using FluentAssertions; using System.Collections.Generic; -namespace DataStructures.Tests.LinkedList +namespace DataStructures.Tests.LinkedList; + +public static class SkipListTests { - public static class SkipListTests + [Test] + public static void TestAdd() + { + var list = new SkipList(); + list.AddOrUpdate(1, 1); + list[2] = 2; + list[3] = 3; + + list.Count.Should().Be(3); + list.GetValues().Should().ContainInOrder(1, 2, 3); + } + + [Test] + public static void TestUpdate() + { + var list = new SkipList(); + + // Add some elements. + list[1] = "v1"; + list[2] = "v2"; + list[5] = "v5"; + + // Update + list.AddOrUpdate(1, "v1-updated"); + list[2] = "v2-updated"; + + list.Count.Should().Be(3); + list.GetValues().Should().ContainInOrder("v1-updated", "v2-updated", "v5"); + } + + [Test] + public static void TestContains() + { + var list = new SkipList(); + list.AddOrUpdate(1, 1); + list.AddOrUpdate(3, 3); + list.AddOrUpdate(5, 5); + + list.Contains(1).Should().BeTrue(); + list.Contains(3).Should().BeTrue(); + list.Contains(5).Should().BeTrue(); + list.Contains(0).Should().BeFalse(); + list.Contains(2).Should().BeFalse(); + list.Contains(9).Should().BeFalse(); + } + + [Test] + public static void TestGetByKey_Success() + { + var list = new SkipList(); + list[1] = "value1"; + + list[1].Should().Be("value1"); + } + + [Test] + public static void TestGetByKey_KeyNotFoundException() { - [Test] - public static void TestAdd() - { - var list = new SkipList(); - list.AddOrUpdate(1, 1); - list[2] = 2; - list[3] = 3; - - list.Count.Should().Be(3); - list.GetValues().Should().ContainInOrder(1, 2, 3); - } - - [Test] - public static void TestUpdate() - { - var list = new SkipList(); - - // Add some elements. - list[1] = "v1"; - list[2] = "v2"; - list[5] = "v5"; - - // Update - list.AddOrUpdate(1, "v1-updated"); - list[2] = "v2-updated"; - - list.Count.Should().Be(3); - list.GetValues().Should().ContainInOrder("v1-updated", "v2-updated", "v5"); - } - - [Test] - public static void TestContains() - { - var list = new SkipList(); - list.AddOrUpdate(1, 1); - list.AddOrUpdate(3, 3); - list.AddOrUpdate(5, 5); - - list.Contains(1).Should().BeTrue(); - list.Contains(3).Should().BeTrue(); - list.Contains(5).Should().BeTrue(); - list.Contains(0).Should().BeFalse(); - list.Contains(2).Should().BeFalse(); - list.Contains(9).Should().BeFalse(); - } - - [Test] - public static void TestGetByKey_Success() - { - var list = new SkipList(); - list[1] = "value1"; - - list[1].Should().Be("value1"); - } - - [Test] - public static void TestGetByKey_KeyNotFoundException() - { - var list = new SkipList(); - list[1] = "value1"; - - string value; - Action act = () => value = list[2]; - act.Should().Throw(); - } - - [Test] - public static void TestRemove_ItemRemoved() - { - var list = new SkipList(); - list.AddOrUpdate(1, 1); - list.AddOrUpdate(2, 2); - list.AddOrUpdate(3, 3); - - list.Count.Should().Be(3); - list.Contains(2).Should().BeTrue(); - - var isRemoved = list.Remove(2); - - list.Count.Should().Be(2); - list.Contains(2).Should().BeFalse(); - isRemoved.Should().BeTrue(); - } - - [Test] - public static void TestRemove_ItemNotFound() - { - var list = new SkipList(); - list.AddOrUpdate(1, 1); - list.AddOrUpdate(2, 2); - list.AddOrUpdate(3, 3); - - var isRemoved = list.Remove(222); - - list.Count.Should().Be(3); - isRemoved.Should().BeFalse(); - } - - [Test] - public static void TestGetValues() - { - var list = new SkipList(); - list[4] = "four"; - list[2] = "two"; - list[3] = "three"; - list[1] = "one"; - - var valuesSortedByKey = list.GetValues(); - - valuesSortedByKey.Should().ContainInOrder("one", "two", "three", "four"); - } + var list = new SkipList(); + list[1] = "value1"; + + string value; + Action act = () => value = list[2]; + act.Should().Throw(); + } + + [Test] + public static void TestRemove_ItemRemoved() + { + var list = new SkipList(); + list.AddOrUpdate(1, 1); + list.AddOrUpdate(2, 2); + list.AddOrUpdate(3, 3); + + list.Count.Should().Be(3); + list.Contains(2).Should().BeTrue(); + + var isRemoved = list.Remove(2); + + list.Count.Should().Be(2); + list.Contains(2).Should().BeFalse(); + isRemoved.Should().BeTrue(); + } + + [Test] + public static void TestRemove_ItemNotFound() + { + var list = new SkipList(); + list.AddOrUpdate(1, 1); + list.AddOrUpdate(2, 2); + list.AddOrUpdate(3, 3); + + var isRemoved = list.Remove(222); + + list.Count.Should().Be(3); + isRemoved.Should().BeFalse(); + } + + [Test] + public static void TestGetValues() + { + var list = new SkipList(); + list[4] = "four"; + list[2] = "two"; + list[3] = "three"; + list[1] = "one"; + + var valuesSortedByKey = list.GetValues(); + + valuesSortedByKey.Should().ContainInOrder("one", "two", "three", "four"); } } diff --git a/DataStructures.Tests/Probabilistic/BloomFilterTests.cs b/DataStructures.Tests/Probabilistic/BloomFilterTests.cs index aaa4ded0..c72d5640 100644 --- a/DataStructures.Tests/Probabilistic/BloomFilterTests.cs +++ b/DataStructures.Tests/Probabilistic/BloomFilterTests.cs @@ -1,118 +1,117 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; using System.Text; using DataStructures.Probabilistic; using NUnit.Framework; -namespace DataStructures.Tests.Probabilistic +namespace DataStructures.Tests.Probabilistic; + +public class BloomFilterTests { - public class BloomFilterTests + static readonly string[] TestNames = { "kal;jsnfka", "alkjsdfn;lakm", "aljfopiawjf", "afowjeaofeij", "oajwsefoaiwje", "aoiwjfaoiejmf", "aoijfoawiejf" }; + + private class SimpleObject { - static readonly string[] TestNames = { "kal;jsnfka", "alkjsdfn;lakm", "aljfopiawjf", "afowjeaofeij", "oajwsefoaiwje", "aoiwjfaoiejmf", "aoijfoawiejf" }; + public string Name { get; set; } + public int Number { get; set; } - private class SimpleObject + public SimpleObject(string name, int number) { - public string Name { get; set; } - public int Number { get; set; } - - public SimpleObject(string name, int number) - { - Name = name; - Number = number; - } + Name = name; + Number = number; } + } - private class SimpleObjectOverridenHash - { - private const uint FnvPrime = 16777619; - private const uint FnvOffsetBasis = 2166136261; - public string Name { get; set; } - public int Number { get; set; } + private class SimpleObjectOverridenHash + { + private const uint FnvPrime = 16777619; + private const uint FnvOffsetBasis = 2166136261; + public string Name { get; set; } + public int Number { get; set; } - public SimpleObjectOverridenHash(string name, int number) - { - Name = name; - Number = number; - } + public SimpleObjectOverridenHash(string name, int number) + { + Name = name; + Number = number; + } - public override int GetHashCode() + public override int GetHashCode() + { + var bytes = Encoding.UTF8.GetBytes(Name).Concat(BitConverter.GetBytes(Number)); + var hash = FnvOffsetBasis; + foreach (var @byte in bytes) { - var bytes = Encoding.UTF8.GetBytes(Name).Concat(BitConverter.GetBytes(Number)); - var hash = FnvOffsetBasis; - foreach (var @byte in bytes) - { - hash = hash * FnvPrime; - hash ^= @byte; - } - - return (int)hash; + hash = hash * FnvPrime; + hash ^= @byte; } - public override bool Equals(object? obj) - { - return obj is SimpleObjectOverridenHash asSimpleObj && asSimpleObj.Name == Name && asSimpleObj.Number == Number; - } + return (int)hash; } - [Test] - public void TestBloomFilterInsertOptimalSize() + public override bool Equals(object? obj) { - var filter = new BloomFilter(1000); - var set = new HashSet(); - var rand = new Random(124); - var falsePositives = 0; - for (var i = 0; i < 1000; i++) - { - var k = rand.Next(0, 1000); - if (!set.Contains(k) && filter.Search(k)) - { - falsePositives++; - } - filter.Insert(k); - set.Add(k); - Assert.IsTrue(filter.Search(k)); - } - - Assert.True(.05 > falsePositives / 1000.0); // be a bit generous in our fault tolerance here + return obj is SimpleObjectOverridenHash asSimpleObj && asSimpleObj.Name == Name && asSimpleObj.Number == Number; } + } - [Test] - public void TestBloomFilterInsert() + [Test] + public void TestBloomFilterInsertOptimalSize() + { + var filter = new BloomFilter(1000); + var set = new HashSet(); + var rand = new Random(124); + var falsePositives = 0; + for (var i = 0; i < 1000; i++) { - var filter = new BloomFilter(100000, 3); - var rand = new Random(); - for (var i = 0; i < 1000; i++) + var k = rand.Next(0, 1000); + if (!set.Contains(k) && filter.Search(k)) { - var simpleObject = new SimpleObject(TestNames[rand.Next(TestNames.Length)], rand.Next(15)); - filter.Insert(simpleObject); - Assert.IsTrue(filter.Search(simpleObject)); + falsePositives++; } + filter.Insert(k); + set.Add(k); + Assert.IsTrue(filter.Search(k)); } - [Test] - public void TestBloomFilterSearchOverridenHash() + Assert.True(.05 > falsePositives / 1000.0); // be a bit generous in our fault tolerance here + } + + [Test] + public void TestBloomFilterInsert() + { + var filter = new BloomFilter(100000, 3); + var rand = new Random(); + for (var i = 0; i < 1000; i++) { - var filter = new BloomFilter(100000, 3); - var simpleObjectInserted = new SimpleObjectOverridenHash("foo", 1); - var simpleObjectInserted2 = new SimpleObjectOverridenHash("foo", 1); - var simpleObjectNotInserted = new SimpleObjectOverridenHash("bar", 2); - filter.Insert(simpleObjectInserted); - Assert.IsTrue(filter.Search(simpleObjectInserted)); - Assert.IsTrue(filter.Search(simpleObjectInserted2)); - Assert.IsFalse(filter.Search(simpleObjectNotInserted)); + var simpleObject = new SimpleObject(TestNames[rand.Next(TestNames.Length)], rand.Next(15)); + filter.Insert(simpleObject); + Assert.IsTrue(filter.Search(simpleObject)); } + } - [Test] - public void TestBloomFilterSearch() - { - var filter = new BloomFilter(10000, 3); - var simpleObjectInserted = new SimpleObject("foo", 1); - var simpleObjectNotInserted = new SimpleObject("foo", 1); - filter.Insert(simpleObjectInserted); - Assert.False(filter.Search(simpleObjectNotInserted)); - Assert.True(filter.Search(simpleObjectInserted)); + [Test] + public void TestBloomFilterSearchOverridenHash() + { + var filter = new BloomFilter(100000, 3); + var simpleObjectInserted = new SimpleObjectOverridenHash("foo", 1); + var simpleObjectInserted2 = new SimpleObjectOverridenHash("foo", 1); + var simpleObjectNotInserted = new SimpleObjectOverridenHash("bar", 2); + filter.Insert(simpleObjectInserted); + Assert.IsTrue(filter.Search(simpleObjectInserted)); + Assert.IsTrue(filter.Search(simpleObjectInserted2)); + Assert.IsFalse(filter.Search(simpleObjectNotInserted)); + } + + [Test] + public void TestBloomFilterSearch() + { + var filter = new BloomFilter(10000, 3); + var simpleObjectInserted = new SimpleObject("foo", 1); + var simpleObjectNotInserted = new SimpleObject("foo", 1); + filter.Insert(simpleObjectInserted); + Assert.False(filter.Search(simpleObjectNotInserted)); + Assert.True(filter.Search(simpleObjectInserted)); - } } } diff --git a/DataStructures.Tests/Probabilistic/CountMinSketchTests.cs b/DataStructures.Tests/Probabilistic/CountMinSketchTests.cs index b8905397..201cca96 100644 --- a/DataStructures.Tests/Probabilistic/CountMinSketchTests.cs +++ b/DataStructures.Tests/Probabilistic/CountMinSketchTests.cs @@ -1,91 +1,90 @@ -using System; +using System; using System.Collections.Generic; using DataStructures.Probabilistic; using NUnit.Framework; using FluentAssertions; -namespace DataStructures.Tests.Probabilistic +namespace DataStructures.Tests.Probabilistic; + +public class CountMinSketchTests { - public class CountMinSketchTests + public class SimpleObject { - public class SimpleObject - { - public string Name { get; set; } - public int Number { get; set; } + public string Name { get; set; } + public int Number { get; set; } - public SimpleObject(string name, int number) - { - Name = name; - Number = number; - } - } - - [Test] - public void TestInsertAndCount() + public SimpleObject(string name, int number) { - var obj1 = new SimpleObject("foo", 5); - var obj2 = new SimpleObject("bar", 6); + Name = name; + Number = number; + } + } - var sketch = new CountMinSketch(200, 5); + [Test] + public void TestInsertAndCount() + { + var obj1 = new SimpleObject("foo", 5); + var obj2 = new SimpleObject("bar", 6); - for (var i = 0; i < 5000; i++) - { - sketch.Insert(obj1); - sketch.Insert(obj2); - } + var sketch = new CountMinSketch(200, 5); - sketch.Query(obj1).Should().BeGreaterOrEqualTo(5000); - sketch.Query(obj2).Should().BeGreaterOrEqualTo(5000); + for (var i = 0; i < 5000; i++) + { + sketch.Insert(obj1); + sketch.Insert(obj2); } - [Test] - public void TestOptimalInitializer() - { - var obj1 = new SimpleObject("foo", 5); - var obj2 = new SimpleObject("bar", 6); + sketch.Query(obj1).Should().BeGreaterOrEqualTo(5000); + sketch.Query(obj2).Should().BeGreaterOrEqualTo(5000); + } - var sketch = new CountMinSketch(.001, .05); + [Test] + public void TestOptimalInitializer() + { + var obj1 = new SimpleObject("foo", 5); + var obj2 = new SimpleObject("bar", 6); - for (var i = 0; i < 5000; i++) - { - sketch.Insert(obj1); - sketch.Insert(obj2); - } + var sketch = new CountMinSketch(.001, .05); - sketch.Query(obj1).Should().BeGreaterOrEqualTo(5000); - sketch.Query(obj2).Should().BeGreaterOrEqualTo(5000); + for (var i = 0; i < 5000; i++) + { + sketch.Insert(obj1); + sketch.Insert(obj2); } - [Test] - public void TestProbabilities() + sketch.Query(obj1).Should().BeGreaterOrEqualTo(5000); + sketch.Query(obj2).Should().BeGreaterOrEqualTo(5000); + } + + [Test] + public void TestProbabilities() + { + var sketch = new CountMinSketch(.01, .05); + var random = new Random(); + var insertedItems = new Dictionary(); + for (var i = 0; i < 10000; i++) { - var sketch = new CountMinSketch(.01, .05); - var random = new Random(); - var insertedItems = new Dictionary(); - for (var i = 0; i < 10000; i++) + var item = random.Next(0, 1000000); + sketch.Insert(item); + if (insertedItems.ContainsKey(item)) { - var item = random.Next(0, 1000000); - sketch.Insert(item); - if (insertedItems.ContainsKey(item)) - { - insertedItems[item]++; - } - else - { - insertedItems.Add(item, 1); - } + insertedItems[item]++; } - - var numMisses = 0; - foreach (var item in insertedItems) + else { - if (sketch.Query(item.Key) - item.Value > .01 * 100000) - { - numMisses++; - } + insertedItems.Add(item, 1); } + } - (numMisses / (double)insertedItems.Count).Should().BeLessOrEqualTo(.05); + var numMisses = 0; + foreach (var item in insertedItems) + { + if (sketch.Query(item.Key) - item.Value > .01 * 100000) + { + numMisses++; + } } + + (numMisses / (double)insertedItems.Count).Should().BeLessOrEqualTo(.05); } } diff --git a/DataStructures.Tests/Probabilistic/HyperLogLogTest.cs b/DataStructures.Tests/Probabilistic/HyperLogLogTest.cs index 2b22a720..bd45c87c 100644 --- a/DataStructures.Tests/Probabilistic/HyperLogLogTest.cs +++ b/DataStructures.Tests/Probabilistic/HyperLogLogTest.cs @@ -1,61 +1,60 @@ -using System; +using System; using System.Collections.Generic; using DataStructures.Probabilistic; using FluentAssertions; using NUnit.Framework; -namespace DataStructures.Tests.Probabilistic +namespace DataStructures.Tests.Probabilistic; + +public class HyperLogLogTest { - public class HyperLogLogTest + [Test] + public void TestHyperLogLog() { - [Test] - public void TestHyperLogLog() + var hll = new HyperLogLog(); + HashSet actual = new (); + + var rand = new Random(); + var tolerance = .05; + for (var i = 0; i < 10000; i++) { - var hll = new HyperLogLog(); - HashSet actual = new (); + var k = rand.Next(20000); + hll.Add(k); + actual.Add(k); + } - var rand = new Random(); - var tolerance = .05; - for (var i = 0; i < 10000; i++) - { - var k = rand.Next(20000); - hll.Add(k); - actual.Add(k); - } + hll.Cardinality().Should() + .BeGreaterOrEqualTo((int)(actual.Count * (1 - tolerance))) + .And + .BeLessOrEqualTo((int)(actual.Count * (1 + tolerance))); + } - hll.Cardinality().Should() - .BeGreaterOrEqualTo((int)(actual.Count * (1 - tolerance))) - .And - .BeLessOrEqualTo((int)(actual.Count * (1 + tolerance))); + [Test] + public void TestHyperLogLogMerge() + { + var hll1 = new HyperLogLog(); + var hll2 = new HyperLogLog(); + var rand = new Random(); + var tolerance = .05; + HashSet actual = new (); + for (var i = 0; i < 5000; i++) + { + var k = rand.Next(20000); + hll1.Add(k); + actual.Add(k); } - [Test] - public void TestHyperLogLogMerge() + for (var i = 0; i < 5000; i++) { - var hll1 = new HyperLogLog(); - var hll2 = new HyperLogLog(); - var rand = new Random(); - var tolerance = .05; - HashSet actual = new (); - for (var i = 0; i < 5000; i++) - { - var k = rand.Next(20000); - hll1.Add(k); - actual.Add(k); - } - - for (var i = 0; i < 5000; i++) - { - var k = rand.Next(20000); - hll2.Add(k); - actual.Add(k); - } - - var hll = HyperLogLog.Merge(hll1, hll2); - hll.Cardinality().Should() - .BeGreaterOrEqualTo((int)(actual.Count * (1 - tolerance))) - .And - .BeLessOrEqualTo((int)(actual.Count * (1 + tolerance))); + var k = rand.Next(20000); + hll2.Add(k); + actual.Add(k); } + + var hll = HyperLogLog.Merge(hll1, hll2); + hll.Cardinality().Should() + .BeGreaterOrEqualTo((int)(actual.Count * (1 - tolerance))) + .And + .BeLessOrEqualTo((int)(actual.Count * (1 + tolerance))); } } diff --git a/DataStructures.Tests/Queue/ArrayBasedQueueTests.cs b/DataStructures.Tests/Queue/ArrayBasedQueueTests.cs index 0ab39754..f980e041 100644 --- a/DataStructures.Tests/Queue/ArrayBasedQueueTests.cs +++ b/DataStructures.Tests/Queue/ArrayBasedQueueTests.cs @@ -1,133 +1,132 @@ -using System; +using System; using System.Text; using DataStructures.Queue; using NUnit.Framework; -namespace DataStructures.Tests.Queue +namespace DataStructures.Tests.Queue; + +public static class ArrayBasedQueueTests { - public static class ArrayBasedQueueTests + [Test] + public static void DequeueWorksCorrectly() { - [Test] - public static void DequeueWorksCorrectly() + // Arrange + var q = new ArrayBasedQueue(3); + q.Enqueue('A'); + q.Enqueue('B'); + q.Enqueue('C'); + var result = new StringBuilder(); + + // Act + for (var i = 0; i < 3; i++) { - // Arrange - var q = new ArrayBasedQueue(3); - q.Enqueue('A'); - q.Enqueue('B'); - q.Enqueue('C'); - var result = new StringBuilder(); - - // Act - for (var i = 0; i < 3; i++) - { - result.Append(q.Dequeue()); - } - - // Assert - Assert.AreEqual("ABC", result.ToString()); - Assert.IsTrue(q.IsEmpty(), "Queue is empty"); - Assert.IsFalse(q.IsFull(), "Queue is full"); + result.Append(q.Dequeue()); } - [Test] - public static void PeekWorksCorrectly() - { - // Arrange - var q = new ArrayBasedQueue(2); - q.Enqueue(1); - q.Enqueue(2); - var peeked = 0; - - // Act - for (var i = 0; i < 3; i++) - { - peeked = q.Peek(); - } - - // Assert - Assert.AreEqual(1, peeked); - Assert.IsFalse(q.IsEmpty(), "Queue is empty"); - Assert.IsTrue(q.IsFull(), "Queue is full"); - } + // Assert + Assert.AreEqual("ABC", result.ToString()); + Assert.IsTrue(q.IsEmpty(), "Queue is empty"); + Assert.IsFalse(q.IsFull(), "Queue is full"); + } - [Test] - public static void DequeueEmptyQueueThrowsInvalidOperationException() + [Test] + public static void PeekWorksCorrectly() + { + // Arrange + var q = new ArrayBasedQueue(2); + q.Enqueue(1); + q.Enqueue(2); + var peeked = 0; + + // Act + for (var i = 0; i < 3; i++) { - // Arrange - var q = new ArrayBasedQueue(1); - Exception? exception = null; - - // Act - try - { - q.Dequeue(); - } - catch (Exception ex) - { - exception = ex; - } - - // Assert - Assert.AreEqual(typeof(InvalidOperationException), exception?.GetType()); + peeked = q.Peek(); } - [Test] - public static void EnqueueFullQueueThrowsInvalidOperationException() + // Assert + Assert.AreEqual(1, peeked); + Assert.IsFalse(q.IsEmpty(), "Queue is empty"); + Assert.IsTrue(q.IsFull(), "Queue is full"); + } + + [Test] + public static void DequeueEmptyQueueThrowsInvalidOperationException() + { + // Arrange + var q = new ArrayBasedQueue(1); + Exception? exception = null; + + // Act + try { - // Arrange - var q = new ArrayBasedQueue(1); - q.Enqueue(0); - Exception? exception = null; - - // Act - try - { - q.Enqueue(1); - } - catch (Exception ex) - { - exception = ex; - } - - // Assert - Assert.AreEqual(typeof(InvalidOperationException), exception?.GetType()); + q.Dequeue(); } - - [Test] - public static void PeekEmptyQueueThrowsInvalidOperationException() + catch (Exception ex) { - // Arrange - var q = new ArrayBasedQueue(1); - Exception? exception = null; - - // Act - try - { - q.Peek(); - } - catch (Exception ex) - { - exception = ex; - } - - // Assert - Assert.AreEqual(typeof(InvalidOperationException), exception?.GetType()); + exception = ex; } - [Test] - public static void ClearWorksCorrectly() + // Assert + Assert.AreEqual(typeof(InvalidOperationException), exception?.GetType()); + } + + [Test] + public static void EnqueueFullQueueThrowsInvalidOperationException() + { + // Arrange + var q = new ArrayBasedQueue(1); + q.Enqueue(0); + Exception? exception = null; + + // Act + try { - // Arrange - var q = new ArrayBasedQueue(2); q.Enqueue(1); - q.Enqueue(2); + } + catch (Exception ex) + { + exception = ex; + } + + // Assert + Assert.AreEqual(typeof(InvalidOperationException), exception?.GetType()); + } - // Act - q.Clear(); + [Test] + public static void PeekEmptyQueueThrowsInvalidOperationException() + { + // Arrange + var q = new ArrayBasedQueue(1); + Exception? exception = null; - // Assert - Assert.IsTrue(q.IsEmpty(), "Queue is empty"); - Assert.IsFalse(q.IsFull(), "Queue is full"); + // Act + try + { + q.Peek(); } + catch (Exception ex) + { + exception = ex; + } + + // Assert + Assert.AreEqual(typeof(InvalidOperationException), exception?.GetType()); + } + + [Test] + public static void ClearWorksCorrectly() + { + // Arrange + var q = new ArrayBasedQueue(2); + q.Enqueue(1); + q.Enqueue(2); + + // Act + q.Clear(); + + // Assert + Assert.IsTrue(q.IsEmpty(), "Queue is empty"); + Assert.IsFalse(q.IsFull(), "Queue is full"); } } diff --git a/DataStructures.Tests/Queue/ListBasedQueueTests.cs b/DataStructures.Tests/Queue/ListBasedQueueTests.cs index f99fa306..a3477d50 100644 --- a/DataStructures.Tests/Queue/ListBasedQueueTests.cs +++ b/DataStructures.Tests/Queue/ListBasedQueueTests.cs @@ -1,111 +1,110 @@ -using System; +using System; using System.Text; using DataStructures.Queue; using NUnit.Framework; -namespace DataStructures.Tests.Queue +namespace DataStructures.Tests.Queue; + +public static class ListBasedQueueTests { - public static class ListBasedQueueTests + [Test] + public static void DequeueWorksCorrectly() { - [Test] - public static void DequeueWorksCorrectly() + // Arrange + var q = new ListBasedQueue(); + q.Enqueue('A'); + q.Enqueue('B'); + q.Enqueue('C'); + var result = new StringBuilder(); + + // Act + for (var i = 0; i < 3; i++) { - // Arrange - var q = new ListBasedQueue(); - q.Enqueue('A'); - q.Enqueue('B'); - q.Enqueue('C'); - var result = new StringBuilder(); - - // Act - for (var i = 0; i < 3; i++) - { - result.Append(q.Dequeue()); - } - - // Assert - Assert.AreEqual("ABC", result.ToString()); - Assert.IsTrue(q.IsEmpty(), "Queue is empty"); - Assert.IsFalse(q.IsFull(), "Queue is full"); + result.Append(q.Dequeue()); } - [Test] - public static void PeekWorksCorrectly() + // Assert + Assert.AreEqual("ABC", result.ToString()); + Assert.IsTrue(q.IsEmpty(), "Queue is empty"); + Assert.IsFalse(q.IsFull(), "Queue is full"); + } + + [Test] + public static void PeekWorksCorrectly() + { + // Arrange + var q = new ListBasedQueue(); + q.Enqueue(1); + q.Enqueue(2); + var peeked = 0; + + // Act + for (var i = 0; i < 3; i++) { - // Arrange - var q = new ListBasedQueue(); - q.Enqueue(1); - q.Enqueue(2); - var peeked = 0; - - // Act - for (var i = 0; i < 3; i++) - { - peeked = q.Peek(); - } - - // Assert - Assert.AreEqual(1, peeked); - Assert.IsFalse(q.IsEmpty(), "Queue is empty"); - Assert.IsFalse(q.IsFull(), "Queue is full"); + peeked = q.Peek(); } - [Test] - public static void DequeueEmptyQueueThrowsInvalidOperationException() + // Assert + Assert.AreEqual(1, peeked); + Assert.IsFalse(q.IsEmpty(), "Queue is empty"); + Assert.IsFalse(q.IsFull(), "Queue is full"); + } + + [Test] + public static void DequeueEmptyQueueThrowsInvalidOperationException() + { + // Arrange + var q = new ListBasedQueue(); + Exception? exception = null; + + // Act + try { - // Arrange - var q = new ListBasedQueue(); - Exception? exception = null; - - // Act - try - { - q.Dequeue(); - } - catch (Exception ex) - { - exception = ex; - } - - // Assert - Assert.AreEqual(typeof(InvalidOperationException), exception?.GetType()); + q.Dequeue(); } - - [Test] - public static void PeekEmptyQueueThrowsInvalidOperationException() + catch (Exception ex) { - // Arrange - var q = new ListBasedQueue(); - Exception? exception = null; - - // Act - try - { - q.Peek(); - } - catch (Exception ex) - { - exception = ex; - } - - // Assert - Assert.AreEqual(typeof(InvalidOperationException), exception?.GetType()); + exception = ex; } - [Test] - public static void ClearWorksCorrectly() - { - // Arrange - var q = new ListBasedQueue(); - q.Enqueue(1); - q.Enqueue(2); + // Assert + Assert.AreEqual(typeof(InvalidOperationException), exception?.GetType()); + } - // Act - q.Clear(); + [Test] + public static void PeekEmptyQueueThrowsInvalidOperationException() + { + // Arrange + var q = new ListBasedQueue(); + Exception? exception = null; - // Assert - Assert.IsTrue(q.IsEmpty(), "Queue is empty"); - Assert.IsFalse(q.IsFull(), "Queue is full"); + // Act + try + { + q.Peek(); } + catch (Exception ex) + { + exception = ex; + } + + // Assert + Assert.AreEqual(typeof(InvalidOperationException), exception?.GetType()); + } + + [Test] + public static void ClearWorksCorrectly() + { + // Arrange + var q = new ListBasedQueue(); + q.Enqueue(1); + q.Enqueue(2); + + // Act + q.Clear(); + + // Assert + Assert.IsTrue(q.IsEmpty(), "Queue is empty"); + Assert.IsFalse(q.IsFull(), "Queue is full"); } } diff --git a/DataStructures.Tests/Queue/StackBasedQueueTests.cs b/DataStructures.Tests/Queue/StackBasedQueueTests.cs index 3913b6ea..7d322bad 100644 --- a/DataStructures.Tests/Queue/StackBasedQueueTests.cs +++ b/DataStructures.Tests/Queue/StackBasedQueueTests.cs @@ -1,111 +1,110 @@ -using System; +using System; using System.Text; using DataStructures.Queue; using NUnit.Framework; -namespace DataStructures.Tests.Queue +namespace DataStructures.Tests.Queue; + +public static class StackBasedQueueTests { - public static class StackBasedQueueTests + [Test] + public static void DequeueWorksCorrectly() { - [Test] - public static void DequeueWorksCorrectly() + // Arrange + var q = new StackBasedQueue(); + q.Enqueue('A'); + q.Enqueue('B'); + q.Enqueue('C'); + var result = new StringBuilder(); + + // Act + for (var i = 0; i < 3; i++) { - // Arrange - var q = new StackBasedQueue(); - q.Enqueue('A'); - q.Enqueue('B'); - q.Enqueue('C'); - var result = new StringBuilder(); - - // Act - for (var i = 0; i < 3; i++) - { - result.Append(q.Dequeue()); - } - - // Assert - Assert.AreEqual("ABC", result.ToString()); - Assert.IsTrue(q.IsEmpty(), "Queue is empty"); - Assert.IsFalse(q.IsFull(), "Queue is full"); + result.Append(q.Dequeue()); } - [Test] - public static void PeekWorksCorrectly() + // Assert + Assert.AreEqual("ABC", result.ToString()); + Assert.IsTrue(q.IsEmpty(), "Queue is empty"); + Assert.IsFalse(q.IsFull(), "Queue is full"); + } + + [Test] + public static void PeekWorksCorrectly() + { + // Arrange + var q = new StackBasedQueue(); + q.Enqueue(1); + q.Enqueue(2); + var peeked = 0; + + // Act + for (var i = 0; i < 3; i++) { - // Arrange - var q = new StackBasedQueue(); - q.Enqueue(1); - q.Enqueue(2); - var peeked = 0; - - // Act - for (var i = 0; i < 3; i++) - { - peeked = q.Peek(); - } - - // Assert - Assert.AreEqual(1, peeked); - Assert.IsFalse(q.IsEmpty(), "Queue is empty"); - Assert.IsFalse(q.IsFull(), "Queue is full"); + peeked = q.Peek(); } - [Test] - public static void DequeueEmptyQueueThrowsInvalidOperationException() + // Assert + Assert.AreEqual(1, peeked); + Assert.IsFalse(q.IsEmpty(), "Queue is empty"); + Assert.IsFalse(q.IsFull(), "Queue is full"); + } + + [Test] + public static void DequeueEmptyQueueThrowsInvalidOperationException() + { + // Arrange + var q = new StackBasedQueue(); + Exception? exception = null; + + // Act + try { - // Arrange - var q = new StackBasedQueue(); - Exception? exception = null; - - // Act - try - { - q.Dequeue(); - } - catch (Exception ex) - { - exception = ex; - } - - // Assert - Assert.AreEqual(typeof(InvalidOperationException), exception?.GetType()); + q.Dequeue(); } - - [Test] - public static void PeekEmptyQueueThrowsInvalidOperationException() + catch (Exception ex) { - // Arrange - var q = new StackBasedQueue(); - Exception? exception = null; - - // Act - try - { - q.Peek(); - } - catch (Exception ex) - { - exception = ex; - } - - // Assert - Assert.AreEqual(typeof(InvalidOperationException), exception?.GetType()); + exception = ex; } - [Test] - public static void ClearWorksCorrectly() - { - // Arrange - var q = new StackBasedQueue(); - q.Enqueue(1); - q.Enqueue(2); + // Assert + Assert.AreEqual(typeof(InvalidOperationException), exception?.GetType()); + } - // Act - q.Clear(); + [Test] + public static void PeekEmptyQueueThrowsInvalidOperationException() + { + // Arrange + var q = new StackBasedQueue(); + Exception? exception = null; - // Assert - Assert.IsTrue(q.IsEmpty(), "Queue is empty"); - Assert.IsFalse(q.IsFull(), "Queue is full"); + // Act + try + { + q.Peek(); } + catch (Exception ex) + { + exception = ex; + } + + // Assert + Assert.AreEqual(typeof(InvalidOperationException), exception?.GetType()); + } + + [Test] + public static void ClearWorksCorrectly() + { + // Arrange + var q = new StackBasedQueue(); + q.Enqueue(1); + q.Enqueue(2); + + // Act + q.Clear(); + + // Assert + Assert.IsTrue(q.IsEmpty(), "Queue is empty"); + Assert.IsFalse(q.IsFull(), "Queue is full"); } } diff --git a/DataStructures.Tests/RedBlackTreeTests.cs b/DataStructures.Tests/RedBlackTreeTests.cs index 4486e836..8dc0ad58 100644 --- a/DataStructures.Tests/RedBlackTreeTests.cs +++ b/DataStructures.Tests/RedBlackTreeTests.cs @@ -5,375 +5,374 @@ using FluentAssertions; using NUnit.Framework; -namespace DataStructures.Tests +namespace DataStructures.Tests; + +internal class RedBlackTreeTests { - internal class RedBlackTreeTests + [Test] + public void Constructor_UseCustomComparer_FormsCorrect_Tree() { - [Test] - public void Constructor_UseCustomComparer_FormsCorrect_Tree() - { - var tree = new RedBlackTree(Comparer.Create((x, y) => y.CompareTo(x))); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.GetMin().Should().Be(10); - tree.GetMax().Should().Be(1); - tree.GetKeysInOrder().SequenceEqual(new[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }).Should().BeTrue(); - } - - [Test] - public void Add_Case3_FormsCorrectTree() - { - var tree = new RedBlackTree(); - tree.Add(5); - tree.Count.Should().Be(1); - } - - [Test] - public void Add_Case24_FormsCorrectTree() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 5, 4, 6, 3 }); - tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 4, 3, 6 }).Should().BeTrue(); - } + var tree = new RedBlackTree(Comparer.Create((x, y) => y.CompareTo(x))); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.GetMin().Should().Be(10); + tree.GetMax().Should().Be(1); + tree.GetKeysInOrder().SequenceEqual(new[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }).Should().BeTrue(); + } - [Test] - public void Add_Case1_FormsCorrectTree() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 5, 4, 6, 3, 7 }); - tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 4, 3, 6, 7 }).Should().BeTrue(); - } + [Test] + public void Add_Case3_FormsCorrectTree() + { + var tree = new RedBlackTree(); + tree.Add(5); + tree.Count.Should().Be(1); + } - [Test] - public void Add_Case6_FormsCorrectTree() - { - // Right rotation - var tree = new RedBlackTree(); - tree.AddRange(new[] { 5, 4, 6, 3, 2 }); - tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 3, 2, 4, 6 }).Should().BeTrue(); - - // Left rotation - tree = new RedBlackTree(); - tree.AddRange(new[] { 5, 4, 6, 7, 8 }); - tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 4, 7, 6, 8 }).Should().BeTrue(); - } + [Test] + public void Add_Case24_FormsCorrectTree() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 5, 4, 6, 3 }); + tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 4, 3, 6 }).Should().BeTrue(); + } - [Test] - public void Add_Case5_FormsCorrectTree() - { - // Left-right rotation - var tree = new RedBlackTree(); - tree.AddRange(new[] { 5, 4, 6, 2, 3 }); - tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 3, 2, 4, 6 }).Should().BeTrue(); - - // Right-left rotation - tree = new RedBlackTree(); - tree.AddRange(new[] { 5, 4, 6, 8, 7 }); - tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 4, 7, 6, 8 }).Should().BeTrue(); - } + [Test] + public void Add_Case1_FormsCorrectTree() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 5, 4, 6, 3, 7 }); + tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 4, 3, 6, 7 }).Should().BeTrue(); + } - [Test] - public void Add_MultipleKeys_FormsCorrectTree() - { - var tree = new RedBlackTree(); + [Test] + public void Add_Case6_FormsCorrectTree() + { + // Right rotation + var tree = new RedBlackTree(); + tree.AddRange(new[] { 5, 4, 6, 3, 2 }); + tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 3, 2, 4, 6 }).Should().BeTrue(); + + // Left rotation + tree = new RedBlackTree(); + tree.AddRange(new[] { 5, 4, 6, 7, 8 }); + tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 4, 7, 6, 8 }).Should().BeTrue(); + } - foreach (var value in new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) - { - tree.Add(value); - tree.Count.Should().Be(value); - } + [Test] + public void Add_Case5_FormsCorrectTree() + { + // Left-right rotation + var tree = new RedBlackTree(); + tree.AddRange(new[] { 5, 4, 6, 2, 3 }); + tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 3, 2, 4, 6 }).Should().BeTrue(); + + // Right-left rotation + tree = new RedBlackTree(); + tree.AddRange(new[] { 5, 4, 6, 8, 7 }); + tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 4, 7, 6, 8 }).Should().BeTrue(); + } - tree.GetKeysInOrder().SequenceEqual(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 4, 2, 1, 3, 6, 5, 8, 7, 9, 10 }).Should().BeTrue(); - } + [Test] + public void Add_MultipleKeys_FormsCorrectTree() + { + var tree = new RedBlackTree(); - [Test] - public void Add_KeyAlreadyInTree_ThrowsException() + foreach (var value in new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }) { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5 }); - Assert.Throws(() => tree.Add(1)); + tree.Add(value); + tree.Count.Should().Be(value); } - [Test] - public void AddRange_MultipleKeys_FormsCorrectTree() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 9, 0, 1, 6, 7, 5, 2, 8, 4, 3 }); - tree.Count.Should().Be(10); - tree.GetKeysInOrder().SequenceEqual(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 1, 0, 3, 2, 4, 7, 6, 9, 8 }).Should().BeTrue(); - } + tree.GetKeysInOrder().SequenceEqual(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 4, 2, 1, 3, 6, 5, 8, 7, 9, 10 }).Should().BeTrue(); + } - [Test] - public void Remove_SimpleCases_TreeStillValid() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 }); - tree.Remove(6); - tree.Count.Should().Be(9); - tree.Contains(6).Should().BeFalse(); - tree.GetKeysInOrder().SequenceEqual(new[] { 1, 8, 11, 13, 15, 17, 22, 25, 27 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 8, 1, 11, 17, 15, 25, 22, 27 }).Should().BeTrue(); - - tree = new RedBlackTree(); - tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 }); - tree.Remove(1); - tree.Count.Should().Be(9); - tree.Contains(1).Should().BeFalse(); - tree.GetKeysInOrder().SequenceEqual(new[] { 6, 8, 11, 13, 15, 17, 22, 25, 27 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 8, 6, 11, 17, 15, 25, 22, 27 }).Should().BeTrue(); - - tree = new RedBlackTree(); - tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 }); - tree.Remove(17); - tree.Count.Should().Be(9); - tree.Contains(17).Should().BeFalse(); - tree.GetKeysInOrder().SequenceEqual(new[] { 1, 6, 8, 11, 13, 15, 22, 25, 27 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 8, 1, 6, 11, 22, 15, 25, 27 }).Should().BeTrue(); - - tree = new RedBlackTree(); - tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 }); - tree.Remove(25); - tree.Count.Should().Be(9); - tree.Contains(25).Should().BeFalse(); - tree.GetKeysInOrder().SequenceEqual(new[] { 1, 6, 8, 11, 13, 15, 17, 22, 27 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 8, 1, 6, 11, 17, 15, 27, 22 }).Should().BeTrue(); - - tree = new RedBlackTree(); - tree.AddRange(new[] { 7, 3, 18, 10, 22, 8, 11, 26 }); - tree.Remove(18); - tree.Count.Should().Be(7); - tree.Contains(18).Should().BeFalse(); - tree.GetKeysInOrder().SequenceEqual(new[] { 3, 7, 8, 10, 11, 22, 26 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 7, 3, 22, 10, 8, 11, 26 }).Should().BeTrue(); - - tree = new RedBlackTree(); - tree.Add(1); - tree.Add(2); - tree.Remove(1); - tree.Count.Should().Be(1); - tree.GetKeysInOrder().SequenceEqual(new[] { 2 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 2 }).Should().BeTrue(); - } + [Test] + public void Add_KeyAlreadyInTree_ThrowsException() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5 }); + Assert.Throws(() => tree.Add(1)); + } - [Test] - public void Remove_Case1_TreeStillValid() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 5, 2, 8, 1 }); - tree.Remove(1); - tree.Remove(2); - tree.Contains(2).Should().BeFalse(); - tree.GetKeysInOrder().SequenceEqual(new[] { 5, 8 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 8 }).Should().BeTrue(); - } + [Test] + public void AddRange_MultipleKeys_FormsCorrectTree() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 9, 0, 1, 6, 7, 5, 2, 8, 4, 3 }); + tree.Count.Should().Be(10); + tree.GetKeysInOrder().SequenceEqual(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 1, 0, 3, 2, 4, 7, 6, 9, 8 }).Should().BeTrue(); + } - [Test] - public void Remove_Case3_TreeStillValid() - { - // Move to case 6 - var tree = new RedBlackTree(); - tree.AddRange(new[] { 7, 3, 18, 1, 10, 22, 8, 11, 26 }); - tree.Remove(1); - tree.Remove(3); - tree.Count.Should().Be(7); - tree.Contains(3).Should().BeFalse(); - tree.GetKeysInOrder().SequenceEqual(new[] { 7, 8, 10, 11, 18, 22, 26 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 18, 10, 7, 8, 11, 22, 26 }).Should().BeTrue(); - - // Move to case 5 - tree = new RedBlackTree(); - tree.AddRange(new[] { 8, 3, 2, 0, 9, 4, 7, 6, 1, 5 }); - tree.Remove(8); - tree.Remove(6); - tree.Remove(9); - tree.Count.Should().Be(7); - tree.GetKeysInOrder().SequenceEqual(new[] { 0, 1, 2, 3, 4, 5, 7 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 3, 1, 0, 2, 5, 4, 7 }).Should().BeTrue(); - - // Move to case 4 - tree = new RedBlackTree(); - tree.AddRange(new[] { 7, 5, 8, 4, 6, 3, 2, 9, 0, 1 }); - tree.Remove(9); - tree.Remove(6); - tree.Remove(5); - tree.Remove(8); - tree.Count.Should().Be(6); - tree.GetKeysInOrder().SequenceEqual(new[] { 0, 1, 2, 3, 4, 7 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 3, 1, 0, 2, 7, 4 }).Should().BeTrue(); - } + [Test] + public void Remove_SimpleCases_TreeStillValid() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 }); + tree.Remove(6); + tree.Count.Should().Be(9); + tree.Contains(6).Should().BeFalse(); + tree.GetKeysInOrder().SequenceEqual(new[] { 1, 8, 11, 13, 15, 17, 22, 25, 27 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 8, 1, 11, 17, 15, 25, 22, 27 }).Should().BeTrue(); + + tree = new RedBlackTree(); + tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 }); + tree.Remove(1); + tree.Count.Should().Be(9); + tree.Contains(1).Should().BeFalse(); + tree.GetKeysInOrder().SequenceEqual(new[] { 6, 8, 11, 13, 15, 17, 22, 25, 27 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 8, 6, 11, 17, 15, 25, 22, 27 }).Should().BeTrue(); + + tree = new RedBlackTree(); + tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 }); + tree.Remove(17); + tree.Count.Should().Be(9); + tree.Contains(17).Should().BeFalse(); + tree.GetKeysInOrder().SequenceEqual(new[] { 1, 6, 8, 11, 13, 15, 22, 25, 27 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 8, 1, 6, 11, 22, 15, 25, 27 }).Should().BeTrue(); + + tree = new RedBlackTree(); + tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 }); + tree.Remove(25); + tree.Count.Should().Be(9); + tree.Contains(25).Should().BeFalse(); + tree.GetKeysInOrder().SequenceEqual(new[] { 1, 6, 8, 11, 13, 15, 17, 22, 27 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 8, 1, 6, 11, 17, 15, 27, 22 }).Should().BeTrue(); + + tree = new RedBlackTree(); + tree.AddRange(new[] { 7, 3, 18, 10, 22, 8, 11, 26 }); + tree.Remove(18); + tree.Count.Should().Be(7); + tree.Contains(18).Should().BeFalse(); + tree.GetKeysInOrder().SequenceEqual(new[] { 3, 7, 8, 10, 11, 22, 26 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 7, 3, 22, 10, 8, 11, 26 }).Should().BeTrue(); + + tree = new RedBlackTree(); + tree.Add(1); + tree.Add(2); + tree.Remove(1); + tree.Count.Should().Be(1); + tree.GetKeysInOrder().SequenceEqual(new[] { 2 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 2 }).Should().BeTrue(); + } - [Test] - public void Remove_Case4_TreeStillValid() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 5, 2, 8, 1, 4, 7, 9, 0, 3 }); - tree.Remove(0); - tree.Remove(3); - tree.Remove(2); - tree.Count.Should().Be(6); - tree.Contains(2).Should().BeFalse(); - tree.GetKeysInOrder().SequenceEqual(new[] { 1, 4, 5, 7, 8, 9 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 4, 1, 8, 7, 9 }).Should().BeTrue(); - } + [Test] + public void Remove_Case1_TreeStillValid() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 5, 2, 8, 1 }); + tree.Remove(1); + tree.Remove(2); + tree.Contains(2).Should().BeFalse(); + tree.GetKeysInOrder().SequenceEqual(new[] { 5, 8 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 8 }).Should().BeTrue(); + } - [Test] - public void Remove_Case5_TreeStillValid() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 }); - tree.Remove(8); - tree.Count.Should().Be(9); - tree.Contains(8).Should().BeFalse(); - tree.GetKeysInOrder().SequenceEqual(new[] { 1, 6, 11, 13, 15, 17, 22, 25, 27 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 6, 1, 11, 17, 15, 25, 22, 27 }).Should().BeTrue(); - - tree = new RedBlackTree(); - tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 0, 6, 22 }); - tree.Remove(13); - tree.Count.Should().Be(9); - tree.Contains(13).Should().BeFalse(); - tree.GetKeysInOrder().SequenceEqual(new[] { 0, 1, 6, 8, 11, 15, 17, 22, 25 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 15, 8, 1, 0, 6, 11, 22, 17, 25 }).Should().BeTrue(); - - tree = new RedBlackTree(); - tree.AddRange(new[] { 7, 0, 1, 4, 8, 2, 3, 6, 5, 9 }); - tree.Remove(7); - tree.Remove(0); - tree.Remove(1); - tree.Remove(4); - tree.Remove(8); - tree.GetKeysInOrder().SequenceEqual(new[] { 2, 3, 5, 6, 9 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 3, 2, 6, 5, 9 }).Should().BeTrue(); - } + [Test] + public void Remove_Case3_TreeStillValid() + { + // Move to case 6 + var tree = new RedBlackTree(); + tree.AddRange(new[] { 7, 3, 18, 1, 10, 22, 8, 11, 26 }); + tree.Remove(1); + tree.Remove(3); + tree.Count.Should().Be(7); + tree.Contains(3).Should().BeFalse(); + tree.GetKeysInOrder().SequenceEqual(new[] { 7, 8, 10, 11, 18, 22, 26 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 18, 10, 7, 8, 11, 22, 26 }).Should().BeTrue(); + + // Move to case 5 + tree = new RedBlackTree(); + tree.AddRange(new[] { 8, 3, 2, 0, 9, 4, 7, 6, 1, 5 }); + tree.Remove(8); + tree.Remove(6); + tree.Remove(9); + tree.Count.Should().Be(7); + tree.GetKeysInOrder().SequenceEqual(new[] { 0, 1, 2, 3, 4, 5, 7 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 3, 1, 0, 2, 5, 4, 7 }).Should().BeTrue(); + + // Move to case 4 + tree = new RedBlackTree(); + tree.AddRange(new[] { 7, 5, 8, 4, 6, 3, 2, 9, 0, 1 }); + tree.Remove(9); + tree.Remove(6); + tree.Remove(5); + tree.Remove(8); + tree.Count.Should().Be(6); + tree.GetKeysInOrder().SequenceEqual(new[] { 0, 1, 2, 3, 4, 7 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 3, 1, 0, 2, 7, 4 }).Should().BeTrue(); + } - [Test] - public void Remove_Case6_TreeStillValid() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 }); - tree.Remove(13); - tree.Count.Should().Be(9); - tree.Contains(13).Should().BeFalse(); - tree.GetKeysInOrder().SequenceEqual(new[] { 1, 6, 8, 11, 15, 17, 22, 25, 27 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 15, 8, 1, 6, 11, 25, 17, 22, 27 }).Should().BeTrue(); - - tree = new RedBlackTree(); - tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 0, 6, 22 }); - tree.Remove(8); - tree.Count.Should().Be(9); - tree.Contains(8).Should().BeFalse(); - tree.GetKeysInOrder().SequenceEqual(new[] { 0, 1, 6, 11, 13, 15, 17, 22, 25 }).Should().BeTrue(); - tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 1, 0, 11, 6, 17, 15, 25, 22 }).Should().BeTrue(); - } + [Test] + public void Remove_Case4_TreeStillValid() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 5, 2, 8, 1, 4, 7, 9, 0, 3 }); + tree.Remove(0); + tree.Remove(3); + tree.Remove(2); + tree.Count.Should().Be(6); + tree.Contains(2).Should().BeFalse(); + tree.GetKeysInOrder().SequenceEqual(new[] { 1, 4, 5, 7, 8, 9 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 5, 4, 1, 8, 7, 9 }).Should().BeTrue(); + } - [Test] - public void Remove_EmptyTree_ThrowsException() - { - var tree = new RedBlackTree(); - Assert.Throws(() => tree.Remove(1)); - } + [Test] + public void Remove_Case5_TreeStillValid() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 }); + tree.Remove(8); + tree.Count.Should().Be(9); + tree.Contains(8).Should().BeFalse(); + tree.GetKeysInOrder().SequenceEqual(new[] { 1, 6, 11, 13, 15, 17, 22, 25, 27 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 6, 1, 11, 17, 15, 25, 22, 27 }).Should().BeTrue(); + + tree = new RedBlackTree(); + tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 0, 6, 22 }); + tree.Remove(13); + tree.Count.Should().Be(9); + tree.Contains(13).Should().BeFalse(); + tree.GetKeysInOrder().SequenceEqual(new[] { 0, 1, 6, 8, 11, 15, 17, 22, 25 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 15, 8, 1, 0, 6, 11, 22, 17, 25 }).Should().BeTrue(); + + tree = new RedBlackTree(); + tree.AddRange(new[] { 7, 0, 1, 4, 8, 2, 3, 6, 5, 9 }); + tree.Remove(7); + tree.Remove(0); + tree.Remove(1); + tree.Remove(4); + tree.Remove(8); + tree.GetKeysInOrder().SequenceEqual(new[] { 2, 3, 5, 6, 9 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 3, 2, 6, 5, 9 }).Should().BeTrue(); + } - [Test] - public void Remove_KeyNotInTree_ThrowsException() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - Assert.Throws(() => tree.Remove(24)); - } + [Test] + public void Remove_Case6_TreeStillValid() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 6, 22, 27 }); + tree.Remove(13); + tree.Count.Should().Be(9); + tree.Contains(13).Should().BeFalse(); + tree.GetKeysInOrder().SequenceEqual(new[] { 1, 6, 8, 11, 15, 17, 22, 25, 27 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 15, 8, 1, 6, 11, 25, 17, 22, 27 }).Should().BeTrue(); + + tree = new RedBlackTree(); + tree.AddRange(new[] { 13, 8, 17, 1, 11, 15, 25, 0, 6, 22 }); + tree.Remove(8); + tree.Count.Should().Be(9); + tree.Contains(8).Should().BeFalse(); + tree.GetKeysInOrder().SequenceEqual(new[] { 0, 1, 6, 11, 13, 15, 17, 22, 25 }).Should().BeTrue(); + tree.GetKeysPreOrder().SequenceEqual(new[] { 13, 1, 0, 11, 6, 17, 15, 25, 22 }).Should().BeTrue(); + } - [Test] - public void Contains_CorrectReturn() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.Contains(3).Should().BeTrue(); - tree.Contains(7).Should().BeTrue(); - tree.Contains(24).Should().BeFalse(); - tree.Contains(-1).Should().BeFalse(); - } + [Test] + public void Remove_EmptyTree_ThrowsException() + { + var tree = new RedBlackTree(); + Assert.Throws(() => tree.Remove(1)); + } - [Test] - public void Contains_EmptyTree_ReturnsFalse() - { - var tree = new RedBlackTree(); - tree.Contains(5).Should().BeFalse(); - tree.Contains(-12).Should().BeFalse(); - } + [Test] + public void Remove_KeyNotInTree_ThrowsException() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + Assert.Throws(() => tree.Remove(24)); + } - [Test] - public void GetMin_CorrectReturn() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.GetMin().Should().Be(1); - } + [Test] + public void Contains_CorrectReturn() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.Contains(3).Should().BeTrue(); + tree.Contains(7).Should().BeTrue(); + tree.Contains(24).Should().BeFalse(); + tree.Contains(-1).Should().BeFalse(); + } - [Test] - public void GetMin_EmptyTree_ThrowsException() - { - var tree = new RedBlackTree(); - Assert.Throws(() => tree.GetMin()); - } + [Test] + public void Contains_EmptyTree_ReturnsFalse() + { + var tree = new RedBlackTree(); + tree.Contains(5).Should().BeFalse(); + tree.Contains(-12).Should().BeFalse(); + } - [Test] - public void GetMax_CorrectReturn() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.GetMax().Should().Be(10); - } + [Test] + public void GetMin_CorrectReturn() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.GetMin().Should().Be(1); + } - [Test] - public void GetMax_EmptyTree_ThrowsException() - { - var tree = new RedBlackTree(); - Assert.Throws(() => tree.GetMax()); - } + [Test] + public void GetMin_EmptyTree_ThrowsException() + { + var tree = new RedBlackTree(); + Assert.Throws(() => tree.GetMin()); + } - [Test] - public void GetKeysInOrder_CorrectReturn() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.GetKeysInOrder().SequenceEqual(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Should().BeTrue(); - } + [Test] + public void GetMax_CorrectReturn() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.GetMax().Should().Be(10); + } - [Test] - public void GetKeysInOrder_EmptyTree_CorrectReturn() - { - var tree = new RedBlackTree(); - tree.GetKeysInOrder().SequenceEqual(Array.Empty()).Should().BeTrue(); - } + [Test] + public void GetMax_EmptyTree_ThrowsException() + { + var tree = new RedBlackTree(); + Assert.Throws(() => tree.GetMax()); + } - [Test] - public void GetKeysPreOrder_CorrectReturn() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.GetKeysPreOrder().SequenceEqual(new[] { 4, 2, 1, 3, 6, 5, 8, 7, 9, 10 }).Should().BeTrue(); - } + [Test] + public void GetKeysInOrder_CorrectReturn() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.GetKeysInOrder().SequenceEqual(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Should().BeTrue(); + } - [Test] - public void GetKeysPreOrder_EmptyTree_CorrectReturn() - { - var tree = new RedBlackTree(); - tree.GetKeysPreOrder().SequenceEqual(Array.Empty()).Should().BeTrue(); - } + [Test] + public void GetKeysInOrder_EmptyTree_CorrectReturn() + { + var tree = new RedBlackTree(); + tree.GetKeysInOrder().SequenceEqual(Array.Empty()).Should().BeTrue(); + } - [Test] - public void GetKeysPostOrder_CorrectReturn() - { - var tree = new RedBlackTree(); - tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); - tree.GetKeysPostOrder().SequenceEqual(new[] { 1, 3, 2, 5, 7, 10, 9, 8, 6, 4 }).Should().BeTrue(); - } + [Test] + public void GetKeysPreOrder_CorrectReturn() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.GetKeysPreOrder().SequenceEqual(new[] { 4, 2, 1, 3, 6, 5, 8, 7, 9, 10 }).Should().BeTrue(); + } - [Test] - public void GetKeysPostOrder_EmptyTree_CorrectReturn() - { - var tree = new RedBlackTree(); - tree.GetKeysPostOrder().SequenceEqual(Array.Empty()).Should().BeTrue(); - } + [Test] + public void GetKeysPreOrder_EmptyTree_CorrectReturn() + { + var tree = new RedBlackTree(); + tree.GetKeysPreOrder().SequenceEqual(Array.Empty()).Should().BeTrue(); + } + + [Test] + public void GetKeysPostOrder_CorrectReturn() + { + var tree = new RedBlackTree(); + tree.AddRange(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + tree.GetKeysPostOrder().SequenceEqual(new[] { 1, 3, 2, 5, 7, 10, 9, 8, 6, 4 }).Should().BeTrue(); + } + + [Test] + public void GetKeysPostOrder_EmptyTree_CorrectReturn() + { + var tree = new RedBlackTree(); + tree.GetKeysPostOrder().SequenceEqual(Array.Empty()).Should().BeTrue(); } } diff --git a/DataStructures.Tests/ScapegoatTree/ExtensionsTests.cs b/DataStructures.Tests/ScapegoatTree/ExtensionsTests.cs index 65bcb205..d81ca973 100644 --- a/DataStructures.Tests/ScapegoatTree/ExtensionsTests.cs +++ b/DataStructures.Tests/ScapegoatTree/ExtensionsTests.cs @@ -3,57 +3,56 @@ using DataStructures.ScapegoatTree; using NUnit.Framework; -namespace DataStructures.Tests.ScapegoatTree +namespace DataStructures.Tests.ScapegoatTree; + +public class ExtensionsTests { - public class ExtensionsTests + [Test] + public void RebuildFlatTree_ValidFlatTree_RebuildsTree() { - [Test] - public void RebuildFlatTree_ValidFlatTree_RebuildsTree() + var expected = new Node(3) { - var expected = new Node(3) + Left = new Node(1) + { + Left = new Node(-1), + Right = new Node(2), + }, + Right = new Node(6) { - Left = new Node(1) - { - Left = new Node(-1), - Right = new Node(2), - }, - Right = new Node(6) - { - Left = new Node(5), - }, - }; + Left = new Node(5), + }, + }; - var list = new List> - { - new(-1), - new(1), - new(2), - new(3), - new(5), - new(6), - }; + var list = new List> + { + new(-1), + new(1), + new(2), + new(3), + new(5), + new(6), + }; - var tree = Extensions.RebuildFromList(list, 0, list.Count - 1); + var tree = Extensions.RebuildFromList(list, 0, list.Count - 1); - Assert.AreEqual(list.Count, tree.GetSize()); - Assert.AreEqual(expected.Key, tree.Key); - Assert.IsNotNull(tree.Left); - Assert.IsNotNull(tree.Right); - Assert.AreEqual(expected.Left.Key, tree.Left!.Key); - Assert.AreEqual(expected.Right.Key, tree.Right!.Key); - Assert.IsNotNull(tree.Left.Left); - Assert.IsNotNull(tree.Left.Right); - Assert.AreEqual(expected.Left.Left.Key, tree.Left!.Left!.Key); - Assert.AreEqual(expected.Left.Right.Key, tree.Left!.Right!.Key); - Assert.IsNotNull(tree.Right.Left); - Assert.AreEqual(expected.Right.Left.Key, tree.Right!.Left!.Key); - } + Assert.AreEqual(list.Count, tree.GetSize()); + Assert.AreEqual(expected.Key, tree.Key); + Assert.IsNotNull(tree.Left); + Assert.IsNotNull(tree.Right); + Assert.AreEqual(expected.Left.Key, tree.Left!.Key); + Assert.AreEqual(expected.Right.Key, tree.Right!.Key); + Assert.IsNotNull(tree.Left.Left); + Assert.IsNotNull(tree.Left.Right); + Assert.AreEqual(expected.Left.Left.Key, tree.Left!.Left!.Key); + Assert.AreEqual(expected.Left.Right.Key, tree.Left!.Right!.Key); + Assert.IsNotNull(tree.Right.Left); + Assert.AreEqual(expected.Right.Left.Key, tree.Right!.Left!.Key); + } - [Test] - public void RebuildFromList_RangeIsInvalid_ThrowsException() - { - Assert.Throws(() => Extensions.RebuildFromList(new List>(), 1, 0)); - } + [Test] + public void RebuildFromList_RangeIsInvalid_ThrowsException() + { + Assert.Throws(() => Extensions.RebuildFromList(new List>(), 1, 0)); } } diff --git a/DataStructures.Tests/ScapegoatTree/ScapegoatTreeNodeTests.cs b/DataStructures.Tests/ScapegoatTree/ScapegoatTreeNodeTests.cs index 196b65a9..39adf687 100644 --- a/DataStructures.Tests/ScapegoatTree/ScapegoatTreeNodeTests.cs +++ b/DataStructures.Tests/ScapegoatTree/ScapegoatTreeNodeTests.cs @@ -2,187 +2,186 @@ using DataStructures.ScapegoatTree; using NUnit.Framework; -namespace DataStructures.Tests.ScapegoatTree +namespace DataStructures.Tests.ScapegoatTree; + +[TestFixture] +public class ScapegoatTreeNodeTests { - [TestFixture] - public class ScapegoatTreeNodeTests + [Test] + [TestCase(2,1)] + [TestCase("B", "A")] + public void RightSetter_OtherKeyPrecedesRightKey_ThrowsException(TKey a, TKey b) + where TKey : IComparable + { + var instance = new Node(a); + var other = new Node(b); + + Assert.Throws(() => instance.Right = other); + } + + [Test] + [TestCase(1,2)] + [TestCase("A","B")] + public void RightSetter_OtherKeyFollowsRightKey_AddsChild(TKey a, TKey b) + where TKey : IComparable + { + var instance = new Node(a); + var other = new Node(b); + + Assert.DoesNotThrow(() => instance.Right = other); + } + + [Test] + [TestCase(1,2)] + [TestCase("A","B")] + public void LeftSetter_OtherKeyFollowsLeftKey_ThrowsException(TKey a, TKey b) + where TKey : IComparable + { + var instance = new Node(a); + var other = new Node(b); + + Assert.Throws(() => instance.Left = other); + } + + [Test] + [TestCase(2,1)] + [TestCase("B", "A")] + public void LeftSetter_OtherKeyPrecedesLeftKey_AddsChild(TKey a, TKey b) + where TKey : IComparable { - [Test] - [TestCase(2,1)] - [TestCase("B", "A")] - public void RightSetter_OtherKeyPrecedesRightKey_ThrowsException(TKey a, TKey b) - where TKey : IComparable - { - var instance = new Node(a); - var other = new Node(b); - - Assert.Throws(() => instance.Right = other); - } - - [Test] - [TestCase(1,2)] - [TestCase("A","B")] - public void RightSetter_OtherKeyFollowsRightKey_AddsChild(TKey a, TKey b) - where TKey : IComparable - { - var instance = new Node(a); - var other = new Node(b); - - Assert.DoesNotThrow(() => instance.Right = other); - } - - [Test] - [TestCase(1,2)] - [TestCase("A","B")] - public void LeftSetter_OtherKeyFollowsLeftKey_ThrowsException(TKey a, TKey b) - where TKey : IComparable - { - var instance = new Node(a); - var other = new Node(b); - - Assert.Throws(() => instance.Left = other); - } - - [Test] - [TestCase(2,1)] - [TestCase("B", "A")] - public void LeftSetter_OtherKeyPrecedesLeftKey_AddsChild(TKey a, TKey b) - where TKey : IComparable - { - var instance = new Node(a); - var other = new Node(b); - - Assert.DoesNotThrow(() => instance.Left = other); - } - - [Test] - [TestCase(1,2)] - [TestCase("A","B")] - public void CompareTo_InstanceKeyPrecedesOtherKey_ReturnsMinusOne(TKey a, TKey b) - where TKey : IComparable - { - var instance = new Node(a); - var other = new Node(b); - - var result = instance.Key.CompareTo(other.Key); - - Assert.AreEqual(result, -1); - } - - [Test] - [TestCase(2, 1)] - [TestCase("B","A")] - public void CompareTo_InstanceKeyFollowsOtherKey_ReturnsOne(TKey a, TKey b) - where TKey : IComparable - { - var instance = new Node(a); - var other = new Node(b); - - var result = instance.Key.CompareTo(other.Key); - - Assert.AreEqual(result, 1); - } - - [Test] - [TestCase(1, 1)] - [TestCase("A","A")] - public void CompareTo_InstanceKeyEqualsOtherKey_ReturnsZero(TKey a, TKey b) - where TKey : IComparable - { - var instance = new Node(a); - var other = new Node(b); - - var result = instance.Key.CompareTo(other.Key); - - Assert.AreEqual(result, 0); - } - - [Test] - public void GetSize_NodeHasNoChildren_ReturnsOne() - { - var node = new Node(1); - - Assert.AreEqual(node.GetSize(), 1); - } - - [Test] - public void GetSize_NodeHasChildren_ReturnsCorrectSize() - { - var node = new Node(1, new Node(2), new Node(0)); - - Assert.AreEqual(node.GetSize(), 3); - } - - [Test] - public void GetSmallestKeyNode_NodeHasNoLeftChildren_ReturnsNode() - { - var node = new Node(1); - - Assert.AreEqual(node.GetSmallestKeyNode(), node); - } - - [Test] - public void GetSmallestKeyNode_NodeHasSmallestChild_ReturnsChild() - { - var node = new Node(1); - var smaller = new Node(0); - var smallest = new Node(-1); - node.Left = smaller; - smaller.Left = smallest; - - Assert.AreEqual(node.GetSmallestKeyNode(), smallest); - } - - [Test] - public void GetLargestKeyNode_NodeHasNoRightChildren_ReturnsNode() - { - var node = new Node(1); - - Assert.AreEqual(node.GetLargestKeyNode(), node); - } - - [Test] - public void GetLargestKeyNode_NodeHasLargestChild_ReturnsChild() - { - var node = new Node(1); - var larger = new Node(2); - var largest = new Node(3); - node.Right = larger; - larger.Right = largest; - - Assert.AreEqual(node.GetLargestKeyNode(), largest); - } - - [Test] - public void IsAlphaWeightBalanced_TreeIsUnbalanced_ReturnsFalse() - { - var root = new Node(0); - var a = new Node(-1); - var b = new Node(-2); - var c = new Node(-3); - var d = new Node(1); - - root.Left = a; - a.Left = b; - b.Left = c; - root.Right = d; - - Assert.IsFalse(root.IsAlphaWeightBalanced(0.5)); - } - - [Test] - public void IsAlphaWeightBalanced_TreeIsBalanced_ReturnsTrue() - { - var root = new Node(0); - var a = new Node(-1); - var b = new Node(-2); - var d = new Node(1); - - root.Left = a; - a.Left = b; - root.Right = d; - - Assert.IsTrue(root.IsAlphaWeightBalanced(0.5)); - } + var instance = new Node(a); + var other = new Node(b); + + Assert.DoesNotThrow(() => instance.Left = other); + } + + [Test] + [TestCase(1,2)] + [TestCase("A","B")] + public void CompareTo_InstanceKeyPrecedesOtherKey_ReturnsMinusOne(TKey a, TKey b) + where TKey : IComparable + { + var instance = new Node(a); + var other = new Node(b); + + var result = instance.Key.CompareTo(other.Key); + + Assert.AreEqual(result, -1); + } + + [Test] + [TestCase(2, 1)] + [TestCase("B","A")] + public void CompareTo_InstanceKeyFollowsOtherKey_ReturnsOne(TKey a, TKey b) + where TKey : IComparable + { + var instance = new Node(a); + var other = new Node(b); + + var result = instance.Key.CompareTo(other.Key); + + Assert.AreEqual(result, 1); + } + + [Test] + [TestCase(1, 1)] + [TestCase("A","A")] + public void CompareTo_InstanceKeyEqualsOtherKey_ReturnsZero(TKey a, TKey b) + where TKey : IComparable + { + var instance = new Node(a); + var other = new Node(b); + + var result = instance.Key.CompareTo(other.Key); + + Assert.AreEqual(result, 0); + } + + [Test] + public void GetSize_NodeHasNoChildren_ReturnsOne() + { + var node = new Node(1); + + Assert.AreEqual(node.GetSize(), 1); + } + + [Test] + public void GetSize_NodeHasChildren_ReturnsCorrectSize() + { + var node = new Node(1, new Node(2), new Node(0)); + + Assert.AreEqual(node.GetSize(), 3); + } + + [Test] + public void GetSmallestKeyNode_NodeHasNoLeftChildren_ReturnsNode() + { + var node = new Node(1); + + Assert.AreEqual(node.GetSmallestKeyNode(), node); + } + + [Test] + public void GetSmallestKeyNode_NodeHasSmallestChild_ReturnsChild() + { + var node = new Node(1); + var smaller = new Node(0); + var smallest = new Node(-1); + node.Left = smaller; + smaller.Left = smallest; + + Assert.AreEqual(node.GetSmallestKeyNode(), smallest); + } + + [Test] + public void GetLargestKeyNode_NodeHasNoRightChildren_ReturnsNode() + { + var node = new Node(1); + + Assert.AreEqual(node.GetLargestKeyNode(), node); + } + + [Test] + public void GetLargestKeyNode_NodeHasLargestChild_ReturnsChild() + { + var node = new Node(1); + var larger = new Node(2); + var largest = new Node(3); + node.Right = larger; + larger.Right = largest; + + Assert.AreEqual(node.GetLargestKeyNode(), largest); + } + + [Test] + public void IsAlphaWeightBalanced_TreeIsUnbalanced_ReturnsFalse() + { + var root = new Node(0); + var a = new Node(-1); + var b = new Node(-2); + var c = new Node(-3); + var d = new Node(1); + + root.Left = a; + a.Left = b; + b.Left = c; + root.Right = d; + + Assert.IsFalse(root.IsAlphaWeightBalanced(0.5)); + } + + [Test] + public void IsAlphaWeightBalanced_TreeIsBalanced_ReturnsTrue() + { + var root = new Node(0); + var a = new Node(-1); + var b = new Node(-2); + var d = new Node(1); + + root.Left = a; + a.Left = b; + root.Right = d; + + Assert.IsTrue(root.IsAlphaWeightBalanced(0.5)); } } diff --git a/DataStructures.Tests/ScapegoatTree/ScapegoatTreeTests.cs b/DataStructures.Tests/ScapegoatTree/ScapegoatTreeTests.cs index 4c128f92..08733c94 100644 --- a/DataStructures.Tests/ScapegoatTree/ScapegoatTreeTests.cs +++ b/DataStructures.Tests/ScapegoatTree/ScapegoatTreeTests.cs @@ -3,458 +3,457 @@ using DataStructures.ScapegoatTree; using NUnit.Framework; -namespace DataStructures.Tests.ScapegoatTree +namespace DataStructures.Tests.ScapegoatTree; + +public class ScapegoatTreeTests { - public class ScapegoatTreeTests + [Test] + public void Constructor_NoParameters_InstanceIsValid() { - [Test] - public void Constructor_NoParameters_InstanceIsValid() - { - var tree = new ScapegoatTree(); + var tree = new ScapegoatTree(); - Assert.IsNull(tree.Root); - Assert.IsTrue(tree.Size == 0); - Assert.IsTrue(tree.MaxSize == 0); - Assert.AreEqual(0.5, tree.Alpha); - } + Assert.IsNull(tree.Root); + Assert.IsTrue(tree.Size == 0); + Assert.IsTrue(tree.MaxSize == 0); + Assert.AreEqual(0.5, tree.Alpha); + } - [Test] - public void Constructor_AlphaParameter_InstanceIsValid() - { - var expected = 0.6; + [Test] + public void Constructor_AlphaParameter_InstanceIsValid() + { + var expected = 0.6; - var tree = new ScapegoatTree(expected); + var tree = new ScapegoatTree(expected); - Assert.IsNull(tree.Root); - Assert.IsTrue(tree.Size == 0); - Assert.IsTrue(tree.MaxSize == 0); - Assert.AreEqual(expected, tree.Alpha); - } + Assert.IsNull(tree.Root); + Assert.IsTrue(tree.Size == 0); + Assert.IsTrue(tree.MaxSize == 0); + Assert.AreEqual(expected, tree.Alpha); + } - [Test] - [TestCase(1.1)] - [TestCase(0.4)] - public void Constructor_AlphaParameterIsInvalid_ThrowsException(double alpha) - { - Assert.Throws(() => new ScapegoatTree(alpha)); - Assert.Throws(() => new ScapegoatTree(1, alpha)); - } + [Test] + [TestCase(1.1)] + [TestCase(0.4)] + public void Constructor_AlphaParameterIsInvalid_ThrowsException(double alpha) + { + Assert.Throws(() => new ScapegoatTree(alpha)); + Assert.Throws(() => new ScapegoatTree(1, alpha)); + } - [Test] - public void Constructor_KeyParameter_InstanceIsValid() - { - var expected = 10; + [Test] + public void Constructor_KeyParameter_InstanceIsValid() + { + var expected = 10; - var tree = new ScapegoatTree(expected); + var tree = new ScapegoatTree(expected); - Assert.IsNotNull(tree.Root); - Assert.IsTrue(tree.Root!.Key == expected); - Assert.IsTrue(tree.Size == 1); - Assert.IsTrue(tree.MaxSize == 1); - Assert.AreEqual(0.5, tree.Alpha); - } + Assert.IsNotNull(tree.Root); + Assert.IsTrue(tree.Root!.Key == expected); + Assert.IsTrue(tree.Size == 1); + Assert.IsTrue(tree.MaxSize == 1); + Assert.AreEqual(0.5, tree.Alpha); + } - [Test] - public void Constructor_KeyAndAlphaParameters_InstanceIsValid() - { - var key = 10; - var alpha = 0.8; + [Test] + public void Constructor_KeyAndAlphaParameters_InstanceIsValid() + { + var key = 10; + var alpha = 0.8; - var tree = new ScapegoatTree(key, alpha); + var tree = new ScapegoatTree(key, alpha); - Assert.IsNotNull(tree.Root); - Assert.IsTrue(tree.Size == 1); - Assert.IsTrue(tree.MaxSize == 1); - Assert.AreEqual(alpha, tree.Alpha); - } + Assert.IsNotNull(tree.Root); + Assert.IsTrue(tree.Size == 1); + Assert.IsTrue(tree.MaxSize == 1); + Assert.AreEqual(alpha, tree.Alpha); + } - [Test] - public void Constructor_NodeAndAlphaParameters_InstanceIsValid() - { - var node = new Node(10, new Node(11), new Node(1)); - var alpha = 0.8; + [Test] + public void Constructor_NodeAndAlphaParameters_InstanceIsValid() + { + var node = new Node(10, new Node(11), new Node(1)); + var alpha = 0.8; - var tree = new ScapegoatTree(node, alpha); + var tree = new ScapegoatTree(node, alpha); - Assert.IsNotNull(tree.Root); - Assert.IsTrue(tree.Size == 3); - Assert.IsTrue(tree.MaxSize == 3); - Assert.AreEqual(alpha, tree.Alpha); - } + Assert.IsNotNull(tree.Root); + Assert.IsTrue(tree.Size == 3); + Assert.IsTrue(tree.MaxSize == 3); + Assert.AreEqual(alpha, tree.Alpha); + } - [Test] - public void IsAlphaWeightBalanced_RootIsNull_ReturnsTrue() - { - var tree = new ScapegoatTree(); + [Test] + public void IsAlphaWeightBalanced_RootIsNull_ReturnsTrue() + { + var tree = new ScapegoatTree(); - var result = tree.IsAlphaWeightBalanced(); + var result = tree.IsAlphaWeightBalanced(); - Assert.IsTrue(result); - } + Assert.IsTrue(result); + } - [Test] - public void Search_RootIsNull_ReturnsNull() - { - var tree = new ScapegoatTree(); + [Test] + public void Search_RootIsNull_ReturnsNull() + { + var tree = new ScapegoatTree(); - var result = tree.Search(1); + var result = tree.Search(1); - Assert.IsNull(result); - } + Assert.IsNull(result); + } - [Test] - public void Search_KeyIsPresent_ReturnsKey() - { - var tree = new ScapegoatTree(key: 1); + [Test] + public void Search_KeyIsPresent_ReturnsKey() + { + var tree = new ScapegoatTree(key: 1); - var result = tree.Search(1); + var result = tree.Search(1); - Assert.IsNotNull(result); - Assert.AreEqual(1, result!.Key); - } + Assert.IsNotNull(result); + Assert.AreEqual(1, result!.Key); + } - [Test] - [TestCase(-2)] - [TestCase(3)] - public void Search_KeyIsNotPresent_ReturnsNull(int key) - { - var root = new Node(1, new Node(2), new Node(-1)); + [Test] + [TestCase(-2)] + [TestCase(3)] + public void Search_KeyIsNotPresent_ReturnsNull(int key) + { + var root = new Node(1, new Node(2), new Node(-1)); - var tree = new ScapegoatTree(root, 0.5); + var tree = new ScapegoatTree(root, 0.5); - var result = tree.Search(key); + var result = tree.Search(key); - Assert.IsNull(result); - } + Assert.IsNull(result); + } - [Test] - public void Insert_RootIsNull_InsertsRoot() - { - var tree = new ScapegoatTree(); + [Test] + public void Insert_RootIsNull_InsertsRoot() + { + var tree = new ScapegoatTree(); - var inserted = tree.Insert(1); + var inserted = tree.Insert(1); - Assert.IsTrue(inserted); - Assert.IsNotNull(tree.Root); - Assert.AreEqual(1, tree.Root!.Key); - Assert.AreEqual(1, tree.Size); - Assert.AreEqual(1, tree.MaxSize); - } + Assert.IsTrue(inserted); + Assert.IsNotNull(tree.Root); + Assert.AreEqual(1, tree.Root!.Key); + Assert.AreEqual(1, tree.Size); + Assert.AreEqual(1, tree.MaxSize); + } - [Test] - public void Delete_RootIsNull_ReturnsFalse() - { - var tree = new ScapegoatTree(); + [Test] + public void Delete_RootIsNull_ReturnsFalse() + { + var tree = new ScapegoatTree(); - var deleted = tree.Delete(1); + var deleted = tree.Delete(1); - Assert.IsFalse(deleted); - } + Assert.IsFalse(deleted); + } - [Test] - public void Delete_KeyIsNotPresent_ReturnsFalse() - { - var tree = new ScapegoatTree(1); + [Test] + public void Delete_KeyIsNotPresent_ReturnsFalse() + { + var tree = new ScapegoatTree(1); - var deleted = tree.Delete(2); + var deleted = tree.Delete(2); - Assert.IsFalse(deleted); - Assert.AreEqual(1, tree.Size); - } + Assert.IsFalse(deleted); + Assert.AreEqual(1, tree.Size); + } - [Test] - public void Insert_KeyIsPresent_ReturnsFalse() - { - var tree = new ScapegoatTree(1); + [Test] + public void Insert_KeyIsPresent_ReturnsFalse() + { + var tree = new ScapegoatTree(1); - var inserted = tree.Insert(1); + var inserted = tree.Insert(1); - Assert.IsFalse(inserted); - Assert.AreEqual(1, tree.Size); - Assert.AreEqual(1, tree.MaxSize); - } + Assert.IsFalse(inserted); + Assert.AreEqual(1, tree.Size); + Assert.AreEqual(1, tree.MaxSize); + } - [Test] - public void Remove_KeyIsPresent_RemovesKey() - { - var tree = new ScapegoatTree(1); + [Test] + public void Remove_KeyIsPresent_RemovesKey() + { + var tree = new ScapegoatTree(1); - var inserted = tree.Insert(2); + var inserted = tree.Insert(2); - Assert.IsTrue(inserted); + Assert.IsTrue(inserted); - var deleted = tree.Delete(2); + var deleted = tree.Delete(2); - Assert.IsTrue(deleted); - Assert.AreEqual(1, tree.Size); - } + Assert.IsTrue(deleted); + Assert.AreEqual(1, tree.Size); + } - [Test] - public void Remove_KeyIsRootWithNoChildren_RemovesKey() - { - var tree = new ScapegoatTree(1); + [Test] + public void Remove_KeyIsRootWithNoChildren_RemovesKey() + { + var tree = new ScapegoatTree(1); - var deleted = tree.Delete(1); + var deleted = tree.Delete(1); - Assert.IsTrue(deleted); - Assert.IsNull(tree.Root); - Assert.AreEqual(0, tree.Size); - } + Assert.IsTrue(deleted); + Assert.IsNull(tree.Root); + Assert.AreEqual(0, tree.Size); + } - [Test] - public void Remove_KeyIsRootWithOneLeftChild_RemovesKey() - { - var tree = new ScapegoatTree(1); + [Test] + public void Remove_KeyIsRootWithOneLeftChild_RemovesKey() + { + var tree = new ScapegoatTree(1); - var inserted = tree.Insert(-1); + var inserted = tree.Insert(-1); - Assert.IsTrue(inserted); + Assert.IsTrue(inserted); - var deleted = tree.Delete(1); + var deleted = tree.Delete(1); - Assert.IsTrue(deleted); - Assert.AreEqual(1, tree.Size); - } + Assert.IsTrue(deleted); + Assert.AreEqual(1, tree.Size); + } - [Test] - public void Remove_KeyIsRootWithOneRightChild_RemovesKey() - { - var tree = new ScapegoatTree(1); + [Test] + public void Remove_KeyIsRootWithOneRightChild_RemovesKey() + { + var tree = new ScapegoatTree(1); - var inserted = tree.Insert(2); + var inserted = tree.Insert(2); - Assert.IsTrue(inserted); + Assert.IsTrue(inserted); - var deleted = tree.Delete(1); + var deleted = tree.Delete(1); - Assert.IsTrue(deleted); - Assert.AreEqual(1, tree.Size); - } + Assert.IsTrue(deleted); + Assert.AreEqual(1, tree.Size); + } - [Test] - public void Remove_KeyIsRootWithTwoChildren_RemovesKey() - { - var tree = new ScapegoatTree(1); + [Test] + public void Remove_KeyIsRootWithTwoChildren_RemovesKey() + { + var tree = new ScapegoatTree(1); - var inserted = tree.Insert(-1); + var inserted = tree.Insert(-1); - Assert.IsTrue(inserted); + Assert.IsTrue(inserted); - inserted = tree.Insert(2); + inserted = tree.Insert(2); - Assert.IsTrue(inserted); + Assert.IsTrue(inserted); - var deleted = tree.Delete(1); + var deleted = tree.Delete(1); - Assert.IsTrue(deleted); - Assert.AreEqual(2, tree.Size); - } + Assert.IsTrue(deleted); + Assert.AreEqual(2, tree.Size); + } - [Test] - public void Insert_KeyIsNotPresent_KeyIsInserted() - { - var tree = new ScapegoatTree(1); + [Test] + public void Insert_KeyIsNotPresent_KeyIsInserted() + { + var tree = new ScapegoatTree(1); - var inserted = tree.Insert(2); + var inserted = tree.Insert(2); - Assert.IsTrue(inserted); - Assert.AreEqual(2, tree.Size); - Assert.AreEqual(2, tree.MaxSize); - } + Assert.IsTrue(inserted); + Assert.AreEqual(2, tree.Size); + Assert.AreEqual(2, tree.MaxSize); + } + + [Test] + [TestCase(3, new[]{2,5,1,6}, -1, 0.5)] + public void Insert_TreeIsUnbalanced_RebuildsTree(int root, int[] keys, int candidate, double alpha) + { + var tree = new ScapegoatTree(root, alpha); + + tree.TreeIsUnbalanced += FailTreeIsUnbalanced; - [Test] - [TestCase(3, new[]{2,5,1,6}, -1, 0.5)] - public void Insert_TreeIsUnbalanced_RebuildsTree(int root, int[] keys, int candidate, double alpha) + foreach (var item in keys) { - var tree = new ScapegoatTree(root, alpha); + Assert.DoesNotThrow(() => tree.Insert(item)); + } - tree.TreeIsUnbalanced += FailTreeIsUnbalanced; + tree.TreeIsUnbalanced -= FailTreeIsUnbalanced; + tree.TreeIsUnbalanced += PassTreeIsUnbalanced; - foreach (var item in keys) - { - Assert.DoesNotThrow(() => tree.Insert(item)); - } + Assert.Throws(() => tree.Insert(candidate)); + } - tree.TreeIsUnbalanced -= FailTreeIsUnbalanced; - tree.TreeIsUnbalanced += PassTreeIsUnbalanced; + [Test] + [TestCase(20, new[]{10,30,5,11,29,40,50, 1, 12}, new[]{50,40,30,29}, 0.7)] + public void Delete_TreeIsUnbalanced_BalancesTree(int root, int[] keys, int[] candidates, double alpha) + { + var tree = new ScapegoatTree(root, alpha); - Assert.Throws(() => tree.Insert(candidate)); - } + tree.TreeIsUnbalanced += FailTreeIsUnbalanced; - [Test] - [TestCase(20, new[]{10,30,5,11,29,40,50, 1, 12}, new[]{50,40,30,29}, 0.7)] - public void Delete_TreeIsUnbalanced_BalancesTree(int root, int[] keys, int[] candidates, double alpha) + foreach (var item in keys) { - var tree = new ScapegoatTree(root, alpha); + Assert.DoesNotThrow(() => tree.Insert(item)); + } - tree.TreeIsUnbalanced += FailTreeIsUnbalanced; + tree.TreeIsUnbalanced -= FailTreeIsUnbalanced; + tree.TreeIsUnbalanced += PassTreeIsUnbalanced; - foreach (var item in keys) + Assert.Throws(() => + { + foreach (var item in candidates) { - Assert.DoesNotThrow(() => tree.Insert(item)); + tree.Delete(item); } + }); + } - tree.TreeIsUnbalanced -= FailTreeIsUnbalanced; - tree.TreeIsUnbalanced += PassTreeIsUnbalanced; + [Test] + [TestCase(20, new[]{10,30,5,11,29,40,50}, 10, 1)] + public void Delete_TreeIsUnbalanced_MaxSizeEqualsSize(int root, int[] keys, int candidate, double alpha) + { + var tree = new ScapegoatTree(root, alpha); - Assert.Throws(() => - { - foreach (var item in candidates) - { - tree.Delete(item); - } - }); - } + tree.TreeIsUnbalanced += FailTreeIsUnbalanced; - [Test] - [TestCase(20, new[]{10,30,5,11,29,40,50}, 10, 1)] - public void Delete_TreeIsUnbalanced_MaxSizeEqualsSize(int root, int[] keys, int candidate, double alpha) + foreach (var item in keys) { - var tree = new ScapegoatTree(root, alpha); + Assert.DoesNotThrow(() => tree.Insert(item)); + } - tree.TreeIsUnbalanced += FailTreeIsUnbalanced; + tree.TreeIsUnbalanced -= FailTreeIsUnbalanced; - foreach (var item in keys) - { - Assert.DoesNotThrow(() => tree.Insert(item)); - } + tree.Delete(candidate); - tree.TreeIsUnbalanced -= FailTreeIsUnbalanced; + Assert.AreEqual(tree.Size, tree.MaxSize); + } - tree.Delete(candidate); + [Test] + [TestCase(3, new[]{2,5,1,6}, -1, 0.5)] + [TestCase(3, new[]{2,5,1,6}, 7, 0.5)] + public void Insert_TreeIsUnbalanced_BalancesTree(int root, int[] keys, int candidate, double alpha) + { + var tree = new ScapegoatTree(root, alpha); - Assert.AreEqual(tree.Size, tree.MaxSize); - } + tree.TreeIsUnbalanced += FailTreeIsUnbalanced; - [Test] - [TestCase(3, new[]{2,5,1,6}, -1, 0.5)] - [TestCase(3, new[]{2,5,1,6}, 7, 0.5)] - public void Insert_TreeIsUnbalanced_BalancesTree(int root, int[] keys, int candidate, double alpha) + foreach (var item in keys) { - var tree = new ScapegoatTree(root, alpha); - - tree.TreeIsUnbalanced += FailTreeIsUnbalanced; - - foreach (var item in keys) - { - Assert.DoesNotThrow(() => tree.Insert(item)); - } + Assert.DoesNotThrow(() => tree.Insert(item)); + } - tree.TreeIsUnbalanced -= FailTreeIsUnbalanced; + tree.TreeIsUnbalanced -= FailTreeIsUnbalanced; - var inserted = tree.Insert(candidate); + var inserted = tree.Insert(candidate); - Assert.True(inserted); - Assert.True(tree.Size == 6); - Assert.True(tree.IsAlphaWeightBalanced()); - } + Assert.True(inserted); + Assert.True(tree.Size == 6); + Assert.True(tree.IsAlphaWeightBalanced()); + } - [TestCase(3, 5, 0.5)] - public void Insert_TreeIsUnbalanced_BalancesTree2(int root, int candidate, double alpha) - { - var tree = new ScapegoatTree(root, alpha); + [TestCase(3, 5, 0.5)] + public void Insert_TreeIsUnbalanced_BalancesTree2(int root, int candidate, double alpha) + { + var tree = new ScapegoatTree(root, alpha); - var inserted = tree.Insert(candidate); + var inserted = tree.Insert(candidate); - Assert.True(inserted); - Assert.True(tree.Size == 2); - Assert.True(tree.IsAlphaWeightBalanced()); - } + Assert.True(inserted); + Assert.True(tree.Size == 2); + Assert.True(tree.IsAlphaWeightBalanced()); + } - [Test] - public void Contains_RootIsNull_ReturnsFalse() - { - var tree = new ScapegoatTree(); + [Test] + public void Contains_RootIsNull_ReturnsFalse() + { + var tree = new ScapegoatTree(); - Assert.IsFalse(tree.Contains(1)); - } + Assert.IsFalse(tree.Contains(1)); + } - [Test] - public void Contains_RootHasKey_ReturnsTrue() - { - var tree = new ScapegoatTree(1); + [Test] + public void Contains_RootHasKey_ReturnsTrue() + { + var tree = new ScapegoatTree(1); - Assert.IsTrue(tree.Contains(1)); - } + Assert.IsTrue(tree.Contains(1)); + } - [Test] - public void Contains_TreeHasKey_ReturnsTrue() - { - var tree = new ScapegoatTree(1); + [Test] + public void Contains_TreeHasKey_ReturnsTrue() + { + var tree = new ScapegoatTree(1); - tree.Insert(2); + tree.Insert(2); - Assert.IsTrue(tree.Contains(2)); - } + Assert.IsTrue(tree.Contains(2)); + } - [Test] - public void Contains_TreeDoesNotContainKey_ReturnsFalse() - { - var tree = new ScapegoatTree(1); + [Test] + public void Contains_TreeDoesNotContainKey_ReturnsFalse() + { + var tree = new ScapegoatTree(1); - tree.Insert(2); + tree.Insert(2); - Assert.IsFalse(tree.Contains(-1)); - } + Assert.IsFalse(tree.Contains(-1)); + } - [Test] - public void Clear_TreeHasKeys_ClearsTree() - { - var tree = new ScapegoatTree(1); + [Test] + public void Clear_TreeHasKeys_ClearsTree() + { + var tree = new ScapegoatTree(1); - tree.Clear(); + tree.Clear(); - Assert.IsTrue(tree.Size == 0); - Assert.IsTrue(tree.MaxSize == 0); - Assert.IsNull(tree.Root); - } + Assert.IsTrue(tree.Size == 0); + Assert.IsTrue(tree.MaxSize == 0); + Assert.IsNull(tree.Root); + } - [Test] - public void Tune_AlphaIsValid_ChangesAlpha() - { - var expected = 0.7; + [Test] + public void Tune_AlphaIsValid_ChangesAlpha() + { + var expected = 0.7; - var tree = new ScapegoatTree(); + var tree = new ScapegoatTree(); - tree.Tune(expected); + tree.Tune(expected); - Assert.AreEqual(expected, tree.Alpha); - } + Assert.AreEqual(expected, tree.Alpha); + } - [Test] - public void Tune_AlphaIsNotValid_ThrowsException() - { - var expected = 9.9; + [Test] + public void Tune_AlphaIsNotValid_ThrowsException() + { + var expected = 9.9; - var tree = new ScapegoatTree(); + var tree = new ScapegoatTree(); - Assert.Throws(() => tree.Tune(expected)); - } + Assert.Throws(() => tree.Tune(expected)); + } - [Test] - public void FindScapegoatInPath_PathIsEmpty_ThrowsAnException() - { - var tree = new ScapegoatTree(); - Assert.Throws(() => tree.FindScapegoatInPath(new Stack>())); - } + [Test] + public void FindScapegoatInPath_PathIsEmpty_ThrowsAnException() + { + var tree = new ScapegoatTree(); + Assert.Throws(() => tree.FindScapegoatInPath(new Stack>())); + } - [Test] - public void FindScapegoatInPath_ScapegoatIsNotPresent_ThrowsAnException() - { - var tree = new ScapegoatTree(1, 1); - var path = new Stack>(); - path.Push(tree.Root!); - Assert.Throws(() => tree.FindScapegoatInPath(path)); - } + [Test] + public void FindScapegoatInPath_ScapegoatIsNotPresent_ThrowsAnException() + { + var tree = new ScapegoatTree(1, 1); + var path = new Stack>(); + path.Push(tree.Root!); + Assert.Throws(() => tree.FindScapegoatInPath(path)); + } - private static void FailTreeIsUnbalanced(object? sender, EventArgs? e) - { - Assert.Fail(); - } + private static void FailTreeIsUnbalanced(object? sender, EventArgs? e) + { + Assert.Fail(); + } - private static void PassTreeIsUnbalanced(object? sender, EventArgs? e) - { - Assert.Pass(); - } + private static void PassTreeIsUnbalanced(object? sender, EventArgs? e) + { + Assert.Pass(); } } diff --git a/DataStructures.Tests/SegmentTrees/SegmentTreeApplyTests.cs b/DataStructures.Tests/SegmentTrees/SegmentTreeApplyTests.cs index 9d53805d..675c3a11 100644 --- a/DataStructures.Tests/SegmentTrees/SegmentTreeApplyTests.cs +++ b/DataStructures.Tests/SegmentTrees/SegmentTreeApplyTests.cs @@ -1,20 +1,19 @@ using DataStructures.SegmentTrees; using NUnit.Framework; -namespace DataStructures.Tests.SegmentTrees +namespace DataStructures.Tests.SegmentTrees; + +[TestFixture] +public class SegmentTreeApplyTests { - [TestFixture] - public class SegmentTreeApplyTests - { - private readonly SegmentTreeApply testTree = new(new[] { 8, 9, 1, 4, 8, 7, 2 }); + private readonly SegmentTreeApply testTree = new(new[] { 8, 9, 1, 4, 8, 7, 2 }); - [Test] - public void Apply_Query_Update_Query_Test() - { - Assert.AreEqual(22, testTree.Query(1, 4)); - testTree.Apply(0, 3, 2); - Assert.AreEqual(new[] { 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, testTree.Operand); - Assert.AreEqual(36, testTree.Query(1, 4)); - } + [Test] + public void Apply_Query_Update_Query_Test() + { + Assert.AreEqual(22, testTree.Query(1, 4)); + testTree.Apply(0, 3, 2); + Assert.AreEqual(new[] { 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, testTree.Operand); + Assert.AreEqual(36, testTree.Query(1, 4)); } } diff --git a/DataStructures.Tests/SegmentTrees/SegmentTreeTests.cs b/DataStructures.Tests/SegmentTrees/SegmentTreeTests.cs index 24017919..07a57713 100644 --- a/DataStructures.Tests/SegmentTrees/SegmentTreeTests.cs +++ b/DataStructures.Tests/SegmentTrees/SegmentTreeTests.cs @@ -1,25 +1,24 @@ using DataStructures.SegmentTrees; using NUnit.Framework; -namespace DataStructures.Tests.SegmentTrees +namespace DataStructures.Tests.SegmentTrees; + +[TestFixture] +public class SegmentTreeTests { - [TestFixture] - public class SegmentTreeTests - { - private readonly SegmentTree testTree = new(new[] { 8, 9, 1, 4, 8, 7, 2 }); + private readonly SegmentTree testTree = new(new[] { 8, 9, 1, 4, 8, 7, 2 }); - [Test] - public void TreeArray_Test() - { - int[] expectedArray = { 0, 39, 22, 17, 17, 5, 15, 2, 8, 9, 1, 4, 8, 7, 2, 0 }; - Assert.AreEqual(expectedArray, testTree.Tree); - } + [Test] + public void TreeArray_Test() + { + int[] expectedArray = { 0, 39, 22, 17, 17, 5, 15, 2, 8, 9, 1, 4, 8, 7, 2, 0 }; + Assert.AreEqual(expectedArray, testTree.Tree); + } - [TestCase(1, 4, 22)] - [TestCase(2, 2, 1)] - public void Query_Test(int left, int right, int expectedValue) - { - Assert.AreEqual(expectedValue, testTree.Query(left, right)); - } + [TestCase(1, 4, 22)] + [TestCase(2, 2, 1)] + public void Query_Test(int left, int right, int expectedValue) + { + Assert.AreEqual(expectedValue, testTree.Query(left, right)); } } diff --git a/DataStructures.Tests/SegmentTrees/SegmentTreeUpdateTest.cs b/DataStructures.Tests/SegmentTrees/SegmentTreeUpdateTest.cs index 87e3ace4..8bf1dd6b 100644 --- a/DataStructures.Tests/SegmentTrees/SegmentTreeUpdateTest.cs +++ b/DataStructures.Tests/SegmentTrees/SegmentTreeUpdateTest.cs @@ -1,25 +1,24 @@ using DataStructures.SegmentTrees; using NUnit.Framework; -namespace DataStructures.Tests.SegmentTrees +namespace DataStructures.Tests.SegmentTrees; + +[TestFixture] +public class SegmentTreeUpdateTests { - [TestFixture] - public class SegmentTreeUpdateTests + [SetUp] + public void Init() { - [SetUp] - public void Init() - { - testTree = new SegmentTreeUpdate(new[] { 8, 9, 1, 4, 8, 7, 2 }); - } + testTree = new SegmentTreeUpdate(new[] { 8, 9, 1, 4, 8, 7, 2 }); + } - private SegmentTreeUpdate testTree = new(new[] { 8, 9, 1, 4, 8, 7, 2 }); + private SegmentTreeUpdate testTree = new(new[] { 8, 9, 1, 4, 8, 7, 2 }); - [TestCase(2, 3, 1, 4, 24)] - [TestCase(0, 3, 1, 4, 22)] - public void Update_Test(int node, int value, int left, int right, int aftQuery) - { - testTree.Update(node, value); - Assert.AreEqual(aftQuery, testTree.Query(left, right)); - } + [TestCase(2, 3, 1, 4, 24)] + [TestCase(0, 3, 1, 4, 22)] + public void Update_Test(int node, int value, int left, int right, int aftQuery) + { + testTree.Update(node, value); + Assert.AreEqual(aftQuery, testTree.Query(left, right)); } } diff --git a/DataStructures.Tests/SortedListTests.cs b/DataStructures.Tests/SortedListTests.cs index dff30d15..b3ca7f6e 100644 --- a/DataStructures.Tests/SortedListTests.cs +++ b/DataStructures.Tests/SortedListTests.cs @@ -2,125 +2,124 @@ using System.Linq; using NUnit.Framework; -namespace DataStructures.Tests +namespace DataStructures.Tests; + +[TestFixture] +public class SortedListTests { - [TestFixture] - public class SortedListTests + [Test] + public void Add_AddMultipleValues_SortingCorrectly( + [Random(1, 1000, 100, Distinct = true)] + int count) { - [Test] - public void Add_AddMultipleValues_SortingCorrectly( - [Random(1, 1000, 100, Distinct = true)] - int count) - { - var values = GetValues(count); - var list = new SortedList(); + var values = GetValues(count); + var list = new SortedList(); - foreach (var value in values) - { - list.Add(value); - } - - CollectionAssert.AreEqual(values.OrderBy(i => i), list); + foreach (var value in values) + { + list.Add(value); } - [Test] - public void Contains_PositiveArrayAdded_NegativeNumberAsked_FalseReturned( - [Random(1, 200, 10, Distinct = true)] int count) - { - var values = GetValues(count); - const int value = -1; + CollectionAssert.AreEqual(values.OrderBy(i => i), list); + } - var list = new SortedList(); + [Test] + public void Contains_PositiveArrayAdded_NegativeNumberAsked_FalseReturned( + [Random(1, 200, 10, Distinct = true)] int count) + { + var values = GetValues(count); + const int value = -1; - foreach (var i in values) - { - list.Add(i); - } + var list = new SortedList(); - Assert.IsFalse(list.Contains(value)); + foreach (var i in values) + { + list.Add(i); } - [Test] - public void Contains_PositiveArrayAdded_ContainingValueAsked_TrueReturned( - [Random(1, 200, 10, Distinct = true)] int count) - { - var values = GetValues(count); - var value = values[TestContext.CurrentContext.Random.Next(count - 1)]; + Assert.IsFalse(list.Contains(value)); + } - var list = new SortedList(); + [Test] + public void Contains_PositiveArrayAdded_ContainingValueAsked_TrueReturned( + [Random(1, 200, 10, Distinct = true)] int count) + { + var values = GetValues(count); + var value = values[TestContext.CurrentContext.Random.Next(count - 1)]; - foreach (var i in values) - { - list.Add(i); - } + var list = new SortedList(); - Assert.IsTrue(list.Contains(value)); + foreach (var i in values) + { + list.Add(i); } + Assert.IsTrue(list.Contains(value)); + } - [Test] - public void Remove_PositiveArrayAdded_NegativeNumberAsked_FalseReturned( - [Random(1, 200, 10, Distinct = true)] int count) - { - var values = GetValues(count); - const int value = -1; - - var list = new SortedList(); - foreach (var i in values) - { - list.Add(i); - } + [Test] + public void Remove_PositiveArrayAdded_NegativeNumberAsked_FalseReturned( + [Random(1, 200, 10, Distinct = true)] int count) + { + var values = GetValues(count); + const int value = -1; - Assert.IsFalse(list.TryRemove(value)); - } + var list = new SortedList(); - [Test] - public void Remove_PositiveArrayAdded_ContainingValueAsked_TrueReturned( - [Random(1, 200, 10, Distinct = true)] int count) + foreach (var i in values) { - var values = GetValues(count); - var value = values[TestContext.CurrentContext.Random.Next(count - 1)]; - - var list = new SortedList(); + list.Add(i); + } - foreach (var i in values) - { - list.Add(i); - } + Assert.IsFalse(list.TryRemove(value)); + } - var expectingValues = values - .OrderBy(i => i) - .ToList(); + [Test] + public void Remove_PositiveArrayAdded_ContainingValueAsked_TrueReturned( + [Random(1, 200, 10, Distinct = true)] int count) + { + var values = GetValues(count); + var value = values[TestContext.CurrentContext.Random.Next(count - 1)]; - expectingValues.Remove(value); + var list = new SortedList(); - Assert.IsTrue(list.TryRemove(value)); - CollectionAssert.AreEqual(expectingValues, list); + foreach (var i in values) + { + list.Add(i); } - [Test] - public void Clear_ArrayAdded_ListCleaned_ListIsEmpty( - [Random(1, 20, 1, Distinct = true)] int count) - { - var values = GetValues(count); + var expectingValues = values + .OrderBy(i => i) + .ToList(); + + expectingValues.Remove(value); - var list = new SortedList(); + Assert.IsTrue(list.TryRemove(value)); + CollectionAssert.AreEqual(expectingValues, list); + } - foreach (var i in values) - { - list.Add(i); - } + [Test] + public void Clear_ArrayAdded_ListCleaned_ListIsEmpty( + [Random(1, 20, 1, Distinct = true)] int count) + { + var values = GetValues(count); - list.Clear(); + var list = new SortedList(); - CollectionAssert.IsEmpty(list); + foreach (var i in values) + { + list.Add(i); } - private static List GetValues(int count) - => Enumerable - .Range(0, count) - .Select(_ => TestContext.CurrentContext.Random.Next(1_000_000)) - .ToList(); + list.Clear(); + + CollectionAssert.IsEmpty(list); } + + private static List GetValues(int count) + => Enumerable + .Range(0, count) + .Select(_ => TestContext.CurrentContext.Random.Next(1_000_000)) + .ToList(); } diff --git a/DataStructures.Tests/Stack/ArrayBasedStackTests.cs b/DataStructures.Tests/Stack/ArrayBasedStackTests.cs index f0e9ce51..cfab5d5a 100644 --- a/DataStructures.Tests/Stack/ArrayBasedStackTests.cs +++ b/DataStructures.Tests/Stack/ArrayBasedStackTests.cs @@ -7,128 +7,127 @@ using System; using System.Linq; -namespace DataStructures.Tests.Stack +namespace DataStructures.Tests.Stack; + +public static class ArrayBasedStackTests { - public static class ArrayBasedStackTests - { - private const string StackEmptyErrorMessage = "Stack is empty"; + private const string StackEmptyErrorMessage = "Stack is empty"; - [Test] - public static void CountTest() - { - var stack = new ArrayBasedStack(new[] { 0, 1, 2, 3, 4 }); - stack.Top.Should().Be(4); - } + [Test] + public static void CountTest() + { + var stack = new ArrayBasedStack(new[] { 0, 1, 2, 3, 4 }); + stack.Top.Should().Be(4); + } - [Test] - public static void ClearTest() - { - var stack = new ArrayBasedStack(new[] { 0, 1, 2, 3, 4 }); + [Test] + public static void ClearTest() + { + var stack = new ArrayBasedStack(new[] { 0, 1, 2, 3, 4 }); - stack.Clear(); + stack.Clear(); - stack.Top.Should().Be(-1); - } + stack.Top.Should().Be(-1); + } - [Test] - public static void ContainsTest() - { - var stack = new ArrayBasedStack(new[] { 0, 1, 2, 3, 4 }); - - Assert.Multiple(() => - { - stack.Contains(0).Should().BeTrue(); - stack.Contains(1).Should().BeTrue(); - stack.Contains(2).Should().BeTrue(); - stack.Contains(3).Should().BeTrue(); - stack.Contains(4).Should().BeTrue(); - }); - } - - [Test] - public static void PeekTest() - { - var stack = new ArrayBasedStack(new[] { 0, 1, 2, 3, 4 }); - - Assert.Multiple(() => - { - stack.Peek().Should().Be(4); - stack.Peek().Should().Be(4); - stack.Peek().Should().Be(4); - }); - } - - [Test] - public static void PopTest() - { - var stack = new ArrayBasedStack(new[] { 0, 1, 2, 3, 4 }); - - Assert.Multiple(() => - { - stack.Pop().Should().Be(4); - stack.Pop().Should().Be(3); - stack.Pop().Should().Be(2); - stack.Pop().Should().Be(1); - stack.Pop().Should().Be(0); - }); - } - - [Test] - public static void PushTest() + [Test] + public static void ContainsTest() + { + var stack = new ArrayBasedStack(new[] { 0, 1, 2, 3, 4 }); + + Assert.Multiple(() => + { + stack.Contains(0).Should().BeTrue(); + stack.Contains(1).Should().BeTrue(); + stack.Contains(2).Should().BeTrue(); + stack.Contains(3).Should().BeTrue(); + stack.Contains(4).Should().BeTrue(); + }); + } + + [Test] + public static void PeekTest() + { + var stack = new ArrayBasedStack(new[] { 0, 1, 2, 3, 4 }); + + Assert.Multiple(() => { - var stack = new ArrayBasedStack(); - - Assert.Multiple(() => - Enumerable.Range(0, 5) - .ToList() - .ForEach(number => - { - stack.Push(number); - stack.Peek().Should().Be(number); - })); - } - - [Test] - public static void AutomaticResizesTest() + stack.Peek().Should().Be(4); + stack.Peek().Should().Be(4); + stack.Peek().Should().Be(4); + }); + } + + [Test] + public static void PopTest() + { + var stack = new ArrayBasedStack(new[] { 0, 1, 2, 3, 4 }); + + Assert.Multiple(() => { - const int initialCapacity = 2; - var stack = new ArrayBasedStack - { - Capacity = initialCapacity, - }; - - stack.Push(0); - stack.Push(1); - stack.Push(2); - stack.Push(3); - stack.Push(4); - - stack.Capacity.Should().BeGreaterThan(initialCapacity); - } - - [Test] - public static void ShouldThrowStackEmptyExceptionOnEmptyPopTest() + stack.Pop().Should().Be(4); + stack.Pop().Should().Be(3); + stack.Pop().Should().Be(2); + stack.Pop().Should().Be(1); + stack.Pop().Should().Be(0); + }); + } + + [Test] + public static void PushTest() + { + var stack = new ArrayBasedStack(); + + Assert.Multiple(() => + Enumerable.Range(0, 5) + .ToList() + .ForEach(number => + { + stack.Push(number); + stack.Peek().Should().Be(number); + })); + } + + [Test] + public static void AutomaticResizesTest() + { + const int initialCapacity = 2; + var stack = new ArrayBasedStack { - var stack = new ArrayBasedStack(); + Capacity = initialCapacity, + }; - Action poppingAnEmptyStack = () => stack.Pop(); + stack.Push(0); + stack.Push(1); + stack.Push(2); + stack.Push(3); + stack.Push(4); - poppingAnEmptyStack.Should() - .Throw() - .WithMessage(StackEmptyErrorMessage); + stack.Capacity.Should().BeGreaterThan(initialCapacity); + } + + [Test] + public static void ShouldThrowStackEmptyExceptionOnEmptyPopTest() + { + var stack = new ArrayBasedStack(); - } + Action poppingAnEmptyStack = () => stack.Pop(); - [Test] - public static void ShouldThrowStackEmptyExceptionOnEmptyPeekTest() - { - var stack = new ArrayBasedStack(); + poppingAnEmptyStack.Should() + .Throw() + .WithMessage(StackEmptyErrorMessage); + + } + + [Test] + public static void ShouldThrowStackEmptyExceptionOnEmptyPeekTest() + { + var stack = new ArrayBasedStack(); - Action peekingAnEmptyStack = () => stack.Peek(); + Action peekingAnEmptyStack = () => stack.Peek(); - peekingAnEmptyStack.Should() - .Throw() - .WithMessage(StackEmptyErrorMessage); - } + peekingAnEmptyStack.Should() + .Throw() + .WithMessage(StackEmptyErrorMessage); } } diff --git a/DataStructures.Tests/Stack/ListBasedStackTests.cs b/DataStructures.Tests/Stack/ListBasedStackTests.cs index 229e6bf4..9cdb30fa 100644 --- a/DataStructures.Tests/Stack/ListBasedStackTests.cs +++ b/DataStructures.Tests/Stack/ListBasedStackTests.cs @@ -6,81 +6,80 @@ using System.Linq; -namespace DataStructures.Tests.Stack +namespace DataStructures.Tests.Stack; + +public static class ListBasedStackTests { - public static class ListBasedStackTests + [Test] + public static void CountTest() { - [Test] - public static void CountTest() - { - var stack = new ListBasedStack(new[] { 0, 1, 2, 3, 4 }); - stack.Count.Should().Be(5); - } - - [Test] - public static void ClearTest() - { - var stack = new ListBasedStack(new[] { 0, 1, 2, 3, 4 }); - stack.Clear(); - stack.Count.Should().Be(0); - } + var stack = new ListBasedStack(new[] { 0, 1, 2, 3, 4 }); + stack.Count.Should().Be(5); + } - [Test] - public static void ContainsTest() - { - var stack = new ListBasedStack(new[] { 0, 1, 2, 3, 4 }); + [Test] + public static void ClearTest() + { + var stack = new ListBasedStack(new[] { 0, 1, 2, 3, 4 }); + stack.Clear(); + stack.Count.Should().Be(0); + } - Assert.Multiple(() => - { - stack.Contains(0).Should().BeTrue(); - stack.Contains(1).Should().BeTrue(); - stack.Contains(2).Should().BeTrue(); - stack.Contains(3).Should().BeTrue(); - stack.Contains(4).Should().BeTrue(); - }); - } + [Test] + public static void ContainsTest() + { + var stack = new ListBasedStack(new[] { 0, 1, 2, 3, 4 }); - [Test] - public static void PeekTest() + Assert.Multiple(() => { - var stack = new ListBasedStack(new[] { 0, 1, 2, 3, 4 }); + stack.Contains(0).Should().BeTrue(); + stack.Contains(1).Should().BeTrue(); + stack.Contains(2).Should().BeTrue(); + stack.Contains(3).Should().BeTrue(); + stack.Contains(4).Should().BeTrue(); + }); + } - Assert.Multiple(() => - { - stack.Peek().Should().Be(4); - stack.Peek().Should().Be(4); - stack.Peek().Should().Be(4); - }); - } + [Test] + public static void PeekTest() + { + var stack = new ListBasedStack(new[] { 0, 1, 2, 3, 4 }); - [Test] - public static void PopTest() + Assert.Multiple(() => { - var stack = new ListBasedStack(new[] { 0, 1, 2, 3, 4 }); + stack.Peek().Should().Be(4); + stack.Peek().Should().Be(4); + stack.Peek().Should().Be(4); + }); + } - Assert.Multiple(() => - { - stack.Pop().Should().Be(4); - stack.Pop().Should().Be(3); - stack.Pop().Should().Be(2); - stack.Pop().Should().Be(1); - stack.Pop().Should().Be(0); - }); - } + [Test] + public static void PopTest() + { + var stack = new ListBasedStack(new[] { 0, 1, 2, 3, 4 }); - [Test] - public static void PushTest() + Assert.Multiple(() => { - var stack = new ListBasedStack(); + stack.Pop().Should().Be(4); + stack.Pop().Should().Be(3); + stack.Pop().Should().Be(2); + stack.Pop().Should().Be(1); + stack.Pop().Should().Be(0); + }); + } + + [Test] + public static void PushTest() + { + var stack = new ListBasedStack(); - Assert.Multiple(() => - Enumerable.Range(0, 5) - .ToList() - .ForEach(number => - { - stack.Push(number); - stack.Peek().Should().Be(number); - })); - } + Assert.Multiple(() => + Enumerable.Range(0, 5) + .ToList() + .ForEach(number => + { + stack.Push(number); + stack.Peek().Should().Be(number); + })); } } diff --git a/DataStructures.Tests/Stack/QueueBasedStackTests.cs b/DataStructures.Tests/Stack/QueueBasedStackTests.cs index 69f67621..a95c451c 100644 --- a/DataStructures.Tests/Stack/QueueBasedStackTests.cs +++ b/DataStructures.Tests/Stack/QueueBasedStackTests.cs @@ -1,127 +1,123 @@ using DataStructures.Stack; using NUnit.Framework; using System; -using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; -namespace DataStructures.Tests.Stack +namespace DataStructures.Tests.Stack; + +public static class QueueBasedStackTests { - public static class QueueBasedStackTests + [Test] + public static void PopWorksCorrectly() { - [Test] - public static void PopWorksCorrectly() + //Arrange + QueueBasedStack s = new QueueBasedStack(); + s.Push('A'); + s.Push('B'); + s.Push('C'); + var result = new StringBuilder(); + + //Act + for (int i = 0; i < 3; i++) { - //Arrange - QueueBasedStack s = new QueueBasedStack(); - s.Push('A'); - s.Push('B'); - s.Push('C'); - var result = new StringBuilder(); - - //Act - for (int i = 0; i < 3; i++) - { - result.Append(s.Pop()); - } - - - //Assert - Assert.That("CBA", Is.EqualTo(result.ToString())); - Assert.IsTrue(s.IsEmpty(), "Stack is Empty"); + result.Append(s.Pop()); } - [Test] - public static void PeekWorksCorrectly() + + + //Assert + Assert.That("CBA", Is.EqualTo(result.ToString())); + Assert.IsTrue(s.IsEmpty(), "Stack is Empty"); + } + [Test] + public static void PeekWorksCorrectly() + { + //Arrange + QueueBasedStack s = new QueueBasedStack(); + s.Push(1); + s.Push(2); + s.Push(3); + var peeked = 0; + + //Act + for (int i = 0; i < 3; i++) { - //Arrange - QueueBasedStack s = new QueueBasedStack(); - s.Push(1); - s.Push(2); - s.Push(3); - var peeked = 0; - - //Act - for (int i = 0; i < 3; i++) - { - peeked = s.Peek(); - } - - - //Assert - Assert.That(3, Is.EqualTo(peeked)); - Assert.IsFalse(s.IsEmpty(), "Stack is Empty"); + peeked = s.Peek(); } - [Test] - public static void PopEmptyStackThrowsInvalidOperationException() + + + //Assert + Assert.That(3, Is.EqualTo(peeked)); + Assert.IsFalse(s.IsEmpty(), "Stack is Empty"); + } + [Test] + public static void PopEmptyStackThrowsInvalidOperationException() + { + //Arrange + var s = new QueueBasedStack(); + Exception? exception = null; + + //Act + try { - //Arrange - var s = new QueueBasedStack(); - Exception? exception = null; - - //Act - try - { - s.Pop(); - } - catch (Exception ex) - { - exception = ex; - } - - //Assert - Assert.That(exception?.GetType(), Is.EqualTo(typeof(InvalidOperationException))); + s.Pop(); } - [Test] - public static void PeekEmptyStackThrowsInvalidOperationException() + catch (Exception ex) { - //Arrange - var s = new QueueBasedStack(); - Exception? exception = null; - - //Act - try - { - s.Peek(); - } - catch (Exception ex) - { - exception = ex; - } - - //Assert - Assert.That(exception?.GetType(), Is.EqualTo(typeof(InvalidOperationException))); + exception = ex; } - [Test] - public static void ClearWorksCorrectly() - { - // Arrange - var s = new QueueBasedStack(); - s.Push(1); - s.Push(2); - - // Act - s.Clear(); - // Assert - Assert.IsTrue(s.IsEmpty(), "Queue is empty"); + //Assert + Assert.That(exception?.GetType(), Is.EqualTo(typeof(InvalidOperationException))); + } + [Test] + public static void PeekEmptyStackThrowsInvalidOperationException() + { + //Arrange + var s = new QueueBasedStack(); + Exception? exception = null; + //Act + try + { + s.Peek(); } - [Test] - public static void LengthWorksCorrectly() + catch (Exception ex) { - // Arrange - var s = new QueueBasedStack(); - s.Push(1); - s.Push(2); - var length = 0; + exception = ex; + } - // Act - length = s.Length(); + //Assert + Assert.That(exception?.GetType(), Is.EqualTo(typeof(InvalidOperationException))); + } + [Test] + public static void ClearWorksCorrectly() + { + // Arrange + var s = new QueueBasedStack(); + s.Push(1); + s.Push(2); - // Assert - Assert.That(2, Is.EqualTo(length)); + // Act + s.Clear(); + + // Assert + Assert.IsTrue(s.IsEmpty(), "Queue is empty"); + + } + [Test] + public static void LengthWorksCorrectly() + { + // Arrange + var s = new QueueBasedStack(); + s.Push(1); + s.Push(2); + var length = 0; + + // Act + length = s.Length(); + + // Assert + Assert.That(2, Is.EqualTo(length)); - } } } diff --git a/DataStructures.Tests/TimelineTests.cs b/DataStructures.Tests/TimelineTests.cs index 9f76371e..be948c1c 100644 --- a/DataStructures.Tests/TimelineTests.cs +++ b/DataStructures.Tests/TimelineTests.cs @@ -5,667 +5,719 @@ using FluentAssertions.Execution; using NUnit.Framework; -namespace DataStructures.Tests +namespace DataStructures.Tests; + +public static class TimelineTests { - public static class TimelineTests + [Test] + public static void CountTest() { - [Test] - public static void CountTest() - { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - timeline.Count - .Should() - .Be(5); - } - - [Test] - public static void TimesCountTest() + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - timeline.TimesCount - .Should() - .Be(timeline.GetAllTimes().Length); - } + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline.Count + .Should() + .Be(5); + } - [Test] - public static void ValuesCountTest() + [Test] + public static void TimesCountTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - timeline.ValuesCount - .Should() - .Be(timeline.GetAllValues().Length); - } + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline.TimesCount + .Should() + .Be(timeline.GetAllTimes().Length); + } - [Test] - public static void IndexerGetTest() + [Test] + public static void ValuesCountTest() + { + var timeline = new Timeline { - const string eventName = "TestTime2"; - var eventDate = new DateTime(2000, 1, 1); - - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { eventDate, eventName }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline.ValuesCount + .Should() + .Be(timeline.GetAllValues().Length); + } - timeline[eventDate][0] - .Should() - .Be(eventName); - } + [Test] + public static void IndexerGetTest() + { + const string eventName = "TestTime2"; + var eventDate = new DateTime(2000, 1, 1); - [Test] - public static void IndexerSetTest() + var timeline = new Timeline { - var eventDate = new DateTime(2000, 1, 1); + { new DateTime(1995, 1, 1), "TestTime1" }, + { eventDate, eventName }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline[eventDate][0] + .Should() + .Be(eventName); + } - const string formerEventName = "TestTime2"; - const string eventName = "TestTime2Modified"; + [Test] + public static void IndexerSetTest() + { + var eventDate = new DateTime(2000, 1, 1); - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { eventDate, formerEventName }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + const string formerEventName = "TestTime2"; + const string eventName = "TestTime2Modified"; - timeline[new DateTime(2000, 1, 1)] = new[] { eventName }; + var timeline = new Timeline + { + { new DateTime(1995, 1, 1), "TestTime1" }, + { eventDate, formerEventName }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline[new DateTime(2000, 1, 1)] = new[] { eventName }; + + timeline[new DateTime(2000, 1, 1)][0] + .Should() + .Be(eventName); + } - timeline[new DateTime(2000, 1, 1)][0] - .Should() - .Be(eventName); - } + [Test] + public static void EqualsTest() + { + var timeline1 = new Timeline + { + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + var timeline2 = new Timeline + { + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + (timeline1 == timeline2) + .Should() + .BeTrue(); + } - [Test] - public static void EqualsTest() + [Test] + public static void ClearTest() + { + var timeline = new Timeline { - var timeline1 = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - var timeline2 = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - (timeline1 == timeline2) - .Should() - .BeTrue(); - } + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline.Clear(); + + timeline.Count + .Should() + .Be(0); + } - [Test] - public static void ClearTest() + [Test] + public static void CopyToTest() + { + var timeline = new Timeline { - var timeline = new Timeline + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + var array = new (DateTime Time, string Value)[timeline.Count]; + timeline.CopyTo(array, 0); + + timeline.Count + .Should() + .Be(array.Length); + + var i = 0; + using (new AssertionScope()) + { + foreach (var (time, value) in timeline) { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + array[i].Time + .Should() + .Be(time); - timeline.Clear(); + array[i].Value + .Should() + .Be(value); - timeline.Count - .Should() - .Be(0); + ++i; + } } + } - [Test] - public static void CopyToTest() + [Test] + public static void GetAllTimesTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; - var array = new (DateTime Time, string Value)[timeline.Count]; - timeline.CopyTo(array, 0); + var times = timeline.GetAllTimes(); - timeline.Count - .Should() - .Be(array.Length); - - var i = 0; - using (new AssertionScope()) + var i = 0; + using (new AssertionScope()) + { + foreach (var (time, _) in timeline) { - foreach (var (time, value) in timeline) - { - array[i].Time - .Should() - .Be(time); - - array[i].Value - .Should() - .Be(value); - - ++i; - } + times[i++] + .Should() + .Be(time); } } + } + + [Test] + public static void GetTimesByValueTest() + { + var eventDate = new DateTime(2000, 1, 1); + const string eventName = "TestTime2"; - [Test] - public static void GetAllTimesTest() + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + { new DateTime(1995, 1, 1), "TestTime1" }, + { eventDate, eventName }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline.GetTimesByValue(eventName)[0] + .Should() + .Be(eventDate); + } - var times = timeline.GetAllTimes(); + [Test] + public static void GetTimesBeforeTest() + { + var timeline = new Timeline + { + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; - var i = 0; - using (new AssertionScope()) - { - foreach (var (time, _) in timeline) - { - times[i++] - .Should() - .Be(time); - } - } - } + var times = timeline.GetTimesBefore(new DateTime(2003, 1, 1)); - [Test] - public static void GetTimesByValueTest() + using (new AssertionScope()) { - var eventDate = new DateTime(2000, 1, 1); - const string eventName = "TestTime2"; + times.Length + .Should() + .Be(2); - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { eventDate, eventName }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - timeline.GetTimesByValue(eventName)[0] + times[0] + .Should() + .Be(new DateTime(1995, 1, 1)); + + times[1] .Should() - .Be(eventDate); + .Be(new DateTime(2000, 1, 1)); } + } - [Test] - public static void GetTimesBeforeTest() + [Test] + public static void GetTimesAfterTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; - var times = timeline.GetTimesBefore(new DateTime(2003, 1, 1)); + var times = timeline.GetTimesAfter(new DateTime(2003, 1, 1)); - using (new AssertionScope()) - { - times.Length - .Should() - .Be(2); + using (new AssertionScope()) + { + times.Length + .Should() + .Be(3); - times[0] - .Should() - .Be(new DateTime(1995, 1, 1)); + times[0] + .Should() + .Be(new DateTime(2005, 1, 1)); - times[1] - .Should() - .Be(new DateTime(2000, 1, 1)); - } + times[1] + .Should() + .Be(new DateTime(2010, 1, 1)); + + times[2] + .Should() + .Be(new DateTime(2015, 1, 1)); } + } - [Test] - public static void GetTimesAfterTest() + [Test] + public static void GetAllValuesTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; - var times = timeline.GetTimesAfter(new DateTime(2003, 1, 1)); + var values = timeline.GetAllValues(); - using (new AssertionScope()) + var i = 0; + using (new AssertionScope()) + { + foreach (var (_, value) in timeline) { - times.Length + values[i++] .Should() - .Be(3); - - times[0] - .Should() - .Be(new DateTime(2005, 1, 1)); - - times[1] - .Should() - .Be(new DateTime(2010, 1, 1)); - - times[2] - .Should() - .Be(new DateTime(2015, 1, 1)); + .Be(value); } } + } - [Test] - public static void GetAllValuesTest() + [Test] + public static void GetValuesByTimeTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline.GetValuesByTime(new DateTime(2000, 1, 1))[0] + .Should() + .Be("TestTime2"); + } - var values = timeline.GetAllValues(); + [Test] + public static void GetValuesBeforeTest() + { + var timeline = new Timeline + { + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; - var i = 0; - using (new AssertionScope()) - { - foreach (var (_, value) in timeline) - { - values[i++] - .Should() - .Be(value); - } - } - } + var array = timeline.GetValuesBefore(new DateTime(2003, 1, 1)).ToArray(); - [Test] - public static void GetValuesByTimeTest() + using (new AssertionScope()) { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - timeline.GetValuesByTime(new DateTime(2000, 1, 1))[0] + array.Length + .Should() + .Be(2); + + array[0].Time .Should() - .Be("TestTime2"); + .Be(new DateTime(1995, 1, 1)); + + array[1].Time + .Should() + .Be(new DateTime(2000, 1, 1)); } + } - [Test] - public static void GetValuesBeforeTest() + [Test] + public static void GetValuesAfterTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; - var array = timeline.GetValuesBefore(new DateTime(2003, 1, 1)).ToArray(); + var array = timeline.GetValuesAfter(new DateTime(2003, 1, 1)).ToArray(); - using (new AssertionScope()) - { - array.Length - .Should() - .Be(2); + using (new AssertionScope()) + { + array.Length + .Should() + .Be(3); - array[0].Time - .Should() - .Be(new DateTime(1995, 1, 1)); + array[0].Time + .Should() + .Be(new DateTime(2005, 1, 1)); - array[1].Time - .Should() - .Be(new DateTime(2000, 1, 1)); - } + array[1].Time + .Should() + .Be(new DateTime(2010, 1, 1)); + + array[2].Time + .Should() + .Be(new DateTime(2015, 1, 1)); } + } - [Test] - public static void GetValuesAfterTest() + [Test] + public static void GetValuesByMillisecondTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - var array = timeline.GetValuesAfter(new DateTime(2003, 1, 1)).ToArray(); + { new DateTime(1985, 1, 1, 10, 0, 0, 250), "TestTime1" }, + { new DateTime(1990, 1, 1, 10, 0, 0, 250), "TestTime2" }, + { new DateTime(1995, 1, 1, 10, 0, 0, 250), "TestTime3" }, + { new DateTime(2005, 1, 1, 10, 0, 0, 750), "TestTime4" }, + { new DateTime(2015, 1, 1, 10, 0, 0, 750), "TestTime5" }, + }; + + var query = timeline.GetValuesByMillisecond(750); + + query.Count + .Should() + .Be(2); + } - using (new AssertionScope()) - { - array.Length - .Should() - .Be(3); + [Test] + public static void GetValuesBySecondTest() + { + var timeline = new Timeline + { + { new DateTime(1985, 1, 1, 10, 0, 5), "TestTime1" }, + { new DateTime(1990, 1, 1, 10, 0, 5), "TestTime2" }, + { new DateTime(1995, 1, 1, 10, 0, 5), "TestTime3" }, + { new DateTime(2005, 1, 1, 10, 0, 20), "TestTime4" }, + { new DateTime(2015, 1, 1, 10, 0, 20), "TestTime5" }, + }; - array[0].Time - .Should() - .Be(new DateTime(2005, 1, 1)); + var query = timeline.GetValuesBySecond(20); - array[1].Time - .Should() - .Be(new DateTime(2010, 1, 1)); + using (new AssertionScope()) + { + query.Count + .Should() + .Be(2); - array[2].Time - .Should() - .Be(new DateTime(2015, 1, 1)); - } + timeline + .Should() + .Contain(query); } + } - [Test] - public static void GetValuesByMillisecondTest() + [Test] + public static void GetValuesByMinuteTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1985, 1, 1, 10, 0, 0, 250), "TestTime1" }, - { new DateTime(1990, 1, 1, 10, 0, 0, 250), "TestTime2" }, - { new DateTime(1995, 1, 1, 10, 0, 0, 250), "TestTime3" }, - { new DateTime(2005, 1, 1, 10, 0, 0, 750), "TestTime4" }, - { new DateTime(2015, 1, 1, 10, 0, 0, 750), "TestTime5" }, - }; + { new DateTime(1985, 1, 1, 10, 15, 0), "TestTime1" }, + { new DateTime(1990, 1, 1, 10, 15, 0), "TestTime2" }, + { new DateTime(1995, 1, 1, 10, 15, 0), "TestTime3" }, + { new DateTime(2005, 1, 1, 10, 40, 0), "TestTime4" }, + { new DateTime(2015, 1, 1, 10, 40, 0), "TestTime5" }, + }; - var query = timeline.GetValuesByMillisecond(750); + var query = timeline.GetValuesByMinute(40); + using (new AssertionScope()) + { query.Count .Should() .Be(2); + + timeline + .Should() + .Contain(query); } + } - [Test] - public static void GetValuesBySecondTest() + [Test] + public static void GetValuesByHourTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1985, 1, 1, 10, 0, 5), "TestTime1" }, - { new DateTime(1990, 1, 1, 10, 0, 5), "TestTime2" }, - { new DateTime(1995, 1, 1, 10, 0, 5), "TestTime3" }, - { new DateTime(2005, 1, 1, 10, 0, 20), "TestTime4" }, - { new DateTime(2015, 1, 1, 10, 0, 20), "TestTime5" }, - }; + { new DateTime(1985, 1, 1, 7, 0, 0), "TestTime1" }, + { new DateTime(1990, 1, 1, 7, 0, 0), "TestTime2" }, + { new DateTime(1995, 1, 1, 7, 0, 0), "TestTime3" }, + { new DateTime(2005, 1, 1, 16, 0, 0), "TestTime4" }, + { new DateTime(2015, 1, 1, 16, 0, 0), "TestTime5" }, + }; - var query = timeline.GetValuesBySecond(20); + var query = timeline.GetValuesByHour(16); - using (new AssertionScope()) - { - query.Count - .Should() - .Be(2); + using (new AssertionScope()) + { + query.Count + .Should() + .Be(2); - timeline - .Should() - .Contain(query); - } + timeline + .Should() + .Contain(query); } + } - [Test] - public static void GetValuesByMinuteTest() + [Test] + public static void GetValuesByDayTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1985, 1, 1, 10, 15, 0), "TestTime1" }, - { new DateTime(1990, 1, 1, 10, 15, 0), "TestTime2" }, - { new DateTime(1995, 1, 1, 10, 15, 0), "TestTime3" }, - { new DateTime(2005, 1, 1, 10, 40, 0), "TestTime4" }, - { new DateTime(2015, 1, 1, 10, 40, 0), "TestTime5" }, - }; + { new DateTime(1985, 1, 10), "TestTime1" }, + { new DateTime(1990, 1, 10), "TestTime2" }, + { new DateTime(1995, 1, 10), "TestTime3" }, + { new DateTime(2005, 1, 20), "TestTime4" }, + { new DateTime(2015, 1, 20), "TestTime5" }, + }; - var query = timeline.GetValuesByMinute(40); + var query = timeline.GetValuesByDay(20); - using (new AssertionScope()) - { - query.Count - .Should() - .Be(2); + using (new AssertionScope()) + { + query.Count + .Should() + .Be(2); - timeline - .Should() - .Contain(query); - } + timeline + .Should() + .Contain(query); } + } - [Test] - public static void GetValuesByHourTest() + [Test] + public static void GetValuesByTimeOfDayTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1985, 1, 1, 7, 0, 0), "TestTime1" }, - { new DateTime(1990, 1, 1, 7, 0, 0), "TestTime2" }, - { new DateTime(1995, 1, 1, 7, 0, 0), "TestTime3" }, - { new DateTime(2005, 1, 1, 16, 0, 0), "TestTime4" }, - { new DateTime(2015, 1, 1, 16, 0, 0), "TestTime5" }, - }; + { new DateTime(1985, 1, 1, 10, 30, 15, 500), "TestTime1" }, + { new DateTime(1990, 1, 1, 10, 30, 15, 500), "TestTime2" }, + { new DateTime(1995, 1, 1, 10, 30, 15, 500), "TestTime3" }, + { new DateTime(2005, 1, 1, 21, 15, 40, 600), "TestTime4" }, + { new DateTime(2015, 1, 1, 21, 15, 40, 600), "TestTime5" }, + }; - var query = timeline.GetValuesByHour(16); + var query = timeline.GetValuesByTimeOfDay(new TimeSpan(0, 21, 15, 40, 600)); - using (new AssertionScope()) - { - query.Count - .Should() - .Be(2); + using (new AssertionScope()) + { + query.Count + .Should() + .Be(2); - timeline - .Should() - .Contain(query); - } + timeline + .Should() + .Contain(query); } + } - [Test] - public static void GetValuesByDayTest() + [Test] + public static void GetValuesByDayOfWeekTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1985, 1, 10), "TestTime1" }, - { new DateTime(1990, 1, 10), "TestTime2" }, - { new DateTime(1995, 1, 10), "TestTime3" }, - { new DateTime(2005, 1, 20), "TestTime4" }, - { new DateTime(2015, 1, 20), "TestTime5" }, - }; + { new DateTime(2015, 1, 5), "TestTime1" }, //Monday + { new DateTime(2015, 2, 2), "TestTime2" }, //Monday + { new DateTime(2015, 1, 6), "TestTime3" }, //Tuesday + { new DateTime(2015, 1, 7), "TestTime4" }, //Wednesday + { new DateTime(2015, 1, 8), "TestTime5" }, //Thursday + }; - var query = timeline.GetValuesByDay(20); + var query = timeline.GetValuesByDayOfWeek(DayOfWeek.Monday); - using (new AssertionScope()) - { - query.Count - .Should() - .Be(2); + using (new AssertionScope()) + { + query.Count + .Should() + .Be(2); - timeline - .Should() - .Contain(query); - } + timeline + .Should() + .Contain(query); } + } - [Test] - public static void GetValuesByTimeOfDayTest() + [Test] + public static void GetValuesByDayOfYearTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1985, 1, 1, 10, 30, 15, 500), "TestTime1" }, - { new DateTime(1990, 1, 1, 10, 30, 15, 500), "TestTime2" }, - { new DateTime(1995, 1, 1, 10, 30, 15, 500), "TestTime3" }, - { new DateTime(2005, 1, 1, 21, 15, 40, 600), "TestTime4" }, - { new DateTime(2015, 1, 1, 21, 15, 40, 600), "TestTime5" }, - }; + { new DateTime(1985, 1, 3), "TestTime1" }, //3rd day of year + { new DateTime(1990, 1, 7), "TestTime2" }, //7th day of year + { new DateTime(1995, 1, 22), "TestTime3" }, //22th day of year + { new DateTime(2000, 2, 1), "TestTime4" }, //32th day of year + { new DateTime(2005, 2, 1), "TestTime5" }, //32th day of year + }; - var query = timeline.GetValuesByTimeOfDay(new TimeSpan(0, 21, 15, 40, 600)); + var query = timeline.GetValuesByDayOfYear(32); - using (new AssertionScope()) - { - query.Count - .Should() - .Be(2); + using (new AssertionScope()) + { + query.Count + .Should() + .Be(2); - timeline - .Should() - .Contain(query); - } + timeline + .Should() + .Contain(query); } + } - [Test] - public static void GetValuesByDayOfWeekTest() + [Test] + public static void GetValuesByMonthTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(2015, 1, 5), "TestTime1" }, //Monday - { new DateTime(2015, 2, 2), "TestTime2" }, //Monday - { new DateTime(2015, 1, 6), "TestTime3" }, //Tuesday - { new DateTime(2015, 1, 7), "TestTime4" }, //Wednesday - { new DateTime(2015, 1, 8), "TestTime5" }, //Thursday - }; + { new DateTime(1985, 1, 1), "TestTime1" }, + { new DateTime(1990, 2, 1), "TestTime2" }, + { new DateTime(1995, 3, 1), "TestTime3" }, + { new DateTime(2005, 4, 1), "TestTime4" }, + { new DateTime(2015, 4, 1), "TestTime5" }, + }; - var query = timeline.GetValuesByDayOfWeek(DayOfWeek.Monday); + var query = timeline.GetValuesByMonth(4); - using (new AssertionScope()) - { - query.Count - .Should() - .Be(2); + using (new AssertionScope()) + { + query.Count + .Should() + .Be(2); - timeline - .Should() - .Contain(query); - } + timeline + .Should() + .Contain(query); } + } - [Test] - public static void GetValuesByDayOfYearTest() + [Test] + public static void GetValuesByYearTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1985, 1, 3), "TestTime1" }, //3rd day of year - { new DateTime(1990, 1, 7), "TestTime2" }, //7th day of year - { new DateTime(1995, 1, 22), "TestTime3" }, //22th day of year - { new DateTime(2000, 2, 1), "TestTime4" }, //32th day of year - { new DateTime(2005, 2, 1), "TestTime5" }, //32th day of year - }; + { new DateTime(1985, 1, 2), "TestTime1" }, + { new DateTime(1990, 2, 1), "TestTime2" }, + { new DateTime(1995, 1, 2), "TestTime3" }, + { new DateTime(2005, 2, 1), "TestTime4" }, + { new DateTime(2005, 1, 2), "TestTime5" }, + }; - var query = timeline.GetValuesByDayOfYear(32); + var query = timeline.GetValuesByYear(2005); - using (new AssertionScope()) - { - query.Count - .Should() - .Be(2); + using (new AssertionScope()) + { + query.Count + .Should() + .Be(2); - timeline - .Should() - .Contain(query); - } + timeline + .Should() + .Contain(query); } + } - [Test] - public static void GetValuesByMonthTest() - { - var timeline = new Timeline - { - { new DateTime(1985, 1, 1), "TestTime1" }, - { new DateTime(1990, 2, 1), "TestTime2" }, - { new DateTime(1995, 3, 1), "TestTime3" }, - { new DateTime(2005, 4, 1), "TestTime4" }, - { new DateTime(2015, 4, 1), "TestTime5" }, - }; + [Test] + public static void AddDateTimeAndTValueTest() //void Add(DateTime time, TValue value) + { + var eventDate = new DateTime(2015, 1, 1); + const string eventName = "TestTime"; - var query = timeline.GetValuesByMonth(4); + var timeline = new Timeline(); - using (new AssertionScope()) - { - query.Count - .Should() - .Be(2); + timeline.Add(eventDate, eventName); - timeline - .Should() - .Contain(query); - } - } + timeline.Count + .Should() + .Be(1); - [Test] - public static void GetValuesByYearTest() - { - var timeline = new Timeline - { - { new DateTime(1985, 1, 2), "TestTime1" }, - { new DateTime(1990, 2, 1), "TestTime2" }, - { new DateTime(1995, 1, 2), "TestTime3" }, - { new DateTime(2005, 2, 1), "TestTime4" }, - { new DateTime(2005, 1, 2), "TestTime5" }, - }; + timeline[eventDate][0] + .Should() + .Be(eventName); + } - var query = timeline.GetValuesByYear(2005); + [Test] + public static void AddDateTimeAndTValueArrayTest() //void Add(params (DateTime, TValue)[] timeline) + { + var eventDate1 = new DateTime(2015, 1, 1); + const string eventName1 = "TestTime1"; - using (new AssertionScope()) - { - query.Count - .Should() - .Be(2); + var eventDate2 = new DateTime(1750, 1, 1); + const string eventName2 = "TestTime2"; - timeline - .Should() - .Contain(query); - } - } + var timeline = new Timeline(); + + timeline.Add( + (eventDate1, eventName1), + (eventDate2, eventName2)); - [Test] - public static void AddDateTimeAndTValueTest() //void Add(DateTime time, TValue value) + using (new AssertionScope()) { - var eventDate = new DateTime(2015, 1, 1); - const string eventName = "TestTime"; + timeline.Count + .Should() + .Be(2); + + timeline[eventDate1][0] + .Should() + .Be(eventName1); - var timeline = new Timeline(); + timeline[eventDate2][0] + .Should() + .Be(eventName2); + } + } - timeline.Add(eventDate, eventName); + [Test] + public static void AddTimelineTest() //void Add(Timeline timeline) + { + var eventDate = new DateTime(2015, 1, 1); + const string eventName = "TestTime"; + var timeline = new Timeline(); + + timeline.Add(new Timeline(eventDate, eventName)); + + using (new AssertionScope()) + { timeline.Count .Should() .Be(1); @@ -674,470 +726,417 @@ public static void AddDateTimeAndTValueTest() //void Add(DateTime time, TValue v .Should() .Be(eventName); } + } - [Test] - public static void AddDateTimeAndTValueArrayTest() //void Add(params (DateTime, TValue)[] timeline) - { - var eventDate1 = new DateTime(2015, 1, 1); - const string eventName1 = "TestTime1"; - - var eventDate2 = new DateTime(1750, 1, 1); - const string eventName2 = "TestTime2"; - - var timeline = new Timeline(); + [Test] + public static void AddNowTest() + { + var timeline = new Timeline(); - timeline.Add( - (eventDate1, eventName1), - (eventDate2, eventName2)); + timeline.AddNow("Now"); - using (new AssertionScope()) - { - timeline.Count - .Should() - .Be(2); - - timeline[eventDate1][0] - .Should() - .Be(eventName1); + using (new AssertionScope()) + { + timeline.Count + .Should() + .Be(1); - timeline[eventDate2][0] - .Should() - .Be(eventName2); - } + timeline.ContainsValue("Now") + .Should() + .BeTrue(); } + } - [Test] - public static void AddTimelineTest() //void Add(Timeline timeline) + [Test] + public static void ContainsDateTimeAndTValueTest() //bool Contains(DateTime time, TValue value) + { + var timeline = new Timeline { - var eventDate = new DateTime(2015, 1, 1); - const string eventName = "TestTime"; - - var timeline = new Timeline(); - - timeline.Add(new Timeline(eventDate, eventName)); + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline.Contains(new DateTime(2000, 1, 1), "TestTime2") + .Should() + .BeTrue(); + } - using (new AssertionScope()) - { - timeline.Count - .Should() - .Be(1); + [Test] + public static void ContainsDateTimeAndTValueArrayTest() //bool Contains(params (DateTime, TValue)[] timeline) + { + var timeline = new Timeline + { + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline.Contains( + (new DateTime(1995, 1, 1), "TestTime1"), + (new DateTime(2000, 1, 1), "TestTime2")) + .Should() + .BeTrue(); + } - timeline[eventDate][0] - .Should() - .Be(eventName); - } - } + [Test] + public static void ContainsTimelineTest() //bool Contains(Timeline timeline) + { + var timeline = new Timeline + { + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline.Contains(new Timeline(new DateTime(2000, 1, 1), "TestTime2")) + .Should() + .BeTrue(); + } - [Test] - public static void AddNowTest() + [Test] + public static void ContainsTimeTest() + { + var timeline = new Timeline { - var timeline = new Timeline(); + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline.ContainsTime(new DateTime(2000, 1, 1)) + .Should() + .BeTrue(); + } - timeline.AddNow("Now"); + [Test] + public static void ContainsValueTest() + { + var timeline = new Timeline + { + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline.ContainsValue("TestTime1") + .Should() + .BeTrue(); + } - using (new AssertionScope()) - { - timeline.Count - .Should() - .Be(1); + [Test] + public static void RemoveDateTimeAndTValueTest() //bool Remove(DateTime time, TValue value) + { + var timeline = new Timeline + { + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; - timeline.ContainsValue("Now") - .Should() - .BeTrue(); - } - } + timeline.Remove(new DateTime(2000, 1, 1), "TestTime2"); - [Test] - public static void ContainsDateTimeAndTValueTest() //bool Contains(DateTime time, TValue value) + using (new AssertionScope()) { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + timeline.Count + .Should() + .Be(4); timeline.Contains(new DateTime(2000, 1, 1), "TestTime2") .Should() - .BeTrue(); + .BeFalse(); } + } - [Test] - public static void ContainsDateTimeAndTValueArrayTest() //bool Contains(params (DateTime, TValue)[] timeline) + [Test] + public static void RemoveDateTimeAndTValueArrayTest() //bool Remove(params (DateTime, TValue)[] timeline) + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline.Remove( + (new DateTime(1995, 1, 1), "TestTime1"), + (new DateTime(2000, 1, 1), "TestTime2")); + + using (new AssertionScope()) + { + timeline.Count + .Should() + .Be(3); timeline.Contains( (new DateTime(1995, 1, 1), "TestTime1"), (new DateTime(2000, 1, 1), "TestTime2")) .Should() - .BeTrue(); + .BeFalse(); } + } - [Test] - public static void ContainsTimelineTest() //bool Contains(Timeline timeline) + [Test] + public static void RemoveTimelineTest() //bool Remove(Timeline timeline) + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - timeline.Contains(new Timeline(new DateTime(2000, 1, 1), "TestTime2")) - .Should() - .BeTrue(); - } + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + timeline.Remove(new Timeline(new DateTime(2000, 1, 1), "TestTime2")); - [Test] - public static void ContainsTimeTest() + using (new AssertionScope()) { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + timeline.Count + .Should() + .Be(4); - timeline.ContainsTime(new DateTime(2000, 1, 1)) + timeline.Contains(new DateTime(2000, 1, 1), "TestTime2") .Should() - .BeTrue(); + .BeFalse(); } + } - [Test] - public static void ContainsValueTest() + [Test] + public static void RemoveTimeTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; - timeline.ContainsValue("TestTime1") + timeline.RemoveTimes(new DateTime(2000, 1, 1)); + + using (new AssertionScope()) + { + timeline.Count .Should() - .BeTrue(); + .Be(4); + + timeline.ContainsTime(new DateTime(2000, 1, 1)) + .Should() + .BeFalse(); } + } - [Test] - public static void RemoveDateTimeAndTValueTest() //bool Remove(DateTime time, TValue value) + [Test] + public static void RemoveValueTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; - timeline.Remove(new DateTime(2000, 1, 1), "TestTime2"); + timeline.RemoveValues("TestTime1"); - using (new AssertionScope()) - { - timeline.Count - .Should() - .Be(4); + using (new AssertionScope()) + { + timeline.Count + .Should() + .Be(4); - timeline.Contains(new DateTime(2000, 1, 1), "TestTime2") - .Should() - .BeFalse(); - } + timeline.ContainsValue("TestTime1") + .Should() + .BeFalse(); } + } - [Test] - public static void RemoveDateTimeAndTValueArrayTest() //bool Remove(params (DateTime, TValue)[] timeline) + [Test] + public static void ToArrayTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - timeline.Remove( - (new DateTime(1995, 1, 1), "TestTime1"), - (new DateTime(2000, 1, 1), "TestTime2")); + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; - using (new AssertionScope()) - { - timeline.Count - .Should() - .Be(3); + var array = timeline.ToArray(); - timeline.Contains( - (new DateTime(1995, 1, 1), "TestTime1"), - (new DateTime(2000, 1, 1), "TestTime2")) - .Should() - .BeFalse(); - } - } + timeline.Count + .Should() + .Be(array.Length); - [Test] - public static void RemoveTimelineTest() //bool Remove(Timeline timeline) + using (new AssertionScope()) { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - timeline.Remove(new Timeline(new DateTime(2000, 1, 1), "TestTime2")); - - using (new AssertionScope()) + var i = 0; + foreach (var (time, value) in timeline) { - timeline.Count + time .Should() - .Be(4); + .Be(array[i].Time); - timeline.Contains(new DateTime(2000, 1, 1), "TestTime2") + value .Should() - .BeFalse(); + .Be(array[i].Value); + + ++i; } } + } - [Test] - public static void RemoveTimeTest() + [Test] + public static void ToListTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - timeline.RemoveTimes(new DateTime(2000, 1, 1)); + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; - using (new AssertionScope()) - { - timeline.Count - .Should() - .Be(4); + var list = timeline.ToList(); - timeline.ContainsTime(new DateTime(2000, 1, 1)) - .Should() - .BeFalse(); - } - } + timeline.Count + .Should() + .Be(list.Count); - [Test] - public static void RemoveValueTest() + using (new AssertionScope()) { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - timeline.RemoveValues("TestTime1"); - - using (new AssertionScope()) + var i = 0; + foreach (var (time, value) in timeline) { - timeline.Count + time .Should() - .Be(4); + .Be(list[i].Time); - timeline.ContainsValue("TestTime1") + value .Should() - .BeFalse(); - } - } - - [Test] - public static void ToArrayTest() - { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - var array = timeline.ToArray(); + .Be(list[i].Value); - timeline.Count - .Should() - .Be(array.Length); - - using (new AssertionScope()) - { - var i = 0; - foreach (var (time, value) in timeline) - { - time - .Should() - .Be(array[i].Time); - - value - .Should() - .Be(array[i].Value); - - ++i; - } + ++i; } } + } - [Test] - public static void ToListTest() + [Test] + public static void ToDictionaryTest() + { + var timeline = new Timeline { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; - var list = timeline.ToList(); + var dictionary = timeline.ToDictionary(); - timeline.Count - .Should() - .Be(list.Count); - - using (new AssertionScope()) - { - var i = 0; - foreach (var (time, value) in timeline) - { - time - .Should() - .Be(list[i].Time); - - value - .Should() - .Be(list[i].Value); - - ++i; - } - } + var timelineList = new List<(DateTime Time, string Value)>(); + foreach (var pair in timeline) + { + timelineList.Add(pair); } - [Test] - public static void ToDictionaryTest() + var dictionaryList = new List<(DateTime Time, string Value)>(); + foreach (var (key, value) in dictionary) { - var timeline = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; + dictionaryList.Add((key, value)); + } - var dictionary = timeline.ToDictionary(); + timelineList.OrderBy(pair => pair.Time); + dictionaryList.OrderBy(pair => pair.Time); - var timelineList = new List<(DateTime Time, string Value)>(); - foreach (var pair in timeline) - { - timelineList.Add(pair); - } + timelineList.Count + .Should() + .Be(dictionaryList.Count); - var dictionaryList = new List<(DateTime Time, string Value)>(); - foreach (var (key, value) in dictionary) + using (new AssertionScope()) + { + for (var i = 0; i < timelineList.Count; ++i) { - dictionaryList.Add((key, value)); - } - - timelineList.OrderBy(pair => pair.Time); - dictionaryList.OrderBy(pair => pair.Time); - - timelineList.Count - .Should() - .Be(dictionaryList.Count); + timelineList[i].Time + .Should() + .Be(dictionaryList[i].Time); - using (new AssertionScope()) - { - for (var i = 0; i < timelineList.Count; ++i) - { - timelineList[i].Time - .Should() - .Be(dictionaryList[i].Time); - - timelineList[i].Value - .Should() - .Be(dictionaryList[i].Value); - } + timelineList[i].Value + .Should() + .Be(dictionaryList[i].Value); } } + } - [Test] - public static void EqualityOperatorTest() + [Test] + public static void EqualityOperatorTest() + { + var timeline1 = new Timeline { - var timeline1 = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - var timeline2 = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - (timeline1 == timeline2) - .Should() - .BeTrue(); - } + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + var timeline2 = new Timeline + { + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + (timeline1 == timeline2) + .Should() + .BeTrue(); + } - [Test] - public static void InequalityOperatorTest() + [Test] + public static void InequalityOperatorTest() + { + var timeline1 = new Timeline { - var timeline1 = new Timeline - { - { new DateTime(1995, 1, 1), "TestTime1" }, - { new DateTime(2000, 1, 1), "TestTime2" }, - { new DateTime(2005, 1, 1), "TestTime3" }, - { new DateTime(2010, 1, 1), "TestTime4" }, - { new DateTime(2015, 1, 1), "TestTime5" }, - }; - - var timeline2 = new Timeline - { - { new DateTime(1895, 1, 1), "TestTime6" }, - { new DateTime(1900, 1, 1), "TestTime7" }, - { new DateTime(1905, 1, 1), "TestTime8" }, - { new DateTime(1910, 1, 1), "TestTime9" }, - { new DateTime(1915, 1, 1), "TestTime10" }, - }; - - (timeline1 == timeline2) - .Should() - .BeFalse(); - } + { new DateTime(1995, 1, 1), "TestTime1" }, + { new DateTime(2000, 1, 1), "TestTime2" }, + { new DateTime(2005, 1, 1), "TestTime3" }, + { new DateTime(2010, 1, 1), "TestTime4" }, + { new DateTime(2015, 1, 1), "TestTime5" }, + }; + + var timeline2 = new Timeline + { + { new DateTime(1895, 1, 1), "TestTime6" }, + { new DateTime(1900, 1, 1), "TestTime7" }, + { new DateTime(1905, 1, 1), "TestTime8" }, + { new DateTime(1910, 1, 1), "TestTime9" }, + { new DateTime(1915, 1, 1), "TestTime10" }, + }; + + (timeline1 == timeline2) + .Should() + .BeFalse(); } } diff --git a/DataStructures.Tests/Tries/TrieTests.cs b/DataStructures.Tests/Tries/TrieTests.cs index 770a54c3..8b84356d 100644 --- a/DataStructures.Tests/Tries/TrieTests.cs +++ b/DataStructures.Tests/Tries/TrieTests.cs @@ -2,114 +2,113 @@ using DataStructures.Tries; using NUnit.Framework; -namespace DataStructures.Tests.Tries +namespace DataStructures.Tests.Tries; + +public static class TrieTests { - public static class TrieTests - { - [Test] - public static void FindWordInTrie(){ - // Arrange - string[] words = { - "trie", - "node", - "none", - "treatment", - }; - - // Act - Trie trie = new(words); - - // Assert - Assert.IsTrue(trie.Find("trie"), "The word 'trie' isn't in Trie structure"); - Assert.IsTrue(trie.Find("node"), "The word 'node' isn't in Trie structure"); - Assert.IsTrue(trie.Find("none"), "The word 'none' isn't in Trie structure"); - Assert.IsTrue(trie.Find("treatment"), "The word 'treatment' isn't in Trie structure"); - - Assert.IsFalse(trie.Find("nodes"), "The word 'nodes' is in Trie sturcture"); - Assert.IsFalse(trie.Find(""), "The word empty is in Trie structure"); - Assert.IsFalse(trie.Find("tri"), "The word 'tri' is in Trie structure"); - } + [Test] + public static void FindWordInTrie(){ + // Arrange + string[] words = { + "trie", + "node", + "none", + "treatment", + }; + + // Act + Trie trie = new(words); + + // Assert + Assert.IsTrue(trie.Find("trie"), "The word 'trie' isn't in Trie structure"); + Assert.IsTrue(trie.Find("node"), "The word 'node' isn't in Trie structure"); + Assert.IsTrue(trie.Find("none"), "The word 'none' isn't in Trie structure"); + Assert.IsTrue(trie.Find("treatment"), "The word 'treatment' isn't in Trie structure"); + + Assert.IsFalse(trie.Find("nodes"), "The word 'nodes' is in Trie sturcture"); + Assert.IsFalse(trie.Find(""), "The word empty is in Trie structure"); + Assert.IsFalse(trie.Find("tri"), "The word 'tri' is in Trie structure"); + } - [Test] - public static void InsertInTrie(){ - // Arrange - string[] words = { - "trie", - "node", - "none", - "treatment", - }; - - Trie trie = new(); - - // Act - foreach (var t in words) - { - trie.Insert(t); - } - - // Assert - Assert.IsTrue(trie.Find("trie"), "The word 'trie' isn't in Trie structure"); - Assert.IsTrue(trie.Find("node"), "The word 'node' isn't in Trie structure"); - Assert.IsTrue(trie.Find("none"), "The word 'none' isn't in Trie structure"); - Assert.IsTrue(trie.Find("treatment"), "The word 'treatment' isn't in Trie structure"); - } + [Test] + public static void InsertInTrie(){ + // Arrange + string[] words = { + "trie", + "node", + "none", + "treatment", + }; - [Test] - public static void RemoveFromTrie(){ - // Arrange - string[] words = { - "trie", - "node", - "none", - "treatment", - }; - - Trie trie = new(); - - // Act - foreach (var t in words) - { - trie.Insert(t); - } - trie.Remove("trie"); - - // Assert - Assert.IsFalse(trie.Find("trie"), "The word 'trie' is in Trie structure"); - Assert.IsTrue(trie.Find("treatment"), "The word 'treament' isn't in Trie structure"); - Assert.IsTrue(trie.Find("node"), "The word 'node' isn't in Trie structure"); - Assert.IsTrue(trie.Find("none"), "The word 'none' isn't in Trie structure"); - } + Trie trie = new(); - [Test] - public static void MultipleInsert() + // Act + foreach (var t in words) { - // Arrange - string w = "trie"; - Trie trie = new(); + trie.Insert(t); + } + + // Assert + Assert.IsTrue(trie.Find("trie"), "The word 'trie' isn't in Trie structure"); + Assert.IsTrue(trie.Find("node"), "The word 'node' isn't in Trie structure"); + Assert.IsTrue(trie.Find("none"), "The word 'none' isn't in Trie structure"); + Assert.IsTrue(trie.Find("treatment"), "The word 'treatment' isn't in Trie structure"); + } + + [Test] + public static void RemoveFromTrie(){ + // Arrange + string[] words = { + "trie", + "node", + "none", + "treatment", + }; - // Act - trie.Insert(w); - trie.Insert(w); + Trie trie = new(); - // Assert - Assert.IsTrue(trie.Find("trie"), "The word 'trie' isn't in Trie structure"); - Assert.IsFalse(trie.Find("nodes"), "The word 'nodes' is in Trie sturcture"); + // Act + foreach (var t in words) + { + trie.Insert(t); } + trie.Remove("trie"); - [Test] - public static void RemoveAWordThatIsNtInTrie(){ - // Arrange - const string w = "trie"; - Trie trie = new(); + // Assert + Assert.IsFalse(trie.Find("trie"), "The word 'trie' is in Trie structure"); + Assert.IsTrue(trie.Find("treatment"), "The word 'treament' isn't in Trie structure"); + Assert.IsTrue(trie.Find("node"), "The word 'node' isn't in Trie structure"); + Assert.IsTrue(trie.Find("none"), "The word 'none' isn't in Trie structure"); + } - // Act - trie.Insert(w); - trie.Remove("tri"); - trie.Remove("none"); + [Test] + public static void MultipleInsert() + { + // Arrange + string w = "trie"; + Trie trie = new(); - // Assert - Assert.IsTrue(trie.Find("trie"), "The word 'trie' isn't in Trie structure"); - } + // Act + trie.Insert(w); + trie.Insert(w); + + // Assert + Assert.IsTrue(trie.Find("trie"), "The word 'trie' isn't in Trie structure"); + Assert.IsFalse(trie.Find("nodes"), "The word 'nodes' is in Trie sturcture"); + } + + [Test] + public static void RemoveAWordThatIsNtInTrie(){ + // Arrange + const string w = "trie"; + Trie trie = new(); + + // Act + trie.Insert(w); + trie.Remove("tri"); + trie.Remove("none"); + + // Assert + Assert.IsTrue(trie.Find("trie"), "The word 'trie' isn't in Trie structure"); } } diff --git a/DataStructures.Tests/UnrolledList/UnrolledLinkedListNodeTests.cs b/DataStructures.Tests/UnrolledList/UnrolledLinkedListNodeTests.cs index 95b0bc1a..eb73b760 100644 --- a/DataStructures.Tests/UnrolledList/UnrolledLinkedListNodeTests.cs +++ b/DataStructures.Tests/UnrolledList/UnrolledLinkedListNodeTests.cs @@ -1,61 +1,60 @@ -using System; +using System; using DataStructures.UnrolledList; using FluentAssertions; using NUnit.Framework; -namespace DataStructures.Tests.UnrolledList +namespace DataStructures.Tests.UnrolledList; + +public class UnrolledLinkedListNodeTests { - public class UnrolledLinkedListNodeTests + [Test] + public void GetAndSet_SetItemNodeAndGetIt_ReturnExpectedItem() { - [Test] - public void GetAndSet_SetItemNodeAndGetIt_ReturnExpectedItem() - { - var node = new UnrolledLinkedListNode(6); - node.Set(0, 1); + var node = new UnrolledLinkedListNode(6); + node.Set(0, 1); - var result = node.Get(0); + var result = node.Get(0); - result.Should().Be(1); - } + result.Should().Be(1); + } - [Test] - public void Get_GetLowIndex_ThrowArgumentException() - { - var node = new UnrolledLinkedListNode(6); + [Test] + public void Get_GetLowIndex_ThrowArgumentException() + { + var node = new UnrolledLinkedListNode(6); - Action action = () => node.Get(-1); + Action action = () => node.Get(-1); - action.Should().Throw(); - } + action.Should().Throw(); + } - [Test] - public void Get_GetHighIndex_ThrowArgumentException() - { - var node = new UnrolledLinkedListNode(6); + [Test] + public void Get_GetHighIndex_ThrowArgumentException() + { + var node = new UnrolledLinkedListNode(6); - Action action = () => node.Get(7); + Action action = () => node.Get(7); - action.Should().Throw(); - } + action.Should().Throw(); + } - [Test] - public void Set_SetLowIndex_ThrowArgumentException() - { - var node = new UnrolledLinkedListNode(6); + [Test] + public void Set_SetLowIndex_ThrowArgumentException() + { + var node = new UnrolledLinkedListNode(6); - Action action = () => node.Set(-1, 0); + Action action = () => node.Set(-1, 0); - action.Should().Throw(); - } + action.Should().Throw(); + } - [Test] - public void Set_SetHighIndex_ThrowArgumentException() - { - var node = new UnrolledLinkedListNode(6); + [Test] + public void Set_SetHighIndex_ThrowArgumentException() + { + var node = new UnrolledLinkedListNode(6); - Action action = () => node.Set(7, 0); + Action action = () => node.Set(7, 0); - action.Should().Throw(); - } + action.Should().Throw(); } } diff --git a/DataStructures.Tests/UnrolledList/UnrolledLinkedListTests.cs b/DataStructures.Tests/UnrolledList/UnrolledLinkedListTests.cs index 26761bf0..32a410d2 100644 --- a/DataStructures.Tests/UnrolledList/UnrolledLinkedListTests.cs +++ b/DataStructures.Tests/UnrolledList/UnrolledLinkedListTests.cs @@ -1,24 +1,23 @@ -using DataStructures.UnrolledList; +using DataStructures.UnrolledList; using FluentAssertions; using NUnit.Framework; -namespace DataStructures.Tests.UnrolledList +namespace DataStructures.Tests.UnrolledList; + +public class UnrolledLinkedListTests { - public class UnrolledLinkedListTests + [Test] + public void Insert_LinkArrayToLinkedList_ReturnArrayHaveSameItems() { - [Test] - public void Insert_LinkArrayToLinkedList_ReturnArrayHaveSameItems() + var linkedList = new UnrolledLinkedList(6); + var contest = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; + foreach (var number in contest) { - var linkedList = new UnrolledLinkedList(6); - var contest = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; - foreach (var number in contest) - { - linkedList.Insert(number); - } + linkedList.Insert(number); + } - var result = linkedList.GetRolledItems(); + var result = linkedList.GetRolledItems(); - result.Should().BeEquivalentTo(contest); - } + result.Should().BeEquivalentTo(contest); } }