Created
February 7, 2017 12:49
-
-
Save MikeMKH/cb34dd03cc6514808947ca095c75e7bb to your computer and use it in GitHub Desktop.
Fibonacci kata in C# using generators with .net core
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.Collections.Generic; | |
using System.Linq; | |
namespace Library | |
{ | |
public static class Fibonacci | |
{ | |
public static int Value(int n) | |
{ | |
return Values(n).Last(); | |
} | |
public static IEnumerable<int> Values(int n) | |
{ | |
var x = 0; | |
var y = 1; | |
yield return x; | |
yield return y; | |
for(var i = 2; i <= n; i++) | |
{ | |
var z = x + y; | |
yield return z; | |
x = y; | |
y = z; | |
} | |
} | |
} | |
} |
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 Xunit; | |
using Library; | |
using System.Linq; | |
namespace Tests | |
{ | |
public class FibonacciTests | |
{ | |
[Theory] | |
[InlineData(1, 1)] | |
[InlineData(2, 1)] | |
[InlineData(3, 2)] | |
[InlineData(4, 3)] | |
[InlineData(14, 377)] | |
[InlineData(20, 6765)] | |
public void GivenValueItMustProduceExpected(int given, int expected) | |
{ | |
var actual = Fibonacci.Value(given); | |
Assert.Equal(expected, actual); | |
} | |
[Fact] | |
public void ValuesMustProduceTheFirst13FibonacciValues() | |
{ | |
var expected = new [] {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144}; | |
var actual = Fibonacci.Values(12); | |
Assert.Equal(expected, actual); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Based on http://geekswithblogs.net/BlackRabbitCoder/archive/2010/04/21/more-fun-with-c-iterators-and-generators.aspx