24
1
Inspired by a question at Stack Overflow.
Given a non-empty array of integers x
and a positive integer n
, compute the sum of each sliding block of length n
along the array x
, circularly filling the missing values at the left with values from the right as follows:
- the first block contains the first entry of
x
, preceded byn-1
circularly shifted entries; - the second block has the first and second entries of
x
, preceded byn-2
circularly shifted entries; and so on.
The output array y
has the same size as x
. It is possible for n
to exceed the length of x
, and then the values of x
are circularly reused several times.
Examples
Example 1 (values are reused only once)
x = [2, 4, -3, 0, -4]
n = 3
give as output
y = [-2, 2, 3, 1, -7]
where
-2
is the sum of the block[0, -4, 2]
(the first two values come from the circular shifting)2
is the sum of[-4, 2, 4]
(the first value comes from the circular shifting)3
is the sum of[2, 4, -3]
(no circular shifting necessary anymore)1
is the sum of[4, -3, 0]
-7
is the sum of[-3, 0, -4]
.
Example 2 (values are reused several times)
x = [1, 2]
n = 5
give
y = [7, 8]
where
7
is the sum of the block[1, 2, 1, 2, 1]
(the first four values have been circularly reused)8
is the sum of the block[2, 1, 2, 1, 2]
(the first three values have been circularly reused)
Additional rules
- The algorithm should work for arrays of arbitrary size and for arbitrary integer values. It is acceptable if the program is limited by data type or memory restrictions; but positive as well as negative integer values must be handled.
- Input/output can be taken/produced by any reasonable means.
- Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
- Shortest code in bytes wins.
Test cases
x, n, -> y
[2, 4, -3, 0, -4], 3 -> [-2, 2, 3, 1, -7]
[1, 2], 5 -> [7, 8]
[2], 7 -> [14]
[-5, 4, 0, 1, 0, -10, -4], 4 -> [-19, -15, -5, 0, 5, -9, -13]
[-5, 4, 0, 1, 0, -10, -4], 1 -> [-5, 4, 0, 1, 0, -10, -4]
[-2, -1, 0, 1, 2, 3], 5 -> [4, 3, 2, 1, 0, 5]
[-10, 0, 10], 4 -> [-10, 0, 10]
6Bah, why did you have to use preceding entries? – Neil – 2017-08-27T10:54:33.447