# Binary Reduce a List By Addition With a Right Bias

Given a list of 2 or more strictly positive integers, sum the first and last half of the list, with the middle element being counted only in the right half if the list has an odd number of elements

Some examples of the middle element being counted in the right half:

[1, 2, 3, 4]       -> Left: [1, 2];    Right: [3, 4]
[1, 2, 3]          -> Left: [1];       Right: [2, 3]
[1, 2, 3, 4, 5]    -> Left: [1, 2];    Right: [3, 4, 5]
[1, 2, 3, 4, 5, 6] -> Left: [1, 2, 3]; Right: [4, 5, 6]


## Test Cases

### Input

[1, 9]
[9, 5, 5, 7]
[6, 7, 5, 1, 3, 9, 7, 1, 6]
[2, 8, 10, 9, 9, 3, 7, 8, 9, 8, 6, 1, 2, 9, 8, 3, 8, 9, 5]
[2, 3, 1, 8, 6, 2, 10, 6, 7, 6]


### Output

[1, 9]
[14, 12]
[19, 26]
[65, 59]
[20, 31]


Reference Program With Two Output Methods

## Rules

• Input/Output can be Taken/Given in any convenient and reasonable format.
• Functions and full programs are both acceptable.
• So just to confirm, we're permitted to return the two sums in reverse order (right sum then left sum)? May 2 '20 at 18:17
• Yes you are allowed to. May 2 '20 at 18:44
• Can the output be in reverse order? May 2 '20 at 19:28
• @Shaggy The question is asked and answered above May 2 '20 at 19:59

# Python 2, 40 bytes

Takes as input a list $$\ l \$$, and outputs the two sums in reverse order ([right, left]).

lambda l:[sum(l.pop()for x in l),sum(l)]


## Explanation

In sum(l.pop()for x in l), we pop the last element, in each iteration, and sum the popped elements. Surprisingly, the loop only runs $$\ \lceil{\frac{|l|}{2}}\rceil \$$ times, since for every element we iterate from the left, we are removing an element from the right, resulting in the loop terminating somewhere in the middle. Therefore it gives us the sum of the right portion of the list. The sum of the remaining elements make up the left portion.

Try it online!

• That's a clever use of .pop() to ensure that only half of the list is summed... That took me a while to figure out how it was doing it! May 2 '20 at 17:28

# Python 3.8, 41 bytes

lambda l:[t:=sum(l[:len(l)//2]),sum(l)-t]


Try it online!

Straightforward solution. Takes in a list, and returns the list of left and right sum.

Interesting idea that didn't go anywhere :(

### Python 3, 45 bytes

lambda l,t=1j:l>[]and l[-1]+t*f(l[-2::-1],-t)


Try it online!

Returns a+bj where a, b is the right and left sum respectively.

f x=[sum$y(div(length x)2)x|y<-[take,drop]]  Try it online! Based on Steven Fontanella's answer with some non-trivial modification. # K (ngn/k) / oK / K4, 8 bytes +/'2 0N#  Try it online! • ...also works in K4 and oK if you wanted to add them to the title – mkst May 19 '20 at 11:54 • @streetster Thanks! I think I tried it in oK. May 19 '20 at 13:03 # J, 14 bytes -@>.@-:@#+/\|.  Try it online! Output is in reverse. # Pyth, 6 5 bytes Outputs the two sums in reverse order (right sum, then left sum) sMc2_  Try it online!  sMc2_ _ Reverse the input c2 Chop into 2 equal-sized chunks, with the first chunk one element longer if necessary sM Sum each chunk  # Rust, 71 bytes |x:&[u8]|{let s=x[..x.len()/2].iter().sum();(s,x.iter().sum::<u8>()-s)}  A closure that takes a reference to a slice of 8-bit unsigned numbers and returns a tuple of two 8-bit unsigned numbers. try it online on the rust playground. # Haskell, 50 bytes f x=(\(a,b)->sum<$>[a,b])$splitAt(length xdiv2)x  Try it online! • Lambdas almost always have a shorter alternative. In this case you save a bye with a helper May 2 '20 at 22:27 • @AdHocGarfHunter Would love to see it! For some reason, it the TIO link shows up empty, though... (on my phone) May 3 '20 at 0:23 # Jelly, 4 bytes ŻŒH§  A monadic Link accepting a list which yields the pair: first-half-sum, last-half-sum. Try it online! ### How? ŻŒH§ - Link: list, A Ż - prepend a zero to A ŒH - split that in half (if the length is odd the first half gets the extra element) § - sums  # Rust macro, 480 bytes macro_rules!f{($($r:expr)*)=>{f!(@I;[$($r),*];[];)};(@$($d:ident)*;[];[$($a:tt)*];$($b:tt)*)=>{f!(%($)0;0;[$($a)*]$($b)*)};(@$($d:ident)*;[$x:expr$(,$r:tt)*];[$($a:tt)*];$($b:tt)*)=>{f!(@I$($d)*;[$($r),*];[$($a)*;($($d)*,$x)];($($d)*,$x);$($b)*)};(%($m:tt)$s:expr;$t:expr;[;($($d:ident)+,$x:expr)$($a:tt)*]$(;)*($($e:ident)*,$y:expr)$($b:tt)*)=>{{macro_rules!i{($($d)*$m(I)+)=>{f!(%($m)$s+$x;$t+$y;[$($a)*];$($b)*)};($($d)*)=>{($s,$t+$y)};($m(I)*)=>{($s,$t)}}i!($($e)*)}};}  try it online This is kind of insane and I kind of hate myself now. The code defines a macro that takes a sequence of whitespace-seperated numbers and expands to a tuple of 2 integers. Everything is calculated at compile-time, so the code runs in $$\O(1)\$$, but compile times may vary. For an introduction to Rust macros, I recommend the Rust book, the Rust refeence and The Little Book of Rust Macros. ## Explanation So rust macros operate on token streams that are matched against patterns. For our case, the main difficulty is that you basically have to consume the token stream front-to-back. To defeat this, I first replace the list of numbers with two numbers, where one of them is reversed. Also, to be able to find the middle, I put an index next to each number. Since yout can't evaluate integer expression like 0+1, I use a tally counter made up of I identifier tokens. That way, I can detect the midpoint by comparing the length of the tally counter. Each part is replaced with ad addition of all its components, which can be evaluated at compile time. ### Example Let's use 1 2 3 as an example. This shows the basic idea, but is still simplified a bit. 1 2 3 [1 2 3] [] [] // input forward backward [2 3] [(I, 1)] [(I, 1)] [3] [(I, 1); (I I, 2)] [(I I, 2); (I, 1)] [] [(I, 1); (I I, 2); (I I I, 3)] [(I I I, 3); (I I, 2); (I, 1)] 0; 0; [(I, 1); (I I, 2); (I I I, 3)] [(I I I, 3); (I I, 2); (I, 1)] // two accumulators 0 + 1; 0 + 3; [(I I, 2); (I I I, 3)] [(I I, 2); (I, 1)] (0 + 1; 0 + 3 + 2)  Refer to the compiler output in the rust playground for the complete expansion. // Define a macro called f macro_rules! f { // This rule is the starting point // It matches any number of expressions ($($r:expr)*) => { // Use the internal rules with an at sign. // Provide the I as the first index. f!(@ I; [$($r),*]; [];) }; // The rules starting with an at sign are responsible for producing a reversed version // of the input and counting with tallys. // This pattern is known as tt-muncher because it consumes a token tree recursively. // This is the base case. It matches when the input is an empty set of brackets. (@$($d:ident)*; []; [$($a:tt)*];$($b:tt)*) => { // Call the second set of internal macros (the ones starting with a percent sign). // We use zeros as the accumulators f!(% ($) 0; 0; [$($a)*] $($b)*)
};
// This is the recursive case.
// It extracts one expression (called x) from the input.
(@ $($d:ident)*; [$x:expr$(,$r:tt)*]; [$($a:tt)*];$($b:tt)*) => { // Call the at-macro recursively. // Add one I to the current tally list. // append (tallys,$x) to the first "array".
// prepend (tallys, $x) to the second "array". f!(@ I$($d)*; [$($r),*]; [$($a)*; ($($d)*,$x)]; ($($d)*,$x);$($b)*) }; // This part of the macro is called with the original and the reversed version. // The first argument is a dollar sign because that it needed later. // It extracts the count$d and value $x of the forwards array, // and count$e and value $y of the backwards array. (% ($m:tt) $s:expr;$t:expr; [; ($($d:ident)+, $x:expr)$($a:tt)*]$(;)* ($($e:ident)*, $y:expr)$($b:tt)*) => { { // To compare the two tally counters at compile time, we use an internal macro. // It defined rules based on$d.
// The argument of this macro will be $e. macro_rules! i { // This case matches when$e is larger than $d. // That means we haven't found the end yet. ($($d)*$m(I)+) => {
// call this part recursively, adding $x and$y to their accumulators
f!(% ($m)$s+$x;$t+$y; [$($a)*];$($b)*) }; //$e and $d are equal. // This case is reached when there is an odd number of element in the input. ($($d)*) => { // Add the value to the right accumulator and expand to a tuple ($s, $t+$y)
};
// $e is less than$d.
// We have moved past the midpoint.
($m(I)*) => { // Expand to a tuple containing the accumulators ($s, $t) } } // call the internal macro with$e
i!($($e)*)
}
};
}


# Octave, 33 bytes

@(x)x*[u=(t=find(x))<mean(t);~u]'


Try it online!

### How it works

@(x)x*[u=(t=find(x))<mean(t);~u]'

@(x)                               % Define an anonynous function with input x
find(x)                % Indices of nonzero entries of x. Gives [1 2 ... n]
% where n is the length of x
(t=       )               % Assign that to variable t
<mean(t)       % Test if each entry of t is less than the mean of t.
% This gives [1 ... 1 0 ... 0], with floor(n/2) ones
% and n-floor(n/2) zeros
u=                          % Assign that to variable u
[                     ;~u]   % Build a 2×n matrix containing u in the first row
% and u negated in the second row
'  % Conjugate transpose. Gives an n×2 matrix
x*                             % Matrix-multiply x (size 1×n) times the above n×2
% matrix. Gives a 1×2 vector containing the result


# brainfuck, 180 bytes

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


Try it online! (testcase [2, 8, 10, 9, 9, 3, 7, 8, 9, 8, 6, 1, 2, 9, 8, 3, 8, 9, 5])

Takes input as bytes on stdin. Outputs the two sums as bytes on stdout in reverse order.

Compiled from this VBF 1.0 code with mapping requirement x:5 :

# set y to 2
y++

# Input is to the right of x; which is the length and the divdend
# Ensure that x is the rightmost variable
# x is the length of a length-prefixed array of numbers
x+>,[[<]>+[>],]
<[<]>
#cursor is at x
# x = x / y
# from user Calamari from esolangs wiki at https://esolangs.org/wiki/Brainfuck_algorithms
x[A+x-]
A[
y[B+C+y-]
C[y+C-]
B[
C+
A-[C[-]D+A-]
D[A+D-]
C[
B-
[x-B[-]]+
C-]
B-]
x+
A]
# After this, x = x / 2, A,B,C,D = 0, y = y
# If x, x = x - 1
# from https://esolangs.org/wiki/Brainfuck_algorithms#if_.28x.29_.7B_code_.7D
x[D+A+x-]D[x+D-]
A[
x-
A[-]
]

# Add up first half, cursor starts at x
# Requires that the cell to the left of x is 0
x[
[>]<   # last input
[<+>-] # add into left neighbor
<[<]>- # back to x, decrement x
]

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


# Brachylog, 3 bytes

ḍ+ᵐ


Try it online!

Brachylog's cut-a-list-in-half predicate just so happens to already make the right half larger.

# brainfuck, 45 43 bytes

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


Shorter, but assumes ',' continues to return 0 after EOF, not just the first time after EOF.

Earlier version:

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


Reads numbers as characters, outputs right sum first.

# APL (Dyalog Extended), 12 bytes

Anonymous tacit prefix function

+/2 ¯.5⍴⌽,0⍨


Try it online!

0⍨ zero

⌽, appended to the reverse of the argument

2 ¯.5⍴reshape to 2 rows and as many columns as needed, chopping trailing elements if uneven

+/ sum the rows

# JavaScript (ES6),  47  45 bytes

Outputs in reverse order.

a=>[a.reduce(s=>s+a.pop(),0),eval(a.join+)]


Try it online!

# 05AB1E, 4 bytes

R2äO


Try it online!

# Clojure, 47 bytes

#(for[x(split-at(quot(count %)2)%)](apply + x))


Try it online!

# asm2bf, 157 bytes

A rather long submission. Let's take a look at the golfed code first:

@l
in r1
cner1,0
cpsr1
cjn%l
movr3,r2
modr3,2
divr2,2
movr4,r2
@x
popr1
decr2
jnzr2,%x
@y
popr1
decr4
jnzr4,%y
outr6
outr5


Try it online!

# I/O format

The program takes input in form of so-called ASCII characters, and produces the output analogically. It's recommended to test the program on a 16-bit brainfuck interpreter (so that the addition doesn't overflow quickly).

asm2bf is a separate language to brainfuck, therefore the Brainfuck restrictions theoretically don't apply to it (because for instance, asm2bf specification says that registers for programmer's convience are at least 16 bits long), but as there is no asm2bf interpreter on TIO, I have to somehow cope with these limitations.

That being said, let's look at some I/O examples:

!"#$% => [33, 34, 35, 36, 37] => [33 + 34, 35 + 36 + 37] => [67, 108] => Cl !"#$ => [33, 34, 35, 36] => [33 + 34, 35 + 36] = [67, 71] => CG


# Explanation

Let's take a look at the ungolfed representation of the code.

## Golfing 101

@inloop
in r1
cne r1, 0
cpush r1
cjn %inloop

mov r3, r2
mod r3, 2
div r2, 2
mov r4, r2

@right
pop r1
dec r2
jnz r2, %right

@left
pop r1
dec r4
jnz r4, %left

out r6
out r5


=> Why does the code compile without spaces between operand and the operation?

The answer is quite simple: the assembler is a very primitive tool. It assumes instruction length of three, therefore after reading instruction name, all spaces are then consumed (but obviously there can be no spaces inbetween).

=> Why is there a space between in and r1?

in is a special instruction, because it has two character length. Under the hood, it's padded to three characters using the floor character (_). Therefore, if the space was ommited, then the assembler would interpret r as the instruction name.

=> Instructions changed. cpo took place of cpush, cad of cadd. Why?

It is perfectly legal, because if every instruction has to have a three byte name, then there must be some alias that magically swaps long instruction names into short instruction names, right?

That's the full list of aliases, as of v1.3.9 (taken from the lib-bfm.lua file):

; Don't ask questions, this is beyond explaining
?band=x00
?bor=x01
?bxor=x02
?bneg=x03
?cflip=x04
; Some common defines
?push=psh
?xchg=swp
; Conditional instructions
?csub=csu
?cmul=cmu
?cdiv=cdi
?cmod=cmd
?casl=csl
?casr=csr
?cpow=cpw
?cpush=cps
?cpsh=cps
?cpop=cpo
?cxchg=csw
?cswp=csw
?csrv=crv
?cmov=cmo
?crcl=crc
?csto=cst
?cout=cou


That being said, let's dive into the algorithm.

## Algorithm

Let's dissect the code step by step for better understanding:

@inloop
in r1
cne r1, 0
cpush r1
cjn %inloop


Some parts are obvious (label declarations for example), some are less. A new feature introduced around v1.3.5 named conditional instructions helps us greatly to solve this task.

The conditional pipeline of this fragment follows:

; if r1 is not zero, set the flag, otherwise clear it
cne r1, 0
; if flag is set, add 1 to r2 (we accumulate the list length)
; push the number on the stack if the flag is set.
cpush r1
cjn %inloop


As you can see, it's quite simple to notice, that this tiny block of code will is responsible for:

• accumulating it's elements on the stack
• keeping track of the amount of elements read (in r2)
• looping until hit EOF

Note: Yes, it's true that you have to set the stack before accessing it, otherwise stack overflow error occurs. In this case, I simply don't make memory accesses, so it's not required to set the stack (because it has nowhere to overflow to)

Between these two loops, there is a tiny block of setup code:

; r3 = r2
mov r3, r2
; r3 = r2 mod 2
mod r3, 2
; r2 = r2 / 2
div r2, 2
; r4 = r2
mov r4, r2
; r2 = r2 + r3


This means, the register values are now:

r4 = r2 / 2
r3 = r2 mod 2
r2 = (r2 / 2) + r3


r3 is used as a flag to indicate whenever the middle element is present and it has to be merged to the list on the right (if count mod 2 is 1, then the count is odd, therefore we have a middle element obviously). The flag is added to the r2 register so the following loop will slurp it from the stack.

Next, there are two very simillar loops. Let's dissect these:

@right
pop r1
dec r2
jnz r2, %right

@left
pop r1
dec r4
jnz r4, %left


@right will execute until r2 is not zero (id est, the amount of elements left to extract from the stack to make the right list). Everytime an element is popped, the pointer (r2) decreases and the popped value is added to r5.

This being said, @right will simply extract r2 elements from the stack and sum them up to r5.

@left works pretty much the same (it will build the list on the left) returning the result in r6.

And finally, we output both values (sum for the left and the right):

    out r6
out r5


# Appendix A

Generated brainfuck code (around 1.9 kilobyte):

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


# Appendix B

The code possibly can be golfed down using constpp - the tool used to set macros on certain [A-Za-z]+ strings and alias them into other, preferably longer strings. Syntax: ?find=replace

There is a tiny chance that one could golf the code down using Lua preprocessor. If you'd like to start a multiline Lua block, use \${...) syntax; single line Lua statements can be prepended with #.

Example on both methods: lib-bfm.lua.

lib-bfm is a file included everytime an assembly program is built using bfmake tool (the one to assemble your code into a ready-to-use Brainfuck program). It's overall recommended to take advantage of it, because it contains some predefined macros (like a memory allocator or quite basic code-preprocessing capabilities).

PS: If anything is unclear, please let me know down in the comments. I'll try to clarify it when I'll have some time on my hands.

# R, 46 45 bytes

sum((v=scan())[l<-1:(sum(v|1)/2)]);sum(v[-l])


Try it online!

Edit: thanks to Giuseppe: -1 byte

• use l<-... instead of (l=...); it's a byte shorter :-) May 19 '20 at 17:03
• Thanks again Giuseppe! BTW: do you have any idea why <- should be designed to behave differently to = in this context (apart from sneaky code golf use)? May 19 '20 at 19:36
• The docs say The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions. So since l is actually an argument to the [ function, it's not at the top level. Or so I believe. May 19 '20 at 19:43
• Thank you: I will try to digest what that means. It's quite disconcerting to imagine that I might actually learn something useful while trying to just waste my time code golfing... May 19 '20 at 19:54
• You're not the only one! Myself included, haha. Sometimes my golfing habits kick in when writing real R code, though... May 19 '20 at 19:55

# Risky, 12 bytes

_?+_0\!?/_2_+?+_0+_0+_0


Try it online!

# Charcoal, 12 bytes

Ｆθ⊞υ⊟θＩ⟦ΣθΣυ


Try it online! Link is to verbose version of code. Port of @dingledooper's answer. Explanation:

Ｆθ


Loop over the list.

⊞υ⊟θ


Move the last element of the list to the empty list.

Ｉ⟦ΣθΣυ


Output the sums of the lists.

# C (gcc), 77 bytes

i,l;f(a,n)int*a;{l=0;for(n-=i=n/2;i--;!i?i=n,n=l=!printf("%u ",l):0)l+=*a++;}


Takes as input an array and its size.

Try it online!

# APL+WIN, 18 bytes

Prompts for vector of integers:

+/(2,⌈.5×⍴s)⍴s←0,⎕


Try it online! Coutesy of Dyalog Classic

# Red, 52 bytes

func[a][reduce[sum take/part a(length? a)/ 2 sum a]]


Try it online!

# Husk, 4 bytes

mΣ½↔


Try it online!

# Explanation

   ↔ Reverse the input
½  Split the input into about-equal parts of 2
m    For every item in the list:
Σ       Sum this list


# dc, 35 bytes

?[zRla+salFx]sU[lb+sbz0<U]dsFxlblaf


Try it online!

Verify the test cases online.

Input is a space-separated list of numbers on stdin.

Output is on stdout, on two lines: the sum of the left part, then the sum of the right part.

How it works:

?        Read the input and push it on the stack.
(The last number in the list is at the top of the stack.)

[        Start a macro.
zR        Move the bottom item on the stack to the top,
moving the rest of the stack down one item.
la+sa     Pop the top item on the stack and add it to register a.
This number comes from the left part.
lFx       Execute F recursively.
]sU      End the macro and name it U.

[        Start a macro.
lb+sb     Pop the top item on the stack and add it to register b.
This number comes from the right part.
(Note that if the stack is empty so that there's
nothing to pop, then b is left unchanged.
This will happen the last time through when the
original list had an even number of items.)
z0<     If there's anything still on the stack,
U         then execute macro U (which adds the bottom item on the
stack to register a and then executes F recursively).
]dsFx    End the macro, name it F, and execute it.

lblaf    Print a, then print b.


# C (gcc), 67 bytes

f(x,y,a,b)int*x,*y,*a,*b;{for(*a=*b=0;x<y--;*a+=x<y?*x++:0)*b+=*y;}


Try the test cases online!

This is a function with two "in" parameters (x and y) and two "out" parameters (a and b).

Input is taken as an array of ints, and is passed as a pointer x to the beginning of the array and a pointer y to (the location immediately after) the end of the array.

The function returns the left and right sums in *a and *b, respectively.

# Julia, 41 bytes

a->[sum(a[1:(e=end÷2)]),sum(a[e+1:end])]


# Scala, 42 bytes

val(a,b)=l.splitAt(l.size/2);(a.sum,b.sum)


Sorry but i'm not sure if it has to be a function if it is the case it costs 74 bytes.

val f:List[Int]=>(Int,Int)=l=>{val(a,b)=l.splitAt(l.size/2);(a.sum,b.sum)}


It should be written using a tail recursion to be more efficient but the cost in caracters would be higher.

• Hello and welcome to CGCC! To answer your question, yes your code should be formatted as a function to be considered a valid submission (you could also format it as a full program by reading from STDIN, but I'm guessing that would be longer). May 3 '20 at 22:22
• Thank you for joining Codegolf! We allow an anonymous function l=>..., because that is a expression that be assigned to a variable. That way, you don't need to count the type annotation. Also, you can take a look our tips for golfing in scala. May 4 '20 at 6:23
• You don't need to write out the whole function like that. You can do it like this with a lambda, and it's just 4 bytes more
– user
Sep 5 '20 at 20:40