Created
September 19, 2017 11:43
-
-
Save MikeMKH/1470952ea403501918951681856e5ea5 to your computer and use it in GitHub Desktop.
Greed kata in C# using the specification pattern along with the factory pattern
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; | |
namespace library | |
{ | |
public class Greed | |
{ | |
public static int Calculate(int [] dice) | |
{ | |
return dice | |
.GroupBy(x => x) | |
.Select(g => new {number = g.Key, count = g.Count()}) | |
.Aggregate(0, (m, g) => | |
m + SpecificationFactory | |
.GetInstance(g.number) | |
.Score(g.count)); | |
} | |
} | |
public class SpecificationFactory | |
{ | |
public static ISpecification GetInstance(int number) | |
{ | |
switch(number) | |
{ | |
case 1: | |
return new Special(1000, 100); | |
case 5: | |
return new Special(500, 50); | |
default: | |
return new Other(number); | |
}; | |
} | |
} | |
public interface ISpecification | |
{ | |
int Score(int count); | |
} | |
public class Special : ISpecification | |
{ | |
private readonly int _triple; | |
private readonly int _single; | |
public Special(int triple, int single) | |
{ | |
this._triple = triple; | |
this._single = single; | |
} | |
public int Score(int count) => | |
(count == 3) ? _triple : (count * _single); | |
} | |
public class Other : ISpecification | |
{ | |
private readonly int _number; | |
public Other(int number) => | |
this._number = number; | |
public int Score(int count) => | |
(count == 3) ? _number * 100 : 0; | |
} | |
} |
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 Xunit; | |
using library; | |
using System.Linq; | |
namespace test | |
{ | |
public class GreedTests | |
{ | |
[Theory] | |
[InlineData(new [] {1, 2, 3, 4, 6}, 100)] | |
[InlineData(new [] {5, 2, 3, 4, 6}, 50)] | |
[InlineData(new [] {5, 2, 3, 5, 6}, 100)] | |
[InlineData(new [] {2, 2, 3, 4, 6}, 0)] | |
[InlineData(new [] {2, 2, 2, 4, 6}, 200)] | |
[InlineData(new [] {3, 4, 5, 3, 3}, 350)] | |
[InlineData(new [] {1, 4, 1, 1, 3}, 1000)] | |
[InlineData(new [] {1, 4, 1, 5, 3}, 250)] | |
[InlineData(new [] {6, 4, 5, 5, 5}, 500)] | |
public void GivenRollMustTotalToExpected( | |
int[] given, int expected) | |
{ | |
var actual = Greed.Calculate(given); | |
Assert.Equal(expected, actual); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment