Last night was our local Functional Kats {Belfast} meetup group that an ex-colleague and I organise. The kata we worked on was a particularly fun one and good enough to share with all you good Ranchers.
Functional Kats Kata wrote:
Concatenate N N Times
A number like 7777777 consists of the number 7 concatenated to itself 7 times. A number like 121212121212121212121212 consists of the number 12 concatenated to itself 12 times. That is to say: the number X consists of the number N concatenated to itself N times.
Your task is to write a program that calculates the number that is concatenated to itself, and the number of times it appears.
Yeah, I went for brevity and simplicity over performance - could be a big difference for larger strings, as you note. I came up with a much more efficient alternative, rejecting many candidates based only on the input length, before it ever looks as the individual characters (once, at most). Roughly analogous solutions in functional Scala:
My mind keeps coming back to this one. Here's a much shorter Java solution, probably not quite as fast as the last two, but much faster than my first Scala solution above. And it doesn't even use any features newer than JDK 1.4:
And the formula used to calculate word length (varible n) is an approximation, but from testing, it's accurate through the range of all possible input array lengths, up through Integer.MAX_VALUE. So unless we need to test longer input than that, we're good...
Minor point: it fails with "0202", but it is not clear if such a string is within the bounds of the assignment.
My Pojo (with some obligatory lambdas, although an old fashioned java one would be more readable):
There are three kinds of actuaries: those who can count, and those who can't.