Created
March 29, 2025 08:36
-
-
Save einarwh/198ad0c68b0c9eb6f012c1d7fbe72969 to your computer and use it in GitHub Desktop.
FizzBuzz using nodes in a circle.
This file contains 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
namespace FizzBuzzCircular; | |
using System.Collections; | |
using System.Collections.Generic; | |
class Program | |
{ | |
public class Node | |
{ | |
private readonly Func<string> _fn; | |
private Node _next; | |
public Node(Func<string> fn) | |
{ | |
_fn = fn; | |
} | |
public Func<string> Value => _fn; | |
public Node Next => _next; | |
public Node Chain(Node next) | |
{ | |
_next = next; | |
return next; | |
} | |
} | |
public class FizzBuzzEnumerable : IEnumerable<string> | |
{ | |
public IEnumerator<string> GetEnumerator() | |
{ | |
return new FizzBuzzEnumerator(); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return GetEnumerator(); | |
} | |
} | |
public class Numberator : IEnumerator<int> | |
{ | |
private int _n; | |
public bool MoveNext() | |
{ | |
++_n; | |
return true; | |
} | |
public int Current => _n; | |
object IEnumerator.Current | |
{ | |
get { return Current; } | |
} | |
public void Dispose() {} | |
public void Reset() {} | |
} | |
public class FizzBuzzEnumerator : IEnumerator<string> | |
{ | |
private Numberator _numberator; | |
private Node _node; | |
public FizzBuzzEnumerator() | |
{ | |
_numberator = new Numberator(); | |
var number = () => _numberator.Current.ToString(); | |
var fizz = () => "Fizz"; | |
var buzz = () => "Buzz"; | |
var fizzBuzz = () => "Fizz Buzz"; | |
_node = new Node(fizzBuzz); | |
_node | |
.Chain(new Node(number)) | |
.Chain(new Node(number)) | |
.Chain(new Node(fizz)) | |
.Chain(new Node(number)) | |
.Chain(new Node(buzz)) | |
.Chain(new Node(fizz)) | |
.Chain(new Node(number)) | |
.Chain(new Node(number)) | |
.Chain(new Node(fizz)) | |
.Chain(new Node(buzz)) | |
.Chain(new Node(number)) | |
.Chain(new Node(fizz)) | |
.Chain(new Node(number)) | |
.Chain(new Node(number)) | |
.Chain(_node); | |
} | |
public bool MoveNext() | |
{ | |
_numberator.MoveNext(); | |
_node = _node.Next; | |
return true; | |
} | |
public string Current => _node.Value(); | |
object IEnumerator.Current | |
{ | |
get { return Current; } | |
} | |
public void Dispose() {} | |
public void Reset() {} | |
} | |
static void Main(string[] args) | |
{ | |
foreach (var s in new FizzBuzzEnumerable().Take(int.Parse(args[0]))) | |
{ | |
Console.WriteLine(s); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment