问题
I heard this was a common interview question, any ideas what is off here, thank you.
for(i in 1:100){
if(i%15==0){
print('fizzbuzz')
} else
if (i%3==0){
print("fizz")
} else
if (i%5==0) {
print("buzz")
} else
(print(i))
}
}
回答1:
I'd place the curly braces in different spots, and you need to correct the operator -- %%
instead of %
.
for(i in 1:100) {
if(i%%15==0){
print('fizzbuzz')
} else if (i%%3==0){
print("fizz")
} else if (i%%5==0) {
print("buzz")
} else {
print(i)
}
}
But the basic idea is sound: get the special 'fizzbuzz' case out the way first, then deal with remaining (exclusive) cases.
Here are the first 16 results:
edd@max:~$ r /tmp/fizzbuzz.R | head -16
[1] 1
[1] 2
[1] "fizz"
[1] 4
[1] "buzz"
[1] "fizz"
[1] 7
[1] 8
[1] "fizz"
[1] "buzz"
[1] 11
[1] "fizz"
[1] 13
[1] 14
[1] "fizzbuzz"
[1] 16
edd@max:~$
回答2:
I've just made R FizzBuzz check on myself:
f = seq(3,100,3)
b = seq(5,100,5)
fb = f[f %in% b]
f = f[!f %in% fb]
b = b[!b %in% fb]
x = as.character(1:100)
x[f] = "Fizz"
x[b] = "Buzz"
x[fb] = "FizzBuzz"
cat(x, sep = "\n")
If you don't understand any function here you should read manual.
Your for
loop solution may be not the best on the R dev interview. It may be interpreted as lack of skills to use R's vectorization feature.
来源:https://stackoverflow.com/questions/25595785/why-isnt-my-fizz-buzz-test-in-r-working