Menu
Coddy logo textTech

Adding The Twist

Part of the Fundamentals section of Coddy's R journey — lesson 55 of 78.

challenge icon

Challenge

Easy

In the previous lesson, you created a FizzBuzz program that loops through numbers using the default divisors 3 and 5. Now, add the twist by making the divisors customizable through default parameters.

Modify your fizzbuzz function to accept three arguments:

  • n - the number to check (required)
  • fizz_divisor - the divisor for "Fizz" (optional, defaults to 3)
  • buzz_divisor - the divisor for "Buzz" (optional, defaults to 5)

The function should use these custom divisors instead of hardcoded values when checking divisibility.

You will receive three lines of input:

  1. The upper limit n
  2. The fizz divisor
  3. The buzz divisor

Loop from 1 to n and call your updated fizzbuzz function with all three arguments. Print each result.

For example, if the inputs are:

10
2
3

The output should be:

[1] "1"
[1] "Fizz"
[1] "Buzz"
[1] "Fizz"
[1] "5"
[1] "FizzBuzz"
[1] "7"
[1] "Fizz"
[1] "Buzz"
[1] "Fizz"

If the inputs are:

15
3
5

The output should be:

[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"

Try it yourself

# Read input
con <- file("stdin", "r")
n <- as.numeric(suppressWarnings(readLines(con, n = 1)))

# Function from previous lesson
check_divisible <- function(number, divisor) {
  return(number %% divisor == 0)
}

# Create the fizzbuzz function
fizzbuzz <- function(n) {
  if (check_divisible(n, 3) && check_divisible(n, 5)) {
    return("FizzBuzz")
  } else if (check_divisible(n, 3)) {
    return("Fizz")
  } else if (check_divisible(n, 5)) {
    return("Buzz")
  } else {
    return(as.character(n))
  }
}

# Loop through numbers from 1 to n and print the result
for (i in 1:n) {
  print(fizzbuzz(i))
}

All lessons in Fundamentals