[Question]
  [
### Intro
We have had [histograms](https://codegolf.stackexchange.com/questions/48216/n-gram-histogram) and [counting](https://codegolf.stackexchange.com/questions/45257/counting-k-mers), but not listing all of them.
Every year, [Dyalog Ltd.](http://www.dyalog.com/) holds a student competition. [The challenge there](http://www.dyalog.com/student-competition.htm) is to write *good* APL code. This is a language agnostic [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") edition of this year's sixth problem.
I have explicit permission to post this challenge here from the original author of the competition. Feel free to verify by following the [provided link](http://www.dyalog.com/student-competition.htm) and contacting the author.
### Problem
The term k-mer typically refers to all the possible substrings of length *k* that are contained in a string. In computational genomics, k-mers refer to all the possible subsequences (of length *k*) from a read obtained through DNA Sequencing. Write a function/program that takes a string and *k* (the substring
length) and returns/outputs a vector of the k-mers of the original string.
### Examples
`[4,"ATCGAAGGTCGT"]` → `["ATCG","TCGA","CGAA","GAAG","AAGG","AGGT","GGTC","GTCG","TCGT"]`
*k* > string length? Return nothing/any empty result:  
`[4,"AC"]` → `[]` or `""` or `[""]`
  
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 [byte](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṡ
```
Jelly has a single byte dyadic atom for this very operation
**[Try it online!](https://tio.run/nexus/jelly#@/9w58L/h5dH/v@v5Bji7O7o6O4OpEKU/psAAA "Jelly – TIO Nexus")** (the footer splits the resulting list with newlines, to avoid a mushed representation being printed.)
[Answer]
# Octave, 28 bytes
```
@(N,s)s((1:N)+(0:nnz(s)-N)')
```
[Try it online!](https://tio.run/nexus/octave#@@@g4adTrFmsoWFo5aeprWFglZdXpVGsqeunqa75nysxr1jDREfJMcTZ3dHR3R1IhShpcv0HAA "Octave – TIO Nexus")
For k > string length works in Octave 4.2.1-windows but in tio (Octave 4.0.3) doesn't work.
Creates numeric indexes of consecutive elements and index the string by it.
```
s= "ATCGAAGGTCGT"
N = 4
idx = (1:N)+(0:nnz(s)-N)'
 =
    1    2    3    4
    2    3    4    5
    3    4    5    6
    4    5    6    7
    5    6    7    8
    6    7    8    9
    7    8    9   10
    8    9   10   11
    9   10   11   12
s(idx) =
ATCG
TCGA
CGAA
GAAG
AAGG
AGGT
GGTC
GTCG
TCGT
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
Code:
```
Œù
```
Explanation:
```
Œ      # Get all substrings of the input
 ù     # Only keep the substrings of length the second input
```
Uses the [**05AB1E** encoding](https://github.com/Adriandmen/05AB1E/blob/master/docs/code-page.md). 
[Try it online!](https://tio.run/nexus/05ab1e#@3900uGd//87Ojm7uLq5cxkDAA "05AB1E – TIO Nexus")
[Answer]
# C (GCC on POSIX), ~~67~~ ~~66~~ 63 bytes
*-3 bytes thanks to @LeakyNun!*
```
f(i,s,j)char*s;{for(;j+i<=strlen(s);puts(""))write(1,s+j++,i);}
```
[Try it online!](https://tio.run/nexus/c-gcc#@5@mkalTrJOlmZyRWKRVbF2dll@kYZ2lnWljW1xSlJOap1GsaV1QWlKsoaSkqVlelFmSqmGoU6ydpa2tk6lpXfs/NzEzTyNZpwxigFYZ0ASNxJL8TI2yaMNYTZ2yaKNYkLL/Jv8dQ5zdHR3d3YFUCAA "C (gcc) – TIO Nexus")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~47 45~~ 42 bytes
-3 bytes thanks to ovs (use Python 3's unpacking to reuse `a[n-1:]` at the tail.)
```
f=lambda a,n:a[n-1:]and[a[:n],*f(a[1:],n)]
```
A recursive function taking the string, `a`, and the slice length, `n`, and returning a list of the slices or an empty string.
`a[n-1:]` takes a slice of the current string from the n-1th (0-indexed) element onward to test whether there are enough elements remaining (an empty string is falsey in Python) - this is shorter than the equivalent `len(a)>=n`.
* If there are enough elements a list is constructed, `[...]`, with the first `n` elements of the string, `a[:n]`, and the unpacked result of calling the function again, `*f(...)`, with a dequeued version of the current input (without the first element), `a[1:]`.
* If there are not enough elements the tail of the recursion is reached when `a[n-1:]` is returned (in this case an empty string).
**[Try it online!](https://tio.run/nexus/python3#@59mm5OYm5SSqJCok2eVGJ2na2gVm5iXEp0YbZUXq6OVppEYDRTRydOM/V9QlJlXopGmoeSRmpOT71KZmJOfrqRjrKn5HwA)**
---
**45** for Python 2 or 3 with:
```
f=lambda a,n:a[n-1:]and[a[:n]]+f(a[1:],n)or[]
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
s₎ᶠ
```
[Try it online!](https://tio.run/nexus/brachylog2#@1/8qKnv4bYF//9HKzmGOLs7Orq7A6kQJR2T2P9RAA "Brachylog – TIO Nexus")
## Specs:
* Input: `["ATCGAAGGTCGT",4]`
* Argument: `Z`
* Output: `Z = ["ATCG","TCGA","CGAA","GAAG","AAGG","AGGT","GGTC","GTCG","TCGT"]`
## How it works
```
s₎ᶠ
s    Output is a substring of first element of input,
 ₎   with length specified by second element of input.
  ᶠ  Find all solutions.
```
[Answer]
# [J](http://jsoftware.com/), 2 bytes
```
,\
```
It is not a complete program, but a function with an operator.
Call it as such:
```
echo 4 ,\ 'ATCGAAGGTCGT'
```
[Try it online!](https://tio.run/nexus/j#@5@anJGvYKKgE6Og7hji7O7o6O4OpELU//8HAA)
## How it works
The operator (called "conjunction") `\` (named "[infix](http://code.jsoftware.com/wiki/Vocabulary/bslash#dyadic)") is used as such:
> 
> `(x u\ y)` applies verb `u` to successive parts of list `y` (called infixes). 
> 
> 
> 
The function (called "verb") `u` in this case is the function `,` which is a simple "[append](http://code.jsoftware.com/wiki/Vocabulary/comma#dyadic)" function:
> 
> Creates an array containing the items of `x` followed by the items of `y`.
> 
> 
> 
[Answer]
# Mathematica, 21 bytes
```
##~StringPartition~1&
```
Anonymous function. Takes a string and a number (in that order) as input and returns a list of strings as output.
[Answer]
# R, ~~65~~ 61 bytes
*-2 bytes thanks to MickyT*
*-2 bytes by changing the indexing*
returns an anonymous function.
```
function(s,n,x=nchar(s))`if`(n>x,'',substring(s,x:n-n+1,n:x))
```
`substring` cycles through the indices (as opposed to `substr` which does not), and if the starting index is less than 1, it defaults to `1` instead, so it checks and returns the empty string.
`x:n-n+1` is equivalent to `1:(x-n+1)` since `:` takes precedence over sums/differences
[Try it online!](https://tio.run/nexus/r#Fco7CoAwDADQ4yTBOAhOQj1LP5raJUJjobevdHrLEzekafrKq2is3J2mJ1Q0Il/Eo56dAdhatK8WzTMdfdVlmxINQQgxXbdk4J3GDw)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 2 bytes
```
.:
```
It is not a complete program, but a built-in function.
Call it as such:
```
.:"ATCGAAGGTCGT"4
```
[Try it online!](http://pyth.herokuapp.com/?code=.%3A%22ATCGAAGGTCGT%224&debug=0)
Full program:
```
.:.*
```
[Try it online!](http://pyth.herokuapp.com/?code=.%3A.%2a&input=%22ATCGAAGGTCGT%22%2C4&debug=0)
(The `.*` is splat.)
[Answer]
# [Jellyfish](https://github.com/iatorm/jellyfish), 7 bytes
```
p
_I
\i
```
[Try it online!](https://tio.run/nexus/jellyfish#@1/AFe/JFZP5/79jiLO7o6O7O5AK4TIBAA "Jellyfish – TIO Nexus")
## How it works
In linear: `p(\(I,i))`, where `p` is print and `\` gets the required substrings.
`I` is the raw first input while `i` is the evaluated second input.
In Jellyfish, every function and operator gets two arguments, one from the right, and one from the bottom. Here, the function `p` gets the argument from the output of `_`, which is required if we are to use the operator `\` to get substrings.
[Answer]
# [Python 2](https://docs.python.org/2/), 54 bytes
```
lambda x,n:map(''.join,zip(*[x[b:]for b in range(n)]))
```
[Try it online!](https://tio.run/nexus/python2#S1OwVYj5n5OYm5SSqFChk2eVm1igoa6ul5WfmadTlVmgoRVdEZ1kFZuWX6SQpJCZp1CUmJeeqpGnGaup@b@gKDOvRCFNQ8nRydnF1c3dQ0lHwUTzPwA "Python 2 – TIO Nexus")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 92 bytes
```
void f(String s,int n){for(int i=n;i<=s.length();)System.out.println(s.substring(i-n,i++));}
```
[Try it online!](https://tio.run/nexus/java-openjdk#LY6xDoJAEERr@YoL1W3Eq@xOCmJBZQWdsQAE3ORYCLtoDOHb8USrN83Mm2EqHVaqcgWzuhRI8/rs8a4ancmI1CqOkEQRzE0/6m/EmCyeYjauplYeGixkb5a6M/0kZvAlcaTZ8FTyNqHxQBHu9wB2WYefj6UQj03Veevfdr2pYmwZ5mBH9Wv7o8E0Okzyc5okaeqRh9ERbLAEy/oB "Java (OpenJDK 8) – TIO Nexus")
[Answer]
## Clojure, 19 bytes
Well [this](https://clojuredocs.org/clojure.core/partition) is handy:
```
#(partition % 1 %2)
```
Examples:
```
(def f #(partition % 1 %2))
(println [(f 4 "ATCGAAGGTCGT")
          (f 4 "abc")])
[((A T C G) (T C G A) (C G A A) (G A A G) (A A G G) (A G G T) (G G T C) (G T C G) (T C G T))
 ()]
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 4 bytes
```
{ew}
```
Anonymous block that expects the arguments on the stack and leaves the result on the stack after.
[Try it online!](https://tio.run/nexus/cjam#K6z7X51aXvu/ruC/iYKSY4izu6OjuzuQClECAA "CJam – TIO Nexus")
`ew` is a built-in that does exactly what is required.
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~41~~ 38 bytes
```
.*$
$*
!&`(.)+(?=.*¶(?<-1>.)+(?(1)¶)$)
```
[Try it online!](https://tio.run/nexus/retina#@6@npcKlosWlqJagoaeprWFvq6d1aJuGvY2uoR2Yr2GoeWibporm//@OIc7ujo7u7kAqhMsEAA "Retina – TIO Nexus")
Takes the string and count on separate lines. The first two lines are used to convert the count from decimal to unary, so if unary input is acceptable then the byte count would be reduced to ~~34~~ 31. Edit: Saved 3 bytes thanks to @FryAmTheEggman. Or, if you prefer, a 48-byte version that handles newlines in the string, although that does produce confusing output:
```
.*$
$*
!&`(\S|\s)+(?=[\S\s]*¶(?<-1>.)+(?(1)$.)$)
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/) with Image Package, 29 bytes
```
@(s,n)[im2col(+s, [1 n])' '']
```
[Try it online!](https://tio.run/nexus/octave#@@@gUayTpxmdmWuUnJ@joV2soxBtqJAXq6muoK4e@z8xr1hDPTEpOSU1LV1dR8FY8z8A "Octave – TIO Nexus")
### Explanation
The function `im2col(m,b)` takes a matrix `m`, extracts blocks of size `b` from it, and arranges them as columns. By default blocks are sliding (as opposed to distinct). Here the matrix `m` is a row vector of the ASCII codes of the input string `s` (this is done as `+s`, which is shorter than the standard `double(s)`), and the size `b` is `[1 n]` to obtain horizontally sliding blocks of `n` elements.
The result is transposed (using complex-conjugate transpose `'`, which is shorter than transpose `.'`) to turn the columns into rows, and then it is converted back to char (`[... '']`, which is shorter than the standard `char(...)`).
[Answer]
# oK, 2 bytes
```
':
```
oK has a [sliding window](https://github.com/JohnEarnest/ok/blob/gh-pages/docs/Manual.md#window) operator!
[Answer]
# [Python 3](https://docs.python.org/3/), 49 bytes
```
f=lambda a,n:[a[i:i+n]for i in range(len(a)-n+1)]
```
[Try it online!](https://tio.run/nexus/python3#@59mm5OYm5SSqJCok2cVnRidaZWpnRebll@kkKmQmadQlJiXnqqRk5qnkaipm6dtqBn7v6AoM69EI01DySM1JyffpTIxJz9dScdYU/P/fwA "Python 3 – TIO Nexus")
A non-recursive solution, albeit not shorter.
Compatible with Python 2.
[Answer]
# PHP, 75 Bytes
[Online Version](http://sandbox.onlinephpfunctions.com/code/41ec5bfef257284cf51c44b118c18f73b0449e10)
```
for([,$n,$s]=$argv;$i+$n-1<strlen($s);)$r[]=substr($s,$i++,$n);print_r($r);
```
80 Bytes without double values
```
for([,$n,$s]=$argv;$i+$n-1<strlen($s);)$r[$p=substr($s,$i++,$n)]=$p;print_r($r);
```
[Answer]
## Haskell, 39 bytes
```
n#s|length s<n=[]|1<2=take n s:n#tail s
```
Usage example: `4 # "ABCDEF"` -> `["ABCD","BCDE","CDEF"]`. [Try it online!](https://tio.run/nexus/haskell#@5@nXFyTk5qXXpKhUGyTZxsdW2NoY2RbkpidqpCnUGyVp1ySmJmjUPw/NzEzT8FWISWfS0GhoCgzr0RBRcFYQVlBydHJ2cXVzc3D00sJU0rpPwA "Haskell – TIO Nexus")
A simple recursion that keeps the first `n` chars of the input string an continues with the tail of the string as long as its length is not less than `n`.
[Answer]
**Microsoft Sql Server, 199 bytes**
```
create function dbo.f(@s nvarchar(max),@ int)returns table as return
with v as(select 2 p,left(@s,@)g where len(@s)>=@ union all
select p+1,substring(@s,p,@)from v where len(@s)>p-2+@)select g from v
```
[Check it.](http://rextester.com/NNQ87039)
[Answer]
**PowerShell, 70 bytes**
```
$b={$c,$s=$args;[regex]::matches($s,"(?=(.{$c}))")|%{''+$_.groups[1]}}
```
[Try it online!](https://tio.run/nexus/powershell#DYtBCsMgEAC/EmSbVSqBQk8JUqQHP@BNRJJg7aWkuC0UUt9uPA0MMxUWtcMqgRTMOdHkckzx58fxNX/WZyQOJBm/KT60rAjBxP@0I54hDClv3ze5iy@lwvYghRIn1PZutDamwTahLbaBQVAOeA9Ld@0gCM9KPQA "PowerShell – TIO Nexus")
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 7 bytes
```
infixes
```
[Try it online!](https://tio.run/nexus/stacked#U3cMcXZ3dHR3B1Ih6gom/zPz0jIrUov/55eW/AcA "Stacked – TIO Nexus")
Pretty standard. Without this builtin, it becomes 20 bytes:
```
{%x#'y-#+:>y#-#>x\#}
```
Which is:
```
{%x#'y-#+:>y#-#>x\#}
{%                 }   dyad; first arg: x, second arg: y
  x#'                  length of x (the array)
     y-                minus y (the skew)
       #+              plus 1
         :>            range [x, y]
           y#-         y minus 1
              #>       range from [[x, y], [x, y] + y]
                x\#    get indices from x
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 3 bytes
```
YC!
```
[Try it online!](https://tio.run/nexus/matl#@x/prPj/v7pjiLO7o6O7O5AKUecyAQA "MATL – TIO Nexus")
### Explanation
```
YC   % Sliding blocks of input string with input size, arranged as columns
!    % Transpose
```
[Answer]
# C# 89 bytes
```
void a(string s,int n){for(int i=n;i<=s.Length;)Console.WriteLine(s.Substring(i++-n,n));}
```
[Try it online!](https://tio.run/nexus/cs-mono#Lc4xD4IwEAXguf0VDVMbkMmtMhAGFpwgcTAOBSteglfDFRND@O0IwnRveC/fDQTYivJL3r405@@h7qARTWeIRMpHzsgbD838cXAXRpLv1z5FgF6gGh@ul2uEBDWcEooLi61/apU5JNfZ@NKDtwWglRSXQ73tJYThASNUSk8z280NEn/obAB363oTpm9JcbY8w4wM0irL0zTPl1MF0VFpziY@zT8 "C# (Mono) – TIO Nexus")
Best method I could find in C# is basically the same as [Java](https://codegolf.stackexchange.com/a/118227/44998)
[Answer]
# Ruby, ~~48~~ 46 bytes
```
->(s,k){0.upto(s.size-k).map{|i|s[i..i+k-1]}}
```
No particular tricks, just a stabby-lambda defining a function that pulls the required substring from each valid starting point.
Saved two bytes, since there doesn't seem to be a need to store the lambda.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 16 bytes
```
òÀ|ly0Ïp
"_xòkVp
```
Not terribly well golfed I'm afraid, struggling with "delete the string if k > len(str)". Input is in the file, k is an argument. Golfing before explanation
[Try it online!](https://tio.run/nexus/v#@3940@GGmpxKg8P9BVxK8RWHN2WHFfz/n5iUnJL63wgA "V – TIO Nexus")
[Answer]
# Standard ML (mosml), ~~109~~ ~~65~~ 61 bytes
```
fun f(n,x)=if n>length(x)then[]else List.take(x,n)::f(n,tl x)
```
Takes a number and a character list (quite a common alternative to strings in the SML world). (Really works on all lists of course.)
Usage:
```
- f(3,explode("ABCDEFGH"));
> val it =
    [[#"A", #"B", #"C"], [#"B", #"C", #"D"], [#"C", #"D", #"E"],
     [#"D", #"E", #"F"], [#"E", #"F", #"G"], [#"F", #"G", #"H"]] :
  char list list
- f(7, explode("ABCD"));
> val it = [] : char list list
```
Changelog:
* Right, there is a standard library.. (-44 bytes)
* Change comparison and nil to [] as suggested (-4 bytes)
[Answer]
## JavaScript (Firefox 30-57), 51 bytes
```
(s,n,t='')=>[for(c of s)if((t+=c)[n-1])t.slice(-n)]
```
64 bytes in ES6:
```
(s,n,t=s.slice(0,--n))=>[...s.slice(n)].map(c=>(t+=c).slice(~n))
```
]