24
1
We are going to fold a list of integers. The procedure to do so is as follows, If the list is of even length, make a list of half of its length where the nth item of the new list is the sum of the nth item of the old list and the nth-to-last item of the old list. For example if we had the list
[1 2 3 4 5 6 7 8]
We would fold it like so
[8 7 6 5]
+[1 2 3 4]
__________
[9 9 9 9]
If the list is of odd length, to fold it we first remove the middle item, fold it as if it were even and the append the middle item to the result.
For example if we had the list
[1 2 3 4 5 6 7]
We would fold it like so
[7 6 5]
+[1 2 3]
__________
[8 8 8]
++ [4]
__________
[8 8 8 4]
Task
Write a program or function that takes a list of integers as input and outputs that list folded.
This is a code-golf question so answers will be scored in bytes, with fewer bytes being better.
Sample implementation
Here's an implementation in Haskell that defines a function f
that performs a fold.
f(a:b@(_:_))=a+last b:f(init b)
f x=x
When you say integers, does this include zero or negative integers? – Neil – 2017-07-31T19:53:41.343
1@Neil Yes it does. – Post Rock Garf Hunter – 2017-07-31T19:54:02.583
Are we supposed to sort the list, or just take what we're given? Also is any type of collection allowed, or just a list (for languages with multiple types of collections)? – Grzegorz Puławski – 2017-07-31T20:40:49.223
2@GrzegorzPuławski You should not sort the list. Any ordered collection is allowed, e.g. vector or array. – Post Rock Garf Hunter – 2017-07-31T20:51:00.623
Now make it recursive and see how many times you can fold a list in half before you overflow. – David Starkey – 2017-08-01T13:49:36.657
1@DavidStarkey Most reasonable lists will not overflow with a reasonable amount of memory. Folding doesn't actually increase the sum so lists will converge to a singleton of the sum of the original list. – Post Rock Garf Hunter – 2017-08-01T14:05:47.070
@WheatWizard That's what I meant, keep folding until one of the items in the list overflows. Sure it needs larger lists than your examples, but that's kinda the point. – David Starkey – 2017-08-01T14:49:36.867
2@WheatWizard I don't know about that, I've heard it's impossible to fold any list in half more than 7 times. – Carmeister – 2017-08-02T04:23:19.227
I would find it easier to visualize and follow if the odd length example just kept the [4] as a fourth column, in between the two rows. – Sparr – 2019-03-10T20:00:48.577