Skip to content

Instantly share code, notes, and snippets.

@MikeMKH
Created June 28, 2017 11:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikeMKH/29909356c023798d47a65624922807ea to your computer and use it in GitHub Desktop.
Save MikeMKH/29909356c023798d47a65624922807ea to your computer and use it in GitHub Desktop.
Collection of FizzBuzz katas in R
sapply(rep(0:100),
function(x)
if(x %% 15 == 0) "FizzBuzz"
else if(x %% 3 == 0) "Fizz"
else if(x %% 5 == 0) "Buzz"
else x)
# based on https://gist.github.com/jangorecki/ef2b908a6ad46a13a5e4
fizzy <- seq(0, 100, 3)
buzzy <- seq(0, 100, 5)
fizzbuzzy <- fizzy[fizzy %in% buzzy]
fizzbuzz <- 0:100
fizzbuzz[fizzbuzz %in% fizzbuzzy] <- "FizzBuzz"
fizzbuzz[fizzbuzz %in% fizzy] <- "Fizz"
fizzbuzz[fizzbuzz %in% buzzy] <- "Buzz"
fizzbuzz
# based on https://wrathematics.github.io/2012/01/10/honing-your-r-skills-for-job-interviews/
fizzbuzz <- 0:100
fizzbuzz[which(fizzbuzz %% 5 == 0)][which(fizzbuzz %% 3 == 0)] <- "FizzBuzz"
fizzbuzz[which(as.numeric(fizzbuzz) %% 3 == 0)] <- "Fizz"
fizzbuzz[which(as.numeric(fizzbuzz) %% 5 == 0)] <- "Buzz"
fizzbuzz
# based on http://www.aske.ws/posts/fizzbuzz_in_R.html
fizzbuzz = function(x, divisors=c(3, 5), translate=c("Fizz", "Buzz")) {
result = translate[x %% divisors == 0]
ifelse (length(result) == 0, as.character(x), paste(result, collapse="")
}
sapply(0:100, function(x) fizzbuzz(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment