Project Euler: Problem 2

Alright, next Project Euler problem:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

Find the sum of all the even-valued terms in the sequence which do not exceed four million.

Continue reading

Project Euler: Problem 1

Recently I decided that my brain needed some exercise. So I figured I would try to solve a couple of Project Euler problems once in a while. And while I was at it, try to to do a bit of TTD, or at least write test cases for things. What is Project Euler? Well, here is some of what they say about themselves, whoever they are:

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

The motivation for starting Project Euler, and its continuation, is to provide a platform for the inquiring mind to delve into unfamiliar areas and learn new concepts in a fun and recreational context.

I’m not particularly good at these things, but it is quite fun when you get it right. I also get to practice my Google-Fu a bit when I need to freshen up things I learned during math at school, but have forgotten. Or if I find that my solution to a problem is totally awful and takes ages to solve…

Anyways, I can recommend the problems so far. They have (so far) been mind bending enough to be challenging, but not so insanely difficult that they are impossible.

The first problem goes like this:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

And to give you a chance to solve it without seeing my solution, I will put my solution on the next page ;)

C#: Handy BCrypt class for hashing passwords

I was working on an application where I needed to store user names and passwords in a database, as we often do. As we all (should) know we never (ever, ever) store passwords in plain text. If we do, we are setting ourselves up for big trouble if the database contents leaks out or someone hacks their way into it. So what should you do?

You should salt the passwords and you should hash them, and hash them good.

Using raw hash functions to authenticate passwords is as naive as using unsalted hash functions. Don’t. – Thomas Ptacek

So, I was looking for a good implementation of a good hashing algorithm and found one written by Derek Slager called BCrypt.net. I really like it. It has a very clean interface and is super easy to use. So to make sure I don’t lose it (if he would remove it or I would lose the link or something), I post it here. And if it helps someone else to discover it and to ease their day a little, that would be awesome too :)

You use it like this:

// Pass a logRounds parameter to GenerateSalt to explicitly specify the
// amount of resources required to check the password. The work factor
// increases exponentially, so each increment is twice as much work. If
// omitted, a default of 10 is used.
string hashed = BCrypt.HashPassword(password, BCrypt.GenerateSalt(12));

// Check the password.
bool matches = BCrypt.CheckPassword(candidate, hashed);

You find the class here.

C#: Natural sorting

When you create an application that displays data in lists or tables, you often run into the problem of sorting. When dealing with only numbers it isn’t a big deal, but when sorting text it can be. Regular sorting is often done by alphanumerically, which means that ‘bear’ comes before ‘cat’ and ’5′ comes before ’7′. The problem is that this is done letter by letter, which works for most of the time, except when you get numbers in with your text. Then you end up with for example ’2′ coming after ’10′, since ’10′ starts with a ’1′ which comes before ’2′. The solution to this is something called natural sorting.

I won’t write a lot about that here, but just say that it tries to sort things the way humans do. Anyways, below you find a C# class that handles this for you. I put it together by looking around and taking some bits and pieces from here and there, so I can’t really take credit for it. I only post it here so that I won’t lose it, cause it was really helpful.

The class uses some built-in sorting functions in windows and implements the IComparer interface. It can for example be used with the OrderBy extension methods and the Sort methods of List.

using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;

namespace Geekality
{
    public sealed class NaturalStringComparer : IComparer<string>
    {
        private readonly int modifier = 1;

        public NaturalStringComparer(bool descending)
        {
            if (descending)
                modifier = -1;
        }

        public NaturalStringComparer()
            :this(false) {}

        public int Compare(string a, string b)
        {
            return SafeNativeMethods.StrCmpLogicalW(a ?? "", b ?? "") * modifier;
        }
    }

    public sealed class NaturalFileInfoComparer : IComparer<FileInfo>
    {
        public int Compare(FileInfo a, FileInfo b)
        {
            return SafeNativeMethods.StrCmpLogicalW(a.Name ?? "", b.Name ?? "");
        }
    }

    [SuppressUnmanagedCodeSecurity]
    internal static class SafeNativeMethods
    {
        [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
        public static extern int StrCmpLogicalW(string psz1, string psz2);
    }
}

How to use assembly embedded resources

After some digging around, I found that it actually wasn’t that difficult at all.

Getting it in

Putting something in an assembly as an embedded resource is pretty easy. At least if you are using Visual Studio. Just add the file to your project, click on it, and then under Properties set Build Action to Embedded Resource. And thats it!

Getting it out

Lets say we want an image called hello.png in a folder called Wopdidoo as a Stream.

If we are executing code in the same assembly, we can do as follows:

Assembly assembly = Assembly.GetExecutingAssembly();
Stream imageStream = assembly
    .GetManifestResourceStream("DefaultNameSpaceOfAssembly.Wopdidoo.hello.png");

If you are not executing code in the same assembly you just have to get that assembly reference in a different way. I often use Assembly.GetAssembly(typeof(T)), where T is some type you know exists in the same assembly as the file you want. The rest is the same.

As far as I know, you use the stream as any other stream. Not sure if it is writable though? Probably not… let me know if you have some brilliant clues on that matter :)

:?: Remember to Dispose it when you are done.

Finding it

I sometimes find it a bit difficult to figure out that string which identifies the resource. I then often use the following code to “find” it:

foreach (string s in assembly.GetManifestResourceNames())
    System.Diagnostics.Debug.WriteLine(s);

It basically just scans through all the resource names and prints them out to the debug console :)

Quick way to do cross-thread calls to update form controls

When doing background work you often want to call back to a user interface and let the user know that you are not dead. However, this is can be a bit difficult some times because windows forms can only be updated by code running on the same thread as the forms are. So, to get around this you can for example use a method called Invoke on the control or form you need to update.

private void SomeEventHandler(object sender, SomeEventArgs e)
        {
            // Check if invoke is required
            if (InvokeRequired)
            {
                // And if it is, call Invoke on the form with a delegate to this same method and return.
                Invoke(new Action<object, SomeEventArgs>(SomeEventHandler),
                   new[] { sender, e });
                return;
            }

            // Second time around, InvokeRequired will be false and it will skip
            // here where you can update the controls you need to update
        }