I was looking at a Perl code golf page (don't ask why) and came across this:
Hole 3 - Smallest Repeating Pattern
Write a subroutine that accepts a string which may consist of a repeating pattern, and returns the smallest repeating substring. If the string does not consist of a repeating pattern, the subroutine should return undef or the empty string. e.g.:
input output
'aaaaaa' 'a'
'ababab' 'ab'
'aabaab' 'aab'
'ababaa' ''
Apparently in Perl this can be expressed as sub g3 { pop=~/^(.*?)\1+\z/s&&$1 }
I don't know much Perl so I don't understand how this works. What is the best we can do in Scala? I'm more interested in elegance than the precise number of characters.
Here is my attempt, but it's pretty ugly, which is why I'm asking.
def srp(s: String) =
s.inits.toList.tail.init.map(i => (i * (s.size / i.size), i)).
filter(_._1 == s).map(_._2).reverse.headOption.getOrElse("")