# Question
Title: The shortest way to find one unique value when all other values are the same
In this question at Code Review they tried to find the fastest way to return the unique element in an array where all the elements are the same except one. But what is the shortest code that accomplish the same thing?

### Goal

Find the unique element in an array and return it.

### Rules

* The input array will contain only integer, strictly positive numbers, so you can use 0 as the end of the input if your language needs it.
* The size of the array will be at least 3 and will have a finite size. You can limit the size of the array to any limit your language has.
* Every element in the array will be the same, except for one which will be different.
* You must output the value (not the position) of the unique element in any standard format. You can output leading or trailing spaces or newlines.
* You can take the input array in any accepted format.

### Examples

```
Input                   Output
------------------------------
[ 1, 1, 1, 2, 1, 1 ]      2
[ 3, 5, 5, 5, 5 ]         3
[ 9, 2, 9, 9, 9, 9, 9 ]   2
[ 4, 4, 4, 6 ]            6
[ 5, 8, 8 ]               5
[ 8, 5, 8 ]               5
[ 8, 8, 5 ]               5

```

### Winner

This is , so may the shortest code for each language win!

# Answer
> 25 votes
# Python 3, 27 bytes

```
lambda x:min(x,key=x.count)

```

Try it online!

# Answer
> 14 votes
# , 24 bytes

```
a=scan();a[a!=median(a)]

```

Try it online!

# Answer
> 13 votes
# JavaScript (ES6),  ~~32~~  27 bytes

*Saved 5 bytes thanks to @xnor*

```
a=>a.sort()[0]+a.pop()-a[1]

```

Try it online!

### How?

`a.sort()` sorts the input array in lexicographical order. We know for sure that this is going to put the unique element either at the first or the last position, but we don't know which one:

```
[ x, ..., y, ..., x ].sort() -> [ y, x, ..., x ] or [ x, x, ..., y ]

```

Either way, the sum of the first and the last elements minus the 2nd one gives the expected result:

```
[ y, x, ..., x ] -> y + x - x = y
[ x, x, ..., y ] -> x + y - x = y

```

We could also XOR all of them:

```
a=>a.sort()[0]^a.pop()^a[1]

```

Try it online!

# Answer
> 10 votes
# x86-16 machine code, 14 bytes

**Binary:**

```
00000000: 498d 7c01 f3a6 e305 4ea6 7401 4ec3       I.|.....N.t.N.

```

**Listing:**

```
49          DEC  CX             ; only do length-1 compares
8D 7C 01    LEA  DI, [SI+1]     ; DI pointer to next value
F3 A6       REPE CMPSB          ; while( [SI++] == [DI++] );
E3 05       JCXZ DONE           ; if end of array, result is second value
4E          DEC  SI             ; SI back to first value
A6          CMPSB               ; [SI++] == [DI++]?
74 01       JE   DONE           ; if so, result is second value
4E          DEC  SI             ; otherwise, result is first value
        DONE:
C3          RET                 ; return to caller

```

Callable function, input array in `[SI]`, length in `CX`. Result in `[SI]`.

**Explanation:**

Loop through the array until two different adjacent values are found. Compare the first to the third value. If they are the same, the "odd value out" must be the second, otherwise it is the first.

*Example:*

Input `[ 1, 1, 1, 2, 1, 1 ]`, reduce until different adjacent values are found `a = [ 1, 2, 1, 1 ]`. If `a[0] == a[2]` then result is `a[1]`, otherwise result is `a[0]`.

**Tests using DOS DEBUG:**

# Answer
> 9 votes
# 05AB1E, 2 bytes

```
ʒ¢

```

Try it online!

Since `1` is the only truthy integer in 05AB1E, we can just filter (`ʒ`) on the `¢`ount.

There is also the Counter-Mode builtin, which returns the least frequent element in a list at the same bytecount:

```
.m

```

Try it online!

# Answer
> 8 votes
# APL (Dyalog Extended), 5 bytes

```
⍸1=¯⍸

```

Try it online!

Regular Dyalog APL 18.0 has `⍸⍣¯1`, but it doesn't work here because it requires the input array to be sorted, unlike Extended's `¯⍸` which allows unsorted input arrays.

### How it works

```
⍸1=¯⍸  ⍝ Input: a vector N of positive integers
       ⍝ (Example: 4 4 6 4)
   ¯⍸  ⍝ Whence; generate a vector V where V[i] is the count of i in N
       ⍝ (¯⍸ 4 4 6 4 → 0 0 0 3 0 1)
 1=    ⍝ Keep 1s intact and change anything else to zero (V1)
       ⍝ (1= 0 0 0 3 0 1 → 0 0 0 0 0 1)
⍸      ⍝ Where; generate a vector W from V1, where i appears V1[i] times in W
       ⍝ (⍸ 0 0 0 0 0 1 → 6)

```

# Answer
> 8 votes
# Haskell, 32 bytes

```
f(x:y)|[e]<-filter(/=x)y=e|1<3=x

```

Try it online!

# Explanation

The code, expanded with variables renamed to be more descriptive.

```
f (first:rest)
 | [unique] <- filter (/=first) rest = unique
 | 1 < 3 = first

```

`(first:rest)` is a pattern match on a list that destructures it into its first element (`first`) and the list without the first element (`rest`).

Each line with a `|` at the front is a case in the function (known as "guards" in Haskell). The syntax looks like `functionName args | condition1 = result1 | condition2 = result2 ...`. There are two cases:

1. `[unique] <- filter (/=first) rest`. This asserts that `filter (/=first) rest` produces a list containing only one element, which we name `unique`. `filter (/=first) rest` filters out all elements in `rest` not equal to `first`. If we are in this case, then we know that `unique` is the unique element, and we return it.
2. `1 < 3`. This asserts that 1 is less than 3. Since it's always true, this is a "fallthrough" case. If we reach it, we know that there are at least 2 elements not equal to the first element, so we return `first`.

# Answer
> 8 votes
# Bash \+ coreutils, 12 bytes

```
sort|uniq -u

```

Try it online!

# Answer
> 6 votes
# Jelly, 3 bytes

```
ḟÆṃ

```

Explanation:  (probably) removes all elements that are not the most common element (returned by `Æṃ`). I don't know why isn't the result a single-element list (perhaps it's a feature I didn't know about?), but that makes this even better.

Try it online!

# Answer
> 6 votes
# , 10 8 bytes

```
1#.|//.~

```

Try it online!

### How it works

```
 1#.|//.~  input:                  1 1 1 2 1
      /.~  group by itself:        1 1 1 1
                                   2
    |/     insert | (remainder) into both groups:
                   1 | 1 | 1 | 1 = 0
                   2             = 2
 1#.       sum:                    2

```

# Answer
> 6 votes
# Octave / MATLAB, 19 bytes

```
@(x)x(sum(x==x')<2)

```

Try it online!

### How it works

```
@(x)                  % Define a function of x
          x==x'       % Square matrix of all pairwise comparisons (non-complex x)
      sum(     )      % Sum of each column
                <2    % Less than 2? This will be true for only one column
    x(            )   % Take that entry from x

```

# Answer
> 6 votes
# Octave, 17 bytes

```
@(x)x(x!=mode(x))

```

Try it online!

2 bytes golfed thanks to Luis Mendo!

# Answer
> 6 votes
# Ruby, 18 bytes

```
->a{a-[a.sort[1]]}

```

Try it online!

The unique element will always be the largest or smallest, so remove all copies of the second element.

# Answer
> 6 votes
# Wolfram Language (Mathematica), ~~21~~ ~~19~~ 17 bytes

```
f[c=a_...,b_,c]=b

```

Try it online!

# Answer
> 5 votes
# , 25 bytes

```
a=sort(scan());a[a!=a[2]]

```

Try it online!

Sort the input, giving `a`. Now `a[2]` is one of the repeated values. Keep only the element not equal to `a[2]`.

This ends up 4 bytes shorter than my best shot with a contingency table:

```
names(which(table(scan())<2))

```

# Answer
> 5 votes
# Pyth, 4 bytes

-1 byte thanks to @FryAmTheEggman

```
ho/Q

```

Try it online!

## Explanation

```
 o   : Order implicit input
  /Q : by count of the element
h    : then take the first element

```

# Answer
> 5 votes
# PowerShell, 23 bytes

```
$args-ne($args|sort)[1]

```

Try it online!

Takes input by splatting. We apply a filter to the original array getting rid of the dupes by sorting it and taking the 2nd element.

# Answer
> 5 votes
# T-SQL, 40 bytes

Input is a table variable

```
DECLARE @ table(v int)
INSERT @ values(1),(1),(2),(1)

SELECT*FROM @
GROUP BY v
HAVING SUM(1)=1

```

Another variation

# T-SQL, 54 bytes

```
DECLARE @ table(v real)
INSERT @ values(1),(1),(2),(1)

SELECT iif(max(v)+min(v)<avg(v)*2,min(v),max(v))FROM @

```

# Answer
> 5 votes
# Brachylog, 4 bytes

```
oḅ∋≠

```

Try it online!

Takes a list and returns a singleton list.

## Explanation

```
oḅ∋≠  Input is a list, say [4,4,3,4].
o     Sort: [3,4,4,4]
 ḅ    Blocks of equal elements: [[3],[4,4,4]]
  ∋   Pick a block: [3]
   ≠  This block must have distinct elements (in this case, must have just one).
      Output it implicitly.

```

# Answer
> 4 votes
# RAD, 13 bytes

```
⍵[1⍳⍨+/⍵∘=¨⍵]

```

The lack of a need for `{}` in this language really helps.

Try it online!

## Explanation

```
⍵[1⍳⍨+/⍵∘=¨⍵]
     +/⍵∘=¨⍵  count of each element's # of occurrences
  1⍳⍨         first occurrence of a 1
⍵[          ] the argument at that index

```

# Answer
> 4 votes
# K (ngn/k), ~~8~~ 6 bytes

**Solution:**

```
*<#'=:

```

Try it online!

**Explanation:**

```
*<#'=: / the solution
    =: / group the input
  #'   / count length of each
 <     / sort ascending
*      / take the first

```

**Extra:**

* **-2 bytes** thanks to `ngn` by dropping the lambda

# Answer
> 4 votes
# Haskell, 30 bytes

```
f(x:y)|elem x y=f$y++[x]|1>0=x

```

Try it online! Footer stolen from coles answer.

If the first element is not in the remaining list, return it, otherwise rotate it to the end and try again.

# Answer
> 4 votes
# Wolfram Language (Mathematica), 19 bytes

```
Tr[#/.Median@#->0]&

```

Inspired by Kirill L.'s R submission

Try it online!

Finds the median, replaces its occurrences in the list with 0, and sums the list.

# Answer
> 4 votes
# Husk, ~~3~~ 2 bytes

*-1 byte thanks to Razetime!*

```
◄=

```

Try it online!

# Answer
> 4 votes
# Vyxal, 3 bytes

```
Ċ↓h

```

Try it Online!

## Explained

```
Ċ↓h
Ċ     # Get the counts of all items
 ↓    # Get the smallest item based on last item
  h   # Output the head of that list

```

Also, according to code-golf's statistics, only a small percentage of people who view my answers actually upvote them. So if you enjoy this answer, consider upvoting, it's free, and you can change your mind at any time (given you have ≥2k rep). Enjoy the answer.

# Answer
> 4 votes
# Julia 1.0, 24 bytes

```
~d=d[@.sum(==(d),[d])<2]

```

Try it online!

# Answer
> 4 votes
# Thunno 2, 2 bytes

```
Ṁo

```

Note that output as a singleton list is a default.

#### Explanation

```
Ṁo  # Implicit input
 o  # Remove all instances of                       from the input
Ṁ   #                         the mode of the input
    # Implicit output

```

#### Screenshot

# Answer
> 4 votes
# ATOM, 15 chars, 18 bytes

### Code:

```
*2>($1$1==*)

```

### Usage:

```
[1,1,1,2,1,1] INTO *2>($1$1==*)

```

## Try it live here

### Explanation:

The ATOM language implicitly treats the expression as a function, where * is the parameter.

Therefore, it interprets the expression as

```
[1,1,1,2,1,1] 2>($1$1==*)

```

The operator is an array filter, which takes an array on the left, and a function on the right. The expression to the right is implicitly parsed into a function. Therefore, it is searching the values in the input array for all values where the following returns true

```
2>($1$1==*)

```

The operator is array length, so it is searching for elements in the original input where ($1$1==\*) evaluates to an array of length 1 i.e. the unique element.

The first $1 looks for the variable on the stack at index 1, which is the original array (index 0 is the element in the array that is being iterated through, since we are inside the where operator).

Another operator is performed on the array. $1==\* is now parsed to a new function, and $1 refers to the variable on the stack at index 1, which is the number being iterated through in the outer . The * refers to the immediate stack variable, which is the number being iterated through in the inner . Matches are returned, so if there are multiple instances of a number in the original array, the resulting array will be of length greater than or equal to 2. As such, only the unique element in the array will satisfy the 2\>($1$1==\*) clause.

# Answer
> 4 votes
# Uiua, 4 bytes

```
⊗1⍘⊚

```

Try it!

```
⊗1⍘⊚
  ⍘⊚  # inverse where, i.e. how many times does each element occur?
⊗1    # index of 1

```

# Answer
> 4 votes
# AWK, 34 bytes

```
{a[$0]++?c=$0:b+=$0}END{print b-c}

```

Attempt This Online!

Takes positive integers separated by newlines. Let's call the unique number `u` and duplicates `d`.

* `{a[$0]++?c=$0:b+=$0}`: Executed for each line. `$0` contains the number on the line.
    + `a` is used as a dict that counts the occurrences of each number. `a[$0]++` increments the count, and evaluates to falsy if it was encountered the first time, truthy otherwise.
    + `b+=$0` is run exactly twice, when each of `u` and `d` is read the first time. Therefore, `b` is equal to `u+d` at the end.
    + `c=$0` is run for the rest of the time, and `$0` in this case is always `d`.
* `END{print b-c}` is run after all inputs are processed. `b-c` is `u`, and it is printed.

# Answer
> 3 votes
# Python 3, ~~56~~ 39 bytes

```
lambda x:[i for i in x if x.count(i)<2]

```

Try it online!

# Answer
> 3 votes
# Gaia, 2 bytes

```
C⌡

```

Not a built-in!

`C` is "count occurrences in list" and  is "find the smallest by".

(the footer is "evaluate" and "call the function above", Gaia doesn't seem to evaluate input by default)

Try it online!

# Answer
> 3 votes
# Wolfram Language (Mathematica), 27 bytes

```
Keys@Select[Counts@#,#<2&]&

```

Try it online!

# Answer
> 3 votes
# Java (JDK), 62 bytes

```
int f(int[] a){Arrays.sort(a);return a[0]+a[a.length-1]-a[1];}

```

Try it online!

Thanks to JollyJoker for correct way.

Original completely own failing dumb#ss solution:

`int f(int[] a){Arrays.sort(a);return a[0];}`

# Answer
> 3 votes
# PHP, ~~46~~ 45 bytes

```
fn($i)=>array_flip(array_count_values($i))[1]

```

Try it online!

Could maybe be golfed more using a custom solution, but the straightforward one is quite short already: returns the first value that is counted one time. Works with any type of value. If only PHP array functions were not prefixed with `array_`!

EDIT: saved 1 byte thanks to @640KB now uses `array_flip`, meaning that it still works for any value type but this time gets the last value counted one time

# Answer
> 3 votes
# Excel, 14 bytes

Put the numbers in column A, and enter this formula in another column

```
=UNIQUE(A:A,,1

```

# Answer
> 3 votes
C GCC, 40 bytes

```
f(int*a){a=*a^*++a?a[-(*a==a[1])]:f(a);}

```

Try it online!

Thanks to xibu for -5 bytes!

Thanks to ceilingcat for -2 bytes!

# Answer
> 3 votes
# C (gcc), 39 bytes

```
f(int*a){a=*a-*++a?a[*a--!=a[2]]:f(a);}

```

Try it online!

```
f(int*a){      // function taking a 0-terminated array pointer.

 a=            // return using eax register trick.
 *a-*++a?      // compare current item with next item :
 a[*a--!=a[2]] // if different we move the pointer by the result of comparing the next item,
:f(a);         // if not we recursively call on the incremented pointer.
}
```

# Answer
> 3 votes
# Arn, 12 bytes

```
BØ├┤ÅöÀ&iG£3

```

# Explanation

Unpacked: `$v{(${=v})#<2}`

```
$ Filter
  v{ block with index named v
    ( Start expression
      $ Filter
        { block with index named _
          =v Is current item equal to v
        }
    )
    # Length
    <2 Is less than 2
  }

```

Output implicit, input on one line split by spaces

# Answer
> 3 votes
# Desmos, 169 ~~105~~ ~~37~~ 25 bytes

*-12 bytes thanks to @Yousername*

```
f(l)=l.max+l.min-l.median

```

Try it on Desmos!

# Answer
> 3 votes
# Ruby 2.7, 15 bytes

```
p$*.tally.key 1

```

Takes in the array of chars as input from the arguments `$*` passed to it.

---

# Ruby 2.7, 18 bytes

```
->a{a.tally.key 1}

```

The following is the screenshot of SoloLearn code playground, which uses Ruby 2.7,

# Answer
> 3 votes
# C (gcc), ~~48~~ ~~46~~ 44 bytes

-2 thanks to @ceilingcat

```
f(int*a){*a=*a-a[-1]?a[-(*a==a[1])]:f(a+1);}

```

Try it online!

# Answer
> 3 votes
# Zsh, 22 bytes

```
<<<${@:#${${(o)@}[2]}}

```

Try it online!

`:#`Removes all elements matching the `[2]`nd element of the `(o)`rdered array, and `<<<`prints.

# Answer
> 3 votes
# Rust, 45 bytes

A closure that takes a mutable slice and returns the outlier.

```
|s:&mut[u8]|{s.sort();s[0]^s[1]^s[s.len()-1]}

```

Attempt This Online!

Explanation:

```
|s:&mut[u8]|{ // Take a mutable slice
  s.sort();   // Sort the slice. This means that
              // the outlier is now either the first or last
              // element, and every element in between must be common.
  s[0]^s[1]^s[s.len()-1]
  // Since the slice must have at least three elements,
  // the first, second and last number must have distinct indices.
  // One of these three is the outlier, and the other two are equal.
  // Xoring two equal numbers yields zero, and xoring zero with a
  // number n yields n. The operation is commutative and associative.
  // Thus, by xoring the three relevant numbers we obtain the outlier.

  // We could have also subtracted the second element since we know
  // it can't be the outliner, but this both looks less cool
  // and gives overflow problems when not using signed integers.
}

```

# Answer
> 2 votes
# Perl 5 `-p`, 30 bytes

```
s/\d+//;$_=s/\b$&\b//g?$_+0:$&

```

Try it online!

### Perl 5 `-a`, 31 bytes

```
//,(1-grep$_==$',@F)||say for@F

```

Try it online!

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

```
1-(@b="@F"=~/\b$_\b/g)||say for@F

```

Try it online!

# Answer
> 2 votes
# Charcoal, 8 bytes

```
ＩΦθ⁼¹№θι

```

Try it online! Link is to verbose version of code. Works by filtering out elements whose count is not `1`. (Singleton list output is allowed by default, although Charcoal's output for a singleton list looks like that of a bare string anyway.) Explanation:

```
  θ         Input list
 Φ          Filtered where
     №      Count of
       ι    Current element
      θ     In input list
   ⁼¹       Equals literal `1`
Ｉ           Cast to string
            Implicitly print

```

# Answer
> 2 votes
# , 36 bytes

```
n=scan();while(sd(n[-T]))T=T+1;n[+T]

```

Try it online!

Iterates over the indices, calculating the standard deviation of the array with the associated element removed; when the standard deviation is 0, the removed element is the unique value.

This isn't the shortest by a long shot, but it's a neat little R approach.

# Answer
> 2 votes
# , ~~30~~ 29 bytes

*Edit: -1 byte thanks to Giuseppe, but still a long way to go to catch the current leading R solution...*

```
y=table(scan());names(y[y<2])

```

Try it online!

Outputs a character string containing the value of the lonely element.

Edit: just realized that this is a worse version of the solution that Robin Ryder already discarded...

# Answer
> 2 votes
# Wolfram Language (Mathematica) ~~17 29~~ 28 bytes

Code corrected due to comment by @att:

```
SortBy[Tally[#],Last][[1,1]]&

```

theorist managed to shave off one byte with this:

```
Cases[Tally@#,{_,1}][[1,1]]&

```

# Answer
> 2 votes
# C (gcc), ~~68~~ \\$\cdots\\$ ~~59~~ 58 bytes

Saved a byte thanks to ceilingcat!!!

```
c;d;f(l,n)int*l;{for(c=0;--n;)l[n]-*l?d=n:(c=1);n=l[d*c];}

```

Try it online!

Inputs a pointer to an array of integers and its length.
Returns the unique element.

**How**

We initialises a flag, `c`, to zero and go through all the elements starting at the last through to the second. We use the first element as a test value. When we find an element different from the first we cache its index in `d`. If an element is the same as the first, we set `c` to one. After looping we know that the first element is unique if `c` is still zero. Otherwise `d` is the index of the unique element.

# Answer
> 2 votes
# Retina, ~~26~~ 25 bytes

```
.+
*
O`
,A2,-2`
+`_¶_
¶
_

```

Try it online! Link includes test suite that converts from a comma-separated list to a newline-separated list for ease of use. Uses @xnor's algorithm. Edit: Saved 1 byte thanks to @FryAmTheEggman pointing out that I didn't need to remove the newlines before counting the `_`s. Explanation:

```
.+
*

```

Convert to unary.

```
O`

```

Sort.

```
,A2,-2`

```

Drop all entries except the first two and the last.

```
+`_¶_
¶

```

Subtract the second value from the sum of the first and last. Well, sort of. All this guarantees is that there are no `_`s left in between the newlines, so the number of remaining `_`s is the desired result, but without actually specifying where they are.

```
_

```

Count the remaining `_`s as a decimal integer.

# Answer
> 2 votes
# Assembly (as, x64, Linux), 142 bytes (455 bytes code)

This runs on Linux only (for the syscalls) and only respects integers as bytes (input in ASCII).

```
.intel_syntax noprefix
.text
.global _start
_start:
mov cx,0
r:
lea rbx,a
lea rsi,i
mov rdi,0
mov rdx,2
mov rax,0
push rcx
syscall
pop rcx
mov al,[rsi]
cmp cx,0
je s
cmp cx,1
je t
cmp cx,2
je v
cmp al,[rbx]
jne p
jmp w
s:
mov [rbx],al
inc cx
jmp r
t:
inc cx
cmp al,[rbx]
je r
inc rbx
jmp s
v:
cmp al,[rbx]
je r
mov [rbx+1],al
w:
inc rbx
p:
mov rsi,rbx
mov rdx,1
mov rdi,1
mov rax,1
syscall
mov rdi,0
mov rax, 60
syscall
.data
a:
.byte 0,0
i:
.byte 0,0,0

```

Try it online!

# Answer
> 2 votes
# Japt, 4 bytes

```
ü l1

```

Try it

Groups (and sorts) by value and then filters items of length 1.

# Answer
> 2 votes
# Dyalog APL, ~~15~~ 14 bytes

```
{⍵[⊃⍋+/⍵∘.=⍵]}

```

-1 byte thanks to @streetster

Try it online!

## Explanation

```
{⍵[⊃⍋+/⍵∘.=⍵]}
     +/⍵∘.=⍵  - a list of the number of occurences of each element
   ⊃⍋         - grab the first index
 ⍵[         ] - extract that element

```

# Answer
> 2 votes
# C (gcc), ~~50~~ 42 bytes

```
f(int*b,int*e){b=(*b^*e--?:f(b,e)^*e)^*e;}

```

Try it online!

# Answer
> 2 votes
# MY, 17 bytes

```
ωω9Ġ'ƒ⇷(⍉Σ1=⍸ω@⍰←

```

Try it online!

## Explanation

```
ωω9Ġ'ƒ⇷(⍉Σ1=⍸ω@⍰←
ωω                  push the argument twice
  9Ġ'               push "=" in the codepage
     ƒ              turn it into a function
      ⇷             keeping the left argument the same, and mapping over each element
       (            apply that
        ⍉           transpose
         Σ          sum (now we have how many times each element occurs)
          1=        whether the elements are 1
            ⍸       the indeces of that
             ω@     the actual element
               ⍰    it's in an array, so pick a random element from it (since theres only one)
                ←   output

```

# Answer
> 2 votes
# Io, 38 bytes

```
method(x,x unique sum-x average round)

```

Try it online!

## Explanation

```
                                       // x = [1,1,2,1,1,1]
method(x,                            )
         x unique                      // Uniquified x: [1,2]
                  sum                  // Sum:          3
                      x average        // Average of x: 1.1666666666666667
                                round  // Round to the closest integer: 1
                     -                 // Minus: 3-1 = 2

```

# Io, 44 bytes

The built-in solution.

```
method(x,x uniqueCount map(reverse)min last)

```

Try it online!

## Explanation

```
                                             // e.g. x = [1,2,1,1,1,1]
method(x,                                  ) // Method (taking x):
         x uniqueCount                       // Uniquified counts.   [[1,5],[2,1]]
                       map(reverse)          // Put counts in front. [[5,1],[1,2]]
                                   min       // The one with the smallest count. [1,2]
                                       last  // Return the current item. 2

```

# Io, 44 bytes

(Comparison answer, if I just ported Arnauld's solution anyway)

```
method(x,x sortInPlace()first+x pop-x at(1))

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 17 bytes

```
O`
^(.*¶)\1+

1G`

```

Try it online! Link includes test suite that converts from a comma-separated list to a newline-separated list for ease of use. Explanation:

```
O`

```

Sort the input lines so that the unique line is now either first or last.

```
^(.*¶)\1+

```

If the first two lines are identical then remove them and all following identical lines.

```
1G`

```

Take the first remaining line.

# Answer
> 2 votes
# Python 2, 47 bytes

```
i=sorted(input())
print(i[0],i[-1])[i[0]==i[1]]

```

Try it online!

A long way from the shortest Python answer but just another way of doing it.

# Answer
> 2 votes
# Brain-Flak, 112 bytes

```
(()){{}({}<{({}<>)<>}<>>){({}<>)<>}<>(({}[({})])<({}({}))>)((){[()]<{{}({}<(({}[({})])<({}{})>)<>{}>)<>}>}{})}<>

```

Try it online!

## Explanation

Very broadly speaking this cycles the list until the first two elements are unequal. Then it deletes the front element until the second two elements are the same. Once that is done it outputs whatever is on the front.

Ok that wasn't quite true. I said

> Then it deletes the front element until the second two elements are the same

But it actually deletes the 1st *and the 3rd* elements until ...

This doesn't actually make a difference to the output though, to see why let's look at the cases. First the easy cases with more than 3 elements

```
b a a a a ...

```

In this case the second two elements are equal (`a = a`) so it stops and outputs `b`.

```
a b a a a ...

```

In this case the second two elements are unequal (`a /= b`) so it removes the first and third elements.

```
b a a ...

```

Now we are back to the first case.

Now for the cases with three elements.

```
b a a

```

In this case the second two elements are equal (`a = a`) so it stops and outputs `b`.

```
a b a

```

In this case the second two elements are unequal (`a /= b`) so it removes the first and third elements.

```
b

```

Now we want to run the check again, but there is only one element. Luckily Brain-Flak pads the bottom of the stack with zeros so this is really the same as

```
b 0 0

```

And we assumed input was positive `b /= 0` so we are back to the case above.

---

So that works fine but *why* do we do it?

The thing about Brain-flak is that in order to do any non trivial checks with an element we need to pop it from the stack. That means that if we want to do things in place, like check if one element is equal to another, we need to pop those things and put them back. So here we save bytes by not putting the third element back when we are checking equality.

This saves us two bytes.

# Answer
> 2 votes
# Lua, 43 bytes

```
t=arg table.sort(t)print(t[1]+t[#t]-t[2]|0)

```

Try it online!

Returning method stolen from Arnauld's solution.

### Alternate Solution, 49 Bytes:

```
t=arg table.sort(t)print(t[t[1]<t[2]and 1or#t]|0)

```

### Notes

Lua's table indexing starts at `1`, and boolean logic generally returns the value rather than an actual `bool`.

# Answer
> 2 votes
# Python 3, 49 bytes

```
def f(n):n.sort();return (n[0],n[-1])[n[0]==n[1]]

```

Try it online!

# Answer
> 2 votes
# JavaScript (61 60 bytes)

My first attempt in this community, so there's room for improvement:
`x=>{[a,b,c]=x.filter((e,i)=>x[i-1]!=e);return !c&&x[1]-a?a:b}`

```
x=>{[a,b,c]=x.filter((e,i)=>x[i-1]!=e);return!c&&x[1]-a?a:b}

```

Try it online!

**Explanation:**

```
x.filter((e,i)=>x[i-1]!=e)

```

The array is filtered to remove any element that is the same as array\[index - 1\]. These are then unpacked into variables `[a,b,c]`.
The three scenarios are 1) \[same, unique, same\] 2) \[unique, same\] 3) \[same, unique\]

```
return !c&&x[1]-a?a:b

```

If c is undefined, i.e. the unique element was on the end of the array - and if 'a' *(which is by now either array\[0\] or array\[last element - 1\])* is not equal to array\[1\], then a is the unique element. Otherwise, we have scenario 1 or 3, either way - return 'b'

# Answer
> 2 votes
# jq, 11 bytes

```
.-[sort[1]]

```

Try it online!

## Explanation

```
.           # The input
 -          # With all occurances of ... removed:
  [sort     #    The sorted input
       [1]] #    's second item

```

# Answer
> 2 votes
# Factor, ~~28~~ 23 bytes

```
[ histogram keys last ]

```

Try it online!

Get the last (second) key in the histogram of the input, which will always have the smaller count.

# Answer
> 2 votes
# Raku, 25 bytes

```
{.BagHash.invert.Hash{1}}

```

Try it online!

# Answer
> 2 votes
# Scala, 85 bytes

Try it online!

```
def f(x:Seq[Int])=x.groupBy(identity).mapValues(_.length).filter(_._2 == 1).keys.head

```

This Scala code defines a function `f` that takes a sequence of integers `x` as input, and returns the unique element in the sequence.

Here's a breakdown of what the function does:

* `x.groupBy(identity)` groups the elements in the sequence `x` by their identity (i.e., their value), returning a map where the keys are the distinct values in `x`, and the values are arrays of elements in `x` with that value.
* `.mapValues(_.length)` transforms the values in the map to their length, i.e., the number of elements in `x` with that value.
* `.filter(_._2 == 1)` filters the key-value pairs in the map to keep only those where the value (i.e., the count of elements with that value in `x`) is equal to 1.
* `.keys` returns the keys (i.e., the distinct values in `x`) of the filtered map as a set.
* `.head` returns the first (and only) element of the set, which is the unique element in `x`.

So the entire function finds the unique element in `x` by grouping its elements by their value, counting the elements with each value, filtering for the value with count 1, and returning it.

# Answer
> 2 votes
# TI-BASIC, ~~10~~ 9 bytes

```
min(Ans)max(Ans)/median(Ans

```

Takes input in `Ans`.

# Answer
> 2 votes
# Vyxal 3, 4 bytes

```
SġⁿL

```

Try it Online!

Sorts the array, groups by adjacent items and takes the minimum by length

# Answer
> 2 votes
# HBL, 10.5 bytes

```
+(1.)('1.)(<(1.2
)(%.

```

Try it!

Port of Arnauld's answer.

-3 bytes thanks to @DLosc!

# Explanation:

## Helper function:

```
+(1.)('1.)(<(1.2
+                 # Add:
 (1.)             # The first element of arg1
     ('1.)        # The last element of arg1
          (<      # Negate below:
            (1.2  # The second element of arg1

```

## Main function:

```
)(%.
 (%.  # Sort arg1
)     # Call the function above

```

Created with the help of Luminespire.

# Answer
> 1 votes
# Scala, ~~28~~ 27 bytes

```
a=>a.minBy(x=>a.count(x==))

```

It finds the minimum number in the list according to the number of occurrences in that same list, since the odd one out will only have 1 occurrence.

Try it in Scastie

# Answer
> 1 votes
# Japt `-m`, 4 bytes

```
ü l1

```

Try it

```
ü       sort and group
  l1    take lenght 1 result

```

# Answer
> 1 votes
# Retina, 24 bytes

```
N`
L0`^(\d+)(?!¶\1)|\d+$

```

Try it online!

This works by sorting the input (one number per line) and then outputting the first number if it is different from the second, and otherwise outputting the last number.

The test case code was taken from Neil's Retina answer which uses an arithmetic method to determine the answer after sorting.

# Answer
> 1 votes
# Google Sheets, 28

Closing parens already discounted.

* Column `A` is input.
* `B1` \- `=SORT(A:A)`
* `B2` \- `=FILTER(B:B,B:B<>B2)`

# Excel 2016, 35

* Column `A` is input.
* `B1` \- `=MAX(A:A)`
* `B2` \- `=IF(MODE(A:A)-B1,B1,MIN(A:A))`

If the mode is the same as the max, then it's the min, otherwise max.

# Answer
> 1 votes
# Burlesque, 8 bytes

```
psf:<][~

```

Try it online!

Explanation:

```
ps       # Parse input string as a block
  f:     # Frequency list - returns block of blocks with format {frequency value}
    <]   # Take the minimum block, in this case calculated based on the first element (frequency)
      [~ # Take the last element (value)
         # Implicitly output

```

# Answer
> 1 votes
# C# 42 Bytes

```
r.GroupBy(a=>a).First(a=>a.Count()==1).Key

```

# Answer
> 1 votes
# Pyth - 6 bytes

I'm not quite sure why this doesn't return an array.

```
f!t/QT

```

# Explanation

```
f!t/QT
f!t/QTQ implicit Q added
f     Q filter on each element T of input for
   /QT  number of times t appears in input
  t     minus 1
 !      is equal to zero

```

# Answer
> 1 votes
# Postgresql, 51 bytes

```
SELECT unnest($1::int[])GROUP BY 1HAVING count(*)=1

```

Takes input as an integer array. Outputs as a row containing the unique value. If there is more than one unique value, it returns all of them in unspecified order.

If the type is specified in the extended query protocol or a function parameter, it can be reduced to 44 bytes

```
SELECT $1.unnest GROUP BY 1HAVING count(*)=1

```

# Answer
> 1 votes
# \[Python 3\], 39 bytes

```
lambda x:x[[*map(x.count, x)].index(1)]

```

# Answer
> 1 votes
# GolfScript, 6 bytes

```
~$.1=-

```

Try it online!

```
~        # Parse the input to an array
 $       # Sort the array
  .1=    # Get the second number in the array, this will always be the repeated number
     -   # Remove all copies of the repeated number

```

# Answer
> 1 votes
# Pyt, 3 bytes

```
ĐṀ\

```

Try it online!

```
Đ        implicit input (S); duplicate on top of stack
 Ṁ       get median (m) (I never got around to fixing a bug in the mode operator, but they do the same thing here)
  \      take the set difference between S and m; implicit print

```

# Answer
> 1 votes
# Arturo, 33 bytes

```
$=>[t:tally&|select[k,v]->v=1t\0]

```

Try it

# Answer
> 1 votes
# \>\<\> (Fish), 29 bytes

```
!!vr:r@:&=&$?$n;
 ~>:@$:@=0$.

```

Try it

# Answer
> 1 votes
# Go, 105 bytes

```
func(N[]int)int{m,o:=make(map[int]int),0
for _,n:=range N{m[n]++}
for k,v:=range m{if v<2{o=k}}
return o}

```

Attempt This Online!

# Answer
> 1 votes
# Java (JDK), 65 bytes

Not the best Java answer, but still really close using a Stream approach.

```
l->l.stream().reduce(0,(a,b)->l.indexOf(b)!=l.lastIndexOf(b)?a:b)

```

Try it online!

# Answer
> 1 votes
# Kotlin, ~~40~~ 24 bytes

```
{minBy{r->count{r==it}}}

```

Try it online!

It doesn't seem to have a count function where you can simply pass the lambda parameter.

-16 bytes thanks to Seggan

# Answer
> 1 votes
# Labyrinth, 34 bytes

```
? }:=
? $ :
: } {
} : +;=$!@
${?"=

```

Try it online!

Examines windows of size 3 until a window with two different numbers is found, and then XORs the three numbers to get the answer.

Given a window of `a b c`, the test is done by checking if `(a^b) + (b^c)` is nonzero. It is trivially zero if `a == b == c`, and we can be sure that it is strictly positive (and therefore nonzero) when `a != b` (i.e. `(a^b) != 0`) or `b != c` (i.e. `(b^c) != 0`) since all the input values are positive.

Also, a redundant work is saved by keeping an XORed value in the stack across iterations.

```
Intro:  ??:}${
??   take two numbers from input [a b]
:}   copy 2nd input to aux.stack [a b | b]
$    XOR                         [a^b | b]
{    pull 2nd input back         [a^b b]

Loop:  ?:}$}:=:{+=   [a^b b] -> [b^c c]
?      take next number from input [a^b b c]
:}     backup c                    [a^b b c | c]
$      XOR                         [a^b b^c | c]
}:     move b^c and copy a^b       [a^b a^b | b^c c]
=:{    swap tops, copy, pull       [a^b b^c b^c a^b | c]
+      add; keep going if zero     [a^b b^c a^b+b^c | c]
=      swap tops                   [... b^c c | ...]

End:  ;=$!@  [a^b b^c a^b+b^c | c]
;=    drop and swap tops   [a^b c | ...]
$!@   print a^b^c and halt

```

# Answer
> 1 votes
# YASEPL, ~~46 32~~ 30 bytes

```
=a=1'±" "=d¥0,1`1!+=e¥a,1}3,d<

```

enter in numbers seperated by a space and nothing else (like `4 4 4 6 4 4`)

## explanation

```
=a=1'±" "=d¥0,1`1!+=e¥a,1}3,d<           packed
=a                                       declare increment variable "a"
  =1'                                    get user input and set it to "1"
     ±" "                                split "1" by every space
         =d¥0,1                          get the first item from "1"
               `1        }3,d            while e == d...
                 !+                      increment a by one
                   =e¥a,1                get item at "1" index "a" and set it to "e"
                             <           print variable "e" when finished

```

# Answer
> 1 votes
# Scala 3, 28 bytes

```
l=>l.minBy(x=>l.count(_==x))

```

Attempt This Online!

# Answer
> 0 votes
# SmileBASIC 4, 43 bytes

```
1  RSORT I:IF I[0]-I[1]GOTO@0
2  ?MIN(I)@0?MAX(I)

```

---

Receives array input through `I[]`. The first value printed is the answer, other printed values are to be ignored. Works by reverse-sorting the list of integers (from largest to smallest values) and comparing the zeroth and first elements. If their difference is non-zero, then the odd one out is the larger value (`MAX(I)`); otherwise, the odd one out is the smaller value (`MIN(I)`).

# Answer
> 0 votes
# gbz80 machine code, 11 bytes

Function that takes the list pointed to by `hl` and returns in `a`. Requires zero-terminator.

```
46 23 2A B8 28 FC 4E B9 C0 78 C9

```

Disassembly:

```
Search:
    ld b, [hl]
    inc hl
.loop:
    ld a, [hl+]
    cp b
    jr z, .loop
; this is for if the first two are different.
    ld c, [hl]
    cp c
    ret nz
    ld a, b
    ret

```

# Answer
> 0 votes
# C, 66 Bytes

```
u(int*a){int*i=a;for(;!(*a-*i);++i);return*a-a[1]&&*a-a[2]?*a:*i;}

```

We iterate over the array until we find an element that's different from the first one, then return the first element if it's different from both the second and the third, otherwise the element that the loop stopped at.

The following optimizations were made:

* Dereferencing a pointer is shorter than indexing an array. Since the elements of an array are stored together, we can use a pointer as an iterator, letting us write `*i` instead of `a[i]`. Similarly, we can always write `*a` instead of `a[0]`.
* For the sake of conditionals, `a-b` is equivalent to `a==b` since every nonzero integer evaluates to true.
* The return type defaults to `int` so we don't need to specify it.
* Ternary operators are shorter than if-conditions, and in this case, it's possible to only use one check. The drawback is that the for-loop gets executed even if it isn't needed.

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


title: Calculate the inverse of factorial

text:
# Question
Title: Calculate the inverse of factorial
Write the shortest code that will take any real number greater than 1 as input and will output its positive inverse factorial. In other words, it answers the question "what number factorial is equal to this number?". Use the Gamma function to extend the definition for factorial to any real number as described here.

For example:

```
input=6 output=3
input=10 output=3.390077654

```

because `3! = 6` and `3.390077654! = 10`

**Rules**

* It is forbidden to use built in factorial functions or gamma functions, or functions that rely on these functions.
* The program should be able to calculate it to 5 decimal digits, with the theoretical ability to calculate it to any precision (It should contain a number that can be made arbitrary big or small to get arbitrary precision)
* Any language is allowed, shortest code in characters wins.

I made a working example here. Have a look.

# Answer
# ised: ~~72~~ 46 characters

This is almost a perfect fit... there is a "language" out there that seems to be meant precisely for math golf: ised. Its obfuscated syntax makes for a very short code (no named variables, just integer memory slots and a lot of versatile single char operators). Defining the gamma function using an integral, I got it to 80 seemingly random characters

```
@4{:.1*@+{@3[.,.1,99]^x:*exp-$3}:}@6{:@{$4::@5avg${0,1}>$2}$5:}@0,0@1,99;$6:::.

```

Here, memory slot $4 is a factorial function, memory slot $6 bisection function and memory slot $2 is expected to be set to input (given before sourcing this code). Slots $0 and $1 are the bisection boundaries. Call example (assuming above code is in file `inversefactorial.ised`)

```
bash> ised '@2{556}' --f inversefactorial.ised
556
5.86118

```

Of course, you could use the builtin ! operator, in which case you get down to 45 characters

```
@6{:@{{@5avg${0,1}}!>$2}$5:}@0,0@1,99;$6:::.

```

Careful, operator precendence is weird sometimes.

Edit: remembered to inline the functions instead of saving them. Beat Mathematica with 72 characters!

```
@0,0@1,99;{:@{{:.1*@+{@3[.,.1,99]^x:*exp-$3}:}::@5avg${0,1}>$2}$5:}:::.

```

And using the ! builtin you get 41.

---

An year overdue update:

I just realized this was highly inefficient. Golfed-down to 60 characters:

```
@0#@1,99;{:@{.1*@3[.,.1,99]^@5avg${0,1}@:exp-$3>$2}$5:}:::.

```

If utf-8 is used (Mathematica does it too), we get to 57:

```
@0#@1,99;{:@{.1*@3[.,.1,99]^@5avg${0,1}·exp-$3>$2}$5:}∙.

```

A bit different rewrite can cut it down to 46 (or 27 if using builtin !):

```
{:x_S{.5@3[.,.1,99]^avgx·exp-$3*.1<$2}:}∙∓99_0

```

The last two characters can be removed if you are ok with having the answer printed twice.
> 6 votes

# Answer
# JavaScript, 116 bytes

Black magic here! Gives a result in **a few milliseconds**.
Only elementary math functions are used: `ln`, `pow`, `exponential`

```
x=9;n=prompt(M=Math);for(i=1e4;i--;)x+=(n/M.exp(-x)/M.pow(x,x-.5)/2.5066/(1+1/12/x+1/288/x/x)-1)/M.log(x);alert(x-1)

```

Basically, I coded a newton solver for \\$ f(y)=\Gamma(y)-n=0 \\$ and \\$ x=y-1 \\$ (because \\$ x! \\$ is \\$ \Gamma(x+1) \\$) and approximations for gamma and digamma functions.

Gamma approximation is Stirling approximation.

Digamma approximation uses Euler Maclaurin formula. The digamma function is the derivative of gamma function divided by gamma function: \\$ f'(y)=\Gamma(y) \cdot \psi(y) \\$

Ungolfed :

```
n = parseInt(prompt());
x = 9; //first guess, whatever but not too high (<500 seems good)

//10000 iterations
for(i=0;i<10000;i++) {

  //approximation for digamma
  d=Math.log(x);

  //approximation for gamma
  g=Math.exp(-x)*Math.pow(x,x-0.5)*Math.sqrt(Math.PI*2)*(1+1/12/x+1/288/x/x);

  //uncomment if more precision is needed
  //d=Math.log(x)-1/2/x-1/12/x/x+120/x/x/x/x;
  //g=Math.exp(-x)*Math.pow(x,x-0.5)*Math.sqrt(Math.PI*2)*(1+1/12/x+1/288/x/x-139/51840/x/x/x);

  //classic newton, gamma derivative is gamma*digamma
  x-=(g-n)/(g*d);
}

alert(x-1);

```

Test cases :

```
10 => 3.390062988090518
120 => 4.99999939151027
720 => 6.00000187248195
40320 => 8.000003557030217
3628800 => 10.000003941731514

```
> 14 votes

# Answer
## Mathematica - ~~74~~ ~~54~~ 49

The proper way will be

```
f[x_?NumberQ]:=NIntegrate[t^x E^-t,{t,0,∞}]
x/.FindRoot[f@x-Input[],{x,1}]

```

If we just drop the test `?NumberQ` it would still work, but throw some nasty warnings, which would go away if we switch to symbolic integration `Integrate`, but this would be illegal (I suppose), because the function would automatically be converted to `Gamma` function. Also we can get rid of external function that way.

Anyway

```
x/.FindRoot[Integrate[t^x E^-t,{t,0,∞}]-Input[],{x,1}]

```

To heck with proper input, just function definition (can't let MatLab win)

```
x/.FindRoot[Integrate[t^x E^-t,{t,0,∞}]-#,{x,1}]&

```

If built-in factorial were allowed

```
N@InverseFunction[#!&]@Input[]

```

The above does not give an integer (which is the argument for a true factorial function). The following does:

```
Floor[InverseFunction[Gamma][n]-1]

```
> 13 votes

# Answer
## MATLAB ~~54~~ 47

If I pick the right challenges MATLAB is really nice for golfing :). In my code I find the solution to the equation (u-x!)=0 in which u is the user input, and x the variable to solve. This means that u=6 will lead to x=3, etc...

```
@(x)fsolve(@(y)u-quad(@(x)x.^y./exp(x),0,99),1)

```

The accuracy can be changed by altering the upper limit of the integral, which is set at 99. Lowering this will change the accuracy of the output as follows. For example for an input of 10:

```
upper limit = 99; answer = 3.390077650833145;
upper limit = 20; answer = 3.390082293675363;
upper limit = 10; answer = 3.402035336604546;
upper limit = 05; answer = 3.747303578099607;

```

etc.
> 5 votes

# Answer
# Python - 199 chars

Ok, so you'll need a lot of stack space and a lot of time, but hey, it'll get there!

```
from random import *
from math import e
def f(x,n):
    q=randint(0,x)+random()
    z=0
    d=0.1**n
    y=d
    while y<100:
            z+=y**q*e**(-y)*d
            y+=d
    return q if round(z,n)==x else f(x,n)

```

Here's another approach with even more recursion.

```
from random import *
from math import e
def f(x,n):
    q=randint(0,x)+random()
    return q if round(h(q,0,0.1**n,0),n)==x else f(x,n)
def h(q,z,d,y):
    if y>100:return z
    else:return h(q,z+y**q*e**(-y)*d,d,y+d)

```

Both of these can be tested with `>>>f(10,1)` provided you set the recursion limit around 10000. More than one decimal place of accuracy will likely not complete with any realistic recursion limit.

Incorporating the comments and a few modifications, down to 199 chars.

```
from random import*
from math import*
def f(x,n):
    q=random()*x+random()
    z=y=0
    while y<100:
            z+=y**q*e**-y*0.1**n
            y+=0.1**n
    return q if round(z,n)==x else f(x,n)

```
> 3 votes

# Answer
# Python 2.7 - ~~215~~ 189 characters

```
f=lambda t:sum((x*.1)**t*2.71828**-(x*.1)*.1for x in range(999))
n=float(raw_input());x=1.;F=0;C=99
while 1:
 if abs(n-f(x))<1e-5:print x;break
 F,C,x=f(x)<n and(x,C,(x+C)/2)or(F,x,(x+F)/2)

```

Usage:

```
# echo 6 | python invfact_golf.py
2.99999904633
# echo 10 | python invfact_golf.py
3.39007514715
# echo 3628800 | python invfact_golf.py
9.99999685376

```

To change precision: change `1e-5` to a smaller number for greater precision, larger number for worse precision. For better precision you probably want to give a better value for `e`.

This just implements the factorial function as `f`, and then does a binary search to hone in on the most accurate value of the inverse of the input. **Assumes the answer is less than or equal to 99** (it wouldn't work for an answer of 365 for sure, I get a math overflow error). Very reasonable space and time usage, always terminates.

Alternatively, replace `if abs(n-f(x))<=10**-5: print x;break` with `print x` to shave off **50 characters**. It'll loop forever, giving you a more and more accurate estimate. Not sure if this would fit with the rules though.
> 3 votes

# Answer
# dg \- 131 133 bytes

```
o,d,n=0,0.1,float$input!
for w in(-2..9)=>while(sum$map(i->d*(i*d)**(o+ 10**(-w))/(2.718281**(i*d)))(0..999))<n=>o+=10**(-w)
print o

```

Since dg produces CPython bytecode this should count for Python as well, but oh... Some examples:

```
$ dg gam.dg
10
3.3900766499999984
$ dg gam.dg
24
3.9999989799999995
$ dg gam.dg
100
4.892517629999997
$ dg gam.dg
12637326743
13.27087070999999
$ dg gam.dg  # i'm not really sure about this one :P it's instantaneous though
28492739842739428347929842398472934929234239432948923
42.800660880000066
$ dg gam.dg  # a float example
284253.232359
8.891269689999989

```

EDIT: Added two bytes because I didn't remember that it should accept floats as well!
> 2 votes

# Answer
# , 92 bytes

A function, `g`, which takes input `z` and outputs the inverse factorial of that number

<sub>*There is almost certainly more to be golfed out of this, so if you see something that I can improve, please let me know.*</sub>

```
library(pryr)
g=f(z,uniroot(f(a,integrate(f(x,x^a*exp(-x)),0,Inf)$v-z),c(0,z+1),tol=1e-9)$r)

```

Try it online!

## Ungolfed and Commented

```
library(pryr)                     # Add pryr to workspace
inv.factorial = f(z,              # Declare function which
  uniroot(                        # Finds the root of
    f(a, integrate(               # The integral of
      f(x, x^a*exp(-x))           # The gamma function
        ,0 ,Inf                   # From 0 to Infinity
      )$value-z                   # Minus the input value, `z`
    ), c(0, z+1),                 # On the bound of 0 to z+1
    tol = 1e-323                  # With a specified tolerance
  )$root                          # And outputs the root
)                                 # End function

```

Try it online!
> 1 votes

# Answer
# PARI/GP, 32 bytes

If we can use `solve()` and \\$\Gamma\\$ function `gamma()`:

```
f(y)=solve(x=0,100,gamma(x+1)-y)

```

Try it online!
> 1 votes

# Answer
# Javascript (without using loops!)

To do this, I used a well-known numerical approximation of the inverse of the Stirling Factorial approximation, (and also got inspiration by this ..cough.. cough.. code of someone else...)

```
function f(n){
    if(n==1) return 1;
    else if(n==2) return 2;
    else if(n==6) return 3;
    else if(n==24) return 4;
    else{
        return Math.round((((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592))+(((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592))+(((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592))+(Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))/Math.log((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))))/Math.log((((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592))+(Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))/Math.log((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))))))/Math.log((((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592))+(((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592))+(Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))/Math.log((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))))/Math.log((((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592))+(Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))/Math.log((Math.log(n)/Math.LN10 *  Math.log(10.) - .5 * Math.log(2.*3.141592)))))))))
    }
}

```
> 0 votes

---
Tags: code-golf, math, factorial
---


title: Vowels up, consonants down

text:
# Question
Title: Vowels up, consonants down
# Challenge

You will be given a string that can contain lowercase letters, uppercase letters, or spaces. You have to turn the vowels (a, e, i, o, u) in the string to upper case and consonants to lower case. This applies whether or not the letter was originally upper case or lower case. Spaces remain as is. Note that "y" is a consonant.

# Examples

```
Hello World -> hEllO wOrld
abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVXWYZ -> AbcdEfghIjklmnOpqrstUvwxyz AbcdEfghIjklmnOpqrstUvxwyz

```

# Info

* The input string can contain letters A to Z, lowercase or uppercase, and spaces.

# Input

The string

# Output

The formatted string (Vowels uppercase and consonants lowercase).

# Answer
# JavaScript (Node.js),  ~~55 ... 46~~  45 bytes

*Saved 1 byte thanks to @KevinCruijssen*

```
s=>Buffer(s).map(c=>c^(c^~68174912>>c)&32)+''

```

Try it online!

### How?

The constant \\$68174912\\$ is a bitmask describing the positions of the vowels:

```
00000100000100000100010001000000
     v     v     v   v   v
zyxwvutsrqponmlkjihgfedcba`_^]\[

```

As per the ECMAScript specification, the following expression:

```
~68174912 >> c & 32

```

is equivalent to:

```
~68174912 >> (c % 32) & 32

```

and therefore evaluates to \\$32\\$ for a consonant or \\$0\\$ for a vowel, no matter the case of \\$c\\$.

### Commented

```
s =>                   // s = input string
  Buffer(s)            // turn s into a buffer
  .map(c =>            // for each ASCII code c:
    c ^                //   change the case if:
      ( c              //     c is not in lower case
        ^              //     XOR
        ~68174912 >> c //     c is a consonant
      ) & 32           //
  ) + ''               // end of map(); coerce back to a string

```
> 25 votes

# Answer
# C (gcc), 49 bytes

Port of my JS answer.

```
f(char*s){for(;*s;s++)*s^=(*s^~68174912>>*s)&32;}

```

Try it online!

---

# C (clang), 48 bytes

*A version suggested by @Neil*

This is abusing the way clang is dealing with the pointer post-increment.

```
f(char*s){for(;*s;)*s++^=(*s^~68174912>>*s)&32;}

```

Try it online!
> 17 votes

# Answer
# Python 3, 55 bytes

```
lambda s:[[c,c.upper()][c in"aeiou"]for c in s.lower()]

```

Try it online!

**Input**: A string/sequence of characters
**Output**: a list of characters.

### Explanation

The solution converts the string to lower case, then convert all vowels to uppercase.

* `for c in s.lower()` converts the string to lower case, then loop through each character in the string.
* `[c,c.upper()][c in "aeiou"]` converts any vowel to uppercase, and consonant to lower case.
`c in "aeiou"` evaluates to `0` or `1`, which is used to index into the list `[c,c.upper()]`.
> 13 votes

# Answer
# Perl 5 `-p`, ~~20~~ 19 bytes

*-1 due to @NahuelFouilleul*

```
$_=lc;y;aeiou;AEIOU

```

Try it online!

Convert everything to lower case, then change vowels to upper case.
> 13 votes

# Answer
# Python, 53 bytes

```
lambda s:[(c*2).title().strip('aeiou')[-1]for c in s]

```

Try it online!

Outputs a list of characters.

Here is an explanation of how it transforms each character `c`, with examples `c='A'` and `c='B'`:

```
                'A'  'B'
(c*2)           'AA' 'BB'  # Two copies of c in a two-character string
.title()        'Aa' 'Bb'  # Title case: uppercase first letter and the rest lowercase
                           # This disregards the case of c
.strip("aeiou") 'A'  'Bb'  # Remove any leading or trailing lowercase vowels 'aeiou'
                           # For a two-character string, this removes all such letters
[-1]            'A'  'b'   # Take the last letter

```

**55 bytes**

```
lambda s:[(c*2).title()[~(c in'aieouAEIOU')]for c in s]

```

Try it online!

If we were instead lowercasing vowels and uppercasing consonants, we wouldn't need the `~()` and would have 52 bytes.
> 10 votes

# Answer
# CJam, 15 bytes

```
lel"aeiou"_euer

```

Try it online!

### Explanation

```
l         e# Read line
el        e# To lowercase
"aeiou"   e# Push this string
_         e# Duplicate
eu        e# To uppercase
er        e# Transliterate. Implicitly display

```
> 7 votes

# Answer
# Bash \+ Core utilities, ~~25~~ 23 bytes

```
tr aeiou AEIOU<<<${1,,}

```

Try it online!

*Saved 2 bytes thanks to a suggestion of Nahuel Fouilleul.*

Input is passed as an argument, output is on stdout.
> 7 votes

# Answer
# Java 8, ~~86~~ 34 bytes

```
S->S.map(c->c^(c^~68174912>>c)&32)

```

-52 bytes by porting *@Arnauld*'s JavaScript answer, so make sure to upvote him!!

**Original 86 bytes answer:**

```
s->{s=s.toLowerCase();for(var p:"aeiou".toCharArray())s=s.replace(p,p&=~32);return s;}

```

Try it online.

**Explanation:**

```
s->{                               // Method with String as both parameter and return-type
  s=s.toLowerCase();               //  Convert the entire String to lowercase
  for(var p:"aeiou".toCharArray()) //  Loop over the vowels as characters:
    s=s.replace(p,p&=~32);         //   And replace the lowercase vowels to uppercase ones
  return s;}                       //  Then return the modified String as result

```
> 7 votes

# Answer
# Jelly,  ~~9~~  7 bytes

Saved 2 using a variation of Luis Mendo's CJam approach

```
ØCŒHyŒu

```

A monadic Link accepting a list of characters which yields a list of characters.

**Try it online!**

### How?

```
ØCŒHyŒu - Link: list of characters, S   e.g. "I am OK!"
ØC      - consonants                         "BCDF...XYZbcdf...xyz"
  ŒH    - split into two                     ["BCDF...XYZ", "bcdf...xyz"]
     Œu - convert (S) to upper-case          "I AM OK!"
    y   - translate                          "I Am Ok!"

```
> 6 votes

# Answer
# Ruby, 33 bytes

```
->s{s.downcase.tr"aeiou","AEIOU"}

```

Straightforward solution: downcase everything, then upcase vowels.

Try it online!
> 6 votes

# Answer
# APL (Dyalog Extended), 14 bytesSBCS

Anonymous tacit prefix function.

```
⌈@(∊∘'aeiou')⌊

```

Try it online!

lowercase

`⌈@(``)` uppercase **at** the following positions:

`∊∘'aeiou'` members of "aeiou"
> 6 votes

# Answer
# sed, ~~41~~ ~~25~~ 24 bytes

Saved 16 bytes thanks to Surculose Sputum!!!
Saved a byte thanks to S.S. Anne!!!

```
s/./\L&/g
y/aeiou/AEIOU/

```

Try it online!
> 6 votes

# Answer
# x86-64 machine code, 21 bytes

(Or **20 bytes** for an x86-32 version with an explicit length input, allowing `dec/jnz` as the loop condition. Using `cl` for a shift count makes it not a win to use `loop`, and 64-bit mode has 2-byte `dec` so it's break-even to make it explicit-length).

Callable as `void vucd_implicit(char *rdi)` with the x86-64 System V calling convention. (It leaves RDI pointing to the terminating `0` byte if you want to use that bonus return value.)

```
# disassembly: objdump -drwC -Mintel
0000000000401000 <theloop>:
  401000:       b8 a0 bb ef fb          mov    eax,0xfbefbba0
  401005:       d3 e8                   shr    eax,cl
  401007:       30 c8                   xor    al,cl
  401009:       24 20                   and    al,0x20
  40100b:       30 c8                   xor    al,cl
  40100d:       aa                      stos   BYTE PTR es:[rdi],al
000000000040100e <vowel_up_consonant_down>:        # the function entry point
  40100e:       8a 0f                   mov    cl,BYTE PTR [rdi]
  401010:       84 c9                   test   cl,cl
  401012:       75 ec                   jne    401000 <theloop>
  401014:       c3                      ret

```

Notice that the function entry point is in the middle of the loop. This is something you can do in real life; as far as other tools are concerned, `theloop` is another function that falls into this one as a tailcall.

This uses something like Arnauld's xor/and/xor idea for applying the lcase bit to an input character, instead of the more obvious `and cl, ~0x20` to clear it in the original, `and al, 0x20` to isolate it from the mask, and `or al, cl` to combine. That would be 1 byte larger because `and cl, imm8` can't use the AL,imm special encoding with no ModRM.

Having the bitmap left-shifted by 5 so the bit we want lines up with 0x20 is also due to @Arnauld's answer. I had been planning to use `bt`/`salc` like in a previous vowel/consonant bitmap answer and mask that with `0x20` until I tried Arnauld's way and found it could be done even more efficiently.

NASM source (Try it online! with a test caller that does strlen on a command line arg and uses a write() system call afterward)

```
global vowel_up_consonant_down
theloop:
                                             ; consonant bitmap
    ;          ZYXWVUTSRQPONMLKJIHGFEDCBA@    For indexing with ASCII c&31 directly
    mov   eax, 111110111110111110111011101b << 5   ; line up with the lcase bit
                                             ; the low bit is 1 to preserve 0x20 ' '
    shr   eax, cl               ; AL & 0x20 is how the lowercase bit *should* be set
    xor   al, cl                ; bitdiff = (mask>>c) & c
    and   al, 0x20              ; isolate the lowercase bit
    xor   al, cl                ; flip the lcase bit if needed
    stosb                       ; and store
vowel_up_consonant_down:
    mov   cl, [rdi]
    test  cl, cl
    jnz  theloop               ; }while(c != 0)
    ret

```

---

## Variants

### no spaces: 19 bytes

If we didn't need to handle spaces (ASCII 0x20), we enter the function at the top, with the `mov cl, [rdi]` load at the top, but still leave the loop condition at the bottom. So we'd load and re-store the terminating `0`, and the XOR that produced it would set ZF. The low bit of the bitmap would be 0 instead of 1.

```
vucd_pure_alphabetic:
.loop:
    mov   cl, [rdi]
   ...               ; same, but with bitmap[0] => 0
    xor   al,cl
    jnz  .loop       ; mask>>0 leave the terminating 0 unmodified; xor sets ZF

```

### Upper-case-only input, like the A to Z in the question indicates: 19 bytes

(Or 17 without spaces either.)

If we can assume the lower-case bit was already cleared on input ASCII bytes, we can save one XOR (and change the other one to an OR)

```
    ...
    shr   eax, cl
    and   al, 0x20
    or    al, cl
    ...

```

---

### Using the `bt` instruction:

Normally testing a bitmap is a job for the `bt` instruction, but where we're not branching on the result, it turns out to be cheaper to shift it, even though that means we can't easily use the `loop` instruction. (I haven't gone back to this idea to re-golf it after realizing we need to handle spaces).

I suspect there's room for more golfing, but the first version of this I tried was

```
vucd:
.loop:
    mov   dl, [rdi]
    ;          ZYXWVUTSRQPONMLKJIHGFEDCBA@    1-indexed using ASCII codes directly
    mov   esi, 111110111110111110111011101b   ; consonant/vowel bitmap for use with bt
    bt    esi, edx              ; CF = mask & (1U << (c&31))
%if CPUMODE == 32
    salc                        ; 1B   only sets AL = 0 or 0xFF.  Not available in 64-bit mode
%else
    sbb   eax, eax              ; 2B   eax = 0 or -1, according to CF.
%endif
    xor   al, dl
    and   al, 0x20              ; just the lowercase bit
    xor   al, dl
    loop .loop
    ret

```

Not re-tested after tweaking to handle spaces.

`bt` \+ `salc` in 32-bit mode costs the same as `shr reg,cl` \+ the extra `test cl,cl` that's needed because we can't use `loop`. So I think this is also 21 bytes. But 32-bit mode explicit-length can just `dec/jnz` a reg other than `cl` for a 20-byte total.

`mov esi, imm32` can be hoisted out of the loop, or we can use EAX. Neither affects byte count, only efficiency or the calling-convention.
> 6 votes

# Answer
# C (gcc), ~~75~~ \\$\cdots\\$~~72~~ 71 bytes

Added 4 bytes to fixed a bug.
Saved a byte thanks to ceilingcat!!!

```
u;f(char*s){for(;*s;*s++=u-65&&u-69&&u-73&&u-79&&u-85?*s|32:u)u=*s&95;}

```

Try it online!
> 5 votes

# Answer
# C (gcc), ~~58~~ \\$\cdots\\$ 58 bytes

```
f(char*s){for(;*s;)*s++=index("aeiou",*s|32)?*s&95:*s|32;}

```

I tried to find a pattern in the vowels' representations using the modulo operator but nothing short enough. Instead, use `strchr`.

*Fixed a bug kindly pointed out by Noodle9 at the cost of 3 bytes.*
*-1 byte thanks to Noodle9!*
*-1 byte thanks to Surculose Sputum!*
*-1 byte thanks to ceilingcat!*

Try it online!
> 5 votes

# Answer
# x86 platform-independent machine code, 46 bytes.

Expects the string pointer to be passed in `eax`, trashes `ebx` and `edx`. Entry point is located at 0x26.

Hex dump:

```
BA 22 82 20 00 D3 EA F6 C2 01 74 0B 8D
51 9F 83 FA 19 8D 59 E0 EB 09 8D 51 BF
83 FA 19 8D 59 20 0F 46 CB 88 08 40 0F
BE 08 85 C9 75 D3 C3

```

Disassembly:

```
00000000  BA22822000        mov edx,0x208222
00000005  D3EA              shr edx,cl
00000007  F6C201            test dl,0x1
0000000A  740B              jz 0x17
0000000C  8D519F            lea edx,[ecx-0x61]
0000000F  83FA19            cmp edx,byte +0x19
00000012  8D59E0            lea ebx,[ecx-0x20]
00000015  EB09              jmp short 0x20
00000017  8D51BF            lea edx,[ecx-0x41]
0000001A  83FA19            cmp edx,byte +0x19
0000001D  8D5920            lea ebx,[ecx+0x20]
00000020  0F46CB            cmovna ecx,ebx
00000023  8808              mov [eax],cl
00000025  40                inc eax
00000026  0FBE08            movsx ecx,byte [eax]
00000029  85C9              test ecx,ecx
0000002B  75D3              jnz 0x0
0000002D  C3                ret

```

byte count = 0x2E = 46
> 5 votes

# Answer
# Retina, 9 bytes

```
T`vVL`VVl

```

Try it online! Explanation:

```
T`v`V

```

Lowercase vowels get uppercased.

```
T`V`V

```

Uppercase vowels also get uppercased, to avoid being matched later.

```
T`L`l

```

All other uppercase letters get lowercased.
> 5 votes

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

Saved 3 using Luis Mendo's CJam approach

```
lžMDu‡

```

**Try it online!** (Footer formats the resulting list of characters as a plain string)

### How?

```
lžMDu‡         e.g. input="LowEr"  stack: []
l      - push lower-case (input)          ["lower"]
 žM    - push lower-case vowels           ["aeiou", "lower"]
   D   - duplicate                        ["aeiou", "aeiou", "lower"]
    u  - upper-case                       ["AEIOU", "aeiou", "lower"]
     ‡ - transliterate                    ["lOwEr"]
       - implicit print                   lOwEr

```
> 4 votes

# Answer
# Red, ~~83~~ 82 bytes

```
func[s][v: charset"aoeiu"parse lowercase s[any[to v change t: v(uppercase t/1)]]s]

```

Try it online!
> 4 votes

# Answer
# Io, 72 bytes

Takes input as a special format.

```
method(x,x map(i,if("aeiou"containsSeq(i),i asUppercase,i asLowercase)))

```

Try it online!
> 4 votes

# Answer
# Javascript (V8), 97 bytes

```
s=>[...s].map(c=>{t="aeiouAEIOU";return(t.includes(c)?c.toUpperCase():c.toLowerCase())}).join('')

```

Takes a string, iterate over every chars and check if the char is a vowel. If so return the char in uppercase, otherwise in lowercase. Then join the return of the map with a void char.

* First post/answer here, if you see some errors or missed case, or just want to improve my code feel free to do so
> 4 votes

# Answer
# JavaScript (V8), 93...77 bytes

Log:

* -5 bytes thanks to @Benji
* -14 bytes: switched to case insensitive matching and `.test()`

```
s=>[...s].map(c=>/[aeiou]/i.test(c)?c.toUpperCase():c.toLowerCase()).join('')

```

Try it online!

```
s=> // es6 arrow function
    [...s]. // split input string into array
        map(c => // another es6 arrow function, this time for a callback iterating over the array
             /[aeiou]/i // case insensitive regex
                .test(c)? // use a ternary operator to check if the character matches the regex
                    c.toUpperCase(): // if true return character to uppercase
                        c.toLowerCase()) // otherwise return lowercase
                            .join('') // join the array back into a string

```

Methods mentioned:
> 4 votes

# Answer
# Haskell, 68 bytes

```
import Data.Char
f=map(g.toLower)
g x|x`elem`"aeiou"=toUpper x|1<2=x

```

Try it online!
> 4 votes

# Answer
# Japt v2.0a0 ~~`-m`~~, ~~10~~ 7 bytes

```
u r\c_v

```

Try it
> 3 votes

# Answer
# Python 3, 50 bytes

```
lambda s:bytes(c^(c^~68174912>>c%32)&32for c in s)

```

Try it online!

Port of Arnauld's JS answer using bytes object in Python. Because Python's `>>` does not imply `%32` on its right argument, it must be done manually.
> 3 votes

# Answer
# T-SQL, 48 bytes

```
SELECT TRANSLATE(LOWER(v),'aeiou','AEIOU')FROM t

```

Takes input from a pre-existing table *t* with varchar column *v*, per our IO rules.

Converts the entire string to lowercase, then makes just the vowels uppercase. The function `TRANSLATE` works in SQL 2017 and later.
> 2 votes

# Answer
# K (oK), ~~27~~ ~~23~~ 21 bytes

**Solution:**

```
`c$x-32*~^"aeiou"?x:_

```

Try it online!

**Explanation:**

Even nicer approach thanks to @ngn... either substract 0 or 32 from the input based on whether or not it's a vowel:

```
`c$x-32*~^"aeiou"?x:_ / the solution
                    _ / lowercase input
                  x:  / store as 'x'
          "aeiou"?    / lookup input in "aeiou" else null
         ^            / is null?
        ~             / not
    -32*              / multiply boolean list by -32 (yields 0 or -32)
   x                  / subtract from x
`c$                   / cast back to characters

```

**Notes:**

* **-6 bytes** thanks to @ngn
> 2 votes

# Answer
# K4, 24 bytes

**Solution:**

```
.q.ssr/[;_v;v:"AEIOU"]@_

```

**Explanation:**

Replace each lowercase vowel with the uppercase equivalent.

```
.q.ssr/[;_v;v:"AEIOU"]@_ / the solution
                       _ / lowercase
                      @  / apply
.q.ssr/[;  ;         ]   / search/replace, iterate over vowels
            v:"AEIOU"    / store uppercase vowels as 'v'
         _v              / lowercase vowels

```
> 2 votes

# Answer
# Julia 49 bytes

## Try it!

```
f=l->map(c->in(c,"aeiou") ? c-32 : c,lowercase.(l))

```
> 2 votes

# Answer
# Pyth, 20 bytes

```
K"aeiou"smrd}d+KrK1w

```

Try it online!

# Explanation

```
                       w=input()
K"aeiou"               K="aeiou"
        s              "".join(
         m              map(
          r              lambda d:r(
           d              d,
             d             d
            }             in
               K           K
              +            +
                 rK1       K.upper())),
                    w    w)

```
> 2 votes

# Answer
# Python 3, 68 bytes

```
lambda s:''.join([p.upper()if p in'aeiou'else p for p in s.lower()])

```

Try it online!
> 2 votes

# Answer
# Zsh `--extendedglob`, 39

```
<<<${${(L)@}//(#m)[aeiou]/${(U)MATCH/}}

```

Try it Online

Code borrowed from the Zsh Manual, Globbing Flags
> 2 votes

# Answer
# Scala 3, ~~94~~ 59 bytes

59 bytes(Saved 35 bytes thanks to @movatica). Attempt This Online!

```
_.toLowerCase.map(c=>if("aeiou"contains c)c.toUpper else c)

```

---

94 bytes. Attempt This Online!

```
_.toLowerCase.map{case'a'=>'A';case'e'=>'E';case'i'=>'I';case'o'=>'O';case'u'=>'U';case c=>c}

```
> 2 votes

# Answer
# 05AB1E, ~~8~~ ~~7~~ 6 bytes

*-1 byte thanks to Kevin Cruijssen*

```
lžODu‡

```

Try it online!
> 1 votes

# Answer
# Charcoal, 14 bytes

```
⭆↧Ｓ⎇№aeiouι↥ιι

```

Try it online! Link is to verbose version of code. Explanation:

```
  Ｓ             Input string
 ↧              Lowercased
⭆               Map over characters and join
     aeiou      Literal string `aeiou`
    №           Count occurrences of
          ι     Current character
   ⎇            If non-zero
            ι   Current character
           ↥    Uppercased
             ι  Else current character
                Implicitly print

```
> 1 votes

# Answer
# `d`, 9 bytes

```
→d╧o╧╪0╨←

```

Uncompressed:

```
("aeiou":)Z

```

# Explanation

```
(           % Convert to lowercase
 "aeiou"    % All vowel strings
        :   % Duplicate
         )  % Convert to uppercase
          Z % Transliterate

```
> 1 votes

# Answer
# Batch, ~~118~~ 115 Bytes

3 bytes saved thanks to Neil

```
@Set o=%*
@For %%A in (A E I O U b c d f g h j k l m n p q r s t v w x y z)do @Call Set o=%%o:%%A=%%A%%
@ECHO(%O%

```

Explanation:

Uses `Call Set` to update variable during operation of For Loop in conjunction with Substring Modification: `VarName=%VarName:ToSub=SubValue%`.

Substring modification is not case-sensitive - case is determined using the defined For loop set `%%A in (set)`
> 1 votes

# Answer
# Python 3, 70 bytes

```
lambda s:''.join(l.upper()if l in'aeiouAEIOU'else l.lower()for l in s)

```

Try it online!
> 1 votes

# Answer
# Python 3, ~~85~~ 84 bytes

```
x=''
for i in input():
 if i in'aAeEiIoOuU':x+=i.upper()
 else:x+=i.lower()
print(x)

```

Try it online!

Pretty new to codegolf, so probably not the shortest solution

edit 1: one byte saved because of a space
> 1 votes

# Answer
# SML 65 bytes

Try it!

```
map(fn c=>if contains"AEIOUaeiou"c then toUpper c else toLower c)

```

This requires `open String` and `open Char`. If those are not allowed, then it would be 87 bytes (`String.map` `Char.contains` `Char.toUpper` `Char.toLower`).
> 1 votes

# Answer
# Funky2, 57 bytes

```
s=>s:gsub("."c=>ifc:match"[aeiou]"c:upper()elsec:lower())
```

Relatively simple solution, benefits from Funky2's relatively concise language.

Attempt This Online!
> 1 votes

# Answer
# Brachylog, ~~10~~ 9 bytes

```
ḷ{∈Ṿ&ụ|}ᵐ

```

Try it online!

-1 byte thanks to @DLosc.

### Explanation

```
ḷ             Lowercase the whole input
 {      }ᵐ    Map on each char of the input:
  ∈Ṿ             The char lowercased is in "aeiou"
     &ụ          Output the char uppercased
       |         Or do nothing

```
> 1 votes

# Answer
# APL (Dyalog Unicode), 17 bytes SBCS

```
1⎕C@(∊∘'aeiou')⎕C

```

Try it on APLgolf!

A tacit function that ports @Adam's Dyalog Extended solution into vanilla Dyalog APL. Makes use of the system function `⎕C` introduced in Dyalog 18.0 (hence, won't work in TIO).

```
1⎕C@(∊∘'aeiou')⎕C    ⍝ Tacit function.
               ⎕C    ⍝ Convert to lowercase. Then:
1⎕C                  ⍝ Convert to uppercase
   @                 ⍝ at the positions
    (∊∘'aeiou')      ⍝ that are part of the vowels.

```
> 1 votes

# Answer
# Excel VBA, ~~78~~ 75 bytes

Saved 3 bytes thanks to Taylor Raine because of course

```
t=LCase([A1]):For Each c in Split("A E I O U"):t=Replace(t,c,c,,,1):Next:?t

```

Code is run in the immediate window and uses the cell `A1` from the active sheet as it's input. The method is simple:

* Save the lowercase version of the input as `t`
* Save the vowels as `s`
* For each vowel, replace the lowercase version with the uppercase version
* Print the result
> 1 votes

# Answer
# Vim, 19 bytes

```
Vu:s/[aeiou]/\U&/g

```

Try it online!

### Explanation

```
Vu

```

Select the current line and lowercase it.

```
:s/

```

In the current line, replace...

```
[aeiou]/

```

a vowel character with...

```
\U&/

```

the uppercase version of itself...

```
g<nl>

```

for every match on the line.
> 1 votes

# Answer
# Vyxal, 7 bytes

```
ɽƛAß⇧;ṅ

```

Try it Online!

```
ɽƛAß⇧;ṅ # Takes the string as input
ɽ       # Lowercase the string
 ƛ   ;  # Map the characters in the string to...
  A     # Is character a vowel?
   ß⇧   # If truthy, uppercase the letter
      ṅ # Join by nothing

```
> 1 votes

# Answer
# Arturo, 43 bytes

```
$=>[replace lower&split"aeiou"split"AEIOU"]

```

Try it
> 1 votes

# Answer
# Vyxal `s`, 35 bitsv2, 4.375 bytes

```
⇩ƛAß⇧

```

Try it Online!

Bitstring:

```
11010011100001101111110111101101010

```

*minus 6 bits thanks to pacmanboss256*

Posted as a separate answer because a) vyncode isn't a golfing suggestion and b) it's different enough to be its own answer - it's not a byte shave from the other answer.

## Explained (old)

```
ƛA[⇧|⇩
ƛ       # To each character:
 A[     #   if it is a vowel:
   ⇧    #     uppercase
    |   #   else:
     ⇩  #     lowercase

```
> 1 votes

# Answer
# Thunno 2 `J`, 8 bytes

```
ıDṃh?R:L

```

#### Explanation

```
ıDṃh?R:L  # Implicit input
ı         # Map over each character
 D        # Duplicate the current character
  ṃh?     # If it's a vowel:
     R    #  Uppercase it
      :   # Otherwise:
       L  #  Lowercase it
          # Implicit output, joined into a string

```
> 1 votes

# Answer
# Swift, ~~95~~ 88 bytes

```
let c={($0+"").map{"aeiouAEIOU".contains($0) ?$0.uppercased():$0.lowercased()}.joined()}

```
> 1 votes

# Answer
# , 45 bytes

```
function(s)chartr('aeiou','AEIOU',tolower(s))

```

Try it online!
> 1 votes

# Answer
# Pip, 9 bytes

```
LCaRXVUC_

```

Attempt This Online!

### Explanation

```
LCaRXVUC_
LCa        ; Lowercase the input string
   R       ; Replace
    XV     ;  any lowercase vowel
      UC_  ;  with itself uppercased

```
> 1 votes

# Answer
## JS 63 .. 59 Bytes

Hello this is how you can create it in JS using one line of code.

### Code:

```
f=s=>s.toLowerCase().replace(/[aeiou]/g,v=>v.toUpperCase())

```

### Test Cases:

1. **Basic Test Cases**:

* Input: `"Hello"`
        + Expected Output: `"hEllO"`
    * Input: `"Stack Exchange"`
        + Expected Output: `"stAck ExchAngE"`
    * Input: `"abcdefghijklmnopqrstuvwxyz"`
        + Expected Output: `"AbcdEfghIjklmnOpqrstUvwxyz"`
2. **Edge Cases**:

* Input: `""` (Empty string)
        + Expected Output: `""` (Empty string)
    * Input: `"12345"` (No vowels)
        + Expected Output: `"12345"`
    * Input: `"AEIOU"` (All vowels)
        + Expected Output: `"AEIOU"` (All uppercase)
3. **Case Insensitivity Test**:

* Input: `"HeLLoWorLD"`
        + Expected Output: `"hEllOwOrLD"`
4. **Special Characters Test**:

* Input: `"@#$%"`
        + Expected Output: `"@#$%"` (No vowels, no change expected)
    * Input: `"hello$world"`
        + Expected Output: `"hEllO$wOrld"` (Vowels in the middle of the string)
5. **Long String Test**:

* Input: `"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."`
        + Expected Output: `"lOrEm IpsUm dOlOr sIt AmEt, cOnsEc tEtUr AdIpIscIng ElIt. sEd dO EIUsmOd tEmpOr IncIdIdUnt Ut lAbOrE Et dOlOrE MAgnA AlIqUA."`
6. **Performance Test**:

* Input: `"a" repeated 10^6 times (a million times)`
        + Expected Output: `"A"` repeated 10^6 times
    * Input: `"abcdefghijklmnopqrstuvwxyz"` repeated 10^4 times
        + Expected Output: `"AbcdEfghIjklmnOpqrstUvwxyz"` repeated 10^4 times
7. **Random Test Cases**:

* Input: `"hElLo!"`
        + Expected Output: `"hEllO!"` (Only 'e' should be capitalized)
    * Input: `"HeLlO 123"`
        + Expected Output: `"hEllO 123"` (Only vowels should be capitalized)
    * Input: `"rAnDoMT3XT"`
        + Expected Output: `"rAndOmt3xt"` (Only 'a' and 'o' should be capitalized)

### Try it Online:

```
f=s=>s.toLowerCase().replace(/[aeiou]/g,v=>v.toUpperCase())

// Test Cases
function runTest(input, expectedOutput) {
    const output = f(input);
    console.log("Input:", input);
    console.log("Expected Output:", expectedOutput);
    console.log("Actual Output:", output);
    if (output === expectedOutput) {
        console.log("Test Passed!");
    } else {
        console.log("Test Failed!");
    }
    console.log("-------------------------");
}

// Basic Test Cases
runTest("Hello", "hEllO");
runTest("abcdefghijklmnopqrstuvwxyz", "AbcdEfghIjklmnOpqrstUvwxyz");

// Edge Cases
runTest("", "");
runTest("12345", "12345");
runTest("AEIOU", "AEIOU");

// Case Insensitivity Test
runTest("HeLLoWorLD", "hEllOwOrld");

// Special Characters Test
runTest("@#$%", "@#$%");
runTest("hello$world", "hEllO$wOrld");

// Long String Test
runTest("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", "lOrEm IpsUm dOlOr sIt AmEt, cOnsEctEtUr AdIpIscIng ElIt. sEd dO EIUsmOd tEmpOr IncIdIdUnt Ut lAbOrE Et dOlOrE mAgnA AlIqUA.");

// Performance Test
runTest("a".repeat(1e6), "A".repeat(1e6));
runTest("abcdefghijklmnopqrstuvwxyz".repeat(1e4), "AbcdEfghIjklmnOpqrstUvwxyz".repeat(1e4));

// Random Test Cases
runTest("hElLo!", "hEllO!");
runTest("HeLlO 123", "hEllO 123");
runTest("rAnDoMT3XT", "rAndOmt3xt");
```
> 1 votes

# Answer
# Lexurgy, 111 bytes

Simple replacement

```
a:
{a,e,i,o,u,B,C,D,F,G,H,J,K,L,M,N,P,Q,R,S,T,V,W,X,Y,Z}=>{A,E,I,O,U,b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z}

```
> 0 votes

# Answer
# Lua, 64 bytes

```
print(((...):lower():gsub('[aeiou]',load'return(...):upper()')))

```

Try it online!
> 0 votes

# Answer
# Vyxal 3 `s`, 5 bytes

```
ʀƛA¿ɾ

```

Try it Online!

lowercase the entire string then uppercase the vowels
> 0 votes

# Answer
# Gema, 36 characters

```
/[aeiou]/=@upcase{$0}
?=@downcase{?}

```

Sample run:

```
bash-5.2$ gema '/[aeiou]/=@upcase{$0};?=@downcase{?}' <<< 'Hello World'
hEllO wOrld

```

Try it online!
> 0 votes

# Answer
# Swift, 125 bytes

Short version:

```
func c(_ t:String)->String{return t.lowercased().map({String($0)}).map({"aeiou".contains($0) ?$0.uppercased():$0}).joined()}

```

Verbose version:

```
func c2 (_ t: String) -> String {
    let s = t.map({String($0).lowercased()})
    let lv = ["a", "e", "i", "o", "u"]

    let r = s.map { l in
        lv.contains(l) ? l.uppercased() : l
    }.joined()

    return r
}

```
> 0 votes

# Answer
# APL(NARS), 45 chars

```
{⍵∊⎕A∼'AEIOU':⎕a[⎕A⍸⍵]⋄⍵∊'aeiou':⎕A[⎕a⍸⍵]⋄⍵}¨

```

test & how to use:

```
      f←{⍵∊⎕A∼'AEIOU':⎕a[⎕A⍸⍵]⋄⍵∊'aeiou':⎕A[⎕a⍸⍵]⋄⍵}¨
      f 'Hello World'
hEllO wOrld

```
> 0 votes

# Answer
# Uiua SBCS, 14 bytes

```
¯⍜▽¯∊,"AEIOU"⌵

```

Try it!

0.9.0 recently extended `abs` and `negate` to work on characters, making this much easier.

```
¯⍜▽¯∊,"AEIOU"⌵
             ⌵  # uppercase the input
    ∊,"AEIOU"   # mask of vowels
 ⍜▽¯            # swap case at indices given by the mask
¯               # swap case

```
> 0 votes

# Answer
# YASEPL, ~~155~~ ~~147~~ 145 bytes

```
=2)"aeiouAEIOU"±""=1'=i=l®1`1=k=f=m¥i,1`9!y¥f,2!m}7,y,8!k$`8!f+}2,10,9=j`2!j+!q$j»}7,m,2`3!j}1,90,5}2,65,5!f$j+32|6`5!f$j`6!k[7!f-32`7!f›!i+}2,l

```

i mistakenly uploaded this without testing my code. whoopsies, heres a fixed version
> 0 votes

# Answer
# Python 3, 82 bytes

```
f=lambda c:c.upper()if c in 'aeiou'else c.lower();lambda s:''.join(map(f,list(s)))

```
> -1 votes

---
Tags: code-golf, string
---


title: µUnitDC: A unit-aware RPN calculator

text:
# Question
Title: µUnitDC: A unit-aware RPN calculator
# Background

This challenge is based on a personal project I did, UnitDC. This challenge is a super-miniaturized version of UnitDC.

# Challenge

Please write a simple unit-aware calculator that evaluates a sequence of positive integers, units and operators in RPN (postfix) notation, while checking whether the units are compatible with each other.

# Tokens

## Numbers

Numbers are all positive integers in the form "\[0-9\]+".

## Units

Pops a value off the stack and set the unit of that quantity. For simplicity, units are represented by a single lower-cased letter. All letters are considered base units. Additionally it is guaranteed that the top of stack will have a quantity with no unit when the unit token is encountered.

## Operators

For simplicity there are only three operators, +, * and /. All pop 2 values off the stack and push one back. It is guaranteed that the stack will not underflow.

* For the + operator, you should check whether the two operands are of the same unit, if not you should report error.
* For the * and / operator, you should update the units accordingly (sum up or subtract the exponents of rhs to lhs). All divisions are guaranteed to be whole.

# I/O

You can choose take Input in any of the following forms, from STDIN, function arguments or a memory location:

* A string of tokens, separated by space.
* An array of token strings.

At the end of the evaluation, print to STDOUT or return as value the contents of the stack (top to bottom or bottom to top) in one of the following forms:

* An array of *quantities*.
* A string concatenation of *quantities*, separated by space.

where *quantity* is a string represented by the regex "^\d+(\[a-z\](-?\d+))\*$". The notation is simply the concatenation of the number, the letter for each unit and then its exponents. For example "1m2s-3" means \\$1m^2s^{-3}\\$. Valid representations include "1" "1g1" "1m1s-2". "1a0" is INVALID (no zero exponents). Ordering of the units are not important.

If an error is encountered during the evaluation, either output '\*' and nothing else, or crash, or exit with a non zero code.

# Examples

```
I: 1
O: 1

I: 1 s
O: 1s1

I: 1 s 2 m +
O: *

I: 1 m 1 s / 1 m 1 s / +
O: 2s-1m1

I: 1 s 2 s * 1 s
O: 2s2 1s1

I: 1 s 1 s /
O: 1
Note: *1s0 is not acceptable here*

I: 1 m 1 s / 2 m 2 s / +
O: 2m1s-1

I: 1 s 1 s / 1 +
O: 2

I: 1 m 1 m / s
S: 1s1

I: 5 s 2 *
S: 10s1

I: 5 s 2 +
O: *

```

# Reference Implementation (Rust)

This is a small reference implementation I made, this program accepts multiple lines of inputs but you only need to accept one input.

Try it online!

# Related

Similar questions that may be helpful:

# Scoring

This is code-golf, shortest code wins!

# Answer
> 6 votes
# K (ngn/k), ~~134~~ ~~124~~ 117 bytes

```
{,//$x,(!y),'.y}.'|(){(,$[43=*y-*|&/=/h;E;1=C;**x;^[_%;.y].|*'h],(&~b)_b:(y!C;*|(1-3!*y)/h:C#x)2=C),(C:3!"0a"'*y)_x}/

```

Try it online! Input and output as list of strings, `t` converts between that and space separated format.

# Answer
> 3 votes
# JavaScript (Node.js), ~~797~~ 795 bytes

```
Z=require('util');O=Object;N="length";A=u=>O.fromEntries([...u.matchAll(/([a-zA-Z])(-?\d+)/g)].map(_=> _.slice(1)));B=u=>{s="";e=O.entries(u);for(i=0;i<e[N];i++){s+=e[i][0]+e[i][1]}return s};D=T=>{S=[];U=[];p=/[+*\/]/;for(t of T){if(/\d+/.test(t[0])||/\d+/.test(t[1])&&(t[0]=="-"||t[0]=="+")){S.push(t)}else if(p.test(t)){let[r,l]=[S.pop(),S.pop()];[h,H]=[U.pop(),U.pop()];if(H){f=A(h);g=A(H);m=1;if(t=="+"){if(Z.isDeepStrictEqual(g,f)){n=B(g)}else{return'*'}}if(t=="/"){m=-1}L=O.keys(g);P=O.keys(f);z={};for(i=0;i<L[N];i++){k=L[i];if(k in f){y=+g[k]+m*+f[k];y!=0?(z[k]=y):0}else{z[k]=+g[k]}}for(i=0;i<P[N];i++){k=P[i];if(!(k in z||k in g)){z[k]=m*+f[k]}}n=B(z);n!=""?U.push(n):0}S.push(""+eval(l+t+r))}else{if(t[N] > 1){U.push(t)}else{U.push(t+1)}}}return S.map((E,I)=> E+(U[I]||"")).join(" ")}

```

Try it online! Input is as an array of token strings passed to `D`. Output is to STDOUT. There's probably a shorter way, but this is what I've got (and JS is not a golfing language).

# Answer
> 3 votes
# JavaScript (Node.js), 209 bytes

```
p=>p.map(n=>a.push(y=+n?[+n,...Buffer(36)]:n<0+a.pop()?a.pop().map((o,i)=>(m=y[i],i)?n<'+'?o+m:n<'/'?o-m?E:o:o-m:eval(o+n+m)):(y[parseInt(n,36)]=1,y)),a=[])&&a.map(x=>x.reduce((x,v,i)=>v?x+i.toString(36)+v:x))

```

Attempt This Online!

Input array of tokens, output array of values or throw error.

# Answer
> 2 votes
# JavaScript (ES6), 263 bytes

```
s=>s.replace(/\S+/g,v=>v>{}?s[0][1]=[[v,1]]:s=[[(u=[])|v||([[y,q],[x,u],...s]=s,v+1|0?e|=u+''!=q:q.map(([U,e])=>(u.find(o=>o[0]==U)||u.push(o=[U,0])&&o)[1]+=v<"/"?e:-e),eval(x+v+y)),u.filter(o=>o[1]).sort()],...s],e=s=[])|e?"*":s.reverse().join` `.split`,`.join``

```

Try it online!

# Answer
> 2 votes
# Uiua, ~~204 192~~ 178 characters

*-12: removed error handling and output reversal and redundant spaces that the formatter always puts back in.*
*-14: used "uiuisms" page to golf character range, use `content ◇` instead of unbox, and golf creation of the stack.*

```
P←⊙:⊙⊙(°⊂°⊂)°⊂°⊂◌
i←⊙(⟨⊂⊂⊓×+P|⊂⊂⊓+⟜(⍤""≍)P|◌|◌|◌|⊂⊂⊓÷-P|⟨⊂+⊙°⊂=□⊙,|⊂×⊙(=□" ",)⋕⟩⍣(1◌⋕)0.⟩↧6/+-@*.):°□°⊂
f←↘1/◇⊂♭∵(□⟨""◌◌|⊂:⊓°⋕°□⟩≠0.)⊙↯:△.◌⍥i⧻.⊙(↯0⊚⧻.⊂□" "◴⊏⊚∵◇(≍[1]×⊓≥≤@a,@z).).

```

commented version with tests golfed version

```
P ← ⊙:⊙⊙(°⊂°⊂)°⊂°⊂ # pop 2 from small stack and separate number and units
i ← ⊙(
  ⟨
    ⊂⊂⊓×+P◌        # times
  | ⊂⊂⊓+⟜(⍤"*"≍)P◌ # plus
  | ◌
  | ◌
  | ◌       # other characters
  | ⊂⊂⊓÷-P◌ # divided by
  | ⟨
      ⊂+⊙°⊂=□⊙,    # letter: add one to corresponding cell in top of small stack
    | ⊂×⊙(=□" ",)⋕ # number: push unitless number to small stack
    ⟩⍣(1◌⋕)0.
  ⟩↧6/+-@*.                    # ---the difference from star, or 6 if it's a number or letter
):°□°⊂                         # process one token from the input
d ← ⊂□" "◴⊏⊚∵◇(≍[1]×⊓≥≤@a,@z). # construct the label array
f ← (
  ◌⍥i⧻.⊙(↯0⊚⧻.d).            # setup the label and small stack
  ∵(□⟨""◌◌|⊂:⊓°⋕°□⟩≠0.)⊙↯:△. # append unit to each number in the small stack
  ↘1/◇⊂♭                     # final concatenation
)

```

Input is a boxed array (`{}`) of token strings like in the example above, or there is an extra string parsing function in the formatted version link.

After and before an Iteration of i, there is on the stack (bottom to top):

* The label array, looking like `{" " "m" "s"}` where the first column is always space and represents the number part,
* The small stack array, where its rows are its entries and they are as wide as the label array, and the columns correspond to the labels in the label array,
* the remaining input.

# Answer
> 1 votes
# Charcoal, ~~123~~ 116 bytes

```
Ｆ⪪Ｓ ¿Σι⊞υ⁺⟦Ｉι⟧Ｅβ⁰¿№βι§≔§υ±¹⊕⌕βι¹«≔⊟υζ≔⊟υη⊞υ∧∨⬤∧ζη∨¬λ⁼κ§ζλ⁻+ιＥ∧ζη⎇λ⁻κ×§ζλ⊖﹪℅ι³§⟦×κ§ζλ⁺κ§ζλ÷κ§ζλ⟧℅ι»Ｅυ⭆∨ι*⎇μ⎇λ⁺§β⊖μλωλ

```

Try it online! Link is to verbose version of code. Since the whole stack is output, I've effectively included several test cases in the link. Explanation:

```
Ｆ⪪Ｓ

```

Split the input on spaces and loop over the resulting tokens.

```
¿Σι⊞υ⁺⟦Ｉι⟧Ｅβ⁰

```

If this token is a positive integer, then push its value with zero exponents for all letters.

```
¿№βι§≔§υ±¹⊕⌕βι¹

```

Otherwise, if this token is a letter, then set the exponent for that letter to `1` for the latest value.

```
«

```

Otherwise:

```
≔⊟υζ≔⊟υη

```

Retrieve the two arguments.

```
⊞υ∧∨⬤∧ζη∨¬λ⁼κ§ζλ⁻+ιＥ∧ζη⎇λ⁻κ×§ζλ⊖﹪℅ι³§⟦×κ§ζλ⁺κ§ζλ÷κ§ζλ⟧℅ι

```

If the arguments are compatible or the operations is not sum, calculate the product, sum and quotient of the two arguments, selecting according to the ordinal of the token. (In the case of the exponents, the ordinal modulo `3` is decremented and multiplied by the second exponent, and this is subtracted from the first exponent.)

```
»Ｅυ⭆∨ι*⎇μ⎇λ⁺§β⊖μλωλ

```

For each value on the stack, concatenate its value with any non-zero exponents, unless the value was invalid, in which case output a `*`.

---
Tags: code-golf, interpreter
---