Reverse Array Sum

34

2

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!

Noah Cristino

Posted 2017-07-24T18:11:01.823

Reputation: 667

J 3 bytes. Program is t. t=:+|. – Richard Donovan – 2019-02-10T19:13:00.767

@RichardDonovan Nice Answer! Can you submit as an answer instead of a comment please :) – Noah Cristino – 2019-02-11T21:10:55.513

Answers

13

Haskell, 20 bytes

5 bytes save by changing to a point free as suggested by nimi

zipWith(+)=<<reverse

Try it online!

Post Rock Garf Hunter

Posted 2017-07-24T18:11:01.823

Reputation: 55 382

4go pointfree: zipWith(+)=<<reverse. – nimi – 2017-07-24T18:19:31.733

@nimi Wow I didn't think to do that but thats pretty smart. – Post Rock Garf Hunter – 2017-07-24T18:21:12.113

Where do I put the array? I tried arguments, and input on TIO – Noah Cristino – 2017-07-24T18:23:35.243

@NoahCristino I fixed the TIO. This is a point-free function so you just put the input after the function however Haskell requires a main to compile. – Post Rock Garf Hunter – 2017-07-24T18:26:39.350

Ok, I'll try it out thanks! – Noah Cristino – 2017-07-24T18:29:20.187

Passed all tests! – Noah Cristino – 2017-07-24T18:29:41.723

@nimi I am trying to wrap my brain around the use of the bind here, can you offer an explanation how this magic works?! – maple_shaft – 2017-07-24T19:20:04.147

3@maple_shaft: we use =<< from the function monad which is defined as: (=<<) f g x = f (g x) x. Here, written in infix: (zipWith(+) =<< reverse) x -> zipWith(+) (reverse x) x. – nimi – 2017-07-24T19:23:47.113

11

Jelly, 2 bytes

+U

Try it online!

or

+Ṛ

Try it online! (thanks @Mr. Xcoder for the second program)

explanation, though it's pretty self-explanatory

+U  Main link
+   Add, vectorizing, 
 U                    the input, reversed

+Ṛ  Main link
+   Add, vectorizing,
 Ṛ                    the input, reversed, without vectorizing (same thing for depth-1 lists)

For empty array [], this outputs nothing. That is correct. Jelly's representation of an empty list is just simply nothing. Note that Jelly's representation of a list with a single element is just the element itself. Append ŒṘ to the code to see the Python internal representation of the output.

HyperNeutrino

Posted 2017-07-24T18:11:01.823

Reputation: 26 575

I found 2 issues. 1) When tested on [9] it outputs 18 instead of [18], and 2) when tested on [] it doesn't output anything. – Noah Cristino – 2017-07-24T18:19:09.430

@NoahCristino It's not a full program, and there's already an explanation for that in the answer. – Erik the Outgolfer – 2017-07-24T18:19:39.250

So I guess this is fine, it's just how Jelly outputs it – Noah Cristino – 2017-07-24T18:23:01.303

@NoahCristino Yeah. I added a part to the end of my answer so you can put that atom at the end of the code to see how Python would print it. – HyperNeutrino – 2017-07-24T18:24:15.693

+Ṛ works too. – Mr. Xcoder – 2017-07-24T18:46:20.713

@Mr.Xcoder Yes, thanks. I'll write that in as well. – HyperNeutrino – 2017-07-24T18:49:40.890

11

JavaScript (ES6), 27 bytes

a=>[...a].map(e=>e+a.pop())

f=
a=>[...a].map(e=>e+a.pop())

console.log(f([8, 92])) // [100, 100]
console.log(f([1, 2, 3])) // [4, 4, 4]
console.log(f([5, 24, 85, 6])) // [11, 109, 109, 11]
console.log(f([])) // []
console.log(f([999])) //[1998]

Neil

Posted 2017-07-24T18:11:01.823

Reputation: 95 035

Oh, man, I was almost there, but I didn't think to use the spread operator to do the clone. – Rick Hitchcock – 2017-07-24T19:09:03.517

Can you add the embedded try it for javascript? – Noah Cristino – 2017-07-24T23:25:12.077

9

05AB1E, 2 bytes

Â+

Try it online!

Erik the Outgolfer

Posted 2017-07-24T18:11:01.823

Reputation: 38 134

Passed all my tests! – Noah Cristino – 2017-07-24T18:21:49.880

R+ also works for 2 bytes. – Riley – 2017-07-24T18:41:56.233

9

Python 2, 32 bytes

lambda l:map(sum,zip(l,l[::-1]))

Alternative solution without zip (35 bytes):

lambda l:map(int.__add__,l,l[::-1])

Try it online!

vaultah

Posted 2017-07-24T18:11:01.823

Reputation: 1 254

7

Python 2, 40 bytes

lambda l:[i+j for i,j in zip(l,l[::-1])]

Try it online!

The other, shorter Python answer replaces a list comprehension with map. Wish I'd thought to do that faster. ;-;

totallyhuman

Posted 2017-07-24T18:11:01.823

Reputation: 15 378

1Passes all my tests! – Noah Cristino – 2017-07-24T18:20:43.203

7

Japt, 7 bytes

mÈ+Ug~Y

Try it online! with the -Q flag to format the output array.

Explanation

Implicit: U = input array

Map the input by the following function...

+Ug

The value, plus the value in the input array at index...

~Y

-(index+1), which gets elements from the end of the array.

Justin Mariner

Posted 2017-07-24T18:11:01.823

Reputation: 4 746

1Good job! I like the multiple input thing! – Noah Cristino – 2017-07-24T18:45:02.333

1I really like the multiple-input Japt interpreter. Nice job! – Oliver – 2017-07-24T19:33:14.663

That's really cool :-) I'd add that feature to the "official" interpreter, but with the current design it's sorta unextendable... – ETHproductions – 2017-07-24T21:08:54.930

7

Ruby, 25 bytes

->a{[*a].map{|i|i+a.pop}}

Try it online!

Ventero

Posted 2017-07-24T18:11:01.823

Reputation: 9 842

6

Mathematica, 12 bytes

Reverse@#+#&

Try it online!

J42161217

Posted 2017-07-24T18:11:01.823

Reputation: 15 931

6

Python 2, 33 32 bytes

-1 byte thanks to @xnor

lambda l:[i+l.pop()for i in l*1]

Try it online!

ovs

Posted 2017-07-24T18:11:01.823

Reputation: 21 408

Passed all my tests good job :) – Noah Cristino – 2017-07-24T20:26:56.427

What an unusual method. l*1 saves a byte. – xnor – 2017-07-24T20:53:07.187

I am having difficulties understanding the par l*1, any elaboration – dhssa – 2017-07-26T08:23:11.423

@dhssa l*1 makes a copy of the list l. If we would not make a copy, pop() would delete elements from the list before they were accessed in the for loop. – ovs – 2017-07-26T08:30:42.267

Thanks for the explanation, I got it now. good trick to know for coding. – dhssa – 2017-07-26T23:33:07.993

@dhssa If you want to copy a list in real python code, I would recommend you to use the functions provided by the copy module. – ovs – 2017-07-27T06:30:36.407

5

Brachylog, 6 bytes

↔;?z+ᵐ

Try it online!

Erik the Outgolfer

Posted 2017-07-24T18:11:01.823

Reputation: 38 134

1Passes all cases, cool name. – Noah Cristino – 2017-07-24T18:37:06.680

5

C# (.NET Core), 61 60 bytes

-1 byte thanks to TheLethalCoder

a=>a.Reverse().Zip(a,(x,y)=>x+y).ToArray()

Try it online!

Byte count also includes:

using System.Linq;

For explanation - Zip function in LINQ takes two collections and executes given function for all corresponding elements, ie. both first elements together, both second elements etc.

Grzegorz Puławski

Posted 2017-07-24T18:11:01.823

Reputation: 781

1Good answer. Thanks for the comment about the input. – Noah Cristino – 2017-07-24T23:23:34.607

1Hello and welcome to PPCG! You don't need the trailing semi colon in the byte count. I believe you can return the collection straight from the Zip call to so no need for the ToArray(). Nice job! – TheLethalCoder – 2017-07-25T08:29:15.247

@TheLethalCoder Thanks, and I added ToArray() since the challenge is about arrays, so I wanted the self-contained lambda to be array -> array. – Grzegorz Puławski – 2017-07-25T11:47:27.973

4

CJam, 7 bytes

{_W%.+}

Try it online!

Erik the Outgolfer

Posted 2017-07-24T18:11:01.823

Reputation: 38 134

It outputs "" for [], that's weird. Not your fault just the language. – Noah Cristino – 2017-07-24T18:28:17.490

@NoahCristino That's CJam's representation of []. – Erik the Outgolfer – 2017-07-24T18:29:39.483

Yup, it's hard to have a standard output for my challenge since many languages display arrays differently especially [], and [4], so it's fine. – Noah Cristino – 2017-07-24T18:30:55.783

4

R, 17 16 bytes

-1 byte thanks to djhurio

rev(l<-scan())+l

Reads from stdin; returns the vector; numeric(0) is the zero-length numeric vector for the empty list.

Try it online!

Giuseppe

Posted 2017-07-24T18:11:01.823

Reputation: 21 077

For an empty "array" it returns numeric(0) – Noah Cristino – 2017-07-24T18:36:36.077

1@NoahCristino an empty vector is represented as numeric(0) in R. – Leaky Nun – 2017-07-24T18:58:42.343

That's fine. @LeakyNun – Noah Cristino – 2017-07-24T19:01:34.580

1rev(l<-scan())+l, 16 bytes? – djhurio – 2017-07-25T13:08:30.733

For the record, an R+pryr functional alternative is just one byte longer: pryr::f(rev(x)+x)

– JayCe – 2018-05-03T18:21:58.497

4

APL (Dyalog), 3 bytes

⌽+⊢

Try it online!

Explanation

⌽          The argument reversed
+           Plus
⊢          The argument

user41805

Posted 2017-07-24T18:11:01.823

Reputation: 16 320

1ninja'd. I need to move to an APL keyboard... xD – Uriel – 2017-07-24T18:33:47.607

@Uriel I am always on my APL keyboard :D – user41805 – 2017-07-24T18:35:23.957

Love the simplicity. It outputs ⌽+⊢ with no input – Noah Cristino – 2017-07-24T18:39:18.733

@NoahCristino An empty input is specified with , the empty vector. With no argument, it prints the train by itself – user41805 – 2017-07-24T18:39:53.303

4

J, 3 bytes

+|.

Reverse, sum.

Try it online!

Jonah

Posted 2017-07-24T18:11:01.823

Reputation: 8 729

4

Clojure, 20 17 bytes

3 bytes saved thanks to @MattPutnam

#(map +(rseq %)%)

Seems to be quite competitive with non-golfing languages.

See it online

cliffroot

Posted 2017-07-24T18:11:01.823

Reputation: 1 080

Use rseq instead of reverse. – MattPutnam – 2017-07-26T19:07:02.847

3

Pyth, 3 bytes

+V_

Try it here.

Erik the Outgolfer

Posted 2017-07-24T18:11:01.823

Reputation: 38 134

Yay passes all my tests! – Noah Cristino – 2017-07-24T18:20:04.740

Equivalent: sV_ – Mr. Xcoder – 2017-07-24T18:25:56.643

@Mr.Xcoder nevermind – Erik the Outgolfer – 2017-07-24T18:28:58.207

3

PowerShell, 40 32 bytes

($n=$args)|%{$n[-++$i]+$n[$i-1]}

Try it online!

Takes input as individual command-line arguments, which is allowed as one of the native list format for PowerShell. Then loops through each element (i.e., a shorter way of looping through the indices), adding the element counting from the back (-1 indexed) to the current element (0 indexed, hence the decrement -1). Those are left on the pipeline and output is implicit.

Saved 8 bytes thanks to @briantist

AdmBorkBork

Posted 2017-07-24T18:11:01.823

Reputation: 41 581

it doesn't output an array. – Noah Cristino – 2017-07-24T18:27:23.567

1

@NoahCristino PowerShell input/output is, in general, weird. It is outputting as an array, it's just there's nothing capturing said array, and so when the implicit Write-Output happens, it puts things on stdout one item per line. For example, you can see here that, when captured, the object is indeed an array type.

– AdmBorkBork – 2017-07-24T18:31:22.073

Good enough then :) atleast it tried – Noah Cristino – 2017-07-24T18:38:11.463

I'm on mobile and can't test so easily, but isn't it 1 byte shorter to remove the param and then replace 1..$n with 1..($n=$args)? – briantist – 2017-07-24T21:51:38.110

@briantist Not quite, but you did give me a different way of thinking about it, saving a bunch of bytes. Thanks! – AdmBorkBork – 2017-07-25T12:54:55.253

3

PowerShell, 26 bytes

($a=$args)|%{+$a[--$i]+$_}

Try it online!

Takes input as command-line arguments.

Joey

Posted 2017-07-24T18:11:01.823

Reputation: 12 260

Can you add a TIO? and a link under the name like this one: https://codegolf.stackexchange.com/a/135427/61877

– Noah Cristino – 2017-07-24T18:48:32.140

@NoahCristino: Like this? Haven't used that thing so far, so no idea what I may have done wrong. By the way, if you expect people to use a certain service in their answers, then please state so in the task description. – Joey – 2017-07-24T18:52:36.707

That's fine. It's not required it just makes the answers more high quality, and easier to test out for future viewers. – Noah Cristino – 2017-07-24T18:54:14.453

3

C, 49 bytes

f(a,n,b)int*a,*b;{for(b=a+n;a<b--;a++)*a=*b+=*a;}

orlp

Posted 2017-07-24T18:11:01.823

Reputation: 37 067

Shouldn't a,n,b be a,b,n or something? – Erik the Outgolfer – 2017-07-24T20:12:28.077

@EriktheOutgolfer No, b isn't a parameter for the function, just an extra definition stuffed in there for golfing reasons. a must be a pointer to integers, and n must be how many integers there are in the array. – orlp – 2017-07-24T20:13:50.750

Could you please add a TIO link? – Noah Cristino – 2017-07-24T20:27:27.937

3

Java 8, 61 57 56 53 bytes

a->{for(int l=0,r=a.length;l<r;a[l]=a[--r]+=a[l++]);}

-1 byte and bug-fixed thanks to @Nevay.
-3 bytes thanks to @OliverGrégoire.

(It was a port of (and golfed by 4 8 bytes) of @jkelm's C# answer, but now it's a different shorter solution thanks to @OliverGrégoire.)

Explanation:

Try it here.

The method modifies the input-array to save bytes, so no need for a return-type.

a->{                    // Method with integer-array parameter and no return-type
  for(int l=0,          //  Left-integer (starting at 0)
          r=a.length;   //  Right-integer (starting at the length of the input-array)
      l<r;              //  Loop as long as left is smaller than right
    a[l]=               //   Change the number at the current left index to:
         a[--r]+=a[l++] //    The number at the right index + itself
                        //    (The += adds the number at the left index also to the right index)
                        //    (And the --/++ increases/decreases the indexes by 1,
                        //     until we've reached the middle of the array)
  );                    //  End of loop
}                       // End of method

Kevin Cruijssen

Posted 2017-07-24T18:11:01.823

Reputation: 67 575

1You can save 1 byte by using a->{for(int i=0,l=a.length;i<l/2;a[i]=a[l+~i]+=a[i++]);}. – Nevay – 2017-08-16T10:56:05.043

1Besides that the code fails for arrays with an odd length 1,2,3 (returns 4,2,4 instead of 4,4,4), the loop has to run as long as 2*i<l, not i<l/2. – Nevay – 2017-08-16T11:03:40.627

@Nevay Thanks. I knew it should be possible to golf l-i-1, just couldn't come up with it.. – Kevin Cruijssen – 2017-08-16T11:10:37.093

253 bytes: a->{for(int l=0,r=a.length;l<r;a[l]=a[--r]+=a[l++]);}. – Olivier Grégoire – 2017-08-16T12:05:37.733

Sorry for the not-identical variable names (short for left and right): I was implementing it by myself before seeing that you had posted an answer. – Olivier Grégoire – 2017-08-16T12:12:43.573

1@OlivierGrégoire Thanks. And your l and r makes sense for your implementation, so I've used those as well (and added an explanation). – Kevin Cruijssen – 2017-08-16T12:58:05.527

2

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

Rick Hitchcock

Posted 2017-07-24T18:11:01.823

Reputation: 2 461

I love how you put in the test cases, +2 – Noah Cristino – 2017-07-24T18:25:22.243

I think you can save a byte by changing -i-1 to +~i. – ETHproductions – 2017-07-24T21:07:50.273

@ETHproductions, yes, thanks! – Rick Hitchcock – 2017-07-24T21:16:54.180

2

Ohm, 3 bytes

DR+

Try it online!

totallyhuman

Posted 2017-07-24T18:11:01.823

Reputation: 15 378

It outputs floats, but I never said it couldn't, so that's fine, and for [] it doesn't output anything but that's just the language. – Noah Cristino – 2017-07-24T18:26:36.433

2

Actually, 4 bytes

;R♀+

Try it online!

Erik the Outgolfer

Posted 2017-07-24T18:11:01.823

Reputation: 38 134

Perfect, great job. – Noah Cristino – 2017-07-24T18:43:05.630

Erik, solving my problem in like 7 languages xD – Noah Cristino – 2017-07-24T18:43:32.207

@NoahCristino Yeah I'm trying to keep it under 15...;) – Erik the Outgolfer – 2017-07-24T18:44:16.483

I'm going to have to start adding a -1 for every submission xD – Noah Cristino – 2017-07-24T18:46:16.913

2

anyfix, 3 bytes

"U+

The version on TryItOnline! is an outdated version of anyfix, which contains a few fatal errors such as not being able to add lists because of typos in the source code. Use the code on GitHub instead.

"U+  Program
"    Duplicate top of stack
 U   Reverse top of stack if it is a list (which it should be...)
  +  Add, vectorizing for lists

HyperNeutrino

Posted 2017-07-24T18:11:01.823

Reputation: 26 575

2

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

user41805

Posted 2017-07-24T18:11:01.823

Reputation: 16 320

Passes my tests! Great answer. – Noah Cristino – 2017-07-24T20:28:07.060

2

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!

Okx

Posted 2017-07-24T18:11:01.823

Reputation: 15 025

Is it allowed to modify the input stack via actual Neim code instead of normal input methods? – LiefdeWen – 2017-07-25T11:59:07.497

@LiefdeWen Yes, that's allowed in the defaults for I/O meta post. – Okx – 2017-07-25T18:15:23.140

2

MATL, 3 bytes

tP+

Try it online!

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

James

Posted 2017-07-24T18:11:01.823

Reputation: 54 537

2

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

Titus

Posted 2017-07-24T18:11:01.823

Reputation: 13 814

Nice answer! :) – Noah Cristino – 2017-07-25T00:57:43.037

2

Swift 3, 30 bytes

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

Alexander - Reinstate Monica

Posted 2017-07-24T18:11:01.823

Reputation: 481

Can you add a try link? – Noah Cristino – 2017-07-26T17:03:55.740

@NoahCristino Done – Alexander - Reinstate Monica – 2017-07-26T17:07:18.627

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.

– Mr. Xcoder – 2017-07-26T17:19:16.823

@Mr.Xcoder {zip($0,$0.reversed()).map(+)} 30 bytes – Alexander - Reinstate Monica – 2017-07-26T17:31:50.973

@Alexander You should edit your answer. – Mr. Xcoder – 2017-07-26T17:32:26.630

@Mr.Xcoder That's not a particularly sensible distinction to make. It just forces people into using languages specifically designed to circumvent this, by implicitly taking input from STDIN, implicitly printing last return value, and crap like that – Alexander - Reinstate Monica – 2017-07-26T17:32:37.740

@Alexander Please trust me when I say hardcoding is not allowed. I think this is a great answer once it fits the default I/O rules – Mr. Xcoder – 2017-07-26T17:34:28.047

@Mr.Xcoder It's not that I don't trust you, I just take issue with the rules. If people are allowed to design languages with implicit input capabilities, why is it disallowed to mimic the behavior with a repl with predefined variables? – Alexander - Reinstate Monica – 2017-07-26T17:40:02.217

Let us continue this discussion in chat.

– Mr. Xcoder – 2017-07-26T17:40:42.037

2

K4 / K (oK), 5 bytes

Solution:

x+|x:

Try it online!

Example:

x+|x:,()
,()
x+|x:8 92
100 100
x+|x:,999
,1998

Explanation:

Not quite as elegant as the J solution, but same kinda thing:

x+|x: / the solution
   x: / store input as x
  |   / reverse it
 +    / add to
x     / x

streetster

Posted 2017-07-24T18:11:01.823

Reputation: 3 635

Nice! I like the line by line explanation – Noah Cristino – 2018-05-03T20:46:24.863

1

Pyth, 5 bytes

sMC_B

Try it online!

Mr. Xcoder

Posted 2017-07-24T18:11:01.823

Reputation: 39 774

Passed all my tests, congrats! – Noah Cristino – 2017-07-24T18:24:32.913

@NoahCristino Thanks, unfortunately got outgolfed – Mr. Xcoder – 2017-07-24T18:25:05.683

1

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

HyperNeutrino

Posted 2017-07-24T18:11:01.823

Reputation: 26 575

Never heard of Positron before, but it passes all the tests :) – Noah Cristino – 2017-07-24T18:32:03.687

@NoahCristino It's a really hacky and horribly malfunctioning language that I made :) – HyperNeutrino – 2017-07-24T18:32:25.273

It would be cool to golf in you're own language lol – Noah Cristino – 2017-07-24T18:35:54.657

@NoahCristino It is quite cool, but it would be cooler if it actually worked properly :))) :P – HyperNeutrino – 2017-07-24T18:37:24.230

1

Ruby 2.4, 31 bytes

Hooray, TIO supports Ruby 2.4 now!

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

Try it online!

Value Ink

Posted 2017-07-24T18:11:01.823

Reputation: 10 608

Passes all cases, good job! – Noah Cristino – 2017-07-24T18:37:33.143

1

Perl 6, 15 bytes

{$_ Z+.reverse}

Try it online!

Sean

Posted 2017-07-24T18:11:01.823

Reputation: 4 136

Works! Good job. – Noah Cristino – 2017-07-24T18:44:01.833

1

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

Mr. Xcoder

Posted 2017-07-24T18:11:01.823

Reputation: 39 774

Works perfect good job – Noah Cristino – 2017-07-24T18:42:33.763

You can just use map(+) – Alexander - Reinstate Monica – 2017-07-26T17:07:36.847

@Alexander Welcome to PPCG! Thanks for the tip! – Mr. Xcoder – 2017-07-26T17:11:55.987

1

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!

jkelm

Posted 2017-07-24T18:11:01.823

Reputation: 441

How do I input into this? – Noah Cristino – 2017-07-24T18:41:17.887

4It throws 18 errors for me. – Mr. Xcoder – 2017-07-24T18:42:03.203

1@Mr.Xcoder Since it's C, that's probably just 1 error. – HyperNeutrino – 2017-07-24T18:46:33.700

2@HyperNeutrino: It's C#. – Joey – 2017-07-24T18:48:28.827

@Joey close enough :P – HyperNeutrino – 2017-07-24T18:49:27.917

@Mr.Xcoder Fixed the TiO link, there was an opening brace missing. – Ventero – 2017-07-24T18:50:23.290

@Ventero I didn't downvote though – Mr. Xcoder – 2017-07-24T18:51:04.827

@NoahCristino it's a lambda. Assign it to a variable like var a = n=>... and then try a(<your_array_here>) – Tamoghna Chowdhury – 2017-07-25T14:20:12.243

You can golf 4 bytes by changing =n[i]=n[i]+ to =n[i]+=. And judging by the previous comments a bracket was missing causing some errors/confusion, so I'll +1 to neutralize the downvote (not by me!) now that that's fixed. – Kevin Cruijssen – 2017-08-16T07:06:13.017

1

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)

– Kevin Cruijssen – 2017-08-16T07:45:57.730

@KevinCruijssen Thanks for the golfing. I didn't even think of the += there for some reason. – jkelm – 2017-08-16T10:37:49.803

@jkelm No problem. Also, Nevay golfed one more by in my Java 8 answer, and also bug-fixed incorrect results for odd-length lists (i.e. 1,2,3 currently returns 4,1,4 instead of 4,4,4). o-1-i can be o+~i for -1 byte; and i<o/2 should be i*2<o to fix the bug. – Kevin Cruijssen – 2017-08-16T11:12:26.697

1

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!

wnnmaw

Posted 2017-07-24T18:11:01.823

Reputation: 1 618

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]??? – Noah Cristino – 2017-07-24T18:48:12.407

Probably because its a numpy array rather than a list – wnnmaw – 2017-07-24T18:48:43.483

It's allowed but please specify that you are using numpy in the header next time. I've done it for you this time. – totallyhuman – 2017-07-24T18:49:28.143

@totallyhuman, I haven't seen that on other posts, but I'll keep it in mind from here on out, thanks for the edit! – wnnmaw – 2017-07-24T18:50:11.777

1Looks weird, but it works. – Noah Cristino – 2017-07-24T18:52:32.513

@NoahCristino, that's what this site is all about, right? – wnnmaw – 2017-07-24T18:53:51.233

1

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.

– Value Ink – 2017-07-24T19:48:35.043

1

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.

Business Cat

Posted 2017-07-24T18:11:01.823

Reputation: 8 927

Works fine, good job. – Noah Cristino – 2017-07-24T18:53:11.017

1

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.

Neil

Posted 2017-07-24T18:11:01.823

Reputation: 95 035

Good answer, but does your code need the newlines? or could it be squished into 1 line? – Noah Cristino – 2017-07-24T20:29:05.883

@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 – 2017-07-24T21:25:06.667

1

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.

Cody Gray

Posted 2017-07-24T18:11:01.823

Reputation: 2 639

Interesting language choice! – Noah Cristino – 2018-05-03T20:46:46.253

1

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)

user65167

Posted 2017-07-24T18:11:01.823

Reputation:

1

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

Zacharý

Posted 2017-07-24T18:11:01.823

Reputation: 5 710

1

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
}

Karl Napf

Posted 2017-07-24T18:11:01.823

Reputation: 4 131

Nice job, can you include a try it link? – Noah Cristino – 2017-08-06T12:05:18.233

@NoahCristino sure, didnt know TIO can generate CodeGolf posts. Now i do :) – Karl Napf – 2017-08-06T14:06:00.813

1

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]

Chaos Manor

Posted 2017-07-24T18:11:01.823

Reputation: 521

Never heard of this language before great job! – Noah Cristino – 2017-08-22T01:00:02.903

1

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.

numbermaniac

Posted 2017-07-24T18:11:01.823

Reputation: 639

Cool! I don't know much about this language, but is it possible to add a try it link? – Noah Cristino – 2017-10-14T14:42:11.420

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 http://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. :)

– numbermaniac – 2017-10-15T01:09:22.683

Cool! I'll try it out. – Noah Cristino – 2017-10-15T12:21:38.823

1

ARBLE, 28 bytes

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

Try it online!

ATaco

Posted 2017-07-24T18:11:01.823

Reputation: 7 898

Nice job, never heard of ARBLE! – Noah Cristino – 2017-10-14T14:42:27.870

1

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

wastl

Posted 2017-07-24T18:11:01.823

Reputation: 3 089

Nice solution, never heard of Stax before! – Noah Cristino – 2018-05-03T20:45:47.023

0

Stacked, 7 bytes

[:rev+]

Try it online!

Just adding to the reversed.

Conor O'Brien

Posted 2017-07-24T18:11:01.823

Reputation: 36 228

Easy to understand! Output is ok I guess. – Noah Cristino – 2017-07-24T23:24:10.043

0

Tcl, 49 bytes

lmap l $L r [lreverse $L] {lappend N [incr l $r]}

Try it online!

sergiol

Posted 2017-07-24T18:11:01.823

Reputation: 3 055

0

Pari/GP, 14 bytes

a->a+Vecrev(a)

Try it online!

alephalpha

Posted 2017-07-24T18:11:01.823

Reputation: 23 988

0

Scala, 49 bytes

(a:Seq[Int])=>a.zip(a.reverse)map{case(a,b)=>a+b}

Lambda. Paste in the REPL, it gets assigned to a default variable, like res0 or whatever. Note the variable name from the output produced after pasting that line into the REPL and pressing Enter, let's say it's res4. To call the lambda, just use res4(Seq(1, 2, 3)) or res4(Seq(89, 88, 1, 2, 3, 1000, 2000)) for the test cases.

Implementation notes:

zip creates a Tuple2 from 2 Seqs, which need to be unpacked in the pattern match (the case expression after the map) before the elements can be added. Indexed access is convoluted for golfing in Scala...

Here's another version, using convoluted indexing tricks for 57 bytes:

(a:Seq[Int])=>{val l=a.size-1;0.to(l)map(i=>a(i)+a(l-i))}

This just produces a new Seq from adding the "complementary" elements of the Seqs (symmetrically about the mid of the Seq. Very imperative.

I don't like it either, but the type ascriptions are necessary to get the REPL to accept it, otherwise it just botches out Missing Parameter Type.

The idea in the 2nd version can be used in Java 8 as well, just swapping in IntStream.rangeClosed(0,l) instead of Scala's implicit to on Ints, unlike the former, which would be considerably more convoluted in Java.

Note that @jkelm's answer for C# can be trivially translated to Java.

Tamoghna Chowdhury

Posted 2017-07-24T18:11:01.823

Reputation: 373

0

R: 19 bytes

function(v)rev(v)+v

Try It Out: http://www.r-fiddle.org/#/fiddle?id=vJhwqK77

Xingzhou Liu

Posted 2017-07-24T18:11:01.823

Reputation: 101

Hello and welcome to the site. I don't know R very well This looks like what is called a snippet which we do not allow for answers here. Your answer may be either a function (anonymous or named) or a full program. – Post Rock Garf Hunter – 2017-07-26T05:31:40.707

0

Clojure, 21 bytes

#(map + %(reverse %))

Try it online!

Having trouble golfing this any further. Any clever ideas?

MONODA43

Posted 2017-07-24T18:11:01.823

Reputation: 131

1There's already a similar answer a little ahead of you. Flip the last two args to eliminate a space, and use rseq instead of reverse. – MattPutnam – 2017-07-26T19:09:20.123

0

Husk, 4 bytes

Sz+↔

Try it online! (Note if you want to test with empty list, you need to supply: []:LN as argument)

Ungolfed/Explanation

      -- implicit input list        - [1,2,3]
S     -- "duplicate input and"      - [1,2,3] [1,2,3]
   ↔  -- reverse one copy           - [1,2,3] [3,2,1]
 z+   -- zip with original using +  - [1+3,2+2,3+1]

ბიმო

Posted 2017-07-24T18:11:01.823

Reputation: 15 345

0

Perl 5, 24 + 1 (-a) = 25 bytes

print$_+$F[--$i],$"for@F

Try it online!

Xcali

Posted 2017-07-24T18:11:01.823

Reputation: 7 671

-2

J, 5 bytes

(+|.)

    (+|.) 1 2 3    ===> 4 4 4
    (+|.) 89 98 1 2 3 1000 2000  =====> 2089 1098 4 4 4 1098 2089

    NB. Does not work without the parentheses as per previous answer by @Jonah

Richard Donovan

Posted 2017-07-24T18:11:01.823

Reputation: 87

4While there's no shame in arriving independently at an answer that is identical to someone else's, this isn't the case here. +|. is valid on its own, so this is just a less golfed version of Jonah's answer. – Dennis – 2017-07-25T00:55:24.733