1
Sep

The gyroball code challenge

by Mikael Lundin in F#, Programming

Thycotic presented a code challenge where you could win a gyroball here. Since I live in Sweden, I’m not eligible to win this challenge but I thought it would be fun to solve the problem.

// We have designed a new magical number system called "alpha-end".  This number system is
// similar to hexadecimal but has the following characters:  0 1 2 3 4 5 6 7 8 9 x y z
// (basically the decimal number system plus the 3 characters x, y and z)
// Therefore converting from decimal to alpha-end gives the following:
//    5   =>   5
//    10  =>   x
//    13  =>   10
//    20  =>   17
// Your task is to implement the Converter.Convert method for this new number system to get all the
// unit tests passing.  Feel free to add more unit tests as you work if it helps you test drive to the goal.
// You will be judged based on the accuracy and design of your code.
//
// Extra challenge:
// Try extending from your Converter to support other number systems such as binary, octal and hexadecimal.
// Is there an easy way to refactor your code/algorithm to support this?

Simply, write a method that will convert from decimal to any number system. Lucky for us all their examples contains only positive discrete numbers.

type Converter(alphabet:list<string>) =
    let alphabet = alphabet

    new () = Converter(["0"; "1"; "2"; "3"; "4"; "5"; "6"; "7"; "8"; "9"; "x"; "y"; "z"])

    member this.Convert (n:int) =
        let division = (n |> float) / (alphabet.Length |> float) |> System.Math.Truncate |> int
        match division with
        | 0 -> alphabet.Item(n)
        | _ -> this.Convert division + alphabet.Item(n % alphabet.Length)

type BinaryConverter() =
    inherit Converter(["0"; "1"])

type OctalConverter() =
    inherit Converter(["0"; "1"; "2"; "3"; "4"; "5"; "6"; "7"])

type HexConverter() =
    inherit Converter(["0"; "1"; "2"; "3"; "4"; "5"; "6"; "7"; "8"; "9"; "a"; "b"; "c"; "d"; "e"; "f"])

Here’s the same thing in C#.

public class Converter2
{
    private readonly string[] alphabet;
    private static string[] AlphaEnd = new[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "x", "y", "z" };

    public Converter2()
        : this(AlphaEnd)
    {
    }

    public Converter2(string[] alphabet)
    {
        this.alphabet = alphabet;
    }

    public string Convert(int number)
    {
        int division = (int) Math.Truncate(((double)number) / alphabet.Length);

        if (division == 0)
        {
            return alphabet[number];
        }

        return Convert(division) + alphabet[number % alphabet.Length];
    }
}

Personally I think F# looks much better.

31
Aug

Outsource your caching with memcached

by Mikael Lundin in Programming

I’m currently working on a large business system for a client where there are several caching situations, because the service that delivers the data is too slow, the database is too slow or we don’t want to hit the source for the data all too often.

I’ve been hand rolling most of these cache layers myself. I don’t like the idea of using ASP.NET caching for non ASP.NET applications.

Memcached

Always when I hit the same problem the third time, I start looking for a common solution. When I was about to write my third caching implementation, I made a google search and found out that I probably should move the cache outside the application pool into a seperate service. Memcached is a service that I’ve heard of before, but I haven’t really tried it out.

Memcached is

  • a key/value store
  • hip and cool because it’s NoSQL
  • available as a windows service from NorthScale with a simple .NET client API

How does it work?

Download and install the service from NorthScale. You’ll get a user interface where you can analyze status of your cache service. Notice all the stuff about clustering which is cool, but probably only usable if you’re Facebook or Twitter.

Before you start writing code you should create a bucket, where you want to store your data. If I understood this correctly, buckets are just there to separate one type of cached data from another type of cached data.

Your own project

Add references to the Enyim.Caching.dll and Northscale.Store.dll.

You will need to add configuration to tell NorthScaleClient where to find memcached service.

<configuration>
	<configSections>
		<section name="northscale" type="NorthScale.Store.Configuration.NorthScaleClientSection, NorthScale.Store" />
	</configSections>
	<northscale>
		<servers bucket="default" userName="Administrator" password="password">
			<add uri="http://localhost:8080/pools/default" />
		</servers>
		<socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:00:10" />
	</northscale>
</configuration>

Now you can get and set data from the cache like this.

public string GetData(string key)
{
    // "memcached" is the configuration section name
    // "default" is the bucket name
    var cache = new NorthScaleClient("northscale", "default");

    // Get data from key, returns null if key is not set in cache
    var result = cache.Get<string>(key);
    if (result == null)
    {
        // Since cache did not exist, get from real source
        result = service.GetData();

        // Input data found to cache
        // Add result to cache (will not overwrite any value)
        // "key" - the key to store it under
        // "result" - the value to store
        // TimeSpan.FromDays(1) - let it expire in 24 hours
        cache.Store(StoreMode.Add, key, result, TimeSpan.FromDays(1));
    }

    return result;
}

Easy huh! Now, go out there and cache the world!

28
Aug

StarCraft 2 crashes on Connect to Battle.net

by Mikael Lundin in Other

I told you about my problems with the StarCraft II Loader recently. After solving that problem I didn’t get very far, until I reached next one.

The game will crash pressing the connect button.

After trying all kind of things I found out that my NOD32 Antivirus software was the cause. Or rather, the problem is that the StarCraft client does not play well with antivirus. Here’s another report with Comodo Internet Security.

Temporarily disable NOD32 to play StarCraft II

  1. Right click on the NOD32 icon in your task bar, and select Open Window.
  2. Press Setup and select “Temporarily disable Antivirus and antispyware protection”

Now you should be able to connect to battle.net and play the campaign. You might think that these issues should have been taken care of during the beta testing. Anyway, I’ll get back to you if I run into any more problems.

28
Aug

StarCraft II requires a patch. Would you like to download and install the patch now?

by Mikael Lundin in Other

So, I finally got around buying, and installing this StarCraft 2. I couldn’t resist being part of the talk-the-talk at work.

Anyhow, it took me 1 week before I had enough time to push the “Start Game” button, and then I met a loop with the error message “StarCraft II requires a patch. Would you like to download and install the patch now?”. Very frustrating.

The reason is that there is a patch available, but the downloader does not recognize your internet/proxy settings. This is easily fixed.

  1. Open up Internet Explorer. Go to Tools – > Internet Options.
  2. Go to connections tab and press the button [LAN Settings]
  3. Make sure that “Automatically detect settings” is unchecked. The problem could also be located around your Proxy server settings, if you’re using a proxy server.

Enjoy the game!

23
Aug

Project Euler #020

by Mikael Lundin in F#, Project Euler

n! means n × (n − 1) × … ××× 1

Find the sum of the digits in the number 100!

let factorial n : bigint = List.fold (*) 1I [1I .. n]

let sum (n:bigint) =
    n |> string |> Seq.fold (fun acc x -> acc + System.Int32.Parse(x.ToString())) 0

sum (factorial 100I)

If you consider using bigint to be cheating, here’s a solution that will calculate it with the use of lists instead.

let rec plan overflow l =
    match l with
    | head :: tail ->
        let column = head + overflow
        if column > 9 then
            let next_overflow = column / 10 |> float |> System.Math.Truncate |> int
            (column - next_overflow * 10) :: plan next_overflow tail
        else
            column :: plan 0 tail
    | _ -> if overflow > 0 then
              (overflow % 10) :: plan ((overflow - (overflow % 10)) / 10) []
           else
              []

let add (l1 : int list) (l2 : int list) =
    l1 |> List.map2 (fun i1 i2 -> i1 + i2) l2 

let prod (l1 : int list) (l2 : int list) =
    let tenths i = 10.0 ** (i |> float) |> int
    l2 |> List.mapi (fun i x -> l1 |> List.map (fun y -> x * y * tenths (-1 + l2.Length - i)))
    |> List.fold (fun acc l -> add acc l) (List.init l1.Length (fun i -> 0))
    |> List.rev
    |> plan 0 // from outer space
    |> List.rev

let to_list n =
    let rec calc x =
        if x > 0 then
            (x % 10) :: calc ((x - (x % 10)) / 10)
        else
            []
    calc n |> List.rev

[2..100] |> List.map (fun x -> to_list x) |> List.fold (fun acc y -> prod acc y) [1] |> List.sum