# Question
Title: Get a random n digit number with distinct digits and first not a 0
I read this question and thought it would make a nice challenge.

## Task

Give an input `0<n<10` generate a random number with

* exactly n digits
* the first not a `0`
    + so `f(n)>10**(n-1)-1`
* distinct digits

## Winning criteria

This is so shortest code wins.

## Random

I mean evenly distributed random. So from the view of the program each possible number has the same chance. If the language you're writing in has a weird random number generator, it's okay to use that one.

## Example

The list of values to randomly select from for `n=2` is:

```
[10, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98]

```

# Answer
# Python 2, 77 bytes

```
from random import*
r=range(10)
while[1]>r:shuffle(r)
print`r`[1:input()*3:3]

```

Try it online!

Shuffles the list of 10 digits until it doesn't start with 0, then makes a number with the first `n` digits listed.
> 17 votes

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

```
{~lℕ₁≜≠}ᶠṛ

```

Try it online!

As usual for Brachylog, this is a function submission. The TIO link above has been given a command-line argument to make the function into a full program.

I had to add an extra byte from the first version of this, changing  to `ℕ₁`, to disallow the output 0 (something that's now been clarified).

## Explanation

```
{~lℕ₁≜≠}ᶠṛ
{      }ᶠṛ  Pick a random value with these properties:
 ~l           it has length equal to the input;
   ℕ₁         it's a positive integer;
     ≜        it's a specific value (not a constraint);
      ≠       all its elements (digits in this case) are different.

```

Fairly inefficient, because the interpreter generates a list of all possible values and then picks one at random (that's what `ᶠṛ` means; Brachylog didn't have a "pick a random solution" option at the time this question was asked).

Some comments on the labelization here: if the  is omitted, the section within the braces only produces one value, a constraint representing numbers with the property we want; picking a random result therefore gives us the constraint, and the interpreter outputs the minimum absolute value that meets the constraint (1, 10, 102, 1023, 10234, etc.), which is not what we want. We thus have to force it to construct the list via an explicit labelization.

Most Prolog implementations I've seen have a builtin to find a random result matching a constraint, but typically not with uniform probability; Brachylog didn't have one, though (one got added in response to this challenge, but obviously I can't use it due to loophole rules). If it did, and if it happened to give uniform probability on this problem, this program would just be `~lℕ₁≠` followed by that builtin, for a likely length of 6 bytes.

# Brachylog, 8 bytes, in collaboration with @Fatalize

```
~lℕ₁≠≜ᶠṛ

```

Try it online!

This is the sort of genius low-level trick that only makes sense with the way Prolog does things, and doesn't make much sense when described mathematically.

As before, `~lℕ₁≠` builds up a value that describes a constraint ("length equal to the input, natural number, all elements different"). Then `≜ᶠ` generates all possible values that meet the constraint. The point here is that with Brachylog's evaluation sequence, no actual choices are made until the  appears, so the "find all solutions" operation  need apply to nothing but the "specific value that fulfils a constraint" operation . That means there's no need for a `{…}` to select its scope, saving 2 bytes.
> 10 votes

# Answer
# Jelly, 9 bytes

```
⁵*ṖQL$€MX

```

**Try it online!** (won't work at TIO for **n \> 6** due to the inefficiency of the implementation)

or an alternative implementation of the same thing:

```
⁵*ṖQL$ÐṀX

```

### How?

This is pretty sneaky, and very inefficient! Jelly does some useful things implicitly when an atom expects a list but receives an integer (this is by design).
This code uses a couple of these useful implicit actions:

* The monadic atom , "pop", when called with an integer input implicitly makes a range from which to pop, so an input of **n** first makes **\[1, 2, ..., n\]**, then pops, yielding **\[1, 2, ..., n-1\]**.
* The monadic atom `Q`, "de-duplicate" or "unique", when called with an integer input implicitly makes a decimal list to de-duplicate, so an input of **n** where:
**n = dk-1×10k-1 \+ dk-2×10k-2 \+ ... + d1×10 + d0**
first makes
**\[dk-1, dk-2, ... ,d1, d0\]**
and then yields the unique values by first appearance.
So, for example, **n = 5835518** would yield **\[5, 8, 3, 1\]**.

Furthermore the monadic atom `M`, "maximal element indexes", returns the indexes of the maximal items from a list, this saves **two** bytes over the far more obvious alternative of testing for equality with the input and finding truthy indexes, `⁵*ṖQL$€=⁸TX`, or `⁵*ṖðQL⁼ð€TX`

```
⁵*ṖQL$€MX - Main link: n                       e.g. 2
⁵         - literal 10
 *        - exponentiate: 10^n                      100
  Ṗ       - pop (make range 1 to 10^n, then pop)    [1  ,2  ,...,21   ,22 ,23   ,...,97   ,98   ,99]
     $€   - last two links as a monad for €ach:
   Q      -   unique (makes a decimal list first)   [[1],[2],...,[2,1],[2],[2,3],...,[9,7],[9,8],[9]]
    L     -   length                                [1  ,1  ,...,2    ,1  ,2    ,...,2    ,2    ,1  ]
       M  - indexes of maximal elements             [        ...,21       ,23,   ...,97   ,98       ]
          -                                         - i.e. all n-digit numbers with n-distinct digits.
        X - pick a random element from that list

```

This is all quite quite inefficient, both in time and memory: first a list of **10n** integers is made and one is discarded, then for each of these a list of **n** integers (not some fancy 4-bit object or enum) is made and then de-duplicated. This de-duplication has a completely list-based implementation (no sets, sorted-sets, or dictionaries are involved under-the-hood, each digit is checked for existence in the list that eventually gets output).
Offline **n = 7** uses ~0.5GB and takes ~25 seconds, while **n = 8** uses ~4GB and takes ~5 minutes - I have not bothered running **n = 9** as I only have 16GB ram (I guess it would take ~45 minutes).

The alternative implementation just uses the built-in `ÐṀ` quick to filter-keep minimal (which here just adds a little overhead in management for the same byte-count).
> 8 votes

# Answer
## JavaScript (ES6), ~~72~~ ~~71~~ ~~70~~ 69 bytes

```
f=(x,y="")=>x?!y.match(z=Math.random()*10|0)&&y|z?f(x-1,y+z):f(x,y):y

```

This is a recursive function that takes in the number of digits **x**. The second parameter **y**, initially set to the empty string, keeps track of the number as we generate it digit by digit.

First we generate a random digit **z** with `Math.random()*10|0`. Now, we want to check that the **y** does not contain **z**, and that **y** and **z** are not both **0**.

We can calculate the first condition with `!y.match(z)`. `y.match(z)` returns an array (always truthy) if **y** contains **z**, **null** (falsy) otherwise; the `!` converts this to a boolean and inverts it.

The second condition is checked with `y|z`. Although **y** is a string, JS implicitly converts it to an integer when using `|`. This is a positive integer if **y** already contains digits, **0** otherwise. The net result is that `y|z` returns **0** iff **y** is empty and **z** is **0**, or a positive integer otherwise.

If both of these conditions are true, then we append the digit to **y**, decrement **x**, and start the process over again. Otherwise, we simply return to the beginning and hope that the next random digit works. When **x** reaches **0**, we simply return the empty string to end the recursion.

---

Previous version:

```
f=(x,y)=>x?~y>>(z=Math.random()*10|0)&1&&y|z?z+f(x-1,y|1<<z):f(x,y):""

```

This is a recursive function that takes in the number of digits. The initially undefined second parameter, **y**, is a 10-bit lookup table telling us which digits we already have, conveniently stored as an integer.

First we generate a random digit **z** with `Math.random()*10|0`. Now, we want to check that the **z**'th least significant bit of **y** is not set, and that **y** and **z** are not both **0**.

We can calculate the first condition with `~y>>z&1`; invert **y**, shift it **z** bits to the right, and take only the least significant bit. This gives **1** if we have not yet generated the digit in question, or **0** otherwise.

The second condition was initially pretty difficult to figure out (I tried using `y/z` at first to generate `NaN` if they're both 0), but at some point I realized that simply `y|z` would do the trick. The result is **0** iff both **y** and **z** are **0**; a positive integer otherwise.

If both of these conditions are true (`~y>>z&1&&y|z`), then we generate the rest of the number and prepend **z**. The rest of the number is generated by calling the function again with `x-1` and `y|1<<z` (**y**, but with the bit at index **z** set to **1**). When **x** reaches **0**, we simply return the empty string to end the recursion.
> 7 votes

# Answer
# Jelly, 11 bytes

```
9Xœ|⁵ḶẊ¤ḣ¹Ḍ

```

Try it online!

### How it works

```
9Xœ|⁵ḶẊ¤ḣ¹Ḍ  Main link. Argument: n

9            Set the return value to 9.
 X           Pick; pseudo-randomly select an integer from [1, ..., 9].
       ¤     Combine the three preceding links into a niladic chain.
    ⁵          Yield 10.
     Ḷ         Unlength; yield [0, ..., 9].
      Ẋ        Shuffle; pseudo-randomly select a permutation of [0, ..., 9].
  œ|         Multiset OR; prepend the selected integer to the selected permutation
             and remove the second occurrence of the first element.
         ¹   Identity; yield n.
        ḣ    Head; keep the first n digits of the permutation.
          Ḍ  Undecimal; convert from base 10 to integer.

```
> 7 votes

# Answer
# Python 2, ~~89~~ ~~81~~ 80 bytes

```
from random import*
lambda n:choice([i for i in range(10**n)if`set(`i`)`[5*n:]])

```

**Try it online**
> 5 votes

# Answer
# R, 45 Bytes

```
k=0
i=scan()
while(!k[1])k=sample(0:9)[1:i]
k

```
> 5 votes

# Answer
# ClojureScript, ~~81~~ 79 bytes

```
#(let[a(subvec(shuffle(range 10))0 %)](if(=(a 0)0)(recur %)(int(apply str a))))

```

This is an anonymous function, so you have to use it like this:

```
(#(...) {arguments})

```

Where you replace `{arguments}` with your arguments.

You can try the code here (ClojureScript REPL).

Thanks `@cliffroot` for shaving off 2 bytes!

---

## Expanded code:

```
(defn random-digits [n]
  (let [num-vector
        (subvec
          (shuffle (range 10))
          0 n)]
    (if (= (num-vector 0) 0)
      (recur n)
      (int (apply str num-vector)))))

```

---

## Explanation:

I'm going to go through the lines one by one, using an example input of `8`.

---

```
(defn random-digits [n] ...)

```

Pretty simple, this defines the function `random-digits` with one argument, called `n`. In my answer I used an anonymous function (`#(...)`), to save bytes.

---

```
(let [num-vector ...] ...)

```

Let's examine inside the `let`, from inside out:

```
(shuffle (range 10))

```

In ClojureScript (and Clojure), `(range n)` is similar to Python's `range(n)`: it gives you a list with every number from `0` to `n - 1` (`9` in this case).

`shuffle` takes a list, and returns a vector (which is slightly different from a list) with all of its elements shuffled. So, using our example, we get something like this:

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

```

---

```
(subvec {see above} 0 n)

```

`(subvec vector start end)` takes a vector (only a vector), and returns a vector which has all the elements from index `start` to `end`. In this case, we're taking elements from the `0`th element to the argument given to `random-digits`. If we apply that to our example, we get:

```
[1 0 8 3 6 7 9 2]

```

---

```
(if (= (num-vector 0) 0)
  (recur n)
  (int (apply str num-vector)))

```

This `if` statement checks if the first element of `num-vector` is a `0`.

If it is `0`, then we call the function again, with the argument `n`, using `recur`.

If it isn't `0`:

---

```
(int (apply str num-vector))

```

`(apply function list)` takes a list, and spits them into the function as arguments. For example:

```
(apply + [2 3 4])

```

Turns into:

```
(+ 2 3 4)

```

Which equals `9`.

`(str items)` turns every item in `items` into a string, and then concatenates them. `int` converts anything to an integer. So if we apply this to our example, we get:

```
   (int (apply str [1 0 8 3 6 7 9 2]))
=> (int (str 1 0 8 3 6 7 9 2))
=> (int "10836792")
=> 10836792

```

Which is our final answer.
> 5 votes

# Answer
# Bash + GNU utils, 46

```
seq 1e$[$1-1] 1e$1|egrep -v '(.).*\1'|shuf -n1

```

Try it online.

This takes a long time for larger *n* \- about 30s for n=7, and increasing 10 times for each increment, so probably 8-9 hours for n=10.
> 3 votes

# Answer
# Java 10, ~~150~~ ~~147~~ ~~145~~ ~~134~~ ~~132~~ 110 bytes

```
n->{var r="";for(int l,x;(l=r.length())<n;x*=Math.random(),r+=(l<1?x>0:!r.contains(""+x))?x:"")x=10;return r;}

```

-2 bytes thanks to *@TheLethalCoder*
-2 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
n->{                    // Method with integer parameter and String return-type
  var r="";             //  Result-String, starting empty
  for(int l,x;          //  Temp integers
      (l=r.length())<n  //  Loop until the length of the String is equal to the input:
      ;                 //    After every iteration:
       x*=Math.random(),//     Pick a random digit
       r+=              //     Append to the result-String:
          (l<1?         //      If the String is empty:
            x>0         //       Make sure the first random digit is not 0
           :            //      Else (the String is not empty):
            !r.contains(""+x))
                        //       Check that the String doesn't contain this digit yet
          ?             //      And if that's truthy:
           x            //       Append the random digit
          :             //      Else:
           "")          //       Leave the String the same by appending an empty String
    x=10;               //   (Re)set `x` to 10 for the next random digit
  return r;}            //  Return the result-String

```
> 3 votes

# Answer
# APL (Dyalog), ~~27~~ ~~19~~ 17 bytes

Requires `⎕IO←0` which is default on many systems.

```
10⊥⊢↑{?⍨10}⍣{×⊃⍺}

```

Try it online!

Shuffles the digits until valid:

`10⊥` decode from base-10 digits to regular number,

the n

first elements of

`{``}⍣{``}` repeating the function…
`?⍨10` shuffle the first ten positive integers
until…
`⊃⍺` the first digit of the last attempt
`×` is positive
> 3 votes

# Answer
# PHP, 67 Bytes

Online Version

All versions based of shuffle the digits from 0-9

```
for($a=range(0,9);!$a[0];)shuffle($a);for(;$i<$argn;)echo$a[+$i++];

```

71 Bytes

```
for($s="0123456789";!$s[0];)$s=str_shuffle($s);echo substr($s,0,$argn);

```

73 Bytes

```
for($a=range(0,9);!$a[0];)shuffle($a);echo join(array_slice($a,0,$argn));

```
> 2 votes

# Answer
# Perl 6, 44 bytes

```
{(->{+[~] (^10).pick($_)}...*>9 x$_-1).tail}

```

Try it

## Expanded:

```
{  # bare block with implicit parameter ｢$_｣
  (

    ->{  # pointy block lambda with no parameters

      +                # turn the following into a numeric
      [~]              # concatenate the following

        (^10).pick($_) # grab $_ digits at random from 0..9
    }

    ...                # keep doing that until

    * > 9 x $_-1       # one of them is big enough

  ).tail # return the last one (only valid one)
}

```
> 2 votes

# Answer
# MATL, 15 bytes

```
`4Y2GZr1)48=]8M

```

Try it at MATL Online!

### Explanation

```
`        % Do...while
  4Y2    %   Push predefined literal '0123456789'
  G      %   Push input n
  Zr     %   Random sample of n unique characters from that string
  1)     %   Pick the first
  48=    %   Is it 48? This is the loop condition
]        % End. If top of the stack evaluates to true: next iteration
8M       % Push the latest random sample. Implicitly display

```
> 2 votes

# Answer
# Jelly, 12 bytes

```
9×!X+!Œ?’ḣƓḌ

```

Currently one byte behind my other Jelly answer, but I really like this one.

Try it online!

### How it works

```
9×!X+!Œ?’ḣƓḌ  Main link. No arguments.

9             Set the argument and the return value to 9.
  !           Yield 9!
 ×            Compute 9 × 9!.
   X          Pick; pseudo-randomly select an integer j from [1, ..., 9 × 9!].
     !        Yield 9!
    +         Compute k := j + 9!.
              The result will belong to [9! + 1, 10!].
      Œ?      Get the permutation P of R := [1, ..., r], with minimal r, such that
              P is the lexicographically k-th permutation of R.
              Since k belongs to [9! + 1, 10!], r = 10 and this generates a per-
              mutation between [2,1,3,4,5,6,7,8,9,10] and [10,9,8,7,6,5,4,3,2,1].
        ’     Subtract 1 from all integers in P.
          Ɠ   Read an integer n from STDIN and yield it.
         ḣ    Head; keep the first n digits of the permutation.
           Ḍ  Undecimal; convert from base 10 to integer.

```
> 2 votes

# Answer
# 05AB1E, ~~9~~ ~~7~~ ~~10~~ 9 bytes

```
°L¨ʒÙgQ}Ω

```

Very slow for larger \\$n\\$.

Try it online or verify some more test cases.

~~+3~~ +2 bytes because I missed the requirement of an evenly distribution..

**Original invalid 7 byter solution:**
(can output all random outputs, but not evenly distributed)

```
žh.rïI£

```

Try it online or verify some more test cases.

**Explanation:**

```
°           # Push 10 to the power of the (implicit) input-integer
 L          # Push a list in the range [1, 10**input]
  ¨         # Remove the last value to make the range [1, 10**input)
   ʒ        # Filter this list by:
     g      #  Where the amount
    Ù       #  of the unique digits
      Q     #  is equal to the (implicit) input-integer
       }Ω   # After the filter: pop and push a random element of the list
            # (after which it is output implicitly as result)

žh          # Push the builtin string "0123456789"
  .r        # Randomly shuffle it
    ï       # Cast it to an integer to remove any potentially leading 0s
     I£     # Only leave the first input amount of digits
            # (after which it is output implicitly as result)

```
> 2 votes

# Answer
# , 6 bytes

To make this work, you need an extra operand (e.g. `""`). After providing it, this W script would ignore this operand.

```
"▬←l╟B

```

Uncompressed:

```
U=a^(Xg

```

## Explanation

```
  a     % Take a single input
   ^    % 10 ** input
    (   % Decrement by 1 so that special cases like 100 would be avoided
     X  % Filter out all items in the implicit range 1 to operand
U       % Uniquify (the current item)
        % This also implicitly converts the current item to a string
 =      % Check whether (the length of) the current item is equal to (the input)
      g % *Evenly* Pick a random number in the list.

```
> 2 votes

# Answer
## Python 2, ~~100~~ ~~93~~ ~~92~~ 90 bytes

*Thanks to @mbomb007 for shaving off 2 bytes*

```
from random import*
def f(n):k=randint(10**~-n,10**n-1);return(n==len(set(`k`)))*k or f(n)

```

Tries numbers in the required until one is found with unique digits. I'll bet there's a much cleaner way to do this, but none's coming to mind.
> 1 votes

# Answer
# Pyth, 11 bytes

```
jk<{+OS9.ST
jk<{+OS9.STQ implicit Q

       9     9
      S      [1,2,3,4,5,6,7,8,9]
     O       random element

          T  10
        .S   random permutation of [0,1,2,3,4,5,6,7,8,9]

    +        add the results from the previous two paragraphs together
   {         deduplicate
  <        Q first (input) elements
jk           join by empty string

```

Uses the same algorithm as Dennis' answer.

Try it online!
> 1 votes

# Answer
# Perl, 48 bytes

```
1until$_=1+int rand 10**$n-1,/.{$n}/&&!/(.).*\1/

```

## Explanation:

Repeatedly generate random integers from 1 to 10\**$n-1, rejecting them until there is one of the correct length (so at least 10\**($n-1)) with no repeated digits.
> 1 votes

# Answer
## C#, ~~127~~ ~~132~~ ~~128~~ ~~126~~ 125 bytes

```
n=>{var s="";for(int l,r;(l=s.Length)<n;)if((l<1&(r=new System.Random().Next(10))>0)|(l>0&!s.Contains(r+"")))s+=r;return s;};

```

Try It Online!

Borrowed the idea from @KevinCruijssen's answer to initialise the random, `r`, in the `if` statement to save 2 bytes.

Pretty sure this can be golfed further but I don't have time at the moment.

---

Old version using a `while` loop:

```
n=>{var s="";while(s.Length<n){int r=new System.Random().Next(10);if(s.Length<1&r>0)s+=r;else if(!s.Contains(r+""))s+=r;}return s;};

```
> 1 votes

# Answer
## Batch, 156 bytes

```
@set/af=9,r=x=0
@for /l %%i in (1,1,%1)do @call:c
@echo %r%
@exit/b
:c
@set/a"d=9-%random%%%f,e=x>>d&1
@if %e%==1 goto c
@set/a"r=r*10+d,f=10,x|=1<<d

```

`x` maintains a bitmask of used digits. `f` indicates the number of available digits (counting down from 9). Random digits are generated until an unused digit is found. `n=10` could be supported for 165 bytes:

```
@set/af=9,r=x=0
@for /l %%i in (1,1,%1)do @call:c
@echo %r:~1%
@exit/b
:c
@set/a"d=9-%random%%%f,e=x>>d&1
@if %e%==1 goto c
@set r=%r%%d%
@set/a"f=10,x|=1<<d

```

(`r` contains an extra leading zero because it's golfier that way.) Previous approach for 165 bytes special-cased the first digit, and also happened to work with `n=10` (the numeric version actually took 166 bytes!):

```
@set/ar=%random%%%9+1,x=0
@for /l %%i in (2,1,%1)do @set/a"x|=1<<d"&call:c
@echo %r%
@exit/b
:c
@set/a"d=%random%%%10,e=x>>d&1
@if %e%==1 goto c
@set r=%r%%d%

```

Original approach for 170 bytes also worked for `n=10`:

```
@set/ar=%random%%%9+1
@for /l %%i in (2,1,%1)do @call:c
@echo %r%
@exit/b
:c
@set/ad=%random%%%10
@call set s=%%r:%d%=%%
@if not "%s%"=="%r%" goto c
@set r=%r%%d%

```

Uses string manipulation to detect duplicate digits.
> 1 votes

# Answer
# C (gcc), ~~123~~ ~~122~~ ~~100~~ ~~95~~ ~~104~~ ~~103~~ ~~99~~ 97 bytes

This one generating an actual random number

```
j;f(n){for(int i,k=n,s[10]={j=0};n;s[i+=i?0:k==n]=!s[i]?j+=i*pow(10,--n):1)i=rand()%10;return j;}

```

Try it online!

# C (gcc), ~~87~~ 85 bytes

Here it is printing a string of digits.

```
f(n){for(int i,k=n,s[10]={0};n;s[i+=i?0:k==n]=!s[i]?--n,putchar(48+i):1)i=rand()%10;}

```

Try it online!
> 1 votes

# Answer
# Bash, 66 bytes

```
a=0;while [[ $a == 0* ]];do a=`shuf -i0-9 -n$1|xargs`;done;echo $a

```

Try it online!

Straight forward, usues shuf, xargs is used to join lines and continues to try while the combination starts with 0.

Cant beat 46 char from other answer but thus is fast!
> 1 votes

# Answer
# PHP, ~~65~~ 63 bytes

```
while(count(count_chars($x=rand(1,10**$argn),1))<$argn);echo$x;

```

takes input from STDIN; run with `-nR`.

create random number between `1` and `10^N` inclusive;
repeat while count of distinct characters is \< `N`.
> 1 votes

# Answer
# Pyth, ~~15~~ 28 bytes

```
=+YhO9VtQ#KOTI!hxYK=+YKB;jkY

```

Try it here
> 1 votes

# Answer
# Jellyfish, 17 bytes

```
p
d^u ?
 j?r10
10

```

Try it online!

Fork of Dennis' Jelly answer.
> 1 votes

# Answer
# MathGolf, ~~10~~ 11 bytes

```
úr╞gÆ░▀£k=w

```

Try it online!

## Explanation

```
úr            push [0, ..., (10**input)-1]
  ╞           discard the first item of the list (0)
   gÆ         filter by block of 5 operators
     ░        convert to string (needed for "unique elements" operator
      ▀£      number of unique characters in string
        k=    is equal to input?
              end of block
          w   random item from the filtered list

```
> 1 votes

# Answer
## Mathematica ~~65~~ 60 Bytes

```
0For[a=11,Max@DigitCount@a>1,a=RandomInteger[10^{#-1,#}]]+a&

```

Here is a faster version but adds 9 bytes:

```
FromDigits@Join[f=(s=RandomSample)[r=Range@9,1],s[r/.f[[1]]->0,#-1]]&

```
> 0 votes

# Answer
## C, ~~96~~ 93 bytes

```
f(n){char d[11],i=0,r;for(;i++^10;d[i-1]=d[r=rand()%i],d[r]=47+i);*d^48?d[n]=0,puts(d):f(n);}

```

Fisher-Yates shuffle initialization until the first digit isn't zero.

Is uniform, assuming `rand()%i` is uniform. (Since for most i `RAND_MAX/i` leaves a small remainder, there is a very small bias. This bias grows smaller as RAND\_MAX grows larger.)

See it work online.

See it generate correct numbers for when n equals 2, as shown in the question.
> 0 votes

# Answer
# Java 9 JShell, 86 bytes

```
n->new Random().longs(0,10).limit(n-1).reduce(new Random().nextInt(9)+1,(a,b)->a*10+b)

```

Try it online!

Note: I'm not counting the imports as those packages are imported by default in JShell, but there's no Try-it-online link that I know of for JShell, so I've provided one for Java 9 with header and footer code to make it work in that context. In JShell you can just do:

```
jshell> Function<Integer,Long> f =
   ...> n->new Random().longs(0,10).limit(n-1).reduce(new Random().nextInt(9)+1,(a,b)->a*10+b)
f ==> $Lambda$27/633070006@5702b3b1

```

And then:

```
jshell> f.apply(6)
$26 ==> 746202

```

### How it works:

We define a function from Integer to Long and create an infinite stream of random longs in the range from 0-9, limit it to the first n-1 items, then reduce it with a random int from 1-9 as the initial value and a function that multiplies the value by 10 and adds the next value from the stream.

I used longs so this should work for up to about 18 digits (n = 18).
> 0 votes

# Answer
# Ruby, ~~53~~ 52 bytes

Shuffle until the first digit is not 0, then combine the digits and convert to an integer.

```
->n{a=*0..9;a.shuffle!while a[0]==0;eval a[0,n]*''}

```

Try it online!
> 0 votes

# Answer
# Axiom, 191 bytes

```
g(a:NNI):Complex INT==(a<1 or a>9=>%i;r:List NNI:=[];b:=a;repeat(a=0=>break;d:=random()$INT rem 10;a=b and d=0=>0;~member?(d,r)=>(a:=a-1;r:=cons(d,r)));reduce(+,[r.i*10^(i-1)for i in 1..#r]))

```

ungolf it, test result

```
-- Return one number of 'a' different random digits if 0<a<10
f(a:NNI):Complex INT==
    a<1 or a>9=>%i
    r:List NNI:=[];b:=a
    repeat
       a=0=>break
       d:=random()$INT rem 10
       a=b and d=0  =>0
       ~member?(d,r)=>(a:=a-1;r:=cons(d,r))
    reduce(+,[r.i*10^(i-1)for i in 1..#r])

(4) -> [[i,g(i)] for i in 0..10]
   (4)
   [[0,%i], [1,9], [2,76], [3,135], [4,6810], [5,48675], [6,415768],
    [7,7461539], [8,98421537], [9,825046739], [10,%i]]
                                          Type: List List Complex Integer
(5) -> [[i,g(i)] for i in [3,3,3,3,3,3,3,3,3]]
   (5)
   [[3,653],[3,128],[3,254],[3,268],[3,914],[3,594],[3,276],[3,240],[3,398]]

```
> 0 votes

# Answer
## C, 77 bytes

```
r;a;n;d(i){for(a=n=0;r=rand()%10,i-=n&1<<r?0:!!(a=a*10+r);n|=1<<r);return a;}

```

See it work online.

See it generate correct numbers for when n equals 2, as shown in the question.
> 0 votes

# Answer
# Io, 108 bytes

With no RNG properly working (even time()!), I had to use a pseudo-random number generator with one more function operand taken.

```
method(X,Y,(Range 1 to(10**X-1)asList map(i,i asString asList unique join asNumber)select(>10**(X-1)))at(Y))

```

Try it online!
> 0 votes

# Answer
# Perl 5 `-pa`, 45 bytes

```
1while($_=substr rand,2,"@F")&&/^0/+/(.).*\1/

```

Try it online!
> 0 votes

# Answer
# Thunno 2, 7 bytes

```
eėæUl:ɼ

```

Try it online!

#### Explanation

```
eėæUl:ɼ  # Implicit input
e        # Push 10 ** input
 ė       # Then push the range [1..that)
  æ  :   # Filter this list by:
   U     #  Uniquify it
    l:   #  Does the length equal the input?
      ɼ  # Take a random item from this list
         # Implicit output

```
> 0 votes

# Answer
# Vyxal `m`, 8 bytes

```
↵'UL?=;℅

```

Try it Online!

Port of my Thunno 2 answer.

#### Explanation

```
↵'UL?=;℅  '# Implicit input
↵          # Push 10 ** input
 '    ;   '# Filter [1..that) by:
  U        #  Uniquify it
   L?=     #  Does the length equal the input?
       ℅   # Take a random item from this list
           # Implicit output

```
> 0 votes

---
Tags: code-golf, number, random
---


# Question
Title: Display the exponent from a binary floating point number as a decimal value
Had my software final exams recently, one of the last questions had me thinking for a while after the exam had finished.

## Background

IEEE754 numbers are according to the below layout

The exponent is stored as n + 127 so for an exponent of 20 the exponent in binary would be: `127 + 20 = 147` then `10010011`

## The Challange

Write a program that when given text representing a binary floating point number to the IEEE754 standard, returns the exponent given as a decimal value.

## Example

Input: `00111101110011001100110011001101` (0.1)

Isolated exponent bits: `01111011`

Convert to binary: `0 + 64 + 32 + 16 + 8 + 0 + 2 + 1 = 123`

Remove offset: `123 - 127 = -4`

Output `-4`

---

Input: `10111111110111101011100001010010` (-1.64)

Isolated exponent bits: `01111111`

Convert to binary: `0 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 127`

Remove offset: `127 - 127 = 0`

Output `0`

## Rules

* Input must be text/string/equivalent indexable datatype, eg. strings **not** integer or numerical
* Output can be any type, as long as it is decimal
* Aim for shortest solutions

---

Adapted from the 2020 Software Design and Development HSC Paper: 30) d) ii

> Design an algorithm that takes in a string of 32 characters representing a floating point number, and displays the exponent as its signed decimal value.

Any feedback is appreciated as this is my first question

# Answer
> 8 votes
# Python 3, 26 bytes

```
lambda s:int(s[1:9],2)-127

```

Try it online!

# Answer
> 8 votes
# C (gcc), ~~55~~ \\$\cdots\\$ ~~40~~ 36 bytes

Saved ~~2~~ 6 bytes thanks to ceilingcat!!!
Saved ~~2~~ a whopping 13 bytes thanks to Arnauld!!!

```
#define f(s)strtol(s+1,s[9]=0,2)-127

```

Try it online!

# Answer
> 8 votes
# Haskell, 33 bytes

```
foldl1(\x y->x*2+y-1).take 8.tail

```

Try it online!

Input is a list of integers 0 or 1.

It's slightly shorter to `foldl1` by `x*2+y-1` than to subtract 127 at the end. This works because

```
  foldl1 (\x y->x*2+y-1) [a,b,c,d,e,f,g,h]
= ((((((a*2+b-1)*2+c-1)*2+d-1)*2+e-1)*2+f-1)*2+g-1)*2+h-1
= a*128 + b*64-64 + c*32-32 + d*16-16 + e*8-8 + f*4-4 + g*2-2 + h-1
= 128a + 64b + 32c + 16d + 8e + 4f + 2g + h - 127
= fromBinary[a,b,c,d,e,f,g,h]-127

```

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

```
¦8£CƵQ-

```

Try it online!

```
¦8£CƵQ-
¦             remove first element
 8£           take next 8 elements
   C          convert from binary string to an integer
    ƵQ        push 127
      -       subtract

```

Thanks to Kevin for -1 byte

# Answer
> 6 votes
# x86 machine code, 14 bytes

Same machine code works in 32 or 64-bit mode. (Same length for 16-bit mode would be easy with different regs). Callable from C as x86-64 System V `int8_t getexp(const char *b2_str);`

```
    23        ; input: char *str in RDI
    24        ; return: int8_t AL; (calling convention allows garbage in high bytes of RAX)
    25                         getexp_scalar:
    26 00000030 6A09              push 9                 ; sign bit gets shifted out the top.
    27 00000032 59                pop  rcx
    28 00000033 B030              mov  al, '0'
    29                         .loop:
    30 00000035 AE                 scasb                    ; set FLAGS like cmp '0', [rdi]  would, if it was encodeable
    31 00000036 10D2               adc  dl,dl               ; DL = DL<<1 | CF, rotate CF into DL.
    32 00000038 E2FB              loop .loop
    33 0000003A 8D4281            lea  eax, [rdx-127]      ; no shorter than sub dl, 127  or  xchg eax,edx / sub al,127
    34 0000003D C3                ret

```

We just do base 2 ASCII-\>integer conversion for 9 bits, letting the first bit (sign bit) overflow off the top of DL. The 8-bit return value is only the 8-bit AL register, as a 2's complement binary integer.

`adc dl,dl` to rotate CF into DL is more efficient on modern CPUs than `rcl dl, 1` (rotate through carry, i.e. shift in CF). They're equivalent except for some FLAGS output semantics. I could have used EDX for the same code size; that would simply leave different garbage in the high bytes outside the AL return value in RAX. (And yes, high garbage above narrow return values is 100% allowed by standard x86 calling conventions.)

Try it online! 3 versions with a test caller.
(Including alternate 15-byte scalar version using `lodsb` / `and al, 1` / `lea edx, [rdx*2 + rax]`)

# x86-64 SIMD (MMXext+MOVBE) machine code, 20 bytes

Having base-2 digits in MSB-first printing order is a major inconvenience for little-endian x86, where the lowest SIMD vector element comes from the lowest address in memory. x86 lacks a bit-reverse like ARM's `rbit`, so I used x86-64 features to byte-reverse 8 bytes. Without that, `movq mm0, [e/rdi+1]` (4B) / `pslld mm0,7` (4B) would be 32-bit-mode compatible and work on a Pentium III (`pmovmskb r32, mm` was new with SSE, aka MMXext, so not original P5 Pentium-MMX).

```
                             ; input: char *RDI;   result int8_t AL
                             ; clobbers: MM0.  Leaves FPU in MMX state (no EMMS)
    12                         getexp_mmx:
    14 00000010 480F38F04701          movbe    rax, [rdi+1]   ; byte-reverse (big-endian) load of the exponent field.  saves 1B vs. mov + bswap
    15 00000016 48C1E007              shl      rax, 7         ; low bit to high in each byte.  same size as pslld mm0, 7.
    16 0000001A 480F6EC0              movq     mm0, rax
    17 0000001E 0FD7C0                pmovmskb eax, mm0       ; pack vector high bits into 1 byte
    18 00000021 2C7F                  sub      al, 127
    19 00000023 C3                    ret
; size = 0x24 - 0x10 = 0x14 = 20 B

```

MMX instructions typically need 1 fewer prefix byte than SSE2 and later; if you were doing this for real you'd probably use XMM0, and avoid the EMMS (exit MMX state) that real code would normally use. (And maybe a `pshufb` for the byte reverse if you have SSSE3, to avoid bouncing through integer regs...) This should still be much faster than a loop with adc and false dependencies, and the slow `loop` instruction itself. **It's handy that the exponent field is exactly 8 bits wide.** Doing this for `double` would need an SSE2 16-byte load (or 2 byte reverses and annoying shuffles to combine into a 16-byte vector), and would have to mask away the sign bit.

lodsb (1) + lodsq (2) + bswap rax (3) is the same total length as `movbe rax, [rsi+1]` (6), although that would make this portable to machines without `movbe` (Atom, Haswell and later).

---

For subnormal (aka denormal) floats including `0.0`, this just returns `-127`, the unbiased the exponent *field*, as requested by the question. And `-128` (overflowed from +128) for Inf / NaN inputs. (I only realized this overflow issue after the fact, posting anyway because all 255 possible outputs are *unique*, and that puts both special exponents at adjacent values so the caller can test for subnormal or inf/nan with `e <= -127`.)

It doesn't return the actual `floor(log2(|x|))` of the represented value like AVX512 `vgetexpps xmm, xmm` does: (`-Inf` for an input of 0, and values below -127 for non-zero subnormals, matching the pseudocode in the documentation).

So even if we could take input as an actual *binary* floating-pointer number in IEEE754 binary32 format (aka `float`) in an XMM register, we couldn't just use that one 6-byte AVX512 instruction to produce an integer-valued `float` result.

---

### not competing AVX2 version, 15 bytes

This takes its arg as 32 bytes of ASCII digits in a YMM register, but they have to be in least-significant-digit first order, hence not competing.

```
     2                         getexp_avx2_ymm_reversed:
     3             ; input: LSD-first ASCII digits in ymm0.  Probably can't justify that and would need to byte-reverse
     5 00000000 C5FD72F007             vpslld     ymm0, ymm0, 7
     6 00000005 C5FDD7C0               vpmovmskb  eax, ymm0
     7 00000009 C1E817                 shr        eax, 23         ; AL = exponent
     8 0000000C 2C7F                   sub        al, 127
     9 0000000E C3                     ret

```

Fun fact: AVX-512 allows `vpslld ymm0, [rdi], 7`, if you had bytes in the LSD-first order in memory. (7 bytes including 4-byte EVEX, so an extra 2 bytes to take a char\* instead of YMM arg.)

# Answer
> 5 votes
# MathGolf, 7 bytes

```
╞8<å♣(-

```

Try it online.

**Explanation:**

```
╞        # Remove the first character of the (implicit) input-string
 8<      # Slice to only keep the first 8 characters of the string
   å     # Convert it from a binary-string to a base-10 integer
    ♣    # Push constant 128
     (   # Decrease it by 1 to 127
      -  # Subtract it from the integer
         # (after which the entire stack joined together is output implicitly as result)

```

# Answer
> 5 votes
## JavaScript (ES6), 23 bytes

```
f=
b=>(`0b${b}0`>>>24)-127
```

```
<input oninput=o.textContent=f(this.value)><pre id=o>
```

Uses the fact that `>>>` truncates to 32 bits.

# Answer
> 5 votes
# Ruby `-n`, ~~24~~ ~~23~~ 20 bytes

*-1 byte thanks to Sisyphus*
*-3 bytes using `-n` command-line flag, inspired by this answer*

```
p$_[1,8].to_i(2)-127

```

Try it online!

# Answer
> 4 votes
# Kotlin,  ~~26~~   ~~31~~  29 bytes

Converted to a valid anonymous function, thanks to Bubbler
-2 bytes thanks to user

```
{it.slice(1..8).toInt(2)-127}

```

Try it online!

# Answer
> 4 votes
# Desmos, ~~42+9=51~~ ~~40+9=49~~ 30 bytes

```
f(l)=\sum_{i=0}^7l[9-i]2^i-127

```

Input as a list of 1's and 0's.

Try It On Desmos!

# Answer
> 4 votes
# Bash, 22 bytes

```
echo $[2#${1:1:8}-127]

```

Try it online!

# Bash, ~~37~~ 27 bytes

Input is from STDIN, output is to STDOUT.

```
expr $[2#`cut -b2-9`] - 127

```

Try it online!

## Explanation

```
expr                             # Evaluate the following:

         `cut -b2-9`             #     Slice all characters from the 2nd character
                                 #     to the 9th character in standard input

     $[2#           ]            #     Convert it from base 2
                      - 127      #     And subtract by 127

```

# Answer
> 3 votes
# Python 3, 54 bytes

ty to @Bubbler and @Kevin Cruijssen for corrections

```
lambda n: sum([2**i*int(n[8-i])for i in range(8)])-127

```

Try it online!

# Answer
> 3 votes
# APL (Dyalog Unicode), 12 bytes (SBCS)

```
¯127+2⊥8↑1↓⊢

```

Try it online!

# Answer
> 3 votes
# Retina 0.8.2, 63 bytes

```
2=M&!`.{8}
1
01
+`10
011
$
-127$*
(1*)-\1
-
^0*(-)?(1*)-?
$1$.2

```

Try it online! Explanation:

```
2=M&!`.{8}

```

Get the second overlapping 8-character substring.

```
1
01
+`10
011

```

Convert to binary (may leave leading `0`s).

```
$
-127$*
(1*)-\1
-

```

Subtract 127 (may leave trailing `-`).

```
^0*(-)?(1*)-?
$1$.2

```

Convert to decimal, removing garbage.

# Answer
> 3 votes
# , 12 bytes

```
127-~1{8#.\]

```

Try it online!

```
        #.        convert to binary
       8  \       all the infixes with length 8
           ]      of the argument
     1{           take the second one (0-indexed)
127-~             subtract 127

```

# Answer
> 3 votes
# Scala, 27 bytes

Uses Lynn's clever approach

```
_.slice(1,9)reduce(_*2+_-1)

```

Try it online

# Scala, 29 bytes

```
n=>BigInt(n.slice(1,9),2)-127

```

Try it online!

Very straightforward. Takes a `String`, parses the exponent's bits as an integer in binary, then subtracts 127, returning a `BigInt`.

# Scala, 29 bytes

```
n=>(BigInt(n.tail,2)>>23)-127

```

Try it online

Unfortunately, because of operator precedence, the outer parentheses are needed.

# Scala, 29 bytes

```
_.slice(1,9)./:(0)(_*2+_)-127

```

Try it online

Yet another solution, this time taking a list of digits (`List[Int]`).

# Answer
> 3 votes
# C#, 120 115 42 32 bytes

```
s=>Convert.ToByte(s[1..9],2)-127

```

Thanks to @SunnyMoon for realising that the code is not actually 120 bytes (-2)
Thanks to @Sunnymoon for slaying 3 *sneaky* spaces in the code (-3)
Thanks to @user for coding a much **much** shorter lambda solution (***-73***)
Thanks to @thedefault. for using the `..` operator and `Convert.ToByte` (***-10***)

Try it online!

**As it turns out, C# is actually quite useful for golfing! Lambdas are the way to go!**

---

Welcome to code golf, Maximilian Rose!

# Answer
> 3 votes
# \>\<\>, 30 bytes

```
r~8[01:@{2%*+$2*60l4)?.{""-n;

```

(contains an unprintable `DEL` between the quotes)

Try it Online!

```
r~8[                           grab relevant part of string
    01                         accumulator and exponent initialization
                             main loop
       @{2%                    convert current digit charcter to 0 and 1
           *+$                 accumulate
      :       2*               increment exponent
                60l4)?.        loop while digits remaining
                       {""-n;  print result sub 127 and terminate

```

Most of the work is constructing a number from binary notation.

# Answer
> 3 votes
# Forth (gforth), 49 bytes

```
: b drop 1+ 8 ['] evaluate 2 base-execute 127 - ;

```

Try it online!

Done using (a lot of) Bubbler's help.

Forth has one(1) convenient command that allows interpretation of strings as binary, and that's used here(`base-execute`).

# Answer
> 3 votes
# Vyxal, ~~11~~ 6 bytes

```
9ŻB⁺ɽ-

```

Try it Online!

I've got an advantage that y'all don't have: I actually sat the exam this question is based upon as well at the same time as the OP (#hsc\_gang #option\_topic\_2 #ir\_sw\_hw). Hopefully I got both that question and this answer right!

## Explained

```
9ŻB⁺ɽ-
9Ż      #     input[1:9]
  B     # int(          , 2)
   ⁺ɽ   #                      127 (N.B. Pushes the index of ɽ in the codepage + 101)
     -  #                    -
        # int(input[1:9], 2) - 127

```

**Update**: Turns out I got the wrong answer in the exam. Not pog.

# Answer
> 3 votes
# Rust, 43 bytes

```
|s|Ok(i32::from_str_radix(&s[1..9],2)?-127)

```

Try it online!

Returns a `Result<i32,ParseIntError>`. I would have loved to use an `i8` instead of an `i32` but that would panic if the leading bit is 1.

# Answer
> 3 votes
# brainfuck, ~~174~~ ~~113~~ 111 bytes

-61 bytes for many optimizations

-2 bytes thanks to RezNesX

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

```

Try it online!

Input is 32 bits taken one at a time.

Explanation:

```
,> first bit garbage
++++++++ set cur cell (cell 2) to 8
>>--[>-<--]>-<<< set cell 5 to 128 (so the first division moves it over)

[> do 8 times

, input to cell 3

>>> cell 6
[--<+>] div 2 to 5
<[->+<] move back to 6
< cell 4

-[<->-----]<+++ convert to bin value (sub 48) using cell 4

[- if 1 (in cell 3)
>>>[->+>+<<] add cell 6 into cell 7 & 8
>>[-<<+>>] move cell 8 back to 6
<<<<<
]

<-] ends on c2

>>>> to c6 (has 1 and next cell has value)

---[>-<--]> sub 127
. outputs final answer (as ASCII= if this is invalid let me know)

```

# Answer
> 2 votes
# Jelly, 8 bytes

```
Ḋḣ8Ḅ_127

```

Try it online!

Takes input as a list of digits

## How it works

```
Ḋḣ8Ḅ_127 - Main link. Takes a list of bits B on the left
Ḋ        - Dequeue; Remove the first element of B
 ḣ8      - Take the first 8 elements
   Ḅ     - Convert from binary
    _127 - Subtract 127

```

# Answer
> 2 votes
# K (ngn/k), 11 bytes

```
-127+2/8#1_

```

Try it online!

```
         1_        drop one
       8#          take 8
     2/            to binary
-127+              subtract 127

```

# K (ngn/k), 14 bytes

Just an experiment - a port of Lynn's Haskell answer

```
{y-1+2*x}/8#1_

```

Try it online!

# Answer
> 2 votes
# Befunge-98 (PyFunge), 31 bytes

```
~$7v@.-1-~'$$<
_1->\2*~2%+\#^:!

```

Try it online!

---

### Animation

### Explanation

`~$7v` is the initialization code:
`~$` read and discard the first character
`7` push initial value of the loop counter
`v` redirect the instruction pointer down

The second line is the main loop, since `>` is the entry point it is executed as `\2*~2%+\#^:!_1-` from left to right. Initially the loop counter is on top of the stack and the current result on the second position:
`\` swap to the current exponent value
`2*` double it
`~` read the next digits
`2%` modulo `2` maps `'0'` to `0` and `'1'` to `1`
`+` add to the current result
`\` swap to the loop counter
`#` skips the the command (`^`)
`:!` duplicate the loop counter and boolean negate the copy

If the value on the top of the stack is now falsey (loop counter was `>0`), `_` lets the IP move east and the main loop continues by subtracing `1` from the loop counter (`1-`). Otherwise the IP moves west and executes the following:

```
    @.-1-~'$$<
_            ^:!

```

By removing the IP movement commands and writing everything from left to right, this results in `!:$$'~-1-.@`:
`!` invert the loop counter again
`:$$` duplicate the value and pop both copies
`'~-` subtract `'~' = 126`
`1-.` subract `1` and print
`@` terminate the program

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

```
/.(.{8})/;$_=-127+oct"0b$1"

```

Try it online!

# Answer
> 2 votes
# Nim, 58 bytes

```
import strutils
echo stdin.readAll[1..8].fromBin[:int]-127

```

Try it online!

# Answer
> 1 votes
# Charcoal, 13 bytes

```
Ｉ⁻⍘Φ…Ｓ⁹κ²¦¹²⁷

```

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

```
     Ｓ          Input string
    … ⁹         Take first 9 characters
   Φ   κ        Remove first character
  ⍘     ²       Convert from base 2
 ⁻        ¹²⁷   Subtract 127
Ｉ               Cast to string
                Implicitly print

```

# Answer
> 1 votes
# JavaScript (Node.js),  ~~26~~  24 bytes

```
x=>'0b'+x.slice(1,9)-127

```

Try it online!

# Answer
> 1 votes
# Canvas, 13 bytes

```
［］９＠ｊ｛┤］２┴‾p－

```

Try it here!

## Explanation

```
[]9@j{⊣]2⊥¯p⊣-
[]              get all prefixes
  9@            9th prefix
    j           remove first element
     {⊣]        cast each element to integer
        2⊥      decode from base 2
          ¯p    127
            -   subtract that from it

```

# Answer
> 1 votes
# Japt, 8 bytes

Note the unprintable (charcode 127) at the end.

```
Å¯8 Í-#

```

Try it

# Answer
> 1 votes
# Whitespace, 121 bytes

```
[S S S N
_Push_0][S S S T    T   T   N
_Push_7][S N
S _Duplicate_7][T   N
T   S _Read_STDIN_as_character][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][S N
S _Duplicate][T N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve_input][S S S T    T   S S S S N
Push_48][T  S S T   _Subtract][S T  S S T   S N
_Copy_0-based_2nd][S S S T  S N
_Push_2][T  S S N
_Multiply][T    S S S _Add][S N
T   _Swap_top_two][S S S T  N
_Push_1][T  S S T   _Subtract][S N
S _Duplicate][N
T   T   S N
_If_negative_Jump_to_Label_PRINT_RESULT][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT_RESULT][S N
N
_Discard_top][S S S T   T   T   T   T   T   T   N
_Push_127][T    S S T   _Subtract][T    N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

**Try it online** (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer r = 0
Integer n = 7
Read STDIN as character
Start LOOP:
  Integer c = STDIN as character
  c = c - 48
  r = r * 2
  r = c + r
  n = n - 1
  If(n < 0):
    Jump to label PRINT_RESULT
  Go to next iteration of LOOP

PRINT_RESULT:
  r = r - 127
  Print r as integer to STDOUT

```

# Answer
> 1 votes
# Husk, 8 bytes

```
-127ḋ↑8t

```

Try it online!

Straightforward implementation following the steps of the question. Accepts list of digits as argument.

```
-127ḋ↑8t
       t        # tail: remove first element
     ↑8         # get first 8 remaining elements
    ḋ           # interpret as binary digits
-127            # subtract 127

```

# Answer
> 1 votes
# Julia 0.7, 25 bytes

```
n->parse("0b"*n[2:9])-127

```

Try it online!

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 40 bytes

```
Convert.ToInt32(s.Substring(1,8),2)-127;

```

Try it online!

# Answer
> 1 votes
# Zsh, 20 bytes

```
<<<$[0b${n:1:8}-127]

```

Try it online!

# Answer
> 1 votes
# Thunno 2, 7 bytes

```
ḣ8ɱḂṇȷ-

```

Try it online!

#### Explanation

```
ḣ8ɱḂṇȷ-  # Implicit input
ḣ        # Remove first item
 8ɱ      # Next 8 characters
   Ḃ     # Convert from binary
    ṇȷ-  # Subtract 127
         # Implicit output

```

---
Tags: code-golf, math, binary, base-conversion, floating-point
---


title: Reliably Broken Sort

text:
# Question
Title: Reliably Broken Sort
Given a list of positive integers that contains at least 3 distinct entries, output a permutation of that list that isn't sorted in ascending or descending order.

### Examples

```
1,2,3 -> 2,1,3 or 3,1,2 or 1,3,2 or 2,3,1
1,2,3,3 -> 2,1,3,3 or 3,1,2,3 or 1,3,2,3 etc..

```

Thanks @Arnauld and @NoOneIsHere for the title!

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

```
a=>[a.sort((x,y)=>x-y).pop(),...a]

```

Sort the array in ascending order, pop the last element and use it as the first element of a new array. Then destructure the remaining elements of the original array into the new array (In JS, both `sort` and `pop` modify the original array).

---

## Test it

```
o.innerText=(f=

a=>[a.sort((x,y)=>x-y).pop(),...a]

)(i.value=[1,2,3]);oninput=_=>o.innerText=f(i.value.split`,`)
```

```
<input id=i><pre id=o>
```
> 14 votes

# Answer
# Brachylog, 2 bytes

```
o↻

```

Try it online!

or

```
o↺

```

Try it online!

Sorts then rotates the list
> 10 votes

# Answer
# Jelly, 3 bytes

```
Ṣṙ1

```

Try it online!
> 7 votes

# Answer
# Ohm, 2 bytes

```
S╙

```

Try it online!

Sort and rotate to the right.
> 6 votes

# Answer
# Japt, 3 bytes

```
n é

```

Test it

Sorts (`n`) the array and rotates it (`é`) one element to the right.
> 6 votes

# Answer
# APL, 9 bytes

```
{1⌽⍵[⍋⍵]}

```

Try it online!

**How?**

`⍵[⍋⍵]` \- sort the list

`1⌽` \- rotate by 1
> 5 votes

# Answer
# Python 3, 31 bytes

```
lambda a:sorted(a)[1:]+[min(a)]

```

Try it online!

-1 byte thanks to xnor
> 5 votes

# Answer
# Pyth, ~~7~~ ~~5~~ 4 bytes

```
.P1S

```

Try it online!

*-1 byte thanks to FryAmTheEggman*
> 5 votes

# Answer
# TI-Basic (TI-84 Plus CE), 31 bytes

```
Prompt A
SortA(<sub>L</sub>A
max(<sub>L</sub>A→B
dim(<sub>L</sub>A)-1→dim(<sub>L</sub>A
augment({B},<sub>L</sub>A

```

Prompts for input in the format `{1,2,3,4}`.

TI-Basic is a tokenized language, all tokens used here are one-byte.

Explanation:

```
Prompt A         # 3 bytes, store user input in <sub>L</sub>A
SortA(<sub>L</sub>A         # 4 bytes, sort <sub>L</sub>A ascending
max(<sub>L</sub>A→B         # 6 bytes, save the last value in the sorted list to B
dim(<sub>L</sub>A)-1→dim(<sub>L</sub>A # 11 bytes, remove the last value from <sub>L</sub>A
augment({B},<sub>L</sub>A   # 7 bytes, prepend B to <sub>L</sub>A and implicitly print the result

```
> 5 votes

# Answer
# 05AB1E, 2 bytes

Try it online!
> 4 votes

# Answer
# 05AB1E, 2 bytes

Try it online!
> 4 votes

# Answer
# Retina, 21 bytes

```
O#`
s`(.*)¶(.*)
$2¶$1

```

Try it online! Sort and rotate as per usual. At least there's no unary conversion this time.
> 3 votes

# Answer
# Java 8, ~~68~~ 37 bytes

```
l->{l.sort(null);l.add(l.remove(0));}

```

-31 bytes thanks to *@Nevay* (forgot Java 8 had a `List#sort(Comparator)` method..)

Modifies the input-`ArrayList`, instead of returning a new one.

**Explanation:**

Try it here.

```
l->{                   // Method with ArrayList parameter and no return-type
  l.sort(null);        //  Sort the input-list (no need for a Comparator, thus null)
  l.add(l.remove(0));  //  Remove the first element, and add it last
}                      // End of method

```
> 3 votes

# Answer
# Haskell, ~~36~~ 37 bytes

```
import Data.List
f(a:b)=b++[a];f.sort

```

~~Use view patterns to match on the head of a sorted version of the input list, then append the first item of the list to the tail of the remaining list.~~

View patterns aren't worth it. Sort the list, take the head off, append it to the end. In this case, it turns out that the naive solution typed out compactly is the best.
> 3 votes

# Answer
# Perl 6,  ~~43~~  19 bytes

```
{first {![<=]($_)&&![>=] $_},.permutations}

```

Try it

```
*.sort[1..*,0].flat

```

Try it

Note that `[1..*,0]` would result in `((2,3),1)`, so `.flat` is there to turn it into `(2,3,1)`
> 2 votes

# Answer
# Mathematica, 18 bytes

```
RotateLeft@Sort@#&

```

Try it online!
> 2 votes

# Answer
# Ly, 7 bytes

```
&nasprl

```

Try it online!

Ugh, ruining the sort is so expensive!

Explanation:

```
&nasprl

&n      # take input as a list of numbers
  a     # sort
   sp   # save top of stack and pop
     r  # reverse stack
      l # load saved item

```
> 2 votes

# Answer
# R, ~~33~~ ~~32~~ 29 bytes

Takes input from stdin. Sorts the list and then moves the first element to the end, ensuring that it is no longer sorted. Saved three bytes due to Giuseppe.

```
c(sort(x<-scan())[-1],min(x))

```

Another implementation, same byte count:

```
c((x<-sort(scan()))[-1],x[1])

```
> 2 votes

# Answer
# Proton, 19 bytes

```
a=>sorted(a)[1to,0]

```

Try it online!

-2 bytes indirectly thanks to xnor

~~Not yet working on TIO; waiting for a pull.~~
> 1 votes

# Answer
# Ohm, 2 bytes

```
S╜

```

Try it online!

I think this is dissimilar enough from totallyhuman's post to post a new answer; I hope you don't mind :P **EDIT**: DAMMIT YOU NINJA'D ME
> 1 votes

# Answer
# Python, 31 bytes

```
def f(a):a[1:]=a[a.sort():0:-1]

```

Yet another Python solution.

Sadly, this one has the same length to HyperNeutrino's answer.
> 1 votes

# Answer
# C# (Mono), ~~76~~ 67 bytes

```
using System.Linq;a=>a.OrderBy(n=>n).Skip(1).Concat(new[]{a.Min()})

```

*Saved 9 bytes thanks to @Patrick Stephansen.*

Try it online!
> 1 votes

# Answer
# PHP, 44 bytes

requires PHP 5.4 or later for short array syntax.

```
sort($a=&$argv);print_r([array_pop($a)]+$a);

```

sort arguments, replace 0-th argument with removed last argument, print.
Run with `-nr` or try it online.

---

The 0-th argument is the script file name, `"-"` if you call PHP with `-r`. `"-"` is compared to the other arguments as a string, and since `ord("-")==45`, it is smaller than any number. The numbers themselves, although strings, are compared as numbers: `"12" > "2"`.

`php -nr '<code>' 3 4 2 5 1` and `sort($a=&$argv)` lead to `$a=["-","1","2","3","4","5"]`
`[array_pop($a)]+$a` is `[0=>"5"]+[0=>"-",1=>"1",2=>"2",3=>"3",4=>"4"]`,
which results in `[0=>"5",1=>"1",2=>"2",3=>"3",4=>"4"]`.
> 1 votes

# Answer
# Pyth, 5 bytes

```
.>SQ1

```

# Explanation

`SQ` \- sort input list

`.>SQ1` \- rotate input list cyclicaly by 1
> 1 votes

# Answer
# Retina, 10 bytes

```
O#`
O^#-2`

```

Try it online!

```
O#`     Sort the list
O^#-2`  Reverse sort the list other than the last element

```

This leaves the list with the 2nd highest element first and the highest element last which is never correctly sorted
> 1 votes

# Answer
# Gaia, 3 bytes

```
ȯ1«

```

Try it online!

Same as other answers: sort `ȯ` and rotate left once .
> 1 votes

# Answer
# Ruby, 18 bytes

Submitted on mobile. Please don't kill me for problems.

```
->a{a.sort.rotate}

```
> 1 votes

# Answer
# Python 3, 28 bytes

```
lambda a:a[1:a.sort()]+a[:1]

```

Try it online!

`a.sort()` sorts `a` in place and returns `None`. `None` can be used as a slicing index and is the same as omitting that index.
> 1 votes

# Answer
# Python 3, 31 bytes

```
lambda a:a.sort()or[a.pop(),*a]

```

Try it online! or Verify all test cases.

Inspired by Shaggy's JS answer.
> 1 votes

# Answer
# RProgN 2, 2 bytes

```
§›

```

Try it online!
> 1 votes

# Answer
# Julia, 23 bytes

```
f(x)=sort(x)[[2:end;1]]

```

Slightly shorter than, but equivalent to `f(x)=circshift(sort(x),1)`. I wish I could makeamethod based on `select` that was more, compact but I can not
> 1 votes

# Answer
# Common Lisp, 52 bytes

```
(let((x(sort(read)'<)))(rotatef(nth 0 x)(nth 1 x))x)

```

Try it online!
> 1 votes

# Answer
# Clojure, 36 bytes

```
#(let[s %](cons(last s)(butlast s)))

```

Stole the solution to sort it and push the last element to the start of the list.
> 1 votes

# Answer
# TeX - ~~207~~ 183 bytes

```
\def\a#1 #2 #3 #4 {\ifnum#2#1#3\def\e{#3 #4 #2 }\else\def\e{#2 #4 #3 }\fi\e}\def\b#1 #2 #3 {\a< #1 #2 \a> #3 {} }\def\c#1 #2 {\ifnum#1=#2\let\b\f\def\d#1 {#1 \c}\else\let\d\b\fi\d#1 #2 }\def\f#1 #2 {#2 #1 }

```

This is the best I can do with a language that doesn't really have data structures, or many builtins.

The approach is to take the first three numbers we find, and do a broken sort as follows: Sort the first two by greater, and then take the second two by lesser. This should always result in our list being unsorted. It's convenient to ignore anything but the first 3 unique inputs.

We also have a check for two of the same number in a row. In that case, we scan ahead until we find a different number, and then switch the two, ensuring that our list is out of order.

I'm gonna work on golfing this down, but it's the best approach I can think of.

EDIT: Considerable work has been put in to this, to make it more golfy and also actually work. So here it is:

```
\let~\def~\a#1 #2 {\if^#2~\e{\box9 #1 }\else\ifnum#1\h#2~\e{\hbox{#1 }\a#2 }\else~\e{\hbox{#2 }\a#1 }\ifnum#1=#2~\h{=}\setbox9=\lastbox\fi\fi\fi~\g{>}\e}~\g{<}~\h{\g}\everypar{\a}\x^

```

I changed the the method from inserting things into the input to one where we recurse, replaced \expandafter with \everypar, and added that when it finds an equal number, it grabs the last number typeset and saves it until the second to last slot, ensuring that 1 2 2 (the case that secretly broke the previous answer) will be incorrectly sorted as 2 1 2.

This is just a function, to properly use it you need to: have input stored on the variable \x (or you could type in a list of numbers, with a ^ as a delimeter).

If you'd really like to try this, then do this

```
\read1to\x

```

before the lines of this function.
> 1 votes

# Answer
# Thunno 2, 2 bytes

```
ṠỤ

```

Try it online! Sort and rotate left.

```
ṠṾ

```

Try it online! Sort and rotate right.
> 1 votes

# Answer
# Ruby, 20 bytes

```
->(x){x.sort.rotate}

```

I can't figure out how to use lambdas on TIO, but I'll add a link when I do
> 0 votes

# Answer
# SmileBASIC, 33 bytes

```
DEF B A
SORT A
PUSH A,SHIFT(A)END

```

Modifies the array in place. This uses the simple sort+rotate algorithm, though there may be a shorter solution involving RINGCOPY or something (the problem being that COPY and RINGCOPY don't work well when copying between overlapping parts of the same array)
> 0 votes

---
Tags: code-golf, array, sorting, permutations
---


# Question
Title: What's the second non-repeating character?
Based on this question from Code Review

Given a non-empty string of printable ASCII characters, output the *second* non-repeating character. For example, for input `DEFD`, output `F`.

### Input

### Output

* The *second* character that doesn't repeat, when reading left-to-right, again in a suitable format.
* The output character is case-insensitive.
* If no such character exists (e.g., all characters repeat), output an empty string.

### Rules

* The algorithm should ignore case. That is, `D` and `d` count as the same character.
* Either a full program or a function are acceptable.
* The input string will be guaranteed non-empty (i.e., at least one character in length).
* The input string is ASCII. Any valid character could repeat, not just alphanumeric (this includes spaces).
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

### Examples

Input is on first line, output is on second line.

```
DEFD
F

FEED
D

This is an example input sentence.
x

...,,,..,,!@
@

ABCDefgHijklMNOPqrsTuVWxyz
B

AAAAAABBBBB

Thisxthis

This this.
.

```

# Answer
> 11 votes
# MATL, 11 bytes

```
tk&=s1=)FT)

```

This exits with an error (allowed by default) if there is no second non-repeated character.

**Try it online!**

### Explanation

```
t      % Implicitly take input string. Duplicate
k      % Convert to lowercase
&=     % 2D array of equality comparisons
s      % Sum of each column
1=     % True for entries that equal 1
)      % Apply logical index to the input string to keep non-repeated characters
TF)    % Apply logical index to take 2nd element if it exists. Implicitly display

```

# Answer
> 10 votes
## Retina, 25 bytes

```
i!2=`(.)(?<!\1.+)(?!.*\1)

```

Try it online! (The first line enables running the code on a test suite of several inputs.)

### Explanation

This is just a single regex match, the regex being:

```
(.)(?<!\1.+)(?!.*\1)

```

That is, match a character and ensure it doesn't appear anywhere else in the input. The rest is configuration:

* `i` activates case insensitivity.
* `!` tells Retina to print the matches as opposed to counting them.
* `2=` tells Retina to print only the second match as opposed to all of them.

# Answer
> 7 votes
## 05AB1E, ~~15~~ 12 bytes

```
l©v®y¢iy}}1@

```

**Explained**

```
l©            # store lower case string in register
  v     }     # for each char in lower case string
   ®y¢iy      # if it occurs once in string, push it to stack
         }    # end if
          1@  # push the 2nd element from stack and implicitly display

```

Try it online

Saved 3 bytes thanks to @Adnan

# Answer
> 6 votes
# Jelly, 11 bytes

```
Œlµḟœ-Q$Ḋḣ1

```

Try it online! or verify all test cases.

### How it works

```
Œlµḟœ-Q$Ḋḣ1  Main link. Argument: s (string)

Œl           Convert s to lowercase.
  µ          Begin a new, monadic chain. Argument: s (lowercase string)
       $     Combine the two links to the left into a monadic chain.
      Q        Unique; yield the first occurrence of each character.
    œ-         Perform multiset subtraction, removing the last occurrence of each
               character.
   ḟ         Filterfalse; keep characters that do not appear in the difference.
        Ḋ    Dequeue; remove the first character.
         ḣ1  Head 1; remove everything but the first character.

```

# Answer
> 5 votes
# Python 2, ~~59~~ 58 bytes

Returns a list of a single character, or an empty list if no output. (Stupid case-insensitivity...)

```
s=input().lower();print[c for c in s if s.count(c)<2][1:2]

```

**Try it online**

# Answer
> 4 votes
## Batch, 171 bytes

```
@echo off
set a=.
set s=%~1
:l
if "%s%"=="" exit/b
set c=%s:~0,1%
call set t=%%s:%c%=%%
if "%s:~1%"=="%t%" set a=%a%%c%
set s=%t%
if "%a:~2%"=="" goto l
echo %c%

```

Alternative formulation, also 171 bytes:

```
@echo off
set a=.
set s=%~1
:l
if "%s%"=="" exit/b
set c=%s:~0,1%
set t=%s:~1%
call set s=%%s:%c%=%%
if "%s%"=="%t%" set a=%a%%c%
if "%a:~2%"=="" goto l
echo %c%

```

# Answer
> 3 votes
# Pyth, ~~16~~ 15 bytes

1 byte thanks to @mbomb007

```
~~=rz1.xhtfq1/zTzk~~
=rz1:fq1/zTz1 2

```

Test suite.

# Answer
> 3 votes
## Actually, 19 bytes

```
;╗`ù╜ùc1=`░ε;(qq1@E

```

Try it online!

Explanation:

```
;╗`ù╜ùc1=`░ε;(qq1@E
;╗                   push a copy of input to reg0
  `ù╜ùc1=`░          [v for v in s if
   ù╜ùc1=              s.lower().count(v.lower()) == 1]
           ε;(qq     append two empty strings to the list
                1@E  element at index 1 (second element)

```

# Answer
> 3 votes
## C#, 129 128 bytes

```
char c(string i){var s=i.Where((n,m)=>i.ToLower().Where(o=>o==Char.ToLower(n)).Count()<2).ToArray();return s.Length>1?s[1]:' ';}

```

works fine. I wish i didnt need to lowercase everything

# Answer
> 2 votes
# C#, 141 bytes

```
void p(){var x=Console.ReadLine().ToLower();var c=0;foreach(char i in x){if(x.Split(i).Length-1<2){if(++c==2){Console.WriteLine(i);break;}}}}

```

# Without break(smallest), 135 bytes

```
void p(){var x=Console.ReadLine().ToLower();var c=0;foreach(char i in x){if(x.Split(i).Length-1<2){if(++c==2){Console.WriteLine(i);}}}}

```

# With for(;;), 150 bytes

```
void p(){for(;;){var x=Console.ReadLine().ToLower();var c=0;foreach(char i in x){if(x.Split(i).Length-1<2){if(++c==2){Console.WriteLine(i);break;}}}}}

```

# Ungolfed with comments

```
void p()
{
    var x=Console.ReadLine().ToLower();//Get lowercase version of input from STDIN
    var c=0; //Create "count" integer
    foreach(char i in x){//For each char in input from STDIN
        if(x.Split(i).Length-1<2)//If current char occurs once in input from STDIN
        {
            if(++c==2){ //Add 1 to count and if count is 2
                Console.WriteLine(i); //Print result to STDOUT
                break; //Exit foreach
            } //End of IF
         } //End of IF
     } //End of FOREACH
} //End of VOID

```

12 bytes saved by TuukkaX(change count to c).

3 bytes saved by TuukkaX(change string to var).

4 bytes saved by TuukkaX in "With for(;;)"(changed while(true) to for(;;)).

2 bytes saved by TuukkaX(changed c++;if(c==2) to if(++c==2)).

14 bytes saved by Bryce Wagner(changed x.ToCharArray() to x).

# Answer
> 2 votes
# C# lambda with Linq, 63 bytes

```
s=>(s=s.ToUpper()).Where(c=>s.Count(C=>c==C)<2).Skip(1).First()

```

# Answer
> 2 votes
# x86 machine code, 43 bytes

In hex:

```
FC31C031C95641AC84C0740E3C6172F63C7A77F28066FFDFEBEC5EAC49740B89F751F2AE5974F44A77F1C3

```

Function takes a pointer to the input string in (E)SI and an integer in (E)DX and returns the (E)DX-th non-repeating character or zero if there's no such character. As a side-effect it converts the string to upper case.

Disassembly:

```
fc             cld
31 c0          xor    eax,eax
31 c9          xor    ecx,ecx
56             push   esi
_loop0:                         ;Search for the NULL char,
41             inc    ecx       ;counting the length in the process
ac             lodsb
84 c0          test   al,al
74 0e          je     _break0   ;NULL found, break
3c 61          cmp    al,0x61   ;If char is
72 f6          jb     _loop0    ;between 'a' and 'z'
3c 7a          cmp    al,0x7a   ;convert this char
77 f2          ja     _loop0    ;to uppercase in-place
80 66 ff df    and    byte ptr [esi-0x1],0xdf
eb ec          jmp    _loop0
_break0:
5e             pop    esi       ;Reset pointer to the string
_loop:                          ;ECX=string length with NULL
ac             lodsb            ;Load next char to AL
49             dec    ecx
74 0b          je     _ret      ;End of string found, break (AL==0)
89 f7          mov    edi,esi   ;EDI points to the next char
51             push   ecx
f2 ae          repnz scasb      ;Search for AL in the rest of the string
59             pop    ecx
74 f4          je     _loop     ;ZF==1 <=> another instance found, continue
4a             dec    edx
77 f1          ja     _loop     ;If not yet the EDX-th non-rep char, continue
_ret:
c3             ret

```

# Answer
> 2 votes
# APL, 32 bytes

```
{⊃1↓⍵/⍨1=+/∘.=⍨(⎕UCS ⍵)+32×⍵∊⎕A}

```

Try it || All test cases

Explanation:

```
                (⎕UCS ⍵)+32×⍵∊⎕A  Add 32 to uppercase letters
            ∘.=⍨                    Make an equality matrix
          +/                        Check how many matches
    ⍵/⍨1=                           Keep elements with 1 match
  1↓                                Drop the first one
⊃                                   Return the second one

```

I was about to post it with 16 bytes, but the I realized it had to be case-insensitive...

# Answer
> 1 votes
# Retina, ~~43~~ 36 bytes

```
iM!`(.)(?<!\1.+)(?!.*\1)
!`(?<=^.¶).

```

Try it online!

# Answer
> 1 votes
# Mathematica, 49 bytes

```
Cases[Tally@ToUpperCase@#,{_,1}][[2,1]]~Check~""&

```

Anonymous function. Takes a list of characters as input. Ignore any errors that are generated.

# Answer
> 1 votes
## JavaScript (Firefox 48 or earlier), 60 bytes

```
f=s=>(m=s.match(/(.).*\1/i))?f(s.replace(m[1],"","gi")):s[1]

```

Returns `undefined` if there are only zero or one non-repeating characters. Works by case-insensitively deleting all occurrences of characters that appear more than once in the string. Relies on a non-standard Firefox extension that was removed in Firefox 49. ~~119~~ 91 byte ES6 version:

```
f=s=>(m=s.match(/(.).*?(\1)(.*\1)?/i))?f((m[3]?s:s.replace(m[2],"")).replace(m[1],"")):s[1]

```

Recursively searches for all characters that appear at least twice in the string. If the character appears exactly twice then both occurrences are deleted otherwise only the first occurrence is deleted (the other occurrences will be deleted later). This allows the occurrences to have a difference case.

# Answer
> 1 votes
# J, 25 bytes

```
(1{2{.]-.]#~1-~:)@tolower

```

## Usage

```
   f =: (1{2{.]-.]#~1-~:)@tolower
   f 'DEFD'
f
   f 'FEED'
d
   f 'This is an example input sentence.'
x
   f '...,,,..,,!@'
@
   f 'ABCDefgHijklMNOPqrsTuVWxyz'
b
   f 'AAAAAABBBBB'

   f 'Thisxthis'

   f 'This this.'
.

```

## Explanation

```
(1{2{.]-.]#~1-~:)@tolower  Input: s
                  tolower  Converts the string s to lowercase
              ~:           Mark the indices where the first time a char appears
            1-             Complement it
         ]                 Identity function to get s
          #~               Copy only the chars appearing more than once
      ]                    Identity function to get s
       -.                  Remove all the chars from s appearing more than once
   2{.                     Take the first 2 chars from the result (pad with empty string)
 1{                        Take the second char at index 1 and return it

```

# Answer
> 1 votes
# Bash, 58 bytes

```
tr A-Z a-z>t
tr -dc "`fold -1<t|sort|uniq -u`"<t|cut -c2

```

**Caution:** This creates a temporary file named **t**. If it already exists, it will be overwritten.

# Answer
> 1 votes
# C, 174 bytes

```
int c(char*s){int y=128,z=256,c[384],t;memset(c,0,z*6);for(;t=toupper(*s);s++){c[t]++?c[t]-2?0:c[z+(c[y+c[z+t]]=c[y+t])]=c[z+t]:c[z]=c[y+(c[z+t]=c[z])]=t;}return c[y+c[y]];}

```

This is not the most short, but quite efficient implementation. In essence it uses double-linked list to maintain ordered set of candidate characters and scans input string just once. Returns character code or zero if none found.

A little bit ungolfed version:

```
int c(char*s)
{
    int y=128,z=256,c[384],t;
    //It's basically c[3][128], but with linear array the code is shorter

    memset(c,0,z*6);

    for(;t=toupper(*s);s++)
    {
        c[t]++ ?        // c[0][x] - number of char x's occurrence
            c[t] - 2 ?  // > 0
                0       // > 1 - nothing to do
                : c[z + (c[y + c[z + t]] = c[y + t])] = c[z + t]  // == 1 - remove char from the list
            : c[z] = c[y + (c[z + t] = c[z])] = t; // == 0 - add char to the end of the list
    }
    return c[y + c[y]];
}

```

# Answer
> 1 votes
## C#, 143 bytes

```
char c(string s){var l=s.Select(o=>Char.ToLower(o)).GroupBy(x=>x).Where(n=>n.Count()<2).Select(m=>m.Key).ToList();return l.Count()>1?l[1]:' ';}

```

# Answer
> 1 votes
# TSQL, 128 bytes

Golfed:

```
DECLARE @ varchar(99)=',,zzzbb@kkkkkkJgg'

,@i INT=99WHILE @i>1SELECT
@i-=1,@=IIF(LEN(@)>LEN(x)+1,x,@)FROM(SELECT
REPLACE(@,SUBSTRING(@,@i,1),'')x)x PRINT SUBSTRING(@,2,1)

```

Ungolfed:

```
DECLARE @ varchar(99)=',,zzzbb@kkkkkkJgg'

,@i INT=99

WHILE @i>1
  SELECT
    @i-=1,@=IIF(LEN(@)>LEN(x)+1,x,@)
  FROM
    (SELECT
       REPLACE(@,SUBSTRING(@,@i,1),'')x
    )x

PRINT SUBSTRING(@,2,1)

```

Fiddle

# Answer
> 1 votes
# Ruby, 53 bytes

Input is STDIN, output is STDOUT. In Ruby, out-of-index positions in an array or string return `nil`, which is not printed.

`String#count` is a strange function in Ruby because instead of counting the number of occurrences for the string that was passed in, it counts the number of occurrences for each letter in that string. It's usually annoying but we can use it to our advantage this time. `String#swapcase` swaps upper and lower case letters.

```
$><<gets.chars.reject{|c|$_.count(c+c.swapcase)>1}[1]

```

Old version that wasn't safe against special characters like `.` \- 46 bytes

```
$><<gets.chars.reject{|c|$_=~/#{c}.*#{c}/i}[1]

```

# Answer
> 1 votes
# Java 8, ~~172~~ 157 bytes

```
(String s)->{s=s.toLowerCase();for(char i=0,c;s.length()>0;s=s.replace(c+"","")){c=s.charAt(0);if(!s.matches(".*"+c+".*"+c+".*")&&++i>1)return c;}return' ';}

```

-15 bytes.. Dang I was bad at golfing back then. ;)

**Explanation:**

Try it here.

```
(String s)->{                          // Method with String parameter and character return-type
  s=s.toLowerCase();                   // Make the input-String lowercase
  for(char i=0,c;s.length()>0;         // Loop over the characters of `s`
      s=s.replace(c+"","")){           // And after every iteration, remove all occurrences of the previous iteration
    c=s.charAt(0);                     // Get the current first character
    if(!s.matches(".*"+c+".*"+c+".*")  // If it doesn't occur more than once
     &&++i>1)                          // And this was the second one we've found
      return c;                        // Return this second characters
  }                                    // End of loop
  return' ';                           // Else: return an empty character/nothing
}                                      // End of method

```

# Answer
> 1 votes
# , 79 bytes

```
function(z){y=tolower(el(strsplit(z,"")));x=table(y);y[y%in%names(x[x==1])][2]}

```

Try it online!

I definitely feel like something can be golfed out here. But I really enjoyed this challenge.

This answer splits the string into a vector of characters, changes them all to lower case, and tables them (counts them). Characters that occur once are selected and compared to characters within the aforementioned vector, then the second value that is true is returned as output. An empty string, or a string with no repeating characters outputs NA.

# Answer
> 1 votes
# Perl 6, ~~38~~ 32 bytes

*-6 bytes thanks to nwellnhof by changing `.comb` to a case-insensitive regex*

```
{~grep({2>m:g:i/$^a/},.comb)[1]}

```

Try it online!

# Answer
> 1 votes
# 05AB1E, ~~9~~ 6 bytes

```
lÐ¢Ï¦н

```

Input as a list of characters.

Try it online or verify all test cases.

**Explanation:**

```
l       # Convert the characters in the (implicit) input-list to lowercase
 Ð      # Triplicate this lowercase list
  ¢     # Pop two, and get the count of each character in the list
   Ï    # Pop the counts and remaining list, and only keep the characters at the truthy
        # (count==1) positions
    ¦   # Remove the first character
     н  # Pop and leave the new first character
        # (after which it is output implicitly as result)

```

Unfortunately the `.m` (least frequent character(s) builtin) doesn't retain its order in the legacy version of 05AB1E and will only keep the first character instead of a list in the new 05AB1E version, otherwise this could have been 5 bytes with `l.m¦¬`.

# Answer
> 1 votes
# K (oK) / K4, 11 bytes

**Solution:**

```
*1_&1=#:'=_

```

Try it online!

**Explanation:**

```
*1_&1=#:'=_ / the solution
          _ / convert input to lowercase
         =  / group alike characters
      #:'   / count (#:) each group
    1=      / 1 equal to length of the group?
   &        / where true
 1_         / drop the first
*           / take the first

```

# Answer
> 1 votes
# Thunno 2 `h`, 6 bytes

```
LDcḅịḣ

```

Try it online!

#### Explanation

```
LDcḅịḣ  # Implicit input
    ị   # Filter the input by:
L c     #  The count of the character lowercased
 D      #  In the input lowercased
   ḅ    #  Equals one?
     ḣ  # Remove the first character
        # Implicit output of next character
        # (or the empty string if it doesn't exist)

```

# Answer
> 1 votes
# Vyxal, 9 bytes

```
⇩)ġ~₃f∑Ḣh

```

Try it Online!

*-3 thanks to @lyxal*

#### Explanation

```
⇩)ġ~₃f∑Ḣh  # Implicit input
⇩)ġ        # Group by lowercasing
   ~₃      # Filter by length == 1
     f∑    # Flatten and join
       Ḣ   # Remove the first character
        h  # Then take the next one
           # (or an empty string
           #  if it doesn't exist)
           # Implicit output

```

# Answer
> 1 votes
# Japt `-g`, 8 bytes

```
k@oX ÅÃÅ

```

Try it

```
k@v èXv)É

```

# Answer
> 0 votes
# Jelly, 15 bytes

```
Œlµċ@Ị¥Ðf¹ḊḢȯ“”

```

Try it online!

Verify all testcases. (Slightly modified to cater for all testcases)

# Answer
> 0 votes
## Perl, 75 bytes

```
 my$s=<>;chomp$s;my$c;for my$i(split//,$s){my$m=@{[$s=~/$i/gi]};$m<2and++$c>=2and say$i and last}

```

# Answer
> 0 votes
## Javascript (using external Library) (107 bytes)

Crushed this using a library I wrote. Not sure if I have to count the declaration of variable "s", which is the string in question.

```
(s)=>_.From(s).ToLookup(y=>y.toLowerCase(),z=>z).Where(g=>g.Value.Count()==1).Select(x=>x.Key).ElementAt(1)

```

This will handle an empty string input, an input with only one non-repeating character, and an input with 2+ non-repeating characters

# Answer
> 0 votes
## Clojure, 109 bytes

```
#(let[s(clojure.string/lower-case %)](or(second(remove(set(map(fn[[k v]](if(> v 1)k))(frequencies s)))s))""))

```

Ough, I hope there is a more succinct way.

# Answer
> 0 votes
# JavaScript, 57 bytes

```
v=>(v+'\0'+v).replace(/(.)(?=.*\1.*\1)|\0.*/gi,"")[1]||""

```

JavaScript doesn't have Regex lookbehind, so I appended a null character and another copy of the string so that I can use lookahead. I then remove the null character and all characters after it as part of the regex replace.

# Answer
> 0 votes
# PowerShell, 55 Bytes

old but good challenge, deserves a PS answer.

```
([char[]]"$args".ToLower()|group|? Count -eq 1)[1].Name

```

Throws errors when there are no non-repeating chars, exits with no error or return if there is only one repeating char.

the `.ToLower()` cost a bit due to the case insensitivity, and using `|% ToL*r` actually costs bytes since you need to wrap it all in brackets before converting to a `char[]`

# Answer
> 0 votes
# PHP, 76 bytes

```
for($a=$argn;~$c=$a[$i++];)stripos($a,$c)<strripos($a,$c)?:$r.=$c;echo$r[1];

```

Try it online!

# Answer
> 0 votes
# Java (OpenJDK 8), ~~133~~ 131 bytes

```
s->{String t=s.toUpperCase();int[]i=t.chars().filter(c->t.indexOf(c)==t.lastIndexOf(c)).toArray();return(char)(i.length>1?i[1]:0);}

```

Try it online!

# Answer
> 0 votes
## Pyth, 17 bytes

```
Jrz1.x.(fq/JT1J1k

```

Test suite

Python 3 translation:
```
J=input().upper()
try:
    print([T for T in J if J.count(T)==1][1])
except:
    print()

```

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