Fold a List in Half

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]
++     
__________
[8 8 8 4]

Write a program or function that takes a list of integers as input and outputs that list folded.

This is a 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

Try it online!

• When you say integers, does this include zero or negative integers? – Neil Jul 31 '17 at 19:53
• @Neil Yes it does. – Sriotchilism O'Zaic Jul 31 '17 at 19:54
• @GrzegorzPuławski You should not sort the list. Any ordered collection is allowed, e.g. vector or array. – Sriotchilism O'Zaic Jul 31 '17 at 20:51
• @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. – Sriotchilism O'Zaic Aug 1 '17 at 14:05
• @WheatWizard I don't know about that, I've heard it's impossible to fold any list in half more than 7 times. – Carmeister Aug 2 '17 at 4:23

Python, 46 bytes

f=lambda l:l[1:]and[l+l[-1]]+f(l[1:-1])or l

Try it online!

Same length:

f=lambda l:l[1:]and[l.pop(0)+l.pop()]+f(l)or l

A much shorter solution works for even-length lists (30 bytes)

lambda l:[x+l.pop()for x in l]

Try it online!

I'm still trying to find a short way to correct it for odd length.

• Oh, I got terribly outgolfed ÷_÷ – Mr. Xcoder Jul 31 '17 at 20:10
• The "middle ground" solution f=lambda l:l[1:]and[l+l.pop()]+f(l[1:])or l is also the same length... – ETHproductions Jul 31 '17 at 20:42

05AB1E, 5 bytes

Code

2äR+

Uses the 05AB1E encoding. Try it online!

Explanation

2ä        # Split the list into two pieces
# Flatten the stack
R      # Reverse the second element from the list
+     # Vectorized addition

Emojicode, 203 bytes

🐋🍨🍇🐖🔢🍇🔂i⏩0➗🐔🐕2🍇😀🔡➕🍺🔲🐽🐕i🚂🍺🔲🐽🐕➖🐔🐕➕1i🚂10🍉🍊😛1🚮🐔🐕2🍇😀🔡🍺🔲🐽🐕➗🐔🐕2🚂10🍉🍉🍉

This was the most painful Emojicode answer to code for me. The unnecessary length :/

Try it online!

Japt, 2118 16 bytes

l
íUj°V/2V w)mx

Test it online!

Completely awful Slightly less awful thanks to @Oliver. BRB after I implement more built-ins and fix some bugs...

Gaia, 7 bytes

e2÷ev+†

Explanation

e        Eval the input (push the list).
2÷      Split it in half. The first half will be longer for an odd length.
e     Dump the two halves on the stack.
v    Reverse the second.
+†  Element-wise addition. If the first half has an extra element, it is simply appended.

Mathematica, 88 bytes

(d=Array[s[[#]]+s[[-#]]&,x=⌊t=Length[s=#]/2⌋];If[IntegerQ@t,d,d~AppendTo~s[[x+1]]])&

Mathematica 57 Bytes

(#+Reverse@#)[[;;d-1]]&@Insert[#,0,d=⌈Length@#/2⌉+1]&

Inserts a zero at the midpoint, adds the list to its reverse and takes the appropriate length.

Japt, 12 bytes

å@o +Y*(Z<Ul

Try it online! with the -Q flag to view the formatted array.

o(½*Ul)c)íU mx

Try it online!

Jelly, 7 bytes

œs2U2¦S

Try it online!

-2 thanks to ETHproductions...and me realizing before.

• ETH was right, 7 bytes – Mr. Xcoder Jul 31 '17 at 19:55
• @ETHproductions Thanks, although I had already figured out after I shut my computer down. – Erik the Outgolfer Aug 1 '17 at 8:11

JavaScript (Node.js), 53 bytes

x=>x.splice(0,x.length/2).map(y=>y+x.pop()).concat(x)

Try it online!

Another suggestion:

JavaScript (Node.js), 43 bytes

f=x=>x+x?[x.pop()+(0|x.shift()),...f(x)]:[]

Try it online!

R, 817068 57 bytes

function(l)c((l+rev(l))[1:(w=sum(l|1)/2)],l[w+1][!!w%%1])

Try it online!

anonymous function; returns the result.

Python 3, 101 bytes

lambda l:[sum(x)for x in zip(l[:len(l)//2],l[int(len(l)/2+.5):][::-1])]+[[],[l[len(l)//2]]][len(l)%2]

Try it online!

Python 3, 70 bytes

lambda l:[l[i]+l[~i]for i in range(len(l)//2)]+len(l)%2*[l[len(l)//2]]

Try it online!

JavaScript, 75 71 bytes

a=>a.slice(0,n=a.length/2).map(b=>b+a[--z],z=n*2).concat(n%1?a[n|0]:[])

Try it online

Saved 2 bytes thanks to ETHproductions

JavaScript (ES6), 41 bytes

f=a=>1/a?[a.shift()+a.pop(),...f(a)]:a

f=a=>1/a?[a.shift()+a.pop(),...f(a)]:a

console.log(JSON.stringify(f([1,2,3,4,5,6,7,8])));
console.log(JSON.stringify(f([1,2,3,4,5,6,7])));

MATL, 9 bytes

6L&)swtn

Try it online!

How it works

Given an array [a b c ... x y z], let [a z] be called the "crust" subarray and [b c ... y z] the "core" subarray.

The code consists in a loop that removes the crust, computes its sum, and moves the core to the top of the stack, ready for the next iteration. The loop condition is the number of elements in the core subarray

% Do...while
6L    %   Push [2 -1+1j]. As an index, this is interpreted as 2:end-1
&)    %   2-output reference indexing: pushes a subarray with the indexed
%   elements (core) and another with the ramaining elements (crust)
s     %   Sum of (crust) subarray
w     %   Swap. Moves the core subarray to the top
t     %   Duplicate
n     %   Number of elements.
% End (implicit). Procced with next iteration if top of the stack is
% nonzero; else exit
% Display stack (implicit)

WendyScript, 72 bytes

<<f=>(l){<<r=[]<<b=l.size#i:0->b/2r+=l[i]+l[b-i-1]?b%2!=0r+=l[(b/2)]/>r}

f([1,2,3,4,5,6,7,8]) // => [9,9,9,9]
f([1,2,3,4,5,6,7]) // => [8,8,8,4]

Try it online!

C# (.NET Core), 118 111 bytes

a=>a.Reverse().Zip(a,(c,d)=>c+d).Take(a.Length/2).Concat(a.Skip(a.Length/2).Take(a.Length%2))

Byte count also includes

using System.Linq;

Try it online!

As input please use numbers separated either with commas (,) or space. Explanation:

a =>                                  // Take one input parameter (array)
a.Reverse()                           // Reverse it
.Zip(a, (c, d) => c + d)              // Take every corresponding member of reversed
//    and original, and add them together
.Take(a.Length / 2)                   // Get first half of the collection
.Concat(                              // Add another collection
a.Skip(a.Length / 2)              // Take input and leave out first half of it
.Take(a.Length % 2)               // If length is odd, take first element (so the middle)
//    otherwise create an empty collection
);
• Can you save bytes by setting the length to a variable and switching to an explicit return? – TheLethalCoder Aug 1 '17 at 8:07
• @TheLethalCoder unfortunately it's longer – Grzegorz Puławski Aug 1 '17 at 8:33

Perl, 42 38 chars

sub f{@a=map{$+pop}splice@,0,@/2;@a,@} sub f{(map{$_+pop}splice@_,0,@_/2),@_}

Try for example like so:

Try it online!