Last active
October 12, 2022 10:00
-
-
Save savaged/90389e4b94a864118d448e4e72901daa to your computer and use it in GitHub Desktop.
Fizz Buzz
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
// Using top-level statements (see https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/top-level-statements) | |
// and Linq along with pattern matching (see https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/pattern-matching) | |
Enumerable.Range(1, 100).Select( | |
i => | |
(i % 3, i % 5) switch | |
{ | |
(0, 0) => "FizzBuzz", | |
(0, _) => "Fizz", | |
(_, 0) => "Buzz", | |
_ => i.ToString() | |
} | |
).ToList().ForEach(Console.WriteLine); | |
/*************** | |
* boring way... | |
* | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace FizzBuzzCLI | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var intergers = Enumerable.Range(1, 17).ToArray(); | |
var verbs = GetWords(intergers); | |
foreach (var verb in verbs) | |
{ | |
Console.WriteLine(verb); | |
} | |
Console.WriteLine("Done!"); | |
} | |
static string[] GetWords(int[] intergers) | |
{ | |
var verbs = new List<string>(); | |
foreach (var i in intergers) | |
{ | |
verbs.Add(GetWord(i)); | |
} | |
return verbs.ToArray(); | |
} | |
static string GetWord(int i) | |
{ | |
//.Net Core 3+ | |
//var value = (i % 3, i % 5) switch | |
//{ | |
// (0, 0) => "FizzBuzz", | |
// (0, _) => "Fizz", | |
// (_, 0) => "Buzz", | |
// _ => i.ToString() | |
//}; | |
//.Net any version, I think | |
var value = string.Empty; | |
var r = i % 3; | |
if (r == 0) | |
{ | |
value = "Fizz"; | |
} | |
r = i % 5; | |
if (r == 0) | |
{ | |
value += "Buzz"; | |
} | |
if (value == string.Empty) | |
{ | |
value = i.ToString(); | |
} | |
return value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment