[Question]
  [
I read [this](https://stackoverflow.com/q/43593278/5401763) 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 [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") 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](https://docs.python.org/2/), 77 bytes
```
from random import*
r=range(10)
while[1]>r:shuffle(r)
print`r`[1:input()*3:3]
```
[Try it online!](https://tio.run/nexus/python2#DcgxCoAgFADQ3VM0qhBkbUJdRASjvimYyk/p5M3m9OA1i@kecI9nx985YeEE1x4XUDEx8jofQAm9oXxctTYARUYy@lgMGiWkj7kWyvgiF93a/MU0Hvvh4Ac "Python 2 – TIO Nexus")
Shuffles the list of 10 digits until it doesn't start with 0, then makes a number with the first `n` digits listed.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~9~~ 10 bytes
```
{~lℕ₁≜≠}ᶠṛ
```
[Try it online!](https://tio.run/nexus/brachylog2#ASUA2v//e35s4oSV4oKB4omc4omgfeG2oOG5m///M/9a9W5vLWNhY2hl "Brachylog – TIO Nexus")
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](https://github.com/JCumin/Brachylog), 8 bytes, in collaboration with @Fatalize
```
~lℕ₁≠≜ᶠṛ
```
[Try it online!](https://tio.run/nexus/brachylog2#ASAA3///fmzihJXiiaDiiZzhtqDhuZv//zT/WvVuby1jYWNoZQ "Brachylog – TIO Nexus")
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.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁵*ṖQL$€MX
```
**[Try it online!](https://tio.run/nexus/jelly#@/@ocavWw53TAn1UHjWt8Y34//@/8de8fN3kxOSMVAA "Jelly – TIO Nexus")** (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).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
9Xœ|⁵ḶẊ¤ḣ¹Ḍ
```
[Try it online!](https://tio.run/nexus/jelly#ASYA2f//OVjFk3zigbXhuLbhuorCpOG4o8K54biM////M/Vuby1jYWNoZQ "Jelly – TIO Nexus")
### 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.
```
[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.
[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](http://clojurescript.io) (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.
[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**](https://tio.run/nexus/python2#FcoxCsMwDADAva/QKBkKzZAl0JeEgF3HagS1ZFT36Z3ddLrlBrtV8KT7idRm3sOF769UH3sCXfJhkguuAmwOAqL//Cw43UJQEo7v0jFKpLjOQZdto9FctAOjaPt0JBrzV@2aUz7KDw)
[Answer]
# R, 45 Bytes
```
k=0
i=scan()
while(!k[1])k=sample(0:9)[1:i]
k
```
[Answer]
# Bash + GNU utils, 46
```
seq 1e$[$1-1] 1e$1|egrep -v '(.).*\1'|shuf -n1
```
[Try it online](https://tio.run/nexus/bash#Fca9DkAwFAbQ3VN8QxM/yW1yF4tHwSB10aVFseCxzcWZzuBXWFiHk7Uu7wq9T/AJsoEIysYgC1hUrZi4/ceXjKvMoANppnNdNJxeYdoHkOPYeyfxcZ5MZyZ5AQ).
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.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~27~~ ~~19~~ 17 bytes
Requires `⎕IO←0` which is default on many systems.
```
10⊥⊢↑{?⍨10}⍣{×⊃⍺}
```
[Try it online!](https://tio.run/nexus/apl-dyalog#U9Z71DfV0/9R2wQDLmUQO8gHyH7Uu@Z/GpA2NHjUtfRR16JHbROr7R/1rjA0qH3Uu7j68PRHXc2PenfV/v@fdmiFoYKRgrGCiYKpgpmCuYKFgqWCocHXvHzd5MTkjFQA "APL (Dyalog Unicode) – TIO Nexus")
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
[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.](https://tio.run/##NZDBboMwDIbvfQovp2RpI7gSUp6gvew47ZABbdMFU5mAMlU8Owttd7Fk//6t7/fVTnZ3bX6W2tthgIN1eN8AOAwtnWzdwnFtAT4COTxDzZMCKHQazptUhmCDq@EICAYW3O3vkyUgw5g@9fTY9tuouTekfIvncOFClKjjuznYcFFksek7LrYkDfdlXsV9VryRqnsMiWXgjMkoRBULxkQ0eaapDSMhkJ4XvRLcxm@fCF4gU@8a6JKTP4k/v8CKZ4R/HmdyDa5cb4GTUjzElPB3CG2n@jGoW3IGj9xJVgCT3JV5VjFgK4NElZ4gXh@Ylz8)
**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
```
[Answer]
# [Perl 6](https://perl6.org), 44 bytes
```
{(->{+[~] (^10).pick($_)}...*>9 x$_-1).tail}
```
[Try it](https://tio.run/nexus/perl6#Ky1OVSgz00u25sqtVFBLzk9JVbD9X62ha1etHV0Xq6ARZ2igqVeQmZytoRKvWaunp6dlZ6lQoRKva6ipV5KYmVP7Py2/SMFAIU5PL07B0EChmktBoTixUgFkEkgLV@3/r3n5usmJyRmpAA "Perl 6 – TIO Nexus")
## 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)
}
```
[Answer]
# PHP, 67 Bytes
[Online Version](http://sandbox.onlinephpfunctions.com/code/436bda2f3f91d9e62bfdfd8cde7f061500948509)
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));
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
9×!X+!Œ?’ḣƓḌ
```
Currently one byte behind my other Jelly answer, but I really like this one.
[Try it online!](https://tio.run/nexus/jelly#ASIA3f//OcOXIVgrIcWSP@KAmeG4o8aT4biM//8z9W5vLWNhY2hl "Jelly – TIO Nexus")
### 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.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ ~~7~~ ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
°L¨ʒÙgQ}Ω
```
Very slow for larger \$n\$.
[Try it online](https://tio.run/##yy9OTMpM/f//0AafQytOTTo8Mz2w9tzK//9NAA) or [verify some more test cases](https://tio.run/##ATkAxv9vc2FiaWX/NEUibj0iP07CqT8iIOKGkiAiP1RGwq7/wrBMwqjKksOZZ8KuUX3Oqf8/w7A/fcK2P/8).
~~+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](https://tio.run/##yy9OTMpM/f//6L4MvaLD6z0PLf7/3xQA) or [verify some more test cases](https://tio.run/##ATQAy/9vc2FiaWX/OUUibj0iP07CqT8iIOKGkiAiP1RGwq7/xb5oLnLDr8KuwqP/P8OwP33Ctj//).
**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)
```
[Answer]
# [W](https://github.com/A-ee/w), 6 [bytes](https://github.com/A-ee/w/wiki/Code-Page)
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.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 15 bytes
```
`4Y2GZr1)48=]8M
```
Try it at [MATL Online!](https://matl.io/?code=%604Y2GZr1%2948%3D%5D8M&inputs=3&version=19.10.0)
### 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
```
[Answer]
## [Python 2](https://docs.python.org/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.
[Answer]
# [Pyth](https://github.com/isaacg1/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](https://codegolf.stackexchange.com/a/117519/48934).
[Try it online!](http://pyth.herokuapp.com/?code=jk%3C%7B%2BOS9.ST&input=6&debug=0)
[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.
[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.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 66 bytes
```
a=0;while [[ $a == 0* ]];do a=`shuf -i0-9 -n$1|xargs`;done;echo $a
```
[Try it online!](https://tio.run/nexus/bash#FYvBCsIwEAXvfsU75CRsSY8l5EtKoUu6NQuShUZRUD/bc4xzG4bZ7YBCC17jMEyfgM1O6FS5gQhOG0cfHlmvgnmGY8QIf8ayhM3Aca35voPU0wQqbnw/@bjUtcciQVK2vrS/tG8xSpyy/AA "Bash – TIO Nexus")
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!
[Answer]
# Pyth, ~~15~~ 28 bytes
```
=+YhO9VtQ#KOTI!hxYK=+YKB;jkY
```
[Try it here](http://pyth.herokuapp.com/?code=%3D%2BYhO9VtQ%23KOTI%21hxYK%3D%2BYKB%3BjkY&input=8&debug=0)
[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!](http://rextester.com/MCE85919)
Borrowed the idea from [@KevinCruijssen's answer](https://codegolf.stackexchange.com/a/117574/38550) 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;};
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~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!](https://tio.run/nexus/c-gcc#bczLCoMwFATQvV9hhUIuKsQ@rSH4IeIi@KgX9VqM7Ub87G5rVboqmd0chplLRjCWXc@QBhu9WpKnk4CncuSTIKETdCXGPKqlpFTulp7Gvk/e4zlklerZKXQRogBQ9opyBvuAi2m21rdWIbFXhzlYo2Uv0dtkwLZgHEBsVrIAxHKmmeOAWOXHBzMfzXwy89nMFzNfzRya@fbP0/zJykbd9ew37Zs6P1NZVXwB "C (gcc) – TIO Nexus")
# [C (gcc)](https://gcc.gnu.org/), ~~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!](https://tio.run/nexus/c-gcc#bczLCoMwFATQvV9hhUIuKsQ@rSH4IeIi@KgX9VqM7Ub87G5rVboqmd0chplLRjCWXc@QBhu9WpKnk4CncuSTIKETdCXGPKqlpFTulp7Gvk/e4zlklerZKXQRogBQ9opyBvuAi2m21rdWIbFXhzlYo2Uv0dtkwLZgHEBsVrIAxHKmmeOAWOXHBzMfzXwy89nMFzNfzRya@fbP0/zJykbd9ew37Zs6P1NZVXwB "C (gcc) – TIO Nexus")
[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`.
[Answer]
# [Jellyfish](https://github.com/iatorm/jellyfish), 17 bytes
```
p
d^u ?
 j?r10
10
```
[Try it online!](https://tio.run/nexus/jellyfish#@1/AlRJXqmDPpZBlX2RowGVo8P@/6de8fN3kxOSMVAA "Jellyfish – TIO Nexus")
Fork of [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/117519/48934).
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~10~~ 11 bytes
```
úr╞gÆ░▀£k=w
```
[Try it online!](https://tio.run/##ASoA1f9tYXRoZ29sZv//w7py4pWeZ8OG4paR4paAwqNrPXf//zEKMgozCjQKNf8 "MathGolf – 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
```
[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]]&
```
[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!](https://tio.run/nexus/java-openjdk9#bU9Nb8IwDL33V/iYjDZq940YHCdN2nYYx4mDCaF4Sp2qSWFo4mfvzMIojE3zIbH83rPfo6p2TYA3XKJqA1n1gjxz1SChv8BYI7Np/kHmLetAjtV91wySpG6nljRoi97DExLDRwKxurkPGOK3dDSDKqJiHBri8nUC2JReduRddWchbhgCm9VhIMZrH0yliOXgSD4YuHvgYErTpPDouBzBHIZbzkY7@T6fkMpGxIs8LfLYU0VBcFZI1ZhZq434RWXzHuJG0Ze9IhWYTmU2wrMi703l9nD6x8RqQdaAIFYL9M@dVJ5m@s61t@/aoOoYPVgWc4V1bdc7JR9lJ@k2yf7dbAs4hwu4hCu4hhu4hT4U@Se7TKNemC8 "Java (OpenJDK 9) – TIO Nexus")
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).
]