Skip to content

Instantly share code, notes, and snippets.

@MikeMKH
Created February 7, 2017 12:49
Show Gist options
  • Save MikeMKH/cb34dd03cc6514808947ca095c75e7bb to your computer and use it in GitHub Desktop.
Save MikeMKH/cb34dd03cc6514808947ca095c75e7bb to your computer and use it in GitHub Desktop.
Fibonacci kata in C# using generators with .net core
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;
}
}
}
}
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