title: Self-Interpreting Interpreter

text:
# Question
Title: Self-Interpreting Interpreter
Based on a comment by George Edison to this question, write the smallest self-interpreting interpreter.

* You may use the language of your choosing.
* Empty languages do not count. Your program must be at least two characters long.
* The program does not need to interpret the *entire* language, just a Turing-complete subset of language features (that contains the interpreter).
* Quines don't count.
* Do not use your language's built-in `eval` function or equivalent. Same goes for `apply`, etc.

# Answer
> 22 votes
## CI - 260

```
,(1p0(2d())(41(2d())('#((1p0()(10()(1d,1p$)=)<)$2d,1p$)(40(1d,1c$^)(''(1d,^)('0
'9('0-(,'0'9('0-2p10*+1p$)(!1d)~)$^)(0($)'$(^)'^(&)'&(c)'c(p)'p(d)'d(=)'=(<)'<(
>)'>(~)'~(.)'.(,)',(!)'!(+)'+(-)'-(*)'*(/)'/(%)'%()38p(1p3p0(3d)((2)(3)=p1d1p$)
=)$)~)=)=,2p$&)=)=)<)$$

```

***320 → 260:** Push simple character-to-instruction mappings, then fold over them. This halves the code size per case (there are 18 cases), but costs 30 characters to do the folding.*

This is another one of my constructed languages, (base interpreter hosted on Gist). It's unique in that the language reifies code fragments. That is, strings of instructions in this stack-based language are used to the same effect as data structures or closures in other languages:

```
1^      # Push a 1, and "lift" it to be a code literal.
(5 +)   # Define a code literal.
&       # Join the two code literals, forming (1 5 +)
$       # Execute the code literal.

```

The interpreter builds a code fragment of the entire program before running it, so it can also be considered a compiler. Because of this, stacking the interpreter does not result in exponential run-time overhead.

The interpreter derives all of its operators directly from the host interpreter. However, it does the parsing by itself, so the majority of the code is just sequences that translate characters into their respective code literals. This isn't the same as using `eval`, but it reveals how dependent any programming language implementation is on the semantics of its host language/architecture.

---

## Language reference:

*Get the interpreter here*

### Blocks

* `(` ... `)`

Create a "block", which is effectively a list of instructions with no context. Internally, it could even be machine code.
* block `$`

Call a block. The callee is handed the global stack, which includes the block being called.
* value `^`

Lift a value. Namely, turn it into a block that pushes that value.

**Example**:

```
   1 ^
== (1)

```
* block1 block2 `&`

Join two blocks, forming one that runs both in sequence.

**Example**:

```
   (1) (2) &
== (1 2)

```

### Stack manipulation

* n `c`

Copy the nth value of the stack.

**Example**:

```
   5 4 3 2 1 0 3c
== 5 4 3 2 1 0 3

```
* n `p`

Pluck the nth value of the stack (remove it, and bring it to front).

**Example**:

```
   5 4 3 2 1 0 3p
== 5 4 2 1 0 3

```
* n `d`

Drop n values from the stack. `0d` is a no-op.

**Example**:

```
   5 4 3 2 1 0 3d
== 5 4 3

```

### Relational operators

* a b (on\_true) (on\_false) `=`

Test if a equals b. Consume all but the first argument, and call on\_true or on\_false. If one argument is zero and the other is any other type, the result will be false. Otherwise, a and b must be integers.

**Example**:

```
   3 3 ('0+ .) (1d) =
== 3 '0+ .

```
* a b (on\_true) (on\_false) `<`

Test if a is less than b. a and b must be integers.

**Example**:

```
   3 5 (1d 5) () <
== 3 1d 5
== 5

```
* a b (on\_true) (on\_false) `>`

Test if a is greater than b. a and b must be integers.

**Example**:

```
   3 5 (1d 5) () >
== 3

```
* a lo hi (on\_true) (on\_false) `~`

Test if lo \<= a \<= hi. a, lo, and hi must be integers.

**Example**:

```
   3 0 10 ('0+ .) (1d) ~
== 3 '0+ .

```

### I/O

* c `.`

Put the character c (consuming it from the stack).
* `,`

Get a character and push it to the stack. If the end of file has been reached, -1 is pushed.
* c `!`

Unget a character. Just like ungetc in C, only one pushback is allowed.

### Integer literals

* `'c`

Push the character c.
* *\[0-9\]+*

Push a decimal integer.

### Arithmetic

* a b `+`
* a b `-`
* a b `*`

Add/subtract/multiply two numbers.

**Example**:

```
   3 5 + 7 3 + *
== 80

```
* a b `/`
* a b `%`

Division and modulus. Unlike in C, these round toward negative infinity.

### Miscellaneous

* code `#` comment

The `#` character comments out everything to the end of the line.
* `)`

Used to end blocks. Can be used to end the whole program, too.
* All other characters are ignored.

# Answer
> 28 votes
# Binary Lambda Calculus, 232 *bits* (29 bytes)

`0101000110100000000101011000000000011110000101111110011110000101110011110000001111000010110110111001111100001111100001011110100111010010110011100001101100001011111000011111000011100110111101111100111101110110000110010001101000011010`

See http://en.wikipedia.org/wiki/Binary\_lambda\_calculus#Lambda\_encoding for details

# Answer
> 18 votes
I can't take credit for this one, but I thought I would share this amazing one:

## Brainf\*** (423)

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

```

# Answer
> 12 votes
## BlockScript - 535

```
{[B':=?0:B';=?0:B'}=?0:B'{=?,A!,A!d1c&:B'?=?,A!,A!2e&:B''=?,,A!d3c&:B{[B'0<?0:B
'9>?0:1}!?B'0-{[,g!?c'0-B10*d+A!:Bd]A!d3c&}!:B'#=?{[,10=?,]A!:A!}!:,A!Bb&}{[AC[
B]DB?[AB{[Bh&hbhn!}{[B[AB]C?1-eA!:b}&[C1=?E[C]FHc&B!:C2=?{G?D:E[C}!FHcI!:C3=?E[
C]B!:C'!=?G[ABC]Hc&dbh&D?b@I!B!:b@I!:C'&=?HB!:C'@=?FGDI!:C'[=?GF&HDI!:C']=?F[A]
HDI!:C',=?,B!:C'.=?G.FHDI!:C'a'z{[DC<?0:DB>?0:1}!?Ce-HA!B!:C'A'Ze!?F[B]Cg-dA!B!
:{C'+=?{[CB+}:C'-=?{[CB-}:C'*=?{[CB*}:C'/=?{[CB/}:C'%=?{[CB%}:C'<=?{[CB<}:C'>=?
{[CB>}:C'==?{[CB=}:0}!?H[A][B]Ge!B!:FHDI!:c},c!0ac&0&0&0bho!;

```

BlockScript is a trivial spaghetti stack-based language I created specifically for this challenge. The base interpreter is blockscript.c .

Sample program (prints the first 15 Fibonacci numbers):

```
{[B?B10/A!B10%d&:0}
{[B0<?'-.0B-A!:{B?Bh!{[B?B[A]A!B[B]'0+.:}!:'0.}!10.}
{[B?Dd!DC+B1-CecA!:}
0 1 15d!
;

```

The interpreter reads both source code and program input from standard input, in that order. This means that to run an interpreter within an interpreter within an interpreter, simply copy and paste:

```
# Level 1
{[B':=?0:B';=?0:B'}=?0:B'{=?,A!,A!d1c&:B'?=?,A!,A!2e&:B''=?,,A!d3c&:B{[B'0<?0:B
'9>?0:1}!?B'0-{[,g!?c'0-B10*d+A!:Bd]A!d3c&}!:B'#=?{[,10=?,]A!:A!}!:,A!Bb&}{[AC[
B]DB?[AB{[Bh&hbhn!}{[B[AB]C?1-eA!:b}&[C1=?E[C]FHc&B!:C2=?{G?D:E[C}!FHcI!:C3=?E[
C]B!:C'!=?G[ABC]Hc&dbh&D?b@I!B!:b@I!:C'&=?HB!:C'@=?FGDI!:C'[=?GF&HDI!:C']=?F[A]
HDI!:C',=?,B!:C'.=?G.FHDI!:C'a'z{[DC<?0:DB>?0:1}!?Ce-HA!B!:C'A'Ze!?F[B]Cg-dA!B!
:{C'+=?{[CB+}:C'-=?{[CB-}:C'*=?{[CB*}:C'/=?{[CB/}:C'%=?{[CB%}:C'<=?{[CB<}:C'>=?
{[CB>}:C'==?{[CB=}:0}!?H[A][B]Ge!B!:FHDI!:c},c!0ac&0&0&0bho!;

# Level 2
{[B':=?0:B';=?0:B'}=?0:B'{=?,A!,A!d1c&:B'?=?,A!,A!2e&:B''=?,,A!d3c&:B{[B'0<?0:B
'9>?0:1}!?B'0-{[,g!?c'0-B10*d+A!:Bd]A!d3c&}!:B'#=?{[,10=?,]A!:A!}!:,A!Bb&}{[AC[
B]DB?[AB{[Bh&hbhn!}{[B[AB]C?1-eA!:b}&[C1=?E[C]FHc&B!:C2=?{G?D:E[C}!FHcI!:C3=?E[
C]B!:C'!=?G[ABC]Hc&dbh&D?b@I!B!:b@I!:C'&=?HB!:C'@=?FGDI!:C'[=?GF&HDI!:C']=?F[A]
HDI!:C',=?,B!:C'.=?G.FHDI!:C'a'z{[DC<?0:DB>?0:1}!?Ce-HA!B!:C'A'Ze!?F[B]Cg-dA!B!
:{C'+=?{[CB+}:C'-=?{[CB-}:C'*=?{[CB*}:C'/=?{[CB/}:C'%=?{[CB%}:C'<=?{[CB<}:C'>=?
{[CB>}:C'==?{[CB=}:0}!?H[A][B]Ge!B!:FHDI!:c},c!0ac&0&0&0bho!;

# Level 3
{[B?B10/A!B10%d&:0}
{[B0<?'-.0B-A!:{B?Bh!{[B?B[A]A!B[B]'0+.:}!:'0.}!10.}
{[B?Dd!DC+B1-CecA!:}
0 1 15d!
;

```

Like the movie Inception, you pretty much can't go any deeper than three levels. It's not a matter of time, but space. BlockScript leaks memory profusely, and this has to do with how the language itself is designed.

---

## Language reference:

*Get the interpreter here*

In BlockScript, the "stack" is not an array that is overwritten by subsequent operations like you may be used to. It is actually implemented as an immutable linked list, and a stack persists for the duration of the program. Also, no operator (except `@`) removes values from the stack. However, stack modifications only affect the block in which they occur.

### Value selection

* `a` through `z`

Fetch the 0-25th item from the stack, and push it to the stack. `a` refers to the head, or most recently pushed item, of the stack.
* `A` through `Z`

Fetch the 0-25th item of the current frame, and push it to the stack.
* `[`

Open a "frame" to select items from the stack reference (see below) on the head of the stack. `[` doesn't require a matching `]`, but frames are lexically scoped. In BlockScript, "scope" is determined by braces (`{` ... `}`) that form blocks. Thus, opening a frame inside of a block will have no effect on code outside of the block.
* `]`

Close the current frame, returning to the previous frame (if any).

### Blocks

* `{` ... `}`

Create a "block", and push it to the stack. Inside a block, the stack will start at what it was before the block, except the stack of the caller will be pushed on top. Stacks are persistent and immutable in BlockScript, so blocks are closures. The idiom `{[` means open a block, then open a frame to start selecting arguments (using `A` through `Z`). The return value of a block is the head of the stack when `}` is reached.

**Example:**

```
 '3 '2 '1 {[ b. d. f. B. C. D. A! } 'D 'C 'B d!;

```

This prints `123BCD123DCB123BCD123DCB…` . The lowercase letters refer to stack values, while the uppercase letters refer to arguments (because the frame is set to the stack of the caller). `A!` takes the head of the caller (which is guaranteed to be the block being called) and calls it. If you're wondering why it reverses `BCD` every other time, it's because `B. C. D.` pushes those arguments in reverse order right before the block calls itself.
* `!`

Call a block. Push the return value to the stack.

### Stack references

* `&`

Create a stack reference, and push it to the stack. Think of this as "super-cons", as it effectively takes every item on the stack and forms a "tuple" out of it. The idiom `&[` means that whatever `a`, `b`, `c` referred to before can now be accessed with `A`, `B`, `C` (for the remainder of the block or until `]` is encountered).

In part because `&` captures more values than it usually needs, BlockScript leaks memory by design.
* `@`

Switch to the stack pointed to by the stack reference `a`. This operator is rather weird, but the BlockScript self-interpreter uses it a couple times to avoid having to push the same arguments twice. The effects of `@` (or any stack operation, for that matter) are confined to the block in which it is invoked. Also, the frame is unaffected by `@`, so the frame can be used to grab values you need after switching stacks.

### Conditional expression

* `?` *\<on true\>* `:` *\<on false\>*

Conditional expression, just like the ternary operator in C. That is, if `a` is "true" (that is, not equal to the integer zero), then do *\<on true\>*, otherwise do *\<on false\>*.

### I/O

Note: Input and output are done in UTF-8. A "character" is an integer corresponding to a Unicode index.

* `,`

Get the next character of input, and push it to the stack. If the end of input is reached, push -1 instead.
* `.`

Output the character on the head of the stack.

### Integer/character literals

Note: Integers and characters are the same thing in BlockScript.

* `'c`

Push the character c.
* *\[0-9\]+*

Push a decimal integer.

### Arithmetic

These operators only work on integer values.

* `+` Compute `b` \+ `a` (pushing the result, but not discarding either value).
* `-` Compute `b` \- `a`.
* `*` Compute `b` * `a`.
* `/` Compute `b` / `a` (integer division; rounds toward negative infinity).
* `%` Compute `b` % `a` (integer modulus; rounds toward negative infinity).

### Relational operators

These operators only work on integer values.

* `<` If `b` is less than `a`, push 1, else push 0.
* `>`
* `=`

### Miscellaneous

* `#` Comment to end of line
* The program must end with `;`
* All other characters are ignored.

# Answer
> 4 votes
# Zozotez LISP: 414

linefeeds added to get a nice block is not needed and not counted.

```
((\(E V A L)(E(r)'(())))(\(x e)(?(s x)(V x e)((\(b j)(?(= b ")(a j)(?(= b \)x
(?(= b ?)(?(E(a j)e)(E(a(d j))e)(E(a(d(d j)))e))(?(s b)(A b(E(a j)e)(E(a(d j)
)e))(E(a(d(d b)))(L(a(d b))j e)))))))(E(a x)e)(d x))))(\(x g)(? g(?(= x(a(a
g)))(d(a g))(V x(d g)))x))(\(f h v)(?(= f r)(r)(?(= f p)(p h)(?(= f s)(s h)(?
(= f a)(a h)(?(= f d)(d h)(?(= f =)(= h v)(c h v))))))))(\(k v i)(? k(L(d k)(
d v)(c(c(a k)(E(a v)i))i))i)))

```

In theory it should be able to run itself, but since the original interpreter is a BrainFuck binary and itself an interpreter I have only been able to test each part. When given itself and a simple expression `(p p)` I think it needs more time than the 40 minutes I have waited so far and I'm using my fast `jitbf` to run it which (mis)uses Perl Inline-C to run C code on the fly.

It's impossible to implement the whole Zozotez in Zozotez since it does not have means of mutating cons and `:` (setq/define) need that to update bindings. I also didn't implement explicit begin/progn or &rest argument, macros and special printing arguments since I didn't use it in the interpreter. I did include `p` (print) even though I don't use it so programs need to explicit print their calculations just like the original interpreter.

The same ungolfed:

```
;; A stand alone Zozotez script need to be
;; contained in one expression, here with
;; all functions provided as arguments to
;; get them bound in the dynamic environment
((\ (E V A L)
  (E(r)'(())))
 ;; E (EVAL)
 (\ (x e)
   (? (s x)
      (V x e)
      ((\ (b j)
         (? (= b ") (a j)
         (? (= b \) x
         (? (= b ?) (? (E(a j)e) (E(a(d j))e) (E(a(d(d j)))e))
         (? (s b)
            (A b (E(a j)e) (E (a(d j))e))
            (E (a(d(d b))) (L(a(d b))j e)))))))
       (E (a x) e)(d x))))
 ;; V (VALUE / symbol->value)
 (\ (x g)
   (? g
      (? (= x (a (a g)))
         (d (a g))
         (V x (d g)))
      x))
 ;; A (APPLY) but just for primitives
 (\ (f h v)
   (? (= f r) (r)
   (? (= f p) (p h)
   (? (= f s) (s h)
   (? (= f a) (a h)
   (? (= f d) (d h)
   (? (= f =)
      (= h v)
      (c h v))))))))
 ;; L ( joint evLis / extend-env)
 (\ (k v i)
   (? k
      (L (d k)
         (d v)
     (c (c (a k)
           (E (a v) i))
        i))
      i)))

```

# Answer
> 2 votes
# GORBITSA, 493 bytes

```
S255 O253 R I188 B12 I68 o252 S1 O250 i252 S0 B2 S71 O255 S18 O254 S0 B134 B143 S79 O255 S25 O254 S0 B134 B149 S82 O255 S32 O254 S0 B134 B155 S66 O255 S39 O254 S0 B134 B158 S73 O255 S46 O254 S0 B134 B168 S84 O255 S53 O254 S0 B134 B172 S83 O255 S60 O254 S0 B134 B175 S65 O255 S67 O254 S0 B134 B179 S103 O255 S74 O254 S0 B134 B185 S111 O255 S81 O254 S0 B134 B193 S114 O255 S88 O254 S0 B134 B201 S98 O255 S95 O254 S0 B134 B207 S105 O255 S102 O254 S0 B134 B219 S116 O255 S109 O254 S0 B134 B224 S115 O255 S116 O254 S0 B134 B230 S97 O255 S123 O254 S0 B134 B239 G251 s253 I1 A252 B255 S2 i251 i250 S0 B12 g251 s253 I1 A255 b254 S1 i254 S0 b254 g250 O248 g248 O249 S0 B124 g250 O248 G249 o248 S0 B124 r249 S0 B124 G249 B162 S0 B124 g250 O251 I1 O250 S0 B12 g250 i249 S0 B124 t249 S0 B124 g250 O249 S0 B124 g250 O248 g248 i249 S0 B124 g250 O248 g248 O248 g248 O249 S0 B124 g250 O248 g248 O248 G249 o248 S0 B124 g250 O248 R o248 S0 B124 G249 B211 S0 B124 g250 O248 g248 O251 I1 O250 S0 B12 g250 A249 o250 S0 B124 g250 O248 g248 T S0 B124 g250 O248 g248 O248 G249 s248 O249 S0 B124 g250 O248 g248 O248 G249 a248 O249 S0 B124

```

Since GORBITSA is kind of strange, I will specify that this runs in ROM mode, while the code it interprets is in RAM mode. Explaining this is kind of weird, but I'll do my best. The 256 command limit on ROM mode killed me for a while.

# Explained

(Full pseudocode I translated this to AFTER I wrote this (yeah, I wrote this with no extra utilities) can be found here).

## Header:

```
S255 O253 R I188 B12 I68 o252 S1 O250 i252 S0 B2

```

Essentially, this part takes the input. It reads STDIN and stores it in the next free spot in memory (starting at 0). If the input is char code 68 ("D"), it will branch to the letter parsing script. Otherwise, it branches back to the beginning of the header and takes another bit of STDIN.

## Letters:

```
S71 O255 S18 O254 S0 B134 B143
S79 O255 S25 O254 S0 B134 B149
S82 O255 S32 O254 S0 B134 B155
S66 O255 S39 O254 S0 B134 B158
S73 O255 S46 O254 S0 B134 B168
S84 O255 S53 O254 S0 B134 B172
S83 O255 S60 O254 S0 B134 B175
S65 O255 S67 O254 S0 B134 B179
S103 O255 S74 O254 S0 B134 B185
S111 O255 S81 O254 S0 B134 B193
S114 O255 S88 O254 S0 B134 B201
S98 O255 S95 O254 S0 B134 B207
S105 O255 S102 O254 S0 B134 B219
S116 O255 S109 O254 S0 B134 B224
S115 O255 S116 O254 S0 B134 B230

```

This section is rather self-explanatory. For each letter, you increment by an amount and then branch to subtraction. If it is 0 (i.e. the current letter is whatever the line is checking) it will then branch to the letter's parsing. Otherwise, it jumps to the next letter. When all letters are done being checked, it jumps to Potential Exit

## Potential Exit

```
S97 O255 S123 O254 S0 B134 B239 G251 s253 I1 A252 B255 S2 i251 i250 S0 B12

```

This section checks to see if there are no letters left to execute. If there are, it increments the pointers so they reference the next character + its argument, and then jump to the beginning of Letters. Otherwise, it terminates by branching to a null instruction.

## Subtraction

```
g251 s253 I1 A255 b254 S1 i254 S0 b254

```

Very simple. Uses XOR subtraction to check if the current character is equal to a character stored in another part of memory (set by the letters section).

## Letter Evaluation

```
g250 O248 g248 O249 S0 B124
g250 O248 G249 o248 S0 B124
r249 S0 B124 G249 B162 S0 B124
g250 O251 I1 O250 S0 B12 g250 i249 S0 B124 t249 S0 B124
g250 O249 S0 B124
g250 O248 g248 i249 S0 B124
g250 O248 g248 O248 g248 O249 S0 B124
g250 O248 g248 O248 G249 o248 S0 B124
g250 O248 R o248 S0 B124 G249 B211 S0 B124
g250 O248 g248 O251 I1 O250 S0 B12 g250 A249 o250 S0 B124
g250 O248 g248 T S0 B124
g250 O248 g248 O248 G249 s248 O249 S0 B124
g250 O248 g248 O248 G249 a248 O249 S0 B124

```

Each line corresponds to the same line in the Letters section. These simply interpret each character (G O R B I T S A g o r b i t s a) in descending order and then branch to Potential Exit.

# Answer
> 0 votes
# CHIQRSX9+ , 2 bytes

```
+I

```

There's no way to write a self-interpreting interpreter in this HQ9+-based language without using `I`, which runs a built-in interpreter that processes STDIN.

# Answer
> 0 votes
# Concurrent Filesystem Befunge 98 - 53\18 bytes (almost certainly cheating)

Full 53 byte interpreter with no restrictions (although I haven't tested complicated timing interactions involving IP splitting and wrapping):

```
v ;;;;;;;;
>]390'ai@
 t;;;;;;;;
;>zzzzz#;

```

Reads input from a file named `a` and executes it. It isn't specifed in the rules that we can't use self-modifying code.

18 byte interpreter that does not allow wrapping (the IP moving of one edge of the code and starting at the opposite edge):

```
]210'ai@
t
><

```

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


title: 26 Singers, 26 Letters

text:
# Question
Title: 26 Singers, 26 Letters
According to RollingStone, below are the 26 greatest singers of all time:

```
Aretha Franklin         Al Green
Ray Charles             Robert Plant
Elvis Presley           Mick Jagger
Sam Cooke               Tina Turner
John Lennon             Freddie Mercury
Marvin Gaye             Bob Marley
Bob Dylan               Smokey Robinson
Otis Redding            Johnny Cash
Stevie Wonder           Etta James
James Brown             David Bowie
Paul McCartney          Van Morrison
Little Richard          Michael Jackson
Roy Orbison             Jackie Wilson

```

You can get this as a list of strings here.

## Task

Given a singer name, print or return a letter from `A` to `Z` which uniquely identifies this singer. (If your code returns *A* for *Bob Dylan*, then it cannot return *A* for any other singer.)

As opposed to other similar challenges, ***the mapping is up to you*** as long as it's collision-free.

## Rules

* The input is guaranteed to be one of the 26 singer names listed above with this exact spelling and without any leading or trailing whitespace.
* You may output the letter in either lowercase or uppercase. But it must be consistent.
* You are encouraged to provide a test suite for all 26 possible inputs.
* This is , so the shortest answer in bytes wins!

# Answer
> 4 votes
# MATL, 28 bytes

```
s98\40\2Y2'ijkl o qst uz'hw)

```

Try it online!

### Explanation

```
s98\40\

```

Implicitly get the input string. Sum the characters of the input string, and do it modulus 98 followed by modulus 40. Results in one of the following numbers: `38 18 13 34 29 23 27 30 5 28 22 1 0 16 7 32 8 14 3 36 25 4 2 6 24 35` (in order of the Pastebin list).

```
2Y2'ijkl o qst uz'h

```

Push the (lowercase) alphabet with `2Y2`. This takes care of the numbers in the range \[1,26\]. However, some numbers are missing, and we have numbers up to 38. Hence, we append (`h`) a string that takes care of the higher numbers, by mapping these numbers to the 'missing' letters. The spaces can be anything, I used capital letters in my original program for my own convenience.

```
w)

```

We can now index the number from the first step into the string from the second step with `)`. We use `w` to get the arguments in the correct order. While it may seem that we use 0-based indexing (the numbers vary from 0 to 38, and the string is 39 characters long), the reality is actually a bit more complicated: we use 1-based modular indexing, a feature unique to MATL. This means that `1` indexes to `a`, `38` actually indexes to `u`, and `0` indexes to the final `z` of the string.

# Answer
> 23 votes
# Python 2, ~~80~~ 71 bytes

```
def f(s):i=sum(map(ord,s))%98%40;return chr(i-i/26*18+i/32*3-i/37*8+65)

```

Try it online!

The sums of ordinals modded give numbers between `0` and `38`

The numbers larger than 25 are then shifted to fill in the blanks as below (sorted sequence shown):

```
  0  1  2  3  4  5  6  7  8  -  -  -  - 13 14  - 16  - 18  -  -  - 22 23 24 25  - 27 28 29 30  - 32  - 34 35 36  - 38

```

Subtract `18` if `i>25`:

```
  0  1  2  3  4  5  6  7  8  -  -  -  - 13 14  - 16  - 18  -  -  - 22 23 24 25
                          - 27 28 29 30  - 32  - 34 35 36  - 38

```

Add `3` if `i>31`:

```
  0  1  2  3  4  5  6  7  8  -  -  -  - 13 14  - 16  - 18  -  -  - 22 23 24 25
                          - 27 28 29 30
                                                  - 32  - 34 35 36  - 38

```

Subtract `8` if `i>37`:

```
  0  1  2  3  4  5  6  7  8  -  -  -  - 13 14  - 16  - 18  -  -  - 22 23 24 25
                          - 27 28 29 30
                                                  - 32  - 34 35 36
                                            - 38

```

Which gives the sequence `0..25`

```
  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

```

These are then converted to `A-Z` with `chr(i+65)`

# Answer
> 22 votes
# 6502 machine code routine (C64), 83 bytes

```
20 FD AE 20 9E AD 85 FC 20 A3 B6 A9 79 85 FB A0 00 84 FD B1 22 10 03 69 A0 18
45 FD 65 FB 85 FD E6 FB C8 C4 FC D0 EC E9 29 B0 FC 69 29 C9 1A 90 1C 29 0F C9
0D 90 04 69 09 90 12 C9 02 F0 0F C9 08 D0 04 A9 06 D0 06 C9 0C D0 02 A9 11 18
69 41 4C D2 FF

```

This is position-independent code, just put it somewhere in RAM and jump there, e.g. using the `sys` command.

**Online demo** (loads to `$C000`/`49152`).

**Usage:** `sys49152,"[name]"`, e.g. `sys49152,"Aretha Franklin"`.

**Important:** If the program was load from disk (like in the online demo), issue a `new` command first! This is necessary because loading a machine program trashes some C64 BASIC pointers.

**Note:** The C64 is by default in a mode without lowercase letters -- in order to be able to enter *readable* names, switch to lowercase mode first by pressing `SHIFT`+`CBM`.

---

### Explanation

The challenge is in fact to find a minimal perfect hash function for these names; for the C64, I had to find one that's easily computable in simple 8bit operations. Here's a commented disassembly listing:

```
.C:c000  20 FD AE    JSR $AEFD          ; consume comma
.C:c003  20 9E AD    JSR $AD9E          ; evaluate expression
.C:c006  85 FC       STA $FC            ; save string length
.C:c008  20 A3 B6    JSR $B6A3          ; free string
.C:c00b  A9 79       LDA #$79           ; value for adding during hashing
.C:c00d  85 FB       STA $FB
.C:c00f  A0 00       LDY #$00           ; offset for reading string
.C:c011  84 FD       STY $FD            ; and initial hash value
.C:c013   .hashloop:
.C:c013  B1 22       LDA ($22),Y        ; read next character from string
.C:c015  10 03       BPL .xor           ; if bit 8 set (shifted)
.C:c017  69 A0       ADC #$A0           ; translate to same unshifted character
.C:c019  18          CLC
.C:c01a   .xor:
.C:c01a  45 FD       EOR $FD            ; xor with previous hash
.C:c01c  65 FB       ADC $FB            ; add offset
.C:c01e  85 FD       STA $FD            ; store new hash
.C:c020  E6 FB       INC $FB            ; increment offset
.C:c022  C8          INY
.C:c023  C4 FC       CPY $FC
.C:c025  D0 EC       BNE .hashloop      ; repeat until last character
.C:c027   .modloop:
.C:c027  E9 29       SBC #$29           ; subtract $29 until
.C:c029  B0 FC       BCS .modloop       ; underflow, then
.C:c02b  69 29       ADC #$29           ; add once again ( => mod $29)
.C:c02d  C9 1A       CMP #$1A           ; value in hash range?
.C:c02f  90 1C       BCC .tochar        ; -> output
.C:c031  29 0F       AND #$0F           ; mask lowest 4 bits only
.C:c033  C9 0D       CMP #$0D           ; greater 12 ?
.C:c035  90 04       BCC .fixedvals
.C:c037  69 09       ADC #$09           ; then just add 10 (9 plus carry)
.C:c039  90 12       BCC .tochar        ; and done -> output
.C:c03b   .fixedvals:
.C:c03b  C9 02       CMP #$02           ; 2 becomes 3 by adding
.C:c03d  F0 0F       BEQ .tochar2       ; with carry (jump after the CLC)
.C:c03f  C9 08       CMP #$08           ; if value was 8
.C:c041  D0 04       BNE .check2
.C:c043  A9 06       LDA #$06           ; new value is 6
.C:c045  D0 06       BNE .tochar        ; and output
.C:c046   .check2:
.C:c047  C9 0C       CMP #$0C           ; else if value was 12
.C:c049  D0 02       BNE .tochar
.C:c04b  A9 11       LDA #$11           ; new value is 17
.C:c04d   .tochar:
.C:c04d  18          CLC
.C:c04d   .tochar2:
.C:c04e  69 41       ADC #$41           ; add character code for 'a'
.C:c050  4C D2 FF    JMP $FFD2          ; jump to kernal CHROUT routine

```

---

### Test suite (C64 BASIC, containing the machine code routine in `data` lines)

```
0fOa=49152to49234:rEb:pOa,b:nE:pO53272,23
1sY49152,"Aretha Franklin":?":Aretha Franklin"
2sY49152,"Ray Charles":?":Ray Charles"
3sY49152,"Elvis Presley":?":Elvis Presley"
4sY49152,"Sam Cooke":?":Sam Cooke"
5sY49152,"John Lennon":?":John Lennon"
6sY49152,"Marvin Gaye":?":Marvin Gaye"
7sY49152,"Bob Dylan":?":Bob Dylan"
8sY49152,"Otis Redding":?":Otis Redding"
9sY49152,"Stevie Wonder":?":Stevie Wonder"
10sY49152,"James Brown":?":James Brown"
11sY49152,"Paul McCartney":?":Paul McCartney"
12sY49152,"Little Richard":?":Little Richard"
13sY49152,"Roy Orbison":?":Roy Orbison"
14sY49152,"Al Green":?":Al Green"
15sY49152,"Robert Plant":?":Robert Plant"
16sY49152,"Mick Jagger":?":Mick Jagger"
17sY49152,"Tina Turner":?":Tina Turner"
18sY49152,"Freddie Mercury":?":Freddie Mercury"
19sY49152,"Bob Marley":?":Bob Marley"
20sY49152,"Smokey Robinson":?":Smokey Robinson"
21sY49152,"Johnny Cash":?":Johnny Cash"
22sY49152,"Etta James":?":Etta James"
23sY49152,"David Bowie":?":David Bowie"
24sY49152,"Van Morrison":?":Van Morrison"
25sY49152,"Michael Jackson":?":Michael Jackson"
26sY49152,"Jackie Wilson":?":Jackie Wilson"
27dA32,253,174,32,158,173,133,252,32,163,182,169,121,133,251,160,0,132,253,177
28dA34,16,3,105,160,24,69,253,101,251,133,253,230,251,200,196,252,208,236,233
29dA41,176,252,105,41,201,26,144,28,41,15,201,13,144,4,105,9,144,18,201,2,240
30dA15,201,8,208,4,169,6,208,6,201,12,208,2,169,17,24,105,65,76,210,255

```

**Online demo of test suite**.

# Answer
> 14 votes
# Python 2, 68 bytes

```
def f(n):i=hash(n)%337%125%45;return chr(65+i-i/25*2-i/29*21+i/35*2)

```

Try it online!

# Answer
> 10 votes
# Javascript, ~~138~~ 132 characters

As all initials are unique, except for `MJ` = **M**ichael **J**ackson / **M**ick **J**agger, I check for Michael Jackson specifically (the only one with an `h` on the 4th position), and for all other names I created a string with the initials followed by a unique letter.

```
s=>s[3]=='h'?'y':"AFaRCbEPcSCdJLeMGfBDgORhSWiJBjPMCkLRlROmAGnRPoMJpTTqFMrBMsSRtJCuEJvDBwVMxJWz".split(s.replace(/[^A-Z]/g,''))[1][0]

```

### Code Snippet

Try it here:

```
var solution =
s=>s[3]=='h'?'y':"AFaRCbEPcSCdJLeMGfBDgORhSWiJBjPMCkLRlROmAGnRPoMJpTTqFMrBMsSRtJCuEJvDBwVMxJWz".split(s.replace(/[^A-Z]/g,''))[1][0]

var testnames = [
"Aretha Franklin",
"Ray Charles",
"Elvis Presley",
"Sam Cooke",
"John Lennon",
"Marvin Gaye",
"Bob Dylan",
"Otis Redding",
"Stevie Wonder",
"James Brown",
"Paul McCartney",
"Little Richard",
"Roy Orbison",
"Al Green",
"Robert Plant",
"Mick Jagger",
"Tina Turner",
"Freddie Mercury",
"Bob Marley",
"Smokey Robinson",
"Johnny Cash",
"Etta James",
"David Bowie",
"Van Morrison",
"Michael Jackson",
"Jackie Wilson"
];
testnames.forEach(name=>document.body.append( solution(name) ));
```

# Answer
> 7 votes
# Java (OpenJDK 8), 128 126 115 113 bytes

Not too shabby for a java submission!

Thanks to Kevin for saving me a whole lot of bytes with the lambda expressions!

```
s->{int a=0;for(int i:s.substring(1,6).getBytes())a+=i;a*=a==431?0.108:2.65108;return(char)(a==1341?70:a%26+65);}

```

Try it online!

# Answer
> 6 votes
# Python 3, ~~132~~ ~~99~~ 96 bytes

```
lambda m:chr(98+"ԇ̲ЙГ̫ѼӿИԸՋжʾҍϴЬֺΝעЕΞϾҞ֜ӣ֪".find(chr(sum(map(ord,m)))))

```

Try it online!

Not golfed brilliantly, but I thought I'd give this a go.

<sup>-33 bytes thanks to modifications made by TFeld.
-3 bytes by using `find` instead of `index` thanks to ovs.</sup>

# Answer
> 5 votes
# PHP, ~~90 88 86~~ 72+1 bytes

might become even shorter with a different modulo.

```
<?=strtr(chr(hexdec(substr(md5($argn),0,2))%65+58),"^<adins",bcfgqvx)&_;

```

Save to file and run as pipe with `-nF` or try it online.

# Answer
> 5 votes
# Perl, ~~56~~, ~~54~~, ~~50~~, 46 +1 (-p) bytes

~~$*=crypt$*,DT;/..(.)/;$\_=$1;y/01268ADIJNVW/adhilmnpqsux/~~

~~$*=crypt$*,DT;/..(.)/;$*=$1;y/01268JVW/hlmpqsux/;$*=lc~~

~~$*=crypt$*,mO;/..(.)/;$*=$1;y/035eft/AHPRXZ/;$*=lc~~

Thanks to Dom's comment could save 4 more bytes, also changed to uppercase to fit better requierements.

```
$_=crypt$_,mO;y/035eft/AHPRXZ/;/..(.)/;$_=uc$1

```

Try It Online

# Answer
> 4 votes
# Python 2, 50 43 bytes

Credit to japh for the new version

```
lambda n:chr(hash(n)%2354%977%237%54%26+65)

```

Try it online!

Note: This is dependent on the `hash` builtin and will not work in all implementations

# Answer
> 3 votes
# Ruby, 63 bytes

```
->s{((0x3c4001c151861b27d>>s.sum%98%66).to_s(2).sum%48+64).chr}

```

Adds the ascii codes of the input, takes them mod 98 and then mod 66 to get a one of 26 unique numbers `n` in the range 0..65. The huge hexadecimal number contains a `1` bit in each of these 26 places, so by rightshifting it by `n` we obtain a number with 1..26 `1` bits in it. We count the `1` bits by adding the ascii codes and taking mod 48, then add 64 and convert to an ASCII code.

**Test program**

the `map` iterates through the singers printing the letter code and singer. It then returns an array of the letter codes, which is `sort`ed to demonstrate that each letter is used once.

```
f=->s{((0x3c4001c151861b27d>>s.sum%98%66).to_s(2).sum%48+64).chr}
a= [
  "Aretha Franklin","Ray Charles",
  "Elvis Presley","Sam Cooke",
  "John Lennon","Marvin Gaye",
  "Bob Dylan","Otis Redding",
  "Stevie Wonder","James Brown",
  "Paul McCartney","Little Richard",
  "Roy Orbison","Al Green",
  "Robert Plant","Mick Jagger",
  "Tina Turner","Freddie Mercury",
  "Bob Marley","Smokey Robinson",
  "Johnny Cash","Etta James",
  "David Bowie","Van Morrison",
  "Michael Jackson","Jackie Wilson"
]

p a.map{|i|p [f[i],i];f[i]}.sort

```

**Output**

```
["S", "Aretha Franklin"]
["E", "Ray Charles"]
["R", "Elvis Presley"]
["J", "Sam Cooke"]
["X", "John Lennon"]
["C", "Marvin Gaye"]
["M", "Bob Dylan"]
["W", "Otis Redding"]
["V", "Stevie Wonder"]
["Y", "James Brown"]
["D", "Paul McCartney"]
["Q", "Little Richard"]
["Z", "Roy Orbison"]
["P", "Al Green"]
["O", "Robert Plant"]
["K", "Mick Jagger"]
["N", "Tina Turner"]
["L", "Freddie Mercury"]
["G", "Bob Marley"]
["I", "Smokey Robinson"]
["A", "Johnny Cash"]
["F", "Etta James"]
["H", "David Bowie"]
["U", "Van Morrison"]
["B", "Michael Jackson"]
["T", "Jackie Wilson"]
["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

```

# Answer
> 3 votes
# JavaScript (Chrome), 102

**Note** Unfortunately it works only in Chrome, because of implementation-dependent approximations in parseInt() (thanks @Arnauld)

```
s=>s[0]=='L'?'z':"ab.c..defghijklmn...o..pqrst.u.vwxy"[parseInt(s.replace(/ /,'o').slice(0,14),36)%35]

```

I looked for a hash function, taking a slice of each name, converting to numbers using base 36 and then applying a modulo.

I used this code to look for the best hash:

```
x=`Al Green\nAretha Franklin\nBob Dylan\nBob Marley\nDavid Bowie\nElvis Presley\nEtta James\nFreddie Mercury\nJackie Wilson\nJames Brown\nJohn Lennon\nJohnny Cash\nLittle Richard\nMarvin Gaye\nMichael Jackson\nMick Jagger\nOtis Redding\nPaul McCartney\nRay Charles\nRobert Plant\nRoy Orbison\nSam Cooke\nSmokey Robinson\nStevie Wonder\nTina Turner\nVan Morrison`.split(`\n`)

max=0
for(m=26;m<60;m++)
  for(i=0;i<20;i++)
    for(j=i;++j<20;)
      for(k=0;k<37;k++)
      {
        S=new Set();
        f=k ? (k-1).toString(36) : ''
        x.forEach(x=>(n=parseInt(x.replace(/ /,f).slice(i,j),36)%m, S.add(n)))
        if (S.size > max) console.log(i,j,f,m,max=S.size)
      }

```

And the results:

```
0 1 "" 26 14
0 2 "" 26 15
0 4 "" 26 16
0 5 "" 26 18
0 6 "0" 26 19
0 6 "3" 26 20
0 8 "a" 26 21
2 5 "7" 28 23
0 14 "h" 35 24
0 14 "o" 35 25
2 9 "" 51 26

```

The best hash function gives 26 different values between 0 and 50, but I used a different one, with 1 duplicate but a smaller range.

**Test**

```
var names=x=`Al Green\nAretha Franklin\nBob Dylan\nBob Marley\nDavid Bowie\nElvis Presley\nEtta James\nFreddie Mercury\nJackie Wilson\nJames Brown\nJohn Lennon\nJohnny Cash\nLittle Richard\nMarvin Gaye\nMichael Jackson\nMick Jagger\nOtis Redding\nPaul McCartney\nRay Charles\nRobert Plant\nRoy Orbison\nSam Cooke\nSmokey Robinson\nStevie Wonder\nTina Turner\nVan Morrison`.split(`\n`)

var F=
s=>s[0]=='L'?'z':"ab.c..defghijklmn...o..pqrst.u.vwxy"[parseInt(s.replace(/ /,'o').slice(0,14),36)%35]

var Singers={}
names.forEach(n=>Singers[F(n)]=n)

;Object.keys(Singers).sort().forEach(i=> console.log(i, Singers[i]))
```

# Answer
> 3 votes
# Octave, ~~85 83 80~~ 74 bytes

```
@(n)('A':'Z')(mod(n([1 2 8])*[1;15;47],124)=='#iZo,gp<C&4Y1!8-G`Kn3wtTIO')

```

This mess of an anonymous is the result of some messing around in MATLAB trying to find a good way to encode the data.

Basically after a quick analysis, only letters 1,2, and 8 of the input string (smallest string is 8 chars, so we are good) are needed to produce a unique value from each input. The hard part is then converting that unique value into something usable.

MATLAB is terrible at compressing data, so I had to look for another way to make the lookup mapping. I set out trying to find some function on the three input letters that resulted in a unique value that was also a printable ASCII value so that I could embed the mapping in a string of one character per input.

It turns out that matrix multiplying the characters at index `[1 2 8]` by the integer matrix `[1;15;47]` and then performing mod 124 results in unique values which all printable ASCII (and none are a `'` character which would bugger up string literals). Pleasingly the mapping ends with `TIO` which is completely accidental. Interestingly this is the **only mapping** for this equation that gives 26 unique printable ASCII characters.

So basically that is my lookup mapping and calculation. Doing the lookup is simply a case of performing the calculation and comparing with the mapping. Adding on `'A'-1` to the index in the map results in a character A-Z.

You can try it online on TIO, which shows the full mapping of inputs and outputs. For completeness the full mapping is also below:

```
'Aretha Franklin' ==> B
'Ray Charles'     ==> S
'Elvis Presley'   ==> F
'Sam Cooke'       ==> V
'John Lennon'     ==> L
'Marvin Gaye'     ==> N
'Bob Dylan'       ==> C
'Otis Redding'    ==> Q
'Stevie Wonder'   ==> X
'James Brown'     ==> I
'Paul McCartney'  ==> R
'Little Richard'  ==> M
'Roy Orbison'     ==> T
'Al Green'        ==> A
'Robert Plant'    ==> U
'Mick Jagger'     ==> P
'Tina Turner'     ==> Y
'Freddie Mercury' ==> H
'Bob Marley'      ==> D
'Smokey Robinson' ==> W
'Johnny Cash'     ==> K
'Etta James'      ==> G
'David Bowie'     ==> E
'Van Morrison'    ==> Z
'Michael Jackson' ==> O
'Jackie Wilson'   ==> J

```

---

* Saved 2 bytes tweaking mapping to remove `+32`.
* Saved 3 bytes by making Octave-only using logical indexing of `'A':'Z'` rather than find.
* Saved 6 bytes by doing sum of multiplications using matrix multiplication.

# Answer
> 3 votes
# C, ~~65~~ ~~55~~ 49 bytes

~~`h(char*s){return*s<77?(*s^s[5]+40)%13+65:(s[5]&s[4]+s[1])%13+78;}`~~

~~`h(char*s){return*(long*)s%887%392%224%120%67%40%26+65;}`~~

Same approach as KSab's answer. C doesn't provide a string `hash` function like Python. Or does it?

```
h(char*s){return*(long*)s%2004%857%361%94%26+65;}

```

Try it online!

`h` returns an `int` whose values are the ASCII codes for `A .. Z`.

# Answer
> 3 votes
# APL (Dyalog), 48 bytes

```
⎕A[' $%&().279<?@CL'⍳⎕UCS 78|7⊥⎕UCS⍞]

```

Assumes `⎕IO←0` (array indexing set to start from 0 instead of 1).

Try it online!

### Explained

It's a complete program; the outer part `⎕A[]` is indexing somewhere into the uppercase alphabet to get the output character. Inside the brackets it reads right-to-left, and  is a prompt for a string input. `⎕UCS` turns that into Unicode char values. `78|7⊥` decodes those values as if they were digits in base 7, then takes the answer modulo 78 (brute forced to find a base and modulo combination which give usable ASCII character values). `⎕UCS` again to turn that single number into a character, and look it up  in the magic string `'...'` of 26 identifier characters. That position becomes the index into the `⎕A[]` uppercase alphabet. (There are control chars in the string, the ASCII codes are `11 14 18 20 22 23 24 25 26 30 31 32 36 37 38 40 41 46 50 55 57 60 63 64 67 76`).

The full mapping is:

```
      singers←'Aretha Franklin' 'Al Green' 'Ray Charles' 'Robert Plant' 'Elvis Presley' 'Mick Jagger' 'Sam Cooke' 'Tina Turner' 'John Lennon' 'Freddie Mercury' 'Marvin Gaye' 'Bob Marley' 'Bob Dylan' 'Smokey Robinson' 'Otis Redding' 'Johnny Cash' 'Stevie Wonder' 'Etta James' 'James Brown' 'David Bowie' 'Paul McCartney' 'Van Morrison' 'Little Richard' 'Michael Jackson' 'Roy Orbison' 'Jackie Wilson'

      f←{⎕A[' $%&().279<?@CL'⍳⎕UCS 78|7⊥⎕UCS⍵]}

      ¯1⌽' ',(↑singers),f¨singers
┌→────────────────┐
↓P Aretha Franklin│
│J Al Green       │
│M Ray Charles    │
│N Robert Plant   │
│U Elvis Presley  │
│Z Mick Jagger    │
│L Sam Cooke      │
│G Tina Turner    │
│F John Lennon    │
│B Freddie Mercury│
│Q Marvin Gaye    │
│H Bob Marley     │
│K Bob Dylan      │
│C Smokey Robinson│
│D Otis Redding   │
│T Johnny Cash    │
│Y Stevie Wonder  │
│I Etta James     │
│X James Brown    │
│O David Bowie    │
│E Paul McCartney │
│V Van Morrison   │
│A Little Richard │
│S Michael Jackson│
│R Roy Orbison    │
│W Jackie Wilson  │
└─────────────────┘

```

And the sorted letters of the mapping is exactly the uppercase alphabet (no dupes or missing):

```
      f¨singers
┌→─────────────────────────┐
│PJMNUZLGFBQHKCDTYIXOEVASRW│
└──────────────────────────┘

      (⊂∘⍋⌷⊢) f¨singers    ⍝ sorted
┌→─────────────────────────┐
│ABCDEFGHIJKLMNOPQRSTUVWXYZ│
└──────────────────────────┘

      ⎕A ≡ (⊂∘⍋⌷⊢) f¨singers    ⍝ matches the alphabet
1

```

# Answer
> 2 votes
## Javascript, 98 bytes

```
s=l=>("heCysvCm hirDb iiesm ultOyr rb c ndeMbeonh tdvMnacic".indexOf(l[4]+l[2])/2+10).toString(36)

```

I found that the combination of the 2nd and the 4th character of the names is unique for each of them.

Therefore I create a string with the combinations of `name[4] + name[2]`, not `name[2] + name[4]` or I would have a repetition of the char group `eh` of the first name Aretha Franklin `eh` and when Smokey Robinson and Johnny Cash `oehn` are concatenated.

I could just move Johnny Cash to another position of the string and get a different mapping, but concatenating the 4th and the 2nd character in this order avoids the collision and leaves the dataset order intact without adding more length to the solution. So I decided to go that way (it's just personal preference)

I search for the position of the concatenation of the 4nd and 2nd letter of the given parameter in the string and divide it by 2 so that I get a number between 0 and 25. Then I add 10 and convert it to string from base 36, where 10 corresponds to `a` and 35 to `z`

```
let singers = [
  "Aretha Franklin",
  "Ray Charles",
  "Elvis Presley",
  "Sam Cooke",
  "John Lennon",
  "Marvin Gaye",
  "Bob Dylan",
  "Otis Redding",
  "Stevie Wonder",
  "James Brown",
  "Paul McCartney",
  "Little Richard",
  "Roy Orbison",
  "Al Green",
  "Robert Plant",
  "Mick Jagger",
  "Tina Turner",
  "Freddie Mercury",
  "Bob Marley",
  "Smokey Robinson",
  "Johnny Cash",
  "Etta James",
  "David Bowie",
  "Van Morrison",
  "Michael Jackson",
  "Jackie Wilson"
]

s=l=>("heCysvCm hirDb iiesm ultOyr rb c ndeMbeonh tdvMnacic".indexOf(l[4]+l[2])/2+10).toString(36)

singers.forEach(singer => console.log(s(singer), singer))
```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 101 ~~126~~ bytes

```
Alphabet[][[#&@@#&@@Position[(t=ToCharacterCode)@"nZ-Be_;f%d^q 0w@x~KDaLJ&`k",Total@t@#~Mod~98+32]]]&

```

`+32` seems leading to the shortest stirng hashtable in Mathematica `InputForm`.

Try it online!

# Answer
> 1 votes
# ///, ~~390~~ 231 bytes

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

```

Try it online!

231 bytes after removing the newlines.

This is very long, but /// cannot handle different characters generically. In other words, /// does not support regex.

# Answer
> 1 votes
# Excel, 96 bytes

After too much time wasted trying other approaches, have implemented @Eduardo Paez's approach:

```
=CHAR(FIND(MID(A1,5,1)&MID(A1,3,1),"her DbMbdvsv tdeicsm hnhltirac c i uCyrbOyCmeoie nMn")/2+65)

```

---
Tags: code-golf, hashing
---


# Question
Title: Diophantine Approximation: find lowest possible denominator to approximate within given precision
## Challenge

Given a number `x` and a precision `e`, find the lowest positive integer `q` such that `x` can be approximated as a fraction `p / q` within precision `e`.

In other words, find the lowest positive integer `q` such that there exists an integer `p` such that `abs(x - p/q) < e`.

## Input

* The pair `(x, e)` where `x` is a floating-point number, and `e` is a positive floating-point number.
* **Alternatively**, a pair `(x, n)` where `n` is a nonnegative integer; then `e` is implicitly defined as `10**(-n)` or `2**(-n)`, meaning `n` is the precision in number of digits/bits.

Restricting `x` to positive floating-point is acceptable.

## Output

The denominator `q`, which is a positive integer.

## Test cases

* Whenever `e > 0.5` ------------------------\> `1` because `x` ≈ an integer
* Whenever `x` is an integer ----------------\> `1` because `x` ≈ itself
* `(3.141592653589793, 0.2)` ------------\> `1` because `x` ≈ 3
* `(3.141592653589793, 0.0015)` --------\> `7` because `x` ≈ 22/7
* `(3.141592653589793, 0.0000003)` ---\> `113` because `x` ≈ 355/113
* `(0.41, 0.01)` -------------------------------\> `12` for 5/12 or `5` for 2/5, see Rules below

## Rules

* This is code-golf, the shortest code wins!
* Although the input is "a pair", how to encode a pair is unspecified
* The type used for `x` must allow a reasonable precision
* Floating-point precision errors can be ignored as long as the algorithm is correct. For instance, the output for `(0.41, 0.01)` should be `12` for 5/12, but the output `5` is acceptable because 0.41-2/5 gives 0.009999999999999953

## Related challenges

# Answer
# , Xx bytes

*Note: this challenge is quite a good introductory-challenge for , which is the 'language-of-the-month' for September 2020, so I've blanked-out my answer in the hope of encouraging some other golfers to have a shot at it in , too...*

> 50 bytes

> `function(x,e,s=1:e^-1)s[(x-round(x*s)/s)^2<e^2][1]`

Try it online!

Function with arguments x & error e. Can handle negative x (even though not required for challenge)

---

*Note 2: dammit! a port of xnor's approach is 6 bytes shorter still:*

> 44 bytes

> `function(x,e,s=1:e^-1)s[(x+e)%%(1/s)<2*e][1]`

Try it online!
> 7 votes

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

```
∞.Δ*`Dòα›

```

Try it online!

**Commented:**

```
          # implicit input                    [e, x]
∞         # in the list of natural numbers
 .Δ       # find the first that satisfies:    [e, x], q
   *      #   multiply                        [e*q, x*q]
    `     #   dump on stack                   e*q, x*q
     D    #   duplicate                       e*q, x*q, x*q
      ò   #   round to integer                e*q, x*q, round(x*q)
       α  #   absolute difference             e*q, abs(x*q - round(x*q))
        › #   is this larger?                 e*q > abs(x*q - round(x*q))

```
> 5 votes

# Answer
# Python, 46 bytes

```
f=lambda x,e,q=1:(x+e)%(1/q)<e*2or-~f(x,e,q+1)

```

Try it online!

We want to check that \\$x\\$ is within \\$\pm \epsilon\\$ of a multiple of \\$1/q\\$, that is, it falls within the interval \\$(-\epsilon,\epsilon)\\$ modulo \\$1/q\\$. To do this, we take \\$x+\epsilon\\$, reduce it modulo \\$1/q\\$, and check if the result is at most \\$2 \epsilon\\$.

A same-length alternative using only `%1`, which might help with porting:

```
f=lambda x,e,q=1:(x+e)*q%1<e*q*2or-~f(x,e,q+1)

```

Try it online!
> 5 votes

# Answer
# MATL, ~~17~~ 5 bytes

```
2$YQ&

```

Try it online! Or verify all test cases.

### Explanation

```
2$   % The next function will take two inputs
YQ   % (Implicit inputs: x, e). Rational approximation with specified tolerance.
     % Gives two outputs: numerator and denominator
&    % The next function will use its alternative default input/output
     % configuration
     % (Implicit) Display. With the alternative specification, this displays
     % only the top of the stack, that is, the denominator

```

## Manual approach: 17 bytes

```
`GZ}1\@:q@/-|>~}@

```

Try it online! Or verify all test cases.

### Explanation

```
`       % Do...while
  GZ}   %   Push input: array [e, x]. Split into e and x
  1\    %   Modulo 1: gives fractional part of x (*)
  @:q   %   Push [0, 1, ... , n-1], where n is iteration index
  @/    %   Divide by n, element-wise: gives [0, 1/n, ..., (n-1)/n]
  -|    %   Absolute difference between (*) and each entry of the above
  >~    %   Is e not greater than each absolute difference? (**)
}       % Finally (execute on loop exit)
  @     %   Push current iteration index. This is the output
        % End (implicit). A new iteration is run if all entries of (**) are true;
        % that is, if all absolute differences were greater than or equal to e
        % Display (implicit)

```
> 3 votes

# Answer
# Wolfram Language (Mathematica), 24 bytes

```
Denominator@*Rationalize

```

Try it online!

All the credits go to @the default
> 3 votes

# Answer
# JavaScript (ES7), 38 bytes

Expects `(x)(e)`.

A port of @xnor's method, which is significantly shorter than my original approach.

```
(x,q=0)=>g=e=>(x+e)%(1/++q)<e*2?q:g(e)

```

Try it online!

---

# JavaScript (ES7), 46 bytes

Expects `(x)(e)`.

```
(x,q=0)=>g=e=>((x*++q+.5|0)/q-x)**2<e*e?q:g(e)

```

Try it online!

We want to avoid using the lengthy `Math.round()` and `Math.abs()`. So we look for the lowest \\$q\>0\\$ such that:

$$\left(\frac{\left\lfloor xq+\frac{1}{2}\right\rfloor}{q}-x\right)^2\<e^2$$
> 3 votes

# Answer
# Python 3, ~~74~~ \\$\cdots\\$ ~~52~~ 50 bytes

Saved ~~a~~ ~~4~~ 6 bytes thanks to ovs!!!

```
f=lambda x,e,q=1:not-x*q%1>e*q<x*q%1or-~f(x,e,q+1)

```

Try it online!
> 3 votes

# Answer
# C (gcc), ~~63~~ ~~59~~ 58 bytes

Saved a byte using xnor's idea in his Python answer!!!

```
i;f(x,e,q)float x,e,q;{for(q=0;fmod(x+e,1/++q)>2*e;);i=q;}

```

Try it online!
> 3 votes

# Answer
# Charcoal, 27 bytes

```
ＮθＮη≔¹ζＷ›↔⁻∕⌊⁺·⁵×θζζθη≦⊕ζＩζ

```

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

```
ＮθＮη

```

Input \\$ x \\$ and \\$ \epsilon \\$.

```
≔¹ζ

```

Start off with \\$ q = 1 \\$.

```
Ｗ›↔⁻∕⌊⁺·⁵×θζζθη

```

Calculate \\$ p = \lfloor 0.5 + q z \rfloor \\$ and repeat while \\$ | \frac p q - x | \> \epsilon \\$...

```
≦⊕ζ

```

... increment \\$ q \\$.

```
Ｉζ

```

Output \\$ q \\$.
> 2 votes

# Answer
# Scala, ~~84~~ ~~60~~ 52 bytes

*Saved a whopping 24 bytes thanks to @Dominic van Essen!*

```
x=>e=>1 to 9<<30 find(q=>(x-(x*q+.5).floor/q).abs<e)

```

Try it online!
> 2 votes

# Answer
# Java (JDK), 52 bytes

Port of xnor’s method

```
x->e->{int q=0;for(;(x+e)%(1./++q)>=e*2;);return q;}

```

Try it online!

# Java (JDK), ~~83~~ 69 bytes

```
x->e->{int q=0;for(;Math.abs(x-Math.ceil(x*++q-.5)/q)>=e;);return q;}

```

Try it online!
> 1 votes

# Answer
# Wolfram Language 89 bytes

```
f[n_,e_]:=Denominator@Cases[{#,Abs[n-#]}&/@Convergents@n,x_/;x[[2]]<=e][[1,1]]

```

---

```
f[0.41,.01]
(* 5. *)

```

This uses the convergents as candidates for approximations.

```
pi = 3.1415926535897932384626433832795028842

```

The first 8 convergents of pi:

```
Convergents[pi, 8]
(* {3, 22/7, 333/106, 355/113, 103993/33102, 104348/33215, 208341/66317, 312689/99532}*)

f[pi, 0.01]
(* 7 *)

f[pi, 0.001]
(* 106 *)

f[pi, 0.00001]
(* 113 *)

f[pi, 0.0000001]
(* 33102 *)

f[pi, 0.0000000001]
(* 99532 *)

```
> 1 votes

# Answer
# Perl 5, 58 bytes

```
sub f{grep{$p=$_[0]*$_;abs$p-int$p+.5<$_[1]*$_}1..1/$_[1]}

```

Try it online!
> 1 votes

---
Tags: code-golf, math, number, rational-numbers, approximation
---


title: Spiralize a Word, Triangularly!

text:
# Question
Title: Spiralize a Word, Triangularly!
## Challenge

Given a string of any length, write it as a triangle, spiraling out from the center. For example, `abcdefghijklmnop` becomes:

```
   g
  fah
 edcbi
ponmlkj

```

Or more explicitly:

If you like, you can spiral counter-clockwise instead:

```
   g
  haf
 ibcde
jklmnop

```

Or add spaces uniformly:

```
      g

    f a h

  e d c b i

p o n m l k j

```

The input characters will be ascii, but may include spaces. Also, the number of characters may not be a perfect square (`Hello World!`):

```
  W
  Ho
oller
   !dl

```

A couple more edge cases. 2 letter input `ab`:

```
 a
  b

```

And 3 letter input `abc`:

```
 a
 cb

```

## Procedural Description

In case the above examples aren't clear, here's a procedural description of the process:

1. Put down your initial letter.
2. Move diagonally down and to the right (i.e., this direction `\`). So if you started at `(0,0)`, you will now be at (1,-1). Put down your second letter.
3. Move left one space a time, dropping a letter on each space, for a total of 3 spaces. That is, drop letters on `(0,-1)`, `(-1,-1)`, and `(-2, -1)`.
4. Next move diagonally up and to the right `/` two spaces, dropping letters on `(-1,0)` and `(0,1)`.
5. Now cycle back to moving diagonally down and to the right, continuing to step and drop letters as long as your current position is left-right adjacent to an existing letter.
6. Next move left again, continuing to step and drop letters as long as you are diagonally adjacent `/` to an existing letter.
7. Move diagonally up and to the right again `/`, stepping and dropping letters as long as your current position is left-right adjacent to an existing letter.
8. Repeat steps 5-7 until all letters are used up.

## More examples

## Rules

* Code golf, standard rules apply.
* Trailing spaces or newlines are ok.
* Consistent leading spaces or newlines are also ok, as long as the shape of the triangle is preserved.

# Answer
> 8 votes
# 05AB1E, ~~24~~ ~~20~~ ~~15~~ 13 bytes

```
2Iā¨t·îŽOGsèΛ

```

-7 bytes by porting *@Neil*'s Charcoal answer, using *@att*'s formula, so make sure to upvote both of them as well!

Try it online. No test suite, because the  builtin will keep its previous contents and there isn't any way to reset it (this is what it would look like.

**Explanation:**

```
2              # Push a 2
 I             # Push the input-string
  ā            # Push a list in the range [1,length] (without popping)
   ¨           # Remove the last value to change the range to [1,length)
    t          # Take the square-root of each value
     ·         # Double each
      î        # Ceil each
       ŽOG     # Push compressed integer 6136
          s    # Swap so the list is at the top of the stack again
           è   # Index each value (0-based and modulair) into the 6136
            Λ  # Pop all three and use the Canvas builtin,
               # after which the result is implicitly output immediately afterwards

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `ŽOG` is `6136`.

The Canvas builtin uses three arguments to draw a shape:

* Character/string to draw: the input in this case
* Length of the lines we'll draw: `2` in this case
* The direction to draw in: `[3,6,6,6,1,1,3,3,3,6,6,6,6,6,6,6,1,1,1,1,3,...]`.

See the original answer below for an explanation of the Canvas builtin. Unlike the program below where the list of lengths are leading, here the list of directions are leading because we use a single length of `2`.

---

**Original ~~24~~ 20 bytes answer:**

```
ā·Ð·s>ø.ι˜DŠOð×«₆1ªΛ

```

Contains leading/trailing spaces and newlines (the longer the input, the more spaces/newlines)

Try it online. No test suite, because the  builtin will keep its previous contents and there isn't any way to reset it (this is what it would look like, where the test cases are drawn on top of one another).

**Explanation:**

```
ā           # Push a list in the range [1, length] of the (implicit) input (without popping)
            #  i.e. "Hello World!" → "Hello World!" and [1,2,3,4,5,6,7,8,9,10,11,12]
 ·          # Double each value in this list
            #  → [2,4,6,8,10,12,14,16,18,20,22,24]
  Ð         # Triplicate it
   ·        # Double each value of the top copy
            #  → [4,8,12,16,20,24,28,32,36,40,44,48]
    s       # Swap to get the other copy
     >      # Increase each by 1
            #  → [3,5,6,9,11,13,15,17,19,21,23,25]
      ø     # Create pairs of the top two lists
            #  → [[4,3],[8,5],[12,7],[16,9],[20,11],[24,13],[28,15],[32,17],[36,19],[40,21],[44,23],[48,25]]
       .ι   # Interleave it with the third list
            #  → [2,[4,3],4,[8,5],6,[12,7],8,[16,9],10,[20,11],12,[24,13],14,[28,15],16,[32,17],18,[36,19],20,[40,21],22,[44,23],24,[48,25]]
         ˜  # Flatten
            #  → [2,4,3,4,8,5,6,12,7,8,16,9,10,20,11,12,24,13,14,28,15,16,32,17,18,36,19,20,40,21,22,44,23,24,48,25]
D           # Duplicate this list of integers
 Š          # Triple-swap, so the stack order is list,input,list
  O         # Pop and sum the top list
            #  → 636
   ð×       # Create a string of that many spaces
     «      # And append it to the string
₆           # Push builtin 36
 1ª         # Convert it to a list of digits, and append 1: [3,6,1]
Λ           # Use the Canvas builtin with these three arguments,
            # after which the result is implicitly output immediately afterwards

```

The Canvas builtin uses three arguments to draw a shape:

* Character/string to draw: the input in this case, appended with trailing spaces
* Length of the lines we'll draw: the list `[2,4,3,4,8,5,6,12,7,8,16,9,10,20,11,...]`
* The direction to draw in: `[3,6,1]`. The digits in the range \\$\[0,7\]\\$ each represent a certain direction:

```
7   0   1
  ↖ ↑ ↗
6 ← X → 2
  ↙ ↓ ↘
5   4   3

```

So the `[3,6,1]` in this case translate to the directions \\$\[↘,←,↗\]\\$.

Here a step-by-step explanation of the output (we'll use input `"Hello_World!"` as example here):

Step 1: Draw 2 characters (`"He"`) in direction `3↘`:

```
H
 e

```

Step 2: Draw 4-1 characters (`"llo"`) in direction `6←`:

```
  H
olle

```

Step 3: Draw 3-1 characters (`"_W"`) in direction `1↗`:

```
  W
 _H
olle

```

Step 4: Draw 4-1 characters (`"orl"`) in direction `3↘`:

```
  W
 _Ho
oller
     l

```

Step 5: Draw 8-1 characters (`"d! "`) in direction `6←`:

```
   W
  _Ho
 oller
    !dl

```

Et cetera for all other trailing spaces.

See this 05AB1E tip of mine for an in-depth explanation of the Canvas builtin.

# Answer
> 15 votes
# Wolfram Language (Mathematica), 99 bytes

```
sPrint@@@Array[s[[4# #-2#+1-#2&@@If[Abs@#2<2#,!##,#-Abs@#2|-#2]]]/._@__->" "&,2{L=Tr[1^s],L},-L]

```

Try it online!

Directly computes the index of each position: in Cartesian coordinates, \\$\operatorname{index}(x,y)=\textit{offset}+\begin{cases}2y(2y+1)-x,&|x|\<-2y\\ 2\left(y+|x|\right)\left(2\left(y+|x|\right)+1\right)+x,&\text{else}\end{cases}\\$

where \\$\textit{offset}\\$ is the index of the "first" character (1, in Mathematica).

Takes a list of characters as input.

---

### Older approach, ~~123~~ ~~122~~ ~~109~~ 107 bytes

```
Print@@@Normal@SparseArray[i=0;p=2Length@#;(p+=ReIm[I[2+I,1-I][[⌈2√i++⌉~Mod~4-1]]-1])->#&/@#,2p," "]&

```

Try it online!

The direction of the (1-indexed) `i`th character relative to the previous character can be computed with \\$\Big\lceil2\sqrt i\Big\rceil\bmod 4\\$:

* 1: ↗
* 2: ↘
* 3,0: ←

# Answer
> 9 votes
# Charcoal, ~~37~~ ~~36~~ 21 bytes

```
ＧＨ✳✳Ｅ⊖ＬθＩ§4174⌈⊗₂⊕ι²θ

```

Attempt This Online! Link is to verbose version of code. Explanation: Inspired by @KevinCruijssen's 05AB1E solution, but then using @att's formula to generate the directions.

```
       θ                Input string
      Ｌ                 Length
     ⊖                  Decremented
    Ｅ                   Map over implicit range
                  ι     Current index (0-indexed)
                 ⊕      Incremented (i.e. 1-indexed)
                ₂       Square rooted
               ⊗        Doubled
              ⌈         Ceiling
         §4174          Cyclically index to find direction
        Ｉ               Cast to integer
  ✳✳                    Convert to directions
ＧＨ                 ²θ   Draw path using input string

```

The path drawing command draws one character for the start and then `n-1` characters for each direction in the array. Unfortunately there aren't any single character strings that represent diagonal directions so I have to use integers instead; these start at `0` for right and increment for each 45° clockwise.

Previous 37 byte solution:

```
≔⮌⪪Ｓ¹θＦＬθＦ³Ｆ§⟦⊕⊗ι⁺³×⁴ι⊗⊕ι⟧κ¿θ✳⁻⁷×³κ⊟θ

```

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

```
≔⮌⪪Ｓ¹θ

```

Split the input into characters and reverse the list.

```
ＦＬθ

```

Loop a large enough number of times.

```
Ｆ³

```

Loop for each side of the triangle.

```
Ｆ§⟦⊕⊗ι⁺³×⁴ι⊗⊕ι⟧κ

```

Loop for the size of the side.

```
¿θ

```

Check whether there is still anything left to print.

```
✳⁻⁷×³κ⊟θ

```

Print the next character in the appropriate direction.

# Answer
> 7 votes
# JavaScript (V8), 222 bytes

```
s=>(g=(a,b,n=1)=>b?g([(c=(b+' '.repeat(n*8)).slice(0,n*8))[n*6-1],...[...a,c.slice(0,n*4-1)].map((l,i)=>c[n*6+i]+l+c[n*6-2-i])],b.slice(n*8),n+1):a)([s[0]],s.slice(1)).reduce((p,l,i,a)=>p+' '.repeat(a.length-i-1)+l+`
`,'')

```

Try it online!

It most definitely can be golfed more.
I use a recursive algorithm, splitting the output into triangle 'layers', where each layer is a complete wrap (three sides) of the previous triangle.

Ungolfed

```
s=>(g=(a,b,n=1)=> // g is a recursive function; a: previous; b: rest; n: increment
  b ? // if there is more string to wrap
    g([ // wrap b around a as a triangle and recurse
        (c=(b+' '.repeat(n*8)).slice(0,n*8))[n*6-1],
        ...[...a,c.slice(0,n*4-1)].map((l,i)=>c[n*6+i]+l+c[n*6-2-i])
      ],
      b.slice(n*8),
      n+1)
  :a // otherwise return the triangle
  )
  ([s[0]],s.slice(1)) // run the function with the first letter and the rest
  .reduce((p,l,i,a)=>p+' '.repeat(a.length-i-1)+l+'\n','') // step the triangle to make it look like it is meant to

```

# Answer
> 7 votes
# JavaScript (ES8), 137 bytes

Expects an array of characters. Returns a string.

This version is based on the formula used by @att, modified to be more golf-friendly in JS.

```
a=>a.map((c,n)=>(m[y+=~(d=2*n**.5-1/n)%4%3?d&++x/x||-1:!x--]=m[y]||[...''.padEnd(x)])[x]=c,m=[],x=y=a.length)&&m.map(r=>r.join``).join`
`

```

Try it online! (raw output)

Try it online! (with extra whitespace removed)

### How?

Given the position \\$n\\$ of the character, the direction \\$0\le d\le 2\\$ can be computed with:

$$d=\left(\left\lfloor2\sqrt{n}+1-\frac{1}{n}\right\rfloor\bmod 4\right)\bmod 3$$

The actual JS implementation is:

```
~(2 * n ** 0.5 - 1 / n) % 4 % 3

```

which evaluates to \\$0\\$, \\$-1\\$ or \\$-2\\$.

---

# JavaScript (ES8),  ~~163~~  157 bytes

Expects an array of characters. Returns a string.

```
a=>a.map(c=>((m[y]=m[y]||[...''.padEnd(x)])[x]=c,j%3%2?x--:y+=!!++x-j%3,k?k--:k=(n=j/3<<1)+(j++%3||n+2)),m=[],j=k=0,x=y=a.length)&&m.map(r=>r.join``).join`
`

```

Try it online! (raw output)

Try it online! (with extra whitespace removed)

### How?

This is a rather straightforward algorithm that draws the output character by character in a matrix \\$m\[\\:\]\\$, keeping track of the position \\$(x,y)\\$ of the pen, a direction in \\$\\{0,1,2\\}\\$ and the number \\$k\\$ of characters to draw before the next direction change.

We move according to the following table:

```
 direction | moving towards | distance
-----------+----------------+----------
     0     | South-East     |  2t + 1       (t = turn number)
     1     | West           |  4t + 3
     2     | North-East     |  2t + 2

```

Which gives:

```
t = 0     t = 1        t = 2            t = 3

                                          2
                         2               2.
            2           2.              2..0
  2        2.          2..0            2....0
 2X       2.X0        2..X.0          2...X..0
1110     2....0      2......0        2........0
        11111110    2........0      2..........0
                   111111111110    2............0
                                  1111111111111110

```

In the JS implementation, we do not store the direction explicitly. Instead, we use a counter \\$j\\$ going from \\$0\\$ to \\$+\infty\\$ and use \\$j\bmod 3\\$ to figure out the current direction. We also do not store the turn number but compute \\$n=2\cdot\lfloor j/3\rfloor\\$, using the value of \\$j\\$ *before* it's incremented to account for the direction change (which means that \\$n\\$ is equal to \\$2(t-1)\\$ rather than \\$2t\\$ when the direction wraps to \\$0\\$).

Hence the following table:

```
     j mod 3     |  (j + 1) mod 3  |                     | new starting
 (old direction) | (new direction) |    new distance     | value for k
-----------------+-----------------+---------------------+--------------
        2        |        0        | (n + 2) + 1 = n + 3 |     n + 2
        0        |        1        |      2n + 3         |    2n + 2
        1        |        2        |       n + 2         |     n + 1

```

And the corresponding expression to update \\$k\\$:

```
k = (n = j / 3 << 1) + (j++ % 3 || n + 2)

```

The coordinates are updated with:

```
j % 3 % 2 ?          // if the direction is 1:
  x--                //   decrement x
:                    // else:
  y += !!++x - j % 3 //   increment y if the direction is 0
                     //   or decrement y if it's 2
                     //   increment x in both cases

```

# Answer
> 6 votes
# , ~~270~~ ~~265~~ ~~252~~ ~~243~~ ~~232~~ ~~227~~ 225 bytes

*I finally managed to remove 2 more characters to bring the total to a number that can be represented in triangular form (as shown here). Code should be formatted conventionally to be run (as in the example on TIO); the '•' represents a newline (`\n`) character.*

```
              f
             unc
            tion(
           s,`~`=c
          bind,m=ma
         trix){n=nch
        ar(s)+1;p=m(,
       n^2,2);while(T<
      n){a=4*F;p[T+0:a,
     ]=c(F:-F,(-F:F)[-1]
    )~0:a-2*F;p[T+a+-2:a+
   3,]=(F=F+1)~(b=2*F-1):-
  b;T=T+2*a+4};m=m(" ",n,n)
 ;m[p[2:n-1,]+b+1]=el(strspl
it(s,''));apply(m,1,cat,"•")}

```

Try it online!

Note that this approach has been comprehensively outgolfed by att's approach, although as consolation neither that nor any of the other current answers can be represented as a triangle...

Works by constructing the coordinates for each letter, then using this to put the letters into an empty matrix.

Commented:

```
triangle=
function(s){n=nchar(s)          # n is the number of letters
s=el(strsplit(s,''))            # first split the string into individual letters
p=matrix(,2,n^2)                # initialize p as a 2-row matrix to hold the coordinates
                                # (with plenty of columns so that we've enough to go all
                                # the way round the outermost triangle)
                                # now, F is the current loop, starting at 0
while(T<=n){                    # T is the current letter index
a=4*F+1                         # a=the size of the 'arch' (number of letters going up & over)
p[,T+1:a-1]=                    # set the coordinates for the arch letters...
  rbind(                        # ...(rbind combines rows for y & x coordinates)...
    c(F:-F,(-F:F)[-1]),         # ...to y = F..-F, and then -F+1..F (so: up & then down again)
    1:a-2*F-1)                  # ...and x = across the arch from -2*F to +2*F
a=a+2                           # a=now the width of the base = size of arch + 2
p[,T+a+1:a-3]=                  # now set the coordinates of the base letters...
  rbind(                        #
    F+1,                        # ... base y = row F+1
    (b=2*F+1):-b)               # ... and x = goes (backwards) from 2*F+1..-2*F-1
T=T+2*a-2                       # update the current letter index
F=F+1}                          # increment the loop
p=p[,1:n]                       # delete any excess coordinates
p=p-min(p)+1                    # re-zero the coordinates to remove negatives
m=matrix(" ",b<-max(p),b)       # create a new matrix filled with " "
m[t(p)]=s                       # and fill it with the letters at the right positions
n=apply(m,1,cat,"               # finally, print each row
")}

```

# Answer
> 6 votes
# , ~~205~~ ~~153~~ ~~147~~ ~~136~~ ~~132~~ 126 bytes

-52 from Dominic van Essen.
-4 from Giuseppe.
-4 again thanks to Giuseppe.
-5 further thanks to Dominic van Essen

```
function(s,n=nchar(s))for(y in(x=-n:n)*2)cat(ifelse((i=(t=y-2*(r=abs(x))*!r<y)*t-t-2*(r<y)*x+x+1)>n," ",substring(s,i,i)),"
")

```

Try it online!

# Answer
> 4 votes
# Pip `-l`, 70 bytes

```
sMC:Y#ax:w:y/2-/2Ly*2L++i/2{I++v<ys@w@x:a@vi%4%3?++x&i%4=1?--w++w--x}s

```

Try it online!

... I'm not sure I want to try explaining this monstrosity in detail. The basic idea is to construct an over-big 2D array of spaces (`sMC:#a`) and then put the characters from the input string into the array at the proper indices (`s@w@x:a@v`). The rest of the code figures out what the "proper indices" are.

---

Alternate approach, 77 bytes:

```
a.:sX#aW<|a{UpaWa^@YxNl?v+1++v%2?v*2+1vl:xNl?RV^p.:lv%2?lPEpl.^pAEx}RVsX,#l.l

```

Try it online!

Builds the triangle as a list of lines, alternating between adding lines to the front/end of the list and adding characters to the front/end of each line. I was hoping this way might be shorter, but so far it seems it's not.

# Answer
> 4 votes
# , 60 bytes

```
4 :'x(<"1(#x)++/\(3|4|>.2*%:i.#x){<:3 3#:3 2 8)}y',~' '"0/,~

```

Try it online!

Obligatory J answer because it's Jonah's challenge.

Because "replace a certain position inside an array with a value" is not a verb but an adverb, it can't be used in a train as-is, so it is wrapped inside an explicit inline verb.

Uses att's formula to construct the directions.

### How it works

```
NB. input: a string (character vector) of length n

,~' '"0/,~  NB. create a large enough canvas (blank matrix of size 2n*2n)
        ,~  NB. concatenate two copies of self
       /    NB. outer product by...
  ' '"0     NB.   a constant function that returns blank per character
,~          NB. concatenate two copies of self

4 :'...'  NB. a dyadic explicit verb, where x is the input string and
          NB. y is the canvas generated above
x(...)}y    NB. replace some places of y by contents of x...
3|4|>.2*%:i.#x  NB. formula by att (gives 0, 1, or 2 per index)
(...){          NB. select the directions based on the above...
<:3 3#:3 2 8    NB. the matrix (0 -1)(-1 1)(1 1) i.e. L/RU/RD
(#x)++/\        NB. take cumulative sum (giving coords to place each char)
                NB. and add n to all elements
<"1             NB. enclose each row to satisfy the input format of }

```

# Answer
> 2 votes
# Scala, ~~322~~ 318 bytes

```
s=>((s zip Seq.unfold((0,0,0->0)){case(r,n,y->x)=>Option.when(n<s.size){val(c,t)=(math.sqrt(n).toInt%2,r+1-math.abs(x.sign))
(y->x,(t,n+1,(y+(c-1)*(1-t%2*2),x+1-c*2)))}}groupBy(_._2._1)toSeq)sortBy(_._1)map(_._2.sortBy(_._2._2)map(_._1)mkString)zipWithIndex)map{t=>" "*(math.sqrt(s.size).toInt-t._2)+t._1}mkString "\n"

```

Try it in Scastie (doesn't work in TIO)

# Answer
> 1 votes
# Perl 5, 163 bytes

```
sub f{                    #newlines and indentation added here for readability.
  $_=' 'x1e3;
  @L=(51,$a=-1,-49)x($p=225);
  for$c(pop=~/./g){
    $P=$p+$L[1];
    $a++>0&&s/^(.{$P}) /$1$c/s&&($p=$P,$a=0,shift@L)||substr$_,$p+=$L[0],1,$c
  }
  s/.{50}/$&\n/gr
}

```

In short, it adds the next char from the input in the current direction unless it discovers it's time to change direction.

Try it online!

---
Tags: code-golf, ascii-art
---


# Question
Title: Smallest n-digit prime containing only these digits
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 , 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.

# Answer
> 5 votes
# Brachylog (2), 8 bytes

```
j₍oᵐ∋ᵐcṗ

```

Try it online!

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
> 13 votes
# 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.

# Answer
> 9 votes
# Python 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!

Takes input like `f(3,{'9','3','8'})`.

Python has no built-ins for primes, so the function generates them using Wilson's Theorem 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
> 5 votes
## 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
> 4 votes
# Jelly, 12 bytes

```
DL×ÆP
ṗḌÇÐṀṂ

```

Takes a set and an integer as command-line arguments. Prints **0** if no solution exists.

Try it online!

### 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
> 3 votes
## Pyke, ~~18~~ 16 bytes

```
j;~p#`ljqi`Q-!)h

```

Try it here!

Runs forever if no values found

# Answer
> 3 votes
## 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
> 3 votes
# Brachylog, 15 bytes

```
tL∧?h~lṗ.dẹp⊆L∧

```

Try it online!

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
> 2 votes
# 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\]). 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
> 2 votes
# 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!**

**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
> 2 votes
# Pyth - ~~13~~ 12 bytes

```
f&P_T!-Tz^Tt

```

Test Suite.

# Answer
> 2 votes
# 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
> 1 votes
# Perl 6, 43 bytes

```
->\n,@k {first *.is-prime&/^@k**{n}$/,^∞}

```

Runs forever if no solution exists.

# Answer
> 1 votes
## 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
> 1 votes
# 05AB1E, ~~22~~ ~~19~~ 18 bytes (-1 @Riley)

```
[NØ©S¹Kg0Q®g²Q&i®q

```

Try it online!

```
[                   # 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
> 1 votes
# 05AB1E, 17 bytes

```
[¾ØÐ¼g¹QiS²Kg0Qiq

```

Try it online!

```
[¾Ø ¼             # 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
> 1 votes
# , 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.*

```
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!

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
> 1 votes
**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
> 0 votes
# 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
> 0 votes
# Perl 6, 68 bytes

```
->\n,\k{first {.is-prime&&/.**{n}/},+«[X~] 0,|(k.unique.sort xx n)}

```

Try it

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
> 0 votes
# Python 2 + 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**

Input is like `4,{'1','2'}`.

# Answer
> 0 votes
# 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.
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
> 0 votes
# 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
> 0 votes
# Whispers v2, 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!

## 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\\$.

---
Tags: code-golf, math, sequence, primes
---