Exercise 3
The Problem
A vector is said to be a palindrome if reversing its elements yields the same vector. Thus, c(3,1,3) is a palindrome, but c(3,1,4) is not a palindrome.
Write a function called isPalindrome() that, when given any vector, will return TRUE if the vector is a palindrome and FALSE if it is not a palindrome. The function should take a single parameter called vec, with no default value. Typical examples of use should be:
isPalindrome(vec = c("Bob", "Marley", "Bob"))## [1] TRUE
isPalindrome(c(3,2,7,4,3))## [1] FALSE
Hints for a Solution
When it seems difficult to make a function right off the bat, then you should follow the four-step process we discussed in class:
- solve the problem for a specific given object;
- generalize so that your code solves the problem for any given object;
- encapsulate your work into a function;
- test the function on a few examples.
We’ll follow the steps here.
Step One: Determine Whether a Specific Vector is a Palindrome
A vector is a palindrome provided that when you reverse it the result is equal to the original vector at all places. Let’s take a specific vector:
myLittleVector <- c(3,2,7,4,3)Now let’s check to see if it’s equal to its reverse:
myLittleVector == reverse(myLittleVector)## [1] TRUE FALSE TRUE FALSE TRUE
Note that this logical vector gives a TRUE when an element of myLittleVector is equal to the corresponding element of the reverse of the vector. The vector is built up like this:
| original vector | reversed vector | elements same? | myLittleVector == reverse(myLittleVector) |
|---|---|---|---|
| 3 | 3 | yes | TRUE |
| 2 | 4 | no | FALSE |
| 7 | 7 | yes | TRUE |
| 4 | 2 | no | FALSE |
| 3 | 3 | yes | TRUE |
Clearly, a vector will be a palindrome if all of the elements of the logical vector are TRUE.
Recall that the function all() takes a logical vector and returns TRUE if and only if all of the elements of the logical vector are TRUE. Thus, the following code does the work of checking whether myLittleVector is a palindrome:
all(myLittleVector == reverse(myLittleVector))## [1] FALSE
Step Two: Generalize
We can write a two line program that solves the problem for any vector:
vec <- c("b", "c", "f", "c", "b") # any old vector, call it vec
all(vec == reverse(vec)) # this line of code does the work## [1] TRUE
All the user would have to do, in order to work with another vector, is to change the binding on the first line. The second line then solves the problem.
Step Three: Encapuslate Into a Function
Now we see how to write our function. The general vector vec should be taken as the parameter. The part of the code that actually does the work goes into the body of the function. Here’s a start (you need to fill in the body):
isPalindrome <- function(vec) {
}Then you’ll move on to Step Four: testing your function on a few examples.