Tuesday, 23 October 2012

FizzBuzz generators

SQL

WITH mil AS (
 SELECT TOP 1000000 ROW_NUMBER() OVER ( ORDER BY c.column_id ) [n]
 FROM master.sys.all_columns as c
 CROSS JOIN master.sys.all_columns as c2
)                
 SELECT CASE WHEN n  % 3 = 0 THEN
             CASE WHEN n  % 5 = 0 THEN 'FizzBuzz' ELSE 'Fizz' END
        WHEN n % 5 = 0 THEN 'Buzz'
        ELSE CAST(n AS char(6))
     END + CHAR(13)
 FROM mil

C#

foreach (int number in Enumerable.Range(1, 100))
{
    bool isDivisibleBy3 = (number % 3) == 0;
    bool isDivisibleBy5 = (number % 5) == 0;

    if (isDivisibleBy3)
         Console.Write("Fizz");

    if (isDivisibleBy5)
         Console.Write("Buzz");

    if (!isDivisibleBy3 && !isDivisibleBy5)
         Console.Write(number);

    Console.WriteLine();
}

C# linq

 Enumerable
  .Range(1, 100)
  .Select(i =>
    i % 15 == 0 ? "FizzBuzz" :
    i % 5 == 0 ? "Buzz" :
    i % 3 == 0 ? "Fizz" :
    i.ToString())
  .ToList()
  .ForEach(s => Console.WriteLine(s));