39
\$\begingroup\$

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 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!

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

58 Answers 58

11
\$\begingroup\$

Python, 46 bytes

f=lambda l:l[1:]and[l[0]+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.

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

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!

\$\endgroup\$
8
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

Japt, 21 18 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...

\$\endgroup\$
0
3
\$\begingroup\$

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.
\$\endgroup\$
3
\$\begingroup\$

Jelly, 7 bytes

ล“s2U2ยฆS

Try it online!

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

\$\endgroup\$
2
  • \$\begingroup\$ ETH was right, 7 bytes \$\endgroup\$
    – Mr. Xcoder
    Jul 31, 2017 at 19:55
  • \$\begingroup\$ @ETHproductions Thanks, although I had already figured out after I shut my computer down. \$\endgroup\$ Aug 1, 2017 at 8:11
3
\$\begingroup\$

C (gcc), 55 41 bytes

f(_,l)int*_;{for(;l--;*_+++=l?_[l--]:0);}

Try it online!

Overwrites the first \$\left\lfloor\frac{l}{2}\right\rfloor\$ entries of the input array.

C (gcc), 46 bytes

f(_,l)int*_;{_=l>1?*_+=_[l-1],1+f(_+1,l-2):l;}

Try it online!

Additionally returns the length \$\left\lceil\frac{l}{2}\right\rceil\$ of the output.

\$\endgroup\$
3
\$\begingroup\$

Vyxal, 4 bytes

Iรทแน˜+

Try it Online!

I    # Halve the list
 รท   # Push each half
  แน˜  # Reverse the second half
   + # Add them together (vectorising)
\$\endgroup\$
2
3
\$\begingroup\$

Pip, 14 12 bytes

YCHa;@y+Ry@1

-2 Thanks to DLosc!

How?

YCHa;@y+Ry@1  : One arg; list
   a          : First input
 CH           : Chop iterable into 2 pieces of roughly equal length
Y             : Yank value
         y    : The two halves
          @1  : Get item/slice at index 1; The second half
        R     : Reverse
       +      : Add with
      y       : The two halves
     @        : Get item at index 0; The first half

Try It Online!

\$\endgroup\$
2
  • \$\begingroup\$ @DLosc that was so obvious I don't know how I missed it lol, thanks for the spot! \$\endgroup\$
    – Baby_Boy
    Jan 20, 2023 at 14:07
  • \$\begingroup\$ @DLosc I see what you mean, it made sense when I wrote it, should be fixed now! :) \$\endgroup\$
    – Baby_Boy
    Jan 21, 2023 at 7:45
3
\$\begingroup\$

Fig, \$23\log_{256}(96)\approx\$ 18.932 bytes

J+t_HLxxt_HLx$xs_HLxtHL

Try it online!

\$-26\log_{256}(96)\approx21.401\$ thanks to Seggan

First time using Fig. Any golfing tips are welcome.

Explanation (outdated):

fw+[yfy$fy$fyx[yfy$fy$fy$x?h%1HLx[]yfy$fy$fyx]yW1
   [yfy$fy$fyx                                    First Mid
  +                                               Add
              [yfy$fy$fy$x                        Second Mid
fw                                                Concat
                          ?                       If
                           h%1HLx                 List length is odd,
                                 []yfy$fy$fyx     Mid
                                             ]yW1 Else Empty list
\$\endgroup\$
2
  • 1
    \$\begingroup\$ the entire if (?h%1HLx[]yfy$fy$fyx]yW1) can be replaced with s_HLxtHL (take half, drop half; will return empty list if even, middle item if odd). fw can be J \$\endgroup\$
    – Seggan
    Jan 19, 2023 at 15:28
  • 1
    \$\begingroup\$ J+t_HLxxt_HLx$xs_HLxtHL works \$\endgroup\$
    – Seggan
    Jan 19, 2023 at 15:37
3
\$\begingroup\$

Thunno 2, 7 5 bytes

2แบ†แบธr+

Attempt This Online!

2แบ†แบธr+ # implicit input
2แบ†    # split list in half
  แบธ   # push both halves to the stack
   r  # reverse top one
    + # vectorized addition
      # implicit output
\$\endgroup\$
2
\$\begingroup\$

Mathematica, 88 bytes

(d=Array[s[[#]]+s[[-#]]&,x=โŒŠt=Length[s=#]/2โŒ‹];If[IntegerQ@t,d,d~AppendTo~s[[x+1]]])&
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
0
2
\$\begingroup\$

JavaScript (ES6), 41 bytes

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

f=a=>1/a[1]?[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])));

\$\endgroup\$
2
\$\begingroup\$

Japt, 12 bytes

รฅ@o +Y*(Z<Ul

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

Alternate solution, 14 bytes

o(ยฝ*Ul)c)รญU mx

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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!

\$\endgroup\$
1
  • \$\begingroup\$ (0|x.shift()) => ~~x.shift() \$\endgroup\$
    – l4m2
    Jan 17, 2023 at 14:29
2
\$\begingroup\$

R, 81 70 68 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.

\$\endgroup\$
2
\$\begingroup\$

Zsh, 55 bytes

If the answer must be put to stdout, but output whitespace is flexible, 55 bytes:

for ((;++i<=#/2;))<<<$[$@[i]+$@[-i]]
<<<$@[#%2*(1+#/2)]

Try it online!


If the output must be stored in an array, 53 bytes: (We can't use this method in place of the above because of <<<...[--i].... The here-string forces a subshell, so the decremented value of i never makes it out.)

for n ($@[1,#/2])y+=($[$@[--i]+n])
y+=$@[#%2*(1+#/2)]

Try it online!

If the answer must be output in one line separated by spaces, then append <<<$y for a 6 byte penalty.


Zsh arrays are indexed from the start starting at 1, or from the end starting at -1. So what happens if you attempt to index at 0? Well, nothing! We take advantage of that here to only output the middle number based on a parity check:

$@[#%2*(1+#/2)]
   #      #       # parameter count
       (1+#/2)    # index of the middle element when count is odd
   #%2*(1+#/2)    # multiply by 0 if even, or 1 if odd
$@[           ]   # Index the parameter array
\$\endgroup\$
2
\$\begingroup\$

Factor, 35 bytes

[ halves reverse 0 pad-longest v+ ]

Try it online!

Explanation

It's a quotation (anonymous function) that takes a sequence from the data stack and leaves a sequence on the data stack. Assuming { 1 2 3 4 5 6 7 } is on the data stack when this quotation is called...

Snippet Comment Data stack (top on right)
halves Split a sequence in half { 1 2 3 } { 4 5 6 7 }
reverse Reverse a sequence { 1 2 3 } { 7 6 5 4 }
0 pad-longest Pad the shorter of two sequences with 0s until it's the same length as the longer sequence { 1 2 3 0 } { 7 6 5 4 }
v+ Vector addition; element-wise addition between two sequences { 8 8 8 4 }
\$\endgroup\$
2
\$\begingroup\$

Go, 115 bytes

func(x[]int)(o[]int){s:=len(x)
for i:=range x[:s/2]{o=append(o,x[i]+x[s-i-1])}
if s%2>0{o=append(o,x[s/2])}
return}

Attempt This Online!

Generic with custom operator, 136 bytes

func f[T any](x[]T,O func(T,T)T)(o[]T){s:=len(x)
for i:=range x[:s/2]{o=append(o,O(x[i],x[s-i-1]))}
if s%2>0{o=append(o,x[s/2])}
return}

Attempt This Online!

\$\endgroup\$
2
\$\begingroup\$

Curry (PAKCS), 34 bytes

f(a:b++[c])=a+c:f b
f x@([]?[_])=x

Attempt This Online!

Based on the sample implementation in Haskell.

\$\endgroup\$
2
\$\begingroup\$

C (gcc), 62 bytes 60 bytes

-2 bytes thanks to @ceilingcat

i;f(v,l)int*v;{for(i=0;i<l/2;++i)v[i]+=v[l+~i];return~l/-2;}

f is a function taking vector (v) and length (l) as arguments. It modifies the vector and returns the new length.

Try It Online!

How it works:

i;
f(v,l) int*v; // v is an integer pointer (or array), l is an integer
{
    for (i = 0; i < l / 2; ++i) // iterate through half the indices using i (if l is odd, the middle element won't be included)
        v[i] += v[l + ~i]; // add the value at the i'th index from the back to the i'th index from the front. ~i == -i - 1, so l + ~i == l + -i -1 = l - i - 1 (l - 1 is the first index from the back, and we subtract i for each index beyond the first)
    return ~l / -2; // return half the length rounded up (~l == -l - 1 => ~l / -2 == (-l - 1) / -2 => (l + 1) / 2
}
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Golf! Nice first answer. \$\endgroup\$
    – alephalpha
    Jan 18, 2023 at 7:27
2
\$\begingroup\$

BQN, 15 12 bytes

(โŒŠโ‰ รท2ห™)โŠธโ†‘โŠข+โŒฝ

Try it online!

-3 thanks to Marshall Lochbaum

Sum the list and its reverse, then take the first โŒŠโ‰ รท2ห™ digits. โŒŠโ‰ รท2ห™ the floor of the length divide 2. Floor is necessary because there is no integer division in BQN. โŠธ is used to bind the output of โŒŠโ‰ รท2ห™ to the take operator โ†‘ on the left and also puts the output of (โŠข+โŒฝ) on the right. Better explanation here.

\$\endgroup\$
3
  • \$\begingroup\$ Welcome to Code Golf, and nice answer! \$\endgroup\$ Jan 20, 2023 at 20:45
  • \$\begingroup\$ Thank you! I only wish my explanation was as concise... \$\endgroup\$ Jan 20, 2023 at 20:49
  • \$\begingroup\$ I don't think this gives the correct output for lists with an odd number of elements. The output of "1 2 3 4 5 6 7" should be "8 8 8 4", not just "8 8 8"... \$\endgroup\$ Jun 9, 2023 at 10:34
2
\$\begingroup\$

Nibbles, 6.5 bytes

/`\~_!:\@0@+

Attempt This Online!

/   Fold
`\~  split into two parts
_     input (row from STDIN as a list of integers)
!    zip
:     join
\      reverse
@       the second part
0      0
@     the first part
+     with addition
\$\endgroup\$
2
\$\begingroup\$

Julia 1.0, 69 68 bytes

!s=(~=length;~s%2>0&&insert!(s,(1+~s)รท2,0);(s+reverse(s))[1:~sรท2])

Try it online!

-1 byte thanks to MarcMush: replace ==1 with >0

\$\endgroup\$
1
  • 1
    \$\begingroup\$ -1 byte: >0 instead of ==1 \$\endgroup\$
    – MarcMush
    Feb 24, 2023 at 12:58
2
\$\begingroup\$

Nekomata, 6 bytes

;แถœรงโ†”แถป+

Attempt This Online!

;แถœรงโ†”แถป+
;       Nondeterministically split the input into two parts
 แถœรง     Optionally prepend a zero to the second part
   โ†”    Reverse the second part
    แถป+  Zip with addition

The + operator is automatically vectorized, but it does not check if the two operands have the same length. So here I use แถป (\zip) to make sure that the two parts are of equal length.

\$\endgroup\$
2
\$\begingroup\$

Wolfram Language (Mathematica), 35 bytes

Set[f[a_,b___,c_],a+c,f@b]
f@a___=a

Try it online!

Input [list...]. Returns a sequence.


Wolfram Language (Mathematica), 39 bytes

f@{a_,b___,c_}:={a+c,##&@@f@{b}}
f@a_=a

Try it online!

Input and output a list instead of a sequence.

\$\endgroup\$
2
\$\begingroup\$

Perl 5 -aE, 36 bytes

map{$F[$_]+=pop@F}0..$#F/2-1;say"@F"

Takes advantage of the autosplit flag and iterates through the first half (rounded down) of the resulting list, modifying it in-place.

Slightly ungolfed:

for (0 .. ($#F / 2) - 1) {
    $F[$_] += pop(@F);
}
say "@F";

Try it online!

\$\endgroup\$
2
\$\begingroup\$

sed -E, 60 bytes

s/^/</
:a
s/<(!*);(.*;)?(!*);$/\1\3,<\2/
ta
s/[<;]//g
s/,$//

Only works with zero and positive numbers. Input is repeated exclamation marks separated by semicolons. Output is repeated exclamation marks separated by commas.

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Uiua, 12 bytes

โฌš0+โ‡ŒโŠƒโ†˜โ†™โŒŠรท2โงป.

Try it online!

โฌš0+โ‡ŒโŠƒโ†˜โ†™โŒŠรท2โงป.   input: a numeric vector
           โŒŠรท2โงป     half of length, rounded down (let's call it k)
     โŠƒโ†˜โ†™     .   fork(drop, take): first k elements removed, first k elements
   โ‡Œ               reverse the top
โฌš0+                elementwise add, filling with zeros when lengths don't match
\$\endgroup\$

Your Answer

By clicking โ€œPost Your Answerโ€, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.