คำนวณค่า Fibonacci แบบไม่ recursive แต่ใช้ IEnumerable เพื่อให้เรียกใช้ด้วย foreach ได้
FibonacciGenerator.cs
using System.Collections.Generic;
namespace ConsoleApp1
{
class FibonacciGenerator
{
private Dictionary<int, int> _cache = new Dictionary<int, int>();
private int Fib(int n) => n < 2 ? n : FibValue(n - 1) + FibValue(n - 2);
private int FibValue(int n)
{
if (!_cache.ContainsKey(n))
{
_cache.Add(n, Fib(n));
}
return _cache[n];
}
public IEnumerable<int> Generate(int n)
{
for (int i = 0; i < n; i++)
{
yield return FibValue(i);
}
}
}
}
บรรทัดที่ 7 เก็บ _cache เป็น Dictionary คือเป็น key, value
บรรทัดที่ 9 ถ้าเป็น .Net เวอร์ชันเก่าๆ ให้แก้ฟังก์ชัน Fib() เป็นดังนี้
private int Fib(int n)
{
return (n < 2) ? n : FibValue(n - 1) + FibValue(n - 2);
}
บรรทัดที่ 21 IEnumerable คือการไล่ (การทำ foreach) ตัวแปรประเภท IEnumerable ก็คือตัวแปรที่สามารถไล่ได้นั่นเอง โดยทุกครั้งที่ไล่ 1 รอบมันจะวิ่งไปจนกว่าจะเจอ yield return อันถัดไป เสริมความเข้าใจเรื่อง IEnumerable/IEnumerator
Program.cs
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var generator = new FibonacciGenerator();
foreach (var digit in generator.Generate(15))
{
Console.WriteLine(digit);
}
}
}
}
ผลการรัน
> dotnet run 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377