Apparently using an if
to solve FizzBuzz is a sign that you’re not a great programmer… Well, that’s how I would have done it :-(
I wanted to see what the map
alternative looked like, and I found this python example
print(*map(lambda i: 'Fizz'*(not i%3)+'Buzz'*(not i%5) or i, range(1,101)),sep='\n')
What’s interesting to me is that there’s an or
in there - if neither of the modulo operations match, then the resulting string is empty, and that can be used in an or
(failing the left-hand side). Whoa! That doesn’t work in R because characters can’t be used in logical operations
"" | 2
Error in "" | 2 :
operations are possible only for numeric, logical or complex types
The rest I can more or less reproduce in R, using strrep
in place of the infix *
used for ‘repeat string’
sapply(1:20,
\(x) paste0(
strrep("Fizz", x %% 3 == 0),
strrep("Buzz", x %% 5 == 0),
strrep(x, x %% 3 != 0 && x %% 5 != 0)
)
)
[1] "1" "2" "Fizz" "4" "Buzz" "Fizz"
[7] "7" "8" "Fizz" "Buzz" "11" "Fizz"
[13] "13" "14" "FizzBuzz" "16" "17" "Fizz"
[19] "19" "Buzz"
This also requires the additional comparison for when the number is a divisor of neither number, so kudos to python for working nicer in that case.
Is there an even better way to solve this without an if
?