Adding The Twist
Part of the Fundamentals section of Coddy's R journey — lesson 55 of 78.
Challenge
EasyIn 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 to3)buzz_divisor- the divisor for "Buzz" (optional, defaults to5)
The function should use these custom divisors instead of hardcoded values when checking divisibility.
You will receive three lines of input:
- The upper limit
n - The fizz divisor
- 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
3The 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
5The 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
4Operators Part 2
Logical Operators (AND, OR)Logical Operators Part 2 (NOT)Recap - Simple LogicVectorized Logic Part 1Vectorized Logic Part 22Variables and Data Types
Numeric Data TypeInteger Data TypeCharacter Data TypeLogical Data TypeChecking Data TypesNaming ConventionsMissing Values: NARecap - Variable Creation8Loops
For LoopWhile LoopBreakNext (Continue)Recap - FactorialSequence Generation (seq, :)Nested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsInteger Division and ModuloAssignment OperatorsRecap - Simple MathComparison Operators6Basic IO
Print OutputCat for OutputOutput With VariablesReading Input with readline()Type Conversion BasicsRecap - Age CalculatorRecap - True or False9Functions
Declaring a FunctionFunction ArgumentsReturn ValuesRecap - Sigma FunctionRecap - Validation FunctionDefault Parameter Values