Home > Software design >  R Programming - Palindrome
R Programming - Palindrome

Time:10-30

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.

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

#find the middle
middle <- ceiling(length(x)/2)
### Loop to the middle
for (i in 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"
    }else {
      answer <- "The word is a palindrome"
    }
  } 
}
  
print(answer)

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

CodePudding user response:

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)

CodePudding user response:

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

CodePudding user response:

You can try the code below using rev utf8ToInt

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