Suma odwrotnej tablicy


34

Twój program powinien przyjąć tablicę jako dane wejściowe.

Tablica:

  1. Zawsze będzie jednowymiarowy
  2. Będzie zawierać tylko liczby całkowite
  3. Może być pusty

Program powinien odwrócić tablicę, a następnie dodać elementy do oryginału, na przykład:

Wkład: [1, 2, 3]

Oryginalny: [1, 2, 3]

Wywrócony: [3, 2, 1]

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

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

Wydajność: [4, 4, 4]


Przypadki testowe:

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

To jest , wygrywa najkrótszy kod (w bajtach)!


J 3 bajty. Program jest t. t =: + |.
Richard Donovan

@RichardDonovan Nice Answer! Czy możesz przesłać jako odpowiedź zamiast komentarza, proszę :)
Noah Cristino

Odpowiedzi:


13

Haskell , 20 bajtów

Oszczędzaj 5 bajtów, zmieniając na wolny punkt, jak sugerują nimi

zipWith(+)=<<reverse

Wypróbuj online!


4
iść pointfree: zipWith(+)=<<reverse.
nimi

@nimi Wow, nie pomyślałem o tym, ale to całkiem sprytne.
Wheat Wizard

Gdzie mam umieścić tablicę? Próbowałem argumentów i włączyłem TIO
Noah Cristino

@NoahCristino Naprawiłem TIO. Jest to funkcja bez punktów, więc wystarczy wstawić dane wejściowe po funkcji, jednak Haskell wymaga mainkompilacji.
Wheat Wizard

3
@maple_shaft: korzystamy =<<z monady funkcji, która jest zdefiniowana jako: (=<<) f g x = f (g x) x. Tutaj napisane infiksem: (zipWith(+) =<< reverse) x-> zipWith(+) (reverse x) x.
nimi

11

Galaretka , 2 bajty

+U

Wypróbuj online!

lub

+Ṛ

Wypróbuj online! (dzięki @Mr. Xcoder za drugi program)

wyjaśnienie, chociaż jest dość oczywiste

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

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

W przypadku pustej tablicy []nic nie wyświetla. To jest poprawne. Przedstawienie przez Jelly pustej listy jest po prostu niczym. Zauważ, że reprezentacja Jelly listy z pojedynczym elementem jest tylko samym elementem. Dołącz ŒṘdo kodu, aby zobaczyć wewnętrzną reprezentację danych wyjściowych w języku Python.


Znalazłem 2 problemy. 1) Po przetestowaniu na [9]nim wyprowadza 18 zamiast [18], oraz 2) po przetestowaniu na []nim niczego nie wypisuje .
Noah Cristino

@NoahCristino To nie jest pełny program, a odpowiedź na to pytanie jest już wyjaśniona.
Erik the Outgolfer

Myślę, że to jest w porządku, tak właśnie wygląda Jelly
Noah Cristino,

@NoahCristino Tak. Dodałem część na końcu mojej odpowiedzi, abyś mógł umieścić ten atom na końcu kodu, aby zobaczyć, jak Python by go wydrukował.
HyperNeutrino

+Ṛteż działa.
Pan Xcoder

11

JavaScript (ES6), 27 bajtów

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


Och, człowieku, byłem prawie na miejscu, ale nie pomyślałem o użyciu operatora rozprzestrzeniania, aby wykonać klon.
Rick Hitchcock

Czy możesz dodać osadzony wypróbuj go dla javascript?
Noah Cristino


9

Python 2, 32 bajty

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!



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.


1
Good job! I like the multiple input thing!
Noah Cristino

1
I really like the multiple-input Japt interpreter. Nice job!
Oliver

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



6

Python 2, 33 32 bytes

-1 byte thanks to @xnor

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

Try it online!


Passed all my tests good job :)
Noah Cristino

What an unusual method. l*1 saves a byte.
xnor

I am having difficulties understanding the par l*1, any elaboration
dhssa

@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

Thanks for the explanation, I got it now. good trick to know for coding.
dhssa


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.


1
Good answer. Thanks for the comment about the input.
Noah Cristino

1
Hello 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

@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




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!


For an empty "array" it returns numeric(0)
Noah Cristino

1
@NoahCristino an empty vector is represented as numeric(0) in R.
Leaky Nun

That's fine. @LeakyNun
Noah Cristino

1
rev(l<-scan())+l, 16 bytes?
djhurio

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



3

PowerShell, 26 bytes

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

Try it online!

Takes input as command-line arguments.


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

@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

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

3

C, 49 bytes

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

Shouldn't a,n,b be a,b,n or something?
Erik the Outgolfer

@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

Could you please add a TIO link?
Noah Cristino

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


it doesn't output an array.
Noah Cristino

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

Good enough then :) atleast it tried
Noah Cristino

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

@briantist Not quite, but you did give me a different way of thinking about it, saving a bunch of bytes. Thanks!
AdmBorkBork

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

1
You 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

1
Besides 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

@Nevay Thanks. I knew it should be possible to golf l-i-1, just couldn't come up with it..
Kevin Cruijssen

2
53 bytes: a->{for(int l=0,r=a.length;l<r;a[l]=a[--r]+=a[l++]);}.
Olivier Grégoire

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



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

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!


Is it allowed to modify the input stack via actual Neim code instead of normal input methods?
LiefdeWen

@LiefdeWen Yes, that's allowed in the defaults for I/O meta post.
Okx

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

Passes my tests! Great answer.
Noah Cristino

2

JavaScript (ES6), 34 33 bytes

Saved a byte thanks to @ETHproductions.

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


I love how you put in the test cases, +2
Noah Cristino

I think you can save a byte by changing -i-1 to +~i.
ETHproductions

@ETHproductions, yes, thanks!
Rick Hitchcock


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

Nice answer! :)
Noah Cristino
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.