I looked at the Perl golf code page (don't ask why) and came across this:
Hole 3 - smallest repeating pattern
Write a subroutine that takes 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 routine should return undef or an empty string. eg:.
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 it works. What is the best we can do in Scala? I'm more interested in elegance than the exact number of characters.
Here is my attempt, but it is pretty ugly, that’s why I ask.
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("")
source share