Starbeamrainbowlabs

Stardust
Blog


Archive


Mailing List Articles Atom Feed Comments Atom Feed Twitter Reddit Facebook

Tag Cloud

3d 3d printing account algorithms android announcement architecture archives arduino artificial intelligence artix assembly async audio automation backups bash batch blender blog bookmarklet booting bug hunting c sharp c++ challenge chrome os cluster code codepen coding conundrums coding conundrums evolved command line compilers compiling compression conference conferences containerisation css dailyprogrammer data analysis debugging defining ai demystification distributed computing dns docker documentation downtime electronics email embedded systems encryption es6 features ethics event experiment external first impressions freeside future game github github gist gitlab graphics guide hardware hardware meetup holiday holidays html html5 html5 canvas infrastructure interfaces internet interoperability io.js jabber jam javascript js bin labs latex learning library linux lora low level lua maintenance manjaro minetest network networking nibriboard node.js open source operating systems optimisation outreach own your code pepperminty wiki performance phd photos php pixelbot portable privacy problem solving programming problems project projects prolog protocol protocols pseudo 3d python reddit redis reference release releases rendering research resource review rust searching secrets security series list server software sorting source code control statistics storage svg systemquery talks technical terminal textures thoughts three thing game three.js tool tutorial twitter ubuntu university update updates upgrade version control virtual reality virtualisation visual web website windows windows 10 worldeditadditions xmpp xslt

C Sharp Performance Tests: Squaring Numbers

The semester 2 coursework has begun, and this time there is a choice of either make a game to a specification, or produce a business related application to a specification. I have chosen the game.

To start off, I started writing a few mathematical functions that I would need when ewriting the game itself. I quickly found that one of things you do rather a lot is squaring numbers. In C♯ I have found 2 ways to square a number so far: a*a and Math.Pow(a, 2), where a is a number.

Even though it probably doesn't matter about the speed at which we square numbers (there are much better optimisations to make), I decided to test it anyway. I wrote this program:

using System;
using System.Diagnostics;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("This program tests the performance of squaring numbers.\n");
        Console.WriteLine("Iterations | a*a Time | Math.Pow(a, 2) Time");
        Console.WriteLine("-----------|----------|--------------------");

        int iterations = 100000;
        double number = 3092d;
        double result;

        while(true)
        {
            Stopwatch timera = Stopwatch.StartNew();

            for(int i = 0; i < iterations; i++)
            {
                result = number*number;
            }
            timera.Stop();

            Stopwatch timerb = Stopwatch.StartNew();
            for(int i = 0; i < iterations; i++)
            {
                result = Math.Pow(number, 2);
            }
            timerb.Stop();

            Console.WriteLine(" {0,9} | {1,8} | {2}", iterations, timera.ElapsedMilliseconds.ToString(), timerb.ElapsedMilliseconds.ToString());

            iterations += 100000;

            System.Threading.Thread.Sleep(500); // make sure that we don't crash the server
        }
    }
}

(pastebin, binary)

I didn't have a Windows Machine handy when writing this post, so the binary has been compiled with mono's dcms. Please leave a comment below if it doesn't work for you.

Everything is done with doubles to maek it a fair test because C♯'s Math.Pow method will only accept a double. The code sleeps for half a second between runs because I was writing this on the server that is serving the websitee, and I didn't want to crash it by accident :)

The results were rather shocking. The easiest way to display the results is in a graph:

A graph of the results.

A pastebin of the results can be found here.

As you can quite clearly see, Math.Pow() is horribly inefficient compared to just multiplying a number by itself. Next time I am squaring numbers, I won't be using Math.Pow again.

Coding Conundrums 2

Number two in a series of more than one. Definitely.

Welcome to my solutions to Rob Miles' Coding Conundrums 2. The problem descriptions can be found below, along with pastebin and 32 bit binary links (other binary type available upon request). If you need any help, please ask in the comments below.

2.1: Crazy Times Tables

Description

A teacher friend wants to be able to print out stupid times-tables for their kids at school. Perhaps they are not a maths teacher. I have no idea. Anyhoo, the program should request the number of the table (for examplethe3.7 times table) and then print out 1 to 12 timesthat value:

What times table do you want? 3.71

times 3.7 is 3.72 times 3.5 is 7.4..

and so on

The teacher tells you that the 0 times table and the 1 times table are too easy and the program should reject those, but any other value (including negative ones) is OK.

My Solution

This solution works ok, but you get a few inaccuracies with certain values. Changing float to double or decimal would probably solve those issues.

using System;

public class CrazyTables
{
    public static void Main(string[] args)
    {
        if(args.Length != 1)
        {
            Console.WriteLine("Use it like this: ");
            Console.WriteLine("    CrayTables.exe <float>");
            Console.WriteLine("\n<float>: The number to use when generating the times table.");
            return;
        }

        float number = float.Parse(args[0].Trim());

        if(number == 0 || number == 1)
        {
            Console.WriteLine("Invalid times table number.");
            return;
        }

        for(int i = 0; i < 12; i++)
        {
            Console.WriteLine("{0,2} times {1} is {2,2}", i + 1, number, (i + 1) * number);
        }
    }

    public static bool ValidateInput(float number)
    {
        if (number == 0 || number == 1)
            return false;
        else
            return true;
    }
}

(Pastebin, 32 bit binary)

2.2: Scrabble™ Scores

Description

Scrabble™ is a word game. Players take turns to make words out of letter tiles. Each tile has a particular value. Generally, the rarer the letter in words, the higher the value. The tiles have the following values:

  • (1 point)-A, E, I, O, U, L, N, S, T, R
  • (2 points)-D, G
  • (3 points)-B, C, M, P
  • (4points)-F, H, V, W, Y
  • (5 points)-K
  • (8 points)-J, X
  • (10 points)-Q, Z

I want a program that will tell me how much a given word is worth in Scrabble™. Turns out that Rob Miles is worth 12 points, I'd like to be able to find out if anyone else has a name worth more than mine.

My Solution

Another C♯ Dictionary here.

using System;
using System.Collections.Generic;

public class ScrabbleScorer
{
    public static void Main(string[] args)
    {
        if(args.Length != 1)
        {
            Console.WriteLine("Use it like this:");
            Console.WriteLine("    ScrabbleScorer.exe <word>");
            Console.WriteLine("\n<word>: The word to calculate the score for.");
            return;
        }

        Console.WriteLine("'{0}' scores {1} points.", args[0], CalculateWordValue(args[0]));
    }

    public static Dictionary<char, int> wordValues = new Dictionary<char, int>()
    {
        { 'a', 1 }, { 'b', 3 }, { 'c', 3 }, { 'd', 2 }, { 'e', 1 }, { 'f', 4 }, { 'g', 2 }, { 'h', 4 }, { 'i', 1 },
        { 'j', 8 }, { 'k', 5 }, { 'l', 1 }, { 'm', 3 }, { 'n', 1 }, { 'o', 1 }, { 'p', 3 }, { 'q', 10 },{ 'r', 1 },
        { 's', 1 }, { 't', 1 }, { 'u', 1 }, { 'v', 4 }, { 'w', 4 }, { 'x', 8 }, { 'y', 4 }, { 'z', 10 }
    };

    public static int CalculateWordValue(string word)
    {
        word = word.ToLower();
        int totalScore = 0;

        foreach(char ch in word)
        {
            int chScore = 0;
            if(wordValues.TryGetValue(ch, out chScore))
            {
                totalScore += chScore;
            }
        }

        return totalScore;
    }
}

(pastebin, 32 bit binary)

2.3: Scrabble™ Validity Tester

Description

Staying with Scrabble. A standardScrabble&153; set contains the following set of tiles: A-9. B-2. C-2. D-4. E-12. F-2. G-3. H-2. I-9. J-1. K-1. L-4. M-2. N-6. O-8. P-2. Q-1. R-6. S-4. T-6. U-4. V-2.

Plus two blanks which can be assigned any letter when they are played.

For extra bonus points you could improve your program so that it indicates whether or not the word could actually entered during the game. The program could also indicate whether or not a blank tile is required.

My Solution

The problem description is missing some of the tile counts for me, so I am using data from [this website]. I tried to compact the array of tile counts for this one, but it didn't work too well because I ended up writing more code to read the array than I saved by compacting it.....

using System;
using System.Collections.Generic;

class ScrabbleValidator
{
    // from http://scrabblewizard.com/scrabble-tile-distribution/
    // the coding conundrums seems to have a few letter counts missing
    public static string[] letterCounts = new string[]
    {
        "", // 0
        "jkqxz", // 1
        "bcfhmpvwy*", // 2 - * = blank tile
        "g", // 3
        "dlsu", // 4
        "", // 5
        "nrt", // 6
        "", // 7
        "o", // 8
        "ai", // 9
        "", // 10
        "", // 11
        "e", // 12
    };

    public static int blankTileCount = 2;

    static void Main(string[] args)
    {
        if(args.Length != 1)
        {
            Console.WriteLine("This program works out whether a word is a valid scrabble word.");
            Console.WriteLine("Use it like this:");
            Console.WriteLine("    ScrabbleValidator.exe <word>");

            Console.WriteLine("\n<word>: The word you want to validate.");
            return;
        }

        string word = args[0].Trim().ToLower();

        // count the number of each letter in the word
        Dictionary<char, int> letterCounts = new Dictionary<char, int>();
        foreach (char ch in word)
        {
            if (letterCounts.ContainsKey(ch))
            {
                letterCounts[ch] += 1;
            }
            else
            {
                letterCounts.Add(ch, 1);
            }
        }

        // loop over the letter counts and validate the word
        string invalidReasons = "";
        int usedBlanks = 0;
        foreach (KeyValuePair<char, int> letterCount in letterCounts)
        {
            char currentChar = letterCount.Key;
            int currentCharCount = letterCount.Value;
            int maxCharCount = getLetterCount(currentChar);

            if (currentCharCount > maxCharCount)
            {
                if(usedBlanks + (currentCharCount - maxCharCount) <= blankTileCount)
                {
                    usedBlanks += currentCharCount - maxCharCount;
                }
                else
                {
                    invalidReasons += String.Format("The character '{0}' is used {1} times (scrabble has {2} tiles for that letter).\n", currentChar, currentCharCount, maxCharCount);
                }
            }
        }

        if(invalidReasons.Length > 0)
        {
            Console.WriteLine("{0} is not valid. Reasons: ", word);
            Console.WriteLine(invalidReasons);
        }
        else
        {
            Console.WriteLine("{0} is a valid scrabble word.", word);
            Console.WriteLine("It would use {0} blank tiles.", usedBlanks);
        }
    }

    static int getLetterCount(char ch)
    {
        for(int i = 0; i < letterCounts.Length; i++)
        {
            if(letterCounts[i].Contains(Char.ToLower(ch).ToString()))
            {
                return i;
            }
        }
        return 0; // the character wasn't recognised, so there won't be any tiles that match it.
    }
}

(pastebin, 32 bit binary)

Note that I don't have any analytics on this site yet, so the only way I know you have been here at all is through the comments (and the server logs).

Splitting your C♯ Code into Multiple Files 2: DLLs

I have found out about compiling and linking to DLLs. I think this is called Dynamic Linking but again, I could be wrong.

We will be using the example files from last time:

filea.cs:

using System;

class ClassA
{
    public static void Main()
    {
        Console.WriteLine("This is a test from file A");
        Someplace.ClassB.PrintHello();
    }
}

fileb.cs:

using System;

namespace Someplace
{
    public class ClassB
    {
        public static void PrintHello()
        {
            Console.WriteLine("Another hello from file B!");
        }
    }
}

This is a 2 step process. First we need to compile the DLL, then we need to compile the main exe and link to the DLL.

To compile the DLL, you type something like this:

csc /target:library fileb.cs

The important bit here is /target:library. This tells the C♯ compiler to compile your code to a DLL and not and exe.

To compile the main exe, you need to type something like this:

csc /reference:fileb.dll filea.cs

This tells the C♯ compiler to compile the code in filea.cs into an exe, and link it to fileb.dll.

Taken from this MSDN page.

Value vs Reference: A Performance Test

I have recently started to learned about classes and objects in C♯. In one of my lectures, Rob Miles mentioned that passing by reference introduced a slight performance hit, and I decided to test this.

Here is the code I used:

using System;
using System.Diagnostics;

class ValueVsReference
{
    public static void SetValue(int somenumber, int maxi)
    {
        for (int i = 0; i < maxi; i++)
        {
            somenumber = i;
        }
    }

    public static void SetReference(ref int somenumber, int maxi)
    {
        for(int i = 0; i < maxi; i++)
        {
            somenumber = i;
        }
    }

    public static void Main()
    {
        int iterations = 100000;
        int a = 0;
        Console.Write("Iterations: {0} ", iterations);

        Console.Write("Value: ");
        Stopwatch valuetime = new Stopwatch();
        valuetime.Start();
        SetValue(a, iterations);
        valuetime.Stop();
        Console.Write("{0} ", valuetime.Elapsed);

        Console.Write("Reference: ");
        Stopwatch referencetime = new Stopwatch();
        referencetime.Start();
        SetReference(ref a, iterations);
        referencetime.Stop();
        Console.WriteLine(referencetime.Elapsed);
    }
}

(gist: https://gist.github.com/sbrl/b10bf5c765630562431f)

The results for 10,000 iterations can be found in this pastebin.

Average times:

  • Value: 0.0000885
  • Reference: 0.00009295

Final result: References are indeed slower than values, by ~5% (100 - ((0.00009295/0.0000885)*100)). Normally you would not need to worry about this performance drop though since it is so small.

Coding Conundrums 1

This is the 50th post I have written for this blog! (There are a few posts scheduled to be released, so you may not be able to see posts #48 and #49 at the time of this post's release) This is also the first time I am trying to insert a post before two scheduled posts. Hopefully they come out in the right order.

Recently Rob Miles has released the first of a series of problem problems called "Coding Conundrums" with this tagline:

Number one in a series of more than one. Probably.

I have decided to write solutions for these problems and post them here on my blog for you. Each solution comes with it's associated description, a pastebin link, and a link to a compiled 32 bit binary (other types of binary are available, just ask in the comments).

1.1: Sequence Reversal

The challenge:

I want a program that reads in 10 numbers and prints them out in the reverse order to the order they were entered. I've no idea why I want this, I just do.

My solution:

using System;

class Program
{
    public static void Main(string[] args)
    {
        if(args.Length != 10)
        {
            Console.WriteLine("Coding Conundrums Problem 1.1 Solution: Sequence Reversal");
            Console.WriteLine("---------------------------------------------------------");
            Console.WriteLine("Problem Description:");
            Console.WriteLine("    I want a program that reads in 10 numbers and prints them out");
            Console.WriteLine("    in the reverse order to the order they were entered.");
            Console.WriteLine();
            Console.WriteLine("(You entered {0} numbers)", args.Length);
            Console.WriteLine();
            Console.WriteLine("Use it like this: ");
            Console.WriteLine("    sequencereverse.exe 1 2 3 4 5 6 7 8 9 10");

            return;
        }

        int[] numbers = new int[args.Length];
        for(int i = 0; i < args.Length; i++)
        {
            if(!int.TryParse(args[i], out numbers[i]))
            {
                Console.WriteLine("Error: {0} is not a number.", args[i]);
                return;
            }
        }
        Array.Reverse(numbers);

        for(int j = 0; j < numbers.Length; j++)
        {
            Console.Write("{0} ", numbers[j]);
        }
        Console.WriteLine();
    }
}

(Pastebin, 32 bit Binary)

1.2: Number Shuffle

Problem Description:

I want a program that will print outthe numbers 1,2,3,4,5,6,7,8,9 in a shuffled order. The order must be different each time the program runs. Note that the same number must be different each time. It should be possible to extend this to work with 52 numbers, in which case I can make a shuffled deck of cards.

My solution:

using System;

class Program
{
    public static void PrintHelp()
    {
        Console.WriteLine("Coding Conundrums Problem 1.2 Solution: Number Shuffle");
        Console.WriteLine("------------------------------------------------------");
        Console.WriteLine("Problem Description:");
        Console.WriteLine("    I want a program that will print outthe numbers 1,2,3,4,5,6,7,8,9 in a");
        Console.WriteLine("    shuffled order. The order must be different each time the program runs. Note");
        Console.WriteLine("    that the same number must be different each time. It should be possible to");
        Console.WriteLine("    extend this to work with 52 numbers, in which case I can make a shuffled");
        Console.WriteLine("    deck of cards.");
        Console.WriteLine();
        Console.WriteLine("Use it like this: ");
        Console.WriteLine("    numbershuffle.exe <count-to>");
        Console.WriteLine();
        Console.WriteLine("Paramters:");
        Console.WriteLine("    <count-to>: The number to count up to when generating the initial sequence of numbers.");
    }

    public static void Main(string[] args)
    {
        if(args.Length != 1)
        {
            PrintHelp();
            return;
        }

        int numberCount;
        if(!int.TryParse(args[0], out numberCount))
        {
            PrintHelp();
            return;
        }

        int[] numbers = new int[numberCount];
        for(int i = 0; i < numberCount; i++)
        {
            numbers[i] = i + 1;
        }

        int swapsCount = numberCount * 2;
        int temp, a, b;
        Random random = new Random();
        for(int i = 0; i < swapsCount; i++)
        {
            a = random.Next(numbers.Length);
            b = random.Next(numbers.Length);

            temp = numbers[a];
            numbers[a] = numbers[b];
            numbers[b] = temp;
        }

        for(int i = 0; i < numbers.Length; i++)
        {
            Console.Write("{0} ", numbers[i]);
        }
    }
}

(pastebin, 32 bit binary)

1.3: Shoe Popularity Contest

Problem Description:

I want a program that reads in 20 integers and tells me how much of each number was entered. I actually have a use for this, in that each day I sell 20 pairs of shoes and I want to find out the most popular shoe sizes

My solution:

I looked up and used a C♯ Dictionary for this one.

using System;
using System.Collections.Generic;

class Program
{
    public static void PrintHelp()
    {
        Console.WriteLine("Coding Conundrums Problem 1.2 Solution: Number Shuffle");
        Console.WriteLine("------------------------------------------------------");
        Console.WriteLine("Problem Description:");
        Console.WriteLine("    I want a program that reads in 20 integers and tells me how much of each number");
        Console.WriteLine("    was entered. I actually have a use for this, in that each day I sell 20 pairs of");
        Console.WriteLine("    shoes and I want to find out the most popular shoe sizes. It's amazing that I");
        Console.WriteLine("    manage to hold down my lecturing job, what with all the shoe sales I'm involved");
        Console.WriteLine("    with.");
        Console.WriteLine();
        Console.WriteLine("Use it like this: ");
        Console.WriteLine("    shoesales.exe");
    }

    ///<summary>
    ///Gets an integer from the user between min and max inclusive.
    ///</summary>
    ///<param name="prompt">The prompt to display to the user.</param>
    ///<param name="min">The minimum value the user should enter.</param>
    ///<param name="max">The maximum value the user should enter.</param>
    static int ReadNumber(string prompt, int min, int max)
    {
        int number;
        while (true)
        {
            Console.Write(prompt);
            try
            {
                number = int.Parse(Console.ReadLine().Trim());
            }
            catch
            {
                Console.WriteLine("That was not a number. Numbers may contain numeric characters only.");
                continue;
            }

            if (number < min)
            {
                Console.WriteLine("That number was too low. Please enter a number between " + min + " and " + max + ".");
                continue;
            }
            if (number > max)
            {
                Console.WriteLine("That number was too high. Please enter a number between " + min + " and " + max + ".");
                continue;
            }

            break;
        }

        return number;
    }

    public static void PrintShoeSizes(Dictionary<int, int> shoes)
    {
        Console.WriteLine("Shoe Sizes:");
        Console.WriteLine("-----------");
        Console.WriteLine("Size     Count");
        foreach(KeyValuePair<int, int> shoeSize in shoes)
        {
            Console.WriteLine("{0,-8} {1}", shoeSize.Key, shoeSize.Value);
        }
    }

    public static void Main(string[] args)
    {
        if(args.Length == 1 && args[0].ToLower().Trim('-') == "help")
        {
            PrintHelp();
            return;
        }

        int shoeTotal = 20;

        Dictionary<int, int> shoes = new Dictionary<int, int>();
        for(int i = 0; i < shoeTotal; i++)
        {
            PrintShoeSizes(shoes);
            int currentShoeSize = ReadNumber(String.Format("Enter the shoe size #{0}: ", i + 1), 1, 12);

            if(!shoes.ContainsKey(currentShoeSize))
            {
                shoes.Add(currentShoeSize, 1);
            }
            else
            {
                shoes[currentShoeSize] += 1;
            }
        }
    }
}

(pastebin, 32 bit binary)

Reading HTTP 1.1 requests from a real web server in C#

I've received rather a lot of questions recently asking the same question, so I thought that I 'd write a blog post on it. Here's the question:

Why does my network client fail to connect when it is using HTTP/1.1?

I encountered this same problem, and after half an hour of debugging I found the problem: It wasn't failing to connect at all, rather it was failing to read the response from the server. Consider the following program:

using System;
using System.IO;
using System.Net.Sockets;

class Program
{
    static void Main(string[] args)
    {
        TcpClient client = new TcpClient("host.name", 80);
        client.SendTimeout = 3000;
        client.ReceiveTimeout = 3000;
        StreamWriter writer = new StreamWriter(client.GetStream());
        StreamReader reader = new StreamReader(client.GetStream());
        writer.WriteLine("GET /path HTTP/1.1");
        writer.WriteLine("Host: server.name");
        writer.WriteLine();
        writer.Flush();

        string response = reader.ReadToEnd();

        Console.WriteLine("Got Response: '{0}'", response);
    }
}

If you change the hostname and request path, and then compile and run it, you (might) get the following error:

An unhandled exception of type 'System.IO.IOException' occurred in System.dll

Additional information: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time or established connection failed because connected host has failed to respond.

Strange. I'm sure that we sent the request. Let's try reading the response line by line:

string response = string.Empty;
do
{
    string nextLine = reader.ReadLine();
    response += nextLine;
    Console.WriteLine("> {0}", nextLine);
} while (reader.Peek() != -1);

Here's some example output from my server:

> HTTP/1.1 200 OK
> Server: nginx/1.9.10
> Date: Tue, 09 Feb 2016 15:48:31 GMT
> Content-Type: text/html
> Transfer-Encoding: chunked
> Connection: keep-alive
> Vary: Accept-Encoding
> strict-transport-security: max-age=31536000;
>
> 2ef
> <html>
> <head><title>Index of /libraries/</title></head>
> <body bgcolor="white">
> <h1>Index of /libraries/</h1><hr><pre><a href="../">../</a>
> <a href="prism-grammars/">prism-grammars/</a>
   09-Feb-2016 13:56                   -
> <a href="blazy.js">blazy.js</a>                                           09-F
eb-2016 13:38                9750
> <a href="prism.css">prism.css</a>                                          09-
Feb-2016 13:58               11937
> <a href="prism.js">prism.js</a>                                           09-F
eb-2016 13:58               35218
> <a href="smoothscroll.js">smoothscroll.js</a>
   20-Apr-2015 17:01                3240
> </pre><hr></body>
> </html>
>
> 0
>

...but we still get the same error. Why? The reason is that the web server is keeping the connection open, just in case we want to send another request. While this would usually be helpful (say in the case of a web browser - it will probably want to download some images or something after receiving the initial response), it's rather a nuisance for us, since we don't want to send another request and it's rather awkward to detect the end of the response without detecting the end of the stream (that's what the while (reader.Peek() != -1); is for in the example above).

Thankfully, there are a few solutions to this. Firstly, the web server will sometimes (but not always - take the example response above for starters) send a content-length header. This header will tell you how many bytes follow after the double newline (\r\n\r\n) that separate the response headers from the response body. We could use this to detect the end of the message. This is the reccommended way , according to RFC2616.

Another way to cheat here is to send the connection: close header. This instructs the web server to close the connection after sending the message (Note that this will break some of the tests in the ACW, so don't use this method!). Then we can use reader.ReadToEnd() as normal.

A further cheat would be to detect the expected end of the message that we are looking for. For HTML this will practically always be </html>. We can close the connection after we receive this line (although this doesn't work when you're not receiving HTML). This is seriously not a good idea. The HTML could be malformed, and not contain </html>.

Splitting your C♯ Code into Multiple Files

I have just started to work out how to split my C♯ code into multiple files, and thought that I would share it with you. This post will be about what I believe to be static linking, but I could be wrong. Anyway, it is actually quite simple:

Here is the contents of filea.cs:

using System;

class ClassA
{
    public static void Main()
    {
        Console.WriteLine("This is a test from file A");
        Someplace.ClassB.PrintHello();
    }
}

and here is the contents of fileb.cs:

using System;

namespace Someplace
{
    class ClassB
    {
        public static void PrintHello()
        {
            Console.WriteLine("Another hello from file B!");
        }
    }
}

Then when you compile, you should do something like this:

csc filea.cs fileb.cs

This will tell the C Sharp compiler to grab both filea.cs and fileb.cs, and to output a single filea.exe.

Next I will try to figure out how to create a .dll file and include that - then I can build my own libraries.

Dailyprogammer Challenge #199 - Bank Numbers Pt 1

I have attempted another dailyprogammer challenge on reddit.

This time, the challenge is to take a number in and print a 'banner' representing that number, like this:

Input: 47262

Output:
    _  _  _  _
|_|  | _||_  _|
  |  ||_ |_||_

Here is my solution:

using System;

public class BigDigits
{
    static string[,] bannerTemplates = new string[,]{
        { " _ ", "| |", "|_|" },
        { "   ", "  |", "  |" },
        { " _ ", " _|", "|_ " },
        { " _ ", " _|", " _|" },
        { "   ", "|_|", "  |" },
        { " _ ", "|_ ", " _|" },
        { " _ ", "|_ ", "|_|" },
        { " _ ", "  |", "  |" },
        { " _ ", "|_|", "|_|" },
        { " _ ", "|_|", " _|" }
    };

    static void Main(string[] args)
    {
        if (args.Length == 0)
        {
            Console.WriteLine("This program converts a number to a banner.");
            Console.WriteLine("\nUse it like this: ");
            Console.WriteLine("    bigintbanners.exe <number>");
            Console.WriteLine("\n<number>: The number you want to convert.");
            return;
        }

        char[] intChars = args[0].ToCharArray();
        string[] resultLines = new string[3];
        int currentDigit = 0;

        int i = 0;

        for(i = 0; i < intChars.Length; i++)
        {
            currentDigit = int.Parse(intChars[i].ToString());
            for (int j = 0; j < 3; j++)
            {
                resultLines[j] += bannerTemplates[currentDigit,j];
            }
        }

        for(i = 0; i < resultLines.Length; i++)
        {
            Console.WriteLine(resultLines[i]);
        }
    }
}

I find the dailyprogrammer challenges to be a great way to practice a language that you are learning.

32 bit binary, SHA1: 0fc2483dacf151b162e22b3f9b4c5c64e6fe5bdf

Reddit post link

Ask below if you need a different binary (e.g. 64 bit, ARM, etc)

Sorting Algorithms 3 / 5: Insertion Sort

Hello again!

This is the 3rd of 5 sorting algorithms that I will be implementing and posting about.

Today I have a reverse insertion sorter for you.

An (reverse) insertion sort takes number one from the end of the array, and shuffles it along to the right until it is in the right place. Then it picks the next number along and does the same, until the whole array is sorted.

/// <summary>
/// Performs an insertion sort in the array.
/// </summary>
/// <param name="array">A reference to the array to sort.</param>
static void insertion_sort(ref int[] array)
{
    for (int i = array.Length - 2; i >= 0; i--)
    {
        int shp = i;
        //                                                      |
        //make sure that we don't fall off the end of the array V
        while(shp < array.Length - 1 && array[shp] > array[shp + 1]) 
        {
            swap_places(ref array, shp, shp + 1);
            shp++;
        }

        Console.Write("i: {0} ", i);
        print_array(ref array);
    }
}

Here is some example output:

[ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 53, 1, 38, 47, 63, 68, 91, 93 ]
i: 23 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 53, 1, 38, 47, 63, 68, 91, 93 ]
i: 22 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 53, 1, 38, 47, 63, 68, 91, 93 ]
i: 21 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 53, 1, 38, 47, 63, 68, 91, 93 ]
i: 20 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 53, 1, 38, 47, 63, 68, 91, 93 ]
i: 19 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 53, 1, 38, 47, 63, 68, 91, 93 ]
i: 18 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 53, 1, 38, 47, 63, 68, 91, 93 ]
i: 17 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 1, 38, 47, 53, 63, 68, 91, 93 ]
i: 16 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 1, 14, 38, 47, 53, 63, 68, 91, 93 ]
i: 15 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 1, 14, 38, 47, 53, 63, 67, 68, 91, 93 ]
i: 14 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 1, 14, 38, 47, 53, 63, 67, 68, 91, 93, 97 ]
i: 13 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 1, 14, 38, 47, 53, 63, 67, 68, 69, 91, 93, 97 ]
i: 12 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 1, 14, 38, 47, 53, 63, 67, 68, 69, 91, 93, 96, 97 ]
i: 11 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 1, 14, 38, 47, 53, 63, 67, 68, 69, 91, 92, 93, 96, 97 ]
i: 10 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 1, 14, 38, 47, 53, 63, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 9 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 1, 14, 38, 41, 47, 53, 63, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 8 [ 17, 10, 83, 67, 8, 50, 46, 63, 1, 2, 14, 38, 41, 47, 53, 63, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 7 [ 17, 10, 83, 67, 8, 50, 46, 1, 2, 14, 38, 41, 47, 53, 63, 63, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 6 [ 17, 10, 83, 67, 8, 50, 1, 2, 14, 38, 41, 46, 47, 53, 63, 63, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 5 [ 17, 10, 83, 67, 8, 1, 2, 14, 38, 41, 46, 47, 50, 53, 63, 63, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 4 [ 17, 10, 83, 67, 1, 2, 8, 14, 38, 41, 46, 47, 50, 53, 63, 63, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 3 [ 17, 10, 83, 1, 2, 8, 14, 38, 41, 46, 47, 50, 53, 63, 63, 67, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 2 [ 17, 10, 1, 2, 8, 14, 38, 41, 46, 47, 50, 53, 63, 63, 67, 67, 68, 69, 83, 91, 92, 93, 95, 96, 97 ]
i: 1 [ 17, 1, 2, 8, 10, 14, 38, 41, 46, 47, 50, 53, 63, 63, 67, 67, 68, 69, 83, 91, 92, 93, 95, 96, 97 ]
i: 0 [ 1, 2, 8, 10, 14, 17, 38, 41, 46, 47, 50, 53, 63, 63, 67, 67, 68, 69, 83, 91, 92, 93, 95, 96, 97 ]

Full source code (pastebin)

Binary (MD5: 01b2d774c70ce46d8e0641da948bc25e, SHA1: 537ee665162887f629200d8839b108a3e4098d38)

Algorithms 2 / 5: Reverse Selection Sort

It has been a while since I have implemented a sorting algorithm - I should probably have implemented these a little bit earlier than I have done :)

Today I bring you the C sharp version of the selection sort I posted earlier. To mix it up a bit htough this implementation is in reverse.

  1. Find the largest number in the sequence
  2. If it is larger than the number at the end of the array, swap them
  3. Find the next largest number
  4. If it is larger than the next number along from the end of the array, swap them
  5. Repeat steps 3 and 4 until all the numbers have been sorted.

Here is the code:

/// <summary>
/// Performs a selection sort on an array of ints.
/// </summary>
/// <param name="array">The array to sort.</param>
static void selection_sort(ref int[] array)
{
    int limit = array.Length - 1;
    while(limit > 0)
    {
        //find the index with the maximum value
        int max_index = 0; //set the max to the first element in the array
        //don't search the first element in the array, we have already done that on the line above
        for(int i = limit - 1; i > 0; i--)
        {
            if(array[i] > array[max_index])
                max_index = i;
        }
        if(array[max_index] > array[limit])
        {
            //we have found an index with a high value than the current limit
            swap_places(ref array, max_index, limit);
        }

        limit--;
    }
}

Full Source Code (pastebin) Link to binary (MD5: ef5e0f15c9bc181d36b193160e3f8ad9 SHA1: ad49eb97675ca6ec9cc9dfebb63fbe03cfa27534)

Next up: Insertion sorting.

Art by Mythdael