Skip to content

Instantly share code, notes, and snippets.

@craigtp
Last active October 8, 2015 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigtp/3323945 to your computer and use it in GitHub Desktop.
Save craigtp/3323945 to your computer and use it in GitHub Desktop.
FizzBuzz - 3 ways
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace FizzBuzz
{
class Program
{
static void Main(string[] args)
{
/*
* Write a program that prints the numbers from 1 to 100.
* But for multiples of three print "Fizz" instead of the number
* and for the multiples of five print "Buzz".
* For numbers which are multiples of both three and five print "FizzBuzz".
*/
// This is the "classic" solution to the FizzBuzz problem.
for (int i = 1; i <= 100; i++)
{
if (i % 3 == 0 && i % 5 == 0)
{
Console.WriteLine("FizzBuzz");
}
else if (i % 3 == 0)
{
Console.WriteLine("Fizz");
}
else if (i % 5 == 0)
{
Console.WriteLine("Buzz");
}
else
{
Console.WriteLine(i.ToString());
}
}
// Wait for the user to hit "Enter" after displaying the list above.
Console.ReadLine();
// This is a "contemporary" solution to the FizzBuzz problem using LINQ.
Enumerable.Range(1, 100).ToList().ForEach(n => Console.WriteLine((n % 3 == 0) ? (n % 5 == 0) ? "FizzBuzz" : "Fizz" : (n % 5 == 0) ? "Buzz" : n.ToString()));
// Wait for the user to hit "Enter" after displaying the list above.
Console.ReadLine();
// Extensible FizzBuzz!
Dictionary<Func<int, bool>, Func<int, string>> rules = new Dictionary<Func<int, bool>, Func<int, string>>();
rules.Add(x => x % 3 == 0, x => "fizz");
rules.Add(x => x % 5 == 0, x => "buzz");
rules.Add(x => x % 5 != 0 && x % 3 != 0, x => x.ToString());
rules.Add(x => true, x => "\n");
var output = from n in Enumerable.Range(1, 100)
from f in rules
where f.Key(n)
select f.Value(n);
output.ToList().ForEach(x => Console.Write(x));
// Wait for the user to hit "Enter" after displaying the list above.
Console.ReadLine();
// Exit from the application.
Environment.Exit(0);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment