Dyalog APL, 11
(-∘1+⍳⌈/)+/
Try it here. Usage:
f ← (-∘1+⍳⌈/)+/
4 f 0 1 1 0 1 1 1 0 0 0 0 1 1
1
Explanation
This is a dyadic (meaning binary) function that takes the substring length from the left, and the sequence from the right. Its structure is the following:
┌───┴────┐
┌─┴──┐ /
∘ ┌─┼─┐ ┌─┘
┌┴┐ + ⍳ / +
- 1 ┌─┘
⌈
So, the topmost branch is a hook of two functions, +/
and -∘1+⍳⌈/
, which means that given inputs n
and x
, we evaluate n +/ x
(the sums of length-n
substrings of x
) and feed that to -∘1+⍳⌈/
. This function, on the other hand, is a hook of -∘1
(subtract 1) and the fork +⍳⌈/
. This means that the result of n +/ x
above (let's call it y
) is given to both +
(which is the identity when only one argument is given) and ⌈/
(which finds the maximum of y
), and the results are given to ⍳
, which returns the first index of the right argument in the left. We have to subtract 1 from this, since APL lists are 1-indexed.Explanation by explosion:
(-∘1+⍳⌈/)+/
( )+/ ⍝ Take sums of substrings of given length, and feed to function in parentheses
+ ⌈/ ⍝ The array of sums itself, and its maximum
⍳ ⍝ First index of right argument in left
-∘1 ⍝ Subtract 1 (APL arrays are 1-indexed)
As an example, let's take 4
and 0 1 1 0 1 1 1 0
as inputs. First we apply the function +/
to them and get 2 3 3 3 3
. Then, +
and ⌈/
applied to this listarray give the list itself and 3
, and 2 3 3 3 3 ⍳ 3
evaluates to 2
, since 3
first occurs as the second element. We subtract 1
and get 1
as the final result.