Determine if a string is collapsible: Difference between revisions

R language
No edit summary
(R language)
Line 2,814:
 
 
</pre>
 
=={{header|R}}==
<lang R>collapse_string <- function(string){
str_iterable <- strsplit(string, "")[[1]]
message(paste0("Original String: ", "<<<", string, ">>>\n",
"Length: ", length(str_iterable)))
detect <- rep(TRUE, length(str_iterable))
for(i in 2:length(str_iterable)){
if(length(str_iterable)==0) break
if(str_iterable[i] == str_iterable[i-1])
detect[i] <- FALSE
}
collapsed_string <- paste(str_iterable[detect],collapse = "")
message(paste0("Collapsed string: ", "<<<",collapsed_string, ">>>\n",
"Length: ", length(str_iterable[detect])), "\n")
}
 
test_strings <- c(
"",
"'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln ",
"..1111111111111111111111111111111111111111111111111111111111111117777888",
"I never give 'em hell, I just tell the truth, and they think it's hell. ",
" --- Harry S Truman ",
"The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
"headmistressship",
"aardvark",
"Ciao Mamma, guarda come mi diverto!!"
)
 
for(test in test_strings){
collapse_string(test)
}
 
</lang>
 
{{out}}
<pre>
Original String: <<<>>>
Length: 0
Collapsed string: <<<>>>
Length: 0
 
Original String: <<<'If I were two-faced, would I be wearing this one?' --- Abraham Lincoln >>>
Length: 72
Collapsed string: <<<'If I were two-faced, would I be wearing this one?' - Abraham Lincoln >>>
Length: 70
 
Original String: <<<..1111111111111111111111111111111111111111111111111111111111111117777888>>>
Length: 72
Collapsed string: <<<.178>>>
Length: 4
 
Original String: <<<I never give 'em hell, I just tell the truth, and they think it's hell. >>>
Length: 72
Collapsed string: <<<I never give 'em hel, I just tel the truth, and they think it's hel. >>>
Length: 69
 
Original String: <<< --- Harry S Truman >>>
Length: 72
Collapsed string: <<< - Hary S Truman >>>
Length: 17
 
Original String: <<<The better the 4-wheel drive, the further you'll be from help when ya get stuck!>>>
Length: 80
Collapsed string: <<<The beter the 4-whel drive, the further you'l be from help when ya get stuck!>>>
Length: 77
 
Original String: <<<headmistressship>>>
Length: 16
Collapsed string: <<<headmistreship>>>
Length: 14
 
Original String: <<<aardvark>>>
Length: 8
Collapsed string: <<<ardvark>>>
Length: 7
 
Original String: <<<Ciao Mamma, guarda come mi diverto!!>>>
Length: 36
Collapsed string: <<<Ciao Mama, guarda come mi diverto!>>>
Length: 34
</pre>
 
Anonymous user