Starbeamrainbowlabs

Stardust
Blog


Archive

Mailing List Articles Atom Feed Comments Atom Feed Twitter

Tag Cloud

3d account algorithms announcement archives arduino artificial intelligence assembly async audio bash batch blog bookmarklet booting c sharp c++ challenge chrome os code codepen coding conundrums coding conundrums evolved command line compiling css dailyprogrammer debugging demystification distributed computing downtime embedded systems encryption es6 features event experiment external first impressions future game github github gist graphics hardware hardware meetup holiday html html5 html5 canvas interfaces internet io.js jabber javascript js bin labs learning library linux low level lua maintenance network networking node.js operating systems performance photos php pixelbot portable privacy programming problems project projects prolog protocol protocols pseudo 3d python reddit reference release releases resource review rust secrets security series list server software sorting source code control statistics svg technical terminal textures three thing game three.js tool tutorial tutorials twitter ubuntu university update updates upgrade version control visual web website windows windows 10 xmpp

Coding Conundrums Series List

I was just looking through my blog's archive, and I found a series of posts I made that solve Rob Miles' Coding Condundrums that he posted on his Python Site. Since I seem to have forgotten to post a series list (it's likely that I finished the series before I thought of such a thing!), I thought that it's better late than never, so here's a series list of all the problems I've solved:

If all goes to plan, I might start a new (possibly related!) series around the end of September.

Coding Conundrums 3

Number three in a series of more than two. But probably less than a thousand.

I have finished my solutions to Rob Miles' Coding Conundrums. If you want to complete them yourself before looking at my solutions, take a look at the pdf.

My solutions share quite a few functions, perhaps I should look into writing a library for them.

3.1: Total Carp

People keep coming to me and bragging about the fish that they just caught. They tell me the make of the fish, "Carp" for example, and how much it weighed, 2000 grams for example.

I want a program into which I can type:

  • The name of each latest fish
  • The weight of each latest fish
  • When I enter a fish called "Finished" (fish pun alert) I want the program to print out:

  • The heaviest fish(name and weight)
  • The lightest fish(name and weight)
  • The total weight of all the fish that have been entered

My solution uses structs - do you remember these from semester 1?

using System;
using System.Collections.Generic;

public class Program
{
    public struct Fish
    {
        public string Name;
        public int Weight;

        public Fish(string inName, int inWeight)
        {
            Name = inName;
            Weight = inWeight;
        }

        public override string ToString()
        {
            return String.Format("{0} at {1}g", Name, Weight);
        }
    }

    public static List<Fish> FishList = new List<Fish>();

    public static int totalWeight;

    public static void Main(string[] args)
    {
        int i = 1;
        while(true)
        {
            string inFishName = ReadString(String.Format("Enter fish {0}'s name: ", i));

            if(inFishName.ToLower() == "finished")
                break;

            int inFishWeight = ReadNumber(String.Format("Enter fish {0}'s weight (in grams): ", i));

            FishList.Add(new Fish(inFishName, inFishWeight));

            Console.WriteLine("Fish added.");
        }

        /// calculate the statistics ///
        // variable declaration
        Fish heaviestFish = FishList[0];
        Fish lightestFish = FishList[0];

        foreach(Fish currentFish in FishList)
        {
            if (currentFish.Weight > heaviestFish.Weight)
                heaviestFish = currentFish;
            if (currentFish.Weight < lightestFish.Weight)
                lightestFish = currentFish;

            totalWeight += currentFish.Weight;
        }

        // Print out the statistics calculated above
        Console.WriteLine("Total weight: {0}", totalWeight);
        Console.WriteLine("Heaviest fish: {0}", heaviestFish.ToString());
        Console.WriteLine("Lightest fish: {0}", lightestFish.ToString());
    }

    /// <summary>
    /// Reads a string in from the user.
    /// </summary>
    /// <param name="prompt">The prompt to display</param>
    /// <param name="minlength">The minimum length of the input the user enters.</param>
    /// <returns>The string the user entered.</returns>
    public static string ReadString(string prompt, int minlength = 1)
    {
        while(true)
        {
            Console.Write(prompt);
            string line = Console.ReadLine();
            if(line.Length < minlength)
            {
                Console.WriteLine("Please enter something that is at least {0} characters.");
                continue;
            }

            return line;
        }
    }

    /// <summary>
    /// Reads a number from the user.
    /// </summary>
    /// <remarks>Depends on ReadString()</remarks>
    /// <param name="prompt">The prompt to display to the user.</param>
    /// <returns>The number that the user entered</returns>
    public static int ReadNumber(string prompt)
    {
        while(true)
        {
            string line = ReadString(prompt).Trim();
            try {
                return int.Parse(line);
            }
            catch
            {
                Console.WriteLine("Sorry, that was not a valid number.");
            }
        }
    }
}

(Pastebin, 32 bit binary)

3.2: Fish Popularity Contest

It occurs to me that it would be useful to add another feature to the fish program above. I'd like to know which is the most popular fish. That way I can buy shares in it. Or something. So I've added the following extra requirement:

  • The most popular fish (i.e. the fish that we have seen the most of)

Note that my keyboard skills are not very gud. And so if I type CArp rather than Carp I'd like the program to behave sensibly and count them both as the same make of fish.

The addition of another List to the loop at the end of the program and a few extra bits and pieces yields FishListPlus:

using System;
using System.Collections.Generic;

public class Program
{
    public struct Fish
    {
        public string Name;
        public int Weight;

        public Fish(string inName, int inWeight)
        {
            Name = inName;
            Weight = inWeight;
        }

        public override string ToString()
        {
            return String.Format("{0} at {1}g", Name, Weight);
        }
    }

    public static List<Fish> FishList = new List<Fish>();

    public static int totalWeight;

    public static void Main(string[] args)
    {
        int i = 1;
        while(true)
        {
            string inFishName = ReadString(String.Format("Enter fish {0}'s name: ", i));

            if(inFishName.ToLower() == "finished")
                break;

            int inFishWeight = ReadNumber(String.Format("Enter fish {0}'s weight (in grams): ", i));

            FishList.Add(new Fish(inFishName, inFishWeight));

            Console.WriteLine("Fish added.");
        }

        /// calculate the statistics ///
        // variable declaration
        Fish heaviestFish = FishList[0];
        Fish lightestFish = FishList[0];

        Dictionary<string, int> PopularFish = new Dictionary<string, int>();

        foreach(Fish currentFish in FishList)
        {
            if (currentFish.Weight > heaviestFish.Weight)
                heaviestFish = currentFish;
            if (currentFish.Weight < lightestFish.Weight)
                lightestFish = currentFish;

            totalWeight += currentFish.Weight;

            int CurrentFishCount;
            if(PopularFish.TryGetValue(currentFish.Name.ToLower(), out CurrentFishCount))
            {
                PopularFish[currentFish.Name.ToLower()]++;
            }
            else
            {
                PopularFish[currentFish.Name.ToLower()] = 1;
            }
        }

        // Print out the statistics calculated above
        Console.WriteLine(" ----------------------------- ");
        Console.WriteLine("| {0,-12} | {1,12} |", "Name", "Count");
        Console.WriteLine("|--------------|--------------|");
        foreach(KeyValuePair<string, int> FishCount in PopularFish)
        {
            Console.WriteLine("| {0,-12} | {1,12} |", FishCount.Key, FishCount.Value);
        }
        Console.WriteLine(" ----------------------------- ");

        Console.WriteLine("Total weight: {0}", totalWeight);
        Console.WriteLine("Heaviest fish: {0}", heaviestFish.ToString());
        Console.WriteLine("Lightest fish: {0}", lightestFish.ToString());
    }

    /// <summary>
    /// Reads a string in from the user.
    /// </summary>
    /// <param name="prompt">The prompt to display</param>
    /// <param name="minlength">The minimum length of the input the user enters.</param>
    /// <returns>The string the user entered.</returns>
    public static string ReadString(string prompt, int minlength = 1)
    {
        while(true)
        {
            Console.Write(prompt);
            string line = Console.ReadLine();
            if(line.Length < minlength)
            {
                Console.WriteLine("Please enter something that is at least {0} characters.");
                continue;
            }

            return line;
        }
    }

    /// <summary>
    /// Reads a number from the user.
    /// </summary>
    /// <remarks>Depends on ReadString()</remarks>
    /// <param name="prompt">The prompt to display to the user.</param>
    /// <returns>The number that the user entered</returns>
    public static int ReadNumber(string prompt)
    {
        while(true)
        {
            string line = ReadString(prompt).Trim();
            try {
                return int.Parse(line);
            }
            catch
            {
                Console.WriteLine("Sorry, that was not a valid number.");
            }
        }
    }
}

(Pastebin, 32 bit binary)

3.3: Ingredients Tracker

Talking of food, I want something to keep track of ingredients that I might have in my kitchen. My program will have two modes:

  1. The program will start in this mode. I can enter the name and amount of each ingredient. If I type in the name "Search" the program will go into mode 2 (see below).
  2. I can type the name of an ingredient and the program will tell me how much of that ingredient I have in stock. If I type in the name "Enter" the program will go into mode 1 (see above)

If you fancy getting clever, you can add a third command, "List", which will list out all the ingredients that have been entered.This is making me quite hungry.

I think I’ll go off for a pie while you work on these.

I decided to use a dictionary for this one, which holds the amount of each item as an int, with the name as the key. Since you can't have duplicate keys, I ask the user if they type in the same key more than once whether they do actually want to overwrite their previous entry.

using System;
using System.Collections.Generic;

public class Program
{
    public enum Mode
    {
        DataEntry,
        Search
    }

    public static Mode CurrentMode = Mode.DataEntry;

    static Dictionary<string, int> Stock = new Dictionary<string, int>();

    public static void Main()
    {
        Console.WriteLine("Kitechen Tracker v0.2");
        Console.WriteLine("---------------------");
        Console.WriteLine("Coding Conundrum 3.3, challenge set by Rob Miles, conquered by Starbeamrainbowlabs");
        Console.WriteLine("Enter the special name 'search' to switch to search mode");
        Console.WriteLine("Enter the special name 'enter' to switch back to data entry mode");
        Console.WriteLine("Enter the special name 'list' at any time to view the current stock");
        Console.WriteLine();
        while(true)
        {
            switch (CurrentMode)
            {
                case Mode.DataEntry:
                    string inName = ReadString("Enter the name of the next ingredient: ").Trim().ToLower();
                    switch(inName)
                    {
                        case "search":
                            Console.WriteLine("Switching to search mode.");
                            CurrentMode = Mode.Search;
                            continue;

                        case "list":
                            ListStock();
                            continue;

                        default:
                            int inAmount = ReadNumber("Enter the amount: ");
                            int currentAmount;
                            if(Stock.TryGetValue(inName, out currentAmount))
                            {
                                if(!Confirm(String.Format("There is already an entry for {0} (with an amount of {1}). Do you want to overwrite it? (y / n)", inName, currentAmount)))
                                {
                                    continue;
                                }
                            }
                            Console.WriteLine("{0} has been added to the list.", inName);
                            Stock[inName] = inAmount;
                            break;
                    }
                    break;

                case Mode.Search:
                    string searchString = ReadString("Enter ingredient name: ").Trim().ToLower();
                    switch(searchString)
                    {
                        case "enter":
                            Console.WriteLine("Switching to data entry mode");
                            CurrentMode = Mode.DataEntry;
                            continue;

                        case "list":
                            ListStock();
                            continue;

                        default:
                            int amountInStock;
                            if(Stock.TryGetValue(searchString, out amountInStock))
                            {
                                Console.WriteLine("Amount of {0}: {1}", searchString, amountInStock);
                            }
                            else
                            {
                                Console.WriteLine("There isn't anything called {0} in stock at the moment.", searchString);
                            }
                            break;
                    }
                    break;
            }
        }
    }

    public static void ListStock()
    {
        Console.WriteLine("Current Stock:");
        foreach(KeyValuePair<string, int> Ingredient in Stock)
        {
            Console.WriteLine("{0,-12}: {1}", Ingredient.Key, Ingredient.Value);
        }
    }

    /// <summary>
    /// Asks the user a simple yes / no question.
    /// </summary>
    /// <param name="prompt">The prompt to display</param>
    /// <returns>The user's choice as a boolean</returns>
    public static bool Confirm(string prompt)
    {
        Console.WriteLine(prompt);
        while(true)
        {
            ConsoleKeyInfo nextChar = Console.ReadKey(true);
            switch(nextChar.Key.ToString().ToLower())
            {
                case "y":
                    return true;
                case "n":
                    return false;
            }
        }
    }

    /// <summary>
    /// Reads a string in from the user.
    /// </summary>
    /// <param name="prompt">The prompt to display</param>
    /// <param name="minlength">The minimum length of the input the user enters.</param>
    /// <returns>The string the user entered.</returns>
    public static string ReadString(string prompt, int minlength = 1)
    {
        while (true)
        {
            Console.Write(prompt);
            string line = Console.ReadLine();
            if (line.Length < minlength)
            {
                Console.WriteLine("Please enter something that is at least {0} characters.");
                continue;
            }

            return line;
        }
    }

    /// <summary>
    /// Reads a number from the user.
    /// </summary>
    /// <remarks>Depends on ReadString()</remarks>
    /// <param name="prompt">The prompt to display to the user.</param>
    /// <returns>The number that the user entered</returns>
    public static int ReadNumber(string prompt)
    {
        while (true)
        {
            string line = ReadString(prompt).Trim();
            try
            {
                return int.Parse(line);
            }
            catch
            {
                Console.WriteLine("Sorry, that was not a valid number.");
            }
        }
    }
}

(Pastebin, 32 bit binary)

New Coding Conundrums

I have just discovered that the Coding Conundrums 3 has been released by Rob Miles on his Python Site. He hasn't put it up on the Coding Sharepoint site yet, so I thought that I would post about it here since I didn't notice until now.

Link to PDF: Coding Conundrums 3

Edit: I will be posting my solutions to the new set of Coding Conundrums just ass soon as I have completed them :)

Edit 2: They are up on the sharepoint site now.

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).

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