Created
June 19, 2020 05:13
-
-
Save jdmallen/71b3244ee5d358b24d757fcf5067c1cb to your computer and use it in GitHub Desktop.
A custom FizzBuzz generator: you select your multiples and keywords, it'll do the rest.
This file contains hidden or 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 System; | |
| using System.Collections.Generic; | |
| using System.Threading.Tasks; | |
| namespace JDMallen.Gists | |
| { | |
| class Program | |
| { | |
| public static async Task Main(string[] args) | |
| { | |
| FizzBuzz(dict:new Dictionary<int, string> | |
| {{3, "Fizz"}, {5, "Buzz"}, {4, "Bop"}, {11, "Boobs"}}); | |
| Console.ReadKey(); | |
| } | |
| /// <summary> | |
| /// Adapted from https://stackoverflow.com/a/3319652/3986790 | |
| /// </summary> | |
| /// <typeparam name="T"></typeparam> | |
| /// <param name="originalSet"></param> | |
| /// <returns></returns> | |
| public static IEnumerable<IEnumerable<T>> CreateSubsets<T>( | |
| IEnumerable<T> originalSet) | |
| { | |
| var subsets = new List<T[]>(); | |
| foreach (var t in originalSet) | |
| { | |
| var subsetCount = subsets.Count; | |
| subsets.Add(new[] {t}); | |
| for (var j = 0; j < subsetCount; j++) | |
| { | |
| var newSubset = new T[subsets[j].Length + 1]; | |
| subsets[j].CopyTo(newSubset, 0); | |
| newSubset[newSubset.Length - 1] = t; | |
| subsets.Add(newSubset); | |
| } | |
| } | |
| return subsets; | |
| } | |
| /// <summary> | |
| /// Custom FizzBuzz generator/printer. | |
| /// </summary> | |
| /// <param name="start"> | |
| /// The start of the range of numbers to print (default: 1). | |
| /// </param> | |
| /// <param name="end"> | |
| /// The end of the range of numbers to print (default: 100). | |
| /// </param> | |
| /// <param name="dict"> | |
| /// Dictionary of int to string defining the multiples and what keyword | |
| /// to print when encountered (default: {3, "Fizz"}, {5, "Buzz"}). | |
| /// </param> | |
| public static void FizzBuzz( | |
| int start = 1, | |
| int end = 100, | |
| IDictionary<int, string> dict = null) | |
| { | |
| dict ??= new Dictionary<int, string> {{3, "Fizz"}, {5, "Buzz"}}; | |
| var allCombinations = CreateSubsets(dict); | |
| for (var i = start; i <= end; i++) | |
| { | |
| var numberString = string.Empty; | |
| var visited = new List<int>(); | |
| foreach (var combination in allCombinations) | |
| { | |
| foreach (var kvp in combination) | |
| { | |
| if (visited.Contains(kvp.Key) || i % kvp.Key != 0) | |
| continue; | |
| numberString += kvp.Value; | |
| visited.Add(kvp.Key); | |
| } | |
| } | |
| Console.WriteLine( | |
| string.IsNullOrEmpty(numberString) | |
| ? i.ToString() | |
| : numberString); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment