1

I can't seem to figure out where in my loop I don't come back to referencing the same indexed values to validate the palindrome.

I tried the code and should expect to see "This is a palindrome" but it returns the opposite

3 Answers 3

3

An easier way would be to check that all elements of your string match all elements of the reversed string:

is_palindrome <- function(s) {
  x <- strsplit(s, "")[[1]]
  all(x == rev(x))
}

is_palindrome("radar")
#> [1] TRUE

is_palindrome("reader")
#> [1] FALSE

If for some reason you need to use a loop, you can do:

is_palindrome <- function(s) {
  
  x <- strsplit(s, "")[[1]]
  
  for(i in 1:length(x)) {
    if(x[i] != x[length(x) + 1 - i]) {
      return(paste0("'", s, "' is not a palindrome"))
    }
  }
  return(paste0("'", s, "' is a palindrome"))
}

is_palindrome("radar")
#> [1] "'radar' is a palindrome"

is_palindrome("reader")
#> [1] "'reader' is not a palindrome"

Created on 2022-10-29 with reprex v2.0.2

Sign up to request clarification or add additional context in comments.

Comments

2

Use seq_along

Edit

Also there is an error at indexing x: must be len-i+1

Finally i do some modifications

s <-"radar"
x <- strsplit(s, "")[[1]]
len <-length(x)

#find the middle
middle <- ceiling(length(x)/2)
### Loop to the middle
answer <- "The word is a palindrome"
for (i in seq_along(x)){
  if (i < middle){
    #check for index position to match the other side
    if (x[i] != x[len-i+1]){
      answer <- "The word is not a palindrome"
      break;
    }
  } 
}
  
print(answer)

1 Comment

is there a way to get around using seq_along?
2

You can try the code below using rev + utf8ToInt

isPalindrome <- function(s) s == intToUtf8(rev(utf8ToInt(s)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.