Code Kata – Coin Change Problem
Remember the old problem you had to tackle when you were first learning to program, where you had to output how many of each coin denomination made up a given value? I thought I’d tackle it using Linq to see how it might look in modern C#.
Here’s my first attempt:
var coins = new[] { 1, 2, 5, 10, 20, 50, 100 }; var amount = 3347; var solution = coins .OrderByDescending(c => c) .TakeWhile(_ => amount > 0) .Select(c => new { Coin = c, Number = amount / c, Remainder = (amount %= c) }) .Where(i => i.Number > 0); foreach (var i in solution) { Console.WriteLine("{0} x {1}c", i.Number, i.Coin); }
This uses OrderByDescending so that the coins don’t need to be defined in any particular order, and reduces the “amount” each time inside the assignment to the “Remainder” property.
What do you think? It’s interesting, tackling these age-old problems with fresh approaches. If you search for “code kata” you’ll find many people writing modern code to do things like finding prime numbers etc. I haven’t seen this particular problem being attacked (perhaps because it’s so simple). If you have a better way to do it, let me know in a comment or a post of your own.
Comments
# Nigel Spencer
14/01/2010 12:09 PM
Hi Matt - I enjoyed reading this post - had to break out LinqPad to give it a test though :-p - and no, I didn't manage to think of a better way.
# Joe
8/01/2013 9:39 AM
you should never use a lambda with side effects in a LINQ query