# Question
Title: Check if an array (or equivalent) has the same number of odd and even numbers - Code Golf Edition!
Inspired by this code review question, I am curious to see what happens if we turn that into a code-golf challenge!

The description is easy, the input is an array or any similar data structure with only unsigned integers, the output is a boolean if the number of odd numbers is equal to the number of even numbers inside (true or false doesn't matter, as long as the opposite is used in case the number doesn't match)

Here are some examples with true as output for matching (thanks to the original OP)

```
[5, 1, 0, 2]      ->  true
[5, 1, 0, 2, 11]  ->  false
[]                ->  true

```

Usual code-golf rules, shortest code wins.

# Answer
# Haskell, 20 bytes

```
(==0).sum.map((-1)^)

```

Try it online!
> 14 votes

# Answer
# Python 2, 33 bytes

```
lambda l:sum(n%-2|1for n in l)==0

```

Try it online!

`n%-2|1` is a shorter way to do`(-1)**n`. It works like this:

```
   n  n%-2  n%-2|1
------------------
even     0       1
 odd    -1      -1

```

**36 bytes**

```
lambda l:sum(map((-1).__pow__,l))==0

```

Try it online!
> 9 votes

# Answer
# Jelly, 4 bytes

Thanks to Nick Kennedy for fixing a bug after three years!

```
Ḃo-S

```

A monadic Link that accepts a list of integers and yields zero (falsey) if the odd and even counts are equal or a non-zero number (truthy) otherwise.

**Try it online!**

### How?

```
Ḃo-S - Link: list of integers              e.g. [ 1, 2, 3, 4, 6]
Ḃ    - least-significant bit (vectorises)       [ 1, 0, 1, 0, 0]
  -  - -1
 o   - logical OR                               [ 1,-1, 1,-1,-1]
   S - sum                                      -1

```

Alternatively, `ịØ+S`, does the same thing using modular indexing.
> 7 votes

# Answer
-2 bytes, BIG Thanks to Arnauld

# JavaScript (V8), 31 bytes

```
s=>s.map(e=>d+=e&1||-1,d=0)&&!d

```

Try it online!
> 5 votes

# Answer
Here is my version (Thanks to @ElPedro and to everyone in the comments for the corrections):

# Python 3, 37 bytes

```
lambda x:sum(i%2for i in x)==len(x)/2

```

Try it online!
> 4 votes

# Answer
# perl -alp, 20 19 bytes

```
$_=@F-2*grep$_%2,@F

```

Try it online!

Just checks whether the size of the input is twice the number of odd integers. Accepts a list of space separated integers on STDIN. Prints 0 if the number of even and odd numbers are equal, something else otherwise.
> 4 votes

# Answer
# Ruby, 23 bytes

```
->x{x.sum{|n|~0**n}==0}

```

Try it online!

Special thanks to Manatwork, Dingus and to histocrat for finding the shortest solution, all credit to them.
> 4 votes

# Answer
# K (Kona), ~~7~~ 6 bytes

-1 byte thanks to coltim

```
~+/-1^

```

Try it online!

# , 9 bytes

```
0=1#._1^]

```

Try it online!

Ports of xnor's Haskell solution \- please upvote him!
> 4 votes

# Answer
# Wolfram Language (Mathematica), 14 bytes

```
Tr[(-1)^#]==0&

```

Try it online!
> 4 votes

# Answer
# MathGolf, 4 bytes

Port of @xnor's Haskell answer. In MathGolf, summing an empty list yields `0`.

```
b▬Σ┌

```

Try it online!

## Explanation

```
b    Constant -1
 ▬   -1 ** input list (vectorizes)
  Σ  Sum the resulting list
   ┌ Convert to inverted boolean

```
> 4 votes

# Answer
# dc, ~~25~~ ~~24~~ 23 bytes

```
?0[r_1r^+z1<F]sFz1<Fd/p

```

Try it online!

Or verify the test examples.

---

Input on stdin: a line of space-separated integers.

Output on stdout: `0` for truthy, and `1` for falsey (dc doesn't have standard truthy/falsey values).
> 4 votes

# Answer
# Python 3, 30 bytes

```
lambda x:sum(i%2-.5for i in x)

```

Try it online!
> 4 votes

# Answer
# x86 32-bit machine code, 13 bytes

Input: `uint32_t *esi, size_t ecx`
returns: EDX = `len - 2*even` = 0 for balanced, non-zero for unbalanced.
This conveniently works even for len=0 = balanced. As part of this asm custom calling convention / ABI, my boolean data type is 0 / non-zero, rather than the 0 / 1 that C ABIs use.

This avoids needing to actually compare, just decrement twice *inside* the loop, starting with the list length.

```
     1                         boe:
     2 00000000 89CA               mov    edx, ecx           ; balance = len
     3 00000002 E309               jecxz  .end
     4                         .loop:                        ; do {
     5 00000004 AD                 lodsd                       ; eax = *p++
     6 00000005 A801               test   al, 1
     7 00000007 7502               jnz   .odd
     8 00000009 4A                 dec    edx
     9 0000000A 4A                 dec    edx                 ; more compact than sub edx,2 in 32-bit code
    10                         .odd:
    11 0000000B E2F7               loop   .loop              ; }while(--ecx);
    12                         .end:
    13                         ;    xchg   eax, edx          ; custom calling convention: return in EDX instead of spending a byte on xchg
    14 0000000D C3                 ret

```

Try it online! (with a `_start` test case that exits with the return value as exit status)

An alternate version that calculates in EAX to return in the standard calling convention's register is 14 bytes. It uses `test byte [edi], 1` (1 byte longer than `test al,1`) and increments the pointer with `scasd` (without caring about the FLAGS result of the `eax - [edi]` it also does). See the TIO link.

Uncommenting the `xchg eax, edx` at the bottom of the 13-byte version would do the same thing, and that version's loop is more efficient.

---

For 8-bit integer input, use `lodsb` instead. Unfortunately, we can't use `and al, 1` / `add dl, al` or similar (without branching). That would only work for array sizes up to 255. `and eax,1` is 3 bytes.

Also, masking and adding only does one increment. `lea edx, [edx + eax*2]` could work but that's also 3 bytes. Branching on the low bit with test/jnz seems to be best for size, although it sucks for performance with branch mispredicts.

Of course if we wanted to go fast, we'd load 16 bytes at once with `movdqa`, isolate the low bits with `pand`, and sum with `paddd`. Then hsum at the end. Or hsum with `psadbw` against a zeroed register, then `paddq`. SIMD is of course especially good for 8-bit elements, 16 per vector instead of 4, with an outer loop to avoid overflowing 8-bit counters. e.g. this AVX2 SO answer.

Something like this could maybe be smallish code-size if we limited it to a fixed-size 16-byte input array, or maybe 8-byte in MMX registers. Unfortunately we rarely get to play with SIMD in code golf because the instructions are larger and inputs can be odd lengths requiring cleanup loops.
> 4 votes

# Answer
# APL (Dyalog Extended), 7 bytes

Port of xnor's Haskell solution. Prompts for the input; -2 thanks to @Graham.

-1 byte thanks to @Adám by switching the language.

```
=+/¯1*⎕

```

Try it online!
> 3 votes

# Answer
# Burlesque, ~~17~~ 14 bytes

```
ps{2.%}pt)L[sm

```

Try it online!

Saved 3 bytes using shorthand map

Explanation:

```
ps                # Parse input as a block
  {2.%}pt         # Partition block based on modulo 2
         )L[      # Map blocks to their length
            sm    # Check lengths are the same

```
> 3 votes

# Answer
# \[Excel\], 28 bytes

Paste this into a cell outside of column A, the array goes in column A.

```
=0=SUM(IF((A:A<>""),-1^A:A))

```

An example:
> 3 votes

# Answer
# Java (JDK), 28 bytes

```
a->a.map(n->-n%2|1).sum()==0

```

Try it online!
> 3 votes

# Answer
# Befunge-98 (PyFunge), ~~13~~ 12 bytes

*-1 byte thanks to @Jo King!*

```
#.&2%2*1-+#@

```

Try it online!

This uses the same logic (`&2%2*1-+`) as @Abigail's answer, but has a different control flow structure. Befunge-98 adds extra "error handling" functionality to the `&` and `~` input instructions: when EOF is reached, they reflect the instruction pointer. When this happens, the program can execute a different section of code without the need for an explicit conditional.

```
#.&2%2*1-+#@

               (Implicit: the counter, the top of the (empty) stack, starts at 0)
               (Implicit in program structure: begin loop)

#              Skip the next instruction
 .             (skipped)
  &            Get integer from STDIN
   2%          Take the integer modulo 2
     2*        Multiply that by 2 (results in 2 if the number was odd and 0 if even)
       1-      Subtract 1 (results in 1 if the number was odd and -1 if even)
         +     Add that to the counter
          #    Skip the next instruction
           @   (skipped)
               Repeat

When the input runs out:
  &            Catch the EOF and reverse direction
 .             Output the counter (0 if odds and evens are matched, nonzero otherwise) as an integer
#              Skip the next instruction (a space)
           @   End the program

```
> 3 votes

# Answer
# MATL, ~~6~~ 5 bytes

-1 bytes thanks to @LuisMendo

```
oEqs~

```

Try it online!

## Explanation

```
oEqs~
o      % Replace each elements with its parity (i.e. mod 2)
 E     % Multiply all element by 2
  q    % Decrement all elements by 1
   s   % Sum the array
    ~  % Boolean not the sum

```
> 3 votes

# Answer
# sed `-E`, ~~78~~ 80 bytes

*+7 to account for 0's and empty lists, -5 from golfing*

Tried to have some fun:) Input is spaced separated unary numbers. Ex: `echo "!!! !! !!!!" | sed -Ef main.sed` (if the code is saved to main.sed)

```
s/_/@/g
s/(!!)+/@/g
s/@*!/!/g
s/ //g
:l
s/(!@|@!)//g
tl
s/!+/true/g
s/^$/false/g

```

Try it online!
> 3 votes

# Answer
# Uiua, 8 bytes

```
=0/+ⁿ∶¯1

```

Try it!

```
=0/+ⁿ∶¯1
    ⁿ∶¯1  # raise -1 to input
  /+      # sum
=0        # is it equal to zero?

```
> 3 votes

# Answer
# K (ngn/k), ~~6~~ 9 bytes

+3 bytes from fixing code per @Dominic van Essen's comment

```
~+/1 1'2!

```

Try it online!

* `2!` mod the (implicit) input by two
* `1 1'` convert `0`'s to `-1`'s, leave `1`s unchanged
* `~+/` not the sum of the above
> 3 votes

# Answer
# 05AB1E, ~~6~~ 4 bytes

```
ÉD¢Ë

```

Try it online!

## Explanation

```
É    Is the number odd?
 D   Duplicate
  ¢  Count the occurances of the bits in the original copy
   Ë Are all items in the list equal?

```
> 2 votes

# Answer
# C (gcc), ~~45~~ ~~44~~ 43 bytes

Saved a byte thanks to ceilingcat!!!

Saved a byte thanks to Olivier Grégoire!!!

```
b;f(int*a){for(b=0;~*a;b+=-*a++%2|1);b=!b;}

```

Try it online!

**Input**:

\\$-1\\$ terminated `int` array.

**Output**

C boolean values: \\$1\\$ if number of odd are equal to the number of even numbers, \\$0\\$ otherwise.

**How**

Initialise a counter `b` to \\$0\\$. Then go through the elements in the array adding \\$1\\$ to `b` for every odd number and \\$-1\\$ to `b` for every even number. Return the boolean result of testing `b` equal to \\$0\\$.
> 2 votes

# Answer
# Factor, 52 bytes

```
: f ( s -- ? ) [ odd? ] partition [ length ] bi@ = ;

```

Try it online!
> 2 votes

# Answer
# Pyth, 6 bytes

```
!sm^_1

```

Try it online!

## Explanation

```
!sm^_1
  m    : map
   ^_1 : -1 power value
       : over implicit input
 s     : sum it
!      : logical negate the sum (i.e. 0 -> True, -1 -> False, 10 -> False)

```
> 2 votes

# Answer
# , ~~18~~ 17 bytes

```
!sum((-1)^scan())

```

Try it online!

*Edit: -1 byte thanks to Bart-Jan van Rossum*
> 2 votes

# Answer
# brainfuck, 34 bytes

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

```

Try it online! (Check the `!` box to enter input automatically.)

Takes input as code points. Prints a null byte if there are equal number of odds and evens. Otherwise, prints a non-null byte.

**Memory layout**:

```
a b 0 n 0

```

where `a` is the current number of odds, `b` is the current number of evens, and `n` is the current element in the array.

**Explanation**:

```
+>+>>        set a and b to 1, and pointer to n
,[           for each element n in the array
  [-[->]<]     if n is even, pointer stops at n, else, pointer stops at left of n
                 in both case, n is set to 0
                 this requires the cells left and right of n to be 0
  <<+          increment a or b appropriately
  [>]>,        pointer back to n, read new n
]            stop if n = 0 (end of array)
<<[-<->]<.   find b - a, and print that value

```
> 2 votes

# Answer
# Brainetry, 342 bytes

Golfed version:

```
a b c d
a b
a b c d
a bb
a b
a b c d e f
a b c d e f g h
a b c d e f g h
a b c d e
a b c d e f g h
a b c d e
a b
a b c d e f g h i
a b c
a b c d e f g h i
a b c
a b c
a b c d
a b c d e f g h
a b
a b c d e f g h i
a b
a b c d e f
a b c d e f g h i
a b c
a b c
a b c d e f g h
a b c d e
a b c
a b c d e
a b
a b c d e f g h i
a b c
a b c d e f g

```

To make our lives easier we use the `--numeric-io` flag, so that we can take input and give output as integers, but we don't really need to and the answer works without it. Read the program below for due credit.

The golfed version was adapted from the program found below. To try this online you can

* head over to this replit link, copy&paste the code into the `btry/replit.btry` file and hit the green "Run" button (takes input as ASCII characters (converts them to codepoints) and outputs ASCII characters, use CTRL-D in a newline to terminate input, doesn't really work well for this challenge.);
* clone the github repo and from your terminal run `./brainetry btry/ppcg/evens_and_odds.btry --numeric-io` (give one integer per line, use CTRL-Z or CTRL-D in an empty line to stop giving input).

```
"Check if an array
(or equivalent)
has the same number
of odd
and even
numbers - Code Golf Edition !"
That is the title of the codegolf.stackexchange.com challenge
that this brainetry program solves. Once more, with
no shame at all ,
I am piggy backing on someone else's answer.
This time, Surculose Sputum's answer.
Oh boy!
You can check the original answer over here: https://codegolf.stackexchange.com/a/205621/75323
Go upvote that!
This is a very literal port of that answer.
I am pretty
sure I could
have used brainetry's builtins
to make this easier, like » or ≥,
except that
would mean I would have to think... ugh... nope!
For now
I will stick to the low
hanging fruit just to show that brainetry is out.
If this is
the first time
you find a brainetry program, welcome! By now
you probably understood you are
allowed to write
pretty much anything as source.
(source code)
You only have to write lines of correct size
and with the
correct line modifiers. (That's a recent addition.)

```
> 2 votes

# Answer
# Keg, ~~13~~ 10 bytes

```
÷⑷0;$Ë⑸⅀0=

```

Try it online!

## Transpiled Code

```
item_split(stack)
keg_map(stack, '0;$Ë')
summate(stack)
integer(stack, 0)
comparative(stack, '=')

```

`0;$Ë` turns into:

```
integer(stack, 0)
decrement(stack)
swap(stack)
exponate(stack)

```
> 2 votes

# Answer
# Brachylog, 6 bytes

```
%₂ᵍlᵐ=

```

Try it online!

### How it works

```
%₂ᵍlᵐ=
  ᵍ     group input based on result of …
%₂        mod 2
   lᵐ   map length over all groups
     =  are the lengths equal?

```
> 2 votes

# Answer
# Arturo, ~~25~~ 23 bytes

```
$=>[0=∑map&=>[^0-1&]]

```

Try it
> 2 votes

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

```
1n@S

```

Attempt This Online!

Outputs `0` (which is falsy in Thunno) for `true` and something else (which is truthy in Thunno) for `false` (meta consensus).

## Thunno, \\$ 6 \log\_{256}(96) \approx \\$ 4.94 bytes

```
1n@S0=

```

Attempt This Online!

Outputs `True` for `true` and `False` for `false`.

### Explanation

Port of xnor's Haskell answer.

```
1n@S0=  # Implicit input
1n      # Push -1
  @     # Get -1 ** each element of the input
   S    # The sum of the resulting list
    0=  # is equal to 0?
        # Implicit output

```
> 2 votes

# Answer
# JavaScript (Node.js), 29 bytes

```
a=>a.map(x=>i+=x%2-.5,i=0)|!i

```

Try it online!

Combined some js and py solution

If input.length==1 then a.map returns 0.5 or -0.5, treated as 0 on bool operation

+1B if returning bool required

```
a=>a.map(x=>i+=x%2-.5,i=0)&&!i

```

Try it online!
> 2 votes

# Answer
# jq, 24 characters

```
map(.%2)|add+0==length/2

```

Just a write of the question owner's Python solution.

(Grr! 2 characters wasted because `[]|add` results `null`.)

Sample run:

```
bash-5.0$ jq 'map(.%2)|add+0==length/2' <<< '[5, 1, 0, 2]'
true

```

Try it online! / Try all test cases online!

# jq, 21 characters

```
map(.%2*2-1)|add+0==0

```

The other most efficient solution from Code Review.

Sample run:

```
bash-5.0$ jq 'map(.%2*2-1)|add+0==0' <<< '[5, 1, 0, 2]'
true

```

Try it online! / Try all test cases online!
> 1 votes

# Answer
# Husk, 6 bytes

Why does need so many bytes... help!

```
EmLk%2

```

Try it online!
> 1 votes

# Answer
# Julia 18 bytes

## Try it!

```
l->sum((-1).^l)==0

```
> 1 votes

# Answer
# Octave, 19 bytes

```
@(x)(~sum((-1).^x))

```

Try it online!
> 1 votes

# Answer
# Golfscript, 18 bytes

```
~.{2%},\{2%!},,\,=

```

Try it online!
> 1 votes

# Answer
# Japt `-!xm`, 3 bytes

```
JpU

```

Try it

## Explanation

The Flags:

* `!` Outputs the logical NOT of the value returned by the program
* `x` Reduces output of program on plus
* `m` Runs the program on each element in the first input, outputting an array of the results.

```
J    // The number -1
 p   // power
  U  // Input

```

---

# Japt, ~~7~~ 6 bytes

```
!Ux!pJ

```

Try it

Same thing as above but without flags

## Explanation

```
   !pJ  // Function that does -1 ** arg
 Ux     // Map input on function then sum
!       // Logical not

```
> 1 votes

# Answer
# Raku, 15 bytes

```
{!sum -1 X**$_}

```

Try it online!

The usual not of the sum of negative one to the power of each element in the input.
> 1 votes

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

```
[ -1 swap n^v Σ 0 = ]

```

Try it online!

## Explanation:

* `-1` push `-1` to the data stack (e.g.) `{ 5 1 0 2 } -1`
* `swap` swap top two objects on the data stack `-1 { 5 1 0 2 }`
* `n^v` vectorized exponentiation `{ -1 -1 1 1 }`
* `Σ` sum a sequence `0`
* `0` push `0` to the data stack `0 0`
* `=` check top two objects on the data stack for equality `t`
> 1 votes

# Answer
# Vyxal, 5 bytes

```
∷Ċvt≈

```

Try it Online!
> 1 votes

# Answer
# Go, 62 bytes

```
func(L[]int)bool{n:=0
for _,i:=range L{n+=-i%2|1}
return n==0}

```

Attempt This Online!
> 1 votes

# Answer
# QBasic, 38 bytes

```
1s=s+(-1)^n
INPUT n
IF n>=0GOTO 1
?s=1

```

Enter the numbers one at a time with `-1` as a sentinel value at the end. The program then outputs either `-1` (true, same number of evens and odds) or `0` (false, different number of evens and odds).

Try it at Archive.org!

### Explanation

The same "sum of \\$-1\\$ to the power of each number" approach as a lot of answers, with a twist. The straightforward approach is to write a loop like this:

* Input a number
* If it's -1, output the sum and quit
* Else, add \\$\pm1\\$ to the sum accordingly and loop

But it's golfier if we can write a simple loop with the condition at the end (`1 ... IF n >= 0 GOTO 1`) rather than breaking out of the middle. So our actual loop looks like this:

* Add \\$\pm1\\$ to the sum
* Input a number
* If it's nonnegative, loop
* Else, output the sum and quit

Since QBasic initializes numeric variables to 0, the first `s = s + (-1) ^ n` before any `n` has been input adds 1 to `s`. Thus, a balanced array at the end of the loop is indicated by `s` being 1, not 0.
> 1 votes

# Answer
# Pyt, 6 bytes

```
1∧2*⁻Ʃ

```

Try it online!

Outputs 0 (which is falsy in Pyt) for `True` and something else (which is truthy) for `False`

```
1∧        implicit print; bitwise-AND with 1 (equivalent to mod 2)
  2*⁻     double and decrement each element
     Ʃ    get sum; implicit print

```
> 1 votes

# Answer
# Zsh, 31 bytes

```
for i;((i%2?j++:k++));<<<$[j-k]

```

Try it online!

Outputs `0` (truthy) if odds = evens, non-zero otherwise.
> 1 votes

# Answer
# Pip, 21 bytes

```
b:0Wa{%POa?++i++b}i=b

```

Try It Online!
> 1 votes

# Answer
# TI-Basic, 10 bytes

```
dim(Ans)=4sum(fPart(Ans/2

```

Takes input in `Ans`.
> 1 votes

# Answer
# Thunno 2 `S!`, 2 bytes

```
u@

```

Attempt This Online!

## Thunno 2, 4 bytes

```
ñEḷạ

```

Attempt This Online!

#### Explanation

```
u@  # Implicit input
u   # Push -1
 @  # Exponentiation
    # Check if the sum is 0
    # Implicit output

```

```
ñEḷạ  # Implicit input
ñ     # Group by:
 E    #  Is even?
  ḷ   # Length of each
   ạ  # Equal?
      # Implicit output

```
> 1 votes

# Answer
# Desmos, 23 bytes

```
f(l)=0^{(-1)^l.total^2}

```

Try It On Desmos!

Try It On Desmos! - Prettified
> 1 votes

# Answer
# Vyxal, 15 bitsv2, 1.875 bytes

```
Ǎ∑

```

Try it Online!

Uses inverted booleans (0 for truthy, any other value for falsey)

## Explained

```
Ǎ∑
 ∑  # Sum of
Ǎ   # -1 to the power of each number in the input

```
> 1 votes

# Answer
# GolfScript, 13 bytes

```
~.,2/\{2%},,=

```

Try it online!

```
~.,2/\{2%},,=
~              # Evaluate the input string.
 .             # Duplicate the list on the stack.
  ,            # Push the length of the list.
   2/          # Divide it by 2.
     \         # Swap so the original list is on top.
      {  },    # Filter, only keeping items that
       2%      # aren’t divisible by 2.
           ,   # The length of the filtered list.
            =  # Is this equal to the length of the original divided by 2?

```

Created with the help of Luminespire.
> 1 votes

# Answer
# APL+WIN, 15 bytes

Prompts for input of array. Can be anything from scalar, vector or multi dimensional array. TIO gives examples up to a 4 dimensional array:

```
(+/~n)=+/n←2|,⎕

```

Try it online! Coutesy of Dyalog Classic
> 0 votes

# Answer
# Erlang (escript), 40 bytes

Port of the Python answer on Code Review.

```
f(I)->lists:sum([X rem 2*2-1||X<-I])==0.

```

Try it online!

## Explanation

```
f(I)->    % Takes an input argument
||X<-I]   % For every inputted item:
[X rem 2*2-1 % Convert X % 2 into 1's and -1's, respectively
lists:sum()  % Sum the list
==0.          % Is it 0?

```
> 0 votes

# Answer
# Befunge-93, 27 26 bytes

```
0v   @.$<
+>&:1+!#^_2%2*1-

```

Try it online!

Prints 0 if the number of odd and even numbers are equal, something else if they aren't. Keeps track of the difference between the number of even and odd numbers seen, adding 1 for an odd number, and -1 for an even number. Prints out this difference.

Edit: Moved the `+` to the left, saving a byte.
> 0 votes

# Answer
# Charcoal, 5 bytes

```
¬ΣＸ±¹

```

Try it online! Port of @xnor's Haskell answer. Corresponds to the verbose code `Print(Not(Sum(Power(Negate(1), Input()))));` except that the input is implicit. Works even for zero-length arrays whose sum is `Null` rather than `0`. Note: Zero-length input arrays seem to confuse Charcoal, so input that case as `[[],[]]`.
> 0 votes

# Answer
# Retina 0.8.2, 49 bytes

```
\d+
$*
+`(^|(,))(11)*(,1|1,)(11)*($|(\2)|,)
$7
^$

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert to unary.

```
(^|(,))(11)*(,1|1,)(11)*($|(\2)|,)
$7

```

Match an even number of characters that includes a single `,` and is delimited on either side by either the end of the string or a `,`, thus corresponding to a pair of numbers of opposite parity. Remove both numbers and at most one adjacent `,`.

```
+`

```

Continue to remove pairs of numbers until all remaining numbers have the same parity.

```
^$

```

Check that there are no numbers left.
> 0 votes

# Answer
# , 28 bytes

```
!sd(table(c(0,1,scan())%%2))

```

Try it online!

`table` gets the counts of the unique values in the array. By appending `c(0,1)` to the array, we take care of the empty case. The standard deviation is equal to zero if and only if all the values from `table()` are equal, so we take the logical negation of that to get the result.

Alternately:

# , 28 bytes

```
!any(diff(table(scan()%%2)))

```

Try it online!
> 0 votes

# Answer
# Icon, 52 bytes

```
procedure f(a)
(s:=0)+:=-1^!a&\z
return(s=0&1)|0
end

```

Try it online!
> 0 votes

# Answer
# Racket, 44 bytes

```
(λ(a)(=(apply +(map(λ(x)(expt -1 x))a))0))

```

Try it online!
> 0 votes

# Answer
# Jelly, 4 bytes

```
-*S¬

```

Try it online!

Could be 3 bytes under "one consistent value, one non-consistent value" rules, with `-*S` outputting 0 for true and anything else for false.

```
   ¬    Whether or not 0 equals
  S     the sum of
-       -1
 *      to the power of every element of the input (implicitly vectorized).

```
> 0 votes

# Answer
*Edit: shortened both by one byte by changing `n%2*-2+1` to `n%2*2-1`*

# JavaScript (Node.js), 28 bytes with `-p` flag

```
.map((i=0,n=>i+=n%2*2-1));!i

```

Try it online!

Link leads to a TIO instance with `console.log(!i)` because I can't find out how to use the Node.js `-p` flag on TIO.

Less "cheating" answer:

# JavaScript (Node.js), 32 bytes

```
a=>(a.map(x=>i+=x%2*2-1),!i);i=0

```

Try it online!

This link also leads to a snippet with `console.log` because I still can't figure out how to use the `-p` flag, but this one's a function.
> 0 votes

# Answer
# Clojure (60 bytes)

```
(defn q[c](reduce = (map #(count(filter % c))[odd? even?])))

```

Ungolfed:

```
(defn eq-odd-even [c]
  (reduce = (map #(count (filter % c)) [odd? even?])))

```

Try it online!
> 0 votes

# Answer
# SQLite, 28 bytes

```
SELECT SUM(N%2*2-1)=0 FROM T

```

Inspired by this comment.

Try it online!
> 0 votes

# Answer
# Zpr'(h, 151 bytes

```
f|>\

```

```
(g ° (section p <$> @))
(g .l)|>((2 * (length (filter (section 0 == @) l))) == (length l))
(p ())|>0
(p (S ()))|>1
(p (S (S .n)))|>(p n)
<|prelude.zpr

```

```
test-cases |> ('\
        (' 5 (' 1 (' 0 (' 2 ())))) ('\
        (' 5 (' 1 (' 0 (' 2 (' 11 ()))))) ('\
        (' 2 (' 16 (' 3 (' 2 (' 11 (' 19 ())))))) ('\
        (' 2 (' 16 (' 3 (' 4 (' 2 (' 11 (' 19 ()))))))) ('\
        () \
    ())))))
main |> (zip test-cases (map f test-cases))

```

```
% ./Zprh stdlib/golf.zpr --de-peano
(' ((' 5 (' 1 (' 0 (' 2 0)))) , true) (' ((' 5 (' 1 (' 0 (' 2 (' 11 0))))) , false) (' ((' 2 (' 16 (' 3 (' 2 (' 11 (' 19 0)))))) , true) (' ((' 2 (' 16 (' 3 (' 4 (' 2 (' 11 (' 19 0))))))) , false) (' (0 , true) 0)))))

```
> 0 votes

# Answer
# Scala, ~~20~~ 18 bytes

```
_.map(_%2*2-1).sum

```

Try it online!

Outputs 0 if there as many odd numbers as even numbers, a negative number if there are more even numbers, and a positive number if there are more odd numbers.

## Also 18 bytes:

```
_.:\(0)(_%2*2-1+_)

```

Try it online!

---

## Previous solution, 33 bytes

```
a=>a.count(_%2>0)==a.count(_%2<1)

```

Pretty straightforward solution. Just checks if the number of odd numbers equals the number of even numbers.

Try it online!
> 0 votes

# Answer
# Rust, 44 bytes

```
|a|a.iter().map(|n|(n&1)*2-1).sum::<i8>()==0

```

Try it online

Argument type is `a: Vec<i8>`.

`.iter()` and `::<i8>` add 13 bytes to the solution which hurts the score quite a bit, but the compiler can't infer the `<i8>` unfortunately. If this closure accepted an iterator instead of a `Vec<i8>` (for example `std::slice::IterMut<'static, i8>`), the `.iter()` could be removed, but that seems a bit cheaty.
> 0 votes

# Answer
# Prolog (SWI), ~~84~~ 72 bytes

Saved 12 bytes thanks to this tip that user41805 suggested!

```
[]*A*A.
[H|T]*E*O:-M is mod(H,2),F is E+1-M,P is O+M,T*F*P.
f(X):-X*0*0.

```

Try it online!

`g` accepts a list, the number of even elements found so far, and the number of odd elements found so far. The base case is an empty list where the second and third parameters are the same. The second case calls `g` on the tail `T`, and increments `E` (number of even elements) or `O` (number of odd elements) depending on the head of the list, `H`. `f` is just for convenience, and starts `g` off with 0 elements of both parities.
> 0 votes

# Answer
# Rust, 43 bytes

```
|a:&[i8]|0==a.iter().fold(0,|a,n|a+n%2*2-1)

```

Attempt This Online!

Simple functional solution. Works by first calculating the parity of the number, replacing each value by -1 if even and +1 if odd using a linear function of the remainder, and then summing the results. The sum is then compared to 0 to output a boolean.
> 0 votes

---
Tags: code-golf, decision-problem, arithmetic
---


title: Reverse Array Sum

text:
# Question
Title: Reverse Array Sum
Your program should take an array as input.

The array:

1. Will always be 1 dimensional
2. Will only contain integers
3. Can be empty

The program should reverse the array, and then add up the elements to the original for example:

**Input:** `[1, 2, 3]`

**Original:** `[1, 2, 3]`

**Reversed:** `[3, 2, 1]`

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

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

```

**Output:** `[4, 4, 4]`

---

**Test Cases:**

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

```

This is , the shortest code (in bytes) wins!

# Answer
# Haskell, 20 bytes

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

```
zipWith(+)=<<reverse

```

Try it online!
> 13 votes

# Answer
# Jelly, 2 bytes

```
+U

```

Try it online!

or

```
+Ṛ

```

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

### explanation, though it's pretty self-explanatory

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

```

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

```

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

# Answer
## JavaScript (ES6), 27 bytes

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

```

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

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

# Answer
# 05AB1E, 2 bytes

```
Â+

```

Try it online!
> 9 votes

# Answer
# Python 2, 32 bytes

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

```

Alternative solution without `zip` (35 bytes):

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

```

Try it online!
> 9 votes

# Answer
# Python 2, 40 bytes

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

```

Try it online!

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

# Answer
# Japt, 7 bytes

```
mÈ+Ug~Y

```

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

## Explanation

Implicit: `U` = input array

Map the input by the following function...

```
+Ug

```

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

```
~Y

```

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

# Answer
# Ruby, 25 bytes

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

```

Try it online!
> 7 votes

# Answer
# Mathematica, 12 bytes

```
Reverse@#+#&

```

Try it online!
> 6 votes

# Answer
# Python 2, ~~33~~ 32 bytes

-1 byte thanks to @xnor

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

```

Try it online!
> 6 votes

# Answer
# Brachylog, 6 bytes

```
↔;?z+ᵐ

```

Try it online!
> 5 votes

# Answer
# J, 3 bytes

```
+|.

```

Reverse, sum.

Try it online!
> 5 votes

# Answer
# C# (.NET Core), ~~61~~ 60 bytes

*-1 byte thanks to TheLethalCoder*

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

```

Try it online!

Byte count also includes:

```
using System.Linq;

```

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

# Answer
# Vyxal, 2 bytes

```
Ḃ+

```

Try it Online!

```
Ḃ+
Ḃ  # bifurcate, i.e. duplicate and reverse
 + # vectorized addition of two lists

```
> 5 votes

# Answer
# CJam, 7 bytes

```
{_W%.+}

```

Try it online!
> 4 votes

# Answer
# , ~~17~~ 16 bytes

*-1 byte thanks to djhurio*

```
rev(l<-scan())+l

```

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

Try it online!
> 4 votes

# Answer
# APL (Dyalog), 3 bytes

```
⌽+⊢

```

Try it online!

### Explanation

```
⌽          The argument reversed
+           Plus
⊢          The argument

```
> 4 votes

# Answer
# Clojure, ~~20~~ 17 bytes

3 bytes saved thanks to @MattPutnam

```
#(map +(rseq %)%)

```

Seems to be quite competitive with non-golfing languages.

See it online
> 4 votes

# Answer
# Pyth, 3 bytes

```
+V_

```

Try it here.
> 3 votes

# Answer
# PowerShell, ~~40~~ 32 bytes

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

```

Try it online!

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

Saved 8 bytes thanks to @briantist
> 3 votes

# Answer
# PowerShell, 26 bytes

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

```

Try it online!

Takes input as command-line arguments.
> 3 votes

# Answer
# C, 49 bytes

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

```
> 3 votes

# Answer
# Java 8, ~~61~~ ~~57~~ ~~56~~ 53 bytes

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

```

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

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

**Explanation:**

Try it here.

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

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

```
> 3 votes

# Answer
# K4 / K (oK), 5 bytes

**Solution:**

```
x+|x:

```

Try it online!

**Example:**

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

```

**Explanation:**

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

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

```
> 3 votes

# Answer
# Factor, 18 bytes

```
[ dup reverse v+ ]

```

Try it online!

## Explanation

```
         ! { 1 2 3 }
dup      ! { 1 2 3 } { 1 2 3 }
reverse  ! { 1 2 3 } { 3 2 1 }
v+       ! { 4 4 4 }

```
> 3 votes

# Answer
# tinylisp, 44 39 bytes

```
(load library
(q((p)(map* a p(reverse p

```

-5 bytes thanks to @DLosc

Try it online!

## Explanation

An anonymous function that maps the `a` function (addition) over pairwise elements in the input and the reverse of the input, forming a new list.
> 3 votes

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

```
{x+|x}

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), ~~34~~ 33 bytes

Saved a byte thanks to @ETHproductions.

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

```

```
let f=

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

console.log(f([8,92]));
console.log(f([1,2,3]));
console.log(f([5, 24, 85, 6]));
console.log(f([]));
console.log(f([999]));
```
> 2 votes

# Answer
# Ohm, 3 bytes

```
DR+

```

Try it online!
> 2 votes

# Answer
# Actually, 4 bytes

```
;R♀+

```

Try it online!
> 2 votes

# Answer
# anyfix, 3 bytes

```
"U+

```

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

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

```
> 2 votes

# Answer
# Röda, 22 bytes

```
{reverse(_)<>_1|[_+_]}

```

Try it online!

This is an anonymous function that takes in an array and returns a stream of values, which the TIO link outputs separated over newlines.

### Explanation

```
reverse(_)          The array reversed
<>                  interleaved with
_1                  the array itself
                    Push each element to the stream
[_+_]               Pull two values and push their sum

```
> 2 votes

# Answer
# Neim, 2 bytes

This is a function that takes input on the top of the stack and outputs on the top of the stack.

```

```

Try it online!
> 2 votes

# Answer
# MATL, 3 bytes

```
tP+

```

Try it online!

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

# Answer
# PHP, 59 bytes

```
for(;a&$c=$argv[++$i];)$a[]=$c+$argv[$argc-$i];print_r($a);

```

takes input from command line arguments; empty output for empty input

Yields a warning in PHP\>7.0. This version does not (60 bytes):

```
for(;++$i<$argc;)$a[]=$argv[$i]+$argv[$argc-$i];print_r($a);

```
> 2 votes

# Answer
# Swift 3, 30 bytes

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

```
> 2 votes

# Answer
# J-uby, 21 bytes

```
:zip%:reverse|:*&:sum

```

Try it online!
> 2 votes

# Answer
# HP 48 User REPL, 19 bytes

```
« DUP REVLIST +
»

```

## Explanation

`«` and `»` mark the object as a program.

`DUP` \- Duplicates the list

`REVLIST` \- Reverses the list

`+` \- Sums them
> 2 votes

# Answer
# Pyth, 5 bytes

```
sMC_B

```

Try it online!
> 1 votes

# Answer
# Positron, 59 bytes

```
->{a=[]i=0;while(i<len@$1)do{a+=[$1@i+($1@(-(i+1)))]i++};a}

```

Try it online!

This has many golfing opportunities that have been ruined by Positron's brokenness :P
> 1 votes

# Answer
# Ruby 2.4, 31 bytes

Hooray, TIO supports Ruby 2.4 now!

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

```

Try it online!
> 1 votes

# Answer
# Perl 6, 15 bytes

```
{$_ Z+.reverse}

```

Try it online!
> 1 votes

# Answer
# Swift, ~~76~~ ~~68~~ 58 bytes (returns an Array)

*-8 bytes thanks to @Alexander.*

```
func f(l:[Int]){print(zip(l,l.reversed()).map(+))}

```

Try it online!

---

# Swift, ~~76~~ 66 bytes

```
func f(l:[Int]){for i in 0..<l.count{print(l.reversed()[i]+l[i])}}

```

Try it online!

Prints the sums separated by a newline. For `[1,2,3]`, the output is:

```
4
4
4

```
> 1 votes

# Answer
# C# (.NET Core),65 57 bytes

-8 bytes thanks to Kevin Cruijssen

```
n=>{for(int i=0,o=n.Length;i<o/2;)n[i]=n[o-1-i]+=n[i++];}

```

Try it online!
> 1 votes

# Answer
# Python 2 + numpy, 31 bytes

I think this is kosher based on the rules, but let me know if not.

Anonymous function takes a `numpy` array as input:

```
import numpy
lambda l:l+l[::-1]

```

Try it online!
> 1 votes

# Answer
# Racket, 30 bytes

```
(lambda(l)(map +(reverse l)l))

```

Try it online!

This is simply an anonymous function that maps corresponding elements from `l` and `l` reversed to the `+` function, returning the results in a list.
> 1 votes

# Answer
# Retina, 31 bytes

```
\d+
$*1;$&$*
O$^`;1+

;

1+
$.&

```

Try it online! Explanation:

```
\d+
$*1;$&$*

```

Convert to unary and duplicate each element.

```
O$^`;1+

```

Reverse the order of the duplicate elements.

```
;

```

Add the elements to their reversed duplicates.

```
1+
$.&

```

Convert the elements back to decimal.
> 1 votes

# Answer
# x86 Machine Code (32-bit protected mode), 19 bytes

```
8D 34 B7 39 F7 73 0C 83 EE 04 8B 07 03 06 89 06 AB EB F0 C3

```

The above bytes of code define a function that takes two parameters (a pointer to the array in the `EDI` register, and the length of the array in the `ESI` register), modifies the pointed-to array to contain the "reverse array sum", and then returns. It does not return a value to the caller.

(This is a custom calling convention used to receive the arguments. It is actually the standard calling convention used on Gnu/Unix systems for x86-64 binaries, but in x86-32, arguments are typically passed on the stack. That takes more bytes to encode, and is less efficient, so we want to ensure that the arguments are passed to us in registers. As far as I understand the rules, this is completely legal. We don't need to conform to a particular standardized calling convention. Certainly, when writing assembly, the programmer is free to define her own calling conventions, unless she needs to interoperate with C code.)

Note that this function also assumes the direction flag is cleared (`DF` == 0) upon entry to the function. This is a sensible assumption, as it is guaranteed by most platform ABIs, including the Linux x86 32-bit ABI. If you need the code to work under circumstances where the state of `DF` cannot be assumed, then you need to add a 1-byte `CLD` instruction to the top of the function.

**Ungolfed assembly mnemonics:**

```
               ; void ReverseArraySum(int *pArray, int length);
8D 34 B7         lea    esi, [edi+esi*4]        ; compute back pointer
               Loop:
39 F7            cmp    edi, esi
73 0C            jae    End                     ; finished when EDI >= ESI
83 EE 04         sub    esi, 4
8B 07            mov    eax, DWORD PTR [edi]
03 06            add    eax, DWORD PTR [esi]
89 06            mov    DWORD PTR [esi], eax
AB               stosd  ; equivalent to 'mov DWORD PTR es:[edi], eax' + 'add edi, 4'
EB F0            jmp    Loop
               End:
C3               ret

```

Conceptually, the code is pretty straightforward. **We just iterate through the array using two pointers.** The first pointer is passed to us as an argument, in the register `EDI`, and it is a pointer to the beginning of the array. The second pointer is computed (initial `LEA` instruction) by adding the address of the beginning of the array to the length of the array, scaled by the size of an element in the array (4 bytes for an `int` on x86-32). Thus, `ESI` is a pointer to the *end* of the array.

At the top of the `Loop`, we check the pointers to see if we should keep looping or if we are finished. Normally, we'd want to save bytes by putting this test at the *end* of the loop (and eliminating the `JMP` you see at the end now), but we can't do that because the challenge requires us to handle an empty input array.

Inside the body of the loop, we:

* Eagerly subtract 4 bytes (the size of a single element in the array) from the back pointer, `ESI`.
* Retrieve and store the value of the element pointed to by the front pointer (`EDI`) in a temporary register (`EAX`).
* Increment `EAX` by the value of the element pointed to by the back pointer (`ESI`).
* Store the sum (`EAX`) in the element pointed to by the back pointer (`ESI`).
* Store the same sum (`EAX`) in the element pointed to by the front pointer (`EDI`), *while simultaneously* incrementing that pointer (`EDI`) by 4 bytes (the size of a single element in the array). The handy x86 string instruction `STOSD` is what allows us to do both of those things in only a single byte of code.
(With the caveat given at the outset, that the direction flag is cleared, and also the assumption that we are running in *flat* mode, where the "extra" segment (`ES`) is identical to the data segment (`DS`).)

Finally, we're done and we return to the caller, without returning any value.

\__
You can see it run on TIO, but note that the TIO link uses a C wrapper to exercise the machine code, and GCC won't necessarily respect our custom calling convention, so we have to add extra code at the top of the function to retrieve the parameters from the stack and put them into the appropriate registers.
> 1 votes

# Answer
# Common Lisp, SBCL, 33 bytes

Pretty simple solution (very similiar to Clojure one):

```
(lambda(x)(mapcar'+(reverse x)x))

```

Example of use:

```
((lambda(x)(mapcar'+(reverse x)x))'(1 2 3)))

```

Try it online!(with `print` function, to show output from function)
> 1 votes

# Answer
# MY, ~~49~~ ~~48~~ 5 bytes

```
ωω⌽+←

```

Try it online!

**How?**

First, you bang your head against the wall after remembering that addition on strings isn't commutative. Then, you bang your head yet again after realizing that you could've used `ω` to save over 40 bytes! Finally, you arrive at this:

```
ω    - First command line argument
ω⌽   - First command line argument, reversed
+    - Add (vectorizes)
←    - Output without a newline

```
> 1 votes

# Answer
# C++14, 57 bytes

As generic unnamed lambda requiring a container and returns via modifying its input:

```
[](auto&L){auto R=L;auto r=R.end();for(auto&x:L)x+=*--r;}

```

Try it online!

Ungolfed:

```
[](auto&L){
 auto R=L;      //copy of the list
 auto r=R.end();//iterator of last+1
 for(auto&x:L)  //foreach
  x+=*--r;      //move iterator to front and sum
}

```
> 1 votes

# Answer
# 8th, 22 bytes

**Code**

```
clone a:rev ' n:+ a:op

```

**SED** (Stack Effect Diagram) is: `a -- a`

**Ungolfed code with comments**

```
: f \ a -- a
  clone      \ clone array on TOS
  a:rev      \ reverse array
  ' n:+ a:op \ Add the corresponding elements of each array producing a new array
;

```

**Usage**

```
ok> [8,92] clone a:rev ' n:+ a:op .
[100,100]

```

**Test cases**

```
ok> [8,92] f .
[100,100]
ok> [1,2,3] f .
[4,4,4]
ok> [5,24,85,6] f .
[11,109,109,11]
ok> [] f .
[]
ok> [999] f .
[1998]

```
> 1 votes

# Answer
# Casio-Basic, 25 bytes

```
l+seq(l[x],x,dim(l),1,-1

```

Addition threads over lists by default - but there's no built-in for reversing a list! `seq` is used to generate the reversed list by indexing backwards through it.

24 bytes for the function, +1 byte to add `l` in the parameters box.
> 1 votes

# Answer
# ARBLE, 28 bytes

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

```

Try it online!
> 1 votes

# Answer
# Stax, 5 bytes

```
òôΩo1

```

Run and debug it

I like that sequence of `o`-style chars `(òôΩo)`.

Explanation (unpacked):

```
cr\m|+ Full program, implicit input  e.g.: [1, 2, 3]
cr     Copy and reverse                    [1, 2, 3] [3, 2, 1]
  \    Zip                                 [[1, 3], [2, 2], [3, 1]]
   m|+ Map sum of array                    [4, 4, 4]
       Implicit output

```
> 1 votes

# Answer
# Add++, 8 bytes

```
L,dbRz£+

```

Try it online!

Finally something sane with Add++

## Explained

```
L,dbRz£+
L,        ; create a lambda that:
  dbR     ; pushes the input list and its reverse
     z    ; zips those together
      £+  ; and reduces each pair by addition

```
> 1 votes

# Answer
# Pip `-p`, 4 bytes

```
g+Rg

```

Attempt This Online!

### Explanation

Just what it says on the tin.

```
   g  List of command-line arguments
  R   Reversed
g+    Add to the original list

```

(Addition operates element-wise on lists in Pip.)
> 1 votes

# Answer
# Risky, 7 bytes

```
0__2-?_+_?+_0

```

Try it online!

Appends `-?` (first input reversed) to `__` (all inputs, which is in this case a trick to wrap the input array), and then transposes. Maps with sum, which is the most complicated usage of Risky's quicks that I'm even going to attempt.
> 1 votes

# Answer
# Desmos, 22 bytes

```
f(l)=l+l[l.length...1]

```

Pretty self-explanatory

Try It On Desmos!

Try It On Desmos! - Prettified
> 1 votes

# Answer
# J-uby, 14 bytes

```
:zip%:~|:*&+:+

```

Attempt This Online!

```
:zip % :~ |           # Zip array with its reverse, then
            :* & +:+  # Map with sum

```
> 1 votes

# Answer
# Thunno 2, 2 bytes

```
r+

```

Attempt This Online!

`r` is reverse and `+` is add.
> 1 votes

# Answer
# Stacked, 7 bytes

```
[:rev+]

```

Try it online!

Just adding to the reversed.
> 0 votes

# Answer
# Tcl, 49 bytes

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

```

Try it online!
> 0 votes

# Answer
# Pari/GP, 14 bytes

```
a->a+Vecrev(a)

```

Try it online!
> 0 votes

# Answer
# Scala, 49 bytes

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

```

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

### Implementation notes:

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

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

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

```

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

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

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

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

# Answer
# R: 19 bytes

function(v)rev(v)+v

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

# Answer
# Clojure, 21 bytes

```
#(map + %(reverse %))

```

Try it online!

Having trouble golfing this any further. Any clever ideas?
> 0 votes

# Answer
# Husk, 4 bytes

```
Sz+↔

```

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

### Ungolfed/Explanation

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

```
> 0 votes

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

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

```

Try it online!
> 0 votes

# Answer
# Uiua, 3 bytes

```
+⇌.

```

Try it!

```
+⇌.
  .  # duplicate
 ⇌   # reverse
+    # add

```
> 0 votes

# Answer
# J, 5 bytes

```
(+|.)

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

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

```
> -2 votes

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


# Question
Title: Find the largest and the smallest number in an array
### The Task

The task is very simple. Given an array containing **only integers** and **strings**, output the largest number and the smallest number.

### Test Cases

```
Input: [1, 2, 3, 4, 5, 6, 7, 8]
Output: 1, 8

Input: [5, 4, 2, 9, 1, 10, 5]
Output: 1, 10

Input: [7, 8, 10, "Hello", 5, 5]
Output: 5, 10

```

Numbers in strings are not considered integers:

```
Input: [1, 2, 3, 4, "5"]
Output: 1, 4

```

If there is only one integer, it is both the largest and smallest integer:

```
Input: [1]
Output: 1, 1

Input: ["1", "2", "3", "4", 5]
Output: 5, 5

```

### Rules

* You can assume that an array will **always** contains at least one integer.
* All integers are positive (greater than 0)
* The order of the output doesn't matter.
* This is , so the submission with the least amount of bytes wins!
* Strings can contain all printable ASCII characters (`32 - 126`) and are non-empty.

# Answer
> 9 votes
## Seriously, ~~9~~ 6 bytes

```
,ì;M@m

```

Try It Online

### How it works

```
,                              Read list input
 ì                             Remove everything but numbers from it
  ;                            Make a copy
   m                           Extract its min value
    @M                         Extract the other one's max value
                               Implicit output (max then min)

```

# Answer
> 11 votes
# JavaScript (ES6), 54 ~~56~~

**Edit** 2 bytes saved thx @Neil

Note: `x===+x` is true if and only if `x` is a number

```
a=>[Math.max(...a=a.filter(x=>x===+x)),Math.min(...a)]

```

# Answer
> 8 votes
# Pyth, ~~14~~ ~~11~~ 10 bytes

```
hM_BS^I#1Q

```

Try it online. Test suite.

### Explanation

* `Q`: evaluated input
* `#`: filter that on:
    + `I`: the value being the same after:
        - `^…1` raising it to power 1
* `S`: sort that
* `_B`: create array `[previous, reversed(previous)]`
* `hM`: take first item of each item of that

The hardest part is to golf the removal of strings, which currently takes 4 bytes. The current approach works due to `^<str>1` taking the first Cartesian power of the sequence (basically, the list of the string's characters), but `^<int>1` is just the identity function.

# Answer
> 8 votes
# Python 2, 42 bytes

In Python 2, integers are always less than strings during comparisons, so a simple `min(s)` will find the smallest integer. When finding the maximum though, we must filter out strings first. The anonymous function accepts a sequence and returns a tuple with the minimum and maximum.

```
lambda s:(min(s),max(x for x in s if''>x))

```

Example:

```
[1,'77', 6, '', 4] -> (1, 6)

```

# Answer
> 8 votes
# Jelly, 8 bytes

```
|f¹Ṣ0,1ị

```

Try it online!

### Background

In a perfect world, it would suffice to intersect the list with a flattened version of itself. Strings are simply lists of characters in Jelly, so while the original list would contain integers and strings, the flattened version would contain integers and characters, leaving only the integers in the intersection.

In the real world, both the parsers of both input and string literals yield *characters* instead of strings of length 1. The only way to pass a singleton string to a function would be to encode it "manually" as, e.g., `[”a]`, which is a character wrapped in an array.

This would save a byte, for a total of **7 bytes** (Try it online!).

```
fFṢ0,1ị

```

Since that's probably not acceptable, we also need a way to differentiate characters from integers.

Jelly's bitwise atoms ~~desperately~~ try to convert their arguments to integers. They start by vectorizing until they encounter types of depth 0 (numbers or characters), then attempt to convert them to integers. For a character that represents an integer, this will be successful. For others, a dyadic, bitwise atom will simply give up and return **0**.

For example, bitwise ORing the list `[1, "2", "34", "-5", "a", "bc"]` with itself will yield

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

```

By intersecting the result with the original list, we get rid of the arrays and the integers that weren't present in the original list.

### How it works

```
|f¹Ṣ0,1ị  Main link. Input: A (list)

|         Bitwise OR the list A with itself.
 f¹       Filter the result by presence in A.
   Ṣ      Sort the resulting list of integers.
    0,1ị  Retrieve the elements at those indexes.
          Indices are 1-based and modular in Jelly, so 0 is the last (maximum),
          and 1 is the first (minimum).

```

# Answer
> 7 votes
# Ruby, ~~57~~ ~~36~~ 29 bytes

Newbie here, so I don't know if there is any standard or universally accepted place/way to calculate bytes used, any help would be very appreciated!

*Edited as per manatwork & Doorknob's comment!*

```
->n{(n.map(&:to_i)&n).minmax}

```

**Test**

```
2.3.0 :076 > f=->n{[(n.map(&:to_i) & n).min, (n.map(&:to_i) & n).max]}
 => #<Proc:0x007ff7650ee868@(irb):76 (lambda)>
2.3.0 :077 > f[[7, 8, 10, "Hello", 5, 5]]
 => [5, 10]

```

# Answer
> 6 votes
# Mathematica, 20 bytes

```
MinMax@*Select[#>0&]

```

---

**Test cases**

```
MinMax@*Select[#>0&]@{1,2,3,4,"5"}
(* {1,4} *)

```

# Answer
> 5 votes
## CJam, ~~15~~ 13 bytes

```
{_:z&$2*_,(%}

```

An unnamed block (function) which expects the input array on the stack and leaves the output array in its place.

Run all test cases.

### Explanation

```
_     e# Duplicate.
:z    e# Map over list: a) take abs() of integer elements (a no-op) or b) wrap strings
      e# in an array.
&     e# Set intersection: only the integers will appear in both arrays.
$     e# Sort.
2*    e# Repeat array twice (to make the code work with single-integer input).
_,    e# Duplicate, get length N.
(%    e# Decrement, get every (N-1)th element, i.e. the first and the last.

```

# Answer
> 5 votes
# jq, 21 characters

```
[.[]|numbers]|min,max

```

Sample run:

```
bash-4.3$ bin/jq '[.[]|numbers]|min,max' <<< '[7, 8, 10, "Hello", 5, 5]'
5
10

```

On-line test:

# Answer
> 5 votes
## Haskell, ~~41~~ 39 bytes

```
f x=[minimum,maximum]<*>[[i|Left i<-x]]

```

In Haskell all elements of a list have to be of the same type, so I cannot mix `Integer` and `String`. However, there's the `Either` type for combining two types into a single one. The input list is therefore of type `Either Integer String`1. `f` filters the Integers, removes the `Either` wrapper, puts the list as the single element in a new list (e.g. `[[1,2,3]]`), so that `<*>` can apply the functions given in the first argument to it.

Usage example: `f [Left 1, Left 3, Right "Hello", Left 2]` -\> `[1,3]`.

Edit: @xnor brought `<*>` into play and saved 2 bytes. Thanks!

---

1 actually it's fully polymorphic in the second type as the `String` property is never used.

# Answer
> 4 votes
# Mathematica, 28 bytes

```
MinMax[#/._String->Nothing]&

```

# Answer
> 4 votes
# PHP, ~~50~~ 48 bytes

```
<?=min($a=array_filter($a,is_int)).', '.max($a);

```

# Answer
> 4 votes
## Perl ~~44~~ 39 + 3 = 41 bytes

```
@a=sort{$a-$b}grep!/"/,@F;$_="@a[0,-1]"

```

Requires `-pa` flags:

```
$ perl -pae'@a=sort{$a-$b}grep!/"/,@F;$_="@a[0,-1]"' <<< '1 2 3 5 4'
1 5
$ perl -pae'@a=sort{$a-$b}grep!/"/,@F;$_="@a[0,-1]"' <<< '1 2 3 4 "5"'
1 4

```

Thanks to @manatwork for shaving off a few bytes

# Answer
> 4 votes
# Retina, 71

Thanks (as always) to @MartinBüttner for the golfing help.

Not competitive golf-wise, but its interesting to implement integer bubble sorting in Retina.

Assumes all strings in the input are `"` double-quoted and don't contain any escaped double quotes `\"`.

```
A`"
¶

\d+
$&$*a $&$*a
+`\b(a+) +\1(a+)\b
$1$2 $1
 +[a ]+ +

(a)+
$#1

```

Input is newline-separated.

Try it online.

# Answer
> 4 votes
## *Mathematica*, 14

```
#&@@@MinMax@#&

```

Example:

```
tests = {
   {1, 2, 3, 4, 5, 6, 7, 8},
   {5, 4, 2, 9, 1, 10, 5},
   {7, 8, 10, "Hello", 5, 5},
   {1, 2, 3, 4, "5"},
   {1},
   {"1", "2", "3", "4", 5}
 };

# & @@@ MinMax@# & /@ tests

```

> ```
> {{1, 8}, {1, 10}, {5, 10}, {1, 4}, {1, 1}, {5, 5}}
>
> ```

Explanation:

When `MinMax` gets non-numeric input it reduces the problem as far as it can, then leaves terms wrapped in `Min` and `Max`:

```
MinMax @ {7, 8, 10, "Hello", 5, 5}

```

> ```
> {Min[5, "Hello"], Max[10, "Hello"]}
>
> ```

Due to the automatic ordering that takes place strings follow integers.

`Apply` at *levelspec* {1}, shorthand `@@@`, is then used to pull the first argument of non-atomic elements. Note that `5` is untouched here:

```
foo @@@ {5, Max[10, "Hello"]}

```

> ```
> {5, foo[10, "Hello"]}
>
> ```

# Answer
> 3 votes
# MATL, 23 bytes

```
"@Y:tX%1)2\?x]N$htX<wX>

```

**Try it online!**

```
"       % implicitly input cell array. For loop that iterates on each cell
  @     %   push each cell
  Y:    %   cell's contents (either a number or a string)
  tX%   %   duplicate and push class. This will produce 'char'  or 'double'
  1)    %   get first letter: either 'c' or 'd'
  2\    %   is its ASCII code odd?
  ?     %   if so...
    x   %     delete (it's a string)
  ]     %   end if
  N$h   %   concatenate all stack into an array. This array will contain up to
        %   three numbers: minimum up to now, maximum up to now, new value (if any)
  tX<   %   duplicate. Push minimum
  wX>   %   swap. Push maximum.
        % implicitly end for
        % implicitly display stack contents

```

# Answer
> 3 votes
# Oracle SQL 11.2, 189 bytes

```
SELECT MIN(TO_NUMBER(i)),MAX(TO_NUMBER(i))FROM(SELECT REGEXP_SUBSTR(:1,'[^,]+',1,LEVEL)i FROM DUAL CONNECT BY LEVEL<REGEXP_COUNT(:1,',')+2)WHERE TRIM(TRANSLATE(i,' 0123456789',' '))IS NULL;

```

Un-golfed

```
SELECT MIN(TO_NUMBER(i)),MAX(TO_NUMBER(i))
FROM  (
        SELECT REGEXP_SUBSTR(:1,'[^,]+',1,LEVEL)i
        FROM   DUAL
        CONNECT BY LEVEL<REGEXP_COUNT(:1,',')+2
      )
WHERE TRIM(TRANSLATE(i,' 0123456789',' '))IS NULL;

```

The sub-query parse the array and split it to populate a view with one element per row. Then the non numeric elements are filtered out.

I wish I could have found a way to do it with LEAST and GREATEST, but no luck with how to handle the array as a parameter.

# Answer
> 3 votes
## vimscript, 25 bytes

```
g/"/d
sort n
t.
t.
2,$-1d

```

Yep, that's right, vimscript.

Expects input in the form

```
1
2
3
4
"5"

```

And outputs in the form

```
1
4

```

Explanation:

```
g/"/d    delete all lines that contain quotes
sort n   sort numerically
t.       duplicate the first line
t.       duplicate it again
2,$-1d   delete from line 2 to line (END-1)

```

The first line needs to be duplicated *twice* to handle the edge case of an input of a single number. This is because the last command will complain if there are only two lines when it is reached, since it ends up being `2,1d` which is a backwards range.

# Answer
> 3 votes
## Bash, ~~40~~ ~~31~~ 30 bytes

```
sort -n|sed /\"/d|sed '1p;$p;d'

```

Requires a line separated list:

```
$ echo $'5\n4\n2\n9\n1\n"10"\n5' | sort -n|sed /\"/d|sed '1p;$p;d'
1
9

```

Thanks to @manatwork to shave off a few bytes

# Answer
> 3 votes
## PowerShell, ~~53~~ 36 bytes

```
@($args[0]|?{$_-is[int]}|sort)[0,-1]

```

Saved 17 bytes thanks to @goric

***OOOF*** ... PowerShell usually plays pretty fast and loose with casting, which is normally a good thing for golfing, but hurts it here.

Takes our input `$args[0]` and pipes it into a `Where-Object` statement (the `?`) that will only select integers and passes them along the pipeline, discarding anything else. Since dynamic re-casting happens on-the-fly in the background for you (e.g., `1+"5"` returning `6` is perfectly valid PowerShell), we need to use the `-is` operator in order to differentiate between the data types.

From there, we pipe that collection into `Sort-Object`, which will sort the integers from smallest to largest. The outer `()` is necessary so we can reference the first and last elements with `[0,-1]` (i.e., the smallest and the largest), but note we also need the outer `@` to force casting the output of `sort` as an array if there's only one object (as the result of the `?`, or only one object was input).

# Answer
> 3 votes
# Julia, 35 bytes

```
x->extrema(filter(i->isa(i,Int),x))

```

This is a lambda function that accepts an array and returns a tuple of integers. To call it, assign it to a variable.

Julia has a built-in function `extrema` for getting the minimum and maximum elements of an array as a tuple. However, since the array can also have strings in it, we first have to filter those out. We can do that by testing whether each element is an integer using `isa`.

# Answer
> 3 votes
# Japt, 23 bytes

```
[V=Uf_bZÃn@X-Y})g Vw g]

```

Test it online!

### How it works

```
[V=Uf_  bZÃ n@  X-Y})g Vw g]
[V=UfZ{ZbZ} nXY{X-Y})g Vw g]

UfZ{ZbZ}   // Filter out the items Z in U where Z.b(Z) is falsy.
           // For numbers, this the original number, which is always non-0 (non-falsy).
           // For strings, this returns Z.indexOf(Z), which is always 0 (falsy).
nXY{X-Y}   // Sort by subtraction. Small items move to the front, large to the back.
V=         // Set variable V to the resulting array.
)g Vw g    // Take the first item in V, and the first in V.reverse().
[       ]  // Wrap them in an array so both are sent to output.

```

# Answer
> 3 votes
# Python 3, 56 bytes

```
lambda x:[m(t for t in x if str(t)!=t)for m in(min,max)]

```

Try it online on Ideone.

# Answer
> 2 votes
# JavaScript (ES5), 105 bytes

```
function a(b){m=Math;b=b.filter(function(c){return c===+c});alert(m.min.apply(m,b)+','+m.max.apply(m,b))}

```

Usage: `a([1,2,3,'4'])`

Just trying :)

"Ungolfed":

```
function a(b){
  m=Math;
  b=b.filter(function(c){
    return c===+c
  });
  alert(m.min.apply(m,b) + ',' + m.max.apply(m,b))
}

```

# Answer
> 2 votes
# Pyth, 11 bytes

```
hJSf!>TkQeJ

```

Explanation:

```
   f    Q   - filter([V for T in >], Q)
    !>Tk    - not(T>"")
  S         - sorted(^)
hJ       eJ - print first and last element

```

Try it here!

# Answer
> 2 votes
# Perl 6, 25 bytes

The obvious answer would be this WhateverCode lambda

```
*.grep(Int).minmax.bounds

```

---

If it has to be a full program

```
put get.words».&val.grep(Int).minmax.bounds

```

The input to this full program is a space separated list of values

---

### Usage

```
# give it a lexical name
my &code = *.grep(Int).minmax.bounds;

say code [1, 2, 3, 4, 5, 6, 7, 8];  # (1 8)
say code [5, 4, 2, 9, 1, 10, 5];    # (1 10)
say code [7, 8, 10, "Hello", 5, 5]; # (5 10)
say code [1, 2, 3, 4, "5"];         # (1 4)
say code [1];                       # (1 1)
say code ["1", "2", "3", "4", 5];   # (5 5)

say code []; # (Inf -Inf)

```

# Answer
> 2 votes
# , 16 chars / 20 bytes

```
[МƲ(ï⇔⒡≔=+$⸩,МƵï

```

`Try it here (Firefox only).`

Not bad, not bad...

# Explanation

This outputs an array containing both the maximum and minimum. `(ï⇔⒡≔=+$⸩,` basically filters out all strings in the input, `МƲ` gets the maximum in the input, and `МƵ` gets the minimum.

Just a note: this is the first challenge where I get to use , which basically turns `ï⇔` into `ï=ï`.

# Answer
> 2 votes
# PARI/GP, 52 bytes

This is terrible -- there has to be a better way to check if something is a number than `type`. `polcoeff(eval(x),0)` is even worse, despite (ab)using the requirement that numbers are positive. `iferr(O(x);1,E,0)` is clever but a byte longer: `E` is required for some reason, and *p*-adic numbers like `O(3)` are falsy (i.e., `O(3)==0`) so the `;1` is needed.

```
v->v=[x|x<-v,type(x)=="t_INT"];[vecmin(v),vecmax(v)]

```

An alternate approach is just as long:

```
v->[f([x|x<-v,type(x)=="t_INT"])|f<-[vecmin,vecmax]]

```

# Answer
> 2 votes
# Java (OpenJDK 8), 124 bytes

```
a->{int s[]={0,0},t;for(Object i:a)try{t=(int)i;s[0]=s[0]<1|t<s[0]?t:s[0];s[1]=s[1]<t?t:s[1];}catch(Exception e){}return s;}

```

Try it online!

Java 8 lambda function, takes array as input and gives out array `{min, max}`. Non competing, because the input has to be an integer array.

Fixed and -1 byte thanks to Kevin Cruijssen

# Answer
> 2 votes
# APL (Dyalog), 13 bytes

```
(⌊/,⌈/)⎕AV~⍨∊

```

Try it online!

enlist (flatten – this makes all the strings into characters in the big list)

`⎕AV~⍨` remove all characters in the **A**tomic **V**ector (the character set – leaves numbers)

`(``)` apply the following tacit function:

`⌊/` the minimum across

`,` appended to

`⌈/` the maximus across

# Answer
> 1 votes
# Jolf, 20 bytes

I can probably golf this... I need to implement type-checking shorter solutions.

```
γ fxd='nF~tH0ͺZkγZKγ
 _fx                 filter the input
    d='nF~tH0        checking for number type
γ                    call that "γ"
             ͺ       pair
              ZkγZKγ  the min and max of the array

```

# Answer
> 1 votes
## Python 3, 65 bytes

Here's the obligatory example of how Python 3 is worse (for golfing) than Python 2, because it *got rid of* weird behaviours, like "you can compare ints and strings, and all ints are less than all strings".

```
def m(a):b=sorted(n for n in a if type(n)==int);return b[0],b[-1]

```

# Answer
> 1 votes
# C#, 71 bytes

```
(object[]z)=>{var a=z.OfType<int>();return new int[]{a.Max(),a.Min()};};

```

Simple lambda which returns the min and max as an int array.

# Answer
> 1 votes
## Hoon, ~~90~~ 84 bytes

```
|*
*
=+
(sort (skip ((list @) +<) (curr test 0)) lte)
[(snag 0 -) (snag 0 (flop -))]

```

This uses a couple fun features of Hoon:

* I'm returning a wet gate instead of a dry one to prevent having to specify the type. This makes the caller typecheck the function instead of definition, which is perfectly fine.
* The function argument for `|=` is an unnamed arm, which is placed in the subject at `+<`. Specifying `a/*` and using `a` as the input is longer than just leaving it unnamed and using `+<` directly
* The same thing applies for `=+` \- it places the variable at the top of the subject at `-`, so I save the sorted list as an intermediate and can reference it the three times needed cheaply
* The input specifies "All integers are positive (greater than 0)", which along with the fact the string will never be empty helps immensely. I can then slam the input through the type verifier gate `(list @)`, which converts all entries in the list that aren't a number into `0` and then get rid of all zeros.

Example of use:

```
> %.  (limo ~[1 2 "hello" 9 17])
      |*
      *
      =+
      (sort (skip ((list @) +<) (curr test 0)) lte)
      [(snag 0 -) (snag 0 (flop -))]
[1 17]

```

# Answer
> 1 votes
# C++20 (gcc) `std::variant` array, ~~139~~ ~~129~~ ~~127~~ ~~126~~ ~~125~~ 124 bytes

```
#import<variant>
int f(auto a,int n,int&m,int&M){for(m=~0u/2,M=0;n--;)if(int*p=std::get_if<int>(a++))*p>m?:m=*p,*p<M?:M=*p;}

```

Try it online!

## Explanation

This uses C++20's **abbreviated function templates** (cppref) which allow me to just put `auto` as a parameter instead of using the full name or a `template<class T>` declaration. It is wonderful.

The effective ungolfed signature is this if it wasn't a template:

```
void f(std::variant<int, char *> *array, int n_elements, int &min, int &max);

```

Note that the second type can be literally anything. In the test, I did `const char *` because C++ string literals are `const char *`.

The input is an `array` of `std::variant<int, char *>` (cppref) of `n_elements` elements, and the output is stored into `min` and `max` which are `int` references.

It then uses `std::get_if<int>` (cppref) to select only the `int`s in the array, and calculates the min and max as normal.

It also uses the `x?:y` extension from GCC which allows me to omit the middle of the ternary to calculate the min/max, as well as cheating a byte because GCC reluctantly allows `#import` in C++ as a deprecated extension from Objective-C, and trading a warning for a byte by using `int` as the return type without returning `int`

An equivalent C++17-compatible version would be this at ~~158~~ ~~153~~ ~~143~~ ~~141~~ ~~140~~ ~~139~~ 138 bytes:

```
#import<variant>
template<class T>int f(T a,int n,int&m,int&M){for(m=~0u/2,M=0;n--;)if(int*p=std::get_if<int>(a++))*p>m?:m=*p,*p<M?:M=*p;}

```

Ungolfed version:

```
#include <variant>

void f(std::variant<int, const char *> *array, int n_elements, int &min, int &max)
{
    // Set min to INT_MAX and max to 0
    // C++20 guarantees 2's complement, so this is guaranteed to work
    min = ~0u/2;
    max = 0;
    // Loop through each element
    while (n_elements--) {
        // std::get_if returns a pointer to the element if it is an int, or nullptr.
        if (int *p = std::get_if<int>(array++)) {
             // if (*p > min) {} else { min = *p; }
             *p > min ?: min = *p;
             // if (*p < max) {} else { max = *p; }
             *p < max ?: max = *p;
        }
    }
}

```

# Answer
> 1 votes
# K (ngn/k), 19 bytes

```
(&/;|/)@\:(`i=@:')#

```

Try it online!

* `(`i=@:')#` filter input to only integers
* `(&/;|/)@\:` apply min (`&/`) and max (`|/`), returning a list

# Answer
> 1 votes
# Ruby, 27 bytes

```
->a{a.grep(Integer).minmax}

```

Try it online!

*Slightly different from the previous Ruby answer! The user seems to be inactive for a while, so I thought of posting it.*

# Answer
> 1 votes
# Vyxal, 6 bytes

```
0+∩₍gG  # main program

```

```
0+      # add 0 to each element of input if number, else append 0
  ∩     # take the set intersection
   ₍    # apply the following two operations on top of stack and wrap
    gG  # min and max
        # implicit output

```

It may be possible to take this down a byte if there is a command that only affects strings but not numbers. I couldn't find one after some basic searching, but its possible a single command exists that does that.

Try it Online!

# Answer
> 1 votes
# Factor, 27 bytes

```
[ [ real? ] filter minmax ]

```

Try it online!

Integers are `object`s, `real`s, and `integer`s in Factor, so we can save a few bytes by using the shortest class predicate word to filter out the strings.

# Answer
> 1 votes
# Zsh (builtins only), 35 bytes

```
A=(${(n)@//[A-z]});<<<$A[1]\ $A[-1]

```

Try it online!

# Answer
> 1 votes
# Japt, 11 bytes

```
'm¬iÔm!rUfâ

```

Try it

# Answer
> 1 votes
# Thunno `D` `E`, \\$3 \log\_{256}(96) \approx\\$ 2.47 bytes

```
zni

```

Attempt This Online! Output as `[max, min]`

Verify some more test cases:

**Explanation:**

```
     # Example input: 1, 2, 3, 4, "5"
     # The E flag tells the interpreter not to evaluate the input strings,
     # so they end up as "1", "2", "3", "4", '"5"'
     # The D flag duplicates the input. The zn command will automatically pop the top item.
     # We want to keep all the items on the stack, so we need the D flag
zn   # Push [max, min]. As the top item is not a list, it applies it to the stack,
     # converting each to a float. It can't convert '"5"', so it just ignores it.
  i  # Convert each to an integer (as the zn command converted to float)

```

# Answer
> 0 votes
# Jelly, 6 bytes

```
OƑƇṢ.ị

```

Try it online!

Yields `[max, min]`

## How it works

```
OƑƇṢ.ị - Main link. Takes  a list L on the left
  Ƈ    - Filter keep:
 Ƒ     -   Invariant under:
O      -     Converting to ordinals
         This filters non-integers from the list, as O has no effect on integers
   Ṣ   - Sort
    .ị - First and last elements

```

# Answer
> 0 votes
# Python 3, 54 bytes

Another Python solution: the mandatory solution using `lambda` was missing :)

```
lambda y:[f(e for e in y if e*0==0)for f in (min,max)]

```

Try it online!

-10 bytes thanks to aeh5040

# Answer
> 0 votes
# , 45 bytes

```
function(l)range(unlist(Filter(is.double,l)))

```

Try it online!

Takes input as a `list`, as R vectors (`c()`) will coerce everything to the same type, in this case, `character` if they are there.

`Filter`s out non-numeric values, then uses `range` to find the max and min values.

# Answer
> 0 votes
# Brachylog, 7 bytes

```
ℕˢ⟨⌋≡⌉⟩

```

Try it online!

### Explanation

```
 ˢ      Select the elements of the input list which...
ℕ       ...are integers >= 0
  ⟨   ⟩  Make a list containing...
   ⌋     ...the minimum element...
     ⌉   ...and the maximum element...
    ≡   ...and return it unchanged

```

# Answer
> 0 votes
# Japt, 11 bytes

```
kÈ¶sÃÍg[TJ]

```

Try it

```
kÈ¶sÃÍg[TJ]     :Implicit input of array
k               :Remove elements that return true
 È              :When passed through the following function as X
  ¶             :  Is strictly equal to
   s            :  X converted to a string
    Ã           :End remove
     Í          :Sort
      g         :Get elements at 0-based indices
       [TJ]     :  0 and -1 (last)

```

# Answer
> 0 votes
# Arturo, ~~38~~ 37 bytes

```
$[a][filter'a=>string?@[min a max a]]

```

Try it

# Answer
> 0 votes
# JavaScript, 53 bytes

Based on edc65's this answer. We can save 1 byte if check `!x[0]` instead of `x===+x`

```
a=>[Math.max(...a=a.filter(x=>!x[0])),Math.min(...a)]

```

```
f=a=>[Math.max(...a=a.filter(x=>!x[0])),Math.min(...a)]

;[
    [1, 2, 3, 4, 5, 6, 7, 8],    // [8, 1]
    [5, 4, 2, 9, 1, 10, 5],      // [10, 1]
    [7, 8, 10, "Hello", 5, 5],   // [10, 5]
    [1, 2, 3, 4, "5"],           // [4, 1]
    [1],                         // [1, 1]
    ["1", "2", "3", "4", 5],     // [5, 5]
].map(a => console.log(JSON.stringify(f(a))))
```

# Answer
> 0 votes
# Uiua, 17 bytes

```
∩⊔⊃/↥/↧▽¬∵'type⊔.

```

Try it!

```
∩⊔⊃/↥/↧▽¬∵'type⊔.
                .  # duplicate
         ∵'type⊔   # mask of types (0 for int, 1 for string)
        ¬          # not
       ▽           # keep
  ⊃/↥/↧            # min and max
∩⊔                 # unbox both (need this for one-int arrays)

```

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


title: Damerau-Damerau distance

text:
# Question
Title: Damerau-Damerau distance
Given a list of the integers from \\$1\\$ to some \\$n\\$, give the minimum number of adjacent swaps required to put the list in ascending order.

You will receive a list as input and should output a non-negative integer. You may if you wish choose to expect a list of the integers from \\$0\\$ to \\$n\\$ instead.

This is so the goal is to minimize the size of your source code as measured in bytes.

## Test cases

```
[3,2,1] -> 3
[1,2,3,4] -> 0
[2,1,3,4] -> 1
[2,1,4,3] -> 2
[2,4,1,3] -> 3
[4,2,3,1] -> 5
[4,3,2,1] -> 6

```

# Answer
# MATL, ~~5~~ 4 bytes

-20% thanks to Luis Mendo!

```
&<Rz

```

Try it online! or Verify all cases!

As long as the list is not sorted, there is always an adjacent pair that is out of order. Swapping this pair yields an optimal strategy as:

* this swap reduces the number of any pairs that are out of order (not just adjacent) by one.
* no swap can remove two of those pairs.
* the list is sorted when there are no such pairs left.

This means counting the number of unordered pairs gets us the minimum number of swaps to sort:

`&<` less-than table
`R` upper triangular matrix
`z` count the non-zero elements
> 12 votes

# Answer
# Factor \+ `koszul`, 10 bytes

```
inversions

```

Try it online!
> 8 votes

# Answer
# , 38 bytes

```
function(x)sum(combn(c(0,x),2,diff)<0)

```

Try it online!

Adaptation of ovs's answer. Test harness taken from Dominic van Essen's answer.

`combn(x,m)` in R generates all size `m` combinations of the elements of `x`1, and has an optional `FUN` argument which it applies to each of those combinations. As luck would have it, it's implemented in such a way as to maintain the order of elements in `x` in each of those combinations; for `x=c(3,1,4,2)`:

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

```

Using `FUN=diff` results in a vector which contains the upper-triangular part of the matrix of comparisons:

```
[1] -2  1 -1  3  1 -2
```

These are negative precisely where there is a swapped pair, so count the negatives.

Unfortunately, R will throw an error for `combn(1,2)` since it can't get a combination of 2 out of a single value, so `0` is prepended. This has no impact (since the `diff` will always be positive), and neatly fixes that edge case.

---

1 If `x` is a single numeric, it instead uses `seq_len(n)` which will be `1:floor(n)` for `n>=1` and an empty vector otherwise. R functions sometimes have weird special cases for length-one inputs.
> 7 votes

# Answer
# Curry (PAKCS), 35 bytes

```
f(h:t)=length[1|c<-t,c<h]+f t
f[]=0

```

Try it online!

A port of ovs' MATL answer.
> 6 votes

# Answer
# Jelly, 6 bytes

```
Œ¿’Æ!S

```

A monadic Link that accepts the shuffled list of \\$\[1,n\]\\$ and yields the swap count.

**Try it online!**

### How?

```
Œ¿’Æ!S - Link: list of [1,n] in some order, L
Œ¿     - 1-indexed index of L in a sorted list of all permutations of L
  ’    - decrement -> same but 0-indexed
   Æ!  - convert to factorial number system (mixed-radix base using ..., 2!, 1!, 0!)
     S - sum

```

---

I *think* that the method employed by ovs is also six, but perhaps there is a five or better out there. For example:

```
Œc>/€S

```

or (counting swapping from the other end):

```
<";\FS

```

or

```
>Ṫ$ƤFS

```
> 3 votes

# Answer
# , 46 bytes

```
function(x)sum(upper.tri(a<-outer(x,x,`>`))*a)

```

Try it online!

Uses ovs' approach: upvote that!
> 3 votes

# Answer
# Nekomata \+ `-n`, 3 bytes

```
Sđ>

```

Attempt This Online!

A port of the @ovs's MATL answer.

```
Sđ>
S     Find a subset of the input that
 đ    has exactly two elements where
  >   the first is greater than the second.

```

`-n` counts the number of solutions.
> 3 votes

# Answer
# Python 3, 69 bytes

port of ovs' MATL answer

```
lambda n:sum(a>b for a,b in combinations(n,2))
from itertools import*

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 6 bytes

```
δ›Åu˜O

```

Port of *@ovs*' MATL answer, so make sure to upvote him as well!

First time I'm using the triangle of a matrix builtin in 05AB1E. :) The `›Åu` could alternatively be `‹Ål` for the same byte-count.

Try it online or verify all test cases.

**Explanation:**

```
δ       # Apply double-vectorized, implicitly using the input-list twice:
 ›      #  Check if the first value is larger than the second
        # (this basically creates a larger-than table)
        #  e.g. [2,4,1,3] → [[0,0,1,0],[1,0,1,1],[0,0,0,0],[1,0,1,0]]
  Åu    # Pop and leave the upper triangle of this matrix
        #  → [[0,0,1,0],[0,1,1],[0,0],[0]]
    ˜   # Flatten it to a list
        #  → [0,0,1,0,0,1,1,0,0,0]
     O  # Sum it
        #  → 3
        # (which is output implicitly as result)

```
> 2 votes

# Answer
# Python, 47 bytes (@dingledooper)

```
f=lambda P,*s:s>()and sum(P>Q for Q in s)+f(*s)
```

Attempt This Online!

#### Old Python, 48 bytes

```
f=lambda P,*s:sum(map(P.__gt__,s),*s and[f(*s)])
```

Attempt This Online!

Takes the splatted input and returns the inversion number.

Just like @ovs's answer this directly computes the inversion number. It uses recurrence through the optional initial value to the `sum` function.

This appears to be quite similar to @arnauld's approach (going by comments as I don't read JS).
> 2 votes

# Answer
# APL+WIN, 25 bytes

Prompts for vector of integers

```
+/>/n[⊃(,n∘.<n)/,n∘.,n←⎕]

```

Try it online! Thanks to Dyalog APL Classic
> 1 votes

# Answer
# JavaScript (ES6), 42 bytes

This is based on ovs' insight.

```
f=([x,...a])=>x&&a.map(y=>n+=y<x,n=f(a))|n

```

Try it online!

### Commented

```
f = (         // f is a recursive function taking:
  [x,         //   x = next value from the input list
      ...a]   //   a[] = remaining values
) =>          //
x &&          // abort if x is undefined
a.map(y =>    // otherwise, for each value y in a[]:
  n += y < x, //   increment n if y is less than x
  n = f(a)    //   initialize n to the result of a recursive call
)             // end of map()
| n           // return n (coerced to 0 if undefined)

```
> 1 votes

# Answer
# C (gcc), 61 bytes

```
c;i;f(a,n)int*a;{for(c=0;n--;)for(i=n;i--;)c+=a[n]<a[i];i=c;}

```

Try it online!

Inputs a pointer to an array of integers and its length (because pointers in C carry no length info).
Returns the minimum number of adjacent swaps required to put the list in ascending order.

Uses ovs's idea from his MATL answer.
> 1 votes

# Answer
# Charcoal, 12 bytes

```
ＩΣＥθＬΦ…θκ›λι

```

Try it online! Link is to verbose version of code. Explanation: Being a competent call change conductor, I already how many adjacent swaps I would need to get back to rounds (all bells in ascending order) from any given change (permutation), which is basically the same algorithm everyone else is using anyway.

```
   θ            Input array
  Ｅ             Map over values
       θ        Input array
      …         Truncated to length
        κ       Current index
     Φ          Filtered where
          λ     Inner value
         ›      Is greater than
           ι    Outer value
    Ｌ           Take the length
 Σ               Take the sum
Ｉ                Cast to string
                 Implicitly print

```
> 1 votes

# Answer
# PARI/GP, 35 bytes

```
a->sum(i=1,#a,sum(j=1,i,a[i]<a[j]))
```

Attempt This Online!

A port of ovs' MATL answer.
> 1 votes

# Answer
# Retina 0.8.2, 33 bytes

```
\d+
$*
+`(1+(1+)#*),\2\b
$2,$1#
#

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert to unary.

```
(1+(1+)#*),\2\b
$2,$1#

```

Swap two adjacent numbers if the first is bigger, and mark that a swap took place.

```
+`

```

Make as many swaps as possible.

```
#

```

Count the number of swaps.
> 1 votes

# Answer
# Arturo, 36 bytes

```
$=>[combine.by:2&|enumerate=>[<do&]]

```

Try it

```
$=>[               ; a function
    combine.by:2&  ; get all pair combinations in input
    |              ; then
    enumerate=>[   ; count how many pairs
        <do&       ; are unsorted
    ]              ; end enumerate
]                  ; end function

```
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~52~~ 43 bytes

saved 9 bytes thanks to the comment of @att.

Modified from @alephalpha's answer

---

Try it online!

```
Sum[Boole[#[[0;]]<#[[j]]],{,Tr[1^#]},{j,}]&

```

---

**In this problem, you need to calculate the inversion number of a permutation.**
> 1 votes

# Answer
# Pyt, 12 bytes

```
Đɐ>ĐŁřĐɐ≤*ƑƩ

```

Try it online!

```
Đ                  implicit input; Đuplicate
 ɐ>                for ɐll possible pairs, is the first element greater than the second?
   Đ               Đuplicate
    Ł              get Łength
     ř             řangify
      Đ            Đuplicate
       ɐ≤          for ɐll possible pairs, is the first element less than or equal to the second?
         *         element-wise multiplication
          Ƒ        Ƒlatten
           Ʃ       Ʃum; implicit print

```
> 1 votes

# Answer
# Vyxal, 11 bytes

```
Ṙṗ'L2=;vÞṠ∑

```

Try it Online!

Based on Kendall tau distance definition.

May be golfed more, but I don't like direct ports of another answers, so golfing should be based on the same definition
> 1 votes

# Answer
# Uiua, ~~14~~ 11 bytes

```
/+♭<∩'⊞<.⊛.

```

Try it!

-3 thanks to Bubbler
> 1 votes

# Answer
# Maxima, 97 bytes

Golfed version. Try it online!

```
f(m):=block([c:0,n:length(m)],for i:1 thru n do(for j:i+1 thru n do(if m[i]>m[j] then c:c+1)),c)$

```

Ungolfed version. Try it online!

```
f(m) := block(
    [count: 0, n: length(m)],
    for i:1 thru n do (
        for j:i+1 thru n do (
            if m[i] > m[j] then count: count + 1
        )
    ),
    return(count)
)$

applyFunction(m) := print(m, " -> ", f(m))$

map(applyFunction, [[3, 2, 1], [1, 2, 3, 4], [2, 1, 3, 4], [2, 1, 4, 3], [2, 4, 1, 3], [4, 2, 3, 1], [4, 3, 2, 1]]);

```
> 1 votes

# Answer
# Retina, 22 bytes

```
\d+
*
rw`\1\b.*,(_+)\b

```

Try it online! Link includes test cases. Explanation: The first stage simply converts to unary. The second stage then counts the number of overlapping matches (`w`) where the first number is not less than the second number. The `r` flag causes the match to be processed right-to-left, so the second number is matched first and the first number then compared against it; if left-to-right matching was used, either the input would have to be reversed, or a negative lookahead used to ensure the second number is less than the first, either way costing more bytes.
> 0 votes

---
Tags: code-golf, array, edit-distance
---