# Understanding Sorting

## Posted by Filip Ekberg on February 24 2014 5 Comments

This is the third piece in the back to basics series that I’ve been doing and this time we’re looking at one of the most fundamental algorithms out there. Arguably one of the first one you’d learn in school; sorting. There’s a huge variety of sorting algorithms ranging from bubble sort, insertion sort, selection sort, merge sort, quick sort among many others. Most of them have their perfect use case, in the case of bubble sort, it’s a great algorithm to get started with to understand how to re-position things in an array. However, bubble sort is a O(n^2) algorithm which means that it will grow quadratic as `n` grows. If you want to win a free digital copy of my book C# Smorgasbord, continue reading and leave a comment with an optimized version of the merge and merge sort functions!

### Sorting in general

The mathematical definition of sorting might seem pretty obvious, but let’s take a look at it.

The input to a sorting algorithm is a sequence of numbers <a1, a2, a3 … an> where the output is a permutation of that input <a′1, a′2, a′3 … a′n> \$ (such that) a′1 <= a′2 … <= a′n

Alright, enough with the fancy maths and symbols basically this means if we have the sequence `{3, 2, 1}` running this through a sorting algorithm will give us `{1, 2, 3}`, not really rocket science, right?

The simplest sorting algorithm to implement which I said before is bubble sort, the way it works is that there’s a loop running that compares each element in the list to each other until the entire list is sorted. Best case everything is sorted and we’re done “super quick”, worst case this will take an extremely long time, at least compared to what we can do to improve it. Do you remember the divide and conquer approach that we talked about previously? Where we divide something into smaller pieces to solve a greater puzzle? When we talked about that, we talked about being able to search through the phone book in super speed by dividing it in half over and over again.

I’m going to side-track for a bit here and talk about something that I find pretty interesting. It’s really relevant to the sorting, you’ll see why later. Given a phone book with 2^32 entries, which we assume are sorted. How many tries does it take for us to find 1 of these entries? We talked about the complexity before and it’s`O(log n)`. This means that you could just do `log(2^32)` and you’d get 32! Which means we have to do 32 checks to find a value in a sorted collection of 2^32 elements. By the way, so there is no confusion, when I am talking about `log()` it’s really `log2()`, hence using the base 2.

So why is this interesting? Turns out that if we write out the recurrence tree for this method, the height of the tree will be `log(n)` and why this is interesting, well, you will just have to read on until we’ve looked at merge sort.

### Merge sort!

Going back to merge sort, this algorithm makes use of the divide and conquer approach. The way that it does this is by splitting up the input sequence into smaller portions, until there is just one element left. Consider that we have the following sequence `{3, 6, 5, 1}` when running this over the divide and conquer approach the first pass will give us two sequences with the following data: `{3, 6} {5, 1}`. Since the base case, only one element left, has not yet been reached we keep going and at the end we will have ended up with each element in their own lists. I’m going to blow your mind a bit, if you write the entire process out on paper you will see that once the splitting is completely done and you are at the position where you have just 1 element in each list, the height of this tree on your paper will be `log(n)` where `n` is the amount of elements. This means that if you have a sequence of 8 numbers you will have 3 steps, this is because `log(8)` is equal to 3 and 2^3 is 8.

Doesn’t make any sense? Well have a look at this illustration (pardon my hand writing skills):

At least I find this pretty cool and looking at it like this sure helps to understand why the algorithm has the time complexity that it has.

When you’re at the bottom of the splitting, what do you do? So far we haven’t done anything that justifies the name “merge”. Exactly! Because the very next step will do just that. It will merge the two lists together and this is where it begins to be interesting, if it wasn’t interesting already that is.

Let’s say that the merge method takes two parameters, we have left and right. We can assume that both left and right are sorted lists and now we want to merge them together. You might ask yourself, how can we assume these are sorted when we haven’t done anything? Let me tell you, the first time we reach merge, how many elements do we have in each subset? If you guessed 2, you were wrong, it’s 1. So if each list has just one element, they’re seen as sorted. Now that we merge our first two elements, we’ll make sure the list that we return from merge is sorted.

Now it might get a bit hard to wrap your head around this without looking at some pseudo-code so let’s do just that. Here’s the main function that gives us an overview of what happens:

MergeSort(input):

left = MergeSort([:input / 2])
right = MergeSort([input / 2:])

return Merge(left, right)

The only thing that might look a bit off is the “thing” that we say to pass to `MergeSort` when we call it recursively. I am simply defining two subsets of the array that is passed to the method, the first one will take the first half the second one will take the second half. That means left and right will have the correct side of the array. The colon defines where to start taking elements.

Looking at this code and looking at the sequence we want to sort (let’s take the one from the picture) `{8, 7, 6, 5, 4, 3, 2, 1}` we know that the first time we reach `Merge` left will be a collection with one element `{8}` and right will be a collection with one element `{7}`. When the merge function is done with the two independently sorted lists, it will return the sorted subset and then when it is all done we will end up with a sorted version of our list.

It starts to get a bit interesting again when we are back to having the list almost merged, when at the final level and the final merge we will have the following two values in left and right:

left = {5, 6, 7, 8}
right = {1, 2, 3, 4}

Merge will now start to process this, when it was just 1 element in each, the comparison in merge was easy, we could do that with just a single if statement. Now it gets a bit more complicated. By just looking at this we know that we want to move the entire right piece over before the left one. We still need to make sure though that each element is put in the right position. So what we need to do is that we need to point at the current left and current right index which we are comparing, because it could happen that we need to take two values from the right before we even touch the left one. Notice that I say take here, one of the disadvantages of merge sort is that it takes up more memory, it is not in-place and in fact, according to the MIT course that I’ve been linking there is a paper that has analysed an in-place merge sort and come to the conclusion that it will perform much worse than this implementation.

This all means that we have two variables, let us call them `i` and `j` and each time we find a smaller object we move that to the result list. In our case that means we would move everything from the right list first into our new list before we even moved anything from the left one.

Look at this breakdown in pseudo-code of what happens and it might make more sense:

i = 0
j = 0

result = []

if left[i] < right[j]   // 5 < 1
i ++
else
j ++

// j is now 1
// i is still 0
if left[i] < right[j]   // 5 < 2
i ++
else
j ++

// j is now 2
// i is still 0
if left[i] < right[j]   // 5 < 3
i ++
else
j ++

// .... All items from right are added to the result

So as you can see, it moves everything over from the right, then when all the right items are added, we know that the rest of the left items can be added to the end of the list as we have always been working with sorted versions. The above is just pseudo-code and a layout of what happens behind it all, we’re going to look at the real implementation now.

Let’s start off my looking at the implementation of `MergeSort` which you might already have figured out is pretty straight forward:

int[] MergeSort(int[] input)
{
if(input.Length <= 1) return input;

var left  = MergeSort(input.Take(input.Length / 2).ToArray());
var right = MergeSort(input.Skip(input.Length / 2).ToArray());

return Merge(left, right);
}

Can you think of a way to optimize this here? We are really beating the memory up here which isn’t really good. This will create a small copy (or large depending on the size of the array) for each time we enter left and right. Ideally you want to keep track of the current position of left and right instead of actually slicing and copying the array which uses much, much more memory and resources. Remember that we are talking about this conceptually and we’re trying to find the best way possible to implement things, this is how we become better.

Tell you way, I’ll leave you to optimize this part here, you will need to change the merge part as well to make it work. If you can write an elegant solution and give it a nice explanation in the comment field below you can win a digital copy of my book.

Now let’s jump over and take a look at what the merging will look like, implementation wise that is. We’ve already talked about what is going on behind the scenes here. As per our pseudo code we saw a bit earlier, we’re setting up the temporary list that we are going to fill with the sorted values, or rather, merged in order! We’ve also seen that we will need two variables to keep track of where we are in the sorting, so the method stub will look something like this, we’re filling in the blanks in a second:

int[] Merge(int[] left, int[] right)
{
var result = new List<int>();
int j = 0;

// Magic goes here

return result.ToArray();
}

We’re going to fill the list with values in order, which means we need to find them from our left and right portions. We are going to start off by pointing at two places, one slot in each array that we are merging. This means that we will keep track of the position that we are currently at in both our left and right portion. Now think about it like this, we are going to assume that left and right is sorted so we don’t need to worry about them being out of order. So what we can do is that we go over each element in the right away and compare that against what is in the right array.

What happens if the current left element is smaller than the one in the right? Well that means that we need to append this to the result array. However, if the opposite were to happen, we need to do something more. Consider that we are running this in a loop, a `for`-loop to be more specific. In each iteration we increment `i` which is our pointer to the current element in our left array. The local variable `j` on the other hand will maintain a pointer to where in the right array we are. So that means if we find an element in the right array that is smaller than the one in the left, we don’t want to increment `i`, because we still want to know if the current left element is smaller than the next right one.

However, at this point we can continue looking at the next right element so we can increment its pointer. Don’t worry if it sounds a bit too much to think about, once you get a look at the code, I bet you will see it more clearly! Speaking of that, here’s the part that we just talked about:

for(int i = 0; i < left.Length; i++)
{
if(right.Length <= j || left[i] < right[j])
{
}
else
{
j++;
i--;
}
}

As you see, when the right element is smaller, we maintain the value of the current index in the left array and just increment the one used to reference the element in the right array. Notice one more thing here, we are checking if there are still elements to analyse in the right portion, why are we doing this? Remember that all the elements in each array are sorted, so when there are no more elements in the right array, we can just move everything over from the left array to the result.

The same applies to when this process has finished, what happens if there are elements left in the right array? We are just going as long as we have elements in the right array. So in order for us to move the elements from the right array, if there are any, to the results array, we can do this:

for(; j < right.Length; j ++)
{
}

Let’s now look at the entire implementation of the merge method:

int[] Merge(int[] left, int[] right)
{
var result = new List<int>();
int j = 0;

for(int i = 0; i < left.Length; i++)
{
if(right.Length <= j || left[i] < right[j])
{
}
else
{
j++;
i--;
}
}

for(; j < right.Length; j ++)
{
}

return result.ToArray();
}

At the end of the merge process and at the end of running our merge sorting, we’ve gone over a complete processes looking what we can see in this illustration:

Here’s a complete example that you can run and experiment with, try and compare the time it takes if you write something like Bubble Sort!

void Main()
{
var array = Enumerable.Range(0, 10000).OrderBy (e => Guid.NewGuid());

var result = MergeSort(array.ToArray());
}

int[] MergeSort(int[] input)
{
if(input.Length <= 1) return input;

var left = MergeSort(input.Take(input.Length / 2).ToArray());
var right = MergeSort(input.Skip(input.Length / 2).ToArray());

return Merge(left, right);
}

int[] Merge(int[] left, int[] right)
{
var result = new List<int>();
int j = 0;

for(int i = 0; i < left.Length; i++)
{
if(right.Length <= j || left[i] < right[j])
{
}
else
{
j++;
i--;
}
}

for(; j < right.Length; j ++)
{
}

return result.ToArray();
}

Merge sort runs in `O(n log n)`, comparing this to something like bubble sort which is `O(n^2)` is pretty fun and a good exercise. However, don’t forget that merge sort uses extra memory and in the examples I have given above, I have not optimized the memory footprint, that’s up to you to play with! There are a lot of different and fun sorting algorithms including for instance quick sort and heap sort.

I hope you enjoyed this and have a better understanding of merge sort and sorting in general. Do you have a favorite sorting algorithm?

# Calculating Document Distance

## Posted by Filip Ekberg on February 17 2014 1 Comment

Previously we looked at the first part in my Back to Basics series where we understood and implemented Peak-Finding. This time we are going to talk about something slightly different; Calculating Document Distance. I really recommend you to take a look at the MIT course on Introduction to Algorithms, for this post I really recommend watching the part about document distance.

Practicing algorithms is both fun and educating, even if you are 20 years into your career you will most certainly always learn something new when analyzing algorithms. There’s no greater feeling than when you’ve tackled a problem for a long time and suddenly you understand it deeply enough to optimize it and play with the edge cases.

### What is Document Distance?

Consider that you have two documents containing a huge amount of text in them, be it essays or websites. Now you want to know how similar these documents are, in the sense of: how many words overlap in these documents. Conceptual the algorithm is really simple there’s just a few steps that you’ll have to go through:

1. Open and read both documents that you are going to compare. Only read words and numbers, skip special characters (spaces, dots, etc..) and convert the words to lower case
2. Calculate the word frequency in both collections of words, this means how many times each word occur in each document
3. Compare the frequencies from both computations and calculate the distance

The distance itself is calculated using a predefined formula that you don’t really have to pay too much attention too at this moment, unless you really fancy computations on vectors.

Both the first two steps are pretty trivial, we’ll make use of some built in data structures that are fast for random access and for inserts and try to not make it all too complex. The second step is the one with the fancy math in it. We’re going to find something called inner product, which basically takes the frequencies of the words that occur in both documents, multiplies these and adds them up.

So let’s say that our frequencies are represented using a dictionary, that way we have O(1) access time and O(1) inserts. To compute the product we then produce a method with the following signature: `int ComputeInnerProduct(Dictionary<string, int> first, Dictionary<string, int> second)`. This means that we have the frequencies for both the first and the second document and now we can add these together where the words intersect.

The implementation of this is quiet simple when you know what the formula expects (we’ll get to that in a moment), here’s the entire method that finds the inner product:

public int ComputeInnerProduct(Dictionary<string, int> first, Dictionary<string, int> second)
{
var sum = 0;
foreach (var key in first.Keys)
{
if (second.ContainsKey(key)) sum += first[key]*second[key];
}

return sum;
}

As we only care about intersection, we just have to go over one of the lists, we don’t care if the other one is longer or not. For each element we have in our dictionary, we simply check if the other document have the same word and then perform the multiplication which we add into our sum.

Ready to take a look at the formula? Well, ready or not here it comes!

This equation is taken from the MIT course material from the open courseware course I linked above, think of L1 as the first document and L2 as the second documents frequencies that intersect. Basically where it says `L1 * L2` it refers to the inner product of these two. The equation finds an angle in a vector based on our inputs. So you might have figured out that `L1 * L1` means the inner product of these two and the same goes for `L2 * L2`. We basically just have to call `ComputeInnerProduct` three times, with slightly different input.

Let’s just take a look at what the implementation of this method does, the method that computes the distance.

public double ComputeDistance(Dictionary<string, int> first, Dictionary<string, int> second)
{
var numerator = ComputeInnerProduct(first, second);

var denominator = Math.Sqrt(ComputeInnerProduct(first, first) * ComputeInnerProduct(second, second));

return Math.Acos(numerator / denominator);
}

As you can see in the code sample we are doing exactly what the formula expresses, at least as long as we trust our `int ComputeInnerProduct` implementation.

We’ve got the two hardest parts done that has the most of math inside it, the rest is just the trivial methods that loads the files and processes the text. Let’s take a look at how we calculate the frequency of the words in our document. I want this operation to be fast as well, so again I will make use of the dictionary to get O(1) (constant) lookup and insert.

public Dictionary<string, int> ComputeFrequency(string[] input)
{
var result = new Dictionary<string, int>();

for (var i = 0; i < input.Length; i++)
{
if (result.ContainsKey(input[i]))
{
result[input[i]]++;
}
else
{
}
}

return result;
}

Let’s take an example input and see what happens, consider that we have the following text:

Algorithms are fun and educating!
Solving the algorithms are as fun as writing about them.

Breaking this up into a frequency table will give us something like this:

 algorithms 2 are 2 fun 2 and 1 educating 1 solving 1 the 1 as 1 writing 1 about 1 them 1

This is just one of the documents that we processed, we still would need to do the same for a second one. You can see from the above how the frequencies are calculated. When having the frequencies from two different documents, this is what we pass to our distance computation. We’ve still got one final step before adding them all together and executing them: we need to load the file and process the text. Notice that everything from above was lower case and that there were no spaces, line-breaks, commas or punctuation? That is because we strip the text from all that.

Honestly the only method so far that I feel is a bit messy is the one that reads the text and processes it. I’d be happy to hear how you’d clean it up, doing it in Python is so much nicer as you get more help from the framework doing the boilerplate stuff. Remember, if you think about using regex that can be a slower operation and you need to keep that in mind when designing your algorithms.

I’ve created a method that retrieves all the words for a single file and it looks like this:

public string[] GetWords(string filename)
{
var words = new List<string>();
var characters = new List<char>();

var seperators = new List<char> { ' ' };
foreach (var word in input.Split(seperators.ToArray()))
{
foreach (var character in word.ToCharArray())
{
}

if (characters.Count > 0)
{
characters.Clear();
}
}

return words.ToArray();
}

Consider the word “don’t” when processing this you’ll get it as “dont”, which is exactly what we want as we want to strip it from everything that is not an alphanumeric. The method is quiet trivial, it splits the text that it loaded by lines and spaces, then it adds each character in the current word that is an alphanumeric to our character collection, when it has processed all the characters, it adds the string representation as a lower case invariant to the collection of words. When all words are processed we are ready for the frequency calculation.

To tie it all together we can run this from the programs main method in this case and the sequence of invocations will look like this:

static void Main(string[] args)
{
var program = new Program();
var first = program.GetWords("file1.txt");
var second = program.GetWords("file2.txt");

var firstFrequencies = program.ComputeFrequency(first);
var secondFrequencies = program.ComputeFrequency(second);

var distance = program.ComputeDistance(firstFrequencies, secondFrequencies);

Console.WriteLine("The distance is: {0}", distance);

}

So looking at the conceptual definition of the algorithm you’ll see that we are doing just that.

1. Open and read both documents that you are going to compare. Only read words and numbers, skip special characters (spaces, dots, etc..) and convert the words to lower case
2. Calculate the word frequency in both collections of words, this means how many times each word occur in each document
3. Compare the frequencies from both computations and calculate the distance

I wrote two text files that contains almost the exact same data, except the author name in the end of the text is different. I opened it up in word and highlighted the difference then I ran the document distance algorithm on it and it shows us that the distance is not far at all, hence this is almost an exact copy.

You will notice that as the documents approach similarity the distance decreases and when the are identical it will be a 0 distance. If the are completely different the distance will be the maximum distance which is 1.5707963267949. This method of finding distances between documents can be used to find cheaters on essays, help with searching through documents and sort by relevance and much more. It’s a really interesting algorithm that lets you think a bit about what is going on.

The complete code is available on GitHub in my Algorithms repository.

It’s fun and educating to try and solve it on paper first by both sketching and coding on paper, you’ll find lots of interesting bugs and edge cases that you didn’t think about when the compiler isn’t there to help you out and it will greatly improve your analysis skills.

# Understanding Peak-Finding

## Posted by Filip Ekberg on February 10 2014 1 Comment

No matter how far we are in our careers as professional developers, it’s great to freshen up on our fundamentals. Be it the importance of Memory Access Patterns or algorithms in general, it’s really beneficial. I find it quiet interesting that it’s been a pretty long time since I sat in the algorithms and data structures course on my technical institute and I tend to understand it completely different now. I heard a really great thing from a professor at MIT who said the following:

You can practice really hard for two years to become a great programmer and you can practice for 10 years to become an excellent programmer. Or you can practice for two years and take an algorithms course and become an excellent programmer

A lot of us might not think about the daily algorithms and data structures that we use, in fact, we hide behind ORMs and such that hides complexity and introduces behavior that we might not be aware of. Which is one of the reasons I personally like to read up on algorithms from time to time. This time though, I’ve decided to share some of the things I learn and like, hopefully you’ll like it and it will help you to become an excellent programmer.

If you haven’t seen this, MIT has a website called Open Courseware where they have video recordings, lecture notes, assignments and exams from their courses. There is one in particular which I recently found and it’s excellent so far, it’s called Introduction to Algorithms. If it’s been a while since you looked into these topics, have a look at their content. Some of the examples and snippets here are from the lectures in this particular course.

Let’s get to it! Back to basics!

### What is Peak-Finding?

Imagine you have a set of numbers, these numbers are stored in a one dimensional array; hence a normal array. Now you want to find one of the elements where the element peaks. Notice that we don’t want to find the highest peak, we just want to find a peak. As to any problem there are multiple solutions and these solutions might differentiate from one and another. Some might be faster and some might be slower.

Let’s say that we have the following set of numbers: `{1, 2, 4, 3, 5, 1, 3}`

How would you find the peak in that?

First we need to define the requirements for it to be a peak: The element needs to be larger or equal to both the elements on its sides

There’s one really obvious way to solve this, can you think of it?

#### Finding the peak in one dimension (slow) O(n)

How about if we just iterate over each element and make sure that the elements surrounding it are less or equal? It’s a simple solution, but is it the best and fastest? Remember that we just need to find if there is a peak somewhere in the array, it doesn’t have to be the highest point.

I won’t bother with showing the code for this one, it’s just a simple loop with some boundary checks. The problem here is that we need to look at every element in the collection, which makes the time to run the algorithm grow linear with the growth of `n`.

#### Finding the peak in one dimension (fast) O(log n)

As the heading says, this is logarithmic, base 2 logarithmic to be exact. This means that somewhere in our algorithm we are dividing the set in two and doing so as `n` grows. So what might this mean, in terms of solving the problem? We’re taking a divide and conquer approach! Just as you would with binary search. Binary search divides the array in half until it finds the correct element. Searching a phone book with 2^32 amount of records would take only 32 tries because we know it is sorted!

The same approach is applicable for the peak finding. If we take a look at the set of numbers we have again: `{1, 2, 4, 3, 5, 1, 3}` we know that if we start in the middle we will look at the value 3, which is less than both 4 and 5. So what now? Which side do we jump to? We can jump to the left here and divide the set in half, leaving us with the following: `{1, 3, 4}` and we’re in the middle so we’ve selected the three here. But, three is only larger than 1 and less than 4 so we have another step to do here and that is to jump to the right, this time we only have `{4}` left so this is our base case, we only have one item and such this is a peak.

Here’s a breakdown of the algorithm where `a` defines the array and `n` the amount of elements.

if a[n/2] < a[n/2 - 1] then only look at the left 1 ... n/2 - 1
else if a[n/2] < a[n/2 + 1] then only look at the right n/2 +1 ... n
else n/2 is a peak

There’s some boundary checks that needs to go into it as well, but you get the idea and you can play around with the implementation of this.

### Two Dimensional Peak-Finder

Things are about to get interesting, we’ve looked at the one dimensional array which is sort of just divide and conquer. Now how about adding another dimension to it and looking at a 2D array? If you’re unaware of what a 2D array looks like, here’s a good example of that:

{0,  0,  9,  0,  0,  0,  0},
{0,  0,  0,  0,  0,  0,  0},
{0,  1,  0,  0,  0,  0,  0},
{0,  2,  0,  0,  0,  0,  0},
{0,  3,  0,  0,  0,  0,  0},
{0,  5,  0,  0,  0,  0,  0},
{0,  4,  7,  0,  0,  0,  0}

It’s simply represented by a `int[][]`.

In a one dimensional approach we looked at our neighbors and we’re going to do the exact same thing in this scenario as well, however in this case we’ve got two more that just moved into our block. If we had people living on our west and east sides we now also have someone living on north and south. There are of course edge cases where we need to check the boundary of the lonely soles that have no one living to their west, north, east or south.

If you think about it, how would you approach this? The MIT course that I listed above has a great Python example that you can download and play with, it comes with a interactive html export when you generate the result. I’ve recorded how the algorithm behaves which might make it easier for you to figure out what happens in this algorithm. In the below animation, when the 5 turns pink, that is when it found the peak.

There are of course faster and slower approaches to this problem as well, this is not the fastest one and it is not the slowest one. Let’s just say it’s one of the ones in the middle. Here’s a breakdown of what the algorithm does where `m` is the amount of columns, `n` the amount of rows.

Pick the middle column j = m/2
Find the largest value in the current column span (global max)
Compare to neighbors if larger than all this is the 2D peak
Jump to left or right depending on comparison (divide and conquer) run recursively
If you are at the last column, the current global max is a 2D peak

There’s a bit more to this than with a single dimension and there is also room for improvement, but read the definition of finding the 2D peak a couple of times, look at the animation and you will see this pattern. Remember that it won’t find the largest peak, just one of the peaks where it is a peak according to our rules.

#### Finding the 2D Peak

Consider that we have the following method signature for our method that looks for a 2D peak: int `int FindPeak(int[][] problem, int left = 0, int right = -1)` now as you might have seen above, this is a recursive method so instead of slicing the array, we just pass a reference to the array and a point to where it starts and where it ends.

We then call it like this:

int[][] problem = new[]{
new [] {0,  0,  9,  0,  0,  0,  0},
new [] {0,  0,  0,  0,  0,  0,  0},
new [] {0,  1,  0,  0,  0,  0,  0},
new [] {0,  2,  0,  0,  0,  0,  0},
new [] {0,  3,  0,  0,  0,  0,  0},
new [] {0,  5,  0,  0,  0,  0,  0},
new [] {0,  4,  7,  0,  0,  0,  0},
};
int peak = FindPeak(problem);

There are a couple of edge cases that we might want to handle while we are at it, such as if the array us empty. The beginning if our `FindPeak` method will look something like this:

if (problem.Length <= 0) return 0;
if (right == -1) right = problem.Length;

int j = (left + right) / 2;
int globalMax = FindGlobalMax(problem, j);

As you see here, we handle the case of when we first call our method with the value of `right` being -1. We initialize this with the length of the array, we could move this outside the method to reduce some branches in each recursion. Now we compute the current column (middle) of our start and stop. After that we look for the global max, I introduced a helper method to do this. All it does is that it goes over the same column position for each row in the array. This way we can find the index of the largest element in that column. This method can look like this:

int FindGlobalMax(int[][] problem, int column)
{
int max = 0;
int index = 0;
for (int i = 0; i < problem.Length; i++)
{
if (max < problem[i][column])
{
max = problem[i][column];
index = i;
}
}

return index;
}

We use the top rows column if we can’t find a value that is larger than it, if we do we just increase the index until we can’t find a larger one. It’s time to check the neighbors and see how they are doing, this statement can be simplified and refactored into multiple methods but let’s leave it verbose for now, you can refactor it all you want and play with it on your own:

if (
(globalMax - 1 > 0 &&
problem[globalMax][j] >=
problem[globalMax - 1][j]) &&

(globalMax + 1 < problem.Length &&
problem[globalMax][j] >=
problem[globalMax + 1][j]) &&

(j - 1 > 0 &&
problem[globalMax][j] >=
problem[globalMax][j - 1]) &&

(j + 1 < problem[globalMax].Length &&
problem[globalMax][j] >=
problem[globalMax][j + 1])
)
{
return problem[globalMax][j];
}

We’re checking 4 things, actually in this case we are only going to check 3 things because as we selected the middle column that has only 0s, there is no global max and it will use the top one when checking the neighbors as seen in this picture:

Which is also why we are doing the boundary checks so that we are not doing any Index out of Bounds exceptions! If this were the largest one of its neighbors, we would simply return from here. While writing up this article I found some interesting edge cases which I hadn’t thought of in the first implementation. Play around with different values yourself and see if you can find some errors.

After checking the neighbors we know that we need to either jump somewhere if there is a place to jump to, or we are at the current global max. If we jump to the left, we set the new right position to our current middle and if we jump to the right we set the new left to the current middle. Then we simply call ourselves like this:

else if (j > 0 && problem[globalMax][j - 1] > problem[globalMax][j])
{
right = j;
return FindPeak(problem, left, right);
}
else if (j + 1 < problem[globalMax].Length && problem[globalMax][j + 1] > problem[globalMax][j])
{
left = j;
return FindPeak(problem, left, right);
}

return problem[globalMax][j];

Now let us take a look at that animation again and see if we can follow along and do the programming steps in our head.

We’ve now found the peak in our 2D array! Here’s a question for you: What is the time time complexity of this algorithm?

The complete code is available on GitHub in my Algorithms repository.

Keep learning, keep coding and keep solving problems! Let me know if you liked this and if you found something to optimize or fix in my examples!

# Test Automation for Web Applications

## Posted by Filip Ekberg on January 30 2014 1 Comment

If you’re a web developer, I am sure you can relate to the feeling where you over and over again start up your web application, navigate to the local instance and try the same feature over and over again where you just thought you had fixed all the bugs. I’m sorry to tell you this, but you’ll most likely be starting it up and navigating to that same page a couple of more times. Both in my book and countless times on this blog I’ve said: If you do something over and over again – automate it!

Sometimes it is easier said than done, when it comes to the case of UI it’s not that easy to test everything and the investment you have to make to get everything automated might seem larger than the return of investment. I’ve tried a couple of different ones. One of the most recent ones is Sikuli – which is not the one I’m going to talk about here. I’ll mention one thing about Sikuli though, it can test any GUI, not just websites. However it relies on screenshots and other magic which makes it easy to break, hence there’s more work involved in maintaining the UI tests.

This brings us to the tool that I have in mind; Selenium.

Their punch-line is pretty simple, they automate browsers. Which in my eyes looks exactly like what I want when automating my tests for web applications. Selenium isn’t specific to C# or .NET, in fact there’s a large support for different languages such as Java, Perl, PHP, Python, Ruby and more. However, if it’s not obvious by now C# is my language of choice so I’ll show how to set this up with a ASP.NET MVC solution.

### Prerequisite

There are a couple of different things that you need before you can get started. Actually there is sort of just one thing – a web browser that corresponds with the web driver of your choice.

Selenium offers a set of web drivers, these drivers interact with browsers like Firefox, Internet Explorer, Chrome, Safari and others. This is pretty great, so you can write your browser tests and have it run against the browsers your customer requires!

I’m going to use Firefox, so all I did was installed the latest version of Firefox.

### Getting started with Selenium

Open up, or create The Next Big Thing that you have in mind, I’m going to create a Test project for my ASP.NET MVC application because that is where I want my UI test to go.

This will work with a lot of different testing frameworks, so don’t worry about that for now. If you have any extremely specific testing framework, just head over to their website and have a look if it supports that.

I want to write a test that verifies that the registration process works, that I can logout and then log back in with the same username and password. As opposed to unit tests where there can be 5 unit tests per function, I want 1 UI test for 5 functions. This might seem odd at first, but UI tests are more expensive to execute, they will take longer than normal unit tests. That isn’t the only reason though, I want to imitate the real end users behaviour when writing my UI tests.

Let’s start now by adding a new test class to the test project, let’s add this in a folder called UI just to group them nicely. My test class is called `RegistrationTest` which contains just one test method for now which I’ll call `Can_Create_Account_And_Login`. This name is pretty descriptive of what is going to happen, sure you can be even more verbose but for the sake of your eyes I’ll stick to something simple.

There’s not much to it yet, we just have the standard template MVC project, with a test project and a empty test which we are going to use for our first UI test.

### Installing Selenium via NuGet

As any other great library, you can install Selenium via NuGet like this:

Install-Package Selenium.WebDriver

Just make sure that you set it to install the package into the test project.

PM> Install-Package Selenium.WebDriver
Successfully added 'Selenium.WebDriver 2.39.0' to TheNextBigThing.Tests.

Now that the Selenium Web Drivers are installed, we can start writing our tests!

### Writing the first test

How do you imagine that we will find elements on the web page? How would you find elements if you were using, for instance, jQuery? You’re guessing right, we can use the selectors that we are use to! There are 5 elements that we want to retrieve these elements exist on the following pages:

• Register

The test we want to write will create a user by first navigating to the URL that our website is located on, I will just hard code this into the tests but I’d recommend storing this in a configuration file. When arrived at the page, we want to click the Register link, enter the username, password, password confirmation and finally press submit. When that is done a user should have been created and we can verify that by looking for the “Hello [Name goes here]”.

Of course after we’ve registered the user and automatically been redirected to the private area of the website we want to logout and verify that the data is still persisted, so we are going to somewhat do the same process but via the registration page instead.

It’s pretty funny that the tests themselves are so much less text than what it takes to explain it. So let’s start looking at that shall we?

I decided to go with the Firefox driver and you can create an instance of this:

FirefoxDriver _firefox = new FirefoxDriver();

I’ll store this as a `private readonly` field in my test class. The driver lets me do things like navigating, finding elements on the current page, submitting and things like you would expect to be able to do with a browser. It also allows you to take screenshots!

Creating screenshots is easy, we’re getting a bit side-tracked when talking about that, but go and play with `_firefox.GetScreenshot().SaveAsFile()`!

The first thing that we need to tell the driver to do is to navigate to the page where it is all located, then perform the other steps we talked about above. You easily navigate to a page by doing the following:

_firefox.Navigate().GoToUrl(<a href="http://localhost:1164/">http://localhost:1164/</a>);

As you see the API is pretty straight forward so far, so how do you imagine we get elements on the page? Well, let’s say that we want to find the register link and click that, that’s easy. As soon as the navigation is done, I’ll be performing the click event on the registration link by doing the following:

The best part here is that you don’t have to wait for the previous execution to finish, it won’t try to click anything until the navigation is done, or any other previous operation that is. I won’t bother you will explaining every single line of code in the rest of the test class, so let’s just have a look at the helper method I created to create the user:

{
_firefox.Navigate().GoToUrl("http://localhost:1164/");
_firefox.FindElementByCssSelector(".btn.btn-default").Click();

var userWasCreated =
Assert.IsTrue(userWasCreated);

_firefox.FindElementById("logoutForm").Submit();
}

Pretty straight forward right?

The helper method to login a user is equally simple:

{
_firefox.Navigate().GoToUrl("http://localhost:1164/");
_firefox.FindElementByCssSelector(".btn.btn-default").Click();

var userWasCreated =
Assert.IsTrue(userWasCreated);

_firefox.FindElementById("logoutForm").Submit();
}

These two together makes up for the first test for our website, they might seem pretty simple. The funny part is that when I wrote the tests I found rules about the registration process that I didn’t know (because I hadn’t dug into the code). So not only am I writing tests to ensure that the behaviour is the same in the future, but I also learned about my current project.

I want to be able to run this test over and over again, so I made some small tweaks to my test method and here’s a complete implementation of the test class:

using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Firefox;

namespace TheNextBigThing.Tests.UI
{
[TestClass]
public class RegistrationTests
{
private readonly FirefoxDriver _firefox = new FirefoxDriver();
[TestMethod]
{
string.Join("", Guid.NewGuid()
.ToString()
.Take(5));
string.Join("", Guid.NewGuid()
.ToString()
.Take(6));

}
{
_firefox.Navigate().GoToUrl("http://localhost:1164/");
_firefox.FindElementByCssSelector(".btn.btn-default").Click();

var userWasCreated =
Assert.IsTrue(userWasCreated);

_firefox.FindElementById("logoutForm").Submit();
}
{
_firefox.Navigate().GoToUrl("http://localhost:1164/");
_firefox.FindElementByCssSelector(".btn.btn-default").Click();

var userWasCreated =
Assert.IsTrue(userWasCreated);

_firefox.FindElementById("logoutForm").Submit();
}
}
}

It’s not really that massive or hard to get started with, this is a very simple scenario but it’s going to help a lot with future development of the application. Now whenever I add something new to my web application that is visible from the user perspective, I can just run all my automated UI tests  and verify that the application is intact. If you have lots of them, it’s going to get a bit slow, so think about having a CI server that runs these heavy tests for you so you’re not blocked in your development.

This is what it will look like when you run it, one thing, make sure that the web application is already up and running, if the tests can’t reach it they’ll fail! Notice that in the end of the test run, all the tests turn green and you can go on to testing the next thing.

Of course there are a couple of things that could come back and bite you if you’re not careful, as always that is. One of the things to keep in mind is that when you use the selectors for your items, what happens if you have the same css selector for multiple items? What happens if you remove the class? There are a bunch of cases like that which you need to have in mind, but at the end of the day, this will surely help you ensure the application works better than if there were no tests!

# Developing Good Software is Damn Hard

## Posted by Filip Ekberg on January 29 2014 9 Comments

Since I first set my foot in the “Software Architecture” class back at the technical institute it feels like I’ve taken things for granted. Over the years I have seen myself as a pretty good software engineer, a programmer with many hats be it developing in C#, Java, Python, PHP, Objective-C, and I’ve tackled lots of different problems. It just hit me though developing good software is damn hard.

I’ve been working for a bunch of different companies now and been on lots of different projects all teaching me different things along the way. It wasn’t until recently though when I got onto a project where everything was, sort of, by the book. As I mentioned, I’ve seen myself as a senior developer for a long time now and in many projects where I’ve been that has been the case. Starting on this project though has in a way opened my eyes again and I see that I still have so much to learn.

I don’t say this as a bad thing, not having things to learn is one of the many reasons I’ve changed companies over the years as I like to be challenged. When I attended the “Software Architecture” class and the teacher talked about decoupled solutions and all that, I just thought it all sounded so very trivial, I wonder though, did I ever really write by the book code? “By the book” is an expression used a lot, even outside software development and it has sort of a negative ring to it. There’s so many things that will not work by the book, so how about just focusing on the things that are possible to do by the book? I mean consider working on a really time intensive project, you won’t have the time to do all the things you would in a multi-million dollar project, right? As long as the customer understands that – everything will be fine. Let’s not get side-tracked on this, the customer rarely understands the implications of not doing it “by the book” and in the end, it’s the customer that’s going to be hurt from that.

When I use the phrase “by the book”, I’m referring to the way that the software is designed and how it’s evolving and not growing (too much) out of the bounds of what “by the book” is. In my case “by the book” isn’t a negative term to use, at least not in this case. I can’t and won’t go into detail about what the project is, but it was well underway when I started working on it and I thought to myself that this would be yet another hard project and even harder domain to understand – oh boy was I wrong. The domain was very straight forward and the code was, well let me put it in simple terms, “by the book”. Sure there are things that could be better, things that had to be hurried up to get finished in a certain amount of time. However, the quality of the code was impressive for something that had been developed on for at least 10-12 months.

Imagine the feeling, when you first fetch the code from the source control that the team works in, you compile it on your machine and starts browsing around. You notice that everything follows the same pattern, the project leads tells you to take a look at a certain piece of the software and uses terms from the business to describe something in the domain that you are about to work on. Suddenly you get this feeling that “damn I have no idea where to start”, but as a senior developer you quickly ask ReSharper to find all the files that could have something to do with the buzz-words that the lead just used. In front of you is now a bunch of files that looks to be exactly what the lead was talking about. Opening these files directly gives you an insight into the business and the domain, it’s like seeing a jumping unicorn on a rainbow – the structure is just so beautiful.

Well structured code will talk to you, without having someone explaining every single line of code for you. It will tell you a story about what the business has asked for and by just reading the code you can start talking to the customer about their domain – this is well structured code.

When I first fetch all the code from the source control I like to run all the tests, to see that everything is working – maybe even adding some tests of my own to understand the domain even better. None of the objects have default, empty constructors though, so how do I create them? How do I know what parameters to pass? Well in my world, all objects that exist in memory are valid objects without any errors. I notice another pattern when looking over the tests, all the tests ask for something through builders, these builders know how to setup valid objects that I can use in my tests. All of a sudden I am on my way to playing around with valid objects, writing tests and getting a so much better understanding of the domain.

I start to get a bit afraid after running all the tests and playing around with the code. What about the database? Did anything I just performed affect any of the data in the database? Not in this world. In my world everything is decoupled and I don’t have to worry about the underlying data structure. Not even when testing actions from my controllers that I know for a fact modifies the data in the database. I notice that the actions raise events that someone else is listening to, this means that when I test my solution I can just ignore these events and be on my merry way.
It hits me, it’s so extremely rare to work with code that is so well structured and so well designed. I need to value this time, learn as much as I can so the next time I am asked to be a part of the design team of a new software I can amaze someone.

I just turned 27, today actually and I have been coding longer than I haven’t. It’s pretty amazing waking up and knowing that you will learn something new and that software development is so extremely fun, educating and yeah, damn hard.

I thought about naming this article “The beauty of a decoupled solutions”, but the message didn’t really seem to go through that well with that title.

# 2013 was an amazing year, here’s a summary!

## Posted by Filip Ekberg on January 1 2014 2 Comments

Another year has gone by and it’s the third yearly summary that I’m writing, hopefully not the last one! I began the previous one that I wrote in the end of 2012 by stating that “Saying that a lot happened in 2012 is probably an understatement.”, I’d like to start this summary similarly. However it hit me that each time I do look back at what I’ve done the previous year, it’s always going to be packed with a lot of great stuff. I like challenging myself both professionally and personally, my friends and co-workers most likely see this in me regularly.

This year started off really great, newly engaged in New York, I received an e-mail telling me that I had become a Microsoft MVP in Visual C# and I had a couple of talks lined up. At the start of this year I really had no idea how much things really would change, I really got to give a shout out to Jake for opening my eyes to Readify in Australia!

I always expected that I would be working overseas at one point or another, at least I always did dream about it. As I always tell others to follow their dreams, why shouldn’t I take the leap of faith and do the same? Having been in Sydney for a bit over 4 months now I can say that it’s truly been great. Generally this is my least favourite time of year (not including xmas, new years and my birthday), I am of course talking about the depressing cold and darkness that comes over Sweden. Australia totally beat the crap out of that though it’s warm, sunny and people are happy here, Love It!

C# Smorgasbord

I really can’t write a summary post without talking about my book, C# Smorgasbord. Even though it’s about 1 year and 5 months since I published it most of the sales has been this year. I’ve now reach above and beyond 1200 books out there, sure this includes books from my give away too, but those are just a small number of books. When I looked over the sales in different channels, I was amazed to the see the support from everyone.

If you’ve read C# Smorgasbord, I’d love to hear about it and I’d also love to hear about if it has helped you in any way.

For anyone thinking about self-publishing I can really recommend it and I wrote a blog series about my experience. I’d like to share the percentage of sales from different channels:

Printed copies 54.5%
Digital copies 45.5%
(Kindle/eBook bundle = 50/50)

Pluralsight

I published 2 courses on Pluralsight this year, which took a lot of time to record and edit. Much more time than most people might seem to expect from when I tell them about it. The topics I choose are really completely different from one and another, the first one was MSIL for the C# Developer and the second one was Game Programming with Python and PyGame. Completely different but awesome and fun topics!

Architecture

Tips & Tricks

Presentations

Software & Tooling

C# Smorgasbord and Self-Publishing

Inspirational

Other

I want to thank everyone that helped me achieve all the amazing this 2013 and I really hope that 2014 will be as good. Without your support I would never have written 40 articles, held 17 presentations, done 3 interviews, webinars, written 2 magazine articles and published 2 courses. It’s your energy and support that makes it fun, keep learning and keep being awesome!

# Hello Nancy

## Posted by Filip Ekberg on December 19 2013 6 Comments

Have you had a chance to play with Nancy yet? Nancy is a way for us to experience the web in a lightweight way, without relying on ASP.NET or ASP.NET MVC. I’m not saying that Nancy is replacing any of those, but it is here as an alternative. Let’s look at some examples of what a Nancy demo application might look like, to give you an idea of how easy it is.

Nancy is a lightweight, low-ceremony, framework for building HTTP based services on .Net and Mono. The goal of the framework is to stay out of the way as much as possible and provide a super-duper-happy-path to all interactions.

As the authors of Nancy explains it, they want to stay out of the way as much as possible. Have you ever created an Emtpy Web Application and then added everything that you need to get ASP.NET MVC running? It might be trivial, it might not be, depends on how much knowledge you have about what happens when you create a new ASP.NET MVC Web Application using the template.

I figured I wanted to give Nancy a try, I’ve seen it being used all over the place and people are praising it as it is really lightweight and not in your way; I really like things like that! (Which is why I wrote my book using LaTeX: Focus on Content and not the Markup).

So where do you start? Nancy is open source and I figured I shouldn’t have to pull the code from Github to get started, there must be a NuGet package! So let’s create a new Empty Web Application and start from there.

This leaves us with a pretty blank solution and we can start off by trying to install some stuff via NuGet. Bring up the Package Manager Console, write Install-Package Nancy and press Tab. This will show you a huge amount of interesting packages that we might need to get this running.

Since we created an empty web application, we’re going to use the “ASP.NET Host”, there’s a package that helps us configure all that called Nancy.Hosting.Aspnet, we’re also going to want the Nancy base package and the package that lets use Razor as a view engine. So let’s bring the following packages into our solution:

Install-Package Nancy
Install-Package Nancy.Hosting.Aspnet
Install-Package Nancy.Viewengines.Razor

These packages have dependencies on Nancy so we probably wouldn’t need to bring in the base package itself as they would have done that. Alright, now we have a set of references in our project and it most likely did some changes in the web.config, let’s not care about that for now. There’s not really much in our solution, we just have the references, packages config and the web config!

How do we create a web page?

I haven’t dug deep enough in the history of Nancy or why they call things what they do, but in order to create “something” that serves us data (or lets us receive data) is called ” `Modules`“. These modules inherit from a class called `NancyModule`.

In the constructor of the module we could define the routes for the current module. If you’re an ASP.NET MVC developer you know that our routes are setup in the Global.asax.cs file, here the module is in charge of setting up its routes.

These routes are setup using something called `Get` (for Get that is!), there’s also Post, Put, Delete, Patch and what other Http Verbs there might be. This is fairly straight forward, we can define a route by assigning a function to a pattern, this pattern can be a complex regex or it can be a simple string.

Let us say that I want to return a string when I navigate to `/` on my website, I could simple setup the following route in my modules constructor:

Get["/"] = _ =>
"Welcome to my Nancy Demo Site!";

When the application is launched and you navigate to `/` it will now simply display that text, if you view the source, it is only that text, no wrapping HTML or anything like that.

The entire code for making that work is the following:

using Nancy;

namespace NancyDemo
{
public class NancyDemoModule : NancyModule
{
public NancyDemoModule()
{
Get["/"] = _ =>
"Welcome to my Nancy Demo Site!";
}
}
}

Simple enough right?

The solution is so clean and we can focus on what is important: The functionality of the application!

We don’t really want all our HTML inlined in our code though, so how about if we move this to a Razor view instead? Remember from before, we pulled in `Nancy.Viewengines.Razor` from NuGet this allows us to use Razor views! It does a lot of magic in the Web.config but let us not worry about that too much, it still keeps the solution clean for us.

I setup a directory structure that I am happy about, I moved my Nancy module to a folder called Controllers then I created another folder called Views where I want to add all my views. There are multiple different View Engines that you can use with Nancy, but I am most familiar with Razor so I am going to stick with that.

Instead of returning a string in the function that we associate with the Get route, we can simply return a View like this:

Get["/Demo"] = _ => View["Demo"];

This will look for the view “Demo” in the Views folder, Nancy uses some magic to find the correct view, just as it uses some magic to determine which route to use if routes are similar.

I added a Layout.cshtml file in the Views\Shared folder, the funny thing is that Nancy seem to reference these layout files a bit different from how I’ve done it in ASP.NET MVC, not entirely different, but different enough that it will crash if you don’t do it right.

Normally when setting which layout file to use we do the following:

Layout = "~/Views/Shared/_Layout.cshtml";

However, with Nancy we must remove the leading “~/” otherwise it will throw an exception on us. My view does thus look like this:

@{
Layout = "Views/Shared/_Layout.cshtml";
}

Hello from my Nancy Demo!

Easily enough I can press F5 to debug the application and it shows me my two beautiful pages.

There’s much more to Nancy than this demo application, but with just some easy steps we’ve created something we can work with and we don’t have so much in the application that it’s messy with lots of files.

The Nancy documentation page is full with lots of interesting information about what you can do with Nancy and I’d love to hear if you used Nancy in a larger production web site! If you get hooked on Nancy or want to read more about it, Philip Haydon has a lot of interesting articles on his blog!

# Making sound using C#

## Posted by Filip Ekberg on December 16 2013 2 Comments

Back in the mid-90s when I first was introduced to the concept of programming the only thing that I could really do that I found funny was to have the computer BEEP at me. At this time of course I didn’t have anything as fancy as Visual Studio or C# to work with, it was just me and my QBasic editor. Basically an application back then looked something like this (syntax may or may not be correct):

CLS
PRINT "Hahaha"
BEEP
BEEP
BEEP
BEEP

Why not use loops? Come on, I was what? 8 years old? I barely understood the concept of how to eat properly with a fork and knife so don’t expect anything fancier than that from an 8 year old! Joking aside, I can’t really recall all the funny moments I had with QBasic, but I do remember playing with BEEP, INPUT and PRINT no matter how primitive it might seem.

The years have passed and I haven’t thought about BEEP sine recently, I came across something, I can’t really remember where and I saw that you can do `Console.Beep()` in C#! For me, this was like seeing one of those cartoons or eating something that you loved as a kid, it brings back those memories of when you first played with and “built” something using a computer.

Of course I just had to do some research and look for ways to do fun stuff with this, guess what I found on reddit? Someone had done the Super Mario theme using `Console.Beep()` because `Console.Beep()` takes a frequency and a length for how long it should play. Amazing isn’t it? I’m gonna save you the scrolling and not paste the code to play the super mario theme in your applications using `Console.Beep()`, just click the reddit link and check it out!

This wasn’t enough for me though, BEEPing was something I did when I was 8 years old, I need to show my parents some progress in my professional career as a software developer. Let’s add some voice!

I started off by looking in to how you can make something speak using C#, did you know there is a class called `SpeechSynthesizer`? You can use this to speak words using text, I think it uses the same technology in the background as Microsoft Sam. This is really great, I came up with lots of fun ideas on what this could be used for. Don’t underestimate the seriousness in `SpeechSynthesizer` though, it helps lots of people that can’t see.

What can you do with BEEP and VOICE? Celine Dion!

I looked up the notes for My Heart Will Go On by Celine Dion, converted that into BEEPs using the frequency and the length (I had some help from the reddit thread) and then it hit me: How do I play a BEEP and VOICE at once? Can I do that?

Sure you can! Here’s the code snippet that I came up with:

{
Console.Beep(520, 215);
Console.Beep(520, 265);
Console.Beep(520, 265);
Console.Beep(520, 215);
Console.Beep(560, 215);
Console.Beep(520, 215);
});

{
SpeechSynthesizer synth = new SpeechSynthesizer();
synth.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Senior);
synth.SpeakAsync("Every night in my dreams");
});

I had much fun in creating that, so much that I shared it to my friends on twitter and got a pretty fun response from David Poeschl (@dpoeschl):

What fun things can you come up with combining BEEP and VOICE?

Here’s some things that you could use BEEP and VOICE for:

• Audible error alerts when something crash (Example: BEEP morse code)
• Feedback when developing (Example voice: “Hey, programmer, you can refactor this class!”)

I write software for a living, but don’t forget that you can have fun with it once in a while as well.

## Posted by Filip Ekberg on December 6 2013 1 Comment

I’m happy to announce an early Christmas present for you all; I am giving away a free sample of my book, you can now download Chapter 1 completely free!

The chapter is called Introduction to Parallel Extensions and it talks about parallel programming, LINQ/PLINQ and Egg Boiling. I really hope you enjoy this free sample so much that you want to read the rest of the book as well! Don’t forget to tell your friends to download it.

Just want to buy the book?
There are multiple versions available: Printed, Kindle, eBook.

# Debugging Asynchronous Code in Visual Studio 2013

## Posted by Filip Ekberg on November 15 2013 1 Comment

With Visual Studio 2013 being publicly released I think it’s time I show off one nice improvements in Visual Studio 2013.tudio 2013. There are in fact a lot of nice improvements in Visual Studio 2013 and one of my favourite ones, actually two of my favourite ones are the debugging improvements of asynchronous code and the information that we are given about for instance how many references there are to our method(s).

You’ve been able to see the current executing threads for a while now in previous versions of Visual Studio, but now you can see a breakdown of the current tasks that are being executed. While you are debugging your application you can go ahead and open up the new `Tasks` window. Without having to navigate yourself around the endless menus in Visual Studio, you can go up to the right corner (don’t click the X!) and type `Tasks` in the search box, you should see something like the following:

I put together a fairly simple code snippet to show some data in the new window that we have access to in order to get improved information about the running tasks and the sample looks something like this:

class AmazingApi
{
{
{
};

{
}
);

}
}

Notice that the method doesn’t really return anything but it’s best practice to return a `Task` instead of `void`, I recently did a talk on why that is so if you want to know that go and have a look! Another thing to notice is that I follow the method naming convention and appending the word `Async` to the method name.

Alright, let’s go back to the window that we are looking for now, I set a breakpoint, told Visual Studio to start a new debugging instance and this is what I get now:

The `Tasks` window gives us tons of important information such as: