[Question]
  [
Given a string **s** composed of lowercase letters, such as
```
aabaaababbbbaaba
```
and a positive integer **n**, such as `4`, output a length-**n** string **t** such that when **t** is repeated to the length of **s**, they have as many chars in common as possible. For the given example, the optimal output would be `aaba`, because it has thirteen chars in common with the target string:
```
s: aabaaababbbbaaba
t: aabaaabaaabaaaba (aaba)
   ^^^^^^^^  ^ ^^^^
```
and no possible **t** has more. However, for `aaaaaab`, there are two possible outputs: `aaaa` and `aaba`, which each have 6 chars in common with the target string:
```
s: aaaaaab
t: aaaaaaaa (aaaa)
   ^^^^^^ 
s: aaaaaab
t: aabaaaba (aaba)
   ^^ ^^^^
```
Either `aaaa` or `aaba` can be outputted, or both if you'd like. Note that **s** is not ever repeated; the trailing `a` in both repeated values of **t** is simply ignored.
## Test cases
```
Inputs -> Valid outputs
1 a -> a
1 aa -> a
2 aa -> aa
1 ab -> a b
2 ab -> ab
1 abb -> b
2 abb -> ab bb
2 ababa -> ab
2 abcba -> ab
2 aabbbbb -> bb  (ab is not a valid output here)
3 aababba -> aab abb
3 aababbaa -> aab
3 asdasfadf -> asf
3 asdasfadfsdf -> asf adf
2 abcdefghijklmnopqrstuvwxyzyx -> yx
2 supercalifragilisticexpialidocious -> ic ii
3 supercalifragilisticexpialidocious -> iri ili ioi
4 supercalifragilisticexpialidocious -> scii
5 supercalifragilisticexpialidocious -> iapic
2 eeeebaadbaecaebbbbbebbbbeecacebdccaecadbbbaceebedbbbddadebeddedbcedeaadcabdeccceccaeaadbbaecbbcbcbea -> bb be
10 bbbbacacbcedecdbbbdebdaedcecdabcebddbdcecebbeeaacdebdbebaebcecddadeeedbbdbbaeaaeebbedbeeaeedadeecbcd -> ebbbdbeece ebdbdbeece
20 aabbbaaabaaabaaaabbbbabbbbabbbabbbbbabbaaaababbbaababbbaababaaaabbaaabbaabbbabaaabbabbaaabbaaaaaaaba -> aabbbbaaabbabbbaabba
```
## Rules
* You may assume the input will only ever be a non-empty string of lowercase letters and a positive integer no greater than the length of the string.
* You may take the inputs in any standard format and in either order.
* You may output a single string, or more than one in the form of an array, separated by newlines or spaces, etc.
* Your code must finish for each test-case in less than 1 minute on any fairly modern computer.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so make your code as short as possible.
  
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
sZµṢŒrUṀṪµ€
```
[Try it online!](https://tio.run/nexus/jelly#FYyxEcJQDENXgmFo0lmWFiALcIzACJS5tCl@mzsG@VnEyD43T092rct5zPH9fZ6POV5zbOdxvfeqgicyEikqaaLAENMUTkGiQYAUka0hhNANBiX5zBvW6hq76bSdH7Putz8 "Jelly – TIO Nexus")
Wasn't expecting to beat Dennis on this one, so tried to FGITW it (after trying several possibilities; there's more than one way to make 11). I came in shorter, much to my surprise.
Takes the string then the count as command-line arguments. Outputs on stdout.
## Explanation
```
sZµṢŒrUṀṪµ€
s            Split {the first input} into {the second input}-sized groups
 Z           Transpose
  µ      µ€  On each of the transposed groups:
   Ṣ           Sort it;
    Œr         Run-length encode it;
      U        Rearrange it to the form {count, letter};
       Ṁ       Take the largest element (i.e. largest count)
        Ṫ      Take the second element of the pair (i.e. just the letter)
```
This uses the insight that the letter in each position of the pattern must be the most common letter corresponding to that position. We can find the letters corresponding to a particular pattern via splitting into pattern-sized groups, and transposing. The main reason this solution is so long is that Jelly doesn't seem to have a short way to find the mode of a list (I made several attempts, but they're all at least six bytes long).
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes, based on @Dennis' solution
```
⁸ċ$ÞṪ
sZÇ€
```
[Try it online!](https://tio.run/nexus/jelly#FYwxFQIBDEN3dCCAs8OWNFGAAlgY8IAAHgK4@TDCGSlpX5efn7b36@f7OG7P3/o6XM7bfb@9u5sZFIpluRSSKVgVQlJKHDBpAzWaJsxpCLKdsyyiPTVNM@m4PFYvpz8 "Jelly – TIO Nexus")
This is a combination of @Dennis' solution and my own; there was a five-byte mode in that solution, which I stole for this solution. (I already had solutions based on `⁸ċ`, but couldn't get below six bytes with it; I hadn't thought of using `Þ`.)
## Explanation
`µ…µ€` and `Ç€` (with the `…` on the previous line) are both three bytes long (the latter needs a newline), and equivalent. Normally I use the former, but the latter's more flexible, as it allows you to use `⁸` to mention the argument.
This makes it possible to sort (`Þ`) by the number of occurrences in `⁸` (`⁸ċ`), then take the last element (`Ṫ`), to find the mode in just five characters.
[Answer]
## Mathematica, 51 bytes
```
#&@@@Commonest/@(PadRight@Partition[#2,UpTo@#])&
```
Input and output are lists of characters.
Also based on the modes of the lines of the transpose. I believe they called the built-in for the mode of a list `Commonest` *solely* to spite code golfers. 
[Answer]
# Python 3, ~~99, 73~~ 61 bytes
-12, thx to @Rod
```
lambda s,n:''.join(max(s,key=s[i::n].count)for i in range(n))
```
Same idea, but rewrote it to eliminate the import statement.
```
lambda s,n:''.join(max(s,key=lambda c:s[i::n].count(c))for i in range(n))
```
Original
```
from collections import*
lambda s,n:''.join(Counter(s[i::n]).most_common(1)[0][0]for i in range(n))
```
Explanation:
```
s[i::n]                  a slice of every nth character of s, starting at position i
Counter(s[i::n])         counts the characters in the slice
  .most_common()         returns a list of (character, count) pairs, sorted by decreasing count
    [0][0]               grabs the letter from the first pair (i.e., the most common letter
      for i in range(n)  repeat for all starting positions
''.join                  combines the most common letters into a single string
```
[Answer]
## Python 2, 106
Now it's a different answer! I was thinking about one(almost)-liner from the beggining. Now even shorter, based on zip usage by @Rod.
Thanks to @L3viathan and @Rod for clarification about using lambdas as answer
[Try it online](https://tio.run/nexus/python2#LcoxEoMgEEDRPqfYsQKHKqUzXCGNbRpUSDayLAFMwMsbi/zyz3P6fnhD02JgVLeBTBUz04TBFOSQxTmlWm3Tf5SHvJGoWjdwnKCqBhhgx3jK3HsbxCjPLi4xARabCrPPgBQ5lf6ICUMBJ3oMcStCyqMz07xY93jia/UUOL5TLtvnW9veaqeuPw) 
```
lambda S,N:max(combinations(S,N),key=lambda s:sum(x==y for x,y in zip(S,s*len(S))))
from itertools import*
```
Explanation:
`combinations(S,N)` creates all combinations length N from characters of S 
`max()` have argument `key` which takes as input function to use to compare elements
`lambda s:sum(x==y for x,y in zip(S,s*len(S)))` passed as such function
This lambda counts number of matching characters in list of tuples, produces by `zip(S,s*len(S))`
`s` - one of combinations and it's multipled by `len(S)` which creates string that is guaranteed longer than S
`zip` creates tuples of characters of each string `S` and `s*len(S)` and ignores all characters that can't be matched (in case of one string longer than another)
So `max` chooses combination, that produce maximum sum
[Answer]
## JavaScript (ES6), ~~104~~ ~~101~~ 94 bytes
```
(n,s)=>s.replace(/./g,(_,i)=>[...s].map((c,j,a)=>j%n-i||(a[c]=-~a[c])>m&&(m++,r=c),m=r=``)&&r)
```
Saved 3 bytes twice thanks to @Arnauld. 97-byte solution that works with all non-newline characters:
```
(n,s)=>s.replace(/./g,(_,i)=>[...s].map((c,j)=>j%n-i||(o[c]=-~o[c])>m&&(m++,r=c),m=r=``,o={})&&r)
```
The previous 104-byte solution works with newline characters too:
```
(n,s)=>[...Array(n)].map((_,i)=>[...s].map((c,j)=>j%n-i||(o[c]=-~o[c])>m&&(m++,r=c),m=0,o={})&&r).join``
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~ 11 bytes
```
s@ZċþZMḢ$€ị
```
[Try it online!](https://tio.run/nexus/jelly#jVE7TgNBDO33FCnoCQF6LkCLRDqP7Q0DC0l2EthQ0uYWSIiGClFEikRBuMhykeXZg0LKzGg8z/bzm4@7dDb8Xm4@h@ft6vng5@mtXS@7dv3Rrt7hXGxev14OAS677qhHBRYVAzNAwVBwlGG2mL5z3hHGKI4NAdM/cpiEUklS7uIE1xVEy9FVvL6pbu/Gk2mdZvP7h2bxuGiQTvOJ1kxVLGsaxSqmWWRtJhERGXMczxMk9yCd7EM63Yc06CkG3iWBlEn94W4VLmsQZksIInA1qCEREoMCj1UU5UxBlJnV@CZnegEfykHx8/1ecAViL2BXgTqpoETwb3AkmKN2NhFbGlfBnYxhJ6od7spEajQxJqKWg7AUg35uHlm78vJebk3urHcydzTsbpn@Z5yX8TZGuewX "Jelly – TIO Nexus")
### How it works
```
s@ZċþZMḢ$€ị  Main link. Arguments: n (integer), s (string)
s@           Split swapped; split s into chunks of length n.
  Z          Zip/transpose, grouping characters that correspond to repetitions.
   ċþ        Count table; for each slice in the previous result, and each character
             in s, count the occurrences of the character in the group.
             This groups by character.
     Z       Zip/transpose to group by slice.
        $€   Map the two-link chain to the left over the groups.
      M        Find all maximal indices.
       Ḣ       Head; pick the first.
          ị  Index into s to retrieve the corresponding characters.
```
[Answer]
# Pyth, 11 bytes
```
meo/dNd.TcF
```
Takes input as `s,n` and outputs as a list of characters.
### Explanation
```
meo/dNd.TcF
         cFQ   Split s into chunks of length n.
       .T      Transpose.
m o/dNd        Sort characters in each string by frequency.
 e             Take the most common.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~16~~ 15 bytes
*Saved 1 byte thanks to @obarakon*
```
Ç=VëUZ)¬ñ!èZ o
```
14 bytes of code + 1 byte for the `-P` flag. [Try it online!](https://tio.run/nexus/japt#@3@43Tbs8OrQKM1Daw5vVDy8Ikoh//9/UwWl4tKC1KLkxJzMtKLE9MyczOKSzOTUioJMoEhKfnJmfmmxkoJuAAA "Japt – TIO Nexus")
### Ungolfed and explanation
```
 Ç   =VëUZ)¬ ñ!èZ o
UoZ{Z=VëUZ)q ñ!èZ o}
                          Implicit: U = input number, V = input string
Uo                        Create the range [0...U).
  Z{               }      Map each item Z by this function:
      VëUZ                  Take every U'th char of V, starting at index Z.
    Z=    )                 Call the result Z.
           q                Split the result into chars.
             ñ!èZ           Sort each char X by the number of occurrences of X in Z.
                  o         Pop; grab the last item (the most common char).
                      -P  Join the results (array of most common chars) into a string.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 132 bytes
```
from itertools import*
p,k=input()
b=l=len(p)
for i in combinations(p,k):
 x=sum(x!=y for x,y in zip(p,i*l))
 if x<b:b,o=x,i
print o
```
[Try it online!](https://tio.run/nexus/python2#FcoxDsMgDADAnVe4UyBi6xaVx@AqSFbBtoBIpJ8nyc03U5UC1PfaRXIDKiq1r0b9LxDr0a0zGHLIO1t1JkkFAmL4SkHi2Em42Tu7zcAI7Sh2vMIJzxv@fOaf9A60ZucMUILxwQ29hOHJaCXuIHMuMWJEjHHx7ws "Python 2 – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
Iôð«øvy{.¡é®èÙJðÜ
```
[Try it online!](https://tio.run/nexus/05ab1e#FYyxDQJRDEN7hkHcGLBFHHsFJMQkSNfQcUJCV1BQ/wz2caI0z8/JPNe39vGu3/V2P45nbeNTr3pcaq91zuV0gCcyEikqaaLAENMUTkGiQYAUka0hhNANBiX5zBvW6hq76bSdH/MP "05AB1E – TIO Nexus")
**Explanation**
```
Iô                 # split 2nd input in chunks of 1st input size
  ð«               # append a space to each
    ø              # zip
     vy            # for each y in the zipped list
       {           # sort the string
        .¡         # group into chunks of consecutive equal elements
          é        # sort by length
           ®è      # pop the last element (the longest)
             Ù     # remove duplicate characters from the string
              J    # join the stack into one string
               ðÜ  # remove any trailing spaces
```
[Answer]
# PHP, 245 Bytes
```
function p($c,$s,$r=""){global$a;if(($c-strlen($r)))foreach(str_split(count_chars($s,3))as$l)p($c,$s,$r.$l);else{for($v=str_pad("",$w=strlen($s),$r);$z<$w;)$t+=$v[$z]==$s[$z++];$a[$t][]=$r;}}p($argv[1],$argv[2]);ksort($a);echo join(" ",end($a));
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/279a92a6ac8467fb5220a8d697eab14d044b51d1)
## Breakdown
```
function p($c,$s,$r=""){
    global$a;
    if(($c-strlen($r)))  # make permutation
        foreach(str_split(count_chars($s,3))as$l)
            p($c,$s,$r.$l); #recursive
    else{
        for($v=str_pad("",$w=strlen($s),$r);$z<$w;) 
        $t+=$v[$z]==$s[$z++]; #compare strings
        $a[$t][]=$r; # insert value in array
    }
}
p($argv[1],$argv[2]); #start function with the input parameter
ksort($a); # sort result array 
echo join(" ",end($a)); #Output
```
[Answer]
## Haskell, 84 bytes
```
import Data.Lists
f n=map(argmax=<<(length.).flip(filter.(==))).transpose.chunksOf n
```
Usage example:
```
f 10 "bbbbacacbcedecdbbbdebdaedcecdabcebddbdcecebbeeaacdebdbebaebcecddadeeedbbdbbaeaaeebbedbeeaeedadeecbcd"
"ebbbdbeece"
```
Split input string into chunks of length `n`, transpose and ffind for each sublist the most frequent element.
[Answer]
# [Röda](https://github.com/fergusq/roda), 68 bytes
```
f s,n{seq 0,n-1|{|i|sort s/"",key={|c|x=s[i::n]x~=c,"";[#x]}|head}_}
```
[Try it online!](https://tio.run/nexus/roda#jVLBjtpADD2Tr7BSqQIpq8K2vdBm7/0GhCqPx4HpsplsJtmGEvrr1J7JUo6AmNjP7/mZiS8VhKI@BX6FZVE/rMbT6Mbg2w7CpzwvnvlYnkYahzJs3Hpdb4e/JRV5/m3zYdiexz2jPf88X17Q1XDKZqE5OFFyU@bw8AQ5jFD5FlzhwfpsNsO2hXUJm8ibu8VWsKYP@/mmmktts1pvP@aQF9BgG/hH3fGO21hZbhcLqUkph@9PSvGLbGZ9zdn5sgJUO8wkmKLH9yiCJoZgFE6xiXCMEzrBYFIq34mnGd1mwjWT0gDMReMC1L4Tgzc8OAu@75q@gz23vMg@q0Ak0zRGrf6D76giwWKo0FYRCtUtFK4oSJZGslzt9u7X8@Gl9s1rG7r@7fdw/HMclHkchBT6hluSkaoWd@7gQueIh8bpkJ6c74NSHYFzYnYnu3UgRXDeZV/u1AQSg6/3GmDjSIZn@cj9WINMyPHK48mSEhtLpAUriKRsWCNr0WpoJSO2LHJCY5mIWPnaTvsZeaFkGKd3aDhbLcHEVkhRSbGd2CBb0Vq5b0ms0YR1CETSsswkwylDrVmniBaIrDSrTEG1Jo2tGuq/UJwYtEEKs8dlWizUxUi/uGfXI21d3Jm0O@b2kejTEXkpvmKYZNO6GXOtRz7@Aw "Röda – TIO Nexus")
It's a function that prints the output without trailing newline.
This was inspired by [this answer](https://codegolf.stackexchange.com/a/113619/66323).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
►ȯΣz=¹¢Ṗ²
```
[Try it online!](https://tio.run/##ATkAxv9odXNr///ilrrIr86jej3CucKi4bmWwrL///8y/2FiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6eXg "Husk – Try It Online")
Zgarb-quality questions need a Zgarb language answer.
## Explanation
```
►ȯΣz=¹¢Ṗ²
     ¹ Ṗ² length n powerset of string
►ȯ        max by:
      ¢   repeating each subsequence infinitely
   z=¹    and check equality with the input
  Σ       sum the results
          this will return the most optimal pattern.
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-P`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
òV ÕËü ñÊ¬Ì
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVA&code=8lYg1cv8IPHKrMw&input=InN1cGVyY2FsaWZyYWdpbGlzdGljZXhwaWFsaWRvY2lvdXMiCjM)
```
òV ÕËü ñÊ¬Ì     :Implcit input of string U & integer V
òV              :Partitions of U of length V
   Õ            :Transpose
    Ë           :Map
     ü          :  Group & sort
       ñ        :  Sort by
        Ê       :    Length
         ¬      :  Join
          Ì     :  Last character
                :Implicitly join & output
```
]