The purpose of this task is to write a program or function to find the most common substring within a given string, of the specified length.
Inputs
- A string,
s
, of any length and characters that are valid as inputs for your language. - A number,
n
, indicating the length of substring to find. Guaranteed to be equal to or less than the length of the string.
Output
The most common (case-sensitive) substring of s
of length n
. In the case of a tie, any of the options may be output.
Win Criteria
This is code-golf, so lowest bytes wins; usual exceptions etc. apply.
Examples
Hello, World!
, 1
> l
(appears 3 times)
Hello! Cheerio!
, 2
> o!
(appears twice)
The Cat sat on the mat
, 2
> at
(appears three times)
The Cat sat on the mat
, 3
> at
or he
(both with trailing spaces. Both appear twice - note case-sensitivity so The
and the
are different substrings)
Mississippi
, 4
> issi
(appears twice, note that the two occurrences overlap each other)
Some more examples, all using the same input string*
Bb:maj/2
F:maj/5
Bb:maj/2
G:9/3
Bb:maj7
F:maj/3
G:min7
C:sus4(b7,9)
C:sus4(b7,9)
C:sus4(b7,9)
F:maj
F:maj
(note the trailing newline)
1 > \r\n
(appears 12 times, counting \r\n
as a single character - my choice, your code may differ on this - otherwise either \r
or \n
appear the same number of times). :
also appears 12 times
2 > :m
(appears 8 times)
3 > :ma
or maj
(appears 7 times)
4 > :maj
(appears 7 times)
5 > F:maj
or \r\nF:ma
or :maj/
(appears 4 times)
14 > \r\nC:sus4(b7,9)\r\n
(appears 3 times)
(* input is taken from How predictable is popular music?. The result of this task might be used, for example, to find the most efficient way to apply a substitution in order to compress the string)
n=5
spot. regarding your second point, each line in the test case ends with a newline - there are 12 lines in the test case, so 11 newlines. Or am I missing something? Or maybe the formatting is messing things up? \$\endgroup\$:
does appear 12 times (not sure how you got 8?) - so that's actually the largest. I've added a trailing newline to the test case, so now we have\r\n
and:
tying. \$\endgroup\$:
occurs one more than\n
, but with a trailing newline they indeed both occur an equal amount of times. \$\endgroup\$