Why isn't my “Fizz Buzz” test in R working?

有些话、适合烂在心里 提交于 2020-01-04 19:07:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!