Visit the raindrops exercise on Exercism to read the full instructions and download the exercise files.
Dig Deeper
if statements
Using if statements
function Raindrops() {
[CmdletBinding()]
Param(
[int]$Number
)
$sounds = ""
if ($Number % 3 -eq 0) {$sounds += "Pling"}
if ($Number % 5 -eq 0) {$sounds += "Plang"}
if ($Number % 7 -eq 0) {$sounds += "Plong"}
$sounds.Length -eq 0 ? "$Number" : $sounds
}
A very standard approach to solve the exercise.
Using if statements to test divisibility of the input vs 3, 5 and 7.
If the test turn out to be true, then the result got concatenated with the designated string.
if ($Number % 3 -eq 0) {$sounds += "Pling"}
if ($Number % 5 -eq 0) {$sounds += "Plang"}
if ($Number % 7 -eq 0) {$sounds += "Plong"}
If none of the tests triggered to be true, then the result string stay empty.
The final ternary operation test if the result string to be empty, if so it would return the original input number as a string.
$sounds.Length -eq 0 ? "$Number" : $sounds
If statement.
switch statement
Using switch statement
function Raindrops() {
[CmdletBinding()]
Param(
[int]$Number
)
$sounds = switch (0) {
($Number % 3) {"Pling"}
($Number % 5) {"Plang"}
($Number % 7) {"Plong"}
Default {$Number}
}
-join $sounds
}
This approach is similar to the if statements.
The value 0 is used to match if the input number is divisible for 3, 5 and 7.
$sounds = switch (0){
($Number % 3) {"Pling"}
($Number % 5) {"Plang"}
($Number % 7) {"Plong"}
}
And if none of those conditions are true, the default value will be the original number.
#Other matches
Default {$Number}
Then you just call the -join operator at the end to get the result.
-join $sounds
This approach doesn’t need an additional check at the end to see if the result is “empty” or not because it leverage the default behavior of switch statement.
Switch statement.
ordered hashtable
Using ordered-hashtable and foreach
function Raindrops() {
[CmdletBinding()]
Param(
[int]$Number
)
$table = [ordered]@{
3 = "Pling"
5 = "Plang"
7 = "Plong"
}
$sounds = foreach ($key in $table.Keys) {
if ($Number % $key -eq 0) {
$table.$key
}
}
$sounds.Count -eq 0 ? "$Number" : -join $sounds
}
This approach loops through an ordered hashtable’s keys.
If the input number is divisible by a key, retrieve the string associated with the key from the hashtable.
The loop can be assigned to a variable to represent the final collection of sounds.
$sounds = foreach ($key in $table.Keys) {
if ($Number % $key -eq 0) {
$table.$key
}
}
If the collection is empty at the end, return the original number as string.
$sounds.Count -eq 0 ? "$Number" : -join $sounds
foreach loop.
Hashtable data structure.
Source: Exercism powershell/raindrops