如何检查给定的字符串是否是r中另一个给定字符串的循环旋转?例如:1234
是3412
的循环旋转。但是,我想检查字符串是否在任何位置上都与另一个字符串相等。
accomodate henrik的评论,对nchar
等价的测试(i),以及(ii)如果复制第二个矢量是另一个向量的一部分,则似乎足够了:
ff = function(x, y) (nchar(y) == nchar(x)) && (grepl(y, strrep(x, 2), fixed = TRUE))
ff("3412", "1234")
#[1] TRUE
您只能生成连续的旋转,直到找到匹配项为止。如果旋转都不匹配,则字符串不是彼此的循环旋转。使用sub
的解决方案:
cycrotT = function(s1,s2) {
if (nchar(s1)!=nchar(s2)) {
return(FALSE) }
for (i in 1:nchar(s2)) {
if (s1==s2) {
return(TRUE) }
# Move the first character to the end of the string
s2 = sub('(.)(.*)', '\2\1', s2)
}
return(FALSE)
}
> cycrotT("1234567", "1324567")
# [1] FALSE
> cycrotT("1234567", "4567123")
# [1] TRUE
> cycrotT("1234567", "1234568")
# [1] FALSE
更长的时间,但也许更清晰地描绘了这样做的方法:
cyclic_index <- function(string1, string2) {
## gather info about the first string
chars <- el(strsplit(string1, ""))
length <- length(chars)
vec <- seq_len(length)
## create a matrix of possible permutations
permutations <- data.frame(matrix(NA, nrow = length, ncol = length + 1))
names(permutations) <- c("id", paste0("index", vec))
permutations$id <- vec
## calculate the offset indices
for (r in vec)
permutations[r, vec + 1] <- (vec + r - 1) %% (length)
## a %% a = 0 so reset this to a
permutations[permutations == 0] <- length
## change from indices to characters
permutations[ , vec + 1] <- sapply(vec, function(x) chars[unlist(permutations[x, vec + 1])])
## paste the characters back into strings
permutations$string <- sapply(vec, function(x) paste0(permutations[x , vec + 1], collapse = ''))
## if string2 is a permutation of string1, return TRUE
return(string2 %in% permutations$string)
}
cyclic_index("jonocarroll", "carrolljono")
#> TRUE
cyclic_index("jonocarroll", "callorrjono")
#> FALSE
cyclic_index("1234567", "4567123")
#> TRUE