Given an array of values and a number of beggars, you are supposed to return an array with the sum of what each beggar brings home, assuming they all take regular turns, from the first to the last.
For example: [1,2,3,4,5]
for 2
beggars will return a result of [9,6]
, as the first one takes [1,3,5]
, the second collects [2,4]
.
The same array with 3
beggars would have in turn have produced a better outcome for the second beggar: [5,7,3]
, as they will respectively take [1,4]
, [2,5]
and [3]
.
Also note that not all beggars have to take the same amount of "offers", meaning that the length of the array is not necessarily a multiple of n; length can be even shorter, in which case the last beggars will, of course, take nothing (0)
.
This challenge comes from GiacomoSorbi on CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (10)
I'm not sure as I can't test it out here but I think that this line
Could have been written as
Even if it is a small change, I find it easier to read.
Thank you for your response, it can also be changed as :
I forgot this function, and it is really helpful and permits to avoid the hackish code I wrote above.
Thanks!
My solution in js
A simple perl solution consuming the array
Or, using Tye::Cycle from CPAN a very clean solution:
Going functional in Perl:
An computation-on-demand approach in js
Elm
Tests
In Go!
amts below could also be a
[]float64
if required. All posted examples were with ints so that is what I used.Go Playground Example
Could you remind me what is the concept of point free style? I know I heard it somewhere when playing with Haskell but I can't remember haha!