# Question
Title: 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.

# Answer
# Brachylog, 3 bytes

```
ḍ+ᵐ

```

Try it online!

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

# Answer
# 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!
> 15 votes

# Answer
# 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.
> 6 votes

# Answer
# Haskell, ~~44~~ 43 bytes

```
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.
> 5 votes

# Answer
# K (ngn/k) / oK / K4, 8 bytes

```
+/'2 0N#

```

Try it online!
> 5 votes

# Answer
# , 14 bytes

```
-@>.@-:@#+/\|.

```

Try it online!

Output is in reverse.
> 4 votes

# Answer
# 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

```
> 3 votes

# Answer
# 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.
> 3 votes

# Answer
# Haskell, 50 bytes

```
f x=(\(a,b)->sum<$>[a,b])$splitAt(length x`div`2)x

```

Try it online!
> 3 votes

# Answer
# 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

```
> 3 votes

# Answer
# 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⍴`**r**eshape to 2 rows and as many columns as needed, chopping trailing elements if uneven

`+/` sum the rows
> 3 votes

# Answer
# 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

```
> 3 votes

# Answer
# 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)*)
        }
    };
}

```
> 3 votes

# Answer
# 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
]

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

```
> 3 votes

# Answer
# asm2bf, 157 bytes

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

```
@l
in r1
cner1,0
cadr2,1
cpsr1
cjn%l
movr3,r2
modr3,2
divr2,2
movr4,r2
addr2,r3
@x
popr1
addr5,r1
decr2
jnzr2,%x
@y
popr1
addr6,r1
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
    cadd r2, 1
    cpush r1
    cjn %inloop

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

@right
    pop r1
    add r5, r1
    dec r2
    jnz r2, %right

@left
    pop r1
    add r6, r1
    dec r4
    jnz r4, %left

    out r6
    out r5

```

Let's answer two questions first:

`=>` 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
?cadd=cad
?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
    cadd r2, 1
    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)
    cadd r2, 1
; push the number on the stack if the flag is set.
    cpush r1
; jump to @inloop if the flag is set.
    cjn %inloop

```

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

* reading the list
* 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
    add 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
    add r5, r1
    dec r2
    jnz r2, %right

@left
    pop r1
    add r6, 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.
> 3 votes

# Answer
# 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.
> 3 votes

# Answer
# JavaScript (ES6),  ~~47~~  45 bytes

Outputs in reverse order.

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

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 4 bytes

```
R2äO

```

Try it online!
> 2 votes

# Answer
# Clojure, 47 bytes

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

```

Try it online!
> 2 votes

# Answer
# , ~~46~~ 45 bytes

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

```

Try it online!

*Edit: thanks to Giuseppe: -1 byte*
> 2 votes

# Answer
# Risky, 12 bytes

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

```

Try it online!
> 2 votes

# Answer
# Thunno 2, 4 bytes

```
r2Ẇʂ

```

Try it online!

#### Explanation

```
r2Ẇʂ  # Implicit input
r     # Reverse the list
 2Ẇ   # Split it in two pieces
      # (with a left-bias)
   ʂ  # Sum each inner list
      # Implicit output

```
> 2 votes

# Answer
# 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.
> 1 votes

# Answer
# 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!
> 1 votes

# Answer
# APL+WIN, 18 bytes

Prompts for vector of integers:

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

```

Try it online! Coutesy of Dyalog Classic
> 1 votes

# Answer
# Red, 52 bytes

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

```

Try it online!
> 1 votes

# Answer
# 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

```
> 1 votes

# Answer
# 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.

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# Factor, ~~55~~ 54 bytes

```
: f ( s -- s s ) dup length 2/ floor cut [ sum ] bi@ ;

```

Try it online!
> 1 votes

# Answer
# Julia, 41 bytes

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

```
> 1 votes

# Answer
# 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.
> 1 votes

# Answer
# PHP, 60 bytes

```
for(;$a=$argv[++$i];)$r[$i<count($argv)/2]+=$a;var_dump($r);

```

Try it online!

Like often, much shorter with a straight loop.. PHP and arrays, *sigh*

# PHP, 79 bytes

```
fn($l,$g=array_sum,$h=array_slice)=>[$g($h($l,0,$n=count($l)/2)),$g($h($l,$n))]

```

Try it online!

PHP takes care itself of the right bias.. it's long mostly because array functions have lengthy names..
> 1 votes

# Answer
# MathGolf, 8 bytes

```
h½‼<≥αmΣ

```

Try it online.

**Explanation:**

```
h        # Get the length of the (implicit) input-list (without popping the list itself)
 ½       # Halve it (integer-divided by 2)
  ‼      # Apply the following two commands separately:
   <     #  Take all elements of the list smaller than the length//2
   ≥     #  Take alle elements of the list larger than or equal to the length//2
    α    # Wrap both lists into a list
     m   # Map over this list of lists:
      Σ  #  And sum each inner list
         # (after which the entire stack joined together is output implicitly as result)

```
> 1 votes

# Answer
# JavaScript (V8), 68 bytes

```
(l,h=k=>k.reduce((a,e)=>a+e,0))=>([h(l.splice(0,l.length>>1)),h(l)])

```

Try it online!
> 1 votes

# Answer
# MAWP, 17 bytes

```
%@[_2A{%M~}]%:1;:

```

Try it! (Only first line is taken as input)

Outputs sums in reverse.
> 1 votes

# Answer
# Factor \+ `math.unicode`, 21 bytes

```
[ halves [ Σ ] bi@ ]

```

Try it online!

## Explanation:

It's a quotation (anonymous function) that takes a sequence from the data stack as input and leaves two integers on the data stack as output.

* `halves` Split a sequence in half. Luckily for us, it keeps the middle element with the latter sequence.
* `[ ... ] bi@` Apply a quotation to two objects.
* `Σ` Sum a sequence.
> 1 votes

# Answer
# Vyxal, 7 bytes

```
Ṙ₅½⌈ẇv∑

```

Try it Online!

-1 thanks to lyxal
> 1 votes

# Answer
# Vyxal 2.7.2, 2 bytes

```
IṠ

```

Try it Online!

Yes.

## Explained

```
IṠ
I  # Split the input list into two halves. Due to a bug in 2.7.2, this unintentionally gives the right bias required
 Ṡ # Sum of each sublist.

```
> 1 votes

# Answer
# JavaScript (V8), 53 bytes

```
x=>eval(x.splice(x.length/2,0,'0,')+`[${x.join`+`}]`)

```

Try it online!
> 1 votes

# Answer
# Arturo, 34 bytes

```
$->a[map split.at:/size a 2a=>sum]

```

Try it!
> 1 votes

# Answer
# Uiua <sup>SBCS</sup>, 11 bytes

```
∩/+⊃↘↙⌊÷2⧻.

```

Try it!
> 1 votes

# Answer
# Perl 5 `-a`, 33 bytes

```
map$a[$i++>@F/2-1]+=$_,@F;say"@a"

```

Try it online!
> 1 votes

---
Tags: code-golf, number, array
---


title: Range, Reverse, Sum!

text:
# Question
Title: Range, Reverse, Sum!
Given a positive integer n as input, output the reversed range sum of n.

A reversed range sum is created by making an inclusive range up to n, starting with 1 and including n, reversing each of the numbers inside, and summing it.

**Example:**

Here is what would happen for an input of 10:

Range: `[1,2,3,4,5,6,7,8,9,10]`

Reverse: `[1,2,3,4,5,6,7,8,9,01]` (1-char numbers reversed are themselves, 10 reversed is 01 or 1)

Sum: `46`

Numbers with 3+ digits are reversed the same way numbers with 2 digits are. For example, 1234 would become 4321.

**Test cases:**

```
Input -> Output

10 -> 46
5 -> 15
21 -> 519
58 -> 2350
75 -> 3147
999 -> 454545

```

Complete text cases to input of 999 can be found here, thanks very much to @fireflame241.

# Answer
# 05AB1E, 3 bytes

### Code

```
LíO

```

Uses the **05AB1E** encoding. Try it online!

### Explanation

```
L       # Range
 í      # Reverse
  O     # Sum

```
> 17 votes

# Answer
# Bash + GNU utils, 24

```
seq $1|rev|paste -sd+|bc

```

Try it online.

### Explanation

```
seq $1                    # range
      |rev                # reverse (each line)
          |paste -sd+|bc  # sum

```
> 13 votes

# Answer
# Perl 6, 20 bytes

```
{(1..$_)».flip.sum}

```

Test it

## Expanded:

```
{
   ( 1 .. $_ )\  # Range
   ».flip        # flip each value in the Range (possibly in parallel)
   .sum          # sum up the list
}

```
> 9 votes

# Answer
## JavaScript (ES6), 42 bytes

```
f=n=>n&&+[...n+""].reverse().join``+f(n-1)

```

My favorite doubly-recursive solution is unfortunately 3 bytes longer:

```
f=n=>n&&+(g=x=>x?x%10+g(x/10|0):"")(n)+f(n-1)

```
> 9 votes

# Answer
# Retina, ~~41~~ ~~36~~ 35 bytes

```
.+
$*
1
1$`¶
1+
$.&
%O^$`.

.+
$*
1

```

Try it online! Link includes test cases. Edit: Saved 5 bytes thanks to @FryAmTheEggman. Saved 1 byte thanks to @PunPun1000. Explanation:

```
.+
$*

```

Convert to unary.

```
1
1$`¶

```

Create a range from `1` to `n`.

```
1+
$.&

```

Convert back to decimal.

```
%O^$`.

```

Reverse each number.

```
.+
$*

```

Convert back to unary.

```
1

```

Sum and convert back to decimal.
> 7 votes

# Answer
# C (gcc), 63 bytes

```
f(n){int t=0,c=n;for(;c;c/=10)t=t*10+c%10;return n?t+f(n-1):0;}

```

Try it online!
> 7 votes

# Answer
# Python 2, 38 bytes

Can't compute higher terms than the recursion limit:

```
f=lambda x:x and int(`x`[::-1])+f(x-1)

```

Try it online!
> 6 votes

# Answer
# Jelly, 4 bytes

```
Ṛ€ḌS

```

**Try it online!**

### How?

```
Ṛ€ḌS - Link: n
Ṛ€   - reverse for €ach (in implicit range)
  Ḍ  - convert from decimal list (vectorises)
   S - sum

```
> 6 votes

# Answer
# Haskell, 34 bytes

```
\n->sum$read.reverse.show<$>[1..n]

```

Simple and straightforward.
> 6 votes

# Answer
# Python 2, 50 47 bytes

-3 bytes thanks to officialaimm!

```
lambda n:sum(int(`i+1`[::-1])for i in range(n))

```

Try it online!
> 5 votes

# Answer
# cQuents, 4 bytes

```
;\r$

```

Try it online!

## Explanation

```
       Implicit input n.
;      Series mode. Outputs the sum of the sequence from 1 to n.
 \r$   Each item in the sequence equals:
 \r    String reverse of
   $                     current index (1-based)

```
> 5 votes

# Answer
# Brachylog, 4 bytes

```
⟦↔ᵐ+

```

Try it online!

### Explanation

```
⟦↔ᵐ+
⟦        range from 0 to input
 ↔ᵐ      map reverse
   +     sum

```
> 5 votes

# Answer
# Röda, ~~56~~ ~~41~~ 36 bytes

*15 bytes saved thanks to @fergusq*

```
{seq 1,_|parseInteger`$_`[::-1]|sum}

```

Try it online!

This is an anonymous function that takes an integer from the input stream and outputs an integer to the output stream.

### Explanation

```
{seq 1,_|parseInteger`$_`[::-1]|sum} Anonymous function
 seq 1,_                             Create a sequence 1 2 3 .. input and push each value to the stream
        |                            For each value in the stream:
                     `$_`             Cast it into a string
                         [::-1]       And reverse it
         parseInteger                 And parse the resulting string as an integer, while pushing the value to the stream
                               |sum  Sum all the values in the stream

```
> 5 votes

# Answer
# C# (.NET Core), ~~103~~ 97 bytes

```
using System.Linq;r=>new int[r+1].Select((_,n)=>int.Parse(string.Concat((n+"").Reverse()))).Sum()

```

Try it online!

TIO link outputs all the results from 1 to 999, so feel free to check my work.

I expected this to be a bit shorter, but it turns out `Reverse()` returns an `IEnumerable<char>` instead of another string so I had to add some extra to turn it back into a string so I could parse it to an int. Maybe there's a shorter way to go from `IEnumerable<char>` to int correctly.

~~Of minor note, this also uses the functions `Range()` `Reverse()` and `Sum()` all in order.~~

-6 bytes thanks to TheLethalCoder
> 4 votes

# Answer
# APL (Dyalog), ~~10~~ 7 bytes

*3 bytes golfed thanks to @Adám by converting to a tradfn from a train*

```
+/⍎⌽⍕⍳⎕

```

Try it online!

```
⎕          Input (example input: 10)
⍳          Range; 1 2 3 4 5 6 7 8 9 10
⍕          Stringify; '1 2 3 4 5 6 7 8 9 10'
⌽          Reverse; '01 9 8 7 6 5 4 3 2 1'
⍎          Evaluate; 1 9 8 7 6 5 4 3 2 1
+/         Sum; 46

```
> 4 votes

# Answer
# Ruby, ~~56, 52, 41,~~ 39 bytes

```
->n{(1..n).sum{|i|i.to_s.reverse.to_i}}

```

# Ruby, 34 bytes (if lambda param is a string)

```
->n{(1..n).sum{|i|i.reverse.to_i}}

```

Thanks to @Unihedron for the second solution.
> 4 votes

# Answer
# Vim, ~~39~~ ~~37~~ 28 bytes

```
D@"O<C-V><C-A>0<ESC>V{g<C-A>:%!rev
v}gJS0<ESC>@"

```

Try it online!

Tons of bytes saved thanks to some great advice by user41805

### Explanation

Step 1: build the range (with summing commands included)
```
D@"O<C-V><C-A>0<ESC>V{g<C-A>
D                               Delete the input number
 @"            <ESC>            Do that many times:
   O                              Insert a new line above
    <C-V><C-A>                    Write a <C-A> byte (\x01)
              0                   Followed by a 0
                    V{          Select all the lines just written
                      g<C-A>    Turn the numbers into an increasing range

```
Step 2: reverse each number

`:%!rev` (that's it)

This will produce a sequence of lines with the reversed number followed by `<C-A>`, which is the command to increase a value by the reversed number. Leading 0s actually move the pointer to the beginning of the line, so they are effectively ignored.

Step 3: sum them all up
```
v}gJS0<ESC>@"
v}               Select all the lines to the end of the file
  gJ             Join them
    S            Replace this line
     0<ESC>         with a 0
           @"    Execute the replaced line as commands

```
> 4 votes

# Answer
# Mathematica, 47 bytes

```
Tr[FromDigits@*Reverse/@IntegerDigits@Range@#]&

```

Try it online! (in order to work on mathics we need to replace "Tr" with "Total")
> 3 votes

# Answer
# Japt, ~~7~~ 5 bytes

*-2 bytes thanks to @Shaggy.*

```
õs xw

```

Try it online!

## Explanation

```
õs xw  Implicit input of integer U
õs     Create range [1,U] and map to strings
    w  Reverse each string
   x   Sum the array, implicitly converting to numbers.

```

# Old solution, 7 bytes

Keeping this since it's a really cool use of `z2`.

```
õs z2 x

```

Try it online!

## Explanation

```
õs z2 x  Implicit input of integer U
õs       Create range [1,U] and map to strings
   z2    Rotate the array 180°, reversing strings
      x  Sum the array, implicitly converting back to integers

```
> 3 votes

# Answer
# Charcoal, ~~14~~ 13 bytes

-1 byte thanks to Carlos Alejo

```
Ｉ∕…·⁰Ｎ«⁺ιＩ⮌Ｉκ

```

Try it online! Link is to verbose version.

## Explanation

```
Ｉ                  Cast
  ∕     «           Reduce
   …·⁰Ｎ            Inclusive range from 0 to input as number
         ⁺          Plus
          ι         i
           Ｉ⮌Ｉκ   Cast(Reverse(Cast(k)))

```
> 3 votes

# Answer
## C++, 146 bytes

```
#include<string>
using namespace std;int r(int i){int v=0,j=0;for(;j<=i;++j){auto t=to_string(j);reverse(t.begin(),t.end());v+=stoi(t);}return v;}

```
> 3 votes

# Answer
# Husk, ~~7 6~~ 3 bytes

```
ṁ↔ḣ

```

Try it online!

### Ungolfed/Explanation

```
  ḣ  -- With the list [1..N] ..
ṁ    -- .. do the following with each element and sum the values:
 ↔   --    reverse it

```
> 3 votes

# Answer
# Perl 5, ~~29 27~~ 22 + 1 (`-p`) = 23 bytes

```
map$\+=reverse,1..$_}{

```

Try it online!
> 3 votes

# Answer
## Magneson, 102 bytes

That's not very visible, so here's a scaled up version (Note: Won't actually run, and still isn't very pretty)

(source: googleapis.com)

Magneson operates by parsing an image and evaluating commands from the colours of the pixels it reads. So stepping through the image for this challenge, we have:

* `R: 0, G: 1, B: 1` is an integer assignment command, which takes a string for the variable name and the value to assign. We'll use this to store the sum total.
* `R: 0, G: 1, B: 0` is a prebuilt string with the value `VAR_1` (Note: This is only while we're asking for a string; the colour code has a separate function when used elsewhere).
* `R: 3, G: 0, B: 0` is a raw number. Magneson handles standard numbers by requiring the Red component to be exactly 3, and then forms a number by using the blue value directly *plus* the green value multiplied by 256. In this case, we're just getting the number 0.
* `R: 0, G: 1, B: 1` is another integer assignment command. This time, we're storing an iteration variable, to keep track of which number we're on
* `R: 0, G: 1, B: 1` is a prebuilt string with the value `VAR_2` (Once more, only when we need a string)
* `R: 3, G: 0, B: 0` is the number 0, once more. Onto the interesting bits now.
* `R: 1, G: 0, B: 0` indicates the start of a loop. This takes a number and loops the following snippet of code that many times.
* `R: 2, G: 0, B: 0` is the STDIN function, or at least it is when we need a number. This reads a line of input from the console and turns it into a number, since we asked for a number.
* `R: 0, G: 8, B: 0` starts off our looping code, and it is an additive command. This adds a number to an integer variable, and so takes a string for the variable name, and the number to add.
* `R: 0, G: 1, B: 1` is the prebuilt string for `VAR_2`, which is our iteration variable.
* `R: 3, G: 0, B: 1` is a raw number, but this time it's the number 1.
* `R: 0, G: 8, B: 0` is another addition command.
* `R: 0, G: 1, B: 0` is the string for `VAR_1`, which is our sum total.
* `R: 0, G: 3, B: 0` is a function that reverses a string. In the context of asking for a number, it then converts the reversed string to a number.
* `R: 0, G: 2, B: 1` is an integer retrieval command, and will retrieve the number stored in a provided variable. In the context of asking for a string (such as from the reverse command), it converts the number to a string.
* `R: 0, G: 1, B: 1` is the name `VAR_2`; our iteration variable.
* `R: 1, G: 0, B: 1` is the marker to end the loop, and go back to the start of the loop if the criteria isn't met (so if we need to keep looping). Otherwise, proceed onwards.
* `R: 0, G: 0, B: 1` is a very simple println command, and takes a string.
* `R: 0, G: 2, B: 1` retrieves an integer from a variable
* `R: 0, G: 1, B: 0` is the name of our sum total variable, `VAR_1`

All in all, the program:

* Assigns the value 0 to `VAR_1` and `VAR_2`
* Loops from 0 to a number provided in STDIN
    + Adds one to `VAR_2`
    + Adds the integer value of reversing `VAR_2` to `VAR_1`
* Prints the contents of `VAR_1`
> 3 votes

# Answer
# CJam, 12 bytes

```
ri){sW%i}%:+

```

Try it online!

-1 thanks to Business Cat.

Explanation:

```
ri){sW%i}%:+
r            Get token
 i           To integer
  )          Increment
   {sW%i}    Push {sW%i}
    s         To string
     W        Push -1
      %       Step
       i      To integer
         %   Map
          :+ Map/reduce by Add

```
> 3 votes

# Answer
# Java 8, 97 bytes

```
IntStream.range(1,n+1).map(i->Integer.valueOf(new StringBuffer(""+i).reverse().toString())).sum()

```

---

**EDIT**

As per the comment of `Kevin Cruijssen`, I would like to improve my answer.

# Java 8, 103 bytes

```
n->java.util.stream.LongStream.range(1,n+1).map(i->new Long(new StringBuffer(""+i).reverse()+"")).sum()

```
> 3 votes

# Answer
# Gol\>\<\>, 26 bytes

```
&IFLPWaSD$|~rlMFa*+|&+&|&h

```

Try it online!

## Explanation

```
&I                      &h < register init, read "n"; print register (h = n;)
  FLP                  |   < For loop, do "n" times for each x in [1] to [n]
     WaSD$|                < modpow "x" to digits: [123] [3 12] [3 2 1] [3 2 1 0]
           ~rlMFa*+|       < Ditch zero, reverse stack, build the number back
                    &+&    < register += final x

```
> 3 votes

# Answer
# Vyxal, `s`, 2 bytes

```
ƛṘ

```

Try it Online!
> 3 votes

# Answer
# vim, 49 46 bytes

```
A@q<ESC>0"bDa1<ESC>qqYp<C-a>q@bdk:%s/$/+
:%!rev
xVGJ:%!bc

```

`<ESC>` is 0x1b, `<C-a>` is 0x01, `<NL>` is 0x0a.

## Annotated

```
A@q<ESC>0"bD  # put {N}@q (run macro q N times) in register b
a1<ESC>       # buffer now contains "1"
qqYp<C-a>q    # store macro that copies and increments the last line in register q
@bd1k         # run {N} times, then delete the extra lines
              # (can't just run {N-1} times, or it won't handle N=1 correctly)
:%s/$/+<NL>   # append + to each line
:%!rev<NL>    # reverse each line
x             # delete leading +
VGJ           # join lines
:%!bc<NL>     # sum

```

Try it online!
> 3 votes

# Answer
# Excel, 59 bytes

```
=LET(y,COLUMN(A:O),SUM((0&MID(SEQUENCE(A1),y,1))*10^(y-1)))

```

Explanation

```
=LET(
y,COLUMN(A:O)                           'y = [1..15] horz.; Excel is accurate to 15 places
SUM((0&MID(SEQUENCE(A1),y,1))*10^(y-1)) 'final result
           SEQUENCE(A1)                 '[1..A1] vertical
    (0&MID(            ,y,1))           'array of individual digits; 0& is to avoid errors on blank cells
                             *10^(y-1)  'multiply 2nd column by 10, 3rd 100, etc.
SUM(                                  ) 'sum the array

```
> 3 votes

# Answer
# RProgN 2, 8 bytes

```
{Ø.in}S+

```

## Explained

```
{Ø.in}S+
{    }S # Create a stack in range 0 through the implicit input, using the function defined
 Ø.     # Append nothing, stringifying the number
   i    # Reverse the string
    n   # Convert back to a number
       +# Get the sum of the stack, and output implicitly.

```

Try it online!
> 2 votes

# Answer
# Pyth, 8 6 bytes

 -2 bytes thanks to FryAmTheEggman!

```
sms_`h

```

Try it online!
> 2 votes

# Answer
# Tcl, 66 bytes

```
time {incr s [regsub ^0+ [string rev $n] ""];incr n -1} $n
puts $s

```

Try it online!
> 2 votes

# Answer
# Neim, 4 bytes

```
Δ)

```

Try it online!

# Explanation

```
Δ )              for each element 1 to n (outputs list)
                reverse
                sum

```
> 2 votes

# Answer
# Excel VBA, ~~80~~ ~~78~~ 49 Bytes

Anonymous VBE Immediate Window function that takes input expected type `Integer` from range `[A1]` determines all of the values that fall within the range `1:[A1]`, and outputs the sum of the reversed values to the VBE immediate window

```
For i=1To[A1]:s=s+Val(StrReverse(Str(i))):Next:?s

```
> 2 votes

# Answer
# C (gcc), 71 bytes

```
q(n,x,p){p=n?q(n/10,x*10+n%10):x;}f(w,a,e){for(a=0;w;)a+=q(w--,0);e=a;}

```

Try it online!
> 2 votes

# Answer
## TXR Lisp: ~~62~~ 56 bytes:

```
(opip(range 1)(mapcar[chain tostring reverse toint])sum)

```

Interactive:

```
1> (opip(range 1)(mapcar[chain tostring reverse toint])sum)
#<intrinsic fun: 0 param + variadic>
2> [*1 10]
46
3> [*1 999]
454545

```

The following 44 byte expression, inspired by the Pari/GP solution, is possible; however, it requires the `sum` macro to be defined:

```
1> (defmacro sum (var from to expr)
      (with-gensyms (accum)
        ^(for ((,var ,from) (,accum 0))
              ((<= ,var ,to) ,accum)
              ((inc ,accum ,expr) (inc ,var)))))
sum
2> (do sum x 1 @1 (toint(reverse(tostring x))))
#<interpreted fun: lambda (#:arg-01-0171 . #:rest-0170)>
3> [*2 10]
46
4> [*2 999]
454545

```
> 2 votes

# Answer
# Python 3, 50 bytes

```
lambda n:sum(int(str(n)[::-1])for n in range(n))

```

Quite close to idiomatic Python code, and honestly I don't really see much room for improvement.
> 2 votes

# Answer
# Ruby, ~~38~~ 35 bytes

Similar to the previous Ruby solution, but a full program and also shorter (for less than an hour)!

```
p (?1..gets).sum{|x|x.reverse.to_i}

```

Shortened by 3 bytes thanks to user akostadinov

Try it online!

## Explanation

```
p             # Inspect and print. Written as infix notation to avoid using ()
(?1..gets)    # All strings from "1" to "input", based on successive string format
  .sum{|x|    # Enumerable -> Map to value -> Sum by value
      x.reverse.to_i
  }

```
> 2 votes

# Answer
# Gaia, 7 bytes

```
@…)¦v¦Σ

```

Try it online!

Range, Reverse, and sum!

```
@             # push an input. stack: n
 …            # generate range. stack: [0...n-1]
  )¦          # map over the list with increment. stack: [1...n]
    v¦        # map over the list with reverse. stack: [1...n], but all digitally reversed
      Σ       # sum the list; output TOS.

```
> 2 votes

# Answer
# Python 3, 52 bytes

```
lambda n:sum(int(str(n+1)[::-1])for n in range(n))
lambda n:sum(int(f'{n+1}'[::-1])for n in range(n))

```

The second is equivalent to the first.
> 2 votes

# Answer
# Pyke, 7 bytes

```
SF`_b)s

```

Try it online!

```
S       -   range(1, input)
 F   )  -  for i in ^:
  `     -     str(i)
   _    -    reversed(^)
    b   -   int(^)
     s  - sum(^)

```
> 1 votes

# Answer
# MATL, 5 bytes

```
:VPUs

```

Try it online!
> 1 votes

# Answer
# , ~~89~~ 75 bytes

```
sum(scan(t=sapply(1:scan(),function(x)intToUtf8(rev(utf8ToInt(c(x,'')))))))

```

Try it online!

Thanks to JayCe and Dominic van Essen for the golfs.
> 1 votes

# Answer
# Pyth - 7 bytes

```
sms_`dS

```

Explanation

```
sms_`dSQ  Q added implicitly
s         Sum of
 m        map
  s_`d    integer representation of reversal of string representation
          to
      SQ  Range from 1 to input

```
> 1 votes

# Answer
# Pyt, 3 bytes

```
ř₫Ʃ

```

Try it online!

The characters perform the following operations: range, reverse, sum.
> 1 votes

# Answer
# Canvas, 7 bytes

```
Ｒ｛ŗ±┤］∑

```

Try it here!
> 1 votes

# Answer
# Lua (59 bytes)

```
function r(u)return u<1 and 0 or(u..""):reverse()+r(u-1)end

```
> 1 votes

# Answer
# PowerShell, 43 bytes

```
1.."$args"-join'+'|% t*y|%{$s=$_+$s}
$s|iex

```

Try it online!

This script converts a range `[1,2,3,4,5,6,7,8,9,10]` to the reversed string `01+9+8+7+6+5+4+3+2+1` and evaluates the string
> 1 votes

# Answer
# Python 3, 127 bytes

```
def f(n):
 s=0
 for i in range(1,n+1):
  r=""
  k=str(i)
  for j in range(0,len(k)):
   r=r+k[len(k)-1-j]
  s+=int(r)
 return s

```
> 1 votes

# Answer
# Java (OpenJDK 8), 81 bytes

```
long g(int n){return n<1?0:new Long(""+new StringBuffer(""+n).reverse())+g(n-1);}

```

Try it online!
> 1 votes

# Answer
# Arn `-x`, 4 bytes

```
P▀g³

```

Try it!

# Explained

Unpacked: `~)@.<`

```
    ~    One-range to
      _  Input; implied
  )
@        Map with
  .<     Reverse fix
      Implicit sum

```
> 1 votes

# Answer
# Desmos, ~~72~~ 70 bytes

```
l=floor(logx)
f(y)=∑_{x=1}^y∑_{n=0}^lmod(floor(x/10^n),10)10^{l-n}

```

Try it on Desmos!

*-2 bytes thanks to Aiden Chow*
> 1 votes

# Answer
# Factor \+ `math.unicode`, 39 bytes

```
[ [1..b] [ >dec reverse dec> ] map Σ ]

```

Using build 2166 for the somewhat recent addition of \>dec.
> 1 votes

# Answer
# Burlesque, 7 bytes

```
ro)<-++

```

Try it online!

```
ro  # Range
)<- # Reverse
++  # Sum

```
> 1 votes

# Answer
# K (ngn/k), ~~15~~ ~~14~~ 13 bytes

```
{+/.'|'$1+!x}

```

Try it online!

*-1 byte thanks to coltim*
> 1 votes

# Answer
# Julia 1.0, 38 bytes

```
!x=sum(Meta.parse∘join∘digits,1:x)

```

Try it online!

this works because `digits` returns an array with the digits starting with the least significants first (`digits(123) == [3, 2, 1]`)

#### alternative, also 38 bytes (but more chars and not as nice)

```
!x=sum(@.parse(Int,join(digits(1:x))))

```

Try it online!
> 1 votes

# Answer
# J-uby, 16 bytes

```
:+|:sum+(S|:~|Z)

```

Attempt This Online!

## Explanation

Same idea as the Ruby answers but J-uby helps us out with some handy shortcuts.

```
:+ | :sum + (S | :~ | Z)

:+ |                      # Make range 1..n, then
     :sum + (          )  # Sum of items...
             S |          #   Converted to string, then
                 :~ |     #   Reversed, then
                      Z   #   Converted to int

```
> 1 votes

# Answer
# \>\<\>, 68 bytes

```
1:{:})?^:9)?v:1+!
a:v?(1:[2$0:<.17-%1:,a}+*a{%
0.>~]$d
=?n+a3.>~{~l1

```

Try it online!
> 1 votes

# Answer
# Japt `-x`, 4 bytes

```
õÈìÔ

```

Try it

```
õÈìÔ     :Implicit input of integer
õ        :Range [1,input]
 È       :Map
  ì      :  Convert to digit array
   Ô     :  Reverse and implicitly convert back
         :Implicit output of sum of resulting array

```
> 1 votes

# Answer
# Thunno `+`, \\$4\log\_{256}(96)\approx\\$ 3.29 bytes

```
R.rS

```

Attempt This Online!

#### Explanation

```
R.rS  # Implicit input
      # + flag adds one
R     # Range
 .r   # Reverse each
   S  # Sum
      # Implicit output

```
> 1 votes

# Answer
# Jelly, 5 bytes

```
RDUḌS

```

Try it online!

```
R      ' [R]ange
 D     ' Integer -> [D]ecimal
  U    ' [U]pend (vectorized reverse?)
   Ḍ   ' [Ḍ]ecimal -> Integer
    S  ' [S]um

```
> 0 votes

# Answer
# MY, 11 bytes

```
iC4ǵ'ƒ⇹(Σ↵

```

Try it online!

## How?

* input as integer
* `i` \[1 ... pop()\] inclusive
* `C4ǵ'` push the string `'\x4C'` (The reverse command (), which works on numbers)
* `ƒ` as a function
* mapped over the argument (pushes a function)
* `(` apply the function
* `Σ` sum
* output with a new line

MY is capable of something, woohoo!
> 0 votes

# Answer
# Ly, 31 bytes

```
ns[l1-s]pr[s>lSrJs>l<p<p]>>r&+u

```

Try it online!
> 0 votes

# Answer
# Javascript,~~89~~ ~~77~~ 72 bytes

*saved 12 bytes thanks to @Justin Mariner*

*saved 5 bytes thanks to @Neil*

```
n=>-eval(`-'${[...[...Array(n+1).keys()].join`'-'`].reverse().join``}'`)

```

### Explanation:

`[...Array(n+1).keys()]` creates an array from 0 to n.

`.reverse().join``` reverses every value.

`.join`'-'`` and `eval(`-'{stuff}'`)` subtracts the values in order, producing the negative of the answer. `-` negates the negative to a positive.
> 0 votes

# Answer
# Pari/GP, 43 bytes

```
n->sum(i=1,n,fromdigits(Vecrev(digits(i))))

```

Try it online!
> 0 votes

# Answer
# QBIC, 19 bytes

```
[:|_F!a$|p=p+!A!}?p

```

## Explanation

```
[:|     FOR a = 1 to n (read from cmd line)
_F   |      FLIP and assign to A$
  !a$        a string cast of our loop counter
p=p+!A!    increment p with A$ cast back to number
}           NEXT
?p         Print the result

```
> 0 votes

# Answer
# Swift 4, ~~63~~ 61 bytes

```
{v in(1...v).reduce(0,{$0+Int(String("\($1)".reversed()))!})}

```

**Try it online!**

---

# Explanation

* `{v in}` \- Creates an anonymous (lambda-like) function with a parameter `v`.
* `(1...v)` \- Inclusive range from `1` to `v` (although it kind of breaks the rules of logic).
* `Int(String("\($1)".reversed()))` \- Reverses the Number by converting it to a String, returning `ReverseCollection<String>`. That cannot be casted directly to an integer (Swift borked types!), so we have to cast it to String again, before making the conversion to an Integer.
* `reduce(0,{$0+...})` \- Sums the mapped range.
> 0 votes

# Answer
# LOGO, 33 bytes

```
[reduce "+ map "reverse iseq 1 ?]

```

There is no "Try it online!" link because all online LOGO interpreter does not support template-list.

That is a template-list (equivalent of lambda function in other languages).

Usage:

```
pr invoke [reduce[?+reverse ?2]iseq 1 ?] 10

```

(`invoke` calls the function, `pr` prints the result)

prints `46`.

Explanation:

LOGO stores numbers as words, therefore apply `reverse` on a number reverse the digits in that number.

`reduce "f [a b c d e]` (where `[a b c d e]` is a list) will calculate `f(a, f(b, f(c, f(d, e))))`. So `reduce "+ list` will calculate sum of values of `list`.
> 0 votes

# Answer
**Swift 3, 98 bytes**

```
func f(a:Int)->Int{return (0...a).map{Int(String(String($0).characters.reversed()))!}.reduce(0,+)}

```
> 0 votes

# Answer
# PowerShell, 53 bytes

```
(1.."$args"|%{-join"$_"["$_".length..0]})-join'+'|iex

```

Try it online!

Literal translation of the specification. Creates a range with `..`, reverses each by using string manipulation and `-join`ing them back into a single number, then `-join`s each number together with a `+` and piping that to `iex` (short for `Invoke-Expression` and similar to `eval`).
> 0 votes

# Answer
# GolfScript, 15 bytes

```
~),{`-1%~}%{+}*

```

Try it online!

Explanation:

```
~),{`-1%~}%{+}* Input all at once
~               Eval
 )              Increment
  ,             Exclusive range
   {     }      Push block
    `            Repr
     -1          -1
       %         Every xth element
        ~        Eval
          %     Map
           { }  Push block
            +    Add
              * Reduce

```
> 0 votes

# Answer
# PHP, 39+1 bytes

```
while($i++<$argn)$s+=strrev($i);echo$s;

```

Run as pipe with `-nR`.
> 0 votes

# Answer
# Rust, 110 bytes

```
|x:i64|(1..x+1).map(|v|format!("{}",v).chars().rev().collect::<String>().parse::<i64>().unwrap()).sum::<i64>()

```

Try it online!

I like Rust, but it is not a very efficient language for golfing!
> 0 votes

# Answer
# Common Lisp, 62 bytes

```
(loop as i to(read)sum(parse-integer(reverse(format()"~d"i))))

```

Try it online!
> 0 votes

# Answer
## REXX, 46 bytes

```
arg n
s=0
do i=1 to n
  s=s+reverse(i)
  end
say s

```
> 0 votes

# Answer
## Swift 3, ~~83~~ 68 characters

~~let f={n in Array(1...n).reduce(0){$0+Int(String("($1)".characters.reversed()))!}}~~

```
{(1...$0).reduce(0){$0+Int(String("\($1)".characters.reversed()))!}}

```

This would probably be shortened by Swift 4's new `String` and `Character` handling.
> 0 votes

# Answer
# , 13 bytes

```
+/.:'|:'$1+!:

```

Try it online!

```
         1+!: /create list 1 2 3 ... x
        $     /turn each number into a string
     |:'      /reverse each string
  .:'         /eval each string
+/            /sum

```
> 0 votes

# Answer
# Java 8, 84 bytes

Lambda from `int` to `long` (e.g. `IntToLongFunction`). Adaptation of *coder-croc*'s solution.

```
n->{long s=0;while(n>0)s+=new Long(new StringBuffer(""+n--).reverse()+"");return s;}

```

Try It Online
> 0 votes

# Answer
# Recursiva, 10 bytes

```
smBa"I_Va"

```

Try it online!
> 0 votes

# Answer
# J, 18 Bytes

```
+/(".@|.@":)"0>:i.

```

### Explanation:

```
+/                 | Sum of
  (".@|.@":)       | Reverse
            "0     | Each member of
              >:i. | Integers from 1 to n inclusive

```
> 0 votes

# Answer
# PowerShell, 89 bytes

```
param($n)function q($x){(($a=$x|% t*y)|%{$a[--$i]})-join''}1..$n|%{$s+=[int](q("$_"))};$s

```

Try it online!
> 0 votes

# Answer
# x86, 27 bytes

```
f:	xor esi, esi	; Input ecx
	push 10
	pop ebx
.p:	mov eax, ecx
	xor edi, edi
.q:	xor edx, edx
	div ebx
	imul edi, 10
	add edi, edx
	test eax, eax
	jnz .q
	add esi, edi
	loop .p
	ret		; Output esi

```

Try it online!

Seem not answered
> 0 votes

# Answer
# Arturo, 52 bytes

```
$[n][sum map 1..n=>[to :integer reverse to :string]]

```

Try it
> 0 votes

# Answer
# GolfScript, 12 bytes

```
,{)`-1%~+}*)

```

Try it online!

# Explanation

```
code         # explanation           | stack
,{)`-1%~+}*) # function with input n | n
,            # range                 | [0..n)
 {       }*  # fold this block over  | [0..n)
  )          # increment             | [1..n]
   `         # stringify             | ["1"..str(n)]
    -1%      # map by -1 (reverse)   | [rev("1")..rev(str(n)]
       ~     # eval                  | [rev(1)..rev(n)]
        +    # add (effectively sum) | sum([rev(1)..rev(n)])
           ) # increment             | sum([rev(1)..rev(n)])+1

```
> 0 votes

# Answer
# Thunno 2 `S`, 3 bytes

```
RṃN

```

Attempt This Online!

#### Explanation

```
RṃN  # Implicit input        -> 10
R    # Push [1..input]       -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 ṃ   # Reverse each          -> [1, 2, 3, 4, 5, 6, 7, 8, 9, '01']
  N  # Cast each to int      -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 1]
     # S flag sums the list  -> 46
     # Implicit output

```
> 0 votes

# Answer
# Excel VBA, 40 bytes

Anonymous Immediate window function that takes input from cell `[A1]` of the `activesheet` object and outputs to the Immediate Window console.

```
For i=1To[A1]:u=u--StrReverse(i):Next:?u

```
> 0 votes

---
Tags: code-golf, number, arithmetic
---


title: Create an array with repeated numbers

text:
# Question
Title: Create an array with repeated numbers
# Challenge

Your task in this question is to write a program or a named function which takes a positive integer `n` (greater than 0) as input via STDIN, ARGV or function arguments and outputs an array via STDOUT or function returned value.

**Sounds simple enough ? Now here are the rules**

* The array will only contain integers from `1` to `n`
* Each integer from `1` to `n` should be repeated `x` times where `x` is the value of each integer.

*For example:*

Input:

```
5

```

Output:

```
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]

```

The array may or may not be sorted.

This is so winner is shortest code in bytes.

**Bonus**

Multiply your score by `0.5` if no two adjacent integers in your output array are same.

For example for `n = 5`, one such configuration would be

```
[5, 4, 5, 4, 3, 4, 5, 2, 5, 3, 1, 2, 3, 4, 5]

```

# Answer
# APL, 4 characters

`/⍨⍳⎕`

How it works:

reads user input. As for output, APL by default prints the result from every line.

`⍳n` is the integers from 1 to `n`. Example: `⍳3``←→ 1 2 3`

`/` means *replicate*. Each element from the right argument is repeated as many times as specified by its corresponding element from the left argument. Example: `2 0 3/'ABC'``←→ 'AACCC'`

is the *commute operator*. When it occurs to the right of a function, it modifies its behaviour, so it either swaps the arguments (`A f⍨ B ←→ B f A`, hence "commute") or provides the same argument on both sides (`f⍨ A ←→ A f A`, a "selfie"). The latter form is used in this solution.

---

Bonus:

`6-∊⌽⍳¨⍳⎕` (8 characters, thanks @phil-h)

`⍳5` (iota five) is `1 2 3 4 5`.

`⍳¨ ⍳5` (iota each iota five) is `(,1)(1 2)(1 2 3)(1 2 3 4)(1 2 3 4 5)`, a vector of vectors. *Each* (`¨`) is an operator, it takes a function on the left and applies it to each item from the array on the right.

reverses the array, so we get `(1 2 3 4 5)(1 2 3 4)(1 2 3)(1 2)(,1)`.

is *enlist* (a.k.a. *flatten*). Recursively traverses the argument and returns the simple scalars from it as a vector.
> 8 votes

# Answer
# Ruby (recursive), 41 bytes * 0.5 = 20.5

```
def n(n,i=1);i>n ?[]:n(n,i+1)+[*i..n];end

```

Or using a lambda (as recommended by histocrat and Ventero): 34 bytes * 0.5 = 17

```
r=->n,i=n{i>0?[*i..n]+r[n,i-1]:[]}

```

(call using `r[argument]`)
> 11 votes

# Answer
# Pyth, 9 bytes * 0.5 = 4.5

```
smrhQhdUQ

```

With help from @FryAmTheEggman

Try it online.

---

## Explanation

```
s             reduce + on list
 m            map
  rhQhd       lambda d: reversed(range(d+1, Q+1)), over
       UQ     range(Q)

```

where `Q` is the input.
> 11 votes

# Answer
# Haskell, 31 characters = 15.5 score

```
f n=[y|x<-[n,n-1..1],y<-[x..n]]

```

### 27 characters without the bonus

```
f n=[x|x<-[1..n],_<-[1..x]]

```

Beaten by Proud Haskeller
> 8 votes

# Answer
# Python 2, 53 bytes * 0.5 = 26.5

```
i=n=input()
x=[]
while i:x+=range(i,n+1);i-=1
print x

```

Shamelessly borrowed @VisualMelon's idea
> 7 votes

# Answer
# C, 22 = 44 bytes * 0.5

The function `h` takes two parameters. The first is an `int` specifying *n*. The second is an `int*` which is the output buffer.

```
h(n,o)int*o;{for(n&&h(~-n,o+=n);*--o=n--;);}

```

**Test program**

```
main(){
int wow[999],*i;
memset(wow,0,sizeof(wow));
h(6, wow);
for(i=wow;*i;i++)printf("%d ", *i);
}

```
> 7 votes

# Answer
## Pyth \- ~~15~~ 10 * .5 = 5

```
smr-QdhQUQ

```

Try it online.

Expects input on stdin. Independently discovered algorithm. Thanks @Sp3000 for helping me stick the last Q in there :P Also, irony? XD

Explanation:

```
Q=eval(input())       : implicit
s                     : The sum of...
 m      UQ            : map(...,range(Q))
  r-QdhQ              : range(Q-d,Q+1)

```
> 7 votes

# Answer
# Haskell, 34 bytes * 0.5 = 17

```
0%n=[]
i%n=[i..n]++(i-1)%n
g n=n%n

```

That's the first time I've ever used Haskell for golfing. Call with `g <number>`.
> 6 votes

# Answer
# CJam, ~~12~~ 15 bytes * 0.5 = 7.5

```
li_,f{),f-W%~}`

```

This is full STDIN-to-STDOUT program. It concatenates increasing suffixes of the `1 ... n` range, which ensures that no two adjacent numbers are identical.

Test it here.
> 6 votes

# Answer
# C# - 81 (161bytes * 0.5)

Simple job in C#, hopefully gets the no-neibouring-numbers bonus. Reads an int from stdin, writes out an array like the example to stdout.

```
class P{static void Main(){int n=int.Parse(System.Console.ReadLine()),m=n-1,i;var R="["+n;for(;m-->0;)for(i=m;i++<n;)R+=", "+i;System.Console.WriteLine(R+"]");}}

```

More readable:

```
class P
{
    static void Main()
    {
        int n=int.Parse(System.Console.ReadLine()),m=n-1,i;
        var R="["+n;
        for(;m-->0;)
            for(i=m;i++<n;)
                R+=", "+i;
        System.Console.WriteLine(R+"]");
    }
}

```

Examples output:

```
n = 5
[5, 4, 5, 3, 4, 5, 2, 3, 4, 5, 1, 2, 3, 4, 5]

```
> 5 votes

# Answer
# Bash + coreutils, 28/2 = 14

Shamelessly stealing @pgy's idea and golfing:

```
seq -f"seq %g $1" $1 -1 1|sh

```

---

# Pure bash (no coreutils), 30/2 = 15

Eval, escape and expansion hell:

```
eval eval echo \\{{$1..1}..$1}

```
> 5 votes

# Answer
## GolfScript (14 bytes * 0.5 = score 7)

```
 ~:x,{~x),>~}%`

```

Online demo

I think this is probably similar to some existing answers in that it builds up the array `concat( [n], [n-1, n], [n-2, n-1, n], ..., [1, 2, ..., n] )`

Sadly I wasn't able to golf any further the arguably more elegant:

```
~:x]{{,{x\-}/}%}2*`

```

which puts the input `x` into an array and then twice applies `{,{x\-}/}%`, which maps each element in an array to a count down of that many elements from `x`.
> 5 votes

# Answer
# Haskell, 14 = 28 bytes / 2

```
f n=n:[1..n-1]>>= \r->[r..n]

```

example output:

```
>f 5
[5,1,2,3,4,5,2,3,4,5,3,4,5,4,5]

```

# 24 bytes without the bonus:

```
f n=[1..n]>>= \r->[r..n]

```
> 5 votes

# Answer
# JavaScript, ES6, 41 bytes

```
f=i=>[...Array(i).fill(i),...i?f(--i):[]]

```

This creates a function `f` which can be called like `f(6)` and it returns the required array.

This uses a recursive approach, where each iteration creates an array of `i` elements all valued `i` and concatenates an array returned by `f(i-1)` with stopping condition of `i==0`.

Works on latest Firefox.
> 4 votes

# Answer
# vba, 76\*0.5=38

```
Sub i(q)
For Z=1 To q:For x=q To Z Step -1:Debug.?x;",";:Next:Next
End Sub

```
> 4 votes

# Answer
# Wolfram Language (Mathematica), 26 * 0.5 = 13

-8 bytes thanks to @att.

```
Join@@Range[#,Range@#,-1]&

```

Try it online!
> 4 votes

# Answer
# Haxe, 53 bytes

```
function l(v)return[for(i in 0...v)for(j in 0...i)i];

```

Works with l(6); because of array comprehension.
Test online http://try.haxe.org/#741f9
> 4 votes

# Answer
# Jelly, 3 × 0.5 = 1.5 bytes

```
rRF

```

Try it online!

## Explanation

```
rRF
r      Range from {input} to
 R       each number from 1 to {input}
  F    Flatten

```

For example, with input 3, the `rR` gives us a range from 3 to 1 (i.e. `[3, 2, 1]`, then a range from 3 to 2 (i.e. `[3, 2]`), then a range from 3 to 3 (i.e. `[3, 3]`). Flattening that gives `[3, 2, 1, 3, 2, 3]`), which meets the problem specifications and has no adjacent numbers.
> 3 votes

# Answer
# Husk, 4 bytes * 0.5 = 2

```
Σ↔ḣṫ

```

Try it online!

### Explanation

```
Σ↔ḣṫ
   ṫ    range from input to 1, [5,4,3,2,1]
  ḣ     prefixes, [[5],[5,4],[5,4,3]...]
 ↔      reverse,  [[5,4,3,2,1],[5,4,3,2]...]
Σ       concat,   [5,4,3,2,1,5,4,3,2...]

```
> 3 votes

# Answer
# perl ,26 bytes

```
for(1..$n){print"$_ "x$_;}

```
> 2 votes

# Answer
## R, 44 \*.5 = 22

```
f=function(n){r=0;for(i in 1:n)r=c(r,n:i);r}

```

A quick test

```
> f(1)
[1] 1
> f(2)
[1] 2 1 2
> f(3)
[1] 3 2 1 3 2 3
> f(4)
 [1] 4 3 2 1 4 3 2 4 3 4

```
> 2 votes

# Answer
# JavaScript, ES6, 66 bytes * 0.5 = 33

```
f=i=>(g=n=>[...Array(n).fill().map((v,x)=>i-x),...n?g(n-1):[]])(i)

```

Building on Optimizer's recursive approach, we can build descending runs of decreasing length, like `[4,3,2,1, 4,3,2, 4,3, 4]`.

Instead of making same-value subarrays with `Array(i).fill(i)`, we make `undefined`-filled subarrays of the appropriate length with `Array(n).fill()` and then change the values to a descending run using `.map((v,x)=>i-x)`. Also, we define and recurse over an inner function `g`; the outer function `f` exists only to store the value of `i` while `g` recurses.
> 2 votes

# Answer
## T-SQL, 176 * 0.5 = 88

Since you seemed to miss the T-SQL @Optimizer, here it is in all it's verbose glory :).

A couple of function options, a Scalar and a Inline Table Valued function. The Scalar function uses while loops to recurse and returns a string of numbers, where the Inline Table Valued function uses a recursive CTE for a sequence and returns a table. Of course these will never be competitive, so I haven't spent a lot of time golfing.

**Inline Table Valued Function, 176 * .5**

```
CREATE FUNCTION F(@ INT)RETURNS TABLE RETURN WITH R AS(SELECT @ N UNION ALL SELECT N-1FROM R WHERE N>0)SELECT B.N FROM R CROSS APPLY(SELECT TOP(R.N)N FROM R A ORDER BY N DESC)B

```

Called as follows

```
SELECT * FROM dbo.F(5)

```

SQLFiddle example

**Scalar Function, 220 * .5**

```
CREATE FUNCTION G(@ INT)RETURNS VARCHAR(MAX)AS BEGIN DECLARE @S VARCHAR(MAX),@N INT=1,@I INT,@C INT WHILE @N<=@ BEGIN SELECT @I=@N,@C=@ WHILE @C>=@I BEGIN SELECT @S=CONCAT(@S+',',@C),@C-=1 END SET @N+=1 END RETURN @S END

```

Called as follows

```
SELECT dbo.G(5)

```

SQLFiddle example
> 2 votes

# Answer
### JavaScript(readable), 131 bytes

I'm new to Code Golf so this isn't the best

```
function f(n) {
    var arr = [];
    for(var i = 1; i <= n; i++) {
        for(var j = 0; j < i; j++) {
            arr.push(i);
        }
    }
    return arr;
}

```

### JavaScript(less readable), 87 bytes

Minified using jscompress.com

```
function f(e){var t=[];for(var n=1;n<=e;n++){for(var r=0;r<n;r++){t.push(n)}}return t}

```
> 2 votes

# Answer
# TECO, 25 bytes * 0.5 = 12.5

```
a\+1%a%b<qauc-1%b<-1%c=>>

```

The above barely beats the non-bonus version at 13 bytes:

```
a\%a<%b<qb=>>

```
> 2 votes

# Answer
## C#, ~~114~~ 99 * 0.5 = 49.5 bytes

*(With a little help from VisualMelon's answer) Edit: and James Webster's comment*

```
int[]A(int n){int m=n,i,c=0;var a=new int[n*(n+1)/2];while(m-->0)for(i=m;i++<n;)a[c++]=i;return a;}

```

*Ungolfed:*

```
int[] FooBar(int n)
{
    int altCounter = n, i, arrayCounter = 0;
    var returnArray = new int[n * (n + 1) / 2];
    while(m-->0)
        for(i = altCounter; i++ < n; )
            returnArray[arrayCounter++]=i;
    return returnArray;
}

```

---

~~There is an unsafe version that I shamelessly took from feersum's C answer, but I'm not 100% sure it fits within the rules since you have to allocate the memory before calling the method.~~

~~**C# (unsafe), 82 * 0.5 = 41 bytes**
```
unsafe void A(int n,int*p){int*z=p;int m=n,i;while(m-->0)for(i=m;i++<n;)z++[0]=i;}

```
Called as follows:
```
int n = 5, length = (int)((n / 2f) * (n + 1));
int* stuff = stackalloc int[length];
int[] stuffArray = new int[length];
A(n, stuff);
System.Runtime.InteropServices.Marshal.Copy(new IntPtr(stuffArray), stuffArray, 0, stuffArray.Length);
//stuffArray == { 5, 4, 5, 3, 4, 5, 2, 3, 4, 5, 1, 2, 3, 4, 5 }

```~~

Per VisualMelon's suggestion (thanks!), the unsafe code can be re-made with safe code which reduces the size even further! Still poses the question if the creation of the final result array is allowed to be done outside of the method.

**C#, 72 * 0.5 = 36 bytes**

```
void A(int n,int[]p){int z=0,m=n,i;while(m-->0)for(i=m;i++<n;)p[z++]=i;}

```
> 2 votes

# Answer
# 05AB1E, 4 bytes * 0.5 = 2

```
L.s˜

```

Try it online!

```
L                             # Inclusive range
 .s                           # Suffixes
   ˜                          # Flatten

```
> 2 votes

# Answer
# C#, ~~116~~ 115 + 33 = 148 bytes

Not the shortest code, but... it works anyway :P

```
int[]l(int m){List<int>i=new List<int>();for(int j=1;j<=m;j++){for(int x=0;x<j;x++){i.Add(j);}}return i.ToArray();}

```

Requires this at the top of the file (33 bytes):

```
using System.Collections.Generic;

```

Un-golfed version:

```
int[] RepatedNumberList(int m)
{
    List<int> intList = new List<int>();
    for (int j = 1; j <= m; j++)
    {
        for (int x = 0; x < j; x++)
        {
            intList.Add(j);
        }
    }
    return initList.ToArray();
}

```
> 1 votes

# Answer
### Bash with seq, expr and xargs = 59 / 2 = 29.5

Save it and run with the number as the first argument.

```
seq $1|xargs -n1 seq|xargs -n1 expr $1 + 1 -|sed 1d;echo $1

```
> 1 votes

# Answer
# J, 23 * 0.5 = 11.5

```
   f=.-;@(<@|.@i."0@>:@i.)
   f 5
5 4 5 3 4 5 2 3 4 5 1 2 3 4 5

```

# J, 11

```
   f=.#~@i.@>:
   f 5
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5

```
> 1 votes

# Answer
# ECMAScript6, 67 * 0.5 = 33.5 bytes

```
f=n=>{a=[],b=0;while(c=n+b,n--){while(c-b)a.push(c--);b++}return a}

```

Pretty happy with this one...It's about a quarter the size of my original.

`f(4)` returns:

```
[ 4, 3, 2, 1, 4, 3, 2, 4, 3, 4 ]

```

*Old answer:*

```
f=i=>{a=b=Array;while(i)a=a.concat(b.apply(null,b(i)).map(e=>i)),i--;return a}

```

This is my first shot at code golf...I still want to get that 0.5x bonus. Any suggestions are welcomed!

Called with f(n).
> 1 votes

# Answer
# JavaScript (ES6) 29 (58 * 0.5)

**Edit** remove ; thx @Optimizer

```
Q=o=>(m=>{for(n=o,r=[];n>m||++m<(n=o);)r.push(n--)})(0)||r

```

**Test** in FireFox/FireBug console

```
Q(9)

```

*Output*

```
[9, 8, 7, 6, 5, 4, 3, 2, 1, 9, 8, 7, 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 9, 8, 7, 6, 5, 4, 9, 8, 7, 6, 5, 9, 8, 7, 6, 9, 8, 7, 9, 8, 9]

```

**Ungolfed**

```
Q=o=>{
  for(m=0,r=[];m<o;++m)
    for(n=o;n>m;)
      r.push(n--);
  return r
}

```
> 1 votes

# Answer
# C#, 108 bytes * 0.5 = 54

```
List<int> f(int n){var r=new List<int>();int m=n-1,i;r.Add(n);for(;m-->0;)for(i=m;i++<n;)r.Add(i);return r;}

```

Thanks to VisualMelon for doing the hard work! I thought I'd try to squeeze it down as much as possible.

(114 bytes * 0.5 = 57, if you insist on using .ToArray() to return int\[\])
> 1 votes

# Answer
# K (oK), 4 bytes

**Solution:**

```
&!1+

```

Try it online!

**Examples:**

```
&!1+5
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
&!1+6
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6

```

**Explanation:**

```
&!1+ / the solution
  1+ / add one to the input, 1+5 => 6
 !   / til, !6 => 0 1 2 3 4 5
&    / where, &0 1 2 3 4 5 => 1 2 2 3 3 3...

```
> 1 votes

# Answer
# Python, 53 bytes ÷ 2 = 26.5

```
lambda n:[n-i%-~n%(i//n-~n)for i in range(n*~n//2,0)]
```

Attempt This Online!

#### Python 2 version, 51 bytes ÷ 2 = 25.5

```
lambda n:[n-i%-~n%(i/n-~n)for i in range(n*~n/2,0)]
```

Attempt This Online!

This uses ranges like many other answers here but groups them in pairs (longest,shortest);(2nd longest,2nd shortest) etc. That way we can use a closed form expression inside a flat loop.
> 1 votes

# Answer
# Factor \+ `grouping.extras`, 35 * 0.5 = 17.5 bytes

```
[ [1,b] tail-clump reverse concat ]

```

Try it online!

```
           ! 5
[1,b]      ! { 1 2 3 4 5 }
tail-clump ! { { 1 2 3 4 5 } { 2 3 4 5 } ... }
reverse    ! { { 5 } { 4 5 } { 3 4 5 } ... }
concat     ! { 5 4 5 3 4 5 2 3 4 5 1 2 3 4 5 }

```
> 1 votes

# Answer
# JavaScript (V8), 44 bytes

```
y=x=>x-1?y(x-1).concat(Array(x).fill(x)):[1]

```

Try it online!

Could probably be golfed more and probably similar to some other answers but might as well post it.
> 1 votes

# Answer
# Vyxal, ~~8~~ ~~6~~ 4 bytes

```
ƛẋ;f

```

Try it Online!

### Explained

```
ƛẋ;f
ƛ    # mapping lambda
 ẋ   # Repeat
  ;  # end lambda
   f # flatten

```
> 1 votes

# Answer
# Raku, 25 bytes * 0.5 = 12.5

```
{$_,|flat (1..$_-1)X..$_}

```

Try it online!

This generates the list consisting of the input number n, and the flattened list of ranges 1 .. (n-1), 2 .. (n-1), ..., n-2 .. n-1, n-1 .. n-1.
> 1 votes

# Answer
# K (ngn/k), 12 bytes

```
,/{x#x}'1+!:

```

Try it online!

Short and sweet.

Explanations:

```
,/{x#x}'1+!:  Main function. Takes implicit input x via Right (:)
          !   Create a range between 0 to x (exclusive)
        1+    + 1 to each of them
       '      For each of the numbers in the range
  {   }       Execute a function that
     x        Takes the number as implicit argument x
   x#         And duplicate by themselves' amount of times
,/            Join together

```
> 1 votes

# Answer
# Perl, 57 * 0.5 = 28.5

This entry is a subroutine named "l" (for "list"?)

```
sub l{$d=$n=shift;while($d){for($d--..$n){@a=(@a,$_)}}@a}

```

You can test it like this:

```
$"=", ";
@a=l(3);
print "[@a]\n"; # prints "[3, 2, 3, 1, 2, 3]"
@a=();          # needed because the function does not re-initialize @a
@a=l(5);
print "[@a]\n"; # prints "[5, 4, 5, 3, 4, 5, 2, 3, 4, 5, 1, 2, 3, 4, 5]"

```

A prior solution is shorter (45 characters), but doesn't print the output prettily so it was disqualified

```
$d=$n=<>;while($d){for($d--..$n){print"$_ "}}

```

For an input of 3, this one prints (with a trailing space):

```
3 2 3 1 2 3

```
> 0 votes

# Answer
# JAGL Alpha 1.1 - 15 bytes

```
1Ti[r{d()+S*}/E

```

Explanation:

```
1Ti               Push 1, take input, and convert to integer
   [r             Increment and make a range
     {d()+S*}     Push a block that makes an array with x occurrences of x
             /E   Map over list and flatten

```
> 0 votes

# Answer
# Perl 48 * 0.5 = 24

```
$i=<>;$"=", ";@a=map{-$_..$i}-$i..-1;print"[@a]"

```

Test run:

```
$ ./repeated.pl <<< 5
[5, 4, 5, 3, 4, 5, 2, 3, 4, 5, 1, 2, 3, 4, 5]

```
> 0 votes

# Answer
# Erlang, 56 Bytes * 0.5 = 28

```
f(I)->L=lists,L:flatten([L:seq(X,I)||X<-L:seq(I,1,-1)]).

```

Using a list comprehension, reverses the list using `lists:seq(UpperBound, 1, -1)` and for each element, creates a sequence using `lists:seq(CurrentValue, UpperBound)`. The eventual list is then flattened.

Expanded:

```
f(I) ->
    lists:flatten([lists:seq(X, I) || X <- lists:seq(I, 1, -1)]).

```

Input: `module_name:f(9).`

Output: `[9,8,9,7,8,9,6,7,8,9,5,6,7,8,9,4,5,6,7,8,9,3,4,5,6,7,8,9,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9]`
> 0 votes

# Answer
# Perl 5: 30 bytes / 2 = 15

Added one byte for the `-p` flag.

```
#!perl -p
$_=join$",map-$_..$',-$_..-//

```

Takes parameter on the input:

```
$ perl int.pl <<<5
5 4 5 3 4 5 2 3 4 5 1 2 3 4 5

```
> 0 votes

# Answer
## Java (adjacent equals ok): 276 bytes

```
public class a{public static int[]b(final int c){final int d=(c+1)*c/2;final int[]e=new int[d];int f=1;int g=0;for(int i=0;i<d;i++){if(g==f){f++;g=0;;}
e[i]=f;g++;}
return e;}
public static void main(String[]args){final int q=new java.util.Scanner(System.in).nextInt();b(q);}}

```

## Java (adjacent equals not ok): 442 * 0.5 = 221 bytes

```
public class a{private static int h=1;public static int[]j(final int k){final int[]l=new int[k+1];for(int i=1;i<=k;i++){l[i]=i;}
final int m=(k+1)*k/2;final int[]n=new int[m];for(int i=1;i<n.length;i++){n[i]=o(l,k);}
n[0]=k;return n;}
private static int o(final int[]p,final int q){if(h>q){h=1;}
while(p[h]==0){h++;}
p[h]=p[h]-1;return h++;}
public static void main(String[]args){final int q=new java.util.Scanner(System.in).nextInt();j(q);}}

```
> 0 votes

# Answer
## CoffeeScript, 57

```
f=(n)->i=0;a=[];(j=0;a.push i while(j++<i))while(i++<n);a

```
> 0 votes

# Answer
# Matlab, 44 * 0.5 = 22

```
function r=f(n);r=[];for i=1:n;r=[i:n,r];end

```

> f(4) == \[4 3 4 2 3 4 1 2 3 4\]

# Javascript, 63 * 0.5 = 31.5

```
F=n=>{r=[m=n];while(--n){r=r.slice(0,m-n).concat(n,r)}return r}

```

> F(4) == \[ 4, 3, 2, 1, 4, 3, 2, 4, 3, 4 \]

Nothing fancy, just concatenating arrays.
> 0 votes

# Answer
# Tcl, 36 bytes

```
time {time {puts $i} [incr i]} $argv

```

Try it online!
> 0 votes

# Answer
# Stax, 4 bytes * 0.5 = 2

```
R|]r

```

Run and debug it online! Note: To verify that is does indeed work, you'll need to step through the execution, as the values are printed as characters rather than numbers.

### Explanation:

```
R|]r
R       Range [1..n].     Example: [1, 2, 3, 4]
 |]     List of suffixes: Example: [[1, 2, 3, 4], [2, 3, 4], [3, 4], [4]]
   r    Reverse.          Example: [[4], [3, 4], [2, 3, 4], [1, 2, 3, 4]]
        Implicit flatten and print (treating numbers as characters and concatenating).

```

### Without the bonus (3 bytes):

```
R|]

```

or

```
R|[     (This does what you expect)

```
> 0 votes

# Answer
# Java 8, 109 bytes (score: 54.5 bytes)

```
import java.util.*;

```

```
n->{List l=new Stack();l.add(n);for(int i=0,j;i<n-1;i++)for(j=i;j++<n;)l.add(j);return l;}

```

That's a lambda from `int` to `List<Object>`. The members are, of course, `Integer`s.

Try It Online
> 0 votes

# Answer
# Pyth, 6 bytes * 0.5 = 3

```
s>RSQS

```

Try it here!
> 0 votes

# Answer
# Golang, 80 bytes

```
func n(a int)(r[]int){for i:=0;i<=a;i++{for j:=0;j<i;j++{r=append(r,i)}};return}

```

Ungolfed and readable:

```
func n(a int) (r []int){
    for i := 0; i <= a; i++ {
        for j := 0; j < i; j++ {
            r = append(r, i)
        }
    }
    return
}

```

Try it online!

Pretty straightforward solution and probably pretty bad.
> 0 votes

# Answer
# Pyth, 17 bytes x 0.5 = 8.5

```
FbQ=+Y-SQSb)+eYPY

```

Possibly golfable. Explanation:

```
FbQ=+Y-SQSb)+eYPY
FbQ                For b in range(int(input()))
     Y             A variable containing an empty list
   =+              +=
      -            The set difference of
       SQ          [1, 2, ..., input()]
         Sb        [1, 2, ..., b]
           )       End function
            +eY    Append to the last element of Y
               PY  All but the last element of Y

```

So for example, putting `3` through the loop would yield `[1,2,3,2,3,3]`, then the last five characters will transpose that final `3` to the beginning so no two numbers touch each other.
> 0 votes

# Answer
# GolfScript, 14 bytes

```
~),1>{.[()]*}%

```

Try it online!
> 0 votes

# Answer
# Add++, 9 bytes

```
L,Rdz£XbF

```

Try it online!

In most other languages, it might be worth going for the bonus by using things like prefixes etc. Not in add++.

## Explained

```
L,Rdz£XbF
L,        # create a lambda that:
  R       # pushes the range [1...n] to the stack
   dz     # ... zips that with itself
     £X   # ... reduces each item by item repetition
       bF # ... and flattens that

```
> 0 votes

# Answer
# brainf\***, 98 bytes

```
[[->+>+<<]>>[-<<+>>]<-[[->+>+<<]>>[-<<+>>]<-<[-]<[->+>>+<<<]>>>[-<<<+>>>]<]<[->+>+<<]>>[-<<+>>]<-]

```

Try it online!

Takes input as first cell on tape and outputs onto the tape. I'm not sure if this is allowed but input and output is really painful in brainf\*** so I'm presuming it's allowed. The example on TIO has header and footer code to print the values out because I couldn't find a way to dump the memory into the output.

If you consider that each brainf\*** character only contains 3 bits of information (as there are only 8 possible characters), then it's only `98 * (3/8) = 36.75` bytes of information.

I would put an explanation but I wrote the code yesterday and have forgotten how it works since then.
> 0 votes

# Answer
# GeoGebra, ~~44~~ 33 bytes * 0.5 bonus = ~~22~~ 16.5

```
n=4
l=Flatten(Zip(1…a,a,n…1))

```

Try It On GeoGebra!

My first time code golfing with GeoGebra :D and I gotta say, GeoGebra has a ton more built-in functions than Desmos. I think I'll start trying out GeoGebra a little bit more, it definitely has a lot of features. It's also surprisingly golfy, especially when it comes to lists!

But, I couldn't figure out how to get functions working properly in GeoGebra for some reason, so the input has to be changed by editing the value of `n`, and then pressing `Enter`. The code currently has a default input of `n=4`.
> 0 votes

# Answer
# MathGolf, score: 2 (4 bytes \\$\times \frac{1}{2}\\$ bonus)

```
╒╒x─

```

Try it online.

**Explanation:**

```
╒     # Push a list in the range [1, (implicit) input]
 ╒    # Map each value to an inner list in the range [1, value]
  x   # Reverse this list of lists
   ─  # Flatten
      # (after which the entire stack is output implicitly as result)

```
> 0 votes

# Answer
# APOL, 14 bytes

`⭳(Ƒ(⧣ Ƒ(∈ ⋒)))`

Explanation:

```
         Implicit print
⭳(       Flatten list
  Ƒ(     One-indexed list-builder for loop
    ⧣    Integer input
    Ƒ(   One-indexed list-builder for loop
      ∈  Loop item (of parent loop in this case)
      ⋒  For iterator (what's being iterated through)
    )
  )
)

```
> 0 votes

# Answer
# Japt, 5 bytes * 0.5 = 2.5

```
õõU c

```

Try it

```
õõU c #
õ     # For all numbers X in the range [1, input]:
 õU   #  Generate the range [input, X]
    c # Flatten

```

A cheatier 3 byte version produces the same visible output, but that's only because Japt's default string representation of 2D arrays isn't very clear. Using the `-Q` flag reveals the real output.
> 0 votes

# Answer
# Ruby, 34 bytes * 0.5 = 17

```
->n{(1..n).flat_map{[*n-_1+1..n]}}

```

Attempt This Online!
> 0 votes

# Answer
# Thunno 2, 3 bytes * 0.5 = 1.5

```
RȷI

```

Attempt This Online!

#### Explanation

```
RȷI  # Implicit input          ->  5
R    # Range [1..input]        ->  [1,2,3,4,5]
 ȷ   # Map over each:
  I  #  Range [input..n]       ->  [[5,4,3,2,1],[5,4,3,2],[5,4,3],[5,4],[5]]
     # Sum (flatten) the list  ->  [5,4,3,2,1,5,4,3,2,5,4,3,5,4,5]
     # Implicit output

```
> 0 votes

# Answer
```
jot 23 | awk NF=OFS=\$_

```

---

```
1
22
333
4444
55555
666666
7777777
88888888
999999999
10101010101010101010
1111111111111111111111
121212121212121212121212
13131313131313131313131313
1414141414141414141414141414
151515151515151515151515151515
16161616161616161616161616161616
1717171717171717171717171717171717
181818181818181818181818181818181818
19191919191919191919191919191919191919
2020202020202020202020202020202020202020
212121212121212121212121212121212121212121
22222222222222222222222222222222222222222222
2323232323232323232323232323232323232323232323

```
> 0 votes

---
Tags: code-golf, array, open-ended-function
---