Created
May 10, 2014 20:13
-
-
Save MikeMKH/b9e74c1dc21395aef90d to your computer and use it in GitHub Desktop.
Coin Changer kata in C# using LINQ and helper class to make the aggregate more immutable.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace CoinChanger | |
{ | |
public class Changer | |
{ | |
public ICollection<int> Coins { get; set; } | |
public Changer() | |
{ | |
Coins = new List<int>(); | |
} | |
public ICollection<int> For(int amount) | |
{ | |
return Coins.Aggregate( | |
new State(new List<int>(), amount), (working, coin) => | |
{ | |
working.Result.Add(working.Amount/coin); | |
return new State(working.Result, working.Amount%coin); | |
}).Result; | |
} | |
class State | |
{ | |
public ICollection<int> Result { get; set; } | |
public int Amount { get; set; } | |
public State(ICollection<int> result, int amount) | |
{ | |
Result = result; | |
Amount = amount; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also my blog post which goes with this gist.
http://comp-phil.blogspot.com/2014/05/the-form-of-katas.html