14
\$\begingroup\$

This question already has an answer here:

The rules are as follows:

  • Take in a string of integers separated by spaces. Add the first and last numbers, the second and second-last numbers, and so on.
  • The program must output the numbers separated by newlines.
  • The program must handle negative numbers, but may not handle decimals.
  • If an odd amount of integers are inputted, just print the lone integer at the end.
  • This is code golf, fewest bytes wins.

Here are some test cases:

> input
output
more output
etc.
-------------------
> 2 2
4

> 1 2 3 4 5 6
7
7
7

> 3 4 2 6
9
6

> 1 2 3 4 5
6
6
3

> -5 3 -8 2
-3
-5
\$\endgroup\$

marked as duplicate by betseg, dzaima, ბიმო, Nissa, H.PWiz Apr 25 '18 at 19:52

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 12
    \$\begingroup\$ "The program must deal with invalid input". I'd strongly suggest rethinking that requirement; input validation doesn't go down too well here. I'd also suggest loosening the I/O formats. Need we handle negative numbers? \$\endgroup\$ – Shaggy Mar 19 '18 at 18:51
  • 8
    \$\begingroup\$ Welcome to PPCG! I have a few questions, but this seems like it can be a good challenge. In the future, I would consider using The Sandbox to get some feedback. :) \$\endgroup\$ – Giuseppe Mar 19 '18 at 18:52
  • 9
    \$\begingroup\$ Like Shaggy, I would reconsider having to handle invalid input, especially since we have a consensus to allow programs to error on invalid input. \$\endgroup\$ – Giuseppe Mar 19 '18 at 18:52
  • 6
    \$\begingroup\$ Along with the requirement that invalid input must be dealt with there are a number of other restrictions here that I would remove. Input as a space separated string is unnecessarily complicated allowing answers to take input as a list of integers would be much nicer. Otherwise answers become almost entirely a parser. \$\endgroup\$ – Sriotchilism O'Zaic Mar 19 '18 at 19:11
  • 7
    \$\begingroup\$ I would upvote but the I/O requirement on strings and newlines is just fluff detracting from the actual challenge. \$\endgroup\$ – FantaC Mar 19 '18 at 23:06

30 Answers 30

9
\$\begingroup\$

Stax, 9 8 bytes

Thanks to Weijun Zhou for -1 bytes

It actually conforms with the required output format!

Φ┴⌐Öâ9|Ö

Run and debug it

Here's the ungolfed ascii representation of the program.

L   Concatenate all inputs into list
2M  Create two equal-ish size batches, with the bigger piece first
Er  Push the two parts to the stack, and reverse the second one
LM  Put two parts back together as 2-row matrix, then transpose
m|+ For each zipped pair, print the sum on a separate line

Run this one

\$\endgroup\$
  • \$\begingroup\$ 8 bytes. \$\endgroup\$ – Weijun Zhou Mar 20 '18 at 6:09
  • 1
    \$\begingroup\$ @WeijunZhou: Much appreciated. \$\endgroup\$ – recursive Mar 20 '18 at 6:18
7
+50
\$\begingroup\$

Perl 5 -a, 23 bytes

#!/usr/bin/perl -a
say$'*s//a/+pop@F for@F

Try it online!

Perl is unusual in that it is valid to change an array while you are looping over it. So you can have $_ walking from front to back while using pop to effectively walk from back to front while removing array elements which will stop the loop when they meet in the middle:

say$_+pop@F for@F

This however fails for an odd number of elements because in the middle both $_ and pop@F are that middle element so you get twice the value.

So instead I use another odd fact of perl loops: the loop variable is not a copy of the corresponding array position but is an alias for it. If you change $_ then you change the corresponding array element. In this case I want to both get the value of $_ and change it to 0 so that the pop@F returns zero when processing the middle element. The shortest way (without needing ()) to do that is s//a/ which changes e.g. 6 to a6 which evaluates to 0 in a numeric context. The part after the substitution is preserved in $' which will be 6 in the example. And since s/// returns the number of substitutions (1 in this case) the expression s//a/*$' will both set $_ to zero and return the original value.

This however would require a space after say. So finally I use yet another perl oddity, the fact that the expression stack also uses aliases of the values and variables you are processing. Therefore $'*s//a/ also works. When $' is put on the expression stack it is not set yet but when next s//a/ is executed it changes to the old value of $_ in place just before the multiplication is done. This is also the reason why the simpler seeming

say$_+($_=0)+pop@F for@F

does not work. The first $_ gets changed to 0 just before the first addition. You would need to force a copy with something like

say "$_"+($_=0)+pop@F for@F

to make that work

\$\endgroup\$
  • 1
    \$\begingroup\$ @msh210 added an explanation \$\endgroup\$ – Ton Hospel Mar 20 '18 at 6:33
  • 1
    \$\begingroup\$ Great explanation. \$\endgroup\$ – ninjalj Mar 20 '18 at 12:53
5
\$\begingroup\$

Python 3, 57 bytes, relaxed I/O

def f(a):
 try:x,*a,y=a;return[x+y]+f(a)
 except:return a

Try it online!

First time to see try..except in golfing.

print version, 57 bytes

def f(a):
 try:x,*a,y=a;print(x+y);f(a)
 except:print(*a)

Try it online!

printing instead of returning gives the same length.

Python 3, 73 bytes, strict I/O

a=*map(int,input().split()),
while len(a)>1:x,*a,y=a;print(x+y)
print(*a)

Try it online!

This prints an extra newline at the end if the number of elements is even.

\$\endgroup\$
4
\$\begingroup\$

JavaScript ES6, 100 97 bytes

_=>{for(_=_.split(' ').map(Number);0<_.length;)console.log(1<_.length?_.shift()+_.pop():_.pop())}

https://jsbin.com/nufanenehu/edit?js,console

First golfing answer ever. Be gentle.

\$\endgroup\$
  • \$\begingroup\$ Welcome to the site! A fair few people here use JavaScript so I'm sure you'll get some golfs in a while. Be sure to read these tips as well! \$\endgroup\$ – caird coinheringaahing Mar 19 '18 at 22:13
  • \$\begingroup\$ A simple thing you can do to save bytes is to drop the f=. Unnamed functions are fine as long as you don't need the function name for a recursive call or something like that. \$\endgroup\$ – Martin Ender Mar 19 '18 at 22:16
  • 1
    \$\begingroup\$ Welcome! There are a few golfing tricks you can use here: 1) x<_.length is essentially the same as x in _, so using 0 in _ and 1 in _? can save you a few bytes. 2) you can use this trick to do _=_.split` `.map(Number), saving 2 bytes. 3) ~~x converts the value of x to an integer, or 0 if this fails; combine this with the fact that _.pop() on an empty array returns undefined, and you can turn the entire final expression into console.log(_.shift()+~~_.pop()). \$\endgroup\$ – ETHproductions Mar 21 '18 at 2:34
4
\$\begingroup\$

05AB1E, 7 bytes

#2ä`R+»

Try it online!

Explanation

#          # split input on spaces
 2ä        # divide into 2 parts
   `       # split separately to stack
    R      # reverse the second one
     +     # add the lists of numbers
      »    # join on newlines
\$\endgroup\$
  • \$\begingroup\$ @JonathanAllan: "must handle negative" + "may not handle decimals" sounds to me like it means "does not have to handle decimals" rather that "must not handle decimals", but we'll see what the OP has to say. \$\endgroup\$ – Emigna Mar 20 '18 at 10:19
  • \$\begingroup\$ You could well be correct with your interpretation as it is not a separate bullet point. \$\endgroup\$ – Jonathan Allan Mar 20 '18 at 10:25
3
\$\begingroup\$

JavaScript (Node.js), 77 58 bytes

a=>g(a.split` `)
g=a=>+a.shift()+~~a.pop()+`
`+(a+a&&g(a))

Try it online!

Thanks to @Neil for chopping off 17 bytes at once. Also, I found that ~~ works instead of |0, which removes a pair of parens.

Original submission, 77 bytes

a=>g(a.split` `.map(x=>+x))
g=a=>a.shift()+(a.pop()|0)+`
`+(a.length?g(a):'')

Try it online!

Input as a space-delimited string, output as a newline-delimited string. First converts the input string into an array, then passes to a recursive function that generates the output string.

\$\endgroup\$
  • 1
    \$\begingroup\$ You don't need to map, just use +a.shift(), also you can use a+a&&g(a) instead of a.length?g(a):'', saving 17 bytes in total if I counted correctly. \$\endgroup\$ – Neil Mar 20 '18 at 0:51
3
\$\begingroup\$

Brainfuck, 61 bytes

>>+[>,]<[<]>->[[-<<+>>]>[>]<[[<]<<+>>>[>]<-]<[<]>]<<<[<]>[.>]

Try it online!

This program takes a null-terminated list of base-256 ASCII numbers as input :)

Commented Version

Read input chars until \0
>>+[>,]<
Clear initial 1
[<]>->
[
  Copy two to the left
  [-<<+>>]>
  Head to right side
  [>]<
  Subtract from right side add to left side repeat
  [[<]<< +>>> [>]< - ]
  Start at next spot
  <[<]>
]
Print it all out
<<<
[<]
>[.>]

Satisfying I/O requirements, 81 bytes

>>+[>,>,[-]<]<[<]>->[[-<<+>>]>[>]<[[<]<<+>>>[>]<-]<[<]>]<<<[<]>[.[-]++++++++++.>]

In this version the input characters must be separated and the output is split by newlines.

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

Jelly, 7 bytes

œs2U2¦S

Try it online!

Takes a list of integers, such as [1, 2, 3, 4, 5]. Outputs as an array, such as [6, 6, 3].

11 bytes to conform to the strict input specifications.

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

J, 28 bytes

>.@-:@#({.|:@,:@+/@,:|.@}.)]

ungolfed

>.@-:@# ({. |:@,:@+/@,: |.@}.) ]

Try it online!

My J is rusty and surely this could be improved -- suggestions encouraged. Almost all the complexity arises from the odd length case and the newline requirement. I had 22 bytes before I noticed the newline requirement:

>.@-:@# ({. +/@,: |.@}.) ]
\$\endgroup\$
2
\$\begingroup\$

R, 68 66 bytes

cat(c((n=scan())[y<-1:(x=sum(n|1)/2)],rep(0,x!=x%/%1))+rev(n[-y]))

Try it online!

Takes input from stdin as in the examples, and prints the output on stdout. Since using scan() is typically shorter than defining a function and taking an array as input, this is the shortest way to take input.

Reads in data, takes the first half (rounded down) of the list, and appends a zero (if necessary), then adds it to the reverse of the second half of the list.

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

Python 2, 46 bytes

f=lambda x:x[1:]and[x[0]+x[-1]]+f(x[1:-1])or x

Try it online!

x[1:] is just a shorter way to write len(x)>1

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

Python 3, 70 bytes

lambda a:[a[i]+a[~i]for i in range(len(a)//2)]+len(a)%2*[a[len(a)//2]]

Try it online!

+32 bytes for strict input:

Python 3, 102 bytes

a=[*map(int,input().split())]
l=len(a)
for q in[a[i]+a[~i]for i in range(l//2)]+l%2*[a[l//2]]:print(q)

Try it online!

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

Ruby + -p, 52 bytes (spec compliant)

a=$_.split.map(&:to_i);loop{puts a.shift+(a.pop||0)}

Try it online!

A full program, taking a string of space-separated integers and printing the results separated by newlines.

Normally the -p flag forces you to reassign the $_ variable, as it will be implicitly printed at the end of the program. However this code terminates with an NoMethodError when it calls + on nil (the result of shifting the head off an empty array), before that implicit print can happen.

Ruby, 33 bytes (relaxed IO)

->a{puts a.shift+(a.pop||0);redo}

Try it online!

This lambda skips the integer parsing code, and it is able to save 2 bytes by replacing loop{} with redo since it is already inside of a repeatable block. This also terminates with NoMethodError.

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

Haskell, 93 80 bytes

Saved 13 bytes thanks to Laikoni!

f s|x<-read<$>words s=mapM print$zipWith(+)(take(div(1+length x)2)x)$reverse$0:x

Try it online!

\$\endgroup\$
  • \$\begingroup\$ div(1+length x)2 instead of (1+length x)`div`2 saves two bytes. \$\endgroup\$ – Laikoni Mar 20 '18 at 11:53
  • \$\begingroup\$ You can get rid of the splitAt with zipWith(+)(take(div(1+length x)2)x)$reverse$0:x. \$\endgroup\$ – Laikoni Mar 20 '18 at 11:57
  • \$\begingroup\$ @Laikoni Thanks! Edited. \$\endgroup\$ – Cristian Lupascu Mar 20 '18 at 12:10
1
\$\begingroup\$

Clojure, 124 bytes

#(loop[l(map bigint(.split %" "))](println(+(first l)(or(last(rest l))0)))(if(>(count l)2)(recur(concat(butlast(rest l))))))

Try it online!

Ungolfed:

#(loop [l (map bigint (.split % " "))]
   (println (+ (first l) (or (last (rest l)) 0)))
   (if (> (count l) 2)
     (recur (concat (butlast (rest l))))))

An anonymous function that takes the input string and splits it. loop is rerun with every iteration with the "middle" items of the changing list if there are enough items left. Combining butlast and rest creates the "middle" list.
Interesting is the part where the sum is printed. Simply adding (first l) and (last l) only works for an even number of items. When an uneven number of items is passed, first and last will hit the same item. Using rest will remove the first item, in this case the only one, and return an empty list. Using last will return nil which is converted into zero by the or function.

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

Haskell, 78 72 70 67 bytes

mapM print.f.map read.words
f(x:r@(_:_))=(x+last r):f(init r)
f e=e

Try it online!

Edits:

  • -6 bytes by using mapM print instead of unlines.map show from GolfWolf's Haskell answer.
  • -2 bytes by removing +0 which I though was necessary for type inference but wasn't. Thanks to GolfWolf for pointing out.
  • -3 bytes by adding r@(_:_) to make the f[x]=f[x] pattern superfluous. Thanks again to GolfWolf.
\$\endgroup\$
  • \$\begingroup\$ Very nice solution! I think the +0 can be safely removed. \$\endgroup\$ – Cristian Lupascu Mar 20 '18 at 12:12
  • 1
    \$\begingroup\$ Here's an even shorter one. \$\endgroup\$ – Cristian Lupascu Mar 20 '18 at 12:16
  • 1
    \$\begingroup\$ x+last r doesn't need parentheses around it. \$\endgroup\$ – nimi Mar 20 '18 at 16:28
1
\$\begingroup\$

Perl 6 -n,  58  42 bytes

.&{$_,{S:s/(\S+) (.*?) (\S+)?$ {say $0+($2//0)}/$1/}...''}

Try it

.say for .=words[^*/2]Z+ |.[$_-1...$_/2],0

Try it


If the input/output restrictions are relaxed 40 bytes

*.[^*/2,{$_-1...$_/2}].&roundrobin».sum

Test it

\$\endgroup\$
  • \$\begingroup\$ You don't need to include command line flags to the byte count, as per this meta consensus. You can just specify the flags used as a part of the language, such as "Perl 6 -n, 58 bytes". \$\endgroup\$ – Bubbler Mar 20 '18 at 1:47
  • \$\begingroup\$ You can use the Z+ operator for 41 bytes: (.=words[^*/2]Z+ |.[$_-1...$_/2],0)>>.say \$\endgroup\$ – nwellnhof Mar 20 '18 at 13:51
  • \$\begingroup\$ @nwellnhof ».say can cause the results to be printed in any order so .say for .=words[^*/2]Z+ |.[$_-1...$_/2],0 would be more correct. (At one point the implementation would intentionally run them out of order) \$\endgroup\$ – Brad Gilbert b2gills Mar 20 '18 at 16:11
  • \$\begingroup\$ @nwellnhof Note that ».sum is fine as even though they can be calculated in any order, they are put back into the right order in the result. \$\endgroup\$ – Brad Gilbert b2gills Mar 20 '18 at 16:28
  • \$\begingroup\$ Right. Z+ also doesn't guarantee that the left operand is evaluated before the right operand, so you'd actually need .=words;.say for .[^*/2]Z+ |.[$_-1...$_/2],0. But relying on implementation quirks is OK according to meta, so it's mostly a matter of taste. \$\endgroup\$ – nwellnhof Mar 20 '18 at 16:36
1
\$\begingroup\$

Java (OpenJDK 9), 76 bytes

a->{for(int i=0,l=a.length;i<l--;)System.out.println(i<l?a[i++]+a[l]:a[i]);}

Try it online!

With strict input

Java (JDK 10), 115 bytes

s->{var a=s.split(" ");for(int i=0,l=a.length;i<l--;)System.out.println(i<l?new Long(a[i++])+new Long(a[l]):a[i]);}

Try it online!

Credits

  • -10 bytes on strict input thanks to Kevin Cruijssen
\$\endgroup\$
  • 1
    \$\begingroup\$ Nice trick with i<l--. I'll delete my longer answer. Although, you currently are ignoring the rule "Take in a string of integers separated by spaces.".. It would be 119 bytes with that rule (probably more golfable). \$\endgroup\$ – Kevin Cruijssen Mar 20 '18 at 8:51
  • 1
    \$\begingroup\$ @KevinCruijssen Oops, I didn't see your post... Sorry. Thanks for the reminder on the strict input and for the following nice golfs! \$\endgroup\$ – Olivier Grégoire Mar 20 '18 at 8:57
1
\$\begingroup\$

JavaScript (Node.js), 56 bytes

f=x=>([a,m='',b]=x.split(/ (.*) | /),b?a- -b+`
`+f(m):a)

Try it online!

Split the string by all the middle numbers and capture them all as a group, add the ends (coercing strings to numbers via a- -b, which is shorter than any alternatives I know of), and concatenate the result with a line break and f(all captured middle numbers) where available.

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

Python 3, 108 bytes

i=[*map(int,input().split())]
l=len(i)
for a,b in zip(i,i[:int(l/2-.5):-1]):print(a+b)
if l&1:print(i[l//2])

Try it online!

Non competitive, just thought it would be nice to share this zip approach :)
Too bad slicing and reversing in python is a bit finicky

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

Python 2, 111 107 103 bytes

i=map(int,input().split())
for y in[i[x]+i[-(x+1)]for x in range(len(i)/2)]+[i[x+1]]*(len(i)%2):print y

Try it online!

Takes input in "strict" format (space separated string of numbers) and outputs a trailing newline if the count is even. Works because in Python 2, list comprehensions leak the last value of the variable x so it can be used later to identify the middle number.

Python 2, 79 75 69 bytes

lambda i:[i[x]+i[-(x+1)]for x in range(len(i)/2)]+[i[x+1]]*(len(i)%2)

Try it online!

Shorter version with input and output as lists. Adds an empty string to the output for even numbers.

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

FORTH 76 Bytes

: A BEGIN DEPTH 1 - ROLL + CR . DEPTH 2 <= UNTIL DEPTH 1 = IF CR . THEN ;

Output:

1 2 3 4 5 a
6
6
3  ok

2 2 A
4  ok

-5 3 -8 2 A
-3
-5 ok
\$\endgroup\$
0
\$\begingroup\$

Python 2, 112 bytes

def f(s):
 s=[int(i)for i in s.split(' ')];s.insert(len(s)//2,0)
 for i in range(len(s)//2):print s[i]+s[-i-1]
\$\endgroup\$
0
\$\begingroup\$

Perl 6/Rakudo 45 bytes

Perl6 -ne

{say .shift+(.pop||0) while $_}(.words.Array)

Super simple, shifts and pops, Perl makes the empty list (with odd count) easy with .pop||0.

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

Red, 105 bytes

func[s][b: to-block s
l: length? b
repeat n l / 2[print b/(n) + b/(l - n + 1)]if odd? l[print b/(n + 1)]]

Try it online!

Red, 91 bytes (Relaxed IO - a list ot integers)

func[b][l: length? b
repeat n l / 2[print b/(n) + b/(l - n + 1)]if odd? l[print b/(n + 1)]]

Try it online!

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

Python 3, 136 bytes

def f(x):
 x,o=[int(i) for i in x.split()],[];y=len(x)
 for i in range(int(y/2)):o+=[x[i]+x[-i-1]]
 if y%2!=0:o+=[x[int(y/2)]]
 return o

Try it online!

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

Ruby, 67 bytes

This can probably be improved, but I'm not sure how...

def x(a);puts a.shift.to_i+a.pop.to_i;return if a.length==0;x a;end

Try it online!

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

C, 128 bytes

This version is more in keeping with the terms of the challenge, but has a hard-coded maximum of 9 numbers that it can accept.

i[9],j,k;f(char*s){for(s=strtok(s," ");j++,s;i[j]=atoi(s),s=strtok(0," "));while(--j>=++k)printf("%d\n",i[j]+(j==k?0:i[k]));}

Try it online!

I let C do the tokenizing for me, which allows me to send each string directly to atoi(). Afterwards, I just add the mirror indexes until the start>end.

As I couldn't get a array length and strtok() destroys the original string, making backtracking difficult, and I didn't want to have to realloc() to resize arrays, I hard-coded an array with a maximum of 9 values.

C, 107 bytes (uses argv)

i,j,*k;f(char**s){k=(int*)s;while(s[++i])k[i]=atoi(s[i]);while(++j<=--i)printf("%d\n",k[i]+(i==j?0:k[j]));}

Try it online!

This version makes use of the fact that argv already has been tokenized; as a bonus, it doesn't have a hard-coded limit on the number of numbers! It does, however, assume that sizeof(int)==sizeof(char*), which is truly evil and non-portable.

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

PHP, 107 bytes

New to this, so please forgive my lack of correct formatting.

for($i=0,$a=explode(" ",$argv[1]),$c=count($a);$i<$c/2;$i++)echo$i==$c-$i-1?$a[$i]:$a[$i]+$a[$c-$i-1]."\n";

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ Welcome to PPCG! It looks like you've hardcoded the input into your solution. That's not generally valid (among other reasons because it means that your byte count depends on the specific input you chose). Answers either need to be full programs or callable functions. You can have a look at this list for valid I/O methods. (I don't know which option is the shortest in PHP. \$\endgroup\$ – Martin Ender Mar 21 '18 at 9:38
  • \$\begingroup\$ OK thanks, Ill see what the best input mechanism is and update accordingly! \$\endgroup\$ – Dave Mar 21 '18 at 10:25
0
\$\begingroup\$

Java (OpenJDK 8), 163 bytes

a->{String[] b=a.split(" ");int c=b.length;a="";for(int d=0;d<c/2;d++){a+=(Integer.parseInt(b[d])+Integer.parseInt(b[c-1-d]))+"\n";}if(c%2>0){a+=b[c/2];}return a;}

Try it online!

Well It’s sure not going to win me the bounty, but all in all I’m pretty happy with my work here.

Explanation:

a->{String[] b=a.split(" ");    //Create String array to get rid of the pesky spaces
int c=b.length;    
a="";    //Since we now only need the array, we can reuse the original string to save a few bytes
for(int d=0;d<c/2;d++){    //Loop half(even) or half-1(odd) of the array length
  a+=(Integer.parseInt(b[d])+    
   Integer.parseInt(b[c-1-d]))+    //Add the ‘rainbow pairs’ to the output string
  "\n";}    //Add a newline to each sum and end the loop
if(c%2>0){a+=b[c/2];}    //If the number of input numbers is odd, print the middle digit
return a;}    //the Output string is the Input string
\$\endgroup\$
  • \$\begingroup\$ Save 28 bytes by using a few tricks and switching to Java 10: a->{var b=a.split(" ");int c=b.length;a="";for(int d=0;d<c/2;d++)a+=new Long(b[d])+new Long(b[c-1-d])+"\n";return a+(c%2>0?b[c/2]:"");} \$\endgroup\$ – Okx Mar 24 '18 at 11:40

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