Solution Review: Append Hearts
In this review, we provide a detailed analysis of the solution to the given problem
We'll cover the following
Solution #1: Using rep()
hearts <- function(testVariable){heart <- "<3"vectorOfHearts <- vector("character", 0)for(i in testVariable){x <- rep(heart, i)x <- paste(x, collapse = "")vectorOfHearts <-c(vectorOfHearts, x)}return(vectorOfHearts)}# Driver CodetestVariable1 <- c(5, 2)testVariable2 <- c(3, 3)hearts(testVariable1)hearts(testVariable2)
Explanation
In the code snippet above, we first create a function:
hearts <- function(testVariable)
In this function, we define the string heart <- "<3"
that we need to replicate. Then initiate a loop over all the elements of the vector testVariable
, that is passed to the function. Using the function:
rep(heart, i)
we duplicate the heart
string i
times.
Solution #2: Using replicate()
hearts <- function(testVariable){heart <- "<3"vectorOfHearts <- vector("character", 0)for(i in testVariable){x <- replicate(i, heart)x <- paste(x, collapse = "")vectorOfHearts <-c(vectorOfHearts, x)}return(vectorOfHearts)}# Driver CodetestVariable1 <- c(5, 2)testVariable2 <- c(3, 3)hearts(testVariable1)hearts(testVariable2)
Explanation
We can also use the function replicate()
to solve this problem.
replicate(i, heart)
# Here i is the number of times the string needs to be duplicated and heart is the string being replicated.
In the next lesson, we have another challenge for you to conquer.