I am converting the "zxcvbn" password strength algorithm from JavaScript to Scala. I am looking for a pure functional algorithm for finding sequences of repeating characters in a string.
I know that I can translate the imperative version from JavaScript, but I would like to keep this as side-effect free as possible, for all the reasons usually given for functional programming.
The algorithm can be in Scala, Clojure, Haskell, F#, or even pseudocode.
Thanks.
Here is another Scala solution
Clojure's version of hammar's algorithm
Here is a Scala solution that I came up with:
For the test case
repeatMatch("abccccdefffg")
, the result isList((2,4), (8,3))
Maybe the calculation of
run
could be improved.Using Haskell's standard higher-order functions:
Data.List.group
finds runs of equal elements in a list:We care about the length of these runs, not the elements themselves:
Next, we need the starting positions of each group. This is just the partial sums of the group lengths, which we can compute using
scanl
:Zipping these two lists gives us all pairs of starting positions and corresponding lengths:
Finally, we remove the groups of length less than 3.
Putting this together: