Skip to main content

The gyroball code challenge

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?</pre>

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([&quot;0&quot;; &quot;1&quot;; &quot;2&quot;; &quot;3&quot;; &quot;4&quot;; &quot;5&quot;; &quot;6&quot;; &quot;7&quot;; &quot;8&quot;; &quot;9&quot;; &quot;x&quot;; &quot;y&quot;; &quot;z&quot;])

member this.Convert (n:int) =
    let division = (n |&gt; float) / (alphabet.Length |&gt; float) |&gt; System.Math.Truncate |&gt; int
    match division with
    | 0 -&gt; alphabet.Item(n)
    | _ -&gt; 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.

comments powered by Disqus