|
このページは大阪弁化フィルタによって翻訳生成されたんですわ。 |
For those who don't know FizzBuzz, you output "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz for multiples of 15, otherwise the current number.
It's a basic test of loop knowledge and how to divide a problem that I've had used in interviews. Surprisingly, a lot of people fail it.
Over on codegolf, there's someone who's written an assembly language version optimized to run as fast as possible.
https://codegolf.stackexchange.com/a/236630
There are typically two basic approaches:
1. three separate cases plus a default
2. string concatenation, which only requires two cases, plus a default
Most people do variant 1, but I think variant 2 is often better future-proofed (in case you wanted to add a 7 multiple in there, in which case #1 now has 6 cases and the #2 only has 3).
I'm more interested in some of the more subtle aspects of it, like: can you show off the idioms of the language in question?
One of the Swift idioms that's kind of fun with FizzBuzz is showing off the _ variable (basically: DGAF what's stored there) and the ability to switch on multiple conditions at the same time.
for i in 1...100
{
switch (i % 3, i % 5)
{
case (0, 0):
print("FizzBuzz")
case (0, _):
print("Fizz")
case (_, 0):
print("Buzz")
default:
print(i)
}
}
Speaking of idioms, I keep meaning to get around to a Swift async/await version of dining philosophers, but haven't yet.
--
Deirdre Saoirse Moen
deirdre at deirdre.net