1) Temperature Conversion

Write a function to convert Fahrenheit to Celsius and Celsius to Fahrenheit.

convert_temperature <- function(input,F_to_C){
  if(F_to_C == TRUE){
    return((input-32) / (9/5))
  }else{
  return(input*(9/5) + 32)
  }
}
convert_temperature(30,F_to_C = FALSE)
## [1] 86
convert_temperature(86,F_to_C = TRUE)
## [1] 30

2) Future Value

Write a function to calculate the future value of an investment given annually compounding interest over an amount of years.

calculate_future_value <- function(investment, interest, duration_in_years){
  return(investment * (1+interest)^duration_in_years)
}
calculate_future_value(investment = 100,interest = 0.07,duration_in_years = 5)
## [1] 140.2552

3) Color Hex Code

Write a function to randomly generate n color hex codes. You can use letters predefined vector.

generate_hex_code <- function(n=3){
  digit_vec <- c(letters[1:6],0:9)
  hex_codes <- c()
  for(i in 1:n){
  hex_codes <- c(hex_codes, paste0("#",paste0(sample(digit_vec,6,replace=TRUE),collapse = "")))
  }
  hex_codes <- unique(hex_codes)
  if(length(hex_codes) < n){
    for(i in 1:(n-length(hex_codes))){
      hex_codes <- c(hex_codes, paste0("#",paste0(sample(digit_vec,6,replace=TRUE),collapse = "")))
    }
  }
  return(hex_codes)
}
generate_hex_code(n = 5)
## [1] "#b37f59" "#b99b10" "#c1782e" "#24ae93" "#372c7b"

4) Calculate Probability of Dice

Write a function which calculates the probability of getting k sixes in n throws of a die. Hint: Use binomial distribution.

comb <- function(n,k) {
  factorial(n) / factorial(n-k) / factorial(k)
}
get_prob_dice <- function(k,n){
  return(comb(n,k) * ((1/6)^k) * ((5/6)^(n-k)))
}
get_prob_dice(n = 3, k = 5)
## [1] NaN

5) Rock, Scissors, Paper

Write a rock scissors paper game which computer randomly chooses.

rsp_game <- function(user,choices=c("rock","scissors","paper")){
  if(!(user %in% choices))
    return("Choose only rock, scissors or paper as input.") 
  response <- sample(choices,1)
  if(user == response)
    return("I chose the same. Tie!")
  if((user == "rock" & response == "scissors") | 
     (user == "scissors" & response == "paper") |
     (user == "paper" & response == "rock")){
    return(paste0("I chose ", response, ". You win!"))
  }else{
    return(paste0("I chose ", response, ". You lose!"))
  }
}
rsp_game("rock")
## [1] "I chose paper. You lose!"

6) FizzBuzz

In a loop from 1 to 15, if a value can be exactly divided by 3, print “Industrial”; if by 5, print “Engineering”; if by 15, print “Industrial Engineering”. (p.s. You shouldn’t print Industrial or Engineering when the value can be exactly divided by 15). (Tip: You can use modulo operator (%%). For example 4%%3 is 1 and 4%%2 is 0.)

fizz <- "Industrial"
buzz <- "Engineering"
for(i in 1:15){
  print(i)
  if(i %% 15 == 0){
    print(paste(fizz,buzz))
  }
  else if(i %% 5 == 0){
    print(buzz)
  }
  else if(i %% 3 == 0){
    print(fizz)
  }
}
## [1] 1
## [1] 2
## [1] 3
## [1] "Industrial"
## [1] 4
## [1] 5
## [1] "Engineering"
## [1] 6
## [1] "Industrial"
## [1] 7
## [1] 8
## [1] 9
## [1] "Industrial"
## [1] 10
## [1] "Engineering"
## [1] 11
## [1] 12
## [1] "Industrial"
## [1] 13
## [1] 14
## [1] 15
## [1] "Industrial Engineering"

Alternative single-row-code:

ifelse(1:15 %% 15 == 0, "Industrial Engineering", ifelse(1:15 %% 5 == 0, "Engineering", ifelse(1:15 %% 3 == 0, "Industrial", "")))
##  [1] ""                       ""                       "Industrial"            
##  [4] ""                       "Engineering"            "Industrial"            
##  [7] ""                       ""                       "Industrial"            
## [10] "Engineering"            ""                       "Industrial"            
## [13] ""                       ""                       "Industrial Engineering"

7) Travelling Salesperson

You can see distances between 10 cities on the data set below.

#Copy paste the following lines to get the distance matrix
set.seed(2017)
distance_matrix<-matrix(sample(10:50,100,replace=TRUE),ncol=10)
distance_matrix[lower.tri(distance_matrix)]<-0
distance_matrix <- distance_matrix + t(distance_matrix)
diag(distance_matrix)<-0
distance_matrix
##       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
##  [1,]    0   42   49   28   27   22   36   50   36    35
##  [2,]   42    0   31   17   16   18   19   26   19    38
##  [3,]   49   31    0   14   21   12   29   26   50    48
##  [4,]   28   17   14    0   28   33   32   23   30    25
##  [5,]   27   16   21   28    0   28   49   28   50    36
##  [6,]   22   18   12   33   28    0   18   15   10    15
##  [7,]   36   19   29   32   49   18    0   41   48    27
##  [8,]   50   26   26   23   28   15   41    0   22    25
##  [9,]   36   19   50   30   50   10   48   22    0    37
## [10,]   35   38   48   25   36   15   27   25   37     0

Consider a salesperson operating in these cities. For a given route create a function which will return the total distance that the salesperson need to cover. Use distance matrix as input.

calculate_total_distance<-function(distance_input,route_info){
    total_distance<-0
    for(i in 1:(length(route_info)-1)){
        total_distance <- total_distance + distance_input[route_info[i],route_info[i+1]]
    }

    return(paste0("Total distance: ",total_distance))
}

Calculate the total distance of the route 1-5-2-6-7-2-4-1.

calculate_total_distance(distance_input=distance_matrix,route_info=c(1,5,2,6,7,2,4,1))
## [1] "Total distance: 143"

8) Number Guessing Game

Have the function to choose a number between 1 and 100 and create a game where the user is asked to guess that number in at most 10 trials. At each trial report whether the guessed number is higher or lower than the actual number. It is either a win or a game over after 10 trials.

guess_number <-function(){
    my_number<-sample(1:100,1)
    print("I have a number on my mind. It is between 1 and 100. Can you guess it in 10 trials?")
    for(i in 10:1){
        player_guess<-readline("Enter a number between 1 and 100: ")
        if(player_guess == my_number){
            return("Congratulations! Correct answer.")
        }else if(player_guess > my_number){
            print("My number is lower than your guess. Try again...")
        }else{
            print("My number is higher than your guess. Try again...")
        }
        print(paste0("Remaining guesses: ", i-1))
    }
    return("Game over :/")
}