Skip to content

Instantly share code, notes, and snippets.

@nathancday
Last active November 15, 2018 17:12
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 nathancday/10ef105531a52df5fe45ca40a29c7699 to your computer and use it in GitHub Desktop.
Save nathancday/10ef105531a52df5fe45ca40a29c7699 to your computer and use it in GitHub Desktop.
# https://en.wikipedia.org/wiki/Fizz_buzz
values <- 1:15
rules <- c("fizz" = 3, "buzz" = 5)
container <- rep("", length.out = length(values))
for (name in names(rules)) {
rule_idx <- values %% rules[name] == 0
container <- ifelse(rule_idx, paste0(container, name), container)
}
blank_idx <- container == ""
container <- ifelse(blank_idx, values, container)
# Level Up -----------------------------------------------
values2 <- 1:105
rules2 <- c("fizz" = 3, "buzz" = 5, "pop" = 7)
soda_shop <- function(rules, values) {
container <- rep("", length.out = length(values))
for (name in names(rules)) {
idx <- values %% rules[name] == 0
container <- ifelse(idx, paste0(container, name), container)
}
idx <- container == ""
ifelse(idx, values, container)
}
soda_shop(rules2, 1:105)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment