Introduction
Raindrops is a slightly more complex version of the FizzBuzz challenge, a classic interview question.
Instructions
Instructions
Your task is to convert a number into its corresponding raindrop sounds.
If a given number:
- is divisible by 3, add “Pling” to the result.
- is divisible by 5, add “Plang” to the result.
- is divisible by 7, add “Plong” to the result.
- is not divisible by 3, 5, or 7, the result should be the number as a string.
Examples
- 28 is divisible by 7, but not 3 or 5, so the result would be
"Plong".
- 30 is divisible by 3 and 5, but not 7, so the result would be
"PlingPlang".
- 34 is not divisible by 3, 5, or 7, so the result would be
"34".
A common way to test if one number is evenly divisible by another is to compare the [remainder][remainder] or [modulus][modulo] to zero.
Most languages provide operators or functions for one (or both) of these.
[remainder]: https://exercism.org/docs/programming/operators/remainder
[modulo]: https://en.wikipedia.org/wiki/Modulo_operation
Dig Deeper
Data Driven
Data Driven
module Raindrops
DROPS = {3 => "Pling", 5 => "Plang", 7 => "Plong"}
def self.convert(number : Int)
DROPS.join { |k, v| v if number.divisible_by?(k) }.presence || number.to_s
end
end
Using a data-driven approach to create logic to solve the raindrops problem, makes the solution both concise and flexible.
If the rules change, it is as easy as to change the rules.
The solution starts by creating a Hash with the rules.
Then it uses Enumerable#join used on the newly created Hash.
The join method will iterate over the Hash and join the values together as a String.
The join method takes a block, which feds the key and value of the Hash.
Then if the number is divisible by the key, it will return the value, otherwise, it will return nil.
The result of the join method is then fed to String#presence.
It will return the String if it is not empty, otherwise, it will return nil.
Then the || operator is used to return the number as a String if the result is nil, otherwise it will return the result.
Conditionals
Conditionals
module Raindrops
def self.convert(count : Int32) : String
result = ""
result += "Pling" if count.divisible_by?(3)
result += "Plang" if count.divisible_by?(5)
result += "Plong" if count.divisible_by?(7)
result.empty? ? count.to_s : result
end
end
This approach uses a series of if’s suffix statements to build a string.
It starts by creating an empty String.
Then based on if the number is divisible by 3, 5, or 7, it adds the appropriate string to the result.
The String added needs to be added in the correct order, otherwise the result would be reversed.
Finally, if the result is empty, it returns the number as a String, otherwise it returns the result.
It uses implicit return to return the result.
Source: Exercism crystal/raindrops