Detecting loops in in in strings
Perl, 36 bytes
#!perl -p
s!(.+)\1+!@{[$&=~/\Q$1/g]}."[$1]"!eg
Try it online!
PHP 5.6, 68 bytes
Same code in PHP. Requires the command line option -F
, and relies on deprecated /e
modifier.
<?=preg_filter('/(.+)\1+/e','substr_count("\0","\1")."[\1]"',$argn);
C, 224 205 203 199 195 193 chars
The string is given as program parameter. As usual, use double quotes if your string contains spaces, and for empty strings - calling the program without any parameter crashes, but calling with ""
works.
Output for test cases is:
st st st Hello ThereThere => 3[st ]He2[l]o 2[There]
Bookkeeper => B2[o]2[k]2[e]per
/\/\/\\\\\\\\/\/\/ => 3[/\]2[\\\]3[\/]
which looks correct to me regarding "choose the largest possible repeating section".
Code:
l,r,f,i;char*c;main(a,b)char**b;{l=strlen(c=b[1]);for(;putchar(*c);c++)for(a=l;--a;f=0)for(r=a;!f;r+=a){for(i=0;i<a;)f|=r>l||c[i]-c[r+i++];if(f*r>a)c[a]=0,printf("\b%i[%s]",r/a,c),c+=r-1,a=1;}}
scala, 102 chars
print("(?!\\s)(.+)\\1+".r.replaceAllIn(readLine,m=>m.matched.size/m.group(1).size+"["+m.group(1)+"]"))
Output
st st st Hello ThereThere -> 3[st ]He2[l]o 2[There]
st Hello st st Bye -> st He2[l]o 2[st ]Bye
Bookkeeper -> B2[o]2[k]2[e]per
/\/\/\\\\\\\\/\/\/ -> 3[/\]2[\\\]3[\/]