普通の FizzBuzz


FizzBuzz 問題を普通に C# で書いただけという何の面白味もないエントリーです。

using System;
using System.Linq;
using System.Text;

class Program
{
   static void Main()
   {
      var fb = new Fizz(new Buzz(FallThrough.Instance));
      var answer = Enumerable.Range(1, 100).Select(fb.FizzBuzz);
      Console.WriteLine(string.Join(" ", answer));
   }
}

public abstract class FizzBuzzBase
{
   private readonly FizzBuzzBase next;

   protected FizzBuzzBase(FizzBuzzBase next)
   {
      this.next = next;
   }

   public String FizzBuzz(int n)
   {
      var builder = new StringBuilder();
      for (var current = this; current != null; current = current.next)
      {
         current.Resolve(n, builder);
      }
      return builder.ToString();
   }

   protected abstract void Resolve(int n, StringBuilder builder); 
}

public class FallThrough : FizzBuzzBase
{
   public static readonly FallThrough Instance = new FallThrough();

   private FallThrough()
      : base(null)
   {
   }

   protected override void Resolve(int n, StringBuilder builder)
   {
      if (builder.Length == 0)
      {
         builder.Append(n);
      }
   }
}

public class Fizz : FizzBuzzBase
{
   public Fizz(FizzBuzzBase next)
      : base(next)
   {
   }

   protected override void Resolve(int n, StringBuilder builder)
   {
      if (n % 3 == 0)
      {
         builder.Append("Fizz");
      }
   }
}

public class Buzz : FizzBuzzBase
{
   public Buzz(FizzBuzzBase next)
      : base(next)
   {
   }

   protected override void Resolve(int n, StringBuilder builder)
   {
      if (n % 5 == 0)
      {
         builder.Append("Buzz");
      }
   }
}

更新履歴

  • [2011-10-21 00:45] do-while 文を for 文に書き換え。