C# Algorithm Examples

Array Collections File String Windows VB.NET Algorithm ASP.NET Cast Class Compression Convert Data Delegate Directive Enum Exception If Interface Keyword LINQ Loop Method .NET Number Regex Sort StringBuilder Struct Switch Time Value

Algorithm illustration

One algorithm might yield astonishing improvements in your computer program. Another might conversely render that program nearly useless. Algorithms are the expression of behavior in computer software. They can be implemented in the C# language.

Beyond craftsmanship lies invention, and it is here that lean, spare, fast programs are born. Brooks, p. 102
Good programmers are a little bit lazy: they sit back and wait for an insight rather than rushing forward with their first idea. Bentley, p. 17

Recursion

No section on algorithms can be introduced without an example of recursion. In this program, the runtime calls the A() method until its parameter has a value equal to 5. You can see that it never prints a value past 5 when called with value 0.

Recursion
Program that shows recursive method [C#]

using System;

class Program
{
    static void Main()
    {
	A(0);
    }

    static void A(int a)
    {
	Console.WriteLine(a);
	if (a < 5)
	{
	    A(++a); // Recurse.
	}
    }
}

Output

0
1
2
3
4
5

Fisher-Yates shuffle

First, one of the most useful algorithms you can find is the Fisher-Yates shuffle algorithm. This algorithm, first implemented on computers in 1964, is not biased and is also very fast. Many shuffling methods introduce biases into your results. This one does not.

Fisher-Yates Shuffle Array

Palindrome

You can check strings for palindromicity with some relatively simple methods. Here, we demonstrate the IsPalindrome method, and then modify it such that it ignores non-letter non-digit characters and is more effective for phrases.

Palindrome Method Palindrome Sentence Method

Note: Palindromicity is a real word. I didn't just make it up.

Fibonacci sequence

You can compute Fibonacci numbers in a recursive or iterative way. The iterative way is much faster and is demonstrated here.

Fibonacci SequenceSpot/tops: example of anagrams

Anagram

There aren't a lot of commercial uses for anagram programs, but designing this sort of algorithm helps inform us of recursive searching techniques. Donald Knuth studied anagrams in his books. We dive into anagrams in the C# language.

Anagram Method Anagram Open Source in Windows

DAWG. The term "dawg" is sometimes used as a slang word, but on this website it refers to a directed acyclic word graph. A DAWG is a tree encoding of a set of words: in a DAWG, the prefixes of all words are shared, as are their suffixes. This makes for an extremely efficiently representation of a word list.

Directed Acyclic Word Graph

Slice

It is possible to create extension methods to slice arrays or strings, using the same arguments that other languages such as JavaScript or PHP use. We describe how you can implement these methods.

Array Slice String SliceROT13 algorithm illustration

Ciphers

There are two cipher codes implemented here: the Atbash cipher, and the ROT13 cipher. They are very similar in concept, but use different shifting logic.

Atbash Caesar ROT13

Vowels

You can test for vowels using different constructs in the C# language. If you model your method on the real world, you can achieve better performance here.

Vowel

Calculate change

You can use recursion to compute exact change for a given amount. You can even determine how many different ways you can make change. Keep the change.

Change: CoinsMu algorithm

Mu

The mu-puzzle shows us how you can derive (or not derive) the string MU from the string MI. This reveals important aspects of formal systems.

Mu

Hash codes

Hash codes are used to get a relatively unique integer for a variety of string inputs. There can be hash collisions, and this adds to the complexity of hash tables considerably. We look at different ways of computing hash codes.

GetHashCode String Implementation IEqualityComparer Dictionary

Count digits

Question and answer

How many digits are in a number? One way to compute this is to convert the number to a string and then get the length of that string, but there are faster ways to do it, as shown here.

Integer Digit Count

Levenshtein distance

We implement the classic Levenshtein distance algorithm, which tells you how close two strings are to each other (edit distance). The code here is not completely original and was adapted from public domain implementations.

Levenshtein Distance

Word search

Have you ever needed a computer program that can search grids of letters for complete words? Neither do I—but this sort of program is fun to develop and can help us understanding recursive searching techniques.

Multidirectional Word Search Word Search AlgorithmPathfinding program screenshot

Pathfinding

How can you make a character walk around walls in your program? The simple pathfinding algorithm in this example does not really include all the complexity of the A-Star Pathfinding algorithm, but it is effective for small demonstrations.

Pathfinding Algorithm

Pi

You can use the C# language to compute approximations of pi. We use a known technique to approximate pi. Unfortunately, the code here has no use outside of learning about pi, because it doesn't support many digits.

Math.PI Constant

Swap

Here, we implement a method that swaps elements in an array. This method doesn't have a lot of practical uses, but is illustrative in purpose.

Swap Methods

Wiki markup

You can implement code that parses in the markup used in popular wiki sites. The example here demonstrates how you can do this with a simple stack-based parser.

Wiki MarkupMemoize illustration

Memoization

With memoization, you can avoid recalculating the result of a method for a certain set of arguments. This can transform very slow methods into very fast methods.

Memoization

Optimization

We present a lot of tips about how to make micro-optimizations in C# programs. Some of these tips are not commonly used. Some of them are not even advisable in many cases. Nevertheless, they can be interesting to review.

Optimization Secrets Optimization Misnomer

Randomize

.NET Framework information

The .NET Framework has a very simple and efficient way to generate random strings. We look at how you can generate short, random character data: for example, we generate a single random letter.

Random Byte Array Random Lowercase Letter Random Number Random Paragraphs and Sentences Random String Randomize Chars in String

Question: Have you ever wanted to start your own junk email enterprise? Hopefully not, but in any case you can generate random text to make content that computers cannot tell is not created by humans.

Strings

String type

Strings are used in many algorithms. Not only this, but many algorithms are designed for string manipulation: methods such as the Boyer-Moore search algorithm search strings quickly; data types such as Dictionary can be used to eliminate duplicate patterns inside strings.

Between, Before and After Extensions Boyer-Moore String Search Example Duplicate Words Explode String Extension Method First Sentence First Words From String Plural Words Replace Extension String Occurrence Count

Summary

The C# programming language

Even as computer systems become faster and cloud-computing technology reduces the workload on a single system, algorithms retain their paramount importance in the field of computer science. Algorithms—even some of these C# algorithms—make problems that are previously unsolvable, solvable.

Dot Net Perls