Rebol3 Code Examplex
Rep-string
A string which is created by repeating a substring of the first N characters of the string truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original.
Rebol [
title: "Rosetta code: Rep-string"
file: %Rep-string.r3
url: https://rosettacode.org/wiki/Rep-string
]
rep-string?: function [
"Return the repeated unit if text is a rep-string, false otherwise"
text [string!]
][
len: length? text
for x len // 2 1 -1 [ ;; try prefix lengths from mid down to 1
unit: copy/part at text x + 1 len - 1 ;; suffix of length len-x
if find/match text unit [ ;; suffix is also a prefix?
return copy/part text x ;; return the repeating unit
]
]
false
]
foreach str [
"1001110011"
"1110111011"
"0010010010"
"1010101010"
"1111111111"
"0100101101"
"0100100"
"101"
"11"
"00"
"1"
][
rep: rep-string? str
prin [pad copy str 10 "-> "]
print either/only rep [
pad copy rep 5 "( length:" length? rep ")"
][ "*not* a rep-string"]
]Output:
1001110011 -> 10011 ( length: 5 )
1110111011 -> 1110 ( length: 4 )
0010010010 -> 001 ( length: 3 )
1010101010 -> 1010 ( length: 4 )
1111111111 -> 11111 ( length: 5 )
0100101101 -> *not* a rep-string
0100100 -> 010 ( length: 3 )
101 -> *not* a rep-string
11 -> 1 ( length: 1 )
00 -> 0 ( length: 1 )
1 -> *not* a rep-string