repo_name
stringlengths 1
52
| repo_creator
stringclasses 6
values | programming_language
stringclasses 4
values | code
stringlengths 0
9.68M
| num_lines
int64 1
234k
|
---|---|---|---|---|
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class BinaryPrimeConstantSequenceTests
{
[Test]
public void First10ElementsCorrect()
{
var sequence = new BinaryPrimeConstantSequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[] { 0, 1, 1, 0, 1, 0, 1, 0, 0, 0 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class BinomialSequenceTests
{
[Test]
public void First4RowsCorrect()
{
var sequence = new BinomialSequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[] { 1, 1, 1, 1, 2, 1, 1, 3, 3, 1 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences;
public class CakeNumbersSequenceTests
{
[Test]
public void First46ElementsCorrect()
{
var sequence = new CakeNumbersSequence().Sequence.Take(46);
sequence.SequenceEqual(new BigInteger[]
{
1, 2, 4, 8, 15, 26, 42, 64, 93, 130,
176, 232, 299, 378, 470, 576, 697, 834, 988, 1160,
1351, 1562, 1794, 2048, 2325, 2626, 2952, 3304, 3683, 4090,
4526, 4992, 5489, 6018, 6580, 7176, 7807, 8474, 9178, 9920,
10701, 11522, 12384, 13288, 14235, 15226
})
.Should().BeTrue();
}
}
| 26 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class CatalanSequenceTest
{
[Test]
public void First30ItemsCorrect()
{
var sequence = new CatalanSequence().Sequence.Take(30);
sequence.SequenceEqual(new BigInteger[] { 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440,
9694845, 35357670, 129644790, 477638700, 1767263190, 6564120420, 24466267020,
91482563640, 343059613650, 1289904147324, 4861946401452, 18367353072152,
69533550916004, 263747951750360, 1002242216651368})
.Should().BeTrue();
}
}
}
| 23 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences;
public class CentralPolygonalNumbersSequenceTests
{
[Test]
public void First53ElementsCorrect()
{
var sequence = new CentralPolygonalNumbersSequence().Sequence.Take(53);
sequence.SequenceEqual(new BigInteger[]
{
1, 2, 4, 7, 11, 16, 22, 29, 37, 46, 56, 67, 79, 92, 106, 121, 137, 154, 172, 191, 211, 232, 254,
277, 301, 326, 352, 379, 407, 436, 466, 497, 529, 562, 596, 631, 667, 704, 742, 781, 821, 862, 904,
947, 991, 1036, 1082, 1129, 1177, 1226, 1276, 1327, 1379,
})
.Should().BeTrue();
}
}
| 24 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class CubesSequenceTests
{
[Test]
public void First10ElementsCorrect()
{
var sequence = new CubesSequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[] { 0, 1, 8, 27, 64, 125, 216, 343, 512, 729 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class DivisorsCountSequenceTests
{
[Test]
public void First10ElementsCorrect()
{
// These values are taken from https://oeis.org/A000005 for comparison.
var oeisSource = new BigInteger[]
{
1, 2, 2, 3, 2, 4, 2, 4, 3, 4, 2, 6, 2,
4, 4, 5, 2, 6, 2, 6, 4, 4, 2, 8, 3, 4,
4, 6, 2, 8, 2, 6, 4, 4, 4, 9, 2, 4, 4,
8, 2, 8, 2, 6, 6, 4, 2, 10, 3, 6, 4, 6,
2, 8, 4, 8, 4, 4, 2, 12, 2, 4, 6, 7, 4,
8, 2, 6, 4, 8, 2, 12, 2, 4, 6, 6, 4, 8,
2, 10, 5, 4, 2, 12, 4, 4, 4, 8, 2, 12, 4,
6, 4, 4, 4, 12, 2, 6, 6, 9, 2, 8, 2, 8,
};
var sequence = new DivisorsCountSequence().Sequence.Take(oeisSource.Length);
sequence.SequenceEqual(oeisSource).Should().BeTrue();
}
}
}
| 32 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class EuclidNumbersSequenceTests
{
[Test]
public void First10ElementsCorrect()
{
var sequence = new EuclidNumbersSequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[]
{ 2, 3, 7, 31, 211, 2311, 30031, 510511, 9699691, 223092871 })
.Should().BeTrue();
}
}
}
| 21 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class EulerTotientSequenceTests
{
[Test]
public void FirstElementsCorrect()
{
// Let's be thorough. 500 phi values!
// Initial test of 69 number from table at https://oeis.org/A000010/list and passed test.
// Extended out to 500 values from https://primefan.tripod.com/Phi500.html and passed initial 69
// along with remaining values.
var check = new BigInteger[]
{
1, 1, 2, 2, 4, 2, 6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16, 6, 18, 8,
12, 10, 22, 8, 20, 12, 18, 12, 28, 8, 30, 16, 20, 16, 24, 12, 36, 18, 24, 16,
40, 12, 42, 20, 24, 22, 46, 16, 42, 20, 32, 24, 52, 18, 40, 24, 36, 28, 58, 16,
60, 30, 36, 32, 48, 20, 66, 32, 44, 24, 70, 24, 72, 36, 40, 36, 60, 24, 78, 32,
54, 40, 82, 24, 64, 42, 56, 40, 88, 24, 72, 44, 60, 46, 72, 32, 96, 42, 60, 40,
100, 32, 102, 48, 48, 52, 106, 36, 108, 40, 72, 48, 112, 36, 88, 56, 72, 58, 96, 32,
110, 60, 80, 60, 100, 36, 126, 64, 84, 48, 130, 40, 108, 66, 72, 64, 136, 44, 138, 48,
92, 70, 120, 48, 112, 72, 84, 72, 148, 40, 150, 72, 96, 60, 120, 48, 156, 78, 104, 64,
132, 54, 162, 80, 80, 82, 166, 48, 156, 64, 108, 84, 172, 56, 120, 80, 116, 88, 178, 48,
180, 72, 120, 88, 144, 60, 160, 92, 108, 72, 190, 64, 192, 96, 96, 84, 196, 60, 198, 80,
132, 100, 168, 64, 160, 102, 132, 96, 180, 48, 210, 104, 140, 106, 168, 72, 180, 108, 144, 80,
192, 72, 222, 96, 120, 112, 226, 72, 228, 88, 120, 112, 232, 72, 184, 116, 156, 96, 238, 64,
240, 110, 162, 120, 168, 80, 216, 120, 164, 100, 250, 72, 220, 126, 128, 128, 256, 84, 216, 96,
168, 130, 262, 80, 208, 108, 176, 132, 268, 72, 270, 128, 144, 136, 200, 88, 276, 138, 180, 96,
280, 92, 282, 140, 144, 120, 240, 96, 272, 112, 192, 144, 292, 84, 232, 144, 180, 148, 264, 80,
252, 150, 200, 144, 240, 96, 306, 120, 204, 120, 310, 96, 312, 156, 144, 156, 316, 104, 280, 128,
212, 132, 288, 108, 240, 162, 216, 160, 276, 80, 330, 164, 216, 166, 264, 96, 336, 156, 224, 128,
300, 108, 294, 168, 176, 172, 346, 112, 348, 120, 216, 160, 352, 116, 280, 176, 192, 178, 358, 96,
342, 180, 220, 144, 288, 120, 366, 176, 240, 144, 312, 120, 372, 160, 200, 184, 336, 108, 378, 144,
252, 190, 382, 128, 240, 192, 252, 192, 388, 96, 352, 168, 260, 196, 312, 120, 396, 198, 216, 160,
400, 132, 360, 200, 216, 168, 360, 128, 408, 160, 272, 204, 348, 132, 328, 192, 276, 180, 418, 96,
420, 210, 276, 208, 320, 140, 360, 212, 240, 168, 430, 144, 432, 180, 224, 216, 396, 144, 438, 160,
252, 192, 442, 144, 352, 222, 296, 192, 448, 120, 400, 224, 300, 226, 288, 144, 456, 228, 288, 176,
460, 120, 462, 224, 240, 232, 466, 144, 396, 184, 312, 232, 420, 156, 360, 192, 312, 238, 478, 128,
432, 240, 264, 220, 384, 162, 486, 240, 324, 168, 490, 160, 448, 216, 240, 240, 420, 164, 498, 200,
};
var sequence = new EulerTotientSequence().Sequence.Take(check.Length);
sequence.SequenceEqual(check).Should().BeTrue();
}
}
}
| 52 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class FactorialSequenceTest
{
[Test]
public void First10ItemsCorrect()
{
var sequence = new FactorialSequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[] { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class FermatNumbersSequenceTests
{
[Test]
public void First5ElementsCorrect()
{
var sequence = new FermatNumbersSequence().Sequence.Take(5);
sequence.SequenceEqual(new BigInteger[] { 3, 5, 17, 257, 65537 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class FermatPrimesSequenceTests
{
[Test]
public void All5ElementsCorrect()
{
var sequence = new FermatPrimesSequence().Sequence.Take(5);
sequence.SequenceEqual(new BigInteger[] { 3, 5, 17, 257, 65537 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class FibonacciSequenceTests
{
[Test]
public void First10ElementsCorrect()
{
var sequence = new FibonacciSequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[] { 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class GolombsSequenceTests
{
[Test]
public void First50ElementsCorrect()
{
// Taken from https://oeis.org/A001462
var expected = new BigInteger[] {
1, 2, 2, 3, 3, 4, 4, 4, 5, 5,
5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
8, 8, 8, 9, 9, 9, 9, 9, 10, 10,
10, 10, 10, 11, 11, 11, 11, 11, 12, 12,
12, 12, 12, 12, 13, 13, 13, 13, 13, 13};
var sequence = new GolombsSequence().Sequence.Take(50);
sequence.SequenceEqual(expected).Should().BeTrue();
}
}
}
| 28 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class KolakoskiSequenceTests
{
[Test]
public void First100ElementsCorrect()
{
// Taken from https://oeis.org/A000002
var expected = new BigInteger[]
{
1, 2, 2, 1, 1, 2, 1, 2, 2, 1,
2, 2, 1, 1, 2, 1, 1, 2, 2, 1,
2, 1, 1, 2, 1, 2, 2, 1, 1, 2,
1, 1, 2, 1, 2, 2, 1, 2, 2, 1,
1, 2, 1, 2, 2, 1, 2, 1, 1, 2,
1, 1, 2, 2, 1, 2, 2, 1, 1, 2,
1, 2, 2, 1, 2, 2, 1, 1, 2, 1,
1, 2, 1, 2, 2, 1, 2, 1, 1, 2,
2, 1, 2, 2, 1, 1, 2, 1, 2, 2,
1, 2, 2, 1, 1, 2, 1, 1, 2, 2,
};
var sequence = new KolakoskiSequence().Sequence.Take(100);
var sequence2 = new KolakoskiSequence2().Sequence.Take(100);
sequence.Should().Equal(expected);
sequence2.Should().Equal(expected);
}
}
}
| 37 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class KummerNumbersSequenceTests
{
[Test]
public void First10ElementsCorrect()
{
var sequence = new KummerNumbersSequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[]
{ 1, 5, 29, 209, 2309, 30029, 510509, 9699689, 223092869, 6469693229 })
.Should().BeTrue();
}
}
}
| 21 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences;
public class LucasNumbersBeginningAt2SequenceTests
{
[Test]
public void FirstElementsCorrect()
{
// Initial test of 38 values from http://oeis.org/A000032/list which passed.
// Testing 200 Lucas numbers, with values from https://r-knott.surrey.ac.uk/Fibonacci/lucas200.html and
// compared to initial 38, which passed.
// Assigning numeric values to BigInteger types performed by string parsing dues to length of value.
var bigNumbers = new[] {
"2", "1", "3", "4", "7", "11", "18", "29", "47", "76", "123", "199", "322",
"521", "843", "1364", "2207", "3571", "5778", "9349", "15127", "24476",
"39603", "64079", "103682", "167761", "271443", "439204", "710647", "1149851",
"1860498", "3010349", "4870847", "7881196", "12752043", "20633239", "33385282",
"54018521", "87403803", "141422324", "228826127", "370248451", "599074578",
"969323029", "1568397607", "2537720636", "4106118243", "6643838879",
"10749957122", "17393796001", "28143753123", "45537549124", "73681302247",
"119218851371", "192900153618", "312119004989", "505019158607", "817138163596",
"1322157322203", "2139295485799", "3461452808002", "5600748293801",
"9062201101803", "14662949395604", "23725150497407", "38388099893011",
"62113250390418", "100501350283429", "162614600673847", "263115950957276",
"425730551631123", "688846502588399", "1114577054219522", "1803423556807921",
"2918000611027443", "4721424167835364", "7639424778862807",
"12360848946698171", "20000273725560978", "32361122672259149",
"52361396397820127", "84722519070079276", "137083915467899403",
"221806434537978679", "358890350005878082", "580696784543856761",
"939587134549734843", "1520283919093591604", "2459871053643326447",
"3980154972736918051", "6440026026380244498", "10420180999117162549",
"16860207025497407047", "27280388024614569596", "44140595050111976643",
"71420983074726546239", "115561578124838522882", "186982561199565069121",
"302544139324403592003", "489526700523968661124", "792070839848372253127",
"1281597540372340914251", "2073668380220713167378", "3355265920593054081629",
"5428934300813767249007", "8784200221406821330636", "14213134522220588579643",
"22997334743627409910279", "37210469265847998489922",
"60207804009475408400201", "97418273275323406890123",
"157626077284798815290324", "255044350560122222180447",
"412670427844921037470771", "667714778405043259651218",
"1080385206249964297121989", "1748099984655007556773207",
"2828485190904971853895196", "4576585175559979410668403",
"7405070366464951264563599", "11981655542024930675232002",
"19386725908489881939795601", "31368381450514812615027603",
"50755107359004694554823204", "82123488809519507169850807",
"132878596168524201724674011", "215002084978043708894524818"
, "347880681146567910619198829", "562882766124611619513723647",
"910763447271179530132922476", "1473646213395791149646646123",
"2384409660666970679779568599", "3858055874062761829426214722",
"6242465534729732509205783321", "10100521408792494338631998043",
"16342986943522226847837781364", "26443508352314721186469779407",
"42786495295836948034307560771", "69230003648151669220777340178",
"112016498943988617255084900949", "181246502592140286475862241127",
"293263001536128903730947142076", "474509504128269190206809383203",
"767772505664398093937756525279", "1242282009792667284144565908482",
"2010054515457065378082322433761", "3252336525249732662226888342243",
"5262391040706798040309210776004", "8514727565956530702536099118247",
"13777118606663328742845309894251", "22291846172619859445381409012498",
"36068964779283188188226718906749", "58360810951903047633608127919247",
"94429775731186235821834846825996", "152790586683089283455442974745243",
"247220362414275519277277821571239", "400010949097364802732720796316482",
"647231311511640322009998617887721", "1047242260609005124742719414204203",
"1694473572120645446752718032091924", "2741715832729650571495437446296127",
"4436189404850296018248155478388051", "7177905237579946589743592924684178",
"11614094642430242607991748403072229", "18791999880010189197735341327756407",
"30406094522440431805727089730828636", "49198094402450621003462431058585043",
"79604188924891052809189520789413679", "128802283327341673812651951847998722",
"208406472252232726621841472637412401", "337208755579574400434493424485411123",
"545615227831807127056334897122823524", "882823983411381527490828321608234647",
"1428439211243188654547163218731058171",
"2311263194654570182037991540339292818",
"3739702405897758836585154759070350989",
"6050965600552329018623146299409643807",
"9790668006450087855208301058479994796",
"15841633607002416873831447357889638603",
"25632301613452504729039748416369633399",
"41473935220454921602871195774259272002",
"67106236833907426331910944190628905401",
"108580172054362347934782139964888177403",
"175686408888269774266693084155517082804",
"284266580942632122201475224120405260207",
"459952989830901896468168308275922343011",
"744219570773534018669643532396327603218",
"1204172560604435915137811840672249946229",
"1948392131377969933807455373068577549447",
"3152564691982405848945267213740827495676",
"5100956823360375782752722586809405045123",
"8253521515342781631697989800550232540799",
"13354478338703157414450712387359637585922",
"21607999854045939046148702187909870126721",
"34962478192749096460599414575269507712643",
"56570478046795035506748116763179377839364",
"91532956239544131967347531338448885552007",
"148103434286339167474095648101628263391371",
"239636390525883299441443179440077148943378",
"387739824812222466915538827541705412334749",
"627376215338105766356982006981782561278127",
};
var check = bigNumbers.Select(BigInteger.Parse).ToArray();
var sequence = new LucasNumbersBeginningAt2Sequence().Sequence.Take(check.Length);
sequence.SequenceEqual(check).Should().BeTrue();
}
}
| 110 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class MakeChangeSequenceTests
{
[Test]
public void First100ElementsCorrect()
{
// Values from https://oeis.org/A000008/b000008.txt
var test = new BigInteger[]
{
1, 1, 2, 2, 3, 4, 5, 6, 7, 8,
11, 12, 15, 16, 19, 22, 25, 28, 31, 34,
40, 43, 49, 52, 58, 64, 70, 76, 82, 88,
98, 104, 114, 120, 130, 140, 150, 160, 170, 180,
195, 205, 220, 230, 245, 260, 275, 290, 305, 320,
341, 356, 377, 392, 413, 434, 455, 476, 497, 518,
546, 567, 595, 616, 644, 672, 700, 728, 756, 784,
820, 848, 884, 912, 948, 984, 1020, 1056, 1092, 1128,
1173, 1209, 1254, 1290, 1335, 1380, 1425, 1470, 1515, 1560,
1615, 1660, 1715, 1760, 1815, 1870, 1925, 1980, 2035, 2090,
};
var sequence = new MakeChangeSequence().Sequence.Take(test.Length);
sequence.SequenceEqual(test).Should().BeTrue();
}
}
}
| 34 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences;
[TestFixture]
public static class MatchstickTriangleSequenceTests
{
private static BigInteger[] TestList = {
0, 1, 5, 13, 27, 48, 78, 118, 170, 235, 315, 411, 525, 658,
812, 988, 1188, 1413, 1665, 1945, 2255, 2596, 2970, 3378,
3822, 4303, 4823, 5383, 5985, 6630, 7320, 8056, 8840, 9673,
10557, 11493, 12483, 13528, 14630, 15790, 17010, 18291,
19635, 21043, 22517,
};
/// <summary>
/// This test uses the list values provided from http://oeis.org/A002717/list.
/// </summary>
[Test]
public static void TestOeisList()
{
var sequence = new MatchstickTriangleSequence().Sequence.Take(TestList.Length);
sequence.SequenceEqual(TestList).Should().BeTrue();
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class NaturalSequenceTests
{
[Test]
public void First10ElementsCorrect()
{
var sequence = new NaturalSequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class NegativeIntegersSequenceTests
{
[Test]
public void First10ElementsCorrect()
{
var sequence = new NegativeIntegersSequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[] { -1, -2, -3, -4, -5, -6, -7, -8, -9, -10 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class NumberOfBooleanFunctionsSequenceTests
{
[Test]
public void First5ElementsCorrect()
{
var sequence = new NumberOfBooleanFunctionsSequence().Sequence.Take(5);
sequence.SequenceEqual(new BigInteger[] { 2, 4, 16, 256, 65536 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class NumberOfPrimesByNumberOfDigitsSequenceTests
{
[Test]
public void First5ElementsCorrect()
{
var sequence = new NumberOfPrimesByNumberOfDigitsSequence().Sequence.Take(5);
sequence.SequenceEqual(new BigInteger[] { 0, 4, 21, 143, 1061 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class NumberOfPrimesByPowersOf10SequenceTests
{
[Test]
public void First5ElementsCorrect()
{
var sequence = new NumberOfPrimesByPowersOf10Sequence().Sequence.Take(5);
sequence.SequenceEqual(new BigInteger[] { 0, 4, 25, 168, 1229 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences;
[TestFixture]
public class OnesCountingSequenceTest
{
/// <summary>
/// <para>
/// Values taken from http://oeis.org/A000120/b000120.txt.
/// </para>
/// <para>
/// While the file contains 10,000 values, this only tests 1000.
/// </para>
/// </summary>
private readonly BigInteger[] oeisValues = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2,
3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3,
3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3,
4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4,
3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5,
6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4,
4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5,
6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5,
3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3,
4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6,
6, 7, 6, 7, 7, 8, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3,
4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5,
4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3,
4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6,
6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6,
7, 5, 6, 6, 7, 6, 7, 7, 8, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4,
5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, 3, 4,
4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6,
7, 6, 7, 7, 8, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, 5, 6, 6, 7,
6, 7, 7, 8, 6, 7, 7, 8, 7, 8, 8, 9, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3,
4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4,
4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6,
7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6,
4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4,
5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4,
4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4,
5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7,
6, 7, 7, 8, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5,
6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7,
7, 8, 5, 6, 6, 7, 6, 7, 7, 8, 6, 7, 7, 8, 7, 8, 8, 9, 2, 3, 3, 4, 3, 4, 4,
5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5,
6, 6, 7, 6, 7, 7, 8, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5,
5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6,
7, 6, 7, 7, 8, 5, 6, 6, 7, 6, 7, 7, 8, 6, 7, 7, 8, 7, 8, 8, 9, 3, 4, 4, 5,
4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6,
7, 7, 8, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, 5, 6, 6, 7, 6, 7,
7, 8, 6, 7, 7, 8, 7, 8, 8, 9, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7,
8, 5, 6, 6, 7, 6, 7, 7, 8, 6, 7, 7, 8, 7, 8, 8, 9, 5, 6, 6, 7, 6, 7, 7, 8,
};
/// <summary>
/// <para>
/// Performs number of ones in the binary representation of a BigInteger.
/// </para>
/// <para>
/// This is used as a check to compare the provided values from OEIS.
/// </para>
/// </summary>
/// <param name="i">BigInteger value to count 1s in</param>
/// <returns>Number of 1s in binary representation of number.</returns>
private int CountOnes(BigInteger i)
{
var temp = i;
BigInteger remainder = 0;
var result = 0;
while (temp != BigInteger.Zero) {
temp = BigInteger.DivRem(temp, 2, out remainder);
result += remainder.IsOne ? 1 : 0;
}
return result;
}
[Test]
public void Count1000()
{
// Compare generated sequence against provided data
var sequence = new OnesCountingSequence().Sequence.Take(oeisValues.Length);
sequence.SequenceEqual(oeisValues).Should().BeTrue();
}
[Test]
public void CompareAgainstCalculated()
{
// Calculate 1s in binary value the old fashioned way.
var calculated = new List<BigInteger>();
for (var i = 0; i < oeisValues.Length; i++) {
calculated.Add(CountOnes(new BigInteger(i)));
}
calculated.SequenceEqual(oeisValues).Should().BeTrue();
}
}
| 109 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class PowersOf10SequenceTests
{
[Test]
public void First10ElementsCorrect()
{
var sequence = new PowersOf10Sequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[]
{ 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 })
.Should().BeTrue();
}
}
}
| 21 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class PowersOf2SequenceTests
{
[Test]
public void First10ElementsCorrect()
{
var sequence = new PowersOf2Sequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[] { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class PrimePiSequenceTests
{
[Test]
public void First10ElementsCorrect()
{
var sequence = new PrimePiSequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[] { 0, 1, 2, 2, 3, 3, 4, 4, 4, 4 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class PrimesSequenceTests
{
[Test]
public void First10ElementsCorrect()
{
var sequence = new PrimesSequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class PrimorialNumbersSequenceTests
{
[Test]
public void First10ElementsCorrect()
{
var sequence = new PrimorialNumbersSequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[]
{ 1, 2, 6, 30, 210, 2310, 30030, 510510, 9699690, 223092870 })
.Should().BeTrue();
}
}
}
| 21 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class RecamansSequenceTests
{
[Test]
public void First50ElementsCorrect()
{
// Taken from http://oeis.org/A005132
var expected = new BigInteger[]
{
0, 1, 3, 6, 2, 7, 13, 20, 12, 21,
11, 22, 10, 23, 9, 24, 8, 25, 43, 62,
42, 63, 41, 18, 42, 17, 43, 16, 44, 15,
45, 14, 46, 79, 113, 78, 114, 77, 39, 78,
38, 79, 37, 80, 36, 81, 35, 82, 34, 83,
};
var sequence = new RecamansSequence().Sequence.Take(50);
sequence.Should().Equal(expected);
}
}
}
| 30 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class SquaresSequenceTests
{
[Test]
public void First10ElementsCorrect()
{
var sequence = new SquaresSequence().Sequence.Take(10);
sequence.SequenceEqual(new BigInteger[] { 0, 1, 4, 9, 16, 25, 36, 49, 64, 81 })
.Should().BeTrue();
}
}
}
| 20 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences;
[TestFixture]
public class TetrahedralSequenceTests
{
private static readonly BigInteger[] TestList = {
0, 1, 4, 10, 20, 35, 56, 84, 120, 165, 220, 286, 364, 455,
560, 680, 816, 969, 1140, 1330, 1540, 1771, 2024, 2300,
2600, 2925, 3276, 3654, 4060, 4495, 4960, 5456, 5984, 6545,
7140, 7770, 8436, 9139, 9880, 10660, 11480, 12341, 13244,
14190, 15180,
};
/// <summary>
/// This test uses the list values provided from http://oeis.org/A000292/list.
/// </summary>
[Test]
public void TestOeisList()
{
var sequence = new TetrahedralSequence().Sequence.Take(TestList.Length);
sequence.SequenceEqual(TestList).Should().BeTrue();
}
}
| 31 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences;
public class TetranacciNumbersSequenceTests
{
[Test]
public void First35ElementsCorrect()
{
var sequence = new TetranacciNumbersSequence().Sequence.Take(35);
sequence.SequenceEqual(new BigInteger[]
{
1, 1, 1, 1, 4, 7, 13, 25, 49, 94, 181, 349, 673, 1297, 2500, 4819, 9289, 17905, 34513, 66526, 128233,
247177, 476449, 918385, 1770244, 3412255, 6577333, 12678217, 24438049, 47105854, 90799453, 175021573,
337364929, 650291809, 1253477764,
})
.Should().BeTrue();
}
}
| 24 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences {
public class ThreeNPlusOneStepsSequenceTests {
[Test]
public void First50ElementsCorrect() {
var sequence = new ThreeNPlusOneStepsSequence().Sequence.Take(50);
var first50 = new BigInteger[] {
0, 1, 7, 2, 5, 8, 16, 3, 19, 6,
14, 9, 9, 17, 17, 4, 12, 20, 20, 7,
7, 15, 15, 10, 23, 10, 111, 18, 18, 18,
106, 5, 26, 13, 13, 21, 21, 21, 34, 8,
109, 8, 29, 16, 16, 16, 104, 11, 24, 24
};
sequence.SequenceEqual(first50).Should().BeTrue();
}
}
}
| 23 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences;
public class TribonacciNumbersSequenceTests
{
[Test]
public void First37ElementsCorrect()
{
var sequence = new TribonacciNumbersSequence().Sequence.Take(37);
sequence.SequenceEqual(new BigInteger[]
{
1, 1, 1, 3, 5, 9, 17, 31, 57, 105, 193, 355, 653, 1201, 2209, 4063, 7473, 13745, 25281, 46499, 85525,
157305, 289329, 532159, 978793, 1800281, 3311233, 6090307, 11201821, 20603361, 37895489, 69700671,
128199521, 235795681, 433695873, 797691075, 1467182629,
})
.Should().BeTrue();
}
}
| 24 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class VanEcksSequenceTests
{
[Test]
public void First50ElementsCorrect()
{
// Taken from http://oeis.org/A181391
var expected = new BigInteger[]
{
0, 0, 1, 0, 2, 0, 2, 2, 1, 6,
0, 5, 0, 2, 6, 5, 4, 0, 5, 3,
0, 3, 2, 9, 0, 4, 9, 3, 6, 14,
0, 6, 3, 5, 15, 0, 5, 3, 5, 2,
17, 0, 6, 11, 0, 3, 8, 0, 3, 3,
};
var sequence = new VanEcksSequence().Sequence.Take(50);
sequence.Should().Equal(expected);
}
}
}
| 30 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using System.Numerics;
using Algorithms.Sequences;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Sequences
{
public class ZeroSequenceTests
{
[Test]
public void First10ElementsCorrect()
{
var sequence = new ZeroSequence().Sequence.Take(10);
sequence.SequenceEqual(Enumerable.Repeat(BigInteger.Zero, 10))
.Should().BeTrue();
}
}
}
| 21 |
C-Sharp | TheAlgorithms | C# | using Algorithms.Shufflers;
using Algorithms.Tests.Helpers;
using FluentAssertions;
using NUnit.Framework;
using System;
namespace Algorithms.Tests.Shufflers
{
public static class FisherYatesShufflerTests
{
[Test]
public static void ArrayShuffled_NewArrayHasSameSize(
[Random(10, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var shuffler = new FisherYatesShuffler<int>();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
shuffler.Shuffle(testArray);
// Assert
testArray.Length.Should().Be(correctArray.Length);
}
[Test]
public static void ArrayShuffled_NewArrayHasSameValues(
[Random(0, 100, 10, Distinct = true)]
int n)
{
// Arrange
var shuffler = new FisherYatesShuffler<int>();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
shuffler.Shuffle(testArray);
// Assert
testArray.Should().BeEquivalentTo(correctArray);
}
[Test]
public static void ArrayShuffled_SameShuffle(
[Random(0, 1000, 2, Distinct = true)] int n,
[Random(1000, 10000, 5, Distinct = true)] int seed)
{
// Arrange
var shuffler = new FisherYatesShuffler<int>();
var (array1, array2) = RandomHelper.GetArrays(n);
// Act
shuffler.Shuffle(array1, seed);
shuffler.Shuffle(array2, seed);
// Assert
array1.Should().BeEquivalentTo(array2, options => options.WithStrictOrdering());
}
[Test]
public static void ArrayShuffled_DifferentSeedDifferentShuffle(
[Random(10, 100, 2, Distinct = true)] int n,
[Random(1000, 10000, 5, Distinct = true)] int seed)
{
// Arrange
var shuffler = new FisherYatesShuffler<int>();
var (array1, array2) = RandomHelper.GetArrays(n);
// Act
shuffler.Shuffle(array1, seed);
shuffler.Shuffle(array2, seed + 13);
// It seems the actual version of FluentAssertion has no options in NotBeEquivalentTo.
// With default options, it does not check for order, but for the same elements in the collection.
// So until the library is updated check that not all the items have the same order.
int hits = 0;
for (int i = 0; i < n; i++)
{
if (array1[i] == array2[i])
{
hits++;
}
}
hits.Should().BeLessThan(array2.Length);
}
}
}
| 88 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class BinaryInsertionSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new BinaryInsertionSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class BogoSorterTests
{
[Test]
public static void ArraySorted([Random(0, 10, 10, Distinct = true)] int n)
{
// Arrange
var sorter = new BogoSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
}
}
| 27 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class BubbleSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new BubbleSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class CocktailSorterTests
{
[Test]
public static void SortsArray(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new CocktailSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray);
// Assert
Assert.AreEqual(correctArray, testArray);
}
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class CombSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new CombSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
[Test]
public static void ArraySorted_WithCustomShrinkFactor(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new CombSorter<int>(1.5);
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
}
}
| 47 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class CycleSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new CycleSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray);
// Assert
Assert.AreEqual(correctArray, testArray);
}
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class ExchangeSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new ExchangeSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class HeapSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new HeapSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray);
// Assert
Assert.AreEqual(correctArray, testArray);
}
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class InsertionSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new InsertionSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class MedianOfThreeQuickSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new MedianOfThreeQuickSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
/// <summary>
/// Class for testing merge sorter algorithm.
/// </summary>
public static class MergeSorterTests
{
[Test]
public static void TestOnMergeSorter(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new MergeSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray);
// Assert
Assert.AreEqual(correctArray, testArray);
}
}
}
| 32 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class MiddlePointQuickSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new MiddlePointQuickSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class PancakeSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new PancakeSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class RandomPivotQuickSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new RandomPivotQuickSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class SelectionSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new SelectionSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class ShellSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new ShellSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
}
}
| 29 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Linq;
using Algorithms.Sorters.Comparison;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Comparison
{
public static class TimSorterTests
{
private static readonly IntComparer IntComparer = new();
[Test]
public static void ArraySorted(
[Random(0, 10_000, 2000)] int n)
{
// Arrange
var sorter = new TimSorter<int>();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray, IntComparer);
Array.Sort(correctArray, IntComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
[Test]
public static void TinyArray()
{
// Arrange
var sorter = new TimSorter<int>();
var tinyArray = new[] { 1 };
var correctArray = new[] { 1 };
// Act
sorter.Sort(tinyArray, IntComparer);
// Assert
Assert.AreEqual(tinyArray, correctArray);
}
[Test]
public static void SmallChunks()
{
// Arrange
var sorter = new TimSorter<int>();
var (correctArray, testArray) = RandomHelper.GetArrays(800);
Array.Sort(correctArray, IntComparer);
Array.Sort(testArray, IntComparer);
var max = testArray.Max();
var min = testArray.Min();
correctArray[0] = max;
correctArray[800-1] = min;
testArray[0] = max;
testArray[800 - 1] = min;
// Act
sorter.Sort(testArray, IntComparer);
Array.Sort(correctArray, IntComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
}
}
| 70 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.External;
using Algorithms.Sorters.External.Storages;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
using NUnit.Framework.Internal;
namespace Algorithms.Tests.Sorters.External
{
public static class ExternalMergeSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new ExternalMergeSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
var main = new IntInMemoryStorage(testArray);
var temp = new IntInMemoryStorage(new int[testArray.Length]);
// Act
sorter.Sort(main, temp, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
Assert.AreEqual(testArray, correctArray);
}
[Test]
public static void ArraySorted_OnDisk(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new ExternalMergeSorter<int>();
var intComparer = new IntComparer();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
var randomizer = Randomizer.CreateRandomizer();
var main = new IntFileStorage($"sorted_{randomizer.GetString(100)}", n);
var temp = new IntFileStorage($"temp_{randomizer.GetString(100)}", n);
var writer = main.GetWriter();
for (var i = 0; i < n; i++)
{
writer.Write(correctArray[i]);
}
writer.Dispose();
// Act
sorter.Sort(main, temp, intComparer);
Array.Sort(correctArray, intComparer);
// Assert
var reader = main.GetReader();
for (var i = 0; i < n; i++)
{
testArray[i] = reader.Read();
}
Assert.AreEqual(testArray, correctArray);
}
}
}
| 68 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Integer;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Integer
{
public static class BucketSorterTests
{
[Test]
public static void ArraySorted(
[Random(0, 1000, 1000, Distinct = true)]
int n)
{
// Arrange
var sorter = new BucketSorter();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray);
Array.Sort(correctArray);
// Assert
Assert.AreEqual(correctArray, testArray);
}
}
}
| 28 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Integer;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Integer
{
public static class CountingSorterTests
{
[Test]
public static void SortsNonEmptyArray(
[Random(1, 10000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new CountingSorter();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray);
Array.Sort(correctArray);
// Assert
Assert.AreEqual(correctArray, testArray);
}
[Test]
public static void SortsEmptyArray()
{
var sorter = new CountingSorter();
sorter.Sort(Array.Empty<int>());
}
}
}
| 35 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.Integer;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.Integer
{
public static class RadixSorterTests
{
[Test]
public static void SortsArray(
[Random(0, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new RadixSorter();
var (correctArray, testArray) = RandomHelper.GetArrays(n);
// Act
sorter.Sort(testArray);
Array.Sort(correctArray);
// Assert
Assert.AreEqual(correctArray, testArray);
}
}
}
| 28 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Sorters.String;
using Algorithms.Tests.Helpers;
using NUnit.Framework;
namespace Algorithms.Tests.Sorters.String
{
/// <summary>
/// Class for testing MSD radix sorter algorithm.
/// </summary>
public static class MsdRadixStringSorterTests
{
[Test]
public static void ArraySorted(
[Random(2, 1000, 100, Distinct = true)]
int n)
{
// Arrange
var sorter = new MsdRadixStringSorter();
var (correctArray, testArray) = RandomHelper.GetStringArrays(n, 100, false);
// Act
sorter.Sort(testArray);
Array.Sort(correctArray);
// Assert
Assert.AreEqual(correctArray, testArray);
}
}
}
| 31 |
C-Sharp | TheAlgorithms | C# | using Algorithms.Strings;
using NUnit.Framework;
namespace Algorithms.Tests.Strings
{
public class BoyerMooreTests
{
[TestCase("HelloImATestcaseAndIWillPass", "Testcase", 8)]
[TestCase("HelloImATestcaseAndImCaseSensitive", "TestCase", -1)]
[TestCase("Hello Im a testcase and I work with whitespaces", "testcase", 11)]
[TestCase("Hello Im a testcase and I work with numbers like 1 2 3 4", "testcase", 11)]
public void FindFirstOccurrence_IndexCheck(string t, string p, int expectedIndex)
{
var resultIndex = BoyerMoore.FindFirstOccurrence(t, p);
Assert.AreEqual(resultIndex, expectedIndex);
}
}
}
| 19 |
C-Sharp | TheAlgorithms | C# | using System;
using Algorithms.Strings;
using NUnit.Framework;
namespace Algorithms.Tests.Strings
{
public static class GeneralStringAlgorithmsTests
{
[Test]
[TestCase("Griffith", 'f', 2)]
[TestCase("Randomwoooord", 'o', 4)]
[TestCase("Control", 'C', 1)]
public static void MaxCountCharIsObtained(string text, char expectedSymbol, int expectedCount)
{
// Arrange
// Act
var (symbol, count) = GeneralStringAlgorithms.FindLongestConsecutiveCharacters(text);
// Assert
Assert.AreEqual(expectedSymbol, symbol);
Assert.AreEqual(expectedCount, count);
}
}
}
| 25 |
C-Sharp | TheAlgorithms | C# | using Algorithms.Strings;
using NUnit.Framework;
using System;
namespace Algorithms.Tests.Strings
{
public class HammingDistanceTests
{
[Test]
[TestCase("equal", "equal", 0)]
[TestCase("dog", "dig", 1)]
[TestCase("12345", "abcde", 5)]
public void Calculate_ReturnsCorrectHammingDistance(string s1, string s2, int expectedDistance)
{
var result = HammingDistance.Calculate(s1, s2);
Assert.AreEqual(expectedDistance, result);
}
[Test]
public void Calculate_ThrowsArgumentExceptionWhenStringLengthsDiffer()
{
Assert.Throws<ArgumentException>(() => HammingDistance.Calculate("123", "12345"));
}
}
}
| 26 |
C-Sharp | TheAlgorithms | C# | using Algorithms.Strings;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Strings
{
public class JaroSimilarityTests
{
[Test]
[TestCase("equal", "equal", 1)]
[TestCase("abc", "123", 0)]
[TestCase("FAREMVIEL", "FARMVILLE", 0.88d)]
[TestCase("CRATE", "TRACE", 0.73d)]
[TestCase("CRATE11111", "CRTAE11111", 0.96d)]
[TestCase("a", "a", 1)]
[TestCase("", "", 1)]
public void Calculate_ReturnsCorrectJaroSimilarity(string s1, string s2, double expected)
{
JaroSimilarity.Calculate(s1, s2).Should().BeApproximately(expected, 0.01);
}
}
}
| 23 |
C-Sharp | TheAlgorithms | C# | using Algorithms.Strings;
using FluentAssertions;
using NUnit.Framework;
namespace Algorithms.Tests.Strings
{
public class JaroWinklerDistanceTests
{
[Test]
[TestCase("equal", "equal", 0)]
[TestCase("abc", "123", 1)]
[TestCase("Winkler", "Welfare", 0.33)]
[TestCase("faremviel", "farmville", 0.08)]
[TestCase("", "", 0)]
public void Calculate_ReturnsCorrectJaroWinklerDistance(string s1, string s2, double expected)
{
JaroWinklerDistance.Calculate(s1, s2).Should().BeApproximately(expected, 0.01);
}
}
}
| 21 |
C-Sharp | TheAlgorithms | C# | using Algorithms.Strings;
using NUnit.Framework;
namespace Algorithms.Tests.Strings
{
public static class KnuthMorrisPrattSearcherTests
{
[Test]
public static void FindIndexes_ItemsPresent_PassExpected()
{
// Arrange
var searcher = new KnuthMorrisPrattSearcher();
var str = "ABABAcdeABA";
var pat = "ABA";
// Act
var expectedItem = new[] { 0, 2, 8 };
var actualItem = searcher.FindIndexes(str, pat);
// Assert
CollectionAssert.AreEqual(expectedItem, actualItem);
}
[Test]
public static void FindIndexes_ItemsMissing_NoIndexesReturned()
{
// Arrange
var searcher = new KnuthMorrisPrattSearcher();
var str = "ABABA";
var pat = "ABB";
// Act & Assert
var indexes = searcher.FindIndexes(str, pat);
// Assert
Assert.IsEmpty(indexes);
}
[Test]
public static void LongestPrefixSuffixArray_PrefixSuffixOfLength1_PassExpected()
{
// Arrange
var searcher = new KnuthMorrisPrattSearcher();
var s = "ABA";
// Act
var expectedItem = new[] { 0, 0, 1 };
var actualItem = searcher.FindLongestPrefixSuffixValues(s);
// Assert
CollectionAssert.AreEqual(expectedItem, actualItem);
}
[Test]
public static void LongestPrefixSuffixArray_PrefixSuffixOfLength5_PassExpected()
{
// Arrange
var searcher = new KnuthMorrisPrattSearcher();
var s = "AABAACAABAA";
// Act
var expectedItem = new[] { 0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5 };
var actualItem = searcher.FindLongestPrefixSuffixValues(s);
// Assert
CollectionAssert.AreEqual(expectedItem, actualItem);
}
[Test]
public static void LongestPrefixSuffixArray_PrefixSuffixOfLength0_PassExpected()
{
// Arrange
var searcher = new KnuthMorrisPrattSearcher();
var s = "AB";
// Act
var expectedItem = new[] { 0, 0 };
var actualItem = searcher.FindLongestPrefixSuffixValues(s);
// Assert
CollectionAssert.AreEqual(expectedItem, actualItem);
}
}
}
| 85 |
C-Sharp | TheAlgorithms | C# | using Algorithms.Strings;
using NUnit.Framework;
namespace Algorithms.Tests.Strings
{
public class LevenshteinDistanceTests
{
[Test]
[TestCase("kitten", "sitting", 3)]
[TestCase("bob", "bond", 2)]
[TestCase("algorithm", "logarithm", 3)]
[TestCase("star", "", 4)]
[TestCase("", "star", 4)]
[TestCase("abcde", "12345", 5)]
public void Calculate_ReturnsCorrectLevenshteinDistance(string source, string destination, int expectedDistance)
{
var result = LevenshteinDistance.Calculate(source, destination);
Assert.AreEqual(expectedDistance, result);
}
}
}
| 22 |
C-Sharp | TheAlgorithms | C# | using System.Linq;
using Algorithms.Strings;
using NUnit.Framework;
namespace Algorithms.Tests.Strings
{
public static class NaiveStringSearchTests
{
[Test]
public static void ThreeMatchesFound_PassExpected()
{
// Arrange
var pattern = "ABB";
var content = "ABBBAAABBAABBBBAB";
// Act
var expectedOccurrences = new[] { 0, 6, 10 };
var actualOccurrences = NaiveStringSearch.NaiveSearch(content, pattern);
var sequencesAreEqual = expectedOccurrences.SequenceEqual(actualOccurrences);
// Assert
Assert.IsTrue(sequencesAreEqual);
}
[Test]
public static void OneMatchFound_PassExpected()
{
// Arrange
var pattern = "BAAB";
var content = "ABBBAAABBAABBBBAB";
// Act
var expectedOccurrences = new[] { 8 };
var actualOccurrences = NaiveStringSearch.NaiveSearch(content, pattern);
var sequencesAreEqual = expectedOccurrences.SequenceEqual(actualOccurrences);
// Assert
Assert.IsTrue(sequencesAreEqual);
}
[Test]
public static void NoMatchFound_PassExpected()
{
// Arrange
var pattern = "XYZ";
var content = "ABBBAAABBAABBBBAB";
// Act
var expectedOccurrences = new int[0];
var actualOccurrences = NaiveStringSearch.NaiveSearch(content, pattern);
var sequencesAreEqual = expectedOccurrences.SequenceEqual(actualOccurrences);
// Assert
Assert.IsTrue(sequencesAreEqual);
}
}
}
| 58 |
C-Sharp | TheAlgorithms | C# | using Algorithms.Strings;
using NUnit.Framework;
namespace Algorithms.Tests.Strings
{
public static class PalindromeTests
{
[Test]
[TestCase("Anna")]
[TestCase("A Santa at Nasa")]
public static void TextIsPalindrome_TrueExpected(string text)
{
// Arrange
// Act
var isPalindrome = Palindrome.IsStringPalindrome(text);
// Assert
Assert.True(isPalindrome);
}
[Test]
[TestCase("hallo")]
[TestCase("Once upon a time")]
public static void TextNotPalindrome_FalseExpected(string text)
{
// Arrange
// Act
var isPalindrome = Palindrome.IsStringPalindrome(text);
// Assert
Assert.False(isPalindrome);
}
}
}
| 35 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using Algorithms.Numeric;
using Algorithms.Strings;
using NUnit.Framework;
namespace Algorithms.Tests.Strings
{
public class PermutationTests
{
[TestCase("")]
[TestCase("A")]
[TestCase("abcd")]
[TestCase("aabcd")]
[TestCase("aabbbcd")]
[TestCase("aabbccccd")]
public void Test_GetEveryUniquePermutation(string word)
{
var permutations = Permutation.GetEveryUniquePermutation(word);
// We need to make sure that
// 1. We have the right number of permutations
// 2. Every string in permutations List is a permutation of word
// 3. There are no repetitions
// Start 1.
// The number of unique permutations is
// n!/(A1! * A2! * ... An!)
// where n is the length of word and Ai is the number of occurrences if ith char in the string
var charOccurrence = new Dictionary<char, int>();
foreach (var c in word)
{
if (charOccurrence.ContainsKey(c))
{
charOccurrence[c] += 1;
}
else
{
charOccurrence[c] = 1;
}
}
// now we know the values of A1, A2, ..., An
// evaluate the above formula
var expectedNumberOfAnagrams = Factorial.Calculate(word.Length);
expectedNumberOfAnagrams = charOccurrence.Aggregate(expectedNumberOfAnagrams, (current, keyValuePair) =>
{
return current / Factorial.Calculate(keyValuePair.Value);
});
Assert.AreEqual(expectedNumberOfAnagrams, new BigInteger(permutations.Count));
// End 1.
// Start 2
// string A is a permutation of string B if and only if sorted(A) == sorted(b)
var wordSorted = SortString(word);
foreach (var permutation in permutations)
{
Assert.AreEqual(wordSorted, SortString(permutation));
}
// End 2
// Start 3
Assert.AreEqual(permutations.Count, new HashSet<string>(permutations).Count);
// End 3
}
private static string SortString(string word)
{
var asArray = word.ToArray();
Array.Sort(asArray);
return new string(asArray);
}
}
}
| 76 |
C-Sharp | TheAlgorithms | C# | using System.Collections.Generic;
using Algorithms.Strings;
using NUnit.Framework;
namespace Algorithms.Tests.Strings
{
public class RabinKarpTest
{
[TestCase("HelloImATestcaseAndIWillPass", "Testcase", new[] { 8 })]
[TestCase("HelloImATestcaseAndImCaseSensitive", "TestCase", new int[] { })]
[TestCase("Hello Im a testcase and you can use whitespaces", "testcase", new[] { 11 })]
[TestCase("Hello Im a testcase and you can use numbers like 1, 2, 3, etcetera", "etcetera", new[] { 58 })]
[TestCase("HelloImATestcaseAndIHaveTwoOccurrencesOfTestcase", "Testcase", new[] { 8, 40 })]
public void FindAllOccurrences_IndexCheck(string t, string p, int[] expectedIndices)
{
List<int> result = RabinKarp.FindAllOccurrences(t, p);
Assert.AreEqual(result, new List<int>(expectedIndices));
}
}
}
| 21 |
C-Sharp | TheAlgorithms | C# | using Algorithms.Strings;
using NUnit.Framework;
namespace Algorithms.Tests.Strings
{
public class ZblockSubstringSearchTest
{
[TestCase("abc", "abcdef", 1)]
[TestCase("xxx", "abxxxcdexxxf", 2)]
[TestCase("aa", "waapaaxcdaalaabb", 4)]
[TestCase("ABC", "ABAAABCDBBABCDDEBCABC", 3)]
[TestCase("xxx", "abcdefghij", 0)]
[TestCase("aab", "caabxaaaz", 1)]
[TestCase("abc", "xababaxbabcdabx", 1)]
[TestCase("GEEK", "GEEKS FOR GEEKS", 2)]
[TestCase("ground", "Hello, playground!", 1)]
public void Test(string pattern, string text, int expectedOccurences)
{
var occurencesFound = ZblockSubstringSearch.FindSubstring(pattern, text);
Assert.AreEqual(expectedOccurences, occurencesFound);
}
}
}
| 24 |
C-Sharp | TheAlgorithms | C# | // Original Author: Christian Bender
// Class: BitArray
//
// implements IComparable, ICloneable, IEnumerator, IEnumerable
//
// This class implements a bit-array and provides some
// useful functions/operations to deal with this type of
// data structure. You see a overview about the functionality, below.
//
//
// Overview
//
// Constructor (N : int)
// The constructor receives a length (N) of the to create bit-field.
//
// Constructor (sequence : string)
// setups the array with the input sequence.
// assumes: the sequence may only be allowed contains onese or zeros.
//
// Constructor (bits : bool[] )
// setups the bit-field with the input array.
//
// Compile(sequence : string)
// compiles a string sequence of 0's and 1's in the inner structure.
// assumes: the sequence may only be allowed contains onese or zeros.
//
// Compile (number : int)
// compiles a positive integer number in the inner data structure.
//
// Compile (number : long)
// compiles a positive long integer number in the inner data structure.
//
// ToString ()
// returns a string representation of the inner structure.
// The returned string is a sequence of 0's and 1's.
//
// Length : int
// Is a property that returns the length of the bit-field.
//
// Indexer : bool
// indexer for selecting the individual bits of the bit array.
//
// NumberOfOneBits() : int
// returns the number of One-bits.
//
// NumberOfZeroBits() : int
// returns the number of Zero-Bits.
//
// EvenParity() : bool
// returns true if parity is even, otherwise false.
//
// OddParity() : bool
// returns true if parity is odd, otherwise false.
//
// ToInt64() : long
// returns a long integer representation of the bit-array.
// assumes: the bit-array length must been smaller or equal to 64 bit.
//
// ToInt32() : int
// returns a integer representation of the bit-array.
// assumes: the bit-array length must been smaller or equal to 32 bit.
//
// ResetField() : void
// sets all bits on false.
//
// SetAll(flag : bool) : void
// sets all bits on the value of the flag.
//
// GetHashCode() : int
// returns hash-code (ToInt32())
//
// Equals (other : Object) : bool
// returns true if there inputs are equal otherwise false.
// assumes: the input bit-arrays must have same length.
//
// CompareTo (other : Object) : int (interface IComparable)
// output: 0 - if the bit-arrays a equal.
// -1 - if this bit-array is smaller.
// 1 - if this bit-array is greater.
// assumes: bit-array lentgh must been smaller or equal to 64 bit
//
// Clone () : object
// returns a copy of this bit-array
//
// Current : object
// returns the current selected bit.
//
// MoveNext() : bool
// purpose: increases the position of the enumerator
// returns true if 'position' successful increased otherwise false.
//
// Reset() : void
// resets the position of the enumerator.
//
// GetEnumerator() : IEnumerator
// returns a enumerator for this BitArray-object.
//
// Operations:
//
// & bitwise AND
// | bitwise OR
// ~ bitwise NOT
// >> bitwise shift right
// >> bitwise shift left
// ^ bitwise XOR
//
// Each operation (above) returns a new BitArray-object.
//
// == equal operator. : bool
// returns true if there inputs are equal otherwise false.
// assumes: the input bit-arrays must have same length.
//
// != not-equal operator : bool
// returns true if there inputs aren't equal otherwise false.
// assumes: the input bit-arrays must have same length.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DataStructures
{
/// <summary>
/// This class implements a bit-array and provides some
/// useful functions/operations to deal with this type of
/// data structure.
/// </summary>
public sealed class BitArray : ICloneable, IEnumerator<bool>, IEnumerable<bool>
{
private readonly bool[] field; // the actual bit-field
private int position = -1; // position for enumerator
/// <summary>
/// Initializes a new instance of the <see cref="BitArray" /> class.
/// setups the array with false-values.
/// </summary>
/// <param name="n">length of the array.</param>
public BitArray(int n)
{
if (n < 1)
{
field = new bool[0];
}
field = new bool[n];
}
/// <summary>
/// Initializes a new instance of the <see cref="BitArray" /> class.
/// Setups the array with the input sequence.
/// purpose: Setups the array with the input sequence.
/// assumes: sequence must been greater or equal to 1.
/// the sequence may only contain ones or zeros.
/// </summary>
/// <param name="sequence">A string sequence of 0's and 1's.</param>
public BitArray(string sequence)
{
// precondition I
if (sequence.Length <= 0)
{
throw new ArgumentException("Sequence must been greater than or equal to 1");
}
// precondition II
ThrowIfSequenceIsInvalid(sequence);
field = new bool[sequence.Length];
Compile(sequence);
}
/// <summary>
/// Initializes a new instance of the <see cref="BitArray" /> class.
/// Setups the bit-array with the input array.
/// </summary>
/// <param name="bits">A boolean array of bits.</param>
public BitArray(bool[] bits) => field = bits;
/// <summary>
/// Gets the length of the current bit array.
/// </summary>
private int Length => field.Length;
/// <summary>
/// Gets element given an offset.
/// </summary>
/// <param name="offset">Position.</param>
/// <returns>Element on array.</returns>
public bool this[int offset]
{
get => field[offset];
private set => field[offset] = value;
}
/// <summary>
/// Returns a copy of the current bit-array.
/// </summary>
/// <returns>Bit-array clone.</returns>
public object Clone()
{
var theClone = new BitArray(Length);
for (var i = 0; i < Length; i++)
{
theClone[i] = field[i];
}
return theClone;
}
/// <summary>
/// Gets a enumerator for this BitArray-Object.
/// </summary>
/// <returns>Returns a enumerator for this BitArray-Object.</returns>
public IEnumerator<bool> GetEnumerator() => this;
/// <summary>
/// Gets a enumerator for this BitArray-Object.
/// </summary>
/// <returns>Returns a enumerator for this BitArray-Object.</returns>
IEnumerator IEnumerable.GetEnumerator() => this;
/// <summary>
/// Gets a value indicating whether the current bit of the array is set.
/// </summary>
public bool Current => field[position];
/// <summary>
/// Gets a value indicating whether the current bit of the array is set.
/// </summary>
object IEnumerator.Current => field[position];
/// <summary>
/// MoveNext (for interface IEnumerator).
/// </summary>
/// <returns>Returns True if 'position' successful increased; False otherwise.</returns>
public bool MoveNext()
{
if (position + 1 >= field.Length)
{
return false;
}
position++;
return true;
}
/// <summary>
/// Resets the position of the enumerator.
/// Reset (for interface IEnumerator).
/// </summary>
public void Reset() => position = -1;
/// <summary>
/// Disposes object, nothing to dispose here though.
/// </summary>
public void Dispose()
{
// Done
}
/// <summary>
/// Returns a bit-array that represents the bit by bit AND (&).
/// Assumes arrays have the same length.
/// </summary>
/// <param name="one">First bit-array.</param>
/// <param name="two">Second bit-array.</param>
/// <returns>bit-array.</returns>
public static BitArray operator &(BitArray one, BitArray two)
{
var sequence1 = one.ToString();
var sequence2 = two.ToString();
var result = new StringBuilder();
var tmp = new StringBuilder();
// for scaling of same length.
if (one.Length != two.Length)
{
int difference;
if (one.Length > two.Length)
{
// one is greater
difference = one.Length - two.Length;
// fills up with 0's
for (var i = 0; i < difference; i++)
{
tmp.Append('0');
}
tmp.Append(two);
sequence2 = tmp.ToString();
}
else
{
// two is greater
difference = two.Length - one.Length;
// fills up with 0's
for (var i = 0; i < difference; i++)
{
tmp.Append('0');
}
tmp.Append(one);
sequence1 = tmp.ToString();
}
} // end scaling
var len = one.Length > two.Length ? one.Length : two.Length;
var ans = new BitArray(len);
for (var i = 0; i < one.Length; i++)
{
result.Append(sequence1[i].Equals('1') && sequence2[i].Equals('1') ? '1' : '0');
}
ans.Compile(result.ToString().Trim());
return ans;
}
/// <summary>
/// Returns a bit-array that represents the bit by bit OR.
/// Assumes arrays have the same length.
/// </summary>
/// <param name="one">First bit-array.</param>
/// <param name="two">Second bit-array.</param>
/// <returns>bit-array that represents the bit by bit OR.</returns>
public static BitArray operator |(BitArray one, BitArray two)
{
var sequence1 = one.ToString();
var sequence2 = two.ToString();
var result = string.Empty;
var tmp = string.Empty;
// for scaling of same length.
if (one.Length != two.Length)
{
int difference;
if (one.Length > two.Length)
{
// one is greater
difference = one.Length - two.Length;
// fills up with 0's
for (var i = 0; i < difference; i++)
{
tmp += '0';
}
tmp += two.ToString();
sequence2 = tmp;
}
else
{
// two is greater
difference = two.Length - one.Length;
// fills up with 0's
for (var i = 0; i < difference; i++)
{
tmp += '0';
}
tmp += one.ToString();
sequence1 = tmp;
}
} // end scaling
var len = one.Length > two.Length ? one.Length : two.Length;
var ans = new BitArray(len);
for (var i = 0; i < len; i++)
{
result += sequence1[i].Equals('0') && sequence2[i].Equals('0') ? '0' : '1';
}
result = result.Trim();
ans.Compile(result);
return ans;
}
/// <summary>
/// Returns a bit-array that represents the operator ~ (NOT).
/// Assumes arrays have the same length.
/// </summary>
/// <param name="one">Bit-array.</param>
/// <returns>bitwise not.</returns>
public static BitArray operator ~(BitArray one)
{
var ans = new BitArray(one.Length);
var sequence = one.ToString();
var result = string.Empty;
foreach (var ch in sequence)
{
if (ch == '1')
{
result += '0';
}
else
{
result += '1';
}
}
result = result.Trim();
ans.Compile(result);
return ans;
}
/// <summary>
/// Returns a bit-array that represents bitwise shift left (>>).
/// Assumes arrays have the same length.
/// </summary>
/// <param name="other">Bit-array.</param>
/// <param name="n">Number of bits.</param>
/// <returns>Bitwise shifted BitArray.</returns>
public static BitArray operator <<(BitArray other, int n)
{
var ans = new BitArray(other.Length + n);
// actual shifting process
for (var i = 0; i < other.Length; i++)
{
ans[i] = other[i];
}
return ans;
}
/// <summary>
/// Returns a bit-array that represents the bit by bit XOR.
/// Assumes arrays have the same length.
/// </summary>
/// <param name="one">First bit-array.</param>
/// <param name="two">Second bit-array.</param>
/// <returns>bit-array.</returns>
public static BitArray operator ^(BitArray one, BitArray two)
{
var sequence1 = one.ToString();
var sequence2 = two.ToString();
var tmp = string.Empty;
// for scaling of same length.
if (one.Length != two.Length)
{
int difference;
if (one.Length > two.Length)
{
// one is greater
difference = one.Length - two.Length;
// fills up with 0's
for (var i = 0; i < difference; i++)
{
tmp += '0';
}
tmp += two.ToString();
sequence2 = tmp;
}
else
{
// two is greater
difference = two.Length - one.Length;
// fills up with 0's
for (var i = 0; i < difference; i++)
{
tmp += '0';
}
tmp += one.ToString();
sequence1 = tmp;
}
} // end scaling
var len = one.Length > two.Length ? one.Length : two.Length;
var ans = new BitArray(len);
var sb = new StringBuilder();
for (var i = 0; i < len; i++)
{
_ = sb.Append(sequence1[i] == sequence2[i] ? '0' : '1');
}
var result = sb.ToString().Trim();
ans.Compile(result);
return ans;
}
/// <summary>
/// Returns a bit-array that represents bitwise shift right (>>).
/// Assumes arrays have the same length.
/// </summary>
/// <param name="other">Bit-array.</param>
/// <param name="n">Number of bits.</param>
/// <returns>Bitwise shifted BitArray.</returns>
public static BitArray operator >>(BitArray other, int n)
{
var ans = new BitArray(other.Length - n);
// actual shifting process.
for (var i = 0; i < other.Length - n; i++)
{
ans[i] = other[i];
}
return ans;
}
/// <summary>
/// Checks if both arrays are == (equal).
/// The input assumes arrays have the same length.
/// </summary>
/// <param name="one">First bit-array.</param>
/// <param name="two">Second bit-array.</param>
/// <returns>Returns True if there inputs are equal; False otherwise.</returns>
public static bool operator ==(BitArray one, BitArray two)
{
if (ReferenceEquals(one, two))
{
return true;
}
if (one.Length != two.Length)
{
return false;
}
var status = true;
for (var i = 0; i < one.Length; i++)
{
if (one[i] != two[i])
{
status = false;
break;
}
}
return status;
}
/// <summary>
/// Checks if both arrays are != (not-equal).
/// The input assumes arrays have the same length.
/// </summary>
/// <param name="one">First bit-array.</param>
/// <param name="two">Second bit-array.</param>
/// <returns>Returns True if there inputs aren't equal; False otherwise.</returns>
public static bool operator !=(BitArray one, BitArray two) => !(one == two);
/// <summary>
/// Compiles the binary sequence into the inner data structure.
/// The sequence must have the same length, as the bit-array.
/// The sequence may only be allowed contains ones or zeros.
/// </summary>
/// <param name="sequence">A string sequence of 0's and 1's.</param>
public void Compile(string sequence)
{
// precondition I
if (sequence.Length > field.Length)
{
throw new ArgumentException($"{nameof(sequence)} must be not longer than the bit array length");
}
// precondition II
ThrowIfSequenceIsInvalid(sequence);
// for appropriate scaling
var tmp = string.Empty;
if (sequence.Length < field.Length)
{
var difference = field.Length - sequence.Length;
for (var i = 0; i < difference; i++)
{
tmp += '0';
}
tmp += sequence;
sequence = tmp;
}
// actual compile procedure.
for (var i = 0; i < sequence.Length; i++)
{
field[i] = sequence[i] == '1';
}
}
/// <summary>
/// Compiles integer number into the inner data structure.
/// Assumes: the number must have the same bit length.
/// </summary>
/// <param name="number">A positive integer number.</param>
public void Compile(int number)
{
var tmp = string.Empty;
// precondition I
if (number <= 0)
{
throw new ArgumentException($"{nameof(number)} must be positive");
}
// converts to binary representation
var binaryNumber = Convert.ToString(number, 2);
// precondition II
if (binaryNumber.Length > field.Length)
{
throw new ArgumentException("Provided number is too big");
}
// for appropriate scaling
if (binaryNumber.Length < field.Length)
{
var difference = field.Length - binaryNumber.Length;
for (var i = 0; i < difference; i++)
{
tmp += '0';
}
tmp += binaryNumber;
binaryNumber = tmp;
}
// actual compile procedure.
for (var i = 0; i < binaryNumber.Length; i++)
{
field[i] = binaryNumber[i] == '1';
}
}
/// <summary>
/// Compiles integer number into the inner data structure.
/// The number must have the same bit length.
/// </summary>
/// <param name="number">A positive long integer number.</param>
public void Compile(long number)
{
var tmp = string.Empty;
// precondition I
if (number <= 0)
{
throw new ArgumentException($"{nameof(number)} must be positive");
}
// converts to binary representation
var binaryNumber = Convert.ToString(number, 2);
// precondition II
if (binaryNumber.Length > field.Length)
{
throw new ArgumentException("Provided number is too big");
}
// for appropriate scaling
if (binaryNumber.Length < field.Length)
{
var difference = field.Length - binaryNumber.Length;
for (var i = 0; i < difference; i++)
{
tmp += '0';
}
tmp += binaryNumber;
binaryNumber = tmp;
}
// actual compile procedure.
for (var i = 0; i < binaryNumber.Length; i++)
{
field[i] = binaryNumber[i] == '1';
}
}
/// <summary>
/// Is the opposit of the Compile(...) method.
/// </summary>
/// <returns>Returns a string representation of the inner data structure.</returns>
public override string ToString()
{
// creates return-string
return field.Aggregate(string.Empty, (current, t) => current + (t ? "1" : "0"));
}
/// <summary>
/// Gets the number of one-bits in the field.
/// </summary>
/// <returns>quantity of bits in current bit-array.</returns>
public int NumberOfOneBits()
{
// counting one-bits.
return field.Count(bit => bit);
}
/// <summary>
/// Gets the number of zero-bits in the field.
/// </summary>
/// <returns>quantity of bits.</returns>
public int NumberOfZeroBits()
{
// counting zero-bits
return field.Count(bit => !bit);
}
/// <summary>
/// To check for even parity.
/// </summary>
/// <returns>Returns True if parity is even; False otherwise.</returns>
public bool EvenParity() => NumberOfOneBits() % 2 == 0;
/// <summary>
/// To check for odd parity.
/// </summary>
/// <returns>Returns True if parity is odd; False otherwise.</returns>
public bool OddParity() => NumberOfOneBits() % 2 != 0;
/// <summary>
/// Returns a long integer representation of the bit-array.
/// Assumes the bit-array length must been smaller or equal to 64 bit.
/// </summary>
/// <returns>Long integer array.</returns>
public long ToInt64()
{
// Precondition
if (field.Length > 64)
{
throw new InvalidOperationException("Value is too big to fit into Int64");
}
var sequence = ToString();
return Convert.ToInt64(sequence, 2);
}
/// <summary>
/// Returns a long integer representation of the bit-array.
/// Assumes the bit-array length must been smaller or equal to 32 bit.
/// </summary>
/// <returns>integer array.</returns>
public int ToInt32()
{
// Precondition
if (field.Length > 32)
{
throw new InvalidOperationException("Value is too big to fit into Int32");
}
var sequence = ToString();
return Convert.ToInt32(sequence, 2);
}
/// <summary>
/// Sets all bits on false.
/// </summary>
public void ResetField()
{
for (var i = 0; i < field.Length; i++)
{
field[i] = false;
}
}
/// <summary>
/// Sets all bits on the value of the flag.
/// </summary>
/// <param name="flag">Bollean flag (false-true).</param>
public void SetAll(bool flag)
{
for (var i = 0; i < field.Length; i++)
{
field[i] = flag;
}
}
/// <summary>
/// Checks if bit-array are equal.
/// Assumes the input bit-arrays must have same length.
/// </summary>
/// <param name="obj">Bit-array object.</param>
/// <returns>Returns true if there inputs are equal otherwise false.</returns>
public override bool Equals(object? obj)
{
if (obj is null)
{
return false;
}
var otherBitArray = (BitArray)obj;
if (Length != otherBitArray.Length)
{
return false;
}
for (var i = 0; i < Length; i++)
{
if (field[i] != otherBitArray[i])
{
return false;
}
}
return true;
}
/// <summary>
/// Gets has-code of bit-array.
/// Assumes bit-array length must been smaller or equal to 32.
/// </summary>
/// <returns>hash-code for this BitArray instance.</returns>
public override int GetHashCode() => ToInt32();
private static void ThrowIfSequenceIsInvalid(string sequence)
{
if (!Match(sequence))
{
throw new ArgumentException("The sequence may only contain ones or zeros");
}
}
/// <summary>
/// Utility method foir checking a given sequence contains only zeros and ones.
/// This method will used in Constructor (sequence : string) and Compile(sequence : string).
/// </summary>
/// <param name="sequence">String sequence.</param>
/// <returns>returns True if sequence contains only zeros and ones; False otherwise.</returns>
private static bool Match(string sequence) => sequence.All(ch => ch == '0' || ch == '1');
}
}
| 843 |
C-Sharp | TheAlgorithms | C# | using System.Collections.Generic;
using System.Linq;
namespace DataStructures
{
/// <summary>
/// Inverted index is the simplest form of document indexing,
/// allowing performing boolean queries on text data.
///
/// This realization is just simplified for better understanding the process of indexing
/// and working on straightforward string inputs.
/// </summary>
public class InvertedIndex
{
private readonly Dictionary<string, List<string>> invertedIndex = new();
/// <summary>
/// Build inverted index with source name and source content.
/// </summary>
/// <param name="sourceName">Name of the source.</param>
/// <param name="sourceContent">Content of the source.</param>
public void AddToIndex(string sourceName, string sourceContent)
{
var context = sourceContent.Split(' ').Distinct();
foreach (var word in context)
{
if (!invertedIndex.ContainsKey(word))
{
invertedIndex.Add(word, new List<string> { sourceName });
}
else
{
invertedIndex[word].Add(sourceName);
}
}
}
/// <summary>
/// Returns the source names contains ALL terms inside at same time.
/// </summary>
/// <param name="terms">List of terms.</param>
/// <returns>Source names.</returns>
public IEnumerable<string> And(IEnumerable<string> terms)
{
var entries = terms
.Select(term => invertedIndex
.Where(x => x.Key.Equals(term))
.SelectMany(x => x.Value))
.ToList();
var intersection = entries
.Skip(1)
.Aggregate(new HashSet<string>(entries.First()), (hashSet, enumerable) =>
{
hashSet.IntersectWith(enumerable);
return hashSet;
});
return intersection;
}
/// <summary>
/// Returns the source names contains AT LEAST ONE from terms inside.
/// </summary>
/// <param name="terms">List of terms.</param>
/// <returns>Source names.</returns>
public IEnumerable<string> Or(IEnumerable<string> terms)
{
var sources = new List<string>();
foreach (var term in terms)
{
var source = invertedIndex
.Where(x => x.Key.Equals(term))
.SelectMany(x => x.Value);
sources.AddRange(source);
}
return sources.Distinct();
}
}
}
| 83 |
C-Sharp | TheAlgorithms | C# | using System.Collections;
using System.Collections.Generic;
namespace DataStructures
{
/// <summary>
/// Implementation of SortedList using binary search.
/// </summary>
/// <typeparam name="T">Generic Type.</typeparam>
public class SortedList<T> : IEnumerable<T>
{
private readonly IComparer<T> comparer;
private readonly List<T> memory;
/// <summary>
/// Initializes a new instance of the <see cref="SortedList{T}" /> class. Uses a Comparer.Default for type T.
/// </summary>
public SortedList()
: this(Comparer<T>.Default)
{
}
/// <summary>
/// Gets the number of elements containing in <see cref="SortedList{T}" />.
/// </summary>
public int Count => memory.Count;
/// <summary>
/// Initializes a new instance of the <see cref="SortedList{T}" /> class.
/// </summary>
/// <param name="comparer">Comparer user for binary search.</param>
public SortedList(IComparer<T> comparer)
{
memory = new List<T>();
this.comparer = comparer;
}
/// <summary>
/// Adds new item to <see cref="SortedList{T}" /> instance, maintaining the order.
/// </summary>
/// <param name="item">An element to insert.</param>
public void Add(T item)
{
var index = IndexFor(item, out _);
memory.Insert(index, item);
}
/// <summary>
/// Gets an element of <see cref="SortedList{T}" /> at specified index.
/// </summary>
/// <param name="i">Index.</param>
public T this[int i] => memory[i];
/// <summary>
/// Removes all elements from <see cref="SortedList{T}" />.
/// </summary>
public void Clear()
=> memory.Clear();
/// <summary>
/// Indicates whether a <see cref="SortedList{T}" /> contains a certain element.
/// </summary>
/// <param name="item">An element to search.</param>
/// <returns>true - <see cref="SortedList{T}" /> contains an element, otherwise - false.</returns>
public bool Contains(T item)
{
_ = IndexFor(item, out var found);
return found;
}
/// <summary>
/// Removes a certain element from <see cref="SortedList{T}" />.
/// </summary>
/// <param name="item">An element to remove.</param>
/// <returns>true - element is found and removed, otherwise false.</returns>
public bool TryRemove(T item)
{
var index = IndexFor(item, out var found);
if (found)
{
memory.RemoveAt(index);
}
return found;
}
/// <summary>
/// Returns an enumerator that iterates through the <see cref="SortedList{T}" />.
/// </summary>
/// <returns>A Enumerator for the <see cref="SortedList{T}" />.</returns>
public IEnumerator<T> GetEnumerator()
=> memory.GetEnumerator();
/// <inheritdoc cref="IEnumerable.GetEnumerator"/>
IEnumerator IEnumerable.GetEnumerator()
=> GetEnumerator();
/// <summary>
/// Binary search algorithm for finding element index in <see cref="SortedList{T}" />.
/// </summary>
/// <param name="item">Element.</param>
/// <param name="found">Indicates whether the equal value was found in <see cref="SortedList{T}" />.</param>
/// <returns>Index for the Element.</returns>
private int IndexFor(T item, out bool found)
{
var left = 0;
var right = memory.Count;
while (right - left > 0)
{
var mid = (left + right) / 2;
switch (comparer.Compare(item, memory[mid]))
{
case > 0:
left = mid + 1;
break;
case < 0:
right = mid;
break;
default:
found = true;
return mid;
}
}
found = false;
return left;
}
}
}
| 133 |
C-Sharp | TheAlgorithms | C# | /*
Author: Lorenzo Lotti
Name: Timeline (DataStructures.Timeline<TValue>)
Type: Data structure (class)
Description: A collection of dates/times and values sorted by dates/times easy to query.
Usage:
this data structure can be used to represent an ordered series of dates or times with which to associate values.
An example is a chronology of events:
306: Constantine is the new emperor,
312: Battle of the Milvian Bridge,
313: Edict of Milan,
330: Constantine move the capital to Constantinople.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace DataStructures
{
/// <summary>
/// A collection of <see cref="DateTime" /> and <see cref="TValue" />
/// sorted by <see cref="DateTime" /> field.
/// </summary>
/// <typeparam name="TValue">Value associated with a <see cref="DateTime" />.</typeparam>
public class Timeline<TValue> : ICollection<(DateTime Time, TValue Value)>, IEquatable<Timeline<TValue>>
{
/// <summary>
/// Inner collection storing the timeline events as key-tuples.
/// </summary>
private readonly List<(DateTime Time, TValue Value)> timeline = new();
/// <summary>
/// Initializes a new instance of the <see cref="Timeline{TValue}"/> class.
/// </summary>
public Timeline()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Timeline{TValue}"/> class populated with an initial event.
/// </summary>
/// <param name="time">The time at which the given event occurred.</param>
/// <param name="value">The event's content.</param>
public Timeline(DateTime time, TValue value)
=> timeline = new List<(DateTime, TValue)>
{
(time, value),
};
/// <summary>
/// Initializes a new instance of the <see cref="Timeline{TValue}"/> class containing the provided events
/// ordered chronologically.
/// </summary>
/// <param name="timeline">The timeline to represent.</param>
public Timeline(params (DateTime, TValue)[] timeline)
=> this.timeline = timeline
.OrderBy(pair => pair.Item1)
.ToList();
/// <summary>
/// Gets he number of unique times within this timeline.
/// </summary>
public int TimesCount
=> GetAllTimes().Length;
/// <summary>
/// Gets all events that has occurred in this timeline.
/// </summary>
public int ValuesCount
=> GetAllValues().Length;
/// <summary>
/// Get all values associated with <paramref name="time" />.
/// </summary>
/// <param name="time">Time to get values for.</param>
/// <returns>Values associated with <paramref name="time" />.</returns>
public TValue[] this[DateTime time]
{
get => GetValuesByTime(time);
set
{
var overridenEvents = timeline.Where(@event => @event.Time == time).ToList();
foreach (var @event in overridenEvents)
{
timeline.Remove(@event);
}
foreach (var v in value)
{
Add(time, v);
}
}
}
/// <inheritdoc />
bool ICollection<(DateTime Time, TValue Value)>.IsReadOnly
=> false;
/// <summary>
/// Gets the count of pairs.
/// </summary>
public int Count
=> timeline.Count;
/// <summary>
/// Clear the timeline, removing all events.
/// </summary>
public void Clear()
=> timeline.Clear();
/// <summary>
/// Copy a value to an array.
/// </summary>
/// <param name="array">Destination array.</param>
/// <param name="arrayIndex">The start index.</param>
public void CopyTo((DateTime, TValue)[] array, int arrayIndex)
=> timeline.CopyTo(array, arrayIndex);
/// <summary>
/// Add an event at a given time.
/// </summary>
/// <param name="item">The tuple containing the event date and value.</param>
void ICollection<(DateTime Time, TValue Value)>.Add((DateTime Time, TValue Value) item)
=> Add(item.Time, item.Value);
/// <summary>
/// Check whether or not a event exists at a specific date in the timeline.
/// </summary>
/// <param name="item">The tuple containing the event date and value.</param>
/// <returns>True if this event exists at the given date, false otherwise.</returns>
bool ICollection<(DateTime Time, TValue Value)>.Contains((DateTime Time, TValue Value) item)
=> Contains(item.Time, item.Value);
/// <summary>
/// Remove an event at a specific date.
/// </summary>
/// <param name="item">The tuple containing the event date and value.</param>
/// <returns>True if the event was removed, false otherwise.</returns>
bool ICollection<(DateTime Time, TValue Value)>.Remove((DateTime Time, TValue Value) item)
=> Remove(item.Time, item.Value);
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator()
=> timeline.GetEnumerator();
/// <inheritdoc />
IEnumerator<(DateTime Time, TValue Value)> IEnumerable<(DateTime Time, TValue Value)>.GetEnumerator()
=> timeline.GetEnumerator();
/// <inheritdoc />
public bool Equals(Timeline<TValue>? other)
=> other is not null && this == other;
/// <summary>
/// Checks whether or not two <see cref="Timeline{TValue}"/> are equals.
/// </summary>
/// <param name="left">The first timeline.</param>
/// <param name="right">The other timeline to be checked against the <paramref name="left"/> one.</param>
/// <returns>True if both timelines are similar, false otherwise.</returns>
public static bool operator ==(Timeline<TValue> left, Timeline<TValue> right)
{
var leftArray = left.ToArray();
var rightArray = right.ToArray();
if (left.Count != rightArray.Length)
{
return false;
}
for (var i = 0; i < leftArray.Length; i++)
{
if (leftArray[i].Time != rightArray[i].Time
&& !leftArray[i].Value!.Equals(rightArray[i].Value))
{
return false;
}
}
return true;
}
/// <summary>
/// Checks whether or not two <see cref="Timeline{TValue}"/> are not equals.
/// </summary>
/// <param name="left">The first timeline.</param>
/// <param name="right">The other timeline to be checked against the <paramref name="left"/> one.</param>
/// <returns>False if both timelines are similar, true otherwise.</returns>
public static bool operator !=(Timeline<TValue> left, Timeline<TValue> right)
=> !(left == right);
/// <summary>
/// Get all <see cref="DateTime" /> of the timeline.
/// </summary>
public DateTime[] GetAllTimes()
=> timeline.Select(t => t.Time)
.Distinct()
.ToArray();
/// <summary>
/// Get <see cref="DateTime" /> values of the timeline that have this <paramref name="value" />.
/// </summary>
public DateTime[] GetTimesByValue(TValue value)
=> timeline.Where(pair => pair.Value!.Equals(value))
.Select(pair => pair.Time)
.ToArray();
/// <summary>
/// Get all <see cref="DateTime" /> before <paramref name="time" />.
/// </summary>
public DateTime[] GetTimesBefore(DateTime time)
=> GetAllTimes()
.Where(t => t < time)
.OrderBy(t => t)
.ToArray();
/// <summary>
/// Get all <see cref="DateTime" /> after <paramref name="time" />.
/// </summary>
public DateTime[] GetTimesAfter(DateTime time)
=> GetAllTimes()
.Where(t => t > time)
.OrderBy(t => t)
.ToArray();
/// <summary>
/// Get all <see cref="TValue" /> of the timeline.
/// </summary>
public TValue[] GetAllValues()
=> timeline.Select(pair => pair.Value)
.ToArray();
/// <summary>
/// Get all <see cref="TValue" /> associated with <paramref name="time" />.
/// </summary>
public TValue[] GetValuesByTime(DateTime time)
=> timeline.Where(pair => pair.Time == time)
.Select(pair => pair.Value)
.ToArray();
/// <summary>
/// Get all <see cref="TValue" /> before <paramref name="time" />.
/// </summary>
public Timeline<TValue> GetValuesBefore(DateTime time)
=> new(this.Where(pair => pair.Time < time).ToArray());
/// <summary>
/// Get all <see cref="TValue" /> before <paramref name="time" />.
/// </summary>
public Timeline<TValue> GetValuesAfter(DateTime time)
=> new(this.Where(pair => pair.Time > time).ToArray());
/// <summary>
/// Gets all values that happened at specified millisecond.
/// </summary>
/// <param name="millisecond">Value to look for.</param>
/// <returns>Array of values.</returns>
public Timeline<TValue> GetValuesByMillisecond(int millisecond)
=> new(timeline.Where(pair => pair.Time.Millisecond == millisecond).ToArray());
/// <summary>
/// Gets all values that happened at specified second.
/// </summary>
/// <param name="second">Value to look for.</param>
/// <returns>Array of values.</returns>
public Timeline<TValue> GetValuesBySecond(int second)
=> new(timeline.Where(pair => pair.Time.Second == second).ToArray());
/// <summary>
/// Gets all values that happened at specified minute.
/// </summary>
/// <param name="minute">Value to look for.</param>
/// <returns>Array of values.</returns>
public Timeline<TValue> GetValuesByMinute(int minute)
=> new(timeline.Where(pair => pair.Time.Minute == minute).ToArray());
/// <summary>
/// Gets all values that happened at specified hour.
/// </summary>
/// <param name="hour">Value to look for.</param>
/// <returns>Array of values.</returns>
public Timeline<TValue> GetValuesByHour(int hour)
=> new(timeline.Where(pair => pair.Time.Hour == hour).ToArray());
/// <summary>
/// Gets all values that happened at specified day.
/// </summary>
/// <param name="day">Value to look for.</param>
/// <returns>Array of values.</returns>
public Timeline<TValue> GetValuesByDay(int day)
=> new(timeline.Where(pair => pair.Time.Day == day).ToArray());
/// <summary>
/// Gets all values that happened at specified time of the day.
/// </summary>
/// <param name="timeOfDay">Value to look for.</param>
/// <returns>Array of values.</returns>
public Timeline<TValue> GetValuesByTimeOfDay(TimeSpan timeOfDay)
=> new(timeline.Where(pair => pair.Time.TimeOfDay == timeOfDay).ToArray());
/// <summary>
/// Gets all values that happened at specified day of the week.
/// </summary>
/// <param name="dayOfWeek">Value to look for.</param>
/// <returns>Array of values.</returns>
public Timeline<TValue> GetValuesByDayOfWeek(DayOfWeek dayOfWeek)
=> new(timeline.Where(pair => pair.Time.DayOfWeek == dayOfWeek).ToArray());
/// <summary>
/// Gets all values that happened at specified day of the year.
/// </summary>
/// <param name="dayOfYear">Value to look for.</param>
/// <returns>Array of values.</returns>
public Timeline<TValue> GetValuesByDayOfYear(int dayOfYear)
=> new(timeline.Where(pair => pair.Time.DayOfYear == dayOfYear).ToArray());
/// <summary>
/// Gets all values that happened at specified month.
/// </summary>
/// <param name="month">Value to look for.</param>
/// <returns>Array of values.</returns>
public Timeline<TValue> GetValuesByMonth(int month)
=> new(timeline.Where(pair => pair.Time.Month == month).ToArray());
/// <summary>
/// Gets all values that happened at specified year.
/// </summary>
/// <param name="year">Value to look for.</param>
/// <returns>Array of values.</returns>
public Timeline<TValue> GetValuesByYear(int year)
=> new(timeline.Where(pair => pair.Time.Year == year).ToArray());
/// <summary>
/// Add an event at a given <paramref name="time"/>.
/// </summary>
/// <param name="time">The date at which the event occurred.</param>
/// <param name="value">The event value.</param>
public void Add(DateTime time, TValue value)
{
timeline.Add((time, value));
}
/// <summary>
/// Add a set of <see cref="DateTime" /> and <see cref="TValue" /> to the timeline.
/// </summary>
public void Add(params (DateTime, TValue)[] timeline)
{
this.timeline.AddRange(timeline);
}
/// <summary>
/// Append an existing timeline to this one.
/// </summary>
public void Add(Timeline<TValue> timeline)
=> Add(timeline.ToArray());
/// <summary>
/// Add a <paramref name="value" /> associated with <see cref="DateTime.Now" /> to the timeline.
/// </summary>
public void AddNow(params TValue[] value)
{
var now = DateTime.Now;
foreach (var v in value)
{
Add(now, v);
}
}
/// <summary>
/// Check whether or not a event exists at a specific date in the timeline.
/// </summary>
/// <param name="time">The date at which the event occurred.</param>
/// <param name="value">The event value.</param>
/// <returns>True if this event exists at the given date, false otherwise.</returns>
public bool Contains(DateTime time, TValue value)
=> timeline.Contains((time, value));
/// <summary>
/// Check if timeline contains this set of value pairs.
/// </summary>
/// <param name="timeline">The events to checks.</param>
/// <returns>True if any of the events has occurred in the timeline.</returns>
public bool Contains(params (DateTime, TValue)[] timeline)
=> timeline.Any(@event => Contains(@event.Item1, @event.Item2));
/// <summary>
/// Check if timeline contains any of the event of the provided <paramref name="timeline"/>.
/// </summary>
/// <param name="timeline">The events to checks.</param>
/// <returns>True if any of the events has occurred in the timeline.</returns>
public bool Contains(Timeline<TValue> timeline)
=> Contains(timeline.ToArray());
/// <summary>
/// Check if timeline contains any of the time of the provided <paramref name="times"/>.
/// </summary>
/// <param name="times">The times to checks.</param>
/// <returns>True if any of the times is stored in the timeline.</returns>
public bool ContainsTime(params DateTime[] times)
{
var storedTimes = GetAllTimes();
return times.Any(value => storedTimes.Contains(value));
}
/// <summary>
/// Check if timeline contains any of the event of the provided <paramref name="values"/>.
/// </summary>
/// <param name="values">The events to checks.</param>
/// <returns>True if any of the events has occurred in the timeline.</returns>
public bool ContainsValue(params TValue[] values)
{
var storedValues = GetAllValues();
return values.Any(value => storedValues.Contains(value));
}
/// <summary>
/// Remove an event at a specific date.
/// </summary>
/// <param name="time">The date at which the event occurred.</param>
/// <param name="value">The event value.</param>
/// <returns>True if the event was removed, false otherwise.</returns>
public bool Remove(DateTime time, TValue value)
=> timeline.Remove((time, value));
/// <summary>
/// Remove a set of value pairs from the timeline.
/// </summary>
/// <param name="timeline">An collection of all events to remove.</param>
/// <returns>Returns true if the operation completed successfully.</returns>
public bool Remove(params (DateTime, TValue)[] timeline)
{
var result = false;
foreach (var (time, value) in timeline)
{
result |= this.timeline.Remove((time, value));
}
return result;
}
/// <summary>
/// Remove an existing timeline from this timeline.
/// </summary>
/// <param name="timeline">An collection of all events to remove.</param>
/// <returns>Returns true if the operation completed successfully.</returns>
public bool Remove(Timeline<TValue> timeline)
=> Remove(timeline.ToArray());
/// <summary>
/// Remove a value pair from the timeline if the time is equal to <paramref name="times" />.
/// </summary>
/// <returns>Returns true if the operation completed successfully.</returns>
public bool RemoveTimes(params DateTime[] times)
{
var isTimeContainedInTheTimeline = times.Any(time => GetAllTimes().Contains(time));
if (!isTimeContainedInTheTimeline)
{
return false;
}
var eventsToRemove = times.SelectMany(time =>
timeline.Where(@event => @event.Time == time))
.ToList();
foreach (var @event in eventsToRemove)
{
timeline.Remove(@event);
}
return true;
}
/// <summary>
/// Remove a value pair from the timeline if the value is equal to <paramref name="values" />.
/// </summary>
/// <returns>Returns true if the operation completed successfully.</returns>
public bool RemoveValues(params TValue[] values)
{
var isValueContainedInTheTimeline = values.Any(v => GetAllValues().Contains(v));
if (!isValueContainedInTheTimeline)
{
return false;
}
var eventsToRemove = values.SelectMany(value =>
timeline.Where(@event => EqualityComparer<TValue>.Default.Equals(@event.Value, value)))
.ToList();
foreach (var @event in eventsToRemove)
{
timeline.Remove(@event);
}
return true;
}
/// <summary>
/// Convert the timeline to an array.
/// </summary>
/// <returns>
/// The timeline as an array of tuples of (<see cref="DateTime"/>, <typeparamref name="TValue"/>).
/// </returns>
public (DateTime Time, TValue Value)[] ToArray()
=> timeline.ToArray();
/// <summary>
/// Convert the timeline to a list.
/// </summary>
/// <returns>
/// The timeline as a list of tuples of (<see cref="DateTime"/>, <typeparamref name="TValue"/>).
/// </returns>
public IList<(DateTime Time, TValue Value)> ToList()
=> timeline;
/// <summary>
/// Convert the timeline to a dictionary.
/// </summary>
/// <returns>
/// The timeline as an dictionary of <typeparamref name="TValue"/> by <see cref="DateTime"/>.
/// </returns>
public IDictionary<DateTime, TValue> ToDictionary()
=> timeline.ToDictionary(@event => @event.Time, @event => @event.Value);
/// <inheritdoc />
public override bool Equals(object? obj)
=> obj is Timeline<TValue> otherTimeline
&& this == otherTimeline;
/// <inheritdoc />
public override int GetHashCode()
=> timeline.GetHashCode();
}
}
| 537 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
namespace DataStructures.AATree
{
/// <summary>
/// A simple self-balancing binary search tree.
/// </summary>
/// <remarks>
/// AA Trees are a form of self-balancing binary search tree named after their inventor
/// Arne Anderson. AA Trees are designed to be simple to understand and implement.
/// This is accomplished by limiting how nodes can be added to the tree.
/// This simplifies rebalancing operations.
/// More information: https://en.wikipedia.org/wiki/AA_tree .
/// </remarks>
/// <typeparam name="TKey">The type of key for the AA tree.</typeparam>
public class AaTree<TKey>
{
/// <summary>
/// The comparer function to use to compare the keys.
/// </summary>
private readonly Comparer<TKey> comparer;
/// <summary>
/// Initializes a new instance of the <see cref="AaTree{TKey}" /> class.
/// </summary>
public AaTree()
: this(Comparer<TKey>.Default)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AaTree{TKey}" /> class with a custom comparer.
/// </summary>
/// <param name="customComparer">The custom comparer to use to compare keys.</param>
public AaTree(Comparer<TKey> customComparer) => comparer = customComparer;
/// <summary>
/// Gets the root of the tree.
/// </summary>
public AaTreeNode<TKey>? Root { get; private set; }
/// <summary>
/// Gets the number of elements in the tree.
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Add a single element to the tree.
/// </summary>
/// <param name="key">The element to add to the tree.</param>
public void Add(TKey key)
{
Root = Add(key, Root);
Count++;
}
/// <summary>
/// Add multiple elements to the tree.
/// </summary>
/// <param name="keys">The elements to add to the tree.</param>
public void AddRange(IEnumerable<TKey> keys)
{
foreach (var key in keys)
{
Root = Add(key, Root);
Count++;
}
}
/// <summary>
/// Remove a single element from the tree.
/// </summary>
/// <param name="key">Element to remove.</param>
public void Remove(TKey key)
{
if (!Contains(key, Root))
{
throw new InvalidOperationException($"{nameof(key)} is not in the tree");
}
Root = Remove(key, Root);
Count--;
}
/// <summary>
/// Checks if the specified element is in the tree.
/// </summary>
/// <param name="key">The element to look for.</param>
/// <returns>true if the element is in the tree, false otherwise.</returns>
public bool Contains(TKey key) => Contains(key, Root);
/// <summary>
/// Gets the largest element in the tree. (ie. the element in the right most node).
/// </summary>
/// <returns>The largest element in the tree according to the stored comparer.</returns>
/// <exception cref="InvalidOperationException">Thrown if the tree is empty.</exception>
public TKey GetMax()
{
if (Root is null)
{
throw new InvalidOperationException("Tree is empty!");
}
return GetMax(Root).Key;
}
/// <summary>
/// Gets the smallest element in the tree. (ie. the element in the left most node).
/// </summary>
/// <returns>The smallest element in the tree according to the stored comparer.</returns>
/// <throws>InvalidOperationException if the tree is empty.</throws>
public TKey GetMin()
{
if (Root is null)
{
throw new InvalidOperationException("Tree is empty!");
}
return GetMin(Root).Key;
}
/// <summary>
/// Gets all the elements in the tree in in-order order.
/// </summary>
/// <returns>Sequence of elements in in-order order.</returns>
public IEnumerable<TKey> GetKeysInOrder()
{
var result = new List<TKey>();
InOrderWalk(Root);
return result;
void InOrderWalk(AaTreeNode<TKey>? node)
{
if (node is null)
{
return;
}
InOrderWalk(node.Left);
result.Add(node.Key);
InOrderWalk(node.Right);
}
}
/// <summary>
/// Gets all the elements in the tree in pre-order order.
/// </summary>
/// <returns>Sequence of elements in pre-order order.</returns>
public IEnumerable<TKey> GetKeysPreOrder()
{
var result = new List<TKey>();
PreOrderWalk(Root);
return result;
void PreOrderWalk(AaTreeNode<TKey>? node)
{
if (node is null)
{
return;
}
result.Add(node.Key);
PreOrderWalk(node.Left);
PreOrderWalk(node.Right);
}
}
/// <summary>
/// Gets all the elements in the tree in post-order order.
/// </summary>
/// <returns>Sequence of elements in post-order order.</returns>
public IEnumerable<TKey> GetKeysPostOrder()
{
var result = new List<TKey>();
PostOrderWalk(Root);
return result;
void PostOrderWalk(AaTreeNode<TKey>? node)
{
if (node is null)
{
return;
}
PostOrderWalk(node.Left);
PostOrderWalk(node.Right);
result.Add(node.Key);
}
}
/// <summary>
/// Recursive function to add an element to the tree.
/// </summary>
/// <param name="key">The element to add.</param>
/// <param name="node">The node to search for a empty spot.</param>
/// <returns>The node with the added element.</returns>
/// <exception cref="ArgumentException">Thrown if key is already in the tree.</exception>
private AaTreeNode<TKey> Add(TKey key, AaTreeNode<TKey>? node)
{
if (node is null)
{
return new AaTreeNode<TKey>(key, 1);
}
if (comparer.Compare(key, node.Key) < 0)
{
node.Left = Add(key, node.Left);
}
else if (comparer.Compare(key, node.Key) > 0)
{
node.Right = Add(key, node.Right);
}
else
{
throw new ArgumentException($"Key \"{key}\" already in tree!", nameof(key));
}
return Split(Skew(node)) !;
}
/// <summary>
/// Recursive function to remove an element from the tree.
/// </summary>
/// <param name="key">The element to remove.</param>
/// <param name="node">The node to search from.</param>
/// <returns>The node with the specified element removed.</returns>
private AaTreeNode<TKey>? Remove(TKey key, AaTreeNode<TKey>? node)
{
if (node is null)
{
return null;
}
if (comparer.Compare(key, node.Key) < 0)
{
node.Left = Remove(key, node.Left);
}
else if (comparer.Compare(key, node.Key) > 0)
{
node.Right = Remove(key, node.Right);
}
else
{
if (node.Left is null && node.Right is null)
{
return null;
}
if (node.Left is null)
{
var successor = GetMin(node.Right!);
node.Right = Remove(successor.Key, node.Right);
node.Key = successor.Key;
}
else
{
var predecessor = GetMax(node.Left);
node.Left = Remove(predecessor.Key, node.Left);
node.Key = predecessor.Key;
}
}
node = DecreaseLevel(node);
node = Skew(node);
node!.Right = Skew(node.Right);
if (node.Right is not null)
{
node.Right.Right = Skew(node.Right.Right);
}
node = Split(node);
node!.Right = Split(node.Right);
return node;
}
/// <summary>
/// Recursive function to check if the element exists in the tree.
/// </summary>
/// <param name="key">The element to check for.</param>
/// <param name="node">The node to search from.</param>
/// <returns>true if the element exists in the tree, false otherwise.</returns>
private bool Contains(TKey key, AaTreeNode<TKey>? node) =>
node is { }
&& comparer.Compare(key, node.Key) is { } v
&& v switch
{
{ } when v > 0 => Contains(key, node.Right),
{ } when v < 0 => Contains(key, node.Left),
_ => true,
};
/// <summary>
/// Recursive to find the maximum/right-most element.
/// </summary>
/// <param name="node">The node to traverse from.</param>
/// <returns>The node with the maximum/right-most element.</returns>
private AaTreeNode<TKey> GetMax(AaTreeNode<TKey> node)
{
while (true)
{
if (node.Right is null)
{
return node;
}
node = node.Right;
}
}
/// <summary>
/// Recursive to find the minimum/left-most element.
/// </summary>
/// <param name="node">The node to traverse from.</param>
/// <returns>The node with the minimum/left-most element.</returns>
private AaTreeNode<TKey> GetMin(AaTreeNode<TKey> node)
{
while (true)
{
if (node.Left is null)
{
return node;
}
node = node.Left;
}
}
/// <summary>
/// Remove right-horizontal links and replaces them with left-horizontal links.
/// Accomplishes this by performing a right rotation.
/// </summary>
/// <param name="node">The node to rebalance from.</param>
/// <returns>The rebalanced node.</returns>
private AaTreeNode<TKey>? Skew(AaTreeNode<TKey>? node)
{
if (node?.Left is null || node.Left.Level != node.Level)
{
return node;
}
var left = node.Left;
node.Left = left.Right;
left.Right = node;
return left;
}
/// <summary>
/// Reduces the number of right-horizontal links.
/// Accomplishes this by performing a left rotation, and incrementing level.
/// </summary>
/// <param name="node">The node to rebalance from.</param>
/// <returns>The rebalanced node.</returns>
private AaTreeNode<TKey>? Split(AaTreeNode<TKey>? node)
{
if (node?.Right?.Right is null || node.Level != node.Right.Right.Level)
{
return node;
}
var right = node.Right;
node.Right = right.Left;
right.Left = node;
right.Level++;
return right;
}
/// <summary>
/// Decreases the level of node if necessary.
/// </summary>
/// <param name="node">The node to decrease level from.</param>
/// <returns>The node with modified level.</returns>
private AaTreeNode<TKey> DecreaseLevel(AaTreeNode<TKey> node)
{
var newLevel = Math.Min(GetLevel(node.Left), GetLevel(node.Right)) + 1;
if (newLevel >= node.Level)
{
return node;
}
node.Level = newLevel;
if (node.Right is { } && newLevel < node.Right.Level)
{
node.Right.Level = newLevel;
}
return node;
static int GetLevel(AaTreeNode<TKey>? x) => x?.Level ?? 0;
}
}
}
| 394 |
C-Sharp | TheAlgorithms | C# | namespace DataStructures.AATree
{
/// <summary>
/// Generic node class for AATree.
/// </summary>
/// <typeparam name="TKey">Type of key for node.</typeparam>
public class AaTreeNode<TKey>
{
/// <summary>
/// Initializes a new instance of the <see cref="AaTreeNode{TKey}" /> class.
/// </summary>
/// <param name="key">The initial key of this node.</param>
/// <param name="level">The level of this node. See <see cref="AaTree{TKey}" /> for more details.</param>
public AaTreeNode(TKey key, int level)
{
Key = key;
Level = level;
}
/// <summary>
/// Gets or Sets key for this node.
/// </summary>
public TKey Key { get; set; }
/// <summary>
/// Gets or Sets level for this node.
/// </summary>
public int Level { get; set; }
/// <summary>
/// Gets or sets the left subtree of this node.
/// </summary>
public AaTreeNode<TKey>? Left { get; set; }
/// <summary>
/// Gets or sets the right subtree of this node.
/// </summary>
public AaTreeNode<TKey>? Right { get; set; }
}
}
| 41 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
namespace DataStructures.AVLTree
{
/// <summary>
/// A simple self-balancing binary tree.
/// </summary>
/// <remarks>
/// An AVL tree is a self-balancing binary search tree (BST) named after
/// its inventors: Adelson, Velsky, and Landis. It is the first self-
/// balancing BST invented. The primary property of an AVL tree is that
/// the height of both child subtrees for any node only differ by one.
/// Due to the balanced nature of the tree, its time complexities for
/// insertion, deletion, and search all have a worst-case time
/// complexity of O(log n). Which is an improvement over the worst-case
/// O(n) for a regular BST.
/// See https://en.wikipedia.org/wiki/AVL_tree for more information.
/// Visualizer: https://visualgo.net/en/bst.
/// </remarks>
/// <typeparam name="TKey">Type of key for the tree.</typeparam>
public class AvlTree<TKey>
{
/// <summary>
/// Gets the number of nodes in the tree.
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Comparer to use when comparing key values.
/// </summary>
private readonly Comparer<TKey> comparer;
/// <summary>
/// Reference to the root node.
/// </summary>
private AvlTreeNode<TKey>? root;
/// <summary>
/// Initializes a new instance of the <see cref="AvlTree{TKey}"/>
/// class.
/// </summary>
public AvlTree()
{
comparer = Comparer<TKey>.Default;
}
/// <summary>
/// Initializes a new instance of the <see cref="AvlTree{TKey}"/>
/// class using the specified comparer.
/// </summary>
/// <param name="customComparer">
/// Comparer to use when comparing keys.
/// </param>
public AvlTree(Comparer<TKey> customComparer)
{
comparer = customComparer;
}
/// <summary>
/// Add a single node to the tree.
/// </summary>
/// <param name="key">Key value to add.</param>
public void Add(TKey key)
{
if (root is null)
{
root = new AvlTreeNode<TKey>(key);
}
else
{
root = Add(root, key);
}
Count++;
}
/// <summary>
/// Add multiple nodes to the tree.
/// </summary>
/// <param name="keys">Key values to add.</param>
public void AddRange(IEnumerable<TKey> keys)
{
foreach (var key in keys)
{
Add(key);
}
}
/// <summary>
/// Remove a node from the tree.
/// </summary>
/// <param name="key">Key value to remove.</param>
public void Remove(TKey key)
{
root = Remove(root, key);
Count--;
}
/// <summary>
/// Check if given node is in the tree.
/// </summary>
/// <param name="key">Key value to search for.</param>
/// <returns>Whether or not the node is in the tree.</returns>
public bool Contains(TKey key)
{
var node = root;
while (node is not null)
{
var compareResult = comparer.Compare(key, node.Key);
if (compareResult < 0)
{
node = node.Left;
}
else if (compareResult > 0)
{
node = node.Right;
}
else
{
return true;
}
}
return false;
}
/// <summary>
/// Get the minimum value in the tree.
/// </summary>
/// <returns>Minimum value in tree.</returns>
public TKey GetMin()
{
if (root is null)
{
throw new InvalidOperationException("AVL tree is empty.");
}
return GetMin(root).Key;
}
/// <summary>
/// Get the maximum value in the tree.
/// </summary>
/// <returns>Maximum value in tree.</returns>
public TKey GetMax()
{
if (root is null)
{
throw new InvalidOperationException("AVL tree is empty.");
}
return GetMax(root).Key;
}
/// <summary>
/// Get keys in order from smallest to largest as defined by the
/// comparer.
/// </summary>
/// <returns>Keys in tree in order from smallest to largest.</returns>
public IEnumerable<TKey> GetKeysInOrder()
{
List<TKey> result = new();
InOrderWalk(root);
return result;
void InOrderWalk(AvlTreeNode<TKey>? node)
{
if (node is null)
{
return;
}
InOrderWalk(node.Left);
result.Add(node.Key);
InOrderWalk(node.Right);
}
}
/// <summary>
/// Get keys in the pre-order order.
/// </summary>
/// <returns>Keys in pre-order order.</returns>
public IEnumerable<TKey> GetKeysPreOrder()
{
var result = new List<TKey>();
PreOrderWalk(root);
return result;
void PreOrderWalk(AvlTreeNode<TKey>? node)
{
if (node is null)
{
return;
}
result.Add(node.Key);
PreOrderWalk(node.Left);
PreOrderWalk(node.Right);
}
}
/// <summary>
/// Get keys in the post-order order.
/// </summary>
/// <returns>Keys in the post-order order.</returns>
public IEnumerable<TKey> GetKeysPostOrder()
{
var result = new List<TKey>();
PostOrderWalk(root);
return result;
void PostOrderWalk(AvlTreeNode<TKey>? node)
{
if (node is null)
{
return;
}
PostOrderWalk(node.Left);
PostOrderWalk(node.Right);
result.Add(node.Key);
}
}
/// <summary>
/// Helper function to rebalance the tree so that all nodes have a
/// balance factor in the range [-1, 1].
/// </summary>
/// <param name="node">Node to rebalance.</param>
/// <returns>New node that has been rebalanced.</returns>
private static AvlTreeNode<TKey> Rebalance(AvlTreeNode<TKey> node)
{
if (node.BalanceFactor > 1)
{
if (node.Right!.BalanceFactor == -1)
{
node.Right = RotateRight(node.Right);
}
return RotateLeft(node);
}
if (node.BalanceFactor < -1)
{
if (node.Left!.BalanceFactor == 1)
{
node.Left = RotateLeft(node.Left);
}
return RotateRight(node);
}
return node;
}
/// <summary>
/// Perform a left (counter-clockwise) rotation.
/// </summary>
/// <param name="node">Node to rotate about.</param>
/// <returns>New node with rotation applied.</returns>
private static AvlTreeNode<TKey> RotateLeft(AvlTreeNode<TKey> node)
{
var temp1 = node;
var temp2 = node.Right!.Left;
node = node.Right;
node.Left = temp1;
node.Left.Right = temp2;
node.Left.UpdateBalanceFactor();
node.UpdateBalanceFactor();
return node;
}
/// <summary>
/// Perform a right (clockwise) rotation.
/// </summary>
/// <param name="node">Node to rotate about.</param>
/// <returns>New node with rotation applied.</returns>
private static AvlTreeNode<TKey> RotateRight(AvlTreeNode<TKey> node)
{
var temp1 = node;
var temp2 = node.Left!.Right;
node = node.Left;
node.Right = temp1;
node.Right.Left = temp2;
node.Right.UpdateBalanceFactor();
node.UpdateBalanceFactor();
return node;
}
/// <summary>
/// Helper function to get node instance with minimum key value
/// in the specified subtree.
/// </summary>
/// <param name="node">Node specifying root of subtree.</param>
/// <returns>Minimum value in node's subtree.</returns>
private static AvlTreeNode<TKey> GetMin(AvlTreeNode<TKey> node)
{
while (node.Left is not null)
{
node = node.Left;
}
return node;
}
/// <summary>
/// Helper function to get node instance with maximum key value
/// in the specified subtree.
/// </summary>
/// <param name="node">Node specifying root of subtree.</param>
/// <returns>Maximum value in node's subtree.</returns>
private static AvlTreeNode<TKey> GetMax(AvlTreeNode<TKey> node)
{
while (node.Right is not null)
{
node = node.Right;
}
return node;
}
/// <summary>
/// Recursively function to add a node to the tree.
/// </summary>
/// <param name="node">Node to check for null leaf.</param>
/// <param name="key">Key value to add.</param>
/// <returns>New node with key inserted.</returns>
private AvlTreeNode<TKey> Add(AvlTreeNode<TKey> node, TKey key)
{
// Regular binary search tree insertion
var compareResult = comparer.Compare(key, node.Key);
if (compareResult < 0)
{
if (node.Left is null)
{
var newNode = new AvlTreeNode<TKey>(key);
node.Left = newNode;
}
else
{
node.Left = Add(node.Left, key);
}
}
else if (compareResult > 0)
{
if (node.Right is null)
{
var newNode = new AvlTreeNode<TKey>(key);
node.Right = newNode;
}
else
{
node.Right = Add(node.Right, key);
}
}
else
{
throw new ArgumentException(
$"Key \"{key}\" already exists in AVL tree.");
}
// Check all of the new node's ancestors for inbalance and perform
// necessary rotations
node.UpdateBalanceFactor();
return Rebalance(node);
}
/// <summary>
/// Recursive function to remove node from tree.
/// </summary>
/// <param name="node">Node to check for key.</param>
/// <param name="key">Key value to remove.</param>
/// <returns>New node with key removed.</returns>
private AvlTreeNode<TKey>? Remove(AvlTreeNode<TKey>? node, TKey key)
{
if (node == null)
{
throw new KeyNotFoundException(
$"Key \"{key}\" is not in the AVL tree.");
}
// Normal binary search tree removal
var compareResult = comparer.Compare(key, node.Key);
if (compareResult < 0)
{
node.Left = Remove(node.Left, key);
}
else if (compareResult > 0)
{
node.Right = Remove(node.Right, key);
}
else
{
if (node.Left is null && node.Right is null)
{
return null;
}
if (node.Left is null)
{
var successor = GetMin(node.Right!);
node.Right = Remove(node.Right!, successor.Key);
node.Key = successor.Key;
}
else
{
var predecessor = GetMax(node.Left!);
node.Left = Remove(node.Left!, predecessor.Key);
node.Key = predecessor.Key;
}
}
// Check all of the removed node's ancestors for rebalance and
// perform necessary rotations.
node.UpdateBalanceFactor();
return Rebalance(node);
}
}
}
| 427 |
C-Sharp | TheAlgorithms | C# | using System;
namespace DataStructures.AVLTree
{
/// <summary>
/// Generic class to represent nodes in an <see cref="AvlTree{TKey}"/>
/// instance.
/// </summary>
/// <typeparam name="TKey">The type of key for the node.</typeparam>
internal class AvlTreeNode<TKey>
{
/// <summary>
/// Gets or sets key value of node.
/// </summary>
public TKey Key { get; set; }
/// <summary>
/// Gets the balance factor of the node.
/// </summary>
public int BalanceFactor { get; private set; }
/// <summary>
/// Gets or sets the left child of the node.
/// </summary>
public AvlTreeNode<TKey>? Left { get; set; }
/// <summary>
/// Gets or sets the right child of the node.
/// </summary>
public AvlTreeNode<TKey>? Right { get; set; }
/// <summary>
/// Gets or sets the height of the node.
/// </summary>
private int Height { get; set; }
/// <summary>
/// Initializes a new instance of the
/// <see cref="AvlTreeNode{TKey}"/> class.
/// </summary>
/// <param name="key">Key value for node.</param>
public AvlTreeNode(TKey key)
{
Key = key;
}
/// <summary>
/// Update the node's height and balance factor.
/// </summary>
public void UpdateBalanceFactor()
{
if (Left is null && Right is null)
{
Height = 0;
BalanceFactor = 0;
}
else if (Left is null)
{
Height = Right!.Height + 1;
BalanceFactor = Height;
}
else if (Right is null)
{
Height = Left!.Height + 1;
BalanceFactor = -Height;
}
else
{
Height = Math.Max(Left.Height, Right.Height) + 1;
BalanceFactor = Right.Height - Left.Height;
}
}
}
}
| 75 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
namespace DataStructures.BinarySearchTree
{
/// <summary>
/// An ordered tree with efficient insertion, removal, and lookup.
/// </summary>
/// <remarks>
/// A Binary Search Tree (BST) is a tree that satisfies the following properties:
/// <list type="bullet">
/// <item>All nodes in the tree contain two children, usually called Left and Right.</item>
/// <item>All nodes in the Left subtree contain keys that are less than the node's key.</item>
/// <item>All nodes in the Right subtree contain keys that are greater than the node's key.</item>
/// </list>
/// A BST will have an average complexity of O(log n) for insertion, removal, and lookup operations.
/// </remarks>
/// <typeparam name="TKey">Type of key for the BST. Keys must implement IComparable.</typeparam>
public class BinarySearchTree<TKey>
{
/// <summary>
/// Comparer to use when comparing node elements/keys.
/// </summary>
private readonly Comparer<TKey> comparer;
/// <summary>
/// Gets the root of the BST.
/// </summary>
public BinarySearchTreeNode<TKey>? Root { get; private set; }
public BinarySearchTree()
{
Root = null;
Count = 0;
comparer = Comparer<TKey>.Default;
}
public BinarySearchTree(Comparer<TKey> customComparer)
{
Root = null;
Count = 0;
comparer = customComparer;
}
/// <summary>
/// Gets the number nodes currently in the BST.
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Insert a key into the BST.
/// </summary>
/// <param name="key">The key to insert.</param>
/// <exception cref="ArgumentException">
/// Thrown if key is already in BST.
/// </exception>
public void Add(TKey key)
{
if (Root is null)
{
Root = new BinarySearchTreeNode<TKey>(key);
}
else
{
Add(Root, key);
}
Count++;
}
/// <summary>
/// Insert multiple keys into the BST.
/// Keys are inserted in the order they appear in the sequence.
/// </summary>
/// <param name="keys">Sequence of keys to insert.</param>
public void AddRange(IEnumerable<TKey> keys)
{
foreach (var key in keys)
{
Add(key);
}
}
/// <summary>
/// Find a node with the specified key.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <returns>The node with the specified key if it exists, otherwise a default value is returned.</returns>
public BinarySearchTreeNode<TKey>? Search(TKey key) => Search(Root, key);
/// <summary>
/// Checks if the specified key is in the BST.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <returns>true if the key is in the BST, false otherwise.</returns>
public bool Contains(TKey key) => Search(Root, key) is not null;
/// <summary>
/// Removes a node with a key that matches <paramref name="key" />.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <returns>true if the removal was successful, false otherwise.</returns>
public bool Remove(TKey key)
{
if (Root is null)
{
return false;
}
var result = Remove(Root, Root, key);
if (result)
{
Count--;
}
return result;
}
/// <summary>
/// Returns a node with the smallest key.
/// </summary>
/// <returns>The node if possible, a default value otherwise.</returns>
public BinarySearchTreeNode<TKey>? GetMin()
{
if (Root is null)
{
return default;
}
return GetMin(Root);
}
/// <summary>
/// Returns a node with the largest key.
/// </summary>
/// <returns>The node if possible, a default value otherwise.</returns>
public BinarySearchTreeNode<TKey>? GetMax()
{
if (Root is null)
{
return default;
}
return GetMax(Root);
}
/// <summary>
/// Returns all the keys in the BST, sorted In-Order.
/// </summary>
/// <returns>A list of keys in the BST.</returns>
public ICollection<TKey> GetKeysInOrder() => GetKeysInOrder(Root);
/// <summary>
/// Returns all the keys in the BST, sorted Pre-Order.
/// </summary>
/// <returns>A list of keys in the BST.</returns>
public ICollection<TKey> GetKeysPreOrder() => GetKeysPreOrder(Root);
/// <summary>
/// Returns all the keys in the BST, sorted Post-Order.
/// </summary>
/// <returns>A list of keys in the BST.</returns>
public ICollection<TKey> GetKeysPostOrder() => GetKeysPostOrder(Root);
/// <summary>
/// Recursive method to add a key to the BST.
/// </summary>
/// <param name="node">Node to search from.</param>
/// <param name="key">Key to add.</param>
/// <exception cref="ArgumentException">
/// Thrown if key is already in the BST.
/// </exception>
private void Add(BinarySearchTreeNode<TKey> node, TKey key)
{
var compareResult = comparer.Compare(node.Key, key);
if (compareResult > 0)
{
if (node.Left is not null)
{
Add(node.Left, key);
}
else
{
var newNode = new BinarySearchTreeNode<TKey>(key);
node.Left = newNode;
}
}
else if (compareResult < 0)
{
if (node.Right is not null)
{
Add(node.Right, key);
}
else
{
var newNode = new BinarySearchTreeNode<TKey>(key);
node.Right = newNode;
}
}
// Key is already in tree.
else
{
throw new ArgumentException($"Key \"{key}\" already exists in tree!");
}
}
/// <summary>
/// Removes a node with the specified key from the BST.
/// </summary>
/// <param name="parent">The parent node of <paramref name="node" />.</param>
/// <param name="node">The node to check/search from.</param>
/// <param name="key">The key to remove.</param>
/// <returns>true if the operation was successful, false otherwise.</returns>
/// <remarks>
/// Removing a node from the BST can be split into three cases:
/// <br></br>
/// 0. The node to be removed has no children. In this case, the node can just be removed from the tree.
/// <br></br>
/// 1. The node to be removed has one child. In this case, the node's child is moved to the node's parent,
/// then the node is removed from the tree.
/// <br></br>
/// 2. The node to be removed has two children. In this case, we must find a suitable node among the children
/// subtrees to replace the node. This can be done with either the in-order predecessor or the in-order successor.
/// The in-order predecessor is the largest node in Left subtree, or the largest node that is still smaller then the
/// current node. The in-order successor is the smallest node in the Right subtree, or the smallest node that is
/// still larger than the current node. Either way, once this suitable node is found, remove it from the tree (it
/// should be either a case 1 or 2 node) and replace the node to be removed with this suitable node.
/// <br></br>
/// More information: https://en.wikipedia.org/wiki/Binary_search_tree#Deletion .
/// </remarks>
private bool Remove(BinarySearchTreeNode<TKey>? parent, BinarySearchTreeNode<TKey>? node, TKey key)
{
if (node is null || parent is null)
{
return false;
}
var compareResult = comparer.Compare(node.Key, key);
if (compareResult > 0)
{
return Remove(node, node.Left, key);
}
if (compareResult < 0)
{
return Remove(node, node.Right, key);
}
BinarySearchTreeNode<TKey>? replacementNode;
// Case 0: Node has no children.
// Case 1: Node has one child.
if (node.Left is null || node.Right is null)
{
replacementNode = node.Left ?? node.Right;
}
// Case 2: Node has two children. (This implementation uses the in-order predecessor to replace node.)
else
{
var predecessorNode = GetMax(node.Left);
Remove(Root, Root, predecessorNode.Key);
replacementNode = new BinarySearchTreeNode<TKey>(predecessorNode.Key)
{
Left = node.Left,
Right = node.Right,
};
}
// Replace the relevant node with a replacement found in the previous stages.
// Special case for replacing the root node.
if (node == Root)
{
Root = replacementNode;
}
else if (parent.Left == node)
{
parent.Left = replacementNode;
}
else
{
parent.Right = replacementNode;
}
return true;
}
/// <summary>
/// Recursive method to get node with largest key.
/// </summary>
/// <param name="node">Node to search from.</param>
/// <returns>Node with largest value.</returns>
private BinarySearchTreeNode<TKey> GetMax(BinarySearchTreeNode<TKey> node)
{
if (node.Right is null)
{
return node;
}
return GetMax(node.Right);
}
/// <summary>
/// Recursive method to get node with smallest key.
/// </summary>
/// <param name="node">Node to search from.</param>
/// <returns>Node with smallest value.</returns>
private BinarySearchTreeNode<TKey> GetMin(BinarySearchTreeNode<TKey> node)
{
if (node.Left is null)
{
return node;
}
return GetMin(node.Left);
}
/// <summary>
/// Recursive method to get a list with the keys sorted in in-order order.
/// </summary>
/// <param name="node">Node to traverse from.</param>
/// <returns>List of keys in in-order order.</returns>
private IList<TKey> GetKeysInOrder(BinarySearchTreeNode<TKey>? node)
{
if (node is null)
{
return new List<TKey>();
}
var result = new List<TKey>();
result.AddRange(GetKeysInOrder(node.Left));
result.Add(node.Key);
result.AddRange(GetKeysInOrder(node.Right));
return result;
}
/// <summary>
/// Recursive method to get a list with the keys sorted in pre-order order.
/// </summary>
/// <param name="node">Node to traverse from.</param>
/// <returns>List of keys in pre-order order.</returns>
private IList<TKey> GetKeysPreOrder(BinarySearchTreeNode<TKey>? node)
{
if (node is null)
{
return new List<TKey>();
}
var result = new List<TKey>();
result.Add(node.Key);
result.AddRange(GetKeysPreOrder(node.Left));
result.AddRange(GetKeysPreOrder(node.Right));
return result;
}
/// <summary>
/// Recursive method to get a list with the keys sorted in post-order order.
/// </summary>
/// <param name="node">Node to traverse from.</param>
/// <returns>List of keys in post-order order.</returns>
private IList<TKey> GetKeysPostOrder(BinarySearchTreeNode<TKey>? node)
{
if (node is null)
{
return new List<TKey>();
}
var result = new List<TKey>();
result.AddRange(GetKeysPostOrder(node.Left));
result.AddRange(GetKeysPostOrder(node.Right));
result.Add(node.Key);
return result;
}
/// <summary>
/// Recursive method to find a node with a matching key.
/// </summary>
/// <param name="node">Node to search from.</param>
/// <param name="key">Key to find.</param>
/// <returns>The node with the specified if it exists, a default value otherwise.</returns>
private BinarySearchTreeNode<TKey>? Search(BinarySearchTreeNode<TKey>? node, TKey key)
{
if (node is null)
{
return default;
}
var compareResult = comparer.Compare(node.Key, key);
if (compareResult > 0)
{
return Search(node.Left, key);
}
if (compareResult < 0)
{
return Search(node.Right, key);
}
return node;
}
}
}
| 405 |
C-Sharp | TheAlgorithms | C# | namespace DataStructures.BinarySearchTree
{
/// <summary>
/// Generic node class for BinarySearchTree.
/// Keys for each node are immutable.
/// </summary>
/// <typeparam name="TKey">Type of key for the node. Keys must implement IComparable.</typeparam>
public class BinarySearchTreeNode<TKey>
{
/// <summary>
/// Initializes a new instance of the <see cref="BinarySearchTreeNode{TKey}" /> class.
/// </summary>
/// <param name="key">The key of this node.</param>
public BinarySearchTreeNode(TKey key) => Key = key;
/// <summary>
/// Gets the key for this node.
/// </summary>
public TKey Key { get; }
/// <summary>
/// Gets or sets the reference to a child node that precedes/comes before this node.
/// </summary>
public BinarySearchTreeNode<TKey>? Left { get; set; }
/// <summary>
/// Gets or sets the reference to a child node that follows/comes after this node.
/// </summary>
public BinarySearchTreeNode<TKey>? Right { get; set; }
}
}
| 32 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
namespace DataStructures.Cache
{
/// <summary>
/// Least Frequently Used (LFU) cache implementation.
/// </summary>
/// <typeparam name="TKey">The type of the key (must be not null).</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <remarks>
/// Cache keeps up to <c>capacity</c> items. When new item is added and cache is full,
/// one of the least frequently used item is removed (e.g. it keeps N items that were the most
/// frequently requested using <c>Get()</c> or <c>Put()</c> methods).
/// When there are multiple items with the same frequency, the least recently used item is removed.
///
/// Cache is built on top of two data structures:
/// - <c>Dictionary</c>. Allows items to be looked up by key in O(1) time. Another dictionary
/// is used to store the frequency of each key.
/// - <c>LinkedList</c> - Allows items with the same frequency to be ordered by the last
/// usage in O(1) time.
///
/// Useful links:
/// https://en.wikipedia.org/wiki/Cache_replacement_policies
/// https://www.enjoyalgorithms.com/blog/least-frequently-used-cache
/// https://www.educative.io/answers/what-is-least-frequently-used-cache-replace-policy
/// https://leetcode.com/problems/lfu-cache/ .
/// </remarks>
public class LfuCache<TKey, TValue> where TKey : notnull
{
private class CachedItem
{
public TKey Key { get; set; } = default!;
public TValue? Value { get; set; }
public int Frequency { get; set; }
}
private const int DefaultCapacity = 100;
private readonly int capacity;
// Note that <c>Dictionary</c> stores <c>LinkedListNode</c> as it allows
// removing the node from the <c>LinkedList</c> in O(1) time.
private readonly Dictionary<TKey, LinkedListNode<CachedItem>> cache = new();
// Map frequency (number of times the item was requested or updated)
// to the LRU linked list.
private readonly Dictionary<int, LinkedList<CachedItem>> frequencies = new();
// Track the minimum frequency with non-empty linked list in <c>frequencies</c>.
// When the last item with the minFrequency is promoted (after being requested or updated),
// the <c>minFrequency</c> is increased.
// When a new item is added, the <c>minFrequency</c> is set to 1.
private int minFrequency = -1;
/// <summary>
/// Initializes a new instance of the <see cref="LfuCache{TKey, TValue}"/> class.
/// </summary>
/// <param name="capacity">The max number of items the cache can store.</param>
public LfuCache(int capacity = DefaultCapacity)
{
this.capacity = capacity;
}
public bool Contains(TKey key) => cache.ContainsKey(key);
/// <summary>
/// Gets the cached item by key.
/// </summary>
/// <param name="key">The key of cached item.</param>
/// <returns>The cached item or <c>default</c> if item is not found.</returns>
/// <remarks> Time complexity: O(1). </remarks>
public TValue? Get(TKey key)
{
if (!cache.ContainsKey(key))
{
return default;
}
var node = cache[key];
UpdateFrequency(node, isNew: false);
return node.Value.Value;
}
/// <summary>
/// Adds or updates the value in the cache.
/// </summary>
/// <param name="key">The key of item to cache.</param>
/// <param name="value">The value to cache.</param>
/// <remarks>
/// Time complexity: O(1).
/// If the value is already cached, it is updated and the item is moved
/// to the end of the LRU list.
/// If the cache is full, one of the least frequently used items is removed.
/// </remarks>
public void Put(TKey key, TValue value)
{
if (cache.ContainsKey(key))
{
var existingNode = cache[key];
existingNode.Value.Value = value;
UpdateFrequency(existingNode, isNew: false);
return;
}
if (cache.Count >= capacity)
{
EvictOneItem();
}
var item = new CachedItem { Key = key, Value = value };
var newNode = new LinkedListNode<CachedItem>(item);
UpdateFrequency(newNode, isNew: true);
cache.Add(key, newNode);
}
private void UpdateFrequency(LinkedListNode<CachedItem> node, bool isNew)
{
var item = node.Value;
if (isNew)
{
item.Frequency = 1;
minFrequency = 1;
}
else
{
// Remove the existing node from the LRU list with its previous frequency.
var lruList = frequencies[item.Frequency];
lruList.Remove(node);
if (lruList.Count == 0 && minFrequency == item.Frequency)
{
minFrequency++;
}
item.Frequency++;
}
// Insert item to the end of the LRU list that corresponds to its new frequency.
if (!frequencies.ContainsKey(item.Frequency))
{
frequencies[item.Frequency] = new LinkedList<CachedItem>();
}
frequencies[item.Frequency].AddLast(node);
}
private void EvictOneItem()
{
var lruList = frequencies[minFrequency];
var itemToRemove = lruList.First!.Value;
lruList.RemoveFirst();
cache.Remove(itemToRemove.Key);
}
}
}
| 159 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
namespace DataStructures.Cache
{
/// <summary>
/// Least Recently Used (LRU) cache implementation.
/// </summary>
/// <typeparam name="TKey">The type of the key (must be not null).</typeparam>
/// <typeparam name="TValue">The type of the value.</typeparam>
/// <remarks>
/// Cache keeps up to <c>capacity</c> items. When new item is added and cache is full,
/// the least recently used item is removed (e.g. it keeps N items that were recently requested
/// using <c>Get()</c> or <c>Put()</c> methods).
///
/// Cache is built on top of two data structures:
/// - <c>Dictionary</c> - allows items to be looked up by key in O(1) time.
/// - <c>LinkedList</c> - allows items to be ordered by last usage time in O(1) time.
///
/// Useful links:
/// https://en.wikipedia.org/wiki/Cache_replacement_policies
/// https://www.educative.io/m/implement-least-recently-used-cache
/// https://leetcode.com/problems/lru-cache/
///
/// In order to make the most recently used (MRU) cache, when the cache is full,
/// just remove the last node from the linked list in the method <c>Put</c>
/// (replace <c>RemoveFirst</c> with <c>RemoveLast</c>).
/// </remarks>
public class LruCache<TKey, TValue> where TKey : notnull
{
private class CachedItem
{
public TKey Key { get; set; } = default!;
public TValue? Value { get; set; }
}
private const int DefaultCapacity = 100;
private readonly int capacity;
// Note that <c>Dictionary</c> stores <c>LinkedListNode</c> as it allows
// removing the node from the <c>LinkedList</c> in O(1) time.
private readonly Dictionary<TKey, LinkedListNode<CachedItem>> cache = new();
private readonly LinkedList<CachedItem> lruList = new();
/// <summary>
/// Initializes a new instance of the <see cref="LruCache{TKey, TValue}"/> class.
/// </summary>
/// <param name="capacity">The max number of items the cache can store.</param>
public LruCache(int capacity = DefaultCapacity)
{
this.capacity = capacity;
}
public bool Contains(TKey key) => cache.ContainsKey(key);
/// <summary>
/// Gets the cached item by key.
/// </summary>
/// <param name="key">The key of cached item.</param>
/// <returns>The cached item or <c>default</c> if item is not found.</returns>
/// <remarks> Time complexity: O(1). </remarks>
public TValue? Get(TKey key)
{
if (!cache.ContainsKey(key))
{
return default;
}
var node = cache[key];
lruList.Remove(node);
lruList.AddLast(node);
return node.Value.Value;
}
/// <summary>
/// Adds or updates the value in the cache.
/// </summary>
/// <param name="key">The key of item to cache.</param>
/// <param name="value">The value to cache.</param>
/// <remarks>
/// Time complexity: O(1).
/// If the value is already cached, it is updated and the item is moved
/// to the end of the LRU list.
/// If the cache is full, the least recently used item is removed.
/// </remarks>
public void Put(TKey key, TValue value)
{
if (cache.ContainsKey(key))
{
var existingNode = cache[key];
existingNode.Value.Value = value;
lruList.Remove(existingNode);
lruList.AddLast(existingNode);
return;
}
if (cache.Count >= capacity)
{
var first = lruList.First!;
lruList.RemoveFirst();
cache.Remove(first.Value.Key);
}
var item = new CachedItem { Key = key, Value = value };
var newNode = lruList.AddLast(item);
cache.Add(key, newNode);
}
}
}
| 113 |
C-Sharp | TheAlgorithms | C# | using System.Collections;
namespace DataStructures.DisjointSet
{
/// <summary>
/// Implementation of Disjoint Set with Union By Rank and Path Compression heuristics.
/// </summary>
/// <typeparam name="T"> generic type for implementation.</typeparam>
public class DisjointSet<T>
{
/// <summary>
/// make a new set and return its representative.
/// </summary>
/// <param name="x">element to add in to the DS.</param>
/// <returns>representative of x.</returns>
public Node<T> MakeSet(T x) => new(x);
/// <summary>
/// find the representative of a certain node.
/// </summary>
/// <param name="node">node to find representative.</param>
/// <returns>representative of x.</returns>
public Node<T> FindSet(Node<T> node)
{
if (node != node.Parent)
{
node.Parent = FindSet(node.Parent);
}
return node.Parent;
}
/// <summary>
/// merge two sets.
/// </summary>
/// <param name="x">first set member.</param>
/// <param name="y">second set member.</param>
public void UnionSet(Node<T> x, Node<T> y)
{
Node<T> nx = FindSet(x);
Node<T> ny = FindSet(y);
if (nx == ny)
{
return;
}
if (nx.Rank > ny.Rank)
{
ny.Parent = nx;
}
else if (ny.Rank > nx.Rank)
{
nx.Parent = ny;
}
else
{
nx.Parent = ny;
ny.Rank++;
}
}
}
}
| 63 |
C-Sharp | TheAlgorithms | C# | namespace DataStructures.DisjointSet
{
/// <summary>
/// node class to be used by disjoint set to represent nodes in Disjoint Set forest.
/// </summary>
/// <typeparam name="T">generic type for data to be stored.</typeparam>
public class Node<T>
{
public int Rank { get; set; }
public Node<T> Parent { get; set; }
public T Data { get; set; }
public Node(T data)
{
Data = data;
Parent = this;
}
}
}
| 22 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
namespace DataStructures.Graph
{
/// <summary>
/// Implementation of the directed weighted graph via adjacency matrix.
/// </summary>
/// <typeparam name="T">Generic Type.</typeparam>
public class DirectedWeightedGraph<T> : IDirectedWeightedGraph<T>
{
/// <summary>
/// Capacity of the graph, indicates the maximum amount of vertices.
/// </summary>
private readonly int capacity;
/// <summary>
/// Adjacency matrix which reflects the edges between vertices and their weight.
/// Zero value indicates no edge between two vertices.
/// </summary>
private readonly double[,] adjacencyMatrix;
/// <summary>
/// Initializes a new instance of the <see cref="DirectedWeightedGraph{T}"/> class.
/// </summary>
/// <param name="capacity">Capacity of the graph, indicates the maximum amount of vertices.</param>
public DirectedWeightedGraph(int capacity)
{
ThrowIfNegativeCapacity(capacity);
this.capacity = capacity;
Vertices = new Vertex<T>[capacity];
adjacencyMatrix = new double[capacity, capacity];
Count = 0;
}
/// <summary>
/// Gets list of vertices of the graph.
/// </summary>
public Vertex<T>?[] Vertices { get; private set; }
/// <summary>
/// Gets current amount of vertices in the graph.
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Adds new vertex to the graph.
/// </summary>
/// <param name="data">Data of the vertex.</param>
/// <returns>Reference to created vertex.</returns>
public Vertex<T> AddVertex(T data)
{
ThrowIfOverflow();
var vertex = new Vertex<T>(data, Count, this);
Vertices[Count] = vertex;
Count++;
return vertex;
}
/// <summary>
/// Creates an edge between two vertices of the graph.
/// </summary>
/// <param name="startVertex">Vertex, edge starts at.</param>
/// <param name="endVertex">Vertex, edge ends at.</param>
/// <param name="weight">Double weight of an edge.</param>
public void AddEdge(Vertex<T> startVertex, Vertex<T> endVertex, double weight)
{
ThrowIfVertexNotInGraph(startVertex);
ThrowIfVertexNotInGraph(endVertex);
ThrowIfWeightZero(weight);
var currentEdgeWeight = adjacencyMatrix[startVertex.Index, endVertex.Index];
ThrowIfEdgeExists(currentEdgeWeight);
adjacencyMatrix[startVertex.Index, endVertex.Index] = weight;
}
/// <summary>
/// Removes vertex from the graph.
/// </summary>
/// <param name="vertex">Vertex to be removed.</param>
public void RemoveVertex(Vertex<T> vertex)
{
ThrowIfVertexNotInGraph(vertex);
Vertices[vertex.Index] = null;
vertex.SetGraphNull();
for (var i = 0; i < Count; i++)
{
adjacencyMatrix[i, vertex.Index] = 0;
adjacencyMatrix[vertex.Index, i] = 0;
}
Count--;
}
/// <summary>
/// Removes edge between two vertices.
/// </summary>
/// <param name="startVertex">Vertex, edge starts at.</param>
/// <param name="endVertex">Vertex, edge ends at.</param>
public void RemoveEdge(Vertex<T> startVertex, Vertex<T> endVertex)
{
ThrowIfVertexNotInGraph(startVertex);
ThrowIfVertexNotInGraph(endVertex);
adjacencyMatrix[startVertex.Index, endVertex.Index] = 0;
}
/// <summary>
/// Gets a neighbors of particular vertex.
/// </summary>
/// <param name="vertex">Vertex, method gets list of neighbors for.</param>
/// <returns>Collection of the neighbors of particular vertex.</returns>
public IEnumerable<Vertex<T>?> GetNeighbors(Vertex<T> vertex)
{
ThrowIfVertexNotInGraph(vertex);
for (var i = 0; i < Count; i++)
{
if (adjacencyMatrix[vertex.Index, i] != 0)
{
yield return Vertices[i];
}
}
}
/// <summary>
/// Returns true, if there is an edge between two vertices.
/// </summary>
/// <param name="startVertex">Vertex, edge starts at.</param>
/// <param name="endVertex">Vertex, edge ends at.</param>
/// <returns>True if edge exists, otherwise false.</returns>
public bool AreAdjacent(Vertex<T> startVertex, Vertex<T> endVertex)
{
ThrowIfVertexNotInGraph(startVertex);
ThrowIfVertexNotInGraph(endVertex);
return adjacencyMatrix[startVertex.Index, endVertex.Index] != 0;
}
/// <summary>
/// Return the distance between two vertices in the graph.
/// </summary>
/// <param name="startVertex">first vertex in edge.</param>
/// <param name="endVertex">secnod vertex in edge.</param>
/// <returns>distance between the two.</returns>
public double AdjacentDistance(Vertex<T> startVertex, Vertex<T> endVertex)
{
if (AreAdjacent(startVertex, endVertex))
{
return adjacencyMatrix[startVertex.Index, endVertex.Index];
}
return 0;
}
private static void ThrowIfNegativeCapacity(int capacity)
{
if (capacity < 0)
{
throw new InvalidOperationException("Graph capacity should always be a non-negative integer.");
}
}
private static void ThrowIfWeightZero(double weight)
{
if (weight.Equals(0.0d))
{
throw new InvalidOperationException("Edge weight cannot be zero.");
}
}
private static void ThrowIfEdgeExists(double currentEdgeWeight)
{
if (!currentEdgeWeight.Equals(0.0d))
{
throw new InvalidOperationException($"Vertex already exists: {currentEdgeWeight}");
}
}
private void ThrowIfOverflow()
{
if (Count == capacity)
{
throw new InvalidOperationException("Graph overflow.");
}
}
private void ThrowIfVertexNotInGraph(Vertex<T> vertex)
{
if (vertex.Graph != this)
{
throw new InvalidOperationException($"Vertex does not belong to graph: {vertex}.");
}
}
}
}
| 202 |
C-Sharp | TheAlgorithms | C# | using System.Collections.Generic;
namespace DataStructures.Graph
{
public interface IDirectedWeightedGraph<T>
{
int Count { get; }
Vertex<T>?[] Vertices { get; }
void AddEdge(Vertex<T> startVertex, Vertex<T> endVertex, double weight);
Vertex<T> AddVertex(T data);
bool AreAdjacent(Vertex<T> startVertex, Vertex<T> endVertex);
double AdjacentDistance(Vertex<T> startVertex, Vertex<T> endVertex);
IEnumerable<Vertex<T>?> GetNeighbors(Vertex<T> vertex);
void RemoveEdge(Vertex<T> startVertex, Vertex<T> endVertex);
void RemoveVertex(Vertex<T> vertex);
}
}
| 26 |
C-Sharp | TheAlgorithms | C# | namespace DataStructures.Graph
{
/// <summary>
/// Implementation of graph vertex.
/// </summary>
/// <typeparam name="T">Generic Type.</typeparam>
public class Vertex<T>
{
/// <summary>
/// Gets vertex data.
/// </summary>
public T Data { get; }
/// <summary>
/// Gets an index of the vertex in graph adjacency matrix.
/// </summary>
public int Index { get; }
/// <summary>
/// Gets reference to the graph this vertex belongs to.
/// </summary>
public DirectedWeightedGraph<T>? Graph { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Vertex{T}"/> class.
/// </summary>
/// <param name="data">Vertex data. Generic type.</param>
/// <param name="index">Index of the vertex in graph adjacency matrix.</param>
/// <param name="graph">Graph this vertex belongs to.</param>
public Vertex(T data, int index, DirectedWeightedGraph<T>? graph)
{
Data = data;
Index = index;
Graph = graph;
}
/// <summary>
/// Initializes a new instance of the <see cref="Vertex{T}"/> class.
/// </summary>
/// <param name="data">Vertex data. Generic type.</param>
/// <param name="index">Index of the vertex in graph adjacency matrix.</param>
public Vertex(T data, int index)
{
Data = data;
Index = index;
}
/// <summary>
/// Sets graph reference to the null. This method called when vertex removed from the graph.
/// </summary>
public void SetGraphNull() => Graph = null;
/// <summary>
/// Override of base ToString method. Prints vertex data and index in graph adjacency matrix.
/// </summary>
/// <returns>String which contains vertex data and index in graph adjacency matrix..</returns>
public override string ToString() => $"Vertex Data: {Data}, Index: {Index}";
}
}
| 60 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
namespace DataStructures.Heap
{
/// <summary>
/// A generic implementation of a binary heap.
/// </summary>
/// <remarks>
/// A binary heap is a complete binary tree that satisfies the heap property;
/// that is every node in the tree compares greater/less than or equal to its left and right
/// child nodes. Note that this is different from a binary search tree, where every node
/// must be the largest/smallest node of all of its children.
/// Although binary heaps are not very efficient, they are (probably) the simpliest heaps
/// to understand and implement.
/// More information: https://en.wikipedia.org/wiki/Binary_heap .
/// </remarks>
/// <typeparam name="T">Type of elements in binary heap.</typeparam>
public class BinaryHeap<T>
{
/// <summary>
/// Comparer to use when comparing elements.
/// </summary>
private readonly Comparer<T> comparer;
/// <summary>
/// List to hold the elements of the heap.
/// </summary>
private readonly List<T> data;
/// <summary>
/// Initializes a new instance of the <see cref="BinaryHeap{T}" /> class.
/// </summary>
public BinaryHeap()
{
data = new List<T>();
comparer = Comparer<T>.Default;
}
/// <summary>
/// Initializes a new instance of the <see cref="BinaryHeap{T}" /> class with a custom comparision function.
/// </summary>
/// <param name="customComparer">The custom comparing function to use to compare elements.</param>
public BinaryHeap(Comparer<T> customComparer)
{
data = new List<T>();
comparer = customComparer;
}
/// <summary>
/// Gets the number of elements in the heap.
/// </summary>
public int Count => data.Count;
/// <summary>
/// Add an element to the binary heap.
/// </summary>
/// <remarks>
/// Adding to the heap is done by append the element to the end of the backing list,
/// and pushing the added element up until the heap property is restored.
/// </remarks>
/// <param name="element">The element to add to the heap.</param>
/// <exception cref="ArgumentException">Thrown if element is already in heap.</exception>
public void Push(T element)
{
data.Add(element);
HeapifyUp(data.Count - 1);
}
/// <summary>
/// Remove the top/root of the binary heap (ie: the largest/smallest element).
/// </summary>
/// <remarks>
/// Removing from the heap is done by swapping the top/root with the last element in
/// the backing list, removing the last element, and pushing the new root down
/// until the heap property is restored.
/// </remarks>
/// <returns>The top/root of the heap.</returns>
/// <exception cref="InvalidOperationException">Thrown if heap is empty.</exception>
public T Pop()
{
if (Count == 0)
{
throw new InvalidOperationException("Heap is empty!");
}
var elem = data[0];
data[0] = data[^1];
data.RemoveAt(data.Count - 1);
HeapifyDown(0);
return elem;
}
/// <summary>
/// Return the top/root of the heap without removing it.
/// </summary>
/// <returns>The top/root of the heap.</returns>
/// <exception cref="InvalidOperationException">Thrown if heap is empty.</exception>
public T Peek()
{
if (Count == 0)
{
throw new InvalidOperationException("Heap is empty!");
}
return data[0];
}
/// <summary>
/// Returns element if it compares larger to the top/root of the heap, else
/// inserts element into the heap and returns the top/root of the heap.
/// </summary>
/// <param name="element">The element to check/insert.</param>
/// <returns>element if element compares larger than top/root of heap, top/root of heap otherwise.</returns>
public T PushPop(T element)
{
if (Count == 0)
{
return element;
}
if (comparer.Compare(element, data[0]) < 0)
{
var tmp = data[0];
data[0] = element;
HeapifyDown(0);
return tmp;
}
return element;
}
/// <summary>
/// Check if element is in the heap.
/// </summary>
/// <param name="element">The element to check for.</param>
/// <returns>true if element is in the heap, false otherwise.</returns>
public bool Contains(T element) => data.Contains(element);
/// <summary>
/// Remove an element from the heap.
/// </summary>
/// <remarks>
/// In removing an element from anywhere in the heap, we only need to push down or up
/// the replacement value depending on how the removed value compares to its
/// replacement value.
/// </remarks>
/// <param name="element">The element to remove from the heap.</param>
/// <exception cref="ArgumentException">Thrown if element is not in heap.</exception>
public void Remove(T element)
{
var idx = data.IndexOf(element);
if (idx == -1)
{
throw new ArgumentException($"{element} not in heap!");
}
Swap(idx, data.Count - 1);
var tmp = data[^1];
data.RemoveAt(data.Count - 1);
if (idx < data.Count)
{
if (comparer.Compare(tmp, data[idx]) > 0)
{
HeapifyDown(idx);
}
else
{
HeapifyUp(idx);
}
}
}
/// <summary>
/// Swap the elements in the heap array at the given indices.
/// </summary>
/// <param name="idx1">First index.</param>
/// <param name="idx2">Second index.</param>
private void Swap(int idx1, int idx2)
{
var tmp = data[idx1];
data[idx1] = data[idx2];
data[idx2] = tmp;
}
/// <summary>
/// Recursive function to restore heap properties.
/// </summary>
/// <remarks>
/// Restores heap property by swapping the element at <paramref name="elemIdx" />
/// with its parent if the element compares greater than its parent.
/// </remarks>
/// <param name="elemIdx">The element to check with its parent.</param>
private void HeapifyUp(int elemIdx)
{
var parent = (elemIdx - 1) / 2;
if (parent >= 0 && comparer.Compare(data[elemIdx], data[parent]) > 0)
{
Swap(elemIdx, parent);
HeapifyUp(parent);
}
}
/// <summary>
/// Recursive function to restore heap properties.
/// </summary>
/// <remarks>
/// Restores heap property by swapping the element at <paramref name="elemIdx" />
/// with the larger of its children.
/// </remarks>
/// <param name="elemIdx">The element to check with its children.</param>
private void HeapifyDown(int elemIdx)
{
var left = 2 * elemIdx + 1;
var right = 2 * elemIdx + 2;
var leftLargerThanElem = left < Count && comparer.Compare(data[elemIdx], data[left]) < 0;
var rightLargerThanElem = right < Count && comparer.Compare(data[elemIdx], data[right]) < 0;
var leftLargerThanRight = left < Count && right < Count && comparer.Compare(data[left], data[right]) > 0;
if (leftLargerThanElem && leftLargerThanRight)
{
Swap(elemIdx, left);
HeapifyDown(left);
}
else if (rightLargerThanElem && !leftLargerThanRight)
{
Swap(elemIdx, right);
HeapifyDown(right);
}
}
}
}
| 238 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace DataStructures.Heap
{
/// <summary>
/// This class implements min-max heap.
/// It provides functionality of both min-heap and max-heap with the same time complexity.
/// Therefore it provides constant time retrieval and logarithmic time removal
/// of both the minimum and maximum elements in it.
/// </summary>
/// <typeparam name="T">Generic type.</typeparam>
public class MinMaxHeap<T>
{
private readonly List<T> heap;
/// <summary>
/// Initializes a new instance of the <see cref="MinMaxHeap{T}" /> class that contains
/// elements copied from a specified enumerable collection and that uses a specified comparer.
/// </summary>
/// <param name="collection">The enumerable collection to be copied.</param>
/// <param name="comparer">The default comparer to use for comparing objects.</param>
public MinMaxHeap(IEnumerable<T>? collection = null, IComparer<T>? comparer = null)
{
Comparer = comparer ?? Comparer<T>.Default;
collection ??= Enumerable.Empty<T>();
heap = collection.ToList();
for (var i = Count / 2 - 1; i >= 0; --i)
{
PushDown(i);
}
}
/// <summary>
/// Gets the <see cref="IComparer{T}" />. object that is used to order the values in the <see cref="MinMaxHeap{T}" />.
/// </summary>
public IComparer<T> Comparer { get; }
/// <summary>
/// Gets the number of elements in the <see cref="MinMaxHeap{T}" />.
/// </summary>
public int Count => heap.Count;
/// <summary>
/// Adds an element to the heap.
/// </summary>
/// <param name="item">The element to add to the heap.</param>
public void Add(T item)
{
heap.Add(item);
PushUp(Count - 1);
}
/// <summary>
/// Removes the maximum node from the heap and returns its value.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if heap is empty.</exception>
/// <returns>Value of the removed maximum node.</returns>
public T ExtractMax()
{
if (Count == 0)
{
throw new InvalidOperationException("Heap is empty");
}
var max = GetMax();
RemoveNode(GetMaxNodeIndex());
return max;
}
/// <summary>
/// Removes the minimum node from the heap and returns its value.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if heap is empty.</exception>
/// <returns>Value of the removed minimum node.</returns>
public T ExtractMin()
{
if (Count == 0)
{
throw new InvalidOperationException("Heap is empty");
}
var min = GetMin();
RemoveNode(0);
return min;
}
/// <summary>
/// Gets the maximum value in the heap, as defined by the comparer.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if heap is empty.</exception>
/// <returns>The maximum value in the heap.</returns>
public T GetMax()
{
if (Count == 0)
{
throw new InvalidOperationException("Heap is empty");
}
return heap[GetMaxNodeIndex()];
}
/// <summary>
/// Gets the minimum value in the heap, as defined by the comparer.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown if heap is empty.</exception>
/// <returns>The minimum value in the heap.</returns>
public T GetMin()
{
if (Count == 0)
{
throw new InvalidOperationException("Heap is empty");
}
return heap[0];
}
/// <summary>
/// Finds maximum value among children and grandchildren of the specified node.
/// </summary>
/// <param name="index">Index of the node in the Heap array.</param>
/// <returns>Index of the maximum descendant.</returns>
private int IndexOfMaxChildOrGrandchild(int index)
{
var descendants = new[]
{
2 * index + 1,
2 * index + 2,
4 * index + 3,
4 * index + 4,
4 * index + 5,
4 * index + 6,
};
var resIndex = descendants[0];
foreach (var descendant in descendants)
{
if (descendant >= Count)
{
break;
}
if (Comparer.Compare(heap[descendant], heap[resIndex]) > 0)
{
resIndex = descendant;
}
}
return resIndex;
}
/// <summary>
/// Finds minumum value among children and grandchildren of the specified node.
/// </summary>
/// <param name="index">Index of the node in the Heap array.</param>
/// <returns>Index of the minimum descendant.</returns>
private int IndexOfMinChildOrGrandchild(int index)
{
var descendants = new[] { 2 * index + 1, 2 * index + 2, 4 * index + 3, 4 * index + 4, 4 * index + 5, 4 * index + 6 };
var resIndex = descendants[0];
foreach (var descendant in descendants)
{
if (descendant >= Count)
{
break;
}
if (Comparer.Compare(heap[descendant], heap[resIndex]) < 0)
{
resIndex = descendant;
}
}
return resIndex;
}
private int GetMaxNodeIndex()
{
return Count switch
{
0 => throw new InvalidOperationException("Heap is empty"),
1 => 0,
2 => 1,
_ => Comparer.Compare(heap[1], heap[2]) > 0 ? 1 : 2,
};
}
private bool HasChild(int index) => index * 2 + 1 < Count;
private bool IsGrandchild(int node, int grandchild) => grandchild > 2 && Grandparent(grandchild) == node;
/// <summary>
/// Checks if node at index belongs to Min or Max level of the heap.
/// Root node belongs to Min level, its children - Max level,
/// its grandchildren - Min level, and so on.
/// </summary>
/// <param name="index">Index to check.</param>
/// <returns>true if index is at Min level; false if it is at Max Level.</returns>
private bool IsMinLevelIndex(int index)
{
// For all Min levels, value (index + 1) has the leftmost bit set to '1' at even position.
const uint minLevelsBits = 0x55555555;
const uint maxLevelsBits = 0xAAAAAAAA;
return ((index + 1) & minLevelsBits) > ((index + 1) & maxLevelsBits);
}
private int Parent(int index) => (index - 1) / 2;
private int Grandparent(int index) => ((index - 1) / 2 - 1) / 2;
/// <summary>
/// Assuming that children sub-trees are valid heaps, pushes node to lower levels
/// to make heap valid.
/// </summary>
/// <param name="index">Node index.</param>
private void PushDown(int index)
{
if (IsMinLevelIndex(index))
{
PushDownMin(index);
}
else
{
PushDownMax(index);
}
}
private void PushDownMax(int index)
{
if (!HasChild(index))
{
return;
}
var maxIndex = IndexOfMaxChildOrGrandchild(index);
// If smaller element are put at min level (as result of swaping), it doesn't affect sub-tree validity.
// If smaller element are put at max level, PushDownMax() should be called for that node.
if (IsGrandchild(index, maxIndex))
{
if (Comparer.Compare(heap[maxIndex], heap[index]) > 0)
{
SwapNodes(maxIndex, index);
if (Comparer.Compare(heap[maxIndex], heap[Parent(maxIndex)]) < 0)
{
SwapNodes(maxIndex, Parent(maxIndex));
}
PushDownMax(maxIndex);
}
}
else
{
if (Comparer.Compare(heap[maxIndex], heap[index]) > 0)
{
SwapNodes(maxIndex, index);
}
}
}
private void PushDownMin(int index)
{
if (!HasChild(index))
{
return;
}
var minIndex = IndexOfMinChildOrGrandchild(index);
// If bigger element are put at max level (as result of swaping), it doesn't affect sub-tree validity.
// If bigger element are put at min level, PushDownMin() should be called for that node.
if (IsGrandchild(index, minIndex))
{
if (Comparer.Compare(heap[minIndex], heap[index]) < 0)
{
SwapNodes(minIndex, index);
if (Comparer.Compare(heap[minIndex], heap[Parent(minIndex)]) > 0)
{
SwapNodes(minIndex, Parent(minIndex));
}
PushDownMin(minIndex);
}
}
else
{
if (Comparer.Compare(heap[minIndex], heap[index]) < 0)
{
SwapNodes(minIndex, index);
}
}
}
/// <summary>
/// Having a new node in the heap, swaps this node with its ancestors to make heap valid.
/// For node at min level. If new node is less than its parent, then it is surely less then
/// all other nodes on max levels on path to the root of the heap. So node are pushed up, by
/// swaping with its grandparent, until they are ordered correctly.
/// For node at max level algorithm is analogical.
/// </summary>
/// <param name="index">Index of the new node.</param>
private void PushUp(int index)
{
if (index == 0)
{
return;
}
var parent = Parent(index);
if (IsMinLevelIndex(index))
{
if (Comparer.Compare(heap[index], heap[parent]) > 0)
{
SwapNodes(index, parent);
PushUpMax(parent);
}
else
{
PushUpMin(index);
}
}
else
{
if (Comparer.Compare(heap[index], heap[parent]) < 0)
{
SwapNodes(index, parent);
PushUpMin(parent);
}
else
{
PushUpMax(index);
}
}
}
private void PushUpMax(int index)
{
if (index > 2)
{
var grandparent = Grandparent(index);
if (Comparer.Compare(heap[index], heap[grandparent]) > 0)
{
SwapNodes(index, grandparent);
PushUpMax(grandparent);
}
}
}
private void PushUpMin(int index)
{
if (index > 2)
{
var grandparent = Grandparent(index);
if (Comparer.Compare(heap[index], heap[grandparent]) < 0)
{
SwapNodes(index, grandparent);
PushUpMin(grandparent);
}
}
}
private void RemoveNode(int index)
{
SwapNodes(index, Count - 1);
heap.RemoveAt(Count - 1);
if (Count != 0)
{
PushDown(index);
}
}
private void SwapNodes(int i, int j)
{
var temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
}
}
| 382 |
C-Sharp | TheAlgorithms | C# | using System;
namespace DataStructures.Heap.FibonacciHeap
{
/// <summary>
/// These FHeapNodes are the bulk of the data structure. The have pointers to
/// their parent, a left and right sibling, and to a child. A node and its
/// siblings comprise a circularly doubly linked list.
/// </summary>
/// <typeparam name="T">A type that can be compared.</typeparam>
public class FHeapNode<T> where T : IComparable
{
/// <summary>
/// Initializes a new instance of the <see cref="FHeapNode{T}" /> class.
/// </summary>
/// <param name="key">An item in the Fibonacci heap.</param>
public FHeapNode(T key)
{
Key = key;
// Since even a single node must form a circularly doubly linked list,
// initialize it as such
Left = Right = this;
Parent = Child = null;
}
/// <summary>
/// Gets or sets the data of this node.
/// </summary>
public T Key { get; set; }
/// <summary>
/// Gets or sets a reference to the parent.
/// </summary>
public FHeapNode<T>? Parent { get; set; }
/// <summary>
/// Gets or sets a reference to the left sibling.
/// </summary>
public FHeapNode<T> Left { get; set; }
/// <summary>
/// Gets or sets a reference to the right sibling.
/// </summary>
public FHeapNode<T> Right { get; set; }
/// <summary>
/// Gets or sets a reference to one of the children, there may be more that
/// are siblings the this child, however this structure only maintains a
/// reference to one of them.
/// </summary>
public FHeapNode<T>? Child { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this node has been marked,
/// used in some operations.
/// </summary>
public bool Mark { get; set; }
/// <summary>
/// Gets or sets the number of nodes in the child linked list.
/// </summary>
public int Degree { get; set; }
public void SetSiblings(FHeapNode<T> left, FHeapNode<T> right)
{
Left = left;
Right = right;
}
/// <summary>
/// A helper function to add a node to the right of this one in the current
/// circularly doubly linked list.
/// </summary>
/// <param name="node">A node to go in the linked list.</param>
public void AddRight(FHeapNode<T> node)
{
Right.Left = node;
node.Right = Right;
node.Left = this;
Right = node;
}
/// <summary>
/// Similar to AddRight, but adds the node as a sibling to the child node.
/// </summary>
/// <param name="node">A node to add to the child list of this node.</param>
public void AddChild(FHeapNode<T> node)
{
Degree++;
if (Child == null)
{
Child = node;
Child.Parent = this;
Child.Left = Child.Right = Child;
return;
}
Child.AddRight(node);
}
/// <summary>
/// Remove this item from the linked list it's in.
/// </summary>
public void Remove()
{
Left.Right = Right;
Right.Left = Left;
}
/// <summary>
/// Combine the linked list that <c>otherList</c> sits inside, with the
/// linked list this is in. Do this by cutting the link between this node,
/// and the node to the right of this, and inserting the contents of the
/// otherList in between.
/// </summary>
/// <param name="otherList">
/// A node from another list whose elements we want
/// to concatenate to this list.
/// </param>
public void ConcatenateRight(FHeapNode<T> otherList)
{
Right.Left = otherList.Left;
otherList.Left.Right = Right;
Right = otherList;
otherList.Left = this;
}
}
}
| 133 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace DataStructures.Heap.FibonacciHeap
{
/// <summary>
/// A generic implementation of a Fibonacci heap.
/// </summary>
/// <remarks>
/// <para>
/// A Fibonacci heap is similar to a standard binary heap
/// <see cref="DataStructures.Heap.BinaryHeap{T}" />, however it uses concepts
/// of amortized analysis to provide theoretical speedups on common operations like
/// insert, union, and decrease-key while maintaining the same speed on all other
/// operations.
/// </para>
/// <para>
/// In practice, Fibonacci heaps are more complicated than binary heaps and require
/// a large input problems before the benifits of the theoretical speed up
/// begin to show.
/// </para>
/// <para>
/// References:
/// [1] Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
/// and Clifford Stein. 2009. Introduction to Algorithms, Third Edition (3rd. ed.).
/// The MIT Press.
/// </para>
/// </remarks>
/// <typeparam name="T">Type of elements in binary heap.</typeparam>
public class FibonacciHeap<T> where T : IComparable
{
/// <summary>
/// Gets or sets the count of the number of nodes in the Fibonacci heap.
/// </summary>
public int Count { get; set; }
/// <summary>
/// Gets or sets a reference to the MinItem. The MinItem and all of its siblings
/// comprise the root list, a list of trees that satisfy the heap property and
/// are joined in a circularly doubly linked list.
/// </summary>
private FHeapNode<T>? MinItem { get; set; }
/// <summary>
/// Add item <c>x</c> to this Fibonacci heap.
/// </summary>
/// <remarks>
/// To add an item to a Fibonacci heap, we simply add it to the "root list",
/// a circularly doubly linked list where our minimum item sits. Since adding
/// items to a linked list takes O(1) time, the overall time to perform this
/// operation is O(1).
/// </remarks>
/// <param name="x">An item to push onto the heap.</param>
/// <returns>
/// A reference to the item as it is in the heap. This is used for
/// operations like decresing key.
/// </returns>
public FHeapNode<T> Push(T x)
{
Count++;
var newItem = new FHeapNode<T>(x);
if (MinItem == null)
{
MinItem = newItem;
}
else
{
MinItem.AddRight(newItem);
if (newItem.Key.CompareTo(MinItem.Key) < 0)
{
MinItem = newItem;
}
}
return newItem;
}
/// <summary>
/// Combines all the elements of two fibonacci heaps.
/// </summary>
/// <remarks>
/// To union two Fibonacci heaps is a single fibonacci heap is a single heap
/// that contains all the elements of both heaps. This can be done in O(1) time
/// by concatenating the root lists together.
/// For more details on how two circularly linked lists are concatenated, see
/// <see cref="FHeapNode{T}.ConcatenateRight" />
/// Finally, check to see which of <c>this.MinItem</c> and <c>other.MinItem</c>
/// is smaller, and set <c>this.MinItem</c> accordingly
/// This operation destroys <c>other</c>.
/// </remarks>
/// <param name="other">
/// Another heap whose elements we wish to add to this heap.
/// The other heap will be destroyed as a result.
/// </param>
public void Union(FibonacciHeap<T> other)
{
// If there are no items in the other heap, then there is nothing to do.
if (other.MinItem == null)
{
return;
}
// If this heap is empty, simply set it equal to the other heap
if (MinItem == null)
{
// Set this heap to the other one
MinItem = other.MinItem;
Count = other.Count;
// Destroy the other heap
other.MinItem = null;
other.Count = 0;
return;
}
Count += other.Count;
// <see cref="DataStructures.FibonacciHeap{T}.FHeapNode.ConcatenateRight(DataStructures.FibonacciHeap{T}.FHeapNode)"/>
MinItem.ConcatenateRight(other.MinItem);
// Set the MinItem to the smaller of the two MinItems
if (other.MinItem.Key.CompareTo(MinItem.Key) < 0)
{
MinItem = other.MinItem;
}
other.MinItem = null;
other.Count = 0;
}
/// <summary>
/// Return the MinItem and remove it from the heap.
/// </summary>
/// <remarks>
/// This function (with all of its helper functions) is the most complicated
/// part of the Fibonacci Heap. However, it can be broken down into a few steps.
/// <list type="number">
/// <item>
/// Add the children of MinItem to the root list. Either one of these children,
/// or another of the items in the root list is a candidate to become the new
/// MinItem.
/// </item>
/// <item>
/// Remove the MinItem from the root list and appoint a new MinItem temporarily.
/// </item>
/// <item>
/// <see cref="Consolidate" /> what's left
/// of the heap.
/// </item>
/// </list>
/// </remarks>
/// <returns>The minimum item from the heap.</returns>
public T Pop()
{
FHeapNode<T>? z = null;
if (MinItem == null)
{
throw new InvalidOperationException("Heap is empty!");
}
z = MinItem;
// Since z is leaving the heap, add its children to the root list
if (z.Child != null)
{
foreach (var x in SiblingIterator(z.Child))
{
x.Parent = null;
}
// This effectively adds each child x to the root list
z.ConcatenateRight(z.Child);
}
if (Count == 1)
{
MinItem = null;
Count = 0;
return z.Key;
}
// Temporarily reassign MinItem to an arbitrary item in the root
// list
MinItem = MinItem.Right;
// Remove the old MinItem from the root list altogether
z.Remove();
// Consolidate the heap
Consolidate();
Count -= 1;
return z.Key;
}
/// <summary>
/// A method to see what's on top of the heap without changing its structure.
/// </summary>
/// <returns>
/// Returns the top element without popping it from the structure of
/// the heap.
/// </returns>
public T Peek()
{
if (MinItem == null)
{
throw new InvalidOperationException("The heap is empty");
}
return MinItem.Key;
}
/// <summary>
/// Reduce the key of x to be k.
/// </summary>
/// <remarks>
/// k must be less than x.Key, increasing the key of an item is not supported.
/// </remarks>
/// <param name="x">The item you want to reduce in value.</param>
/// <param name="k">The new value for the item.</param>
public void DecreaseKey(FHeapNode<T> x, T k)
{
if (MinItem == null)
{
throw new ArgumentException($"{nameof(x)} is not from the heap");
}
if (x.Key == null)
{
throw new ArgumentException("x has no value");
}
if (k.CompareTo(x.Key) > 0)
{
throw new InvalidOperationException("Value cannot be increased");
}
x.Key = k;
var y = x.Parent;
if (y != null && x.Key.CompareTo(y.Key) < 0)
{
Cut(x, y);
CascadingCut(y);
}
if (x.Key.CompareTo(MinItem.Key) < 0)
{
MinItem = x;
}
}
/// <summary>
/// Remove x from the child list of y.
/// </summary>
/// <param name="x">A child of y we just decreased the value of.</param>
/// <param name="y">The now former parent of x.</param>
protected void Cut(FHeapNode<T> x, FHeapNode<T> y)
{
if (MinItem == null)
{
throw new InvalidOperationException("Heap malformed");
}
if (y.Degree == 1)
{
y.Child = null;
MinItem.AddRight(x);
}
else if (y.Degree > 1)
{
x.Remove();
}
else
{
throw new InvalidOperationException("Heap malformed");
}
y.Degree--;
x.Mark = false;
x.Parent = null;
}
/// <summary>
/// Rebalances the heap after the decrease operation takes place.
/// </summary>
/// <param name="y">An item that may no longer obey the heap property.</param>
protected void CascadingCut(FHeapNode<T> y)
{
var z = y.Parent;
if (z != null)
{
if (!y.Mark)
{
y.Mark = true;
}
else
{
Cut(y, z);
CascadingCut(z);
}
}
}
/// <summary>
/// <para>
/// Consolidate is analogous to Heapify in <see cref="DataStructures.Heap.BinaryHeap{T}" />.
/// </para>
/// <para>
/// First, an array <c>A</c> [0...D(H.n)] is created where H.n is the number
/// of items in this heap, and D(x) is the max degree any node can have in a
/// Fibonacci heap with x nodes.
/// </para>
/// <para>
/// For each node <c>x</c> in the root list, try to add it to <c>A[d]</c> where
/// d is the degree of <c>x</c>.
/// If there is already a node in <c>A[d]</c>, call it <c>y</c>, and make
/// <c>y</c> a child of <c>x</c>. (Swap <c>x</c> and <c>y</c> beforehand if
/// <c>x</c> is greater than <c>y</c>). Now that <c>x</c> has one more child,
/// remove if from <c>A[d]</c> and add it to <c>A[d+1]</c> to reflect that its
/// degree is one more. Loop this behavior until we find an empty spot to put
/// <c>x</c>.
/// </para>
/// <para>
/// With <c>A</c> all filled, empty the root list of the heap. And add each item
/// from <c>A</c> into the root list, one by one, making sure to keep track of
/// which is smallest.
/// </para>
/// </summary>
protected void Consolidate()
{
if (MinItem == null)
{
return;
}
// There's a fact in Intro to Algorithms:
// "the max degree of any node in an n-node fibonacci heap is O(lg(n)).
// In particular, we shall show that D(n) <= floor(log_phi(n)) where phi is
// the golden ratio, defined in equation 3.24 as phi = (1 + sqrt(5))/2"
//
// For a proof, see [1]
var maxDegree = 1 + (int)Math.Log(Count, (1 + Math.Sqrt(5)) / 2);
// Create slots for every possible node degree of x
var a = new FHeapNode<T>?[maxDegree];
var siblings = SiblingIterator(MinItem).ToList();
foreach (var w in siblings)
{
var x = w;
var d = x.Degree;
var y = a[d];
// While A[d] is not empty, we can't blindly put x here
while (y != null)
{
if (x.Key.CompareTo(y.Key) > 0)
{
// Exchange x and y
var temp = x;
x = y;
y = temp;
}
// Make y a child of x
FibHeapLink(y, x);
// Empty out this spot since x now has a higher degree
a[d] = null;
// Add 1 to x's degree before going back into the loop
d++;
y = a[d];
}
// Now that there's an empty spot for x, place it there
a[d] = x;
}
ReconstructHeap(a);
}
/// <summary>
/// Reconstructs the heap based on the array of node degrees created by the consolidate step.
/// </summary>
/// <param name="a">An array of FHeapNodes where a[i] represents a node of degree i.</param>
private void ReconstructHeap(FHeapNode<T>?[] a)
{
// Once all items are in A, empty out the root list
MinItem = null;
for (var i = 0; i < a.Length; i++)
{
var r = a[i];
if (r == null)
{
continue;
}
if (MinItem == null)
{
// If the root list is completely empty, make this the new
// MinItem
MinItem = r;
// Make a new root list with just this item. Make sure to make
// it its own list.
MinItem.SetSiblings(MinItem, MinItem);
MinItem.Parent = null;
}
else
{
// Add A[i] to the root list
MinItem.AddRight(r);
// If this item is smaller, make it the new min item
if (MinItem.Key.CompareTo(r.Key) > 0)
{
MinItem = a[i];
}
}
}
}
/// <summary>
/// Make y a child of x.
/// </summary>
/// <param name="y">A node to become the child of x.</param>
/// <param name="x">A node to become the parent of y.</param>
private void FibHeapLink(FHeapNode<T> y, FHeapNode<T> x)
{
y.Remove();
x.AddChild(y);
y.Mark = false;
}
/// <summary>
/// A helper function to iterate through all the siblings of this node in the
/// circularly doubly linked list.
/// </summary>
/// <param name="node">A node we want the siblings of.</param>
/// <returns>An iterator over all of the siblings.</returns>
private IEnumerable<FHeapNode<T>> SiblingIterator(FHeapNode<T> node)
{
var currentNode = node;
yield return currentNode;
currentNode = node.Right;
while (currentNode != node)
{
yield return currentNode;
currentNode = currentNode.Right;
}
}
}
}
| 464 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace DataStructures.Heap.PairingHeap
{
/// <summary>
/// A pairing minMax heap implementation.
/// </summary>
/// <typeparam name="T">Base type.</typeparam>
public class PairingHeap<T> : IEnumerable<T> where T : IComparable
{
private readonly Sorting sorting;
private readonly IComparer<T> comparer;
private readonly Dictionary<T, List<PairingHeapNode<T>>> mapping = new();
private PairingHeapNode<T> root = null!;
public int Count { get; private set; }
public PairingHeap(Sorting sortDirection = Sorting.Ascending)
{
sorting = sortDirection;
comparer = new PairingNodeComparer<T>(sortDirection, Comparer<T>.Default);
}
/// <summary>
/// Insert a new Node [O(1)].
/// </summary>
public void Insert(T newItem)
{
var newNode = new PairingHeapNode<T>(newItem);
root = RebuildHeap(root, newNode);
Map(newItem, newNode);
Count++;
}
/// <summary>
/// Get the element from heap [O(log(n))].
/// </summary>
public T Extract()
{
var minMax = root;
RemoveMapping(minMax.Value, minMax);
RebuildHeap(root.ChildrenHead);
Count--;
return minMax.Value;
}
/// <summary>
/// Update heap key [O(log(n))].
/// </summary>
public void UpdateKey(T currentValue, T newValue)
{
if(!mapping.ContainsKey(currentValue))
{
throw new ArgumentException("Current value is not present in this heap.");
}
var node = mapping[currentValue]?.Where(x => x.Value.Equals(currentValue)).FirstOrDefault();
if (comparer.Compare(newValue, node!.Value) > 0)
{
throw new ArgumentException($"New value is not {(sorting != Sorting.Descending ? "less" : "greater")} than old value.");
}
UpdateNodeValue(currentValue, newValue, node);
if (node == root)
{
return;
}
DeleteChild(node);
root = RebuildHeap(root, node);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return mapping.SelectMany(x => x.Value).Select(x => x.Value).GetEnumerator();
}
/// <summary>
/// Rebuild heap on action [O(log(n))].
/// </summary>
private void RebuildHeap(PairingHeapNode<T> headNode)
{
if (headNode == null)
{
return;
}
var passOneResult = new List<PairingHeapNode<T>>();
var current = headNode;
if (current.Next == null)
{
headNode.Next = null!;
headNode.Previous = null!;
passOneResult.Add(headNode);
}
else
{
while (true)
{
if (current == null)
{
break;
}
if (current.Next != null)
{
var next = current.Next;
var nextNext = next.Next;
passOneResult.Add(RebuildHeap(current, next));
current = nextNext;
}
else
{
var lastInserted = passOneResult[^1];
passOneResult[^1] = RebuildHeap(lastInserted, current);
break;
}
}
}
var passTwoResult = passOneResult[^1];
if (passOneResult.Count == 1)
{
root = passTwoResult;
return;
}
for (var i = passOneResult.Count - 2; i >= 0; i--)
{
current = passOneResult[i];
passTwoResult = RebuildHeap(passTwoResult, current);
}
root = passTwoResult;
}
private PairingHeapNode<T> RebuildHeap(PairingHeapNode<T> node1, PairingHeapNode<T> node2)
{
if (node2 != null)
{
node2.Previous = null!;
node2.Next = null!;
}
if (node1 == null)
{
return node2!;
}
node1.Previous = null!;
node1.Next = null!;
if (node2 != null && comparer.Compare(node1.Value, node2.Value) <= 0)
{
AddChild(ref node1, node2);
return node1;
}
AddChild(ref node2!, node1);
return node2;
}
private void AddChild(ref PairingHeapNode<T> parent, PairingHeapNode<T> child)
{
if (parent.ChildrenHead == null)
{
parent.ChildrenHead = child;
child.Previous = parent;
return;
}
var head = parent.ChildrenHead;
child.Previous = head;
child.Next = head.Next;
if (head.Next != null)
{
head.Next.Previous = child;
}
head.Next = child;
}
private void DeleteChild(PairingHeapNode<T> node)
{
if (node.IsHeadChild)
{
var parent = node.Previous;
if (node.Next != null)
{
node.Next.Previous = parent;
}
parent.ChildrenHead = node.Next!;
}
else
{
node.Previous.Next = node.Next;
if (node.Next != null)
{
node.Next.Previous = node.Previous;
}
}
}
private void Map(T newItem, PairingHeapNode<T> newNode)
{
if (mapping.ContainsKey(newItem))
{
mapping[newItem].Add(newNode);
}
else
{
mapping[newItem] = new List<PairingHeapNode<T>>(new[] { newNode });
}
}
private void UpdateNodeValue(T currentValue, T newValue, PairingHeapNode<T> node)
{
RemoveMapping(currentValue, node);
node.Value = newValue;
Map(newValue, node);
}
private void RemoveMapping(T currentValue, PairingHeapNode<T> node)
{
mapping[currentValue].Remove(node);
if (mapping[currentValue].Count == 0)
{
mapping.Remove(currentValue);
}
}
}
}
| 256 |
C-Sharp | TheAlgorithms | C# | using System;
namespace DataStructures.Heap.PairingHeap
{
/// <summary>
/// Node represented the value and connections.
/// </summary>
/// <typeparam name="T">Type, supported comparing.</typeparam>
public class PairingHeapNode<T>
{
public PairingHeapNode(T value)
{
Value = value;
}
public T Value { get; set; }
public PairingHeapNode<T> ChildrenHead { get; set; } = null!;
public bool IsHeadChild => Previous != null && Previous.ChildrenHead == this;
public PairingHeapNode<T> Previous { get; set; } = null!;
public PairingHeapNode<T> Next { get; set; } = null!;
}
}
| 27 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
namespace DataStructures.Heap.PairingHeap
{
/// <summary>
/// Node comparer.
/// </summary>
/// <typeparam name="T">Node type.</typeparam>
public class PairingNodeComparer<T> : IComparer<T> where T : IComparable
{
private readonly bool isMax;
private readonly IComparer<T> nodeComparer;
public PairingNodeComparer(Sorting sortDirection, IComparer<T> comparer)
{
isMax = sortDirection == Sorting.Descending;
nodeComparer = comparer;
}
public int Compare(T? x, T? y)
{
return !isMax
? CompareNodes(x, y)
: CompareNodes(y, x);
}
private int CompareNodes(T? one, T? second)
{
return nodeComparer.Compare(one, second);
}
}
}
| 34 |
C-Sharp | TheAlgorithms | C# | namespace DataStructures.Heap.PairingHeap
{
public enum Sorting
{
/// <summary>
/// Ascending order.
/// </summary>
Ascending = 0,
/// <summary>
/// Descending order.
/// </summary>
Descending = 1,
}
}
| 16 |
C-Sharp | TheAlgorithms | C# | using System;
using System.Collections.Generic;
using Utilities.Exceptions;
namespace DataStructures.LinkedList.DoublyLinkedList
{
/// <summary>
/// Similar to a Singly Linked List but each node contains a refenrence to the previous node in the list.
/// <see cref="System.Collections.Generic.LinkedList{T}" /> is a doubly linked list.
/// Compared to singly linked lists it can be traversed forwards and backwards.
/// Adding a node to a doubly linked list is simpler because ever node contains a reference to the previous node.
/// </summary>
/// <typeparam name="T">Generic type.</typeparam>
public class DoublyLinkedList<T>
{
/// <summary>
/// Initializes a new instance of the <see cref="DoublyLinkedList{T}" /> class.
/// </summary>
/// <param name="data"> Data of the original head of the list.</param>
public DoublyLinkedList(T data)
{
Head = new DoublyLinkedListNode<T>(data);
Tail = Head;
Count = 1;
}
/// <summary>
/// Initializes a new instance of the <see cref="DoublyLinkedList{T}" /> class from an enumerable.
/// </summary>
/// <param name="data"> Enumerable of data to be stored in the list.</param>
public DoublyLinkedList(IEnumerable<T> data)
{
foreach (var d in data)
{
Add(d);
}
}
/// <summary>
/// Gets the amount of nodes in the list.
/// </summary>
public int Count { get; private set; }
/// <summary>
/// Gets or sets the first node of the list.
/// </summary>
private DoublyLinkedListNode<T>? Head { get; set; }
/// <summary>
/// Gets or sets the last node of the list.
/// </summary>
private DoublyLinkedListNode<T>? Tail { get; set; }
/// <summary>
/// Replaces the Head of the list with the new value.
/// </summary>
/// <param name="data"> Value for the new Head of the list.</param>
/// <returns>The new Head node.</returns>
public DoublyLinkedListNode<T> AddHead(T data)
{
var node = new DoublyLinkedListNode<T>(data);
if (Head is null)
{
Head = node;
Tail = node;
Count = 1;
return node;
}
Head.Previous = node;
node.Next = Head;
Head = node;
Count++;
return node;
}
/// <summary>
/// Adds a new value at the end of the list.
/// </summary>
/// <param name="data"> New value to be added to the list.</param>
/// <returns>The new node created based on the new value.</returns>
public DoublyLinkedListNode<T> Add(T data)
{
if (Head is null)
{
return AddHead(data);
}
var node = new DoublyLinkedListNode<T>(data);
Tail!.Next = node;
node.Previous = Tail;
Tail = node;
Count++;
return node;
}
/// <summary>
/// Adds a new value after an existing node.
/// </summary>
/// <param name="data"> New value to be added to the list.</param>
/// <param name="existingNode"> An existing node in the list.</param>
/// <returns>The new node created based on the new value.</returns>
public DoublyLinkedListNode<T> AddAfter(T data, DoublyLinkedListNode<T> existingNode)
{
if (existingNode == Tail)
{
return Add(data);
}
var node = new DoublyLinkedListNode<T>(data);
node.Next = existingNode.Next;
node.Previous = existingNode;
existingNode.Next = node;
if (node.Next is not null)
{
node.Next.Previous = node;
}
Count++;
return node;
}
/// <summary>
/// Gets an enumerable based on the data in the list.
/// </summary>
/// <returns>The data in the list in an IEnumerable. It can used to create a list or an array with LINQ.</returns>
public IEnumerable<T> GetData()
{
var current = Head;
while (current is not null)
{
yield return current.Data;
current = current.Next;
}
}
/// <summary>
/// Gets an enumerable based on the data in the list reversed.
/// </summary>
/// <returns>The data in the list in an IEnumerable. It can used to create a list or an array with LINQ.</returns>
public IEnumerable<T> GetDataReversed()
{
var current = Tail;
while (current is not null)
{
yield return current.Data;
current = current.Previous;
}
}
/// <summary>
/// Reverses the list. Because of how doubly linked list are structured this is not a complex action.
/// </summary>
public void Reverse()
{
var current = Head;
DoublyLinkedListNode<T>? temp = null;
while (current is not null)
{
temp = current.Previous;
current.Previous = current.Next;
current.Next = temp;
current = current.Previous;
}
Tail = Head;
// temp can be null on empty list
if (temp is not null)
{
Head = temp.Previous;
}
}
/// <summary>
/// Looks for a node in the list that contains the value of the parameter.
/// </summary>
/// <param name="data"> Value to be looked for in a node.</param>
/// <returns>The node in the list the has the paramater as a value or null if not found.</returns>
public DoublyLinkedListNode<T> Find(T data)
{
var current = Head;
while (current is not null)
{
if (current.Data is null && data is null || current.Data is not null && current.Data.Equals(data))
{
return current;
}
current = current.Next;
}
throw new ItemNotFoundException();
}
/// <summary>
/// Looks for a node in the list that contains the value of the parameter.
/// </summary>
/// <param name="position"> Position in the list.</param>
/// <returns>The node in the list the has the paramater as a value or null if not found.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown when position is negative or out range of the list.</exception>
public DoublyLinkedListNode<T> GetAt(int position)
{
if (position < 0 || position >= Count)
{
throw new ArgumentOutOfRangeException($"Max count is {Count}");
}
var current = Head;
for (var i = 0; i < position; i++)
{
current = current!.Next;
}
return current ?? throw new ArgumentOutOfRangeException($"{nameof(position)} must be an index in the list");
}
/// <summary>
/// Removes the Head and replaces it with the second node in the list.
/// </summary>
public void RemoveHead()
{
if (Head is null)
{
throw new InvalidOperationException();
}
Head = Head.Next;
if (Head is null)
{
Tail = null;
Count = 0;
return;
}
Head.Previous = null;
Count--;
}
/// <summary>
/// Removes the last node in the list.
/// </summary>
public void Remove()
{
if (Tail is null)
{
throw new InvalidOperationException("Cannot prune empty list");
}
Tail = Tail.Previous;
if (Tail is null)
{
Head = null;
Count = 0;
return;
}
Tail.Next = null;
Count--;
}
/// <summary>
/// Removes specific node.
/// </summary>
/// <param name="node"> Node to be removed.</param>
public void RemoveNode(DoublyLinkedListNode<T> node)
{
if (node == Head)
{
RemoveHead();
return;
}
if (node == Tail)
{
Remove();
return;
}
if (node.Previous is null || node.Next is null)
{
throw new ArgumentException(
$"{nameof(node)} cannot have Previous or Next null if it's an internal node");
}
node.Previous.Next = node.Next;
node.Next.Previous = node.Previous;
Count--;
}
/// <summary>
/// Removes a node that contains the data from the parameter.
/// </summary>
/// <param name="data"> Data to be removed form the list.</param>
public void Remove(T data)
{
var node = Find(data);
RemoveNode(node);
}
/// <summary>
/// Looks for the index of the node with the parameter as data.
/// </summary>
/// <param name="data"> Data to look for.</param>
/// <returns>Returns the index of the node if it is found or -1 if the node is not found.</returns>
public int IndexOf(T data)
{
var current = Head;
var index = 0;
while (current is not null)
{
if (current.Data is null && data is null || current.Data is not null && current.Data.Equals(data))
{
return index;
}
index++;
current = current.Next;
}
return -1;
}
/// <summary>
/// List contains a node that has the parameter as data.
/// </summary>
/// <param name="data"> Node to be removed.</param>
/// <returns>True if the node is found. False if it isn't.</returns>
public bool Contains(T data) => IndexOf(data) != -1;
}
}
| 335 |
C-Sharp | TheAlgorithms | C# | namespace DataStructures.LinkedList.DoublyLinkedList
{
/// <summary>
/// Generic node class for Doubly Linked List.
/// </summary>
/// <typeparam name="T">Generic type.</typeparam>
public class DoublyLinkedListNode<T>
{
/// <summary>
/// Initializes a new instance of the <see cref="DoublyLinkedListNode{T}" /> class.
/// </summary>
/// <param name="data">Data to be stored in this node.</param>
public DoublyLinkedListNode(T data) => Data = data;
/// <summary>
/// Gets the data stored on this node.
/// </summary>
public T Data { get; }
/// <summary>
/// Gets or sets the reference to the next node in the Doubly Linked List.
/// </summary>
public DoublyLinkedListNode<T>? Next { get; set; }
/// <summary>
/// Gets or sets the reference to the previous node in the Doubly Linked List.
/// </summary>
public DoublyLinkedListNode<T>? Previous { get; set; }
}
}
| 31 |
Subsets and Splits