[Question]
  [
You will need to generate the smallest prime with `n` digits, and it will only contain digits specified in the list `k`.
### Examples:
Input:
```
4
1 2
```
For this, you must generate the smallest prime with `4` digits, and that prime must only contain the digits `1` and `2`.
Output:
```
2111
```
Input:
```
10
0 4 7 
```
Output:
```
4000000007
```
Input:
```
6
5 5 5 5 5 5 5 5 5 5 1 5 5 5 5 5 5 5 5 5 5
```
Output:
```
115151
```
You can guarantee that the input will always be in the format you specify, and you can do anything if you get invalid input (such as the input being a single digit `n`, without `k`.)
If no such solution to an input exists, your program is allowed to do any of the following:
* Print `banana`
* Throw an error
* Run forever
* Anything else
Since this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), try to aim for the shortest code.
The input can be in any format you specify. For example, if you want your input to be like any of the following, that is fine.
```
4
[1, 2]
[1,2]4
1,2
4
4 12
```
You can either write a program or a function, and it must either return the correct value or print it.
Whitespace is allowed anywhere.
This challenge inspired by [A036229](https://oeis.org/A036229).
  
[Answer]
# Bash + bsd-games package, 28 bytes
* 18 bytes saved thanks to @Dennis.
```
primes 1|egrep -wm1 [$2]{$1}
```
Input given at the command-line as n followed by k as a non-delimited list of digits.
[Try it online.](https://tio.run/nexus/bash#S8svUihJLS5JTixOVcjMU1AyUTA0UlJQMlMwhQNDBFPJWiEln6s4tURBBabrf0FRZm5qsYJhTWp6UWqBgm55rqFCtIpRbLWKYe3/lPy81P//zf5jNQ0A)
[Answer]
# [Python 2](https://docs.python.org/2/), 66 bytes
```
f=lambda n,s,k=1,p=1:10**~-n<p%k*k<s>=set(`k`)or-~f(n,s,k+1,p*k*k)
```
[Try it online!](https://tio.run/nexus/python2#@59mm5OYm5SSqJCnU6yTbWuoU2BraGVooKVVp5tnU6CarZVtU2xnW5xaopGQnaCZX6Rbl6YBVqoNVKoFlNb8X1CUmVeikKZhrFOtbqmuo24MxBbqtZr/AQ "Python 2 – TIO Nexus")
Takes input like `f(3,{'9','3','8'})`.
Python has no built-ins for primes, so the function generates them using [Wilson's Theorem](https://codegolf.stackexchange.com/a/27022/20260) to check each potential value for `k` in turn for being prime. 
The chained inequality `10**~-n<p%k*k<s>=set(`k`)` combines three conditions on `k`:
* `10**~-n<k`: `k` contains at least `n` digits. We don't need to check exactly since if we reach more digits, there must have been no solution
* `p%k>0`: `k` is prime, via the Wilson's Theorem condition with `p=(n-1)!^2`. Since `p%k` is 0 or 1, this can be combined with the previous condition as `10**~-n<p%k*k`
* `s>=set(`k`)`: All digits in `k` are in the set `s`. This can be spliced in because Python 2 considers sets as bigger than numbers.
If the current `k` doesn't satisfy all of these, the function recurses onto `k+1`, adding 1 to the resulting output. Since the output terminates with `True` which equals `1`, and `k` starts at `1`, the output is `k`. This parallel tracking of `k` beats outputting `k` directly on success.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (2), 8 bytes
```
j₍oᵐ∋ᵐcṗ
```
[Try it online!](https://tio.run/nexus/brachylog2#@5/1qKk3/@HWCY86uoFk8sOd0///jzbTiY421cGEhjrYRE1jY2P/RwEA "Brachylog – TIO Nexus")
Very slow on problems which have a lot of possible digits, or which contain a 0 in the set of possible digits (it does *work* in this case; it's just that it's so much slower that TIO times out unless the problem's very simple). As usual for Brachylog, this is a function, not a full program.
Input is taken in the format `[ndigits,[list of digits]]`, e.g. `[10,[[0,4,7]]]`.
## Explanation
```
j₍oᵐ∋ᵐcṗ
j₍        Make a number of copies of the second element equal to the first element
  oᵐ      Sort each (ᵐ) of those copies (evaluation order hint)
    ∋ᵐ    Take one element from each of those copies
      c   Concatenate those elements to form an integer (asserts no leading 0)
       ṗ  producing a prime number
```
Seen from the purely declarative point of view, this says "find a prime number, with the given number of digits, where all digits are one of the given digits". In order to find the *smallest* such number, we use evaluation order hints in order to ensure the order in which we test the numbers is smallest to largest; in this case, `ᵐ` makes decisions near the start of the list less prone to changing than decisions near the end (this is its natural order, which happens to be the same as lexicographic and thus numerical order on integers), and thus `{o∋}ᵐ` has two evaluation order hints, "vary the last few digits first" (from the `ᵐ`'s natural order) as the more important hint, and "check smaller digits before larger digits" (from the `o` before the `∋`, which acts as a hint in this context) as the tiebreak. `{o∋}ᵐ` can be written as the equivalent `oᵐ∋ᵐ` to save a byte.
[Answer]
## JavaScript (ES7), 100 bytes
Takes input as number of digits `n` and string of allowed digits `s` in currying syntax `(n)(s)`. Returns `undefined` if no solution is found.
Works rather quickly for up to 6 digits, might work for 7 and definitely too slow -- and memory hungry -- beyond that.
```
n=>s=>(a=[...Array(10**n).keys()]).find(i=>eval(`/[${s}]{${n}}/`).test(i)&&a.every(j=>j<2|j==i|i%j))
```
### Test
```
let f =
n=>s=>(a=[...Array(10**n).keys()]).find(i=>eval(`/[${s}]{${n}}/`).test(i)&&a.every(j=>j<2|j==i|i%j))
                                        
console.log(f(5)("247")) // 22247
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
DL×ÆP
ṗḌÇÐṀṂ
```
Takes a set and an integer as command-line arguments. Prints **0** if no solution exists.
[Try it online!](https://tio.run/nexus/jelly#@@/ic3j64bYAroc7pz/c0XO4/fCEhzsbHu5s@n94uZK7wsMd2x81zFHwTSwoVijJSFXITczMU8jJzMtWyC9LLVJIzi8qSi0uyM9LycxLV0gsSi/NTc0rKdb7/7/aUMeoVkeh2kDHRMccwgCK6BgDuaYgrqkOJjTEImZa@18BCEx0FMDA0ADKgAI0Ln5ghmACAA "Jelly – TIO Nexus")
### How it works
```
ṗḌÇÐṀṂ  Main link. Left argument: A (digit set/array). Right argument: n (integer)
ṗ       Cartesian power; yield all arrays of length n that consist only of elements
        of the array A.
 Ḍ      Undecimal; convert all generated digit arrays to integers.
  ÇÐṀ   Keep only elements for which the helper link returns a maximal result.
     Ṃ  Take the minimum.
DL×ÆP   Helper link. Argument: k (integer)
D       Decimal; convert k into the array of its base 10 digits.
 L      Take the length.
   ÆP   Test if k is a prime number. Yields 1 or 0.
  ×     Multiply the length and the Boolean.
```
[Answer]
## Pyke, ~~18~~ 16 bytes
```
j;~p#`ljqi`Q-!)h
```
[Try it here!](http://pyke.catbus.co.uk/?code=j%3B%7Ep%23%60ljqi%60Q-%21%29h&input=1+2%0A4)
Runs forever if no values found
[Answer]
## Mathematica, 64 bytes
```
FirstCase[Tuples@##,x:{f_,___}/;f>0&&PrimeQ[y=FromDigits@x]:>y]&
```
Pure function where the first argument is the (sorted) list of allowed digits and the second argument is the allowed length. `Tuples@##` computes all lists of the allowed digits of the allowed length, then we find the `FirstCase` which matches `x:{f_,___}` such that the first digit `f` is not `0` and the integer `y=FromDigits@x` is prime and replaces it with `y`.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes
```
tL∧?h~lṗ.dẹp⊆L∧
```
[Try it online!](https://tio.run/nexus/brachylog2#@1/i86hjuX1GXc7DndP1Uh7u2lnwqKsNJPb/f7SZTrSpDggagsjY2P9RAA "Brachylog – TIO Nexus")
This is fairly slow.
### Explanation
```
tL                Input = [H, L]
  ∧
   ?h~l .         The Output is a variable of length H
       ṗ.         The Output is a prime number
          ẹ       The Output's digits...
        .d        ...when removing duplicate digits...
           p      ...is a permutation...
            ⊆L    ...of an ordered subset of L
              ∧
```
[Answer]
# JavaScript (ES6), 86 bytes
Takes input via the currying syntax, e.g., `(4)('12')`
```
n=>(d,F=(i,P=j=>i%--j?P(j):1==j)=>P(i)&&`${i}`.match(`^[${d}]{${n}}$`)?i:F(i+1))=>F(2)
```
```
'use strict';
const G=n=>(d,F=(i,P=j=>i%--j?P(j):1==j)=>P(i)&&`${i}`.match(`^[${d}]{${n}}$`)?i:F(i+1))=>F(2)
const submit = () => {
  console.clear();
  console.log(G(+n.value)(d.value));
}
button.onclick = submit;
submit();
```
```
<input id="n" type="number" min="1" value="4" />
<input id="d" type="text" value="12" />
<button id="button">Submit</button>
```
To be run in strict mode (for [tail call optimisation [TCO]](http://www.ecma-international.org/ecma-262/6.0/#sec-tail-position-calls)). If your environment doesn't support TCO it will result in a stack overflow error for primes larger than the environments stack.
For invalid inputs it will run forever.
**Note:**
* Chrome (>= 51) users can go to `chrome://flags/#enable-javascript-harmony` and enable this flag to run the above snippet with TCO support.
* Safari (>= 10) supports TCO
[Answer]
# MATL, 17 bytes
```
wlwX"1GXNUStZp)l)
```
This function accepts two inputs, an integer specifying the number of digits and a character array indicating the possible values. In the case of no primes, an error is shown.
[**Try it Online!**](https://tio.run/nexus/matl#@1@eUx6hZOge4RcaXBJVoJmj@f@/CZe6oZE6AA)
**Explanation**
```
        % Implicitly grab two inputs. First as an integer (N), second as a string (OPTS)
w       % Reverse the order of the inputs
l       % Push the literal 1 to the stack
w       % Pull N back to the top of the stack
X"      % Repeat OPTS N times 
1G      % Explicitly grab N again
XN      % Get all N-character combinations of the repeated version of OPTS
U       % Convert each row from a string to a number
S       % Sort them in ascending order
tZp)    % Grab only those that are primes
l)      % Retrieve the first prime
        % Implicitly print the result
```
[Answer]
# Pyth - ~~13~~ 12 bytes
```
f&P_T!-Tz^Tt
```
[Test Suite](http://pyth.herokuapp.com/?code=f%26P_T%21-Tz%5ETt&test_suite=1&test_suite_input=4%0A%5B1%2C+2%5D%0A6%0A%5B5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+1%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%5D&debug=0&input_size=2).
[Answer]
# Sage, 62 bytes
```
lambda l,d:[p for p in primes(10^(l-1),10^l)if set(`p`)<=d][0]
```
Takes input of the form: `f( 4 , {'1','2'} )`
[Answer]
# [Perl 6](http://perl6.org/), 43 bytes
```
->\n,@k {first *.is-prime&/^@k**{n}$/,^∞}
```
Runs forever if no solution exists.
[Answer]
## Ruby, ~~77~~ 76 bytes
```
->n,l{(10**~-n..10**n).find{|n|(2...n).none?{|x|n%x<1}&&!n.to_s[/[^#{l}]/]}}
```
Input format: a number and a string.
### Example:
```
->n,l{...see above...} [6,"555555555515555555555"]
=> 115151
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
[¾ØÐ¼g¹QiS²Kg0Qiq
```
[Try it online!](https://tio.run/nexus/05ab1e#ASEA3v//W8K@w5jDkMK8Z8K5UWlTwrJLZzBRaXH//zQKWzEsMl0 "05AB1E – TIO Nexus")
```
[¾Ø ¼             # Infinite loop over all primes
   Ð              # Push two extra copies on the stack
     g¹Qi         # If the length of this prime == the first input...
         S²K      # Push this prime without any of the digits in the second input
            g0Qi  # If the length of what remains is 0...
                q # quit
                  # implicitly print this prime
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~22~~ ~~19~~ 18 bytes (-1 @Riley)
```
[NØ©S¹Kg0Q®g²Q&i®q
```
[Try it online!](https://tio.run/nexus/05ab1e#ASwA0///W07DmMKpU8K5S2cwUcKuZ8KyUSZpwq4scf//WzEsM10KNPVuby1jYWNoZQ "05AB1E – TIO Nexus")
```
[                   # infinite loop.
 NØ©                # push nth prime.
    S¹Kg0Q          # see if, without banned digits, it's 0 length.
          ®g²Q&     # see if, it is originally also the length specified.
               i®q  # if true, print result and exit.
```
[Answer]
# [R](https://www.r-project.org/), 88 bytes
*Note: as a special 'Language of the month' treat for anyone contemplating starting to golf in R (and I hope there are many of you...), I've written a short commentary of the various iterations that led to this answer in the [R golfing chatroom](https://chat.stackexchange.com/rooms/112541/the-r-project-for-statistical-golfing).*
```
function(n,k)for(x in 1:10^n)if(sum(x%/%10^(1:n-1)%%10%in%k)==n&(sum(!x%%1:x)<3))stop(x)
```
[Try it online!](https://tio.run/##hY5RasMwEET/c4oNQUULCrXatAVTX6UmVeRmSbQy0oqop3dVX8B/OzOPnUlLDuf73WcZ@UI/JOOcKPjxQXIdVyMPy1TYCUXWbG44xaQrEIPtbffFSJPOJeiqnlXT2vZ8tKjarYjVDYeBn1ZgX5vZV/x8RcwSZ11xu1ufjO1fEA4Qi8xFgDJ8/4JPKSYDOYKLIXgWkGtLGgMSIRWG7F3kC0h7Du6c/R5gt932bpx@MxZxd4Bt2nYN78zJfPwPlBavE5Y/ "R – Try It Online")
Outputs as an error message. No output when there is no solution.
Checks all numbers in the range `1:10^n` (obviously 10^n is not a prime, so we don't need to worry about the end case):
* `x%/%10^(1:n-1)%%10` extracts the digits, and `%in% k` checks whether each digit is in the list. If the `sum` is `==n` then we know that all the digits are Ok.
* `(sum(!x%%1:x)<3)` checks for primality (a prime should have only 2 factors including 1 and itself).
When we find the first solution, we exit with `stop(x)` to output the answer as an error message. `return(x)` would be the friendlier solution to output to STDOUT, but it costs +2 bytes.
[Answer]
**APL (NARS2000 0.5.14), 31 characters:**
```
{A←⍺⋄((1∘π)⍣{∧/A∊⍨⍎¨⍕⍺})10*⍵-1}
```
**Example:**
```
      1 2 {A←⍺⋄((1∘π)⍣{∧/A∊⍨⍎¨⍕⍺})10*⍵-1} 4
2111
      5 5 5 5 5 5 5 5 5 5 1 5 5 5 5 5 5 5 5 5 5 {A←⍺⋄((1∘π)⍣{∧/A∊⍨⍎¨⍕⍺})10*⍵-1} 6
115151
```
**How it works:**
`A←⍺` captures left argument, that is, the required digits composing target prime.
`10*⍵-1` generates the least number have `⍵` digits e.g. `10*(4-1) = 1000`
`1∘π` finds next prime number of right argument; So on first iteration, `(1∘π)1000` yields `1009`
`⍣` operator recursively applies (1∘π) to result from above, unless the inner function `{∧/A∊⍨⍎¨⍕⍺}`, when applied to `1009`, evaluates to `1` i.e. boolean true, where it does not; Thus recurse.
The inner function `{∧/A∊⍨⍎¨⍕⍺}` takes `⍺`, result of current iteration, as argument and test if every digit of it is an element of vector A.
**Limitations:**
Non-termination if no such prime of `n` digit exist.
Runs very slowly using the `n = 10` example, not able to return even after 30 seconds.
[Answer]
# Perl5, 77 bytes
```
($n,$d)=@ARGV;/^[$d]{$n}$/&&("x"x$_)!~/^(..+?)\1+$/&&print&&die for 2..10**$n
```
Run like this:
```
perl -le '($n,$d)=@ARGV;/^[$d]{$n}$/&&("x"x$_)!~/^(..+?)\1+$/&&print&&die for 2..10**$n' 4 12
```
[Answer]
# [Perl 6](https://perl6.org), 68 bytes
```
->\n,\k{first {.is-prime&&/.**{n}/},+«[X~] 0,|(k.unique.sort xx n)}
```
[Try it](https://tio.run/nexus/perl6#bZDBboJAEIbv@xRzIGRXh5U1oIkE4kP00KQ2DcFVN@hC2cVgKH2hvkXfqWeKSry0818m//z58mdqI@G84FlE6mF7ksZG5HQBNyu2EuLeSzYaN3m7U5Wx0HJlvLJSJ@m6Mz6ZtLqbdTj9/np5/nwFHz9ozmut3mvJTVFZaBrQrOsH3toOZIiBEgAaIBU4ZwziBOZCCLyawkfqY4DLux/44yxv1wXSEP9K/OOFd4AQ4SAkLCLlMdUwvVWIyK6oxjZeAs4bUFjl8kKpo3GdM4awOqfHWlJHNqXMrNwyYNAOHZSB61PGIMIjgMD3yljS9T@68LI0O8hf "Perl 6 – TIO Nexus")
Returns `Nil` if no such prime can be found.
## Expanded:
```
->
  \n, # number of digits
  \k  # list of digits
{
  first
    {
        .is-prime
      &&
        / . ** {n} / # exactly ｢n｣ digits ( in case ｢k｣ has a 0 )
    },
    +«\          # turn the following into a list of numbers
    [X[~]]       # cross the following with &infix:<~>
    0,           # append a 0 in case ｢n｣ was 1
    |(           # slip this list in (flatten)
        k        # the input list of possible digits
        .unique  # only one of each to reduce the search space (optional)
        .sort    # sort it so that the cross meta op returns them sorted
      xx         # list repeat
        n        # ｢n｣ times
    )
}
```
[Answer]
# Python 2 + [primefac](https://pypi.python.org/pypi/primefac), ~~91~~ 85 bytes
```
import primefac as P
n,k=input()
p=10**~-n
while set(`p`)!=k:p=P.nextprime(p)
print p
```
[**Try it online**](https://repl.it/Fnpe/1)
Input is like `4,{'1','2'}`.
[Answer]
# PHP, 82 bytes
```
for($n=10**--$argv[1];$i-1||a&trim($n,$argv[2]);)for($i=++$n;--$i&&$n%$i;);echo$n;
```
Takes a number and a string of digits from command line arguments. Run with `-nr`.
**breakdown**
```
for($n=10**--$argv[1];  // $n = smallest number with (argument1) digits
    $i-1||                  // loop while $n is not prime or
    a&trim($n,$argv[2]);    // $n without all digits from (argument2) is not empty
)
    for($i=++$n;--$i&&$n%$i;);  // $i=largest divisor of $n smaller than $n (1 for primes)
echo$n;                 // print
```
[Answer]
# Java 7, ~~139~~ 141 bytes
```
long c(int a,String b){for(long n=2,i,x;;n++){for(x=n,i=2;i<x;x=x%i++<1?0:x);if(x>1&(n+"").length()==a&(n+"").matches("["+b+"]+"))return n;}}
```
+2 bytes by supporting numbers above 32-bit (changed `int` to `long`)
**Input format:** An integer (i.e. `4`) and a String (i.e. `"12"`)
**Explanation:**
```
long c(int a, String b){                  // Method with the two input parameters specified above
  for(long n = 2, i, x; ; n++){           // Loop from 2 going upwards
    for(x = n, i = 2; i < x; x = x % i++ < 1 ? 0 : x);  // Prime check for `n` 
    if (x > 1                             // if `n` is a prime (if `x` > 1 after the loop above it means `n` is a prime)
         & (n+"").length() == a           // AND if `n` has a length equal to the input integer
         & (n+"").matches("["+b+"]+")){   // AND if `n` only contains the specified digits of the input String (using a regex)
      return n;                           // Then we have our answer
    }
  }                                       // If no answer is available for the given input, it continues looping
}
```
**Test code:**
[Try it here.](https://ideone.com/5Q6olw)  
NOTE: The second test case is disabled because it loops for a very long time..
```
class M{
  static long c(int a,String b){for(long n=2,i,x;;n++){for(x=n,i=2;i<x;x=x%i++<1?0:x);if(x>1&(n+"").length()==a&(n+"").matches("["+b+"]+"))return n;}}
  public static void main(String[] a){
    System.out.println(c(4, "12"));
    //System.out.println(c(10, "047"));
    System.out.println(c(6, "555555555515555555555"));
  }
}
```
**Output:**
```
2111
115151
```
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 245 bytes
```
> Input
> Input
> 10
> 0
>> ≺1
>> 3*1
>> 3*5
>> 7…6
>> L’
>> Select∧ 9 8
>> L⊥3
>> L∖2
>> Each 11 10
>> Each 12 13
>> #L
>> L=4
>> Each 15 14
>> Each 16 17
>> L⋅R
>> Each 19 13 18
>> Select∧ 15 20
>> 21ⁿ4
>> 22⊤3
>> Output 23
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hAtBGxoACSC2U3jUucsQRBtrQSlTEGX@qGGZGYjh86hhJogOTs1JTS551LFcwVLBAiLRtdQYwuiYZgRiuCYmZygYGoLNhvGMFAzBipR9wEptTRBSpgqGSDwzBUNziGndrUEIYUugfgVDC1QXALUage0wMnzUuB9siJHRo64lYJv8S0uAXlQwMv7/34Qr2lBHwSgWAA "Whispers v2 – Try It Online")
## How it works
Assuming the two inputs are \$n\$ (the number of digits) and \$S\$ (the set of digits), the program works as follows:
First we generate the range \$A = \{10^{n-1}\dots10^n\}\$ and remove all composite numbers in this range. Next, we take the set difference of each value and the input set \$S\$, which gives \$\{\}\$ for all numbers which have the same digits as \$S\$ and a non-empty set for those that don't. We then take the length of each set, and if it is \$0\$, we keep the values in the set. Finally, of the filtered values, we select the first value i.e. the lowest value. This outputs the lowest value in the set of prime numbers between \$10^{n-1}\$ and \$10^n\$, where the digits are in \$S\$.
]