Find the substring with the most 1's in a sequence
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 ┌─┘
⌈
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 array give 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.
Ruby, 42
f=->s,n{(0..s.size).max_by{|i|s[i,n].sum}}
Takes input by calling it, e.g.
f['01001010101101111011101001010100010101101010101010101101101010010110110110',5]
This compares substrings using their total ASCII value and returns the index of the maximum. I'm not sure if max_by
is required by the Ruby spec to be stable but it appears to be in the C implementation.
Python 2, 56
lambda s,l:max(range(len(s)),key=lambda i:sum(s[i:i+l]))
Accepts an array of integers, then the length.