Homework 1

Task 1 - Implement fizzbuzz

Write up

In order to write our fizzbuzz function, we took a series of steps. We began by thinking broadly about the errors we needed to throw before the actual function could run. We determined that the following would be necessary: checking for non-numeric types of inputs, negative values, inputs that are not coercible to integers without rounding or truncating, infinite values, and NAs and NaNs.

Once we came up with the criteria, we wrote the necessary code to check for this using stopifnot() statements and decided on helpful error messages to include. We then worked on setting up the format for the function. We used a for-loop to check each element of the vector and determine what it needs to be replaced with. We had to consider the order of the if else statements to ensure that each number was being labelled correctly.

Throughout this entire process, we were checking individual parts of our code using test cases in the console. Then we ran the good and bad test cases and discovered that we had too many double negatives in our stopifnot() statements, which we resolved. After debugging our code, we ran all of the test cases, and added our own, to ensure that our function was running properly.

Function

fizzbuzz = function(input) {
  n = length(input)
  return_vector = vector(mode = "character", length = n)
  
  #stop cases for the entire vector
  stopifnot("Input vector has non-numeric types" = is.numeric(input))
  stopifnot("Input vector has values less than 0" = (input >= 0))
  stopifnot("Input vector has values not coercible to integer type" = (input %% 1 == 0))
  stopifnot("Input vector has infinite values" = !is.infinite(input))
  stopifnot("Input vector has NA values" = !is.na(input))
  stopifnot("Input vector has NaN values" = !is.nan(input))
  
  for (integer in 1:n) {
    value = input[integer]
    
    if ((value %% 3 == 0) & (value %% 5 == 0)) {
      return_vector[integer] = "FizzBuzz"
    }
    else if (value %% 3 == 0) {
      return_vector[integer] = "Fizz"
    }
    else if (value %% 5 == 0) {
      return_vector[integer] = "Buzz"
    }
    
    #integer not divisible by either 3 or 5
    else {
      return_vector[integer] = as.character(value)
    }
  }
  return (return_vector)
}
fizzbuzz(1:5)
[1] "1"    "2"    "Fizz" "4"    "Buzz"
fizzbuzz(5:1)
[1] "Buzz" "4"    "Fizz" "2"    "1"   
fizzbuzz(-1)
Error in fizzbuzz(-1): Input vector has values less than 0