Giter VIP home page Giter VIP logo

aalhour / c-sharp-algorithms Goto Github PK

View Code? Open in Web Editor NEW
5.8K 5.8K 1.4K 3.27 MB

:books: :chart_with_upwards_trend: Plug-and-play class-library project of standard Data Structures and Algorithms in C#

License: MIT License

C# 99.98% Batchfile 0.02%
algorithms binary-trees csharp data-structures graph graph-algorithms hashing hashing-algorithms heaps queues searching searching-algorithms sorting sorting-algorithms tree tree-algorithms

c-sharp-algorithms's Introduction


                                          o---o    |   |                                 
                                         /       --O---O--                               
                                        O          |   |                                 
                                         \       --O---O--                               
                                          o---o    |   |                                 


              O    o       o--o    o--o   o---o   o-O-o  o--O--o  o   o  o     o   o--o 
             / \   |      o       o    o  |   |     |       |     |   |  |\   /|  |     
            o---o  |      |  o-o  |    |  O--Oo     |       |     O---O  | \o/ |   o--o 
            |   |  |      o    |  o    o  |  \      |       |     |   |  |     |      | 
            o   o  O---o   o--o    o--o   o   \o  o-O-o     o     o   o  o     o  o---o 

WHAT IS C# ALGORITHMS?

A plug-and-play class-library project of standard Data Structures and Algorithms, written in C#. It contains 75+ Data Structures and Algorithms, designed as Object-Oriented isolated components. Even though this project started for educational purposes, the implemented Data Structures and Algorithms are standard, efficient, stable and tested.

BACK STORY

This project originally started out as an interview preparation project. However, after receiving a great amount of positive responses on reddit, and noticing excitement from a few GitHubers to contribute furthermore to it, the project took on a different meaning. So, I decided to keep maintaining it as a reference for data structures and algorithm implementations in C# as well as my own research side-project under these topics.

DESCRIPTION

Solution Hierarchy:

This is a C#.NET solution-project, and it contains three subprojects:

  1. Algorithms: A class library project. Contains the Algorithms implementations
  2. Data Structures: A class library project. Contains the Data Structures implementations
  3. UnitTest: Unit-testing project for the Algorithms and Data Structures

Requirements:

  1. .NET Core >= 2.0
  2. XUnit

A Note to Contributors:

If you wish to contribute to C# ALGORITHMS, then please make sure you check out the Contribution Guidelines first.

DATA STRUCTURES

Linear:

Circular:

Heaps:

Priority Queues:

Hashing Functions:

Hash Tables:

Sorted Collections (Tree-based):

Trees:

Graphs:

ALGORITHMS

Sorting:

Searching:

Graphs:

Trees:

Strings:

Numeric:

Visualization:

CONTRIBUTORS


LICENSE

This project is licensed under the MIT License.

c-sharp-algorithms's People

Contributors

aalhour avatar adamfisher avatar anamale avatar clonedeath avatar codehuntio avatar gregfra avatar gutsonok avatar hbsock avatar iskandarfischer avatar ivandrofly avatar j-rewerts avatar karv avatar kdimolikas avatar kroneckerx avatar mattbonnell avatar maxm2017 avatar ndubuisijr avatar nickntg avatar nickpolyder avatar patrykolejniczak avatar raphaelmdcoelho avatar ryangrange avatar samuelkenney avatar scohe001 avatar tautcony avatar yanxiaodi avatar zhijli avatar zwanona avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

c-sharp-algorithms's Issues

AVLTreeTest failing - Case 5 (delete root of AVL tree)

Case 5 -- could this be a test verification failure?
Xunit.Sdk.TrueException: 'Wrong root.
Expected: True
Actual: False'

Assert.True(avlRoot.Value == 6, "Wrong root.");

The code seems to produce the tree of 5 at L1, 2 and 6 are children of 5 (L2), 1 and 3 are children of 2 (L2), 7 is right child of 6 (L2). This is a valid BST and AVL tree.

The final (expected) tree mentioned in the comments (lines 119-127) is not a proper BST.

Suggest changing the assertions or updating case #5 to set up a tree that does require rebalancing after root node deletion. I can make the change and submit a PR from here.

Unit testing

Hello,

There are many static class which are testing algorithms and data structures implementations. Why not creating a unit testing project instead (or additionnaly)?

ZwoRmi

How to use UnitTest

Hello @aalhour. I am unsure of how to run the unit tests that are placed in the UnitTest folder. In the MainProgram folder I see you have a program.cs that allows you to specify which test(s) to run. How do you accomplish this same task in the UnitTest folder? Thanks!

.NetStandard and nuget

Hi,

Are there any plans to migrate this project to .net standard and/or have a nuget package?

Improve README list formatting

Describe the bug

The README document contains a few issues regarding list formats, e.g.: list sentences ending with a . character.

To Reproduce

N/A

Expected behavior

List sentences don't end with a . character.

MaxHeap bad algorithm.

steps to reproduce

Write a loop, from 1 to 80000, each time add a random int to the max heap.

In theory it takes very little time(NlogN, N=80000, <1sec ), but the program does take a long time.

I'v also tested the BinaryHeap in https://github.com/SolutionsDesign/Algorithmia, it performs well, so it is probably due to the bad algorithm.

Inefficient merge soft

int midIndex = collection.Count / 2;
var leftCollection = collection.GetRange(startIndex, midIndex);
var rightCollection = collection.GetRange(midIndex, (endIndex - midIndex) + 1);
leftCollection = InternalMergeSort<T>(leftCollection, 0, leftCollection.Count - 1, comparer);
rightCollection = InternalMergeSort<T>(rightCollection, 0, rightCollection.Count - 1, comparer);

No need to invoke GetRange, as it copies the data and consumes extra memory. Passing StartIndex, EndIndex along with the original array should be sufficient. Don't you think so?

Graph by clans

I have implemented an similar IGraph<T>, which acts like a undirected unweighted graph.
It should be fast at finding paths and other connexity algorimths; but slower at direct manipulation like adding or removing edges.

It stores in memory the clan: the maximal complete subgraphs in ISet<T>'s

If you are interesed i could implement it to your IGraph<T> interface and merge it.

What is the goal of this repo?

Hello,

I read that you start this repo as an interview-preparation project. Now, what do you want to do with it? Keep collecting c# implementation of algorithms? It could be nice to share them on Rosetta Code or Wikipedia for example.

Also, I wrote algorithms in C# for learning purpose in this repository. If you want, I can share all of them in a pull request.

Cheers,

B* Trees

Implement the B* Tree Data Structure.

IsAnagram logic needs to be fixed

I think the IsAnagram() method doesn't work as expected. For example, it would fail for the below string combinations ("abc","bbb") or ("acdf", "bcde").

I think a simple LINQ implementation would be easy enough to implement here.
If you like, I could do that and also implement unit tests for it.

[Error] dotnet test command fails to execute the UnitTest project

Running tests on Travis-CI and locally gets aborted due to a weird error. Find the command, environment and stderr output below:

Command:

dotnet test UnitTest/UnitTest.csproj

Error:

The active test run was aborted. Reason: ncTaskMethodBuilder`1[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].Start[[Xunit.Sdk.TestClassRunner`1+<RunTestMethodsAsync>d__38[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], xunit.execution.dotnet, Version=2.4.0.4049, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c]](<RunTestMethodsAsync>d__38<System.__Canon> ByRef)
   at Xunit.Sdk.TestClassRunner`1[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].RunTestMethodsAsync()
   at Xunit.Sdk.TestClassRunner`1+<RunAsync>d__37[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].Start[[Xunit.Sdk.TestClassRunner`1+<RunAsync>d__37[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], xunit.execution.dotnet, Version=2.4.0.4049, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c]](<RunAsync>d__37<System.__Canon> ByRef)
   at Xunit.Sdk.TestClassRunner`1[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].RunAsync()
   at Xunit.Sdk.TestCollectionRunner`1+<RunTestClassesAsync>d__28[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].Start[[Xunit.Sdk.TestCollectionRunner`1+<RunTestClassesAsync>d__28[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], xunit.execution.dotnet, Version=2.4.0.4049, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c]](<RunTestClassesAsync>d__28<System.__Canon> ByRef)
   at Xunit.Sdk.TestCollectionRunner`1[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].RunTestClassesAsync()
   at Xunit.Sdk.TestCollectionRunner`1+<RunAsync>d__27[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].MoveNext()
   at System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].Start[[Xunit.Sdk.TestCollectionRunner`1+<RunAsync>d__27[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], xunit.execution.dotnet, Version=2.4.0.4049, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c]](<RunAsync>d__27<System.__Canon> ByRef)
   at Xunit.Sdk.TestCollectionRunner`1[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].RunAsync()
   at System.Threading.Tasks.Task`1[[System.__Canon, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].InnerInvoke()
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at System.Threading.Tasks.Task.ExecuteWithThreadLocal(System.Threading.Tasks.Task ByRef)
   at System.Threading.Tasks.Task.ExecuteEntry()
   at System.Threading.Tasks.SynchronizationContextTaskScheduler+<>c.<.cctor>b__8_0(System.Object)
   at Xunit.Sdk.MaxConcurrencySyncContext.RunOnSyncContext(System.Threading.SendOrPostCallback, System.Object)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
   at Xunit.Sdk.MaxConcurrencySyncContext.WorkerThreadProc()
   at System.Threading.Thread.ThreadMain_ParameterizedThreadStart(System.Object)
   at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)

Environment:

macOS Sierra

Open-Addressing Hash Table

Implement the Open-Addressing Hash Table Data Structure.

Top priority goes to implementing the the data structure with Double-Hashing algorithm. Nevertheless, implementing all of the three main Open-Addressing algorithms is always welcome.

The three main Open-Addressing Algorithms:

  • Linear Probing.
  • Quadratic Probing.
  • Double Hashing.

Fix RedBlackTree impl/test

Hello,
after downloading the repository, I noticed that not all tests pass.
e.g. tests related with RedBlackTree.
I would like to work on these tests or implementation depends on what the problem will turn out to be if nobody else actual work with it?

I can also add some more unit test for that trees.

Regards.

一个问题

red back tree :in _adjustTreeAfterInsertion method,I found a problem which in code:
if (currentNode != null && currentNode != Root && _safeCheckIsRed(_safeGetParent(currentNode)))
{
//
// STEP 2.A:
// This is the simplest step: Basically recolor, and bubble up to see if more work is needed.
if (_safeCheckIsRed(_safeGetSibling(currentNode.Parent)))
{
// If it has a sibling and it is red, then then it has a parent
currentNode.Parent.Color = RedBlackTreeColors.Red;//black?

I think right code is currentNode.Parent.Color = RedBlackTreeColors.Black

Dijkstra fails on sparse graph

With many vertices and not many edges, the Dijkstra algorithm fails on the following line:
//_edgeTo = new WeightedEdge[_edgesCount];
which now runs with the following line:
_edgeTo = new WeightedEdge[_verticesCount];

Similarly the test for optimality fails in DijkstraShortestPaths with directed edges, I think because code fails due to adding an edge weight to Infinity, when it should not do this for the directed edge when the edge is not in the right direction.

//Debug.Assert(_checkOptimalityConditions(Graph, Source));

(_distances[v] + edge.Value < _distances[w])
infinity + an edge weight will be less than distances[w](infinity + positive number) = small number.

Implement the new Edges API for CliqueGraph

Hello @karv,

I have added 3 new methods to the IGraph interface.

  1. Edges: Getter property that returns all the edges in graph.
  2. OutgoingEdges(Vertex): Returns all the outgoing edges from a vertex.
  3. IncomingEdges(Vertex): Returns all the incoming edges to a vertex.

I have added empty implementations for these methods to the CliqueGraph class, the one you contributed, which throw a "Not Implemented Exception".

I am opening this issue because you are the owner of this class, and now it needs your maintenance.

Improve Contributors list on the REAMDE document

Is your feature request related to a problem? Please describe.

Automatically list new and existing contributors on the README document

Describe the solution you'd like

Use an automated service like contributors-img where the images are listed automatically.

Describe alternatives you've considered

N/A

Additional context

N/A

Question - possible enhancement

Hello, searching through the repo i stumbled upon this Queue implementation.

The Queue implementation uses Generics for the values it holds but the container is of type object[].

Is there any reason for that?

Could i do my first pull request to make this enhancement?

Thank you for your time.

SortedDictionaryTests and DLinkedListTest fail to pass

On the current master 9fc09bd, it seems that these two tests don't pass.

Example code that fails in DLinkedListTest:

            /****************************************************************************************/
            var stringsIterators = listOfStrings.GetEnumerator();

            Debug.Assert(stringsIterators.Current == listOfStrings[0], "Wrong enumeration.");

Example code that fails in SortedDictionaryTests:

            Debug.Assert(sortedDict["Bic"] == 12);
            Debug.Assert(sortedDict["Carter"] == 13);

The errors were very minor (typos, forgetting to undo updates, etc), so I've fixed them myself.

Would it be okay for me to send a pull request for this?

Radix Trees

Implement the Radix Trees Data Structure.

Multiple issues with catalan numbers

Specifically:

  • The algorithm does not produce correct numbers when large ranks are used.
  • The implementation of GetNumberByBinomialCoefficients() produces different results when rank >= 32.
  • As a result of the above, CatalanNumbersTest.DoTest() fails.
  • There are no tests to validate the algorithm implementation against known and documented catalan numbers.

BitArray

I just wanted to say I building at the moment a bit-array.
This bit-array is in namespace DataStructures.BitArray
I hope this is correct.
I put also a Nunit test to it.

a question

protected bool _remove(RedBlackTreeNode nodeToDelete)
{
if (nodeToDelete == null)
return false;

        // Temporary nodes
        RedBlackTreeNode<TKey> node1, node2;

        // If nodeToDelete has either one child or no children at all
        if (!nodeToDelete.HasLeftChild || !nodeToDelete.HasRightChild)
        {
            node1 = nodeToDelete;
        }
        else
        {
            // nodeToDelete has two children
            node1 = (RedBlackTreeNode<TKey>)base._findNextLarger(nodeToDelete);//why is _findNextLarger
        }

        // Left child case
        if (node1.HasLeftChild)
        {
            node2 = node1.LeftChild;
        }
        else
        {
            node2 = node1.RightChild;
        }

        // If node2 is not null, copy parent references
        if (node2 != null)
            node2.Parent = node1.Parent;

        if (node1.Parent != null)
        {
            if (node1.IsLeftChild)
            {
                node1.Parent.LeftChild = node2;
            }
            else
            {
                node1.Parent.RightChild = node2;
            }
        }
        else
        {
            Root = node2;
            Root.Parent = null;
        }

        // Swap values
        if (!node1.IsEqualTo(nodeToDelete))
        {
            nodeToDelete.Value = node1.Value;
        }

        // Adjust the Red-Black Tree rules
        if (node1.Color == RedBlackTreeColors.Black && node2 != null)
        {
            _adjustTreeAfterRemoval(node2);
            Root.Color = RedBlackTreeColors.Black;
        }

        // Decrement the count
        base._count--;

        return true;
    }

node1 = (RedBlackTreeNode)base._findNextLarger(nodeToDelete); in this code why is find larger but not find smaller.
https://www.cs.usfca.edu/~galles/visualization/RedBlack.html this link shows the process of delete a note,and it process is find a smaller note but not larger note
which is right?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.