A generalised FizzBuzz solution in R ;-)


Just spotted this and wondered if I could come up with a pretty solution in R. Here’s an attempt.

fizzbuzz = function(i, multiples = c(3,5), text = c("Fizz", "Buzz")) {
  words = text[i %% multiples == 0]
  if (length(words) == 0)
    as.character(i)
  else
    paste(words, collapse = "")
}

sapply(1:200,function(x) fizzbuzz(x))

This also generalises, e.g., call

sapply(1:200,function(x) fizzbuzz(x, c(3,5,7), c("Fizz","Buzz","Bang")))

2 thoughts on “A generalised FizzBuzz solution in R ;-)”

Comments are closed.