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")))
Advertisements

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s