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
int
and astring
. - The LINQ method Aggregate is called on the
drips
array. 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 ifnumber
is evenly divisible by theint
in the tuple. If so, it returns the accumulatorstring
concatenated with thestring
in the tuple. Ifnumber
is not evenly divisble by theint
in the tuple, it simply returns the accumulatorstring
. - The result of all the iterations of
Aggregate
is the value of the accumulatorstring
. That value is set to thedrops
string
. - A ternary operator is used to test the
drops
string
. If the length ofdrops
is greater than0
, thendrops
is returned from the function. Otherwisenumber
.ToString()
is returned from the function.
11th Dec 2024
·
Found it useful?