# Reverse Array Sum

Your program should take an array as input.

The array:

1. Will always be 1 dimensional
2. Will only contain integers
3. Can be empty

The program should reverse the array, and then add up the elements to the original for example:

Input: [1, 2, 3]

Original: [1, 2, 3]

Reversed: [3, 2, 1]

[1, 2, 3]
+  +  +
[3, 2, 1]

[1+3, 2+2, 3+1]


Output: [4, 4, 4]

Test Cases:

#In             #Out
[8, 92],        [100, 100]
[1, 2, 3],      [4, 4, 4]
[5, 24, 85, 6], [11, 109, 109, 11]
[],             []
[999],          [1998]


This is , the shortest code (in bytes) wins!

• J 3 bytes. Program is t. t=:+|. Feb 10, 2019 at 19:13

# Röda, 22 bytes

{reverse(_)<>_1|[_+_]}


Try it online!

This is an anonymous function that takes in an array and returns a stream of values, which the TIO link outputs separated over newlines.

### Explanation

reverse(_)          The array reversed
<>                  interleaved with
_1                  the array itself
Push each element to the stream
[_+_]               Pull two values and push their sum

• Passes my tests! Great answer. Jul 24, 2017 at 20:28

# JavaScript (ES6), 34 33 bytes

Saved a byte thanks to @ETHproductions.

a=>a.map((e,i)=>e+a[a.length+~i])


let f=

a=>a.map((e,i)=>e+a[a.length+~i])

console.log(f([8,92]));
console.log(f([1,2,3]));
console.log(f([5, 24, 85, 6]));
console.log(f([]));
console.log(f([999]));

• I love how you put in the test cases, +2 Jul 24, 2017 at 18:25
• I think you can save a byte by changing -i-1 to +~i. Jul 24, 2017 at 21:07
• @ETHproductions, yes, thanks! Jul 24, 2017 at 21:16

# MATL, 3 bytes

tP+


Try it online!

Extremely straightforward. t duplicates the input. P flips (reverses) it, and + adds the two arrays element wise.

# PHP, 59 bytes

for(;a&$c=$argv[++$i];)$a[]=$c+$argv[$argc-$i];print_r($a);  takes input from command line arguments; empty output for empty input Yields a warning in PHP>7.0. This version does not (60 bytes): for(;++$i<$argc;)$a[]=$argv[$i]+$argv[$argc-$i];print_r($a);

• Nice answer! :) Jul 25, 2017 at 0:57

# Swift 3, 30 bytes

{zip($0,$0.reversed()).map(+)}

• Can you add a try link? Jul 26, 2017 at 17:03
• @NoahCristino Done Jul 26, 2017 at 17:07
• Unfortunately, this is a snippet. Since Swift has no useful input method, you must take the input as a function. Hardcoding the input into a variable is disallowed by meta consensus. See Default for Code Golf: Input/Output methods for more details. That's the reason I incorporated my answer into a function, too. Jul 26, 2017 at 17:19
• @Mr.Xcoder {zip($0,$0.reversed()).map(+)} 30 bytes Jul 26, 2017 at 17:31
• @Alexander You should edit your answer. Jul 26, 2017 at 17:32

# J-uby, 21 bytes

:zip%:reverse|:*&:sum


Try it online!

# HP 48 User REPL, 19 bytes

« DUP REVLIST +
»


## Explanation

« and » mark the object as a program.

DUP - Duplicates the list

REVLIST - Reverses the list

+ - Sums them

# K (ngn/k), 6 bytes

{x+|x}


Try it online!

# Pyth, 5 bytes

sMC_B


Try it online!

• Passed all my tests, congrats! Jul 24, 2017 at 18:24
• @NoahCristino Thanks, unfortunately got outgolfed Jul 24, 2017 at 18:25

->{a=[]i=0;while(i<len@$1)do{a+=[$1@i+($1@(-(i+1)))]i++};a}  Try it online! This has many golfing opportunities that have been ruined by Positron's brokenness :P • Never heard of Positron before, but it passes all the tests :) Jul 24, 2017 at 18:32 • @NoahCristino It's a really hacky and horribly malfunctioning language that I made :) Jul 24, 2017 at 18:32 • It would be cool to golf in you're own language lol Jul 24, 2017 at 18:35 • @NoahCristino It is quite cool, but it would be cooler if it actually worked properly :))) :P Jul 24, 2017 at 18:37 # Ruby 2.4, 31 bytes Hooray, TIO supports Ruby 2.4 now! ->a{a.zip(a.reverse).map &:sum}  Try it online! • Passes all cases, good job! Jul 24, 2017 at 18:37 # Perl 6, 15 bytes {$_ Z+.reverse}


Try it online!

• Works! Good job. Jul 24, 2017 at 18:44

# Python 2 + numpy, 31 bytes

I think this is kosher based on the rules, but let me know if not.

Anonymous function takes a numpy array as input:

import numpy
lambda l:l+l[::-1]


Try it online!

• It works, but why does it output so weird? Some are like: [4 4 4] which is already weird for python, and then one is like [ 11 109 109 11]??? Jul 24, 2017 at 18:48
• Probably because its a numpy array rather than a list Jul 24, 2017 at 18:48
• Looks weird, but it works. Jul 24, 2017 at 18:52
• @NoahCristino, that's what this site is all about, right? Jul 24, 2017 at 18:53
• The general rule of thumb is that if you use an external library that doesn't come packaged with the language, it should be added to the header. So you don't need to mention urllib2 because it comes included with Python, but requests will need to be mentioned. Jul 24, 2017 at 19:48

# Racket, 30 bytes

(lambda(l)(map +(reverse l)l))


Try it online!

This is simply an anonymous function that maps corresponding elements from l and l reversed to the + function, returning the results in a list.

• Works fine, good job. Jul 24, 2017 at 18:53

# Retina, 31 bytes

\d+
$*1;$&$* O$^;1+

;

1+
$.&  Try it online! Explanation: \d+$*1;$&$*


Convert to unary and duplicate each element.

O$^;1+  Reverse the order of the duplicate elements. ;  Add the elements to their reversed duplicates. 1+$.&


Convert the elements back to decimal.

• Good answer, but does your code need the newlines? or could it be squished into 1 line? Jul 24, 2017 at 20:29
• @NoahCristino No, in Retina the newlines normally delimit statements. (The exception is the command-line option to place each statement in a separate file.)
– Neil
Jul 24, 2017 at 21:25

# x86 Machine Code (32-bit protected mode), 19 bytes

8D 34 B7 39 F7 73 0C 83 EE 04 8B 07 03 06 89 06 AB EB F0 C3


The above bytes of code define a function that takes two parameters (a pointer to the array in the EDI register, and the length of the array in the ESI register), modifies the pointed-to array to contain the "reverse array sum", and then returns. It does not return a value to the caller.

(This is a custom calling convention used to receive the arguments. It is actually the standard calling convention used on Gnu/Unix systems for x86-64 binaries, but in x86-32, arguments are typically passed on the stack. That takes more bytes to encode, and is less efficient, so we want to ensure that the arguments are passed to us in registers. As far as I understand the rules, this is completely legal. We don't need to conform to a particular standardized calling convention. Certainly, when writing assembly, the programmer is free to define her own calling conventions, unless she needs to interoperate with C code.)

Note that this function also assumes the direction flag is cleared (DF == 0) upon entry to the function. This is a sensible assumption, as it is guaranteed by most platform ABIs, including the Linux x86 32-bit ABI. If you need the code to work under circumstances where the state of DF cannot be assumed, then you need to add a 1-byte CLD instruction to the top of the function.

Ungolfed assembly mnemonics:

               ; void ReverseArraySum(int *pArray, int length);
8D 34 B7         lea    esi, [edi+esi*4]        ; compute back pointer
Loop:
39 F7            cmp    edi, esi
73 0C            jae    End                     ; finished when EDI >= ESI
83 EE 04         sub    esi, 4
8B 07            mov    eax, DWORD PTR [edi]
03 06            add    eax, DWORD PTR [esi]
89 06            mov    DWORD PTR [esi], eax
AB               stosd  ; equivalent to 'mov DWORD PTR es:[edi], eax' + 'add edi, 4'
EB F0            jmp    Loop
End:
C3               ret


Conceptually, the code is pretty straightforward. We just iterate through the array using two pointers. The first pointer is passed to us as an argument, in the register EDI, and it is a pointer to the beginning of the array. The second pointer is computed (initial LEA instruction) by adding the address of the beginning of the array to the length of the array, scaled by the size of an element in the array (4 bytes for an int on x86-32). Thus, ESI is a pointer to the end of the array.

At the top of the Loop, we check the pointers to see if we should keep looping or if we are finished. Normally, we'd want to save bytes by putting this test at the end of the loop (and eliminating the JMP you see at the end now), but we can't do that because the challenge requires us to handle an empty input array.

Inside the body of the loop, we:

• Eagerly subtract 4 bytes (the size of a single element in the array) from the back pointer, ESI.
• Retrieve and store the value of the element pointed to by the front pointer (EDI) in a temporary register (EAX).
• Increment EAX by the value of the element pointed to by the back pointer (ESI).
• Store the sum (EAX) in the element pointed to by the back pointer (ESI).
• Store the same sum (EAX) in the element pointed to by the front pointer (EDI), while simultaneously incrementing that pointer (EDI) by 4 bytes (the size of a single element in the array). The handy x86 string instruction STOSD is what allows us to do both of those things in only a single byte of code.
(With the caveat given at the outset, that the direction flag is cleared, and also the assumption that we are running in flat mode, where the "extra" segment (ES) is identical to the data segment (DS).)

Finally, we're done and we return to the caller, without returning any value.

__
You can see it run on TIO, but note that the TIO link uses a C wrapper to exercise the machine code, and GCC won't necessarily respect our custom calling convention, so we have to add extra code at the top of the function to retrieve the parameters from the stack and put them into the appropriate registers.

• Interesting language choice! May 3, 2018 at 20:46

# Common Lisp, SBCL, 33 bytes

Pretty simple solution (very similiar to Clojure one):

(lambda(x)(mapcar'+(reverse x)x))


Example of use:

((lambda(x)(mapcar'+(reverse x)x))'(1 2 3)))


Try it online!(with print function, to show output from function)

# Swift, 7668 58 bytes (returns an Array)

-8 bytes thanks to @Alexander.

func f(l:[Int]){print(zip(l,l.reversed()).map(+))}


Try it online!

# Swift, 76 66 bytes

func f(l:[Int]){for i in 0..<l.count{print(l.reversed()[i]+l[i])}}


Try it online!

Prints the sums separated by a newline. For [1,2,3], the output is:

4
4
4

• Works perfect good job Jul 24, 2017 at 18:42
• You can just use map(+) Jul 26, 2017 at 17:07
• @Alexander Welcome to PPCG! Thanks for the tip! Jul 26, 2017 at 17:11

# C++14, 57 bytes

As generic unnamed lambda requiring a container and returns via modifying its input:

[](auto&L){auto R=L;auto r=R.end();for(auto&x:L)x+=*--r;}


Try it online!

Ungolfed:

[](auto&L){
auto R=L;      //copy of the list
auto r=R.end();//iterator of last+1
for(auto&x:L)  //foreach
x+=*--r;      //move iterator to front and sum
}

• Nice job, can you include a try it link? Aug 6, 2017 at 12:05
• @NoahCristino sure, didnt know TIO can generate CodeGolf posts. Now i do :) Aug 6, 2017 at 14:06

# C# (.NET Core),65 57 bytes

-8 bytes thanks to Kevin Cruijssen

n=>{for(int i=0,o=n.Length;i<o/2;)n[i]=n[o-1-i]+=n[i++];}


Try it online!

• How do I input into this? Jul 24, 2017 at 18:41
• It throws 18 errors for me. Jul 24, 2017 at 18:42
• @Mr.Xcoder Since it's C, that's probably just 1 error. Jul 24, 2017 at 18:46
• @HyperNeutrino: It's C#.
– Joey
Jul 24, 2017 at 18:48
• Just created a port of your answer in Java 8, and I noticed you can golf 4 more bytes by swapping the n[o-1-i] and n[i], so you'll use the shorter n[i] twice instead of n[o-1-i]. So it will become this: n=>{for(int i=0,o=n.Length;i<o/2;)n[i]=n[o-1-i]+=n[i++];} (57 bytes) Aug 16, 2017 at 7:45

# MY, 4948 5 bytes

ωω⌽+←


Try it online!

How?

First, you bang your head against the wall after remembering that addition on strings isn't commutative. Then, you bang your head yet again after realizing that you could've used ω to save over 40 bytes! Finally, you arrive at this:

ω    - First command line argument
ω⌽   - First command line argument, reversed
←    - Output without a newline


# 8th, 22 bytes

Code

clone a:rev ' n:+ a:op


SED (Stack Effect Diagram) is: a -- a

: f \ a -- a
clone      \ clone array on TOS
a:rev      \ reverse array
' n:+ a:op \ Add the corresponding elements of each array producing a new array
;


Usage

ok> [8,92] clone a:rev ' n:+ a:op .
[100,100]


Test cases

ok> [8,92] f .
[100,100]
ok> [1,2,3] f .
[4,4,4]
ok> [5,24,85,6] f .
[11,109,109,11]
ok> [] f .
[]
ok> [999] f .
[1998]

• Never heard of this language before great job! Aug 22, 2017 at 1:00

# ARBLE, 28 bytes

map(a,a+index(c,len(c)-b+1))


Try it online!

• Nice job, never heard of ARBLE! Oct 14, 2017 at 14:42

# Casio-Basic, 25 bytes

l+seq(l[x],x,dim(l),1,-1


Addition threads over lists by default - but there's no built-in for reversing a list! seq is used to generate the reversed list by indexing backwards through it.

24 bytes for the function, +1 byte to add l in the parameters box.

• There isn't really a way to try it online - but, if you're willing, you can download the 90 day free trial of the calculator emulator software from edu.casio.com/softwarelicense/index.php. If it redirects you to the home page, just click on software/app at the top right and get the appropriate ClassPad II Manager for your OS. :) Oct 15, 2017 at 1:09
• Cool! I'll try it out. Oct 15, 2017 at 12:21

# Stax, 5 bytes

òôΩo1


Run and debug it

I like that sequence of o-style chars (òôΩo).

Explanation (unpacked):

cr\m|+ Full program, implicit input  e.g.: [1, 2, 3]
cr     Copy and reverse                    [1, 2, 3] [3, 2, 1]
\    Zip                                 [[1, 3], [2, 2], [3, 1]]
m|+ Map sum of array                    [4, 4, 4]
Implicit output

• Nice solution, never heard of Stax before! May 3, 2018 at 20:45

# Pip-p, 4 bytes

g+Rg


Attempt This Online!

### Explanation

Just what it says on the tin.

   g  List of command-line arguments
R   Reversed
g+    Add to the original list


(Addition operates element-wise on lists in Pip.)

L,dbRz£+


Try it online!

## Explained

L,dbRz£+
L,        ; create a lambda that:
dbR     ; pushes the input list and its reverse
z    ; zips those together
£+  ; and reduces each pair by addition


# Risky, 7 bytes

0__2-?_+_?+_0


Try it online!

Appends -? (first input reversed) to __ (all inputs, which is in this case a trick to wrap the input array), and then transposes. Maps with sum, which is the most complicated usage of Risky's quicks that I'm even going to attempt.

# Desmos, 22 bytes

f(l)=l+l[l.length...1]


Pretty self-explanatory

Try It On Desmos!

Try It On Desmos! - Prettified

# Stacked, 7 bytes

[:rev+]


Try it online!