38
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ J 3 bytes. Program is t. t=:+|. \$\endgroup\$ Commented Feb 10, 2019 at 19:13
  • 1
    \$\begingroup\$ @RichardDonovan Nice Answer! Can you submit as an answer instead of a comment please :) \$\endgroup\$ Commented Feb 11, 2019 at 21:10

71 Answers 71

2
\$\begingroup\$

Neim, 2 bytes

This is a function that takes input on the top of the stack and outputs on the top of the stack.

𝕓𝔻

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Is it allowed to modify the input stack via actual Neim code instead of normal input methods? \$\endgroup\$
    – LiefdeWen
    Commented Jul 25, 2017 at 11:59
  • \$\begingroup\$ @LiefdeWen Yes, that's allowed in the defaults for I/O meta post. \$\endgroup\$
    – Okx
    Commented Jul 25, 2017 at 18:15
2
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ Passes my tests! Great answer. \$\endgroup\$ Commented Jul 24, 2017 at 20:28
2
\$\begingroup\$

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]));

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

MATL, 3 bytes

tP+

Try it online!

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

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

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);
\$\endgroup\$
1
  • \$\begingroup\$ Nice answer! :) \$\endgroup\$ Commented Jul 25, 2017 at 0:57
2
\$\begingroup\$

Swift 3, 30 bytes

{zip($0,$0.reversed()).map(+)}
\$\endgroup\$
9
  • \$\begingroup\$ Can you add a try link? \$\endgroup\$ Commented Jul 26, 2017 at 17:03
  • \$\begingroup\$ @NoahCristino Done \$\endgroup\$
    – Alexander
    Commented Jul 26, 2017 at 17:07
  • \$\begingroup\$ 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. \$\endgroup\$
    – Mr. Xcoder
    Commented Jul 26, 2017 at 17:19
  • \$\begingroup\$ @Mr.Xcoder {zip($0,$0.reversed()).map(+)} 30 bytes \$\endgroup\$
    – Alexander
    Commented Jul 26, 2017 at 17:31
  • \$\begingroup\$ @Alexander You should edit your answer. \$\endgroup\$
    – Mr. Xcoder
    Commented Jul 26, 2017 at 17:32
2
\$\begingroup\$

J-uby, 21 bytes

:zip%:reverse|:*&:sum

Try it online!

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

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

\$\endgroup\$
1
\$\begingroup\$

Pyth, 5 bytes

sMC_B

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Passed all my tests, congrats! \$\endgroup\$ Commented Jul 24, 2017 at 18:24
  • \$\begingroup\$ @NoahCristino Thanks, unfortunately got outgolfed \$\endgroup\$
    – Mr. Xcoder
    Commented Jul 24, 2017 at 18:25
1
\$\begingroup\$

Positron, 59 bytes

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

\$\endgroup\$
4
  • \$\begingroup\$ Never heard of Positron before, but it passes all the tests :) \$\endgroup\$ Commented Jul 24, 2017 at 18:32
  • \$\begingroup\$ @NoahCristino It's a really hacky and horribly malfunctioning language that I made :) \$\endgroup\$
    – hyper-neutrino
    Commented Jul 24, 2017 at 18:32
  • \$\begingroup\$ It would be cool to golf in you're own language lol \$\endgroup\$ Commented Jul 24, 2017 at 18:35
  • \$\begingroup\$ @NoahCristino It is quite cool, but it would be cooler if it actually worked properly :))) :P \$\endgroup\$
    – hyper-neutrino
    Commented Jul 24, 2017 at 18:37
1
\$\begingroup\$

Ruby 2.4, 31 bytes

Hooray, TIO supports Ruby 2.4 now!

->a{a.zip(a.reverse).map &:sum}

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Passes all cases, good job! \$\endgroup\$ Commented Jul 24, 2017 at 18:37
1
\$\begingroup\$

Perl 6, 15 bytes

{$_ Z+.reverse}

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Works! Good job. \$\endgroup\$ Commented Jul 24, 2017 at 18:44
1
\$\begingroup\$

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!

\$\endgroup\$
7
  • \$\begingroup\$ 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]??? \$\endgroup\$ Commented Jul 24, 2017 at 18:48
  • \$\begingroup\$ Probably because its a numpy array rather than a list \$\endgroup\$
    – wnnmaw
    Commented Jul 24, 2017 at 18:48
  • 1
    \$\begingroup\$ Looks weird, but it works. \$\endgroup\$ Commented Jul 24, 2017 at 18:52
  • 1
    \$\begingroup\$ @NoahCristino, that's what this site is all about, right? \$\endgroup\$
    – wnnmaw
    Commented Jul 24, 2017 at 18:53
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Value Ink
    Commented Jul 24, 2017 at 19:48
1
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ Works fine, good job. \$\endgroup\$ Commented Jul 24, 2017 at 18:53
1
\$\begingroup\$

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.

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

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.

\$\endgroup\$
1
  • \$\begingroup\$ Interesting language choice! \$\endgroup\$ Commented May 3, 2018 at 20:46
1
\$\begingroup\$

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)

\$\endgroup\$
1
\$\begingroup\$

Swift, 76 68 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
\$\endgroup\$
3
  • \$\begingroup\$ Works perfect good job \$\endgroup\$ Commented Jul 24, 2017 at 18:42
  • \$\begingroup\$ You can just use map(+) \$\endgroup\$
    – Alexander
    Commented Jul 26, 2017 at 17:07
  • \$\begingroup\$ @Alexander Welcome to PPCG! Thanks for the tip! \$\endgroup\$
    – Mr. Xcoder
    Commented Jul 26, 2017 at 17:11
1
\$\begingroup\$

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
}
\$\endgroup\$
2
  • \$\begingroup\$ Nice job, can you include a try it link? \$\endgroup\$ Commented Aug 6, 2017 at 12:05
  • \$\begingroup\$ @NoahCristino sure, didnt know TIO can generate CodeGolf posts. Now i do :) \$\endgroup\$
    – Karl Napf
    Commented Aug 6, 2017 at 14:06
1
\$\begingroup\$

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!

\$\endgroup\$
12
  • \$\begingroup\$ How do I input into this? \$\endgroup\$ Commented Jul 24, 2017 at 18:41
  • 4
    \$\begingroup\$ It throws 18 errors for me. \$\endgroup\$
    – Mr. Xcoder
    Commented Jul 24, 2017 at 18:42
  • 1
    \$\begingroup\$ @Mr.Xcoder Since it's C, that's probably just 1 error. \$\endgroup\$
    – hyper-neutrino
    Commented Jul 24, 2017 at 18:46
  • 2
    \$\begingroup\$ @HyperNeutrino: It's C#. \$\endgroup\$
    – Joey
    Commented Jul 24, 2017 at 18:48
  • 1
    \$\begingroup\$ 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) \$\endgroup\$ Commented Aug 16, 2017 at 7:45
1
\$\begingroup\$

MY, 49 48 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
+    - Add (vectorizes)
←    - Output without a newline
\$\endgroup\$
1
\$\begingroup\$

8th, 22 bytes

Code

clone a:rev ' n:+ a:op

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

Ungolfed code with comments

: 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]
\$\endgroup\$
1
  • \$\begingroup\$ Never heard of this language before great job! \$\endgroup\$ Commented Aug 22, 2017 at 1:00
1
\$\begingroup\$

ARBLE, 28 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Nice job, never heard of ARBLE! \$\endgroup\$ Commented Oct 14, 2017 at 14:42
1
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ Cool! I don't know much about this language, but is it possible to add a try it link? \$\endgroup\$ Commented Oct 14, 2017 at 14:42
  • \$\begingroup\$ 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. :) \$\endgroup\$ Commented Oct 15, 2017 at 1:09
  • \$\begingroup\$ Cool! I'll try it out. \$\endgroup\$ Commented Oct 15, 2017 at 12:21
1
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ Nice solution, never heard of Stax before! \$\endgroup\$ Commented May 3, 2018 at 20:45
1
\$\begingroup\$

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.)

\$\endgroup\$
1
\$\begingroup\$

Add++, 8 bytes

L,dbRz£+

Try it online!

Finally something sane with Add++

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

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.

\$\endgroup\$
1
\$\begingroup\$

Desmos, 22 bytes

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

Pretty self-explanatory

Try It On Desmos!

Try It On Desmos! - Prettified

\$\endgroup\$
1
\$\begingroup\$

J-uby, 14 bytes

:zip%:~|:*&+:+

Attempt This Online!

:zip % :~ |           # Zip array with its reverse, then
            :* & +:+  # Map with sum
\$\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.