Write a complete program (not just a function) which using stdin takes in a string of arbitrary length (assume string-length at least one) composed only of digits 0-9 and outputs using stdout the substring which appears most often in the input string. The input string can be any length and the substring can be maximum half the length of the input string because it must appear at least twice non-overlapped to be printed.
We following the following hierarchy selecting the substring to be printed.
- First priority, the longest substring
- Second priority, if we have multiple substrings of the same length, we pick the one appearing the most often.
- Third priority, if multiple substrings of the same size appear the same number of times, pick the one which appears first scanning from the left.
Here are some test cases followed by the rules and some explanation.
No substrings repeat.
The substring must appear more than once. If no substrings repeat the the output must exactly be the string "No substrings repeat." complete with the capitalization and the period.
The sub-strings must not overlap. So in this case the largest repeating substring is
12 instead of
We want the largest substring which appears at least twice. Here
9999 all appears at least twice. But we want the largest substring which appears at least twice.
878 each appear multiple times so we pick
788 which appears the most often.
21 both appear twice so we pick
12 which appears first from the left.
12 occurs first and appears thrice but
9999 is longer and appears only twice so we pick
9999 because it has the highest priority.
No substrings of length more than three repeat.
123 each appear twice.
412 occurs first and is thus printed.
I think I have taken care of all the cases. True code-golf. The shortest code in any language wins. In the case of ties, I pick the one with the highest upvotes after waiting at least for two weeks and probably longer. So the community please feel free to upvote any solutions you like. The cleverness/beauty of the code matters much more than who posts first.