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 Evolved 5: Space Transmissions

A pretty procedurally generaated nebula. Code not written by me! (Banner from here with the seed 64oekm9bi4cg.)

This post is part of a biweekly series of programming problems, targeted at those learning to program using C# at University. The problems will vary in difficulty - some will be rather easy, and some will be quite challenging! Don't worry if you can't solve a problem just yet - come back to it in a few months and it'll seem a lot easier than it did before.

Coding Conundrums Evolved is back for another episode! I can't promise that these will be a regular feature on here due to the amount of time they take to put together, but I had a good idea for another one that I really couldn't turn down :D

The 2 new elligon-class starships, called the Lilai and the Inveinya, are on a joint mission deep in the newly-discovered Tenobulet Nebula. Due to the thickness of the gas clouds surrounding the 2 ships, they are having difficulty communicating, as talking over a video-link is causing the quantum neural-network based interference analysis system is draining all their available power clearing up the incoming data streams.

To combat this, the genius communications officer Mr. Ümafa has devised the Dassma System. The system allows the 2 ships to communicate by sending text-based messages, reducing power usage by sending a quantum coaxial error correction stream in parallel to the actual message stream.

Anyway, Mr. Ümafa needs your help as the newly-hired systems programming engineer, since all the other programmers onboard are busy scratching their heads over a new asymmetric inverse shift register algorithm whilst writing a firmware upgrade for the quadrilateral energy transmission stabilisers to increase their efficiency.

Unfortunately, his dassma system can only transmit messages in short chunks of 128 characters, and he's finding it terribly cumbersome to keep splitting up the long messages that the crew keep asking him to send.

Given a long string as input, write a program that splits the input into multiple chunks that are at most 128 characters long, and outputs each chunk on a separate line.

Helpful Hints

  • Perform every step of the process on paper first.
  • Draw a flowchart of what your program needs to do.
  • If you're having trouble, step through your code line by line and inspect it's state at each point.

Challenge

Mr. Ümafa is impressed with your program, but he's got an additional request or two. Unfortunately, Communications Officer Bramaar of the Iveinya keeps mixing up the different message parts, and he finds it annoying when it splits a message in the middle of a word.

Mr. Ümafa would like you to upgrade your program so that it only splits on spaces, and so that it labels each of the chunks with their number in the sequence.

The solution archive is here. I'll release the password to this challenge in the comments in 2 weeks time.

Coding Conundrums Evolved Series List

A combination of all the banner images form the series so far. Left to right: ep 1, 2, 3, and then finally 4. Since a while ago I didn't have the time to write the next episode of Coding Conundrums Evolved and then I kind of forgot about it (sorry! I really haven't had much time since September this year, and they take ages to write... :-(), I've decided post a series list for the 4 episodes I've posted so far.

Before I forget though, the (long overdue!) password for last episode's solution (#4) is illykin. Remember to attempt the challenge yourself first before looking at my solution! Working out how you'd attempt a problem is just as important as actually writing the solution itself.

With the last password revealed, here's the series list:

While I'm certainly not averse to releasing a new entry in this series, it'll probably have to wait until the end of this year - unless I think of a really good idea that can't wait. Suggestions and ideas are welcome though :-)

Coding Conundrums Evolved 4: Prime Wall Hangings

This post is part of a biweekly series of programming problems, targeted at those learning to program using C# at University. The problems will vary in difficulty - some will be rather easy, and some will be quite challenging! Don't worry if you can't solve a problem just yet - come back to it in a few months and it'll seem a lot easier than it did before.

Welcome to episode 4 of coding conundrums evolved. If you missed the last one, it is all about fiddly fuel and is located here. The password to the archive that contains my solution for it is iveinya, but try solving it on your own first if you haven't already :-). This episode holds a bit of a different challenge for you.

The famous Professor Arkin, discoverer of illykin theory (the technology behind the quadrilateral engine first installed in the Lilai), has recently been recognised and awarded the prestigious Byema Or award. Along with this award comes a place for a statue in the hall of fame at Timiku University on the planet Eiriodin, the most distinguished and renowned University in the galaxy!

Since it's generally considered to be rather important to have an impressive statue (as you'd naturally expect!), Professor Arkin hired only the most skilled craftsmen to create his statue. After having the magnificent statue made and put in the hall, he thinks that there is still something missing.

Professor Arkin, upon hearing about your impressive skills from Chief Engineer Nebrilla, has asked you to write a program that generates a wall hanging to go behind his statue. In his specification for the wall hanging, he wrote this:

The exact nature of the wall hanging is up to you, but I am interested in something particularly impressive looking. The more impressive it looks, the more credits I will pay you for your trouble!

One of the key secrets to my illykin theory is actually prime numbers, so your design should feature them prominently.

(Author's Note: No actual funds will be paid upon completion of this challenge! Post about your creations in the comments and have a virtual cookie instead :D)

Write a program that generates a suitable wall hanging for Professor Arkin. Make sure that you feature prime numbers in your design!

Helpful Hints

  • Plan your design on paper first so that you have something to work towards.
  • There isn't any set solution for this problem (though I will certainly be providing mine in the next episode!).
  • GDI+ is the native drawing library for C#. Make sure you include a reference to System.Drawing.dll if you decide to use it!
  • I've written a simple image generator template here: ImageGenerator.cs. If you have trouble getting started, feel free to use it as a starting point!

Here's what I managed to put together. I'm sure you can do better than I :-)

My creation.

There isn't a challenge for this conundrum this time - though if you want one you could always try and animate your wall hanging (Professor Arkin is considering digital projector-based installations too). As usual the archive for my solution is here, and the password will be released in the next post.

Coding Conundrums Evolved 3: Fiddly Fuel

This post is part of a biweekly series of programming problems, targeted at those learning to program using C# at University. The problems will vary in difficulty - some will be rather easy, and some will be quite challenging! Don't worry if you can't solve a problem just yet - come back to it in a few months and it'll seem a lot easier than it did before.

Rocket engines at NASA. (Above: Some 15 RS-25 rocket engines at NASA. Source: NASA Image and Video Library)

Get ready for 3rd episode of Coding Conundrums Evolved! This time, you've been asked to write some software for a brand new ftl engine.

First though, the password to the last solution is zirros.

It's the year 2252, and the engineers at the Hazuva spacecraft dry dock orbiting the ocean world Eiriodin are busily working away on putting the finishing touches to a brand new elligon class starship. Capable of FTL travel like no other craft before it, the new ship (dubbed the Lilai by the engineers) will be able to take its crew on an unforgettable journey across the stars.

There's a problem though. The Lilai has a brand new engine that was designed from scratch with a quadrilateral fuel regulation valve. As a result, the standard linear fuel balancing agent on the engine's control computer needs to be completely rewritten! Upon hearing the news, Chief Engineer Nebrilla has hired you to do the job.

The engine in question handles fuel through a grid of reactor cells. Oddly enough, the fuel in the reactor cells must be arranged in ratios such that they form a 5x5 magic square.

         
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
         

(Above: An example magic square.)

Write a program that outputs a 5x5 magic square.

Helpful Hints

  • The Siamese method can be used to programatically generate a magic square.
  • Read the description of the algorithm carefully and make sure you understand it before writing any code.
  • Follow the algorithm through on paper first.
  • You may want to take a look at using a 2D array to store information about your magic square.
  • I've written a magic square validator so that you can test your implementation.
    • Use it like this on Windows: type MagicSquare.txt | ./MagicSquareValidator.exe [Order] [MagicNumber]
    • ...or this on Linux: cat MagicSquare.txt | mono ./MagicSquareValidator.exe [Order] [MagicNumber]

Challenge

The new engine design tested in the Lilai was so successful that a second ship, the Iveinya, is going to be retrofitted with a modified version of the engine. This new modified engine takes a 3x3 fuel matrix, which, surprisingly enough, also has to take fuel in ratios that form a magic square.

Since you wrote the control program for the original engine, you've been drafted in to update your program to work with the new engine.

Adjust your program so that it supports generating magic squares of any size.

My solution to this puzzle is here - the password to the archive will be released in the next post.

Find the last post here: Binary Biomass

Coding Conundrums Evolved 2: Binary Biomass

This post is part of a biweekly series of programming problems, targeted at those learning to program using C# at University. The problems will vary in difficulty - some will be rather easy, and some will be quite challenging! Don't worry if you can't solve a problem just yet - come back to it in a few months and it'll seem a lot easier than it did before.

Welcome back to Coding Conundrums Evolved, my take on Rob Miles' original Coding Conundrums series. Last time we built a translator for an alien language. As promised, you can find my solution to that problem here. The password to the archive is eyamporrean. In episode 2, some scientists have made an amazing discovery.

The ISS (Above: The ISS as seen from the Space Shuttle Atlantis when departing from the station.)

The scientists on the Zirros orbital research station have managed to create a brand new species of tree (which they've decided to call the mikoko tree) in their lab that grows in precisely the same way every time, allowing the number of leaves on a tree to be predicted with accuracy months or even years in advance.

Upon hearing about this new discovery, the engineering department of Zirros immediately designed a biomass generators a that runs on the leaves of the mikoko tree, since they have been having issues with the station's solar panels recently.

A mikoko tree growing.

The mikoko starts with a single shoot, which splits into 2 every 9 days. Every time the shoot splits in two, all the previous joints grow a cluster of up to 3 leaves. A joint may not hold more than 3 leaves at once. Incredibly, the mikoko doesn't actually need any of its leaves to grow. It can perform all the photosynthesis it needs to in its branches, apparently. Furthermore, the shoots on the mikoko can be snipped off, at which point the tree ceases to grow any further. In this state it still produces the clusters of leaves every 9 days. The scientists have performed various experiments and come to the conclusion that a single leaf produces 1.5 energy credits when burnt in one of engineering's new biomass generators. The Zirros station, according to engineering, uss 56 energy credits per day.

It is anticipated that once the scientists' paper is released on the mikoko, every station / spaceship / colony within 25 light years will want to power themselves very own mikoko farm. Doing the calculation to work out how big of a tree is needed for each installation is boring and time consuming, and so you've been asked to write a program that will do the calculations needed to work it out automatically.

Given the number of energy credits a station uses per day, write a program that will calculate the day on which a mikoko tree should be snipped such that it will produce enough leaves to produce enough energy to power the station in question. The following stations have already issued requests:

  • Zirros station: 56 credits per day
  • Spaceship Iveinya: 12 credits per day
  • Mining station Kira 4: 304 credits per day
  • Spaceship Aheya: 2 credits per day

Helpful Hints

  • It might help to draw it out on a whiteboard first. Make sure you've got your head around the problem before you start writing code.
  • Don't be afraid to ask questions in the comments if there's something you don't understand! I'll be happy to help you.
  • Make sure that you manually test your program to make sure that it gives the correct output. While your program might work with one input, it might not with another.

Challenge

The scientists have also found that you can plant 5 leaves together, and a new mikoko shoot will grow after 3 days. Alter your program so that it takes this into account when reporting the day that the mikoko trees should be snipped. Make your program also report the days on which leaves should be taken from the existing tree(s) and planted to create new trees.

As per last time, my solution can be found here, and the password will be released with the next challenge.

Update: The next post has been released! Find it here: Fiddly Fuel. The last post was Alien Encounter

Coding Conundrums Evolved 1: Alien Encounter

Banner image. (Banner generated with LC_ALL=C tr -c "[:lower:]" " " < /dev/urandom | dd cbs=$COLUMNS conv=unblock | GREP_COLOR="1;32" grep --color "[^ ]", adapted from here)

This post is part of a new biweekly series of programming problems, targeted at those learning to program using C# at University. The problems will vary in difficulty - some will be rather easy, and some will be quite challenging! Don't worry if you can't solve a problem just yet - come back to it in a few months and it'll seem a lot easier than it did before.

The year is 2258. Humans have established themselves as spacefarers and have made contact with several alien species. You are a member of the esteemed Captain Obanji's crew aboard the spaceship iveinya, on a mission to explore the galaxy! While out exploring, you and your crew discover a new species of intelligent life! You decide to call them the Outer Clockwise Eyamporreans (simply because it sounds cool).

Chief of Communications Officer Bramaar has been analysing the Eyamporreans' language. He has discovered that it is based on the english alphabet (abcdefghijklmnopqrstuvwxyz) managed to work out that he can use a simple substitution cipher to translate the Eyamporreans' language into English. He has also worked out what each letter in their language corresponds to in english:

a b c d e f g h i j k l m n o p q r s t u v w x y z
i u c r a v j w m d q o n b f p l y e t s k z g x h

(abcdefghijklmnopqrstuvwxyz / iucravjwmdqonbfplyetskzgxh)

Unfortunately, he has been having a spot of bother whilst writing an automatic translator for the language. This is where you come in. Given a single line of Eyamporrean through the standard input, translate it into English and output the result. See if you can translate the following alien communications back into english:

jyaatmbje, etyibja cyaitsyae!

za zfsor omqa tf zaocfna xfs tf fsy poibat.

rf xfs wika ibx yfcqat vsao? fsy epicacyvt me ysbbmbj fst.

Helpful Hints

  • The input will only contain the lowercase letters of the alphabet, spaces, and possibly punctuation such as ! and ?.
  • You should pass any characters such as whitespace and punctuation that your program doesn't understand straight through your translator.
  • It never hurts to do a quick .ToLower() call on all the input your program receives, just in case.

Challenge

Officer Bramaar and Captain Obanji are impressed with your work. Using your translator, they have been able to understand the Eyamporreans' messages and ascertain their intentions. Now, they would like to send a message back.

Alter your program so that you can not only translate Eyamporrean messages into english, but also translate English into Eyamporrean.

See if you can translate these messages into Eyamporrean:

hello eyamporreans! we come in peace.

we represent the planet earth.

do you require assistance?

The solution to this puzzle can be found here. The password to the archive will be released along with next week's challenge.

Update: The next post has been released! Find it here: Binary Biomass

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

Art by Mythdael