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

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)

Art by Mythdael