1. Conclusion </ b>
2. What is the FizzBuzz problem? </ B>
3. How to program </ b>
4. What I learned from here </ b>
In conclusion, it's a program designed to separate programmer aspirants who can't write code.
As a specific example, (i) When outputting numbers from 1 to 100 (ii) Multiples of 3 are "Fizz" (iii) Multiples of 5 are "Buzz" (iv) Multiples of 15 are "FizzBuzz" To display </ b>
It is a program called!
It is famous as a problem that you can try to understand the basics!
This time, the language used will be "Ruby".
def fizz_buzz
num = 1 #---❶
(1..100).each do |i| #---❷
if num % 15 == 0 #---❸
puts "FizzBuzz"
elsif num % 3 == 0
puts "Fizz"
elsif num % 5 == 0
puts "Buzz"
else
puts num #---❹
end
num = num + 1 #---❺
end
end
fizz_buzz
❶ First, unless you assign "1" to num here, you cannot know which value of which variable. This time it is 1 ~ 100, so "1" is substituted.
❷ Iterative processing + conditions are required to satisfy (i) explained in "2. What is the FizzBuzz problem?". This will be described later in "4. What I learned from here", but you can also code with methods other than each.
❸ This is a conditional expression to satisfy (ii) to (iv) explained in "2. What is the FizzBuzz problem?". For multiple case classification, the remainder operator is used to determine the multiple of 3/5/15. As a caveat, if you code from a conditional expression that is a multiple of 3, when the number "15" appears, it will be recognized under the condition of "multiple of 3". Programs are basically loaded from top to bottom </ b>, so once the conditions are met, subsequent programs will be ignored. I also introduced how to write the remainder in my article, so you can save the trouble of searching! Operator of remainder and power (exponentiation)
❹ Since "1 ~ 100" is displayed in (i) explained in "2. What is the FizzBuzz problem", conditions other than multiples are also output. Therefore, I try to output the numbers as they are except for the conditions.
❺ Without this, numbers after “1” cannot be produced. Even if 1 to 100 is written in each, it will be a repetitive process that outputs "1" 100 times. You can also use "num + = 1".
❷ part is I thought it would be possible to combine the iterative processing method and the conditional expression (100 or less), and when I used the while method, it worked.
while num <= 100 do
After searching variously, There were many ways to iterate, as shown in the URL below! What I knew was the times / each / while method. Also, how to incorporate the condition depends on the method!
Referenced URL: while statement Output from 1 to 100 in various ways
Recommended Posts