using System.Linq;
public static class Raindrops
{
private static readonly (int, string)[] drips = { (3, "Pling"), (5, "Plang"), (7, "Plong") };
public static string Convert(int number)
{
var drops = drips.Aggregate("", (acc, drop) => number % drop.Item1 == 0 ? acc + drop.Item2 : acc);
return drops.Length > 0 ? drops : number.ToString();
}
}
- This solution begins by defining an array of tuples.
Each tuple has an
intand astring. - The LINQ method Aggregate is called on the
dripsarray. It passes the accumulator, which starts as an empty string, and each tuple to a lambda expression. The lambda expression uses a ternary operator to test ifnumberis evenly divisible by theintin the tuple. If so, it returns the accumulatorstringconcatenated with thestringin the tuple. Ifnumberis not evenly divisble by theintin the tuple, it simply returns the accumulatorstring. - The result of all the iterations of
Aggregateis the value of the accumulatorstring. That value is set to thedropsstring. - A ternary operator is used to test the
dropsstring. If the length ofdropsis greater than0, thendropsis returned from the function. Otherwisenumber.ToString()is returned from the function.
4th Sep 2024
·
Found it useful?