title: Double it your way

text:
# Question
Title: Double it your way
There have been a couple of challenges involving doubling source code: here and here. The task we have here is a bit harder, but should be doable in almost every language.

In this challenge, you will take in an arbitrary positive integer. Your program must output that integer **doubled**. When your source code is doubled, it will take in a positive integer, and output it **squared**.

How is your source code doubled? Well, you can have it your way. That is to say, you can split your source code up into strings of bytes or characters (or tokens in tokenized langs) of *any **equal** length you want*, and repeat each chunk twice in succession.

For an initial program of `ABCDEFGHIJKL`, (length 12) here are **all** possible doubled programs:

```
Chunk length |   Doubled source code
-------------+-------------------------
           1 | AABBCCDDEEFFGGHHIIJJKKLL
           2 | ABABCDCDEFEFGHGHIJIJKLKL
           3 | ABCABCDEFDEFGHIGHIJKLJKL
           4 | ABCDABCDEFGHEFGHIJKLIJKL
           6 | ABCDEFABCDEFGHIJKLGHIJKL
          12 | ABCDEFGHIJKLABCDEFGHIJKL

```

Note that this means programs of prime lengths can only be doubled two ways: every character doubled, or the full program is repeated twice.

### Rules:

* Code must be a full program or function.
* Standard loopholes are forbidden.
* Standard I/O methods are allowed.
* All characters/bytes, including whitespace and newlines, are counted in the length of the code and contribute to chunks.
* You **may** assume that the input and its square can be represented by your language's int/integer type.
* You **may not** assume a trailing newline or other character.
* Provide your chunk size in the heading after the byte count.
* This is , so shorter programs are better! If two programs are the same length, the one which uses the smaller chunk length wins. (If you have a longer program which uses a smaller chunk length, that is worth posting too!)
* If your program requires a second input/line, you may make no assumptions on its value. In particular, your program should work if the second input is empty, the same as the first, or a different integer. If your program does not require a second input/line, you may ignore this restriction.

> Sandbox link

# Answer
> 18 votes
# Perl 5, 8 bytes (chunk size 4)

```
$_*=~~+2

```

Try it online, or try the doubled version.

Unary `~` is the bitwise negate, so applying it twice is a noop. Thus, the base program simply multiplies `$_` (the implicit input-output variable) by 2.

Binary `~~` is smartmatch, which returns a boolean. `~~+2~~+2` parses as `(~~+2) ~~ (+2)`. Since 2 equals 2, this yields true (1). Thus, the doubled program first multiplies `$_` by 1, then multiplies `$_` by itself.

# Answer
> 17 votes
# 05AB1E, 4 bytes (chunk size 2 or 4)

```
·Inr

```

Try it online or doubled as a single 4-byte chunk or doubled as two 2-byte chunks.

```
·        # double the implicit input
 In      # square the input
   r     # reverse the stack: it's now [input ** 2, input * 2]
         # if we stop here: implicitly output the top of the stack (input * 2)
·        # double the top of the stack (giving input * 4, not that it matters)
 In      # square the input
   r     # reverse the stack: it's now [input ** 2, input * 4, input ** 2]
         # implicitly the top of the stack (input ** 2)

```

# Answer
> 15 votes
# Python 3, 26 bytes (chunk size 13)

```
lambda n:"and n*n#"and 2*n

```

Try it online!

### Doubled:

```
lambda n:"andlambda d:"and n*n#"and 2*n n*n#"and 2*n

```

This solution is provided by @Grimy.

---

## Python 3, ~~32~~ ~~30~~ 28 bytes (chunk size ~~16~~ ~~15~~ 14)

```
lambda n:bool(0)*n*n or  2*n

```

Try it online!

*-4 bytes thanks to @negativeSeven*

### Doubled:

```
lambda n:bool(lambda n:bool(0)*n*n or  2*n0)*n*n or  2*n

```

Try it online!

The function takes advantage of the unique chunk rule of this challenge.

# Answer
> 10 votes
# Hexagony, 14 bytes (chunk size 14)

```
?"+==*/}=+!@!<

```

### Expanded:

```
  ? " +
 = = * /
} = + ! @
 ! < . .
  . . .

```

Try it online!

## Doubled

```
?"+==*/}=+!@!<?"+==*/}=+!@!<

```

### Expanded:

```
   ? " + =
  = * / } =
 + ! @ ! < ?
" + = = * / }
 = + ! @ ! <
  . . . . .
   . . . .

```

Try it doubled online!

Hexagony is in a bit of a weird position in this challenge, in that actually achieving the task is not much more difficult than simply being able to write the two individual programs. However, golfing the solution proved rather difficult.

This solution is the trivial idea in the shortest form that I could fit, but I suspect there are shorter, cleverer answers. This version very naively sets two values to the input and sums them or multiplies them, depending on if the source is doubled. The only code reuse is the `"+` which makes making the copy code for the doubled program short enough to fit in the unused space from the original program.

I suspect using the IP change instructions `[]` will make isolating the parts easier, but a truly ideal solution will reuse a lot of code between the two. I made a helper program to double hexagony source code. Note that it removes trailing no-ops so if you want to have placeholder no-ops at the end just fill in some other character and change it back after. It can handle different chunk sizes, though I didn't yet write code to output each possible program (Hexagony seems to lend itself to using the full chunk size).

# Answer
> 9 votes
# Befunge-98 (FBBI), 8 bytes (chunk length 2)

```
;&:#* +q

```

Try it online!

```
;&;&:#:#* * +q+q

```

Try it online! (doubled)

Excluding control flow, the first program executes `&:+q` (input, duplicate top of stack, add, exit with return code), and the second executes `&:*+q` (input, duplicate top of stack, multiply, add (sums with an implicit 0), exit with return code)

# Answer
> 9 votes
# Hexagony, 12 bytes (chunk size 4)

```
?"2+...}=*!@

```

Try it online!

Formatted:

```
  ? " 2
 + . . .
} = * ! @
 . . . .
  . . .

```

And doubled, then formatted:

```
   ? " 2 +
  ? " 2 + .
 . . } . . .
} = * ! @ = *
 ! @ . . . .
  . . . . .
   . . . .

```

Basically, this sets the first edge to the input, then the second edge to either `2` or a copy of the input, then multiplies those two edges into the third edge, prints that and terminates. The list of executed instructions are just

```
?"2}=*!@

```

and

```
?"2+}=*!@

```

With the only difference being the `+` overriding the `2` on the second program.

# Answer
> 8 votes
# JavaScript (ES6),  ~~24~~  22 bytes

Despite its unusual format, this is the definition of an anonymous function, which can be either called directly or assigned to a variable.

```
+(g=x=>x*x)?g:(x=>x*2)

```

Try it online!

```
+(g=x=>x*x)?g:(x=>x*2)+(g=x=>x*x)?g:(x=>x*2)

```

Try it online doubled!

### How?

Applying the unary `+` to a function is interpreted as an attempt to coerce it to a number and results in *NaN*. Therefore, the leading `+(g=x=>x*x)` is falsy in both versions.

On the other hand, applying the binary `+` between 2 functions results in a string. Therefore, `(x=>x*2)+(g=x=>x*x)` is truthy in the doubled version.

# Answer
> 7 votes
# Perl 6, 8 bytes (chunk size 1)

```
* *<1 2>

```

Try it online! Try it doubled!

A Whatever/HyperWhatever lambda that takes a number and returns a number for the first program and a singleton list for the second program. Basically this keeps the exact same logic, except that the multiplication operator (`*`) is replaced by the exponential one (`**`).

```
**  **<<11  22>>

```

The Whatever literal (confusingly also represented by a `*`) are doubled up to a HyperWhatever (`**`) which is basically the same except it maps over lists. The space is needed to separate the Whatever literal from the multiplication and is ignored when doubled up. Instead of just `2` (which would get doubled to `22`) we use a list containing two elements, which evaluates to 2 in a numeric context). The `<>` can be doubled to a list with interpolation, and the two elements inside are doubled, but neither of those change the length of the list.

# Answer
> 6 votes
# Runic Enchantments, 9 bytes (chunk size 3)

```
i3?:*@:+@

```

Try it online!
Try it doubled!

The `3?` skips the next 3 instructions, resulting in an (executed) `i3?...:+@`. When doubled it results in an executed `i3?...:*@` where `.` represents the 3 NOP'd instructions. `@` is "print entire stack and terminate."

# Answer
> 6 votes
# C# (Visual C# Interactive Compiler) / Javascript, 22 bytes, chunk size 11

```
m=>/*      /2*m//*/m*2

```

Try it online!

# Answer
> 5 votes
# Brain-Flak, 76 bytes, 76 byte chunks

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

```

Try it online!

## Doubled (with newline for clarity)

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

```

Try it online!

Here is a version that uses a more complex doubling procedure. It does 5 chunks of size 15. The code here is 46 bytes however due to the required padding it is substantially longer.

# ~~105~~ 90 bytes, 15 byte chunks

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

```

Try it online!

## Doubled (with newlines for clarity)

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

```

Try it online!

# Answer
> 5 votes
# Brain-Flak, ~~48~~ 30 bytes (chunk size 10)

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

```

Try it online! Try it doubled!

This basically takes three steps, then when doubled executes those steps twice each. The initial program is:

1. Duplicate TOS, switch stacks and start pushing a value
2. Get the TOS's triangular number n\*(n-1)/2
3. Pop TOS, switch stack and pop twice, then push the result.

For an input `n` into an undoubled program, this results in:

```
1.  Start stack: n n
    Other stack: <
    Third stack:
2.  Start stack: n n
    Other stack: 0 <
    Third stack: tri(0) = 0
3.  Start stack: n+n+tri(0) = 2n <
    Other stack:
    Third stack:

```

For the doubled program:

```
1a. Start stack: n n
    Other stack: <
    Third stack:
1b. Start stack: n n <
    Other stack: 0 0
    Third stack:
2a. Start stack: n 0 <
    Other stack: 0 0
    Third stack: tri(n)
2b. Start stack: n 0 <
    Other stack: 0 0
    Third stack: tri(n)+tri(0) = tri(n)
3a. Start stack: n
    Other stack: tri(n) <
    Third stack: tri(n)
3a. Start stack: 0+n+tri(n)+tri(n) = n + 2*tri(n) = n + n*(n-1) = n*n <
    Other stack:
    Third stack:

```

# Answer
> 4 votes
# Cubix, ~~18~~ 14 bytes (chunk length ~~9~~ 7)

```
*OI$|:/@O+:I.

```

Note the trailing space. Try it online!

Doubled:

```
*OI$|:/*OI$|:/@O+:I. @O+:I.

```

Again, there is one trailing space. Try it online!

## Explanation

The main idea is that doubling the code causes the cube to become bigger, so the instruction pointer starts at a different symbol. Since the addition program cannot be put on a cube of side length 1, the side length is going to be 2. Additionally, the doubled code needs to be on a cube of side length 3, so the doubled code must be at least 25 bytes. This means the code must be at least 13 bytes long. As such, at most 1 more byte can be saved.

Now to the actual code. The first observation is that the top face (that is, the first 4 characters) are not used by the addition program. Furthermore, if we make the 5th character reflect the IP around the cube, we can free up 2 more characters. We will use these characters to put the squaring program.

# Answer
> 4 votes
# Mornington Crescent, 656 Bytes (Chunk size 328)

Just to add weight to the theory that this can be solved in almost any language...

```
Take Northern Line to Bank
Take District Line to Bank
Take District Line to Parsons Green
Take District Line to Bank
Take District Line to Hammersmith
Take Piccadilly Line to Russell Square
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Hammersmith
Take District Line to Upminster
Take District Line to Embankment
Take District Line to Hammersmith
Take District Line to Upminster
Take District Line to Acton Town
Take District Line to Acton Town
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Bounds Green
Take Piccadilly Line to Leicester Square
Take Northern Line to Leicester Square
Take Northern Line to Mornington Crescent

```

(The trailing newline is important)

Try the single version! ...or... Try the doubled version!

---

This was a particularly tricky challenge in Mornington Crescent because the program must have such a rigid structure. It's also important to watch where the doubling would take place, because teleporting between stations is illegal in London.

The theory here is simple: In the single version, 'Bounds Green' is filled with a random string, but in the doubled version it gets filled with the squared input. After the chunk ends, both versions double the 'input', but in the doubled version of the code, the input has been replaced with 0.

This result is taken back to Bounds Green, which performs a max() operation twice, before taking the result to the output. In the single version this leaves the doubling unaltered (the int and string are just switched back and forth), but in the doubled version this replaces the 0 with the squared result already stored in Bounds Green.

---

If my explanation wasn't good enough, I suggest you visit London and try the two routes yourself.

# Answer
> 3 votes
# , ~~59~~ 30 bytes (chunk size ~~59~~ 30)

```
F=F+1;f=function(n)n*c(2,n)[F]

```

Try it online!

Credit to Robin Ryder for inspiring this; increments `F` each time, and the function `f` selects the appropriate output.

~~This isn't particularly interesting, but doubtless something clever manipulating the chunk size will be dreamed up.~~ As expected, Robin Ryder came up with this which is both shorter and has some neat chunk manipulation.

# Answer
> 3 votes
# , ~~42~~ ~~35~~ 28 bytes (chunk size 4)

Now with a smaller chunk and no error. I also have a longer solution with chunk size 3; see below.

I don't think it is possible to write an R answer with chunk size 1 or 2; I'll happily give a bounty to anyone who proves me wrong.

```
s =scan#
n=s()#

n/2*4#

```

Try it online!

The `#` is for comments in R. The 3rd line is only spaces, making a chunk of newline + 2 spaces + newline, so that the previous and next chunk can have no newline.

Doubled, it becomes:

```
s =ss =scan#can#
n=s
n=s()# ()#

n/2*n/2*4#  4#

```

Try it online!

The single version computes \\$\frac n2\times4=2n\\$; the double version computes \\$\frac n2\times \frac n2\times4=n^2\\$.

Here is a slightly longer solution, but with chunk size 3:

# , 39 bytes (chunk size 3)

```
s =bbb=scan#
n=s(#

)#
n* 1/ 2/ 1* 4#

```

Try it online!

Doubled:

```
s =s =bbbbbb=sc=scan#an#
n=
n=s(#s(#

)# )#
n*
n* 1/ 1/ 2/ 2/ 1* 1* 4# 4#

```

Try it online!

Note that Giuseppe has another R answer, with one chunk of 30 bytes.

# Answer
> 3 votes
# JavaScript (Node.js), ~~15~~ 12 bytes (chunk size: 6)

```
x=>/**/2*(x)

```

Try it online!

Single case:

```
x=>/**/2*(x)

```

Double case:

```
x=>/**x=>/**/2*(x)/2*(x)

```

Seems to also work in C#, and Java if changing `=>` to `->`?

# Answer
> 2 votes
# PowerShell, 22 bytes (chunk size 11)

```
param($p)
#   /
2 * $p

```

Try it online.

**Doubled:**

```
param($p)
#param($p)
#   /
2 * $p   /
2 * $p

```

This solution is based on @ShieruAsakoto's solution.

**@Grimy solution that has been converted to PowerShell, 26 bytes (chunk size 13)**

```
param($p)$t=';$p*$p#';$p*2

```

Try it online.

**Doubled:**

```
param($p)$t=';param($p)$t=';$p*$p#';$p*2$p*$p#';$p*2

```

# Answer
> 1 votes
# Perl 5 (`-p`), ~~22~~ 15 bytes

-7 bytes thanks to Grimy

```
$_*=$'/4||2;//;

```

TIO

# Answer
> 1 votes
# Python 3, ~~56~~ 53 bytes

```
print(eval(input()+"**2"[len(*open(__file__))%2:])) #

```

My python skills kinda suck, so can definitely be golfed.. Based on the Python answer in the "*I double the source, you double the output!*" challenge.

Chunk length 53.

Try it online or try it online doubled.

# Answer
> 1 votes
# Charcoal, 13 bytes

```
ＰＩ×Ｉθ⎇υＩθ²⊞υω

```

Try it online! Explanation: The predefined empty list is falsey so the input is multiplied by 2. When doubled the second pass sees the empty string has been pushed to the list so it multiplies the input by itself instead. Try it online! In verbose syntax this corresponds to `Multiprint(Cast(Times(Cast(q), Ternary(u, Cast(q), 2)))); Push(u, w);`.

# Answer
> 1 votes
# Java 8, 62 bytes

```
n->n*(Byte.SIZE>8?n:2);/*
class Byte{static int SIZE=9;}/**///

```

Chunk length 62.

Try it online or try it online doubled.

**Explanation:**

```
n->                    // Method with integer as both parameter and return-type
  n*                   //  The input, multiplied by:
    (Byte.SIZE>8?      //   If Byte.SIZE is larger than 8:
      n                //    Multiply by the input itself
     :                 //   Else:
      2);              //    Multiply by 2
class Byte{            // Class which overwrites Byte
  static int SIZE=9;}  //  And sets the SIZE to 9

```

In Java, the available comments are `// comment` and `/* comment */`. Which are combined here to overwrite certain parts. See how these comments work thanks to the Java highlighting:

```
n->n*(Byte.SIZE>8?n:2);/*
class Byte{static int SIZE=9;}/**///

n->n*(Byte.SIZE>8?n:2);/*
class Byte{static int SIZE=9;}/**///n->n*(Byte.SIZE>8?n:2);/*
class Byte{static int SIZE=9;}/**///

```

The doubled program created a custom `Byte` class and its value `SIZE=9`, which overwrites the default `java.lang.Byte` class and its value `SIZE=8`.

# Answer
> 1 votes
# Japt, ~~7~~ 5 bytes

```
*N²jJ

```

Try it | Doubled

`²` pushes 2 to the array of inputs `N` then `j` removes & returns the element at index `J=-1` (i.e., the newly inserted `2`) and multiplies the input by that.

When doubled it results in `J` being multiplied by `2`, so the element at index `-2` (i.e., the input) is returned by `j` and used as the multiplier.

# Answer
> 1 votes
# Jelly, ~~8~~ 6 bytes (chunk length 3)

```
Ḥ;²3ị

```

Try it online!

Doubled

# Answer
> 1 votes
# , ~~15~~ ~~10~~ 9 bytes

```
+: :(*-:)

```

Try it online!

Doubled version: Try it online!

`f : g` creates a verb that executes `f` when called with one argument, and `g` when called with 2 arguments. So ours executes double `+:` with the original source and `*-:` when the source is doubled.

This works because a train of two verbs in J becomes a hook, and thus `f f` is executed as `y f (f y)` where y is the original input. Additionally, `*-:` is itself a "dyadic hook" which works by multiplying `*` the left arg by half `-:` the right arg. The left arg will be the original input, and the right arg will be the input doubled, so this will produce the square of the original input.

## original answer

## , 15 bytes

```
*:@]`(+:@])@.=~

```

Try it online!

Doubled version: Try it online!

In the single version, we have a single verb which uses Agenda `@.` to do the if... then logic: If the argument is equal to itself `=~`, then take the argument and double it `(+:@[)`.

However, when we double the code, we get a J hook. Call the verb `f` and the input `y`. Then the hook `f f` executes like this:

```
y f (f y)

```

Which means that now the original input is the left arg, and the right arg is the doubled input. Since these will not be equal, `=~` will return false this time, and now we'll execute the other fork of the Agenda, ie, `*:@]`, which means "square the right arg." And since `~` reverses the inputs of a dyadic verb, the right arg will be the original input.

# Answer
> 1 votes
# Nice solution: Lua, 66 bytes (chunk size 66 bytes)

```
a,x=a and...^2 or ...*2,setmetatable(x or{},{__gc=load'print(a)'})

```

Try it online! (double it yourself, it is not so hard)

Oh yeah, pretty sure that there is shorter solution to this, but it's the best I was able to came up with this way. Take input as first argument.

Brief explanation: whole business with `a` is quite obvious for everyone, while the second part with `x` is more interesting. Basically, I create a table (or update existing one on second pass) with finalizer (`__gc` metamethod) which gets called when program exits.

# Lame solution: Lua, 60 bytes (chunk size 30 bytes)

```
a=a and...^2 or ...*2;                     print(a)os.exit()

```

Try it online! or Try it doubled!

Smaller and with better chunking, but ultimately boring and lame without any clever tricks. I'm pretty sure no comments are required to this one.

# Answer
> 1 votes
# Python 3, 60 bytes

Chunk size 6.
Not a great solution, but it works. This is such a unique challenge, it really makes you think from a different perspective.

```
0;  i=input;0;  p=print;n=i()#
x=int(n)##
z=2*x#z=x*x
p(z)##

```

Try it online!

Doubled:

```
0;  i=0;  i=input;input;0;  p=0;  p=print;print;n=i()#n=i()#
x=int
x=int(n)##
(n)##
z=2*x#z=2*x#z=x*x
z=x*x
p(z)##p(z)##

```

Try it online!

# Answer
> 1 votes
# Zsh, 30 bytes (chunk size 10)

```
m=$m[1]*2
x=$[$1$m]
return $x

```

Try it online! Try it doubled!

Abuses the fact that `$var` in `$[$var]` gets expanded first, then evaluated in the arithmetic context.

```
             # each line is 9 characters long. when doubled, each is run twice.
m=$m[1]*2    # first time: m='*2'   second time: $m[1] is '*', so m='**2'
x=$[$1$m]    # single: x=$[$1*2]    doubled: x=$[$1**2];x=$[$1**2].
return $x    # zsh supports 32-bit return values from functions, unlike bash

```

If anyone wants a crack at lowering this, here's the closest to a `24/8` solution I've gotten (outputs `x^2+2` when doubled)

# Answer
> 1 votes
# Cascade, 13 bytes (chunk size 13)

```
]
&/2
#
*
 2&

```

Try it online!

```
]
&/2
#
*
 2&]
&/2
#
*
 2&

```

Try it doubled!

This was quite difficult. The basic gist of this is to print the input multiplied by `2` for the first program, and replace the `2` by a copy of the input for the second.

### Explanation:

The executed part of the first program looks like

```
]     Redirection
 /
#     Print
*     The multiplication of
 2&   Input and 2 (wrapping around the left)

```

The doubled program basically adds the first `]` to the end of the last line, so the program wraps around to that instead of the `&`. This turns it into

```
]     Redirection
 /
#     Print
*     The multiplication of
 2 ]  Set the value of
& 2   The variable '2' to the input
      Then multiply the result of that (input) by '2' (input)

```

---
Tags: code-golf, integer, source-layout
---


# Question
Title: Find the largest root of a polynomial with a neural network
## The challenge

Find the smallest feedforward neural network such that, given any 3-dimensional input vector \\$(a,b,c)\\$ with integer entries in \\$\[-10,10\]\\$, the network outputs the largest (i.e., "most positive") root of the polynomial \\$x^3+ax^2+bx+c\\$ with error strictly smaller than \\$0.1\\$.

## Admissibility

The notion of admissibility in my previous neural net golfing challenge seemed a bit restrictive, so for this challenge, we are using a more liberal definition of feedforward neural network:

A **neuron** is a function \\$\nu\colon\mathbf{R}^n\to\mathbf{R}\\$ that is specified by a vector \\$w\in\mathbf{R}^{n}\\$ of **weights**, a **bias** \\$b\in\mathbf{R}\\$, and an **activation function** \\$f\colon\mathbf{R}\to\mathbf{R}\\$ in the following way:

$$ \nu(x) := f(w^\top x+b), \qquad x\in\mathbf{R}^n. $$

A feedforward neural network with **input nodes** \\$\\{1,\ldots,n\\}\\$ is a function of \\$(x\_1,\ldots,x\_n)\in\mathbf{R}^n\\$ that can be built from a sequence \\$(\nu\_k)\_{k=n+1}^N\\$ of neurons, where each \\$\nu\_k\colon\mathbf{R}^{k-1}\to\mathbf{R}\\$ takes inputs from \\$(x\_1,\ldots,x\_{k-1})\\$ and outputs a scalar \\$x\_k\\$. Given some specified set \\$S\subseteq\\{1,\ldots,N\\}\\$ of **output nodes**, then the output of the neural network is the vector \\$(x\_k)\_{k\in S}\\$.

Since activation functions can be tuned for any given task, we need to restrict the class of activation functions to keep this challenge interesting. The following activation functions are permitted:

* **Identity.** \\$f(t)=t\\$
* **ReLU.** \\$f(t)=\operatorname{max}(t,0)\\$
* **SoftPlus.** \\$f(t)=\ln(e^t+1)\\$
* **Sigmoid.** \\$f(t)=\frac{e^t}{e^t+1}\\$
* **Sinusoid.** \\$f(t)=\sin t\\$

Overall, an admissible neural net is specified by input nodes, a sequence of neurons, and output nodes, while each neuron is specified by a vector of weights, a bias, and an activation function from the above list. For example, the following neural net is admissible, though it does not meet the performance goal of this challenge:

* **Input nodes:** \\$\\{1,2\\}\\$
* **Neurons:** \\$\nu\_k(x\_1,\ldots,x\_{k-1}):=x\_{k-2}+x\_{k-1}\\$ for \\$k\in\\{3,\ldots,10\\}\\$
* **Output nodes:** \\$\\{5,9,10\\}\\$

This network consists of 8 neurons, each with zero bias and identity activation. In words, this network computes the generalized Fibonacci sequence generated by \\$x\_1\\$ and \\$x\_2\\$ and then outputs the 5th, 9th, and 10th numbers from this sequence, in that order.

## Scoring

Given a real number \\$x\\$ with terminating decimal expansion, let \\$p(x)\\$ be the smallest nonnegative integer \\$p\\$ for which \\$10^{-p}\cdot |x|\<1\\$, and let \\$q(x)\\$ be the smallest nonnegative integer \\$q\\$ for which \\$10^q \cdot x\\$ is integer. Then we say \\$p(x)+q(x)\\$ is the **precision** of \\$x\\$.

For example, \\$x=1.001\\$ has a precision of \\$4\\$, whereas \\$x=0\\$ has a precision of \\$0\\$.

Your score is the sum of the precisions of the weights and biases in your neural network.

(E.g., the above example has a score of 16.)

## Verification

While the roots can be expressed in terms of the cubic formula, the largest root is perhaps most easily accessed by numerical means. Following @xnor's suggestion, I computed the largest root for every choice of integers \\$a,b,c\in\[-10,10\]\\$, and the results can be found here. Each line of this text file is of the form `a,b,c,root`. For example, the first line reports that the largest root of \\$x^3-10x^2-10x-10\\$ is approximately \\$10.99247140445449\\$.

**Edit:** The original file I posted had errors in cases where the polynomial exhibited a multiple root. The current version should be free of such errors.

# Answer
> 6 votes
# ~~14,674,000,667~~ ~~5,436,050~~ ~~5,403,448~~ ~~10,385~~ ~~5,994~~ ~~4,447~~ <br>3,806 total precision

For a baseline, I investigated the following approach: Select \\$M,\delta,\epsilon\>0\\$ such that if we sample the polynomial \\$p(x)=x^3+ax^2+bx+c\\$ at

$$ S:=\\{-M,-M+\delta,-M+2\delta,\ldots,M\\}, $$

then the largest sample point \\$s^\star\in S\\$ satisfying \\$p(s^\star)\<\epsilon\\$ necessarily exists and necessarily resides within \\$0.1\\$ of the largest root of \\$p\\$. One can show that for our collection of polynomials, one may take \\$M=11\\$, \\$\delta=0.1\\$, and \\$\epsilon=10^{-4}\\$.

To design a neural net that implements this logic, we start with a layer of neurons that sample the polynomial on \\$S\\$. For each \\$s\in S\\$, we take

$$ x\_{1,s} = s^2\cdot a + s\cdot b + 1\cdot c + s^3. $$

Next, we identify which of these are less than \\$\epsilon=10^{-4}\\$. It turns out that for \\$s\in S\\$, it holds that \\$p(s)\<10^{-4}\\$ only if \\$p(s)\leq 0\\$. As such, we can use relu activations to exactly identify our samples:

$$ \frac{\mathrm{relu}(10^{-4}-t) - \mathrm{relu}(-t)}{10^{-4}} = \left\\{\begin{array}{cl}1&\text{if }t\leq 0\\0&\text{if }t\geq 10^{-4}.\end{array}\right.$$

We implement this with a few layers of neurons:

$$ \begin{aligned} x\_{2,s} &= \mathrm{relu}(-1\cdot x\_{1,s}+10^{-4}), \\ x\_{3,s} & = \mathrm{relu}(-1\cdot x\_{1,s}), \\ x\_{4,s} &= 10^{4}\cdot x\_{2,s}-10^{4}\cdot x\_{3,s}. \end{aligned}$$

At this point, we have \\$x\_{4,s}=1\\$ when \\$p(s)\<10^{-4}\\$, and otherwise \\$x\_{4,s}=0\\$. Recall that we seek the largest \\$s^\star\\$ for which \\$x\_{4,s^\star}=1\\$. To this end, we label \\$x\_{4,M}\\$ as \\$x\_{5,M}\\$ (for notational convenience), and for each \\$k\geq 1\\$, we iteratively define

$$ x\_{5,M-k\delta} = 1\cdot x\_{4,M-k\delta}+2\cdot x\_{5,M-(k-1)\delta} = \sum\_{j=0}^k 2^{k-j}x\_{4,M-j\delta}. $$

Thanks to this transformation, every \\$x\_{5,s}\\$ is a nonnegative integer, and \\$s^\star\\$ is the unique \\$s\\$ for which \\$x\_{5,s}=1\\$. We may now identify \\$s^\star\\$ by another application of relu activations:

$$ \mathrm{relu}(t-2)-2\cdot\mathrm{relu}(t-1)+t = \left\\{\begin{array}{cl}1&\text{if }t=1\\0&\text{if }t\in\mathbf{Z}\_{\geq 0}\setminus\\{1\\}.\end{array}\right.$$

Explicitly, we define neurons by

$$ \begin{aligned} x\_{6,s} &= \mathrm{relu}(1\cdot x\_{5,s} - 2), \\ x\_{7,s} &= \mathrm{relu}(1\cdot x\_{5,s} - 1), \\ x\_{8,s} &= 1\cdot x\_{6,s} - 2\cdot x\_{7,s} + 1\cdot x\_{5s}. \end{aligned} $$

Then \\$x\_{8,s}=1\\$ if \\$s=s^\star\\$ and otherwise \\$x\_{8,s}=0\\$. We linearly combine these to produce our output node:

$$ x\_9 = \sum\_{s\in S} s\cdot x\_{8,s} = s^\star. $$

For the score, each layer has neurons with different levels of precision: (1) \\$6+3+1+9=19\\$, (2) \\$1+4=5\\$, (3) \\$1\\$, (4) \\$5+5=10\\$, (5) \\$1+1=2\\$, (6) \\$1+1=2\\$, (7) \\$1+1=2\\$, (8) \\$1+1+1=3\\$, (9) \\$3|S|\\$. Furthermore, all but two of the layers have \\$|S|=221\\$ neurons; layer 5 has \\$|S|-1\\$ neurons and layer 9 has \\$1\\$ neuron.

**Edit:** Improvements: (1) We can sample the polynomial much more efficiently using finite differences. (2) We can bypass layers 2 through 4 by instead using a sigmoid activation. (3) The overflow issues in layer 5 can be averted (and subsequent layers can be combined) by more carefully applying relu activations. (4) The final sum is cheaper with summation by parts.

What follows is the MATLAB code. To be clear, `prec` is a function (found here) that computes the precision of a vector of weights or biases.

```
function sstar = findsstar2(a,b,c)

relu = @(x) x .* (x>0);

totprec = 0;

% x1 samples the polynomial on -11:0.1:11
x1=[];
for s = -11:0.1:11
    if length(x1) < 5
        w1 = [s^2 s 1];
        b1 = s^3;
        x1(end+1,:) = w1 * [a; b; c] + b1;
        totprec = totprec + prec(w1) + prec(b1);
    else
        w1 = [-1 4 -6 4];
        x1(end+1,:) = w1 * x1(end-3:end,:);
        totprec = totprec + prec(w1);
    end
end

% x4 indicates whether the polynomial is nonpositive
w4 = -6e5;
b4 = 60;
x4=[];
for ii=1:length(x1)
    x4(end+1) = sigmf(w4 * x1(ii) + b4, [1,0]);
    totprec = totprec + prec(w4) + prec(b4);
end

% x6 indicates which entries are less than or equal to sstar
x5 = zeros(size(x1));
x6 = zeros(size(x1));
x5(end) = 0;
x6(end) = 0;
for ii = 1:length(x5)-1
    w5 = [-1 -1];
    b5 = 1;
    x5(end-ii) = relu(w5 * [x4(end-ii); x6(end-ii+1)] + b5);
    totprec = totprec + prec(w5) + prec(b5);
    w6 = -1;
    b6 = 1;
    x6(end-ii) = w6 * x5(end-ii) + b6;
    totprec = totprec + prec(w6) + prec(b6);
end

% a linear combination produces sstar
w7 = 0.1*ones(1,length(x1));
w7(1) = -11;
sstar = w7 * x6;

%disp(totprec) % uncomment to display score

end

```

# Answer
> 2 votes
# ~~53,268~~ ~~29,596~~ 29,306 total precision

Private communication with @A.Rex led to this solution, in which we construct a neural net that memorizes the answers. The core idea is that every function \\$f\colon S\to\mathbf{R}\\$ over a finite set \\$S\\$ enjoys the decomposition

$$ f(x) = \sum\_{s\in S}f(s)\cdot \left\\{\begin{array}{cl}1&\text{if }x=s\\0&\text{else}\end{array}\right\\}. $$

As such, one may construct a neural net implementation of \\$f\\$ by first transforming the input into an indicator function of the input, and then linearly combining using the desired outputs as weights. Furthermore, relu activations make this transformation possible:

$$ \mathrm{relu}(t-1)-2\cdot\mathrm{relu}(t)+\mathrm{relu}(t+1) = \left\\{\begin{array}{cl}1&\text{if } t=0\\0&\text{if }t\in\mathbf{Z}\setminus\\{0\\}.\end{array}\right. $$

What follows is a MATLAB implementation of this approach. To be clear, `roots.txt` is the roots file posted above (found here), and `prec` is a function (found here) that computes the total precision of a vector of weights or biases.

**Edit 1:** Two improvements over the original: (1) I factored some neurons out of the for loops. (2) I implemented "Lebesgue integration" in the final sum by first combining terms from the same level set. This way, I pay for the higher-precision value of an output only once every level set. Also, it is safe to round outputs to the nearest fifth by the rational root theorem.

**Edit 2:** Additional minor improvements: (1) I factored more neurons out of a for loop. (2) I don't bother computing the term in the final sum for which the output is already zero.

```
function r = approxroot(a,b,c)

relu = @(x)x .* (x>0);

totalprec=0;

% x4 indicates which entry of (-10:10) is a
w1 = ones(21,1);   b1 = -(-10:10)'-1;    x1 = relu(w1 * a + b1);
w2 = ones(21,1);   b2 = -(-10:10)';      x2 = relu(w2 * a + b2);
w3 = ones(21,1);   b3 = -(-10:10)'+1;    x3 = relu(w3 * a + b3);
w4p1 = ones(21,1); w4p2 = -2*ones(21,1); w4p3 = ones(21,1);
x4 = w4p1 .* x1 + w4p2 .* x2 + w4p3 .* x3;
totalprec = totalprec + prec(w1) + prec(w2) + prec(w3) + prec(b1) + prec(b2) + prec(b3) + prec(w4p1) + prec(w4p2) + prec(w4p3);

% x8 indicates which entry of (-10:10) is b
w5 = ones(21,1);   b5 = -(-10:10)'-1;    x5 = relu(w5 * b + b5);
w6 = ones(21,1);   b6 = -(-10:10)';      x6 = relu(w6 * b + b6);
w7 = ones(21,1);   b7 = -(-10:10)'+1;    x7 = relu(w7 * b + b7);
w8p1 = ones(21,1); w8p2 = -2*ones(21,1); w8p3 = ones(21,1);
x8 = w8p1 .* x5 + w8p2 .* x6 + w8p3 .* x7;
totalprec = totalprec + prec(w5) + prec(w6) + prec(w7) + prec(b5) + prec(b6) + prec(b7) + prec(w8p1) + prec(w8p2) + prec(w8p3);

% x12 indicates which entry of (-10:10) is c
w9 = ones(21,1);    b9 = -(-10:10)'-1;     x9 = relu(w9 * c + b9);
w10 = ones(21,1);   b10 = -(-10:10)';      x10 = relu(w10 * c + b10);
w11 = ones(21,1);   b11 = -(-10:10)'+1;    x11 = relu(w11 * c + b11);
w12p1 = ones(21,1); w12p2 = -2*ones(21,1); w12p3 = ones(21,1);
x12 = w12p1 .* x9 + w12p2 .* x10 + w12p3 .* x11;
totalprec = totalprec + prec(w9) + prec(w10) + prec(w11) + prec(b9) + prec(b10) + prec(b11) + prec(w12p1) + prec(w12p2) + prec(w12p3);

% x15 indicates which row of the roots file is relevant
x15=[];
for aa=-10:10
    w13 = 1;
    b13 = -2;
    x13 = w13 * x4(aa+11) + b13;
    totalprec = totalprec + prec(w13) + prec(b13);
    for bb=-10:10
        w14p1 = 1;
        w14p2 = 1;
        x14 = w14p1 * x13 + w14p2 * x8(bb+11);
        totalprec = totalprec + prec(w14p1) + prec(w14p2);
        for cc=-10:10
            w15p1 = 1;
            w15p2 = 1;
            x15(end+1,1) = relu(w15p1 * x14 + w15p2 * x12(cc+11));
            totalprec = totalprec + prec(w15p1) + prec(w15p2);
        end
    end
end

% r is the desired root, rounded to the nearest fifth
A = importdata('roots.txt');
outputs = 0.2 * round(5 * A(:,4)');
uniqueoutputs = unique(outputs);
x16 = [];
for rr = uniqueoutputs
    if rr == 0
        x16(end+1,:) = 0;
    else
        lvlset = find(outputs == rr);
        w16 = ones(1,length(lvlset));
        x16(end+1,:) = w16 * x15(lvlset);
        totalprec = totalprec + prec(w16);
    end
end
w17 = uniqueoutputs;
r = w17 * x16;
totalprec = totalprec + prec(w17);

%disp(totalprec) % uncomment to display score

end

```

---
Tags: code-challenge, optimization, polynomials, neural-networks
---


title: Can I Choose Not to Fly?

text:
# Question
Title: Can I Choose Not to Fly?
*Inspired by a chat conversation I lurked.*

I am an adventurer on the far away land of Zendikar. I truly enjoy traveling the land. Bushwhacking, weathering the roil and encountering strange and exotic flora and fauna are the highlights of any good adventure. Unfortunately, my duties as an adventurer do not always allow me to stop and smell the lotuses. Occasionally I am crunched for time and must hop on my kitesail and fly to my destination. I just glide over the land without being able to enjoy it.

# The Challenge

Write a program that will let me know if I can choose not to fly. The program will take three inputs: my current location, my destination, and the maximum permitted travel time in days. Using the information below, determine if my travel time on foot is less than my maximum allowed travel time. If it is and I can travel on foot, return a truthy value. If the land travel time is as long as or longer than the maximum time, return a falsey value.

**Guul Draz** is two days away from **Sejiri**, its only neighboring territory.

**Sejiri** is one day away from **Murasa** and two days from **Guul Draz**.

**Murasa** is one day from **Bala Ged**, one day from **Akoum**, two days from **Tazeem**, and one day from **Sejiri**.

**Bala Ged** is two days from **Akoum** and one day from **Murasa**.

**Akoum** is one day from **Ondu**, one day from **Murasa** and two days from **Bala Ged**.

**Ondu** is one day from **Akoum**, its only neighboring territory.

**Tazeem** is two days from **Murasa**, its only neighboring territory.

Every location is connected, but not always directly. For example, going from Tazeem to anywhere requires you to travel to Murasa first. There are no real branches in the path either. Protip: Only go to Bala Ged if it is one of your endpoints. Here is a rough map if you're lost:

```
                        Bala Ged --
                           |       \
Guul Draz ---- Sejiri -- Murasa -- Akoum -- Ondu
                            |
                            |
                         Tazeem

```

# Scoring

This is code golf, so shortest program wins. Standard loopholes apply.

# Test Cases

```
Guul Draz
Ondu
5

False

Bala Ged
Akoum
3

True

Tazeem
Sejiri
1

False

```

# Answer
# TI-BASIC, ~~84~~ 82 bytes

```
Prompt Str1,Str2,X
"GSMAOBT->Str3
{-3,-1,0,1,2,i,-2i
Ans(inString(Str3,sub(Str1,1,1))-Ans(inString(Str3,sub(Str2,1,1
X>real(Ans-iAns

```

I store the positions of each city on the complex plane, then calculate the Manhattan distance. Bala Ged is at `0+1i`, Guul Draz is at `-3+0i`, and so on.

There would be a 75-ish byte solution if quotes could be in strings, but one of TI-BASIC's limitations prevents that.
> 8 votes

# Answer
# Mathematica 153

This checks whether the required time to travel (the `GraphDistance` in `Edgeweight`s, i.e. days), is less than or equal to the available time to travel, also in days. This sort of approach should work with much larger graphs, corresponding to a great many locations and connections.

```
s=StringTake;g=Graph[UndirectedEdge@@@Partition[Characters@"GSSMMBMAMTBAAO",2],
EdgeWeight->{2,1,1,1,2,1,1}]
f[a_,b_,n_]:=GraphDistance[g,a~s~1,b~s~1]<=n

```
> 4 votes

# Answer
# Ruby 113/112

More bytes than TI Basic, but less characters.

```
v=0
a=(0..1).map{c=gets[0];(d="BT".index(c))&&v+=1+d;"GGSMAO".index(c.tr('BT',?M))}
p gets.to_i>(a[0]-a[1]).abs+v

v=0
a=(0..1).map{c=gets[0];(d="BT".index(c))&&v+=1+d;"OAMSSGGGBBBBBBT".index(c)%6}
p gets.to_i>(a[0]-a[1]).abs+v

```

Two slightly different solutions, on the same principle:

There's no point in considering the direct route between Bala Ged and Akoum, because the route via Murasa is the same length.

The main left-right string of places can be considered by taking the indices in a string and finding the difference between them.

For B and T, we need to add an extra 1 or 2. This is held in the variable `v`. The two versions differ in the way that B and T are made to give the same index in the main string as M. In the first, it's done by replacement B or T --\> M in the input. In the second it's done by modulo (I prefer the first one, but the second one's a byte shorter.)
> 1 votes

# Answer
# 05AB1E, 44 bytes

```
"GSMAOBT"D2FsIнk])εyy0Qi¼ëy4›i2¼y5-½]`α¾+³-d

```

Try it online!

A little too long to be proud of

```
"GSMAOBT"   push the first letters of each city
D           duplicate this
2F          do 2 times:
  s           swap the two previous stack entries
  I           get next input
  н           get the first letter of that
  k           push the index of that letter in "GSMAOBT"
]
)           push both indexes in a list

ε           for each entry of that list
  y           push the current value for that entry
  y0Qi        if current entry == 0 (Guul Draz)
  ¼           increment counter (will be added to the distance in the end)
ë           else
  y4›i        if current entry > 4 (Bala Ged or Tazeem)
    2           set current list entry = 2 (Murasa)
    ¼           increment counter
    y5-½        if entry = 4 (Tazeem), increment counter another time
]
`           push both indexes on the stack separated
α           get absolute difference of them
¾+          add the counter variable to that
³-d         check, if it's equal or smaller than the maximum time

```
> 0 votes

---
Tags: code-golf
---


title: What is the score of my Scopa hand?

text:
# Question
Title: What is the score of my Scopa hand?
I like card game challenges so I made this one for the Italian card game Scopa. My family has been playing this game since time immemorial. It has a very interesting scoring system that should be fun to golf. I will post an answer in R to get the fun started, that I am sure people will improve upon.

**The challenge: figure out the number of points scored in a round of Scopa, given the cards the player captured during the round as input.**

There are 40 cards in a Scopa deck. If you are using an international deck you remove the 8s, 9s, and 10s, leaving A,2,3,4,5,6,7,Q,J,K in each suit.1 There are two players or partnerships, and after every round, all cards end up captured by one or the other of the two players. The score is counted as follows (more information here):

* The player with the most **cards** scores 1 point.
* The player with the most **diamonds** (or coins if using the Italian deck) scores 1 point.
* The player with the **7 of diamonds** (or coins), known as the *sette bello* or beautiful seven, scores 1 point.
* The player with the highest ***primiera*** scores 1 point. A player's *primiera* score is the sum of the scores of the highest-value card that the player captured in each suit (see table below). If you do not have at least one card in every suit, you lose by default even if your score would exceed your opponent's score. In the exceedingly rare case that neither player has at least one card in every suit, the player with the higher *primiera* total scores the point.2

### Table of primiera scores

```
| Rank  | Value |
| ----- | ----- |
| 7     | 21    |
| 6     | 18    |
| A     | 16    |
| 5     | 15    |
| 4     | 14    |
| 3     | 13    |
| 2     | 12    |
| Q,J,K | 10    |

```

So a player can score at most 4 points in a round.3 If there is a tie, which is possible for cards, diamonds, or *primiera*, no one scores the point.

It's important to realize that since each card must be captured by one of the two players, you can infer what cards the other player must have taken even if you only know what cards one player took. You will need to do this to correctly score *primiera*.

## Challenge rules

### Input

Your code should take as input the cards captured by a single player during a round of Scopa.

***Input must be in string format, in which one character represents the rank of each card and one character its suit.*** This removes the potential loophole of passing the *primiera* scores in directly as input. Conversion of card ranks to *primiera* scores must be done in the program. However you may choose to use a single string separated by spaces or commas, an array of strings, or any other format. For example if you choose to encode ranks as `76A5432QJK` and suits as `DCHS` you could use inputs such as `['7D', '6H', 'QD', 'JS']` or `'7D,6H,QD,JS'`.

### Output

An integer from 0 to 4 representing the player's score.

### Winning

Shortest answer in bytes wins!

## Test cases

`["7D", "6D", "AD", "5D", "4D", "3D", "2D", "QD", "7C", "6C", "4C", "3C", "2C", "7H", "4H", "2H", "5S", "3S", "QS", "JS", "KS"]`

**Scores 4**: 1 point for \>20 cards, 1 point for \>5 diamonds, 1 point for the 7 of diamonds, and 1 point for scoring 78 in *primiera* (7,7,7,5 where opponent has 7,6,5,K for 64)

`["3D", "7C", "6C", "AC", "5C", "4C", "3C", "2C", "QC", "4H", "7S"]`

**Scores 0**: \<=20 cards, \<=5 diamonds, no 7 of diamonds, and only scores 69 in *primiera* (7,7,4,3 where opponent has 7,7,6,K for 70)

`[7D", "6D", "AD", "5D", "4D", "3D", "2D", "7C", "6C", "AC", "5C", "4C", "3C", "2C", "7H", "6H", "AH", "5H", "4H", "3H", "2H"]`

**Scores 3**: 1 point for \>20 cards, 1 point for \>5 diamonds, 1 point for 7 of diamonds. The *primiera* would be 63 (7,7,7) and the opponent can only score 51 (7,Q,Q,Q) but since this hand has no spades it loses the point by default.

`["7D", "6D", "AD", "5D", "4D", "3D", "2D", "QD", "JD", "KD", "QC", "QH", "QS"]`

**Scores 3**: \<=20 cards, 1 point for \>5 diamonds, 1 point for 7 of diamonds. The *primiera* only scores 51 (7,Q,Q,Q) and the opponent can score 63 (7,7,7) but since the opponent's hand has no diamonds this hand wins the *primiera* point by default.

`["7D", "6D", "AD", "5D", "4D", "3D", "2D", "QD", "JD", "KD", "7C", "7H"]`

**Scores 3**: \<=20 cards, 1 point for \>5 diamonds, 1 point for 7 of diamonds. Even though this hand has no spades, it still wins *primiera* by a score of 63 to 57 (7,7,7 versus 7,6,6) because the opponent's hand has no diamonds.

`["7D", "6D", "AD", "5D", "4D", "3D", "2D", "QD", "JD", "KD", "QC", "QH"]`

**Scores 2**: \<=20 cards, 1 point for \>5 diamonds, 1 point for 7 of diamonds. This hand has no spades, and opponent's hand has no diamonds. Opponent wins *primiera* by a score of 63 to 41 (7,7,7 versus 7,Q,Q).

`[]` (empty array)

**Scores 0**

---

1: At least in our family, Jack outranks Queen in Scopa but this is irrelevant for scoring purposes.

2: I've been playing this game since childhood and have never seen that happen but your code had better be able to handle that case!

3: There are bonus points for "sweeps" scored during the round which I am ignoring for the purpose of this challenge.

# Answer
## Ruby, ~~156~~ 153 bytes

```
->a{b='';([a[40],a.scan(/.d/)[5],a=~/;d/,'dchs'.gsub(/./){l=a.scan /.(?=#$&)/;l.size<10&&b+=(';865432'.tr(l*'','')+?0)[0];l.max}.sum>b.sum||p]-[p]).size}

```

Try it online!

```
->a{
b='';                # stores primiera of other player
([                   # this array stores all checks
a[40],               # check if >20 cards (>40 characters)
a.scan(/.d/)[5],     # check if >5 diamonds
a=~/;d/,             # check if 7 of diamonds
'dchs'.gsub(/./){    # for each suit, build a string with...
l=a.scan /.(?=#$&)/; # find all cards with this suit
l.size<10&&          # if there are less than 10, the other person has some, so
b+=                  # append to their score string the following:
(';865432'           #   start with all the cards
.tr(l*'','')         #   remove the ones we have
+?0)                 #   add back the JQK at the end
[0];                 #   take the highest
l.max}               # return the highest card that we have
.sum                 # take the sum of the codepoints
>b.sum               # check if it's greater than the other player's sum
||p                  # if not, evaluate to nil
]-[p])               # remove all nils
.size}               # count how many are left

```

This uses `;865432000` to represent `76A5432QJK` respectively, and suits are in lowercase. (The choice of characters is because subtracting 38 from each gives their primiera value, but we never actually do so because only the relative difference matters.)

We don't check whether either player is missing a suit because it is unnecessary -- since all cards are counted as 38 plus their actual value, if someone is missing a suit, the highest score they can get is (21+38)\*3 = 177, which is less than (10+38)\*3 + 21+38 = 203, the lowest score the other player can get. We cannot have the two players missing an unequal nonzero number of suits, because a player can only be missing 0, 1, or 2 suits, and if someone is missing 2 suits they have all the cards of the other 2 suits.
> 6 votes

# Answer
# R, ~~320~~ ~~298~~ ~~265~~ ~~238~~ ~~229~~ ~~224~~ ~~211~~ ~~209~~ 179 bytes

This is a solution mostly due to @digEmAll, in the form of a function.

Try it online!

```
function(h,S=sum,A=apply,l=99+c(11,8,5:2,6,!1:3)%o%!!1:4)S(S(p<-outer(c(7:2,'A','K','J','Q'),c('D','C','H','S'),paste0)%in%h)>20,S(p[1:10])>5,p[1],S(A(l*p,2,max)-A(l*!p,2,max))>0)

```

Below is the best of my old mediocre attempts for 209 bytes.

*edit: golfed down by aliasing some functions, then by taking Doorknob's idea of adding a constant to the score instead of checking the suits.*

*next edit: got rid of some redundancy and then incorporated some improvements from Giuseppe*

*next edit: -2 bytes thanks to digEmAll*

I am terrible at this, so I'm sure someone can improve on this if they care to take the time. I feel like the `sapply` and `function` are super long and could get rid of them but I can't figure out how. Inputs are two-character strings in the standard notation.

```
function(h,s=sum,l=c(11,8,5:2,6,!1:3)+99)s(length(h)>20,s(grepl('D',h))>5,'7D'%in%h,s(sapply(c('D','C','H','S'),function(i,r=c(7:2,'A','K','J','Q')%in%substr(h[grep(i,h)],1,1))s(l[r][1],-l[!r][1],na.rm=T)))>0)

```
> 4 votes

# Answer
# JavaScript (ES6),  ~~171~~  163 bytes

Takes input as a set of cards, using their standard representation.

```
c=>(c.size>20)+((g=o=>[..."CHSD"].map(s=>[..."JQK2345A67"].map((v,i)=>(S=o^c.has(v+s))?m="111345679"[++n,i]||12:0,n=m=0)|(n?0:T=1,t-=m),T=t=4)|t*T)(1)>g``)+S+(n>5)

```

Try it online!

### Commented

```
c =>                                // c = set of cards
  (c.size > 20) + (                 // +1 point if we have more than 20 cards
    ( g = o =>                      // g is a function taking the flag o (for 'opponent')
      [..."CHSD"].map(s =>          // for each suit s, ending with diamonds:
        [..."JQK2345A67"]           //   for each rank v at position i, sorted from
        .map((v, i) =>              //   lowest to highest primiera score:
          (S = o ^ c.has(v + s)) ?  //     if the player owns this card, set S to 1 and:
            m = "111345679"[++n, i] //       increment n; update m to the score of this
                || 12               //       rank (we use the official score - 9)
          :                         //     else:
            0,                      //       do nothing
          n = m = 0                 //     start with n = m = 0
        ) |                         //   end of inner map()
        ( n ? 0 : T = 1,            //   if n = 0, set T to 1
          t -= m ),                 //   subtract m from t
        T = t = 4                   //   start with T = t = 4
      ) | t * T                     // end of outer map(); yield t * T
    )(1) > g``                      // +1 point if g(1) is greater than g(0)
  ) +                               // (we test this way because the scores are negative)
  S +                               // +1 point if we own the 7 of diamonds
  (n > 5)                           // +1 point if we own more than 5 diamonds

```
> 2 votes

# Answer
# C# (Visual C# Interactive Compiler), 193 bytes

```
x=>x.Count/21+x.Count(g=>g>48)+x.Sum(g=>g/40)/6+("".Sum(m=>{var r=x.Where(g=>g/10==m);return(r.Any()?r.Max()%10+50:0)-(r.Count()<10?"	".Max(l=>x.Contains(m*10+l)?48:l+50):0);})>0?1:0)

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 41 bytes

```
39ÝsK‚εg9y@Oy0å•Dδ¿m(/d•₆вy.γT÷}è€àO)}`›O

```

Try it online or check all test cases.

Suits `DCHS` are respectively represented by `0123`. Ranks `7A65432KJQ` are respectively represented by `0123456789`. Those are taken as strings, not integers, as required by the challenge (but then 05AB1E converts them to integers when needed anyway).

As in other solutions, we add a large constant (14) to each primiera score in order to make the check for missing suits unnecessary.

39Ý                      # range 0..39 (the list of all cards in the game)
   sK                    # remove all elements that appear in the input
      ‚                  # pair with the input: [player's hand, opponent's hand]

ε                     }  # map each hand to a list of its 4 subscores:
 g                       #  first subscore: length (number of cards)
 9y@O                    #  second subscore: count elements <= 9 (diamonds)
 y0å                     #  third subscore: is 0 (representing 7D) in the list
            y.γT÷}       #  group the hand by suit
 •Dδ¿m(/d•₆в      è      #  map each rank to its primiera score
                   €à    #  maximum primiera score in each suit
                     O   #  fourth subscore: the sum of those

`›                       # for each subscore: is player's > opponent's?
  O                      # sum
```
</code></pre>
> 2 votes

# Answer
# MS SQL Server 2017, 525 bytes

```
CREATE FUNCTION f(@ NVARCHAR(MAX))RETURNS TABLE RETURN
SELECT q/21+IIF(d>6,2,IIF(d=6,1,0))+IIF(m=0,IIF(n=0 AND a>b,1,0),IIF(n=0 OR a>b,1,0))p
FROM(SELECT SUM(q)q,MAX(IIF(s='D',q,0))d,SUM(a)a,MIN(q)m,SUM(b)b,MIN(10-q)n
FROM(SELECT s,COUNT(k)q,MAX(IIF(r=k,v,0))a,MAX(IIF(r=k,0,v))b
FROM(SELECT LEFT(value,1)r,s,ASCII(RIGHT(value,1))-38 v
FROM STRING_SPLIT('7;,68,A6,5,4,3,2,Q0,J0,K0',','),(VALUES('D'),('C'),('H'),('S'))s(s))d
LEFT JOIN(SELECT LEFT(value,1)k,RIGHT(value,1)u FROM STRING_SPLIT(@,','))a
ON r+s=k+u GROUP BY s)t)t

```

Try it on db\<\>fiddle.
> 2 votes

# Answer
# Retina 0.8.2, 334 bytes

```
$
 ¶234567JQKA
r`.\G
$&C $&D $&H $&S
+`((\w\w).*¶.*)\2
$1
T`67AJQK`8960
%O$`(\w)(\w)
$2$1
m`^(?=(...)*)(.C )*(.D )*(.H )*(.S )*
$3;$#1 $#2 $#3 $#4 $#5;${2}${3}${4}$5
m`^(?=(9D))?...;
$#1;
(;(?!.*10).* 0.*;).*
$1
\d[C-S]
1$&
19\w
21$*@
\d+(\w )?
$*@
(@)?;(@*) @* (@*).*;(@*)¶@?;((?!\2))?@* @* ((?!\3))?.*;((?!\4))?.*
$#1$#5$#6$#7
1

```

Try it online! Link includes test cases. Explanation:

```
$
 ¶234567JQKA
r`.\G
$&C $&D $&H $&S

```

Create a list of all 40 cards.

```
+`((\w\w).*¶.*)\2
$1

```

Remove the cards the player holds.

```
T`67AJQK`8960

```

Replace each rank by its sort order, which is 9 for `7` and 10 less than its value for other cards.

```
%O$`(\w)(\w)
$2$1

```

Sort the cards by suit and rank.

```
m`^(?=(...)*)(.C )*(.D )*(.H )*(.S )*
$3;$#1 $#2 $#3 $#4 $#5;${2}${3}${4}$5

```

Count the number of cards in each suit and also capture the highest ranked card in each suit, capturing the highest diamond twice.

```
m`^(?=(9D))?...;
$#1;

```

Check whether the highest diamond was the 7.

```
(;(?!.*10).* 0.*;).*
$1

```

Delete all of the highest cards if one of the suits has no cards.

```
\d[C-S]
1$&
19\w
21$*@
\d+(\w )?
$*@

```

Convert the highest cards to their unary score and sum them together. Also convert the total number of cards and suit lengths to unary.

```
(@)?;(@*) @* (@*).*;(@*)¶@?;((?!\2))?@* @* ((?!\3))?.*;((?!\4))?.*
$#1$#5$#6$#7

```

Score points if the total, diamonds, or primiera, is higher.

```
1

```

Total the score.
> 1 votes

# Answer
# Python 3, ~~249 245 239~~ 238 bytes

*-4 bytes thanks to @ovs*

*-6 bytes thanks to @movatica*

```
lambda C:sum([len(C)>20,'7D'in C,len([c for c in C if'E'>c[1]])>5,p(C)>p({n+s for n in'9876543210'for s in S}-C)])
p=lambda C:[not S.strip(''.join(C)),sum(max([(c[1]==s)*int('9gcdefil99'[int(c[0])],22)for c in C]+[0])for s in S)]
S='DcHS'

```

Try it online!
> 1 votes

# Answer
# AWK, 235 bytes

```
{s[9]=35;s[8]=32;s[7]=30;s[6]=29;s[5]=28;s[4]=27;s[3]=26;s[2]=s[1]=s[0]=24;a[$1 $2]=s[$1]}END{while(i++<4){D=0;for(j=0;j<10;j++){if(a[j i]<1){B[i]=s[j];D++}if(A[i]<a[j i])A[i]=a[j i]}x+=A[i];y+=B[i]}print(20<NR)+(D<5)+(1<a[9 4])+(y<x)}

```

Try it online!

Suits map to 1234 (4 is diamonds), values map to 0123456789. This program transforms the test cases into the accepted format:

```
BEGIN{RS=", ";FS="";t[7]=9;t[6]=8;t["A"]=7;t[5]=6;t[4]=5;t[3]=4;t[2]=3;t["Q"]=2;t["J"]=1;t["K"]=0;u["D"]=4;u["C"]=1;u["H"]=2;u["S"]=3}{gsub("[\\[\"\\]]","",$0);print t[$1],u[$2]}

```

My goal was just to beat the leading Python implementation :D
> 1 votes

---
Tags: code-golf, card-games
---


title: French license plates

text:
# Question
Title: French license plates
Sandbox

# French License Plates

French license plates come in a sequential order, following a specific pattern of numbers and letters : `AB-012-CD`

## Challenge

Write a program or function that, for a given number, outputs the corresponding french license plate number. Your program should not handle any special case as specified in the linked page. It should be able to generate the full `26*26*1000*26*26 => 456 976 000` possible plates, or as far as your language can support.

The numbering system goes as follows:

* AA-000-AA to AA-999-AA (numbers evolve first);
* AA-000-AB to AA-999-AZ (then the last letter on the right);
* AA-000-BA to AA-999-ZZ (then the first letter on the right);
* AB-000-AA to AZ-999-ZZ (then the last letter on the left);
* BA-000-AA to ZZ-999-ZZ (then the first letter on the left).

### Input

* The plate number's index as an integer

### Output

* The corresponding french license plate number

### Additional information

* Letters have to be uppercase
* You can use both 0-based and 1-based indexing to generate the plates (meaning AA-000-AA can correspond to `0`or `1`, assuming all the other test cases use the same indexing.

This is code-golf, shortest answer in every language wins!

## Test cases (0-based indexing)

```
          0 -> AA-000-AA
          1 -> AA-001-AA
        999 -> AA-999-AA
       1000 -> AA-000-AB
    675 999 -> AA-999-ZZ
    676 000 -> AB-000-AA
456 975 999 -> ZZ-999-ZZ

```

# Answer
# Perl 5 (-ap), 47 bytes

```
$_=AAAA000;$_++while$F[0]--;s/(..)(\d+)/-$2-$1/

```

Try it online!

---

# PHP, 74 bytes

```
for($a=AAAA000;$argn--;$a++);echo preg_replace('/(..)(\d+)/','-$2-$1',$a);

```

Try it online!
> 13 votes

# Answer
# Pure Bash (no external utils), 64

* 2 bytes saved thanks to @NahuelFouilleul

```
x={A..Z}
eval f=($x$x-%03d-$x$x)
printf ${f[$1/1000]} $[$1%1000]

```

Try it online! \- takes about 10s to run over the 7 testcases.

* Line #1 is a simple assignment of a string to a variable
* Line #2 is a brace expansion to build an array of printf format strings, one for all 456,976 possible letter combinations, with the digits not yet specified. The `eval` is required to ensure variable expansion (of x) occurs before brace expansion.
* Line #3 indexes the array to get the appropriate format string and takes the digits portion as its parameter.
> 17 votes

# Answer
## Ruby, ~~61~~ ~~59~~ 55 bytes

```
->n{s='AA-AA000-';eval's.succ!;'*n;s[2]+=s[5,4];s[0,9]}

```

Also 55 bytes:

```
->n{s='AA-AA000-';eval's.succ!;'*n;s[2]+=s.slice!5,4;s}

```

Try it online!

This initializes a counter to `AA-AA000-`, increments it `n` times (by multiplying a string of the code that does so by n and `eval`ing), and then moves the last 4 characters after the 3nd.
> 8 votes

# Answer
# Python 3, 79 78 77 bytes

```
lambda n:f"%c%c-{n%1000:03}-%c%c"%(*(65+n//1000//26**i%26for i in[3,2,1,0]),)

```

Try it online!

I somehow never realised that the `f"string"` format shortcut exists until seeing Black Owl Kai's answer.
> 8 votes

# Answer
# PHP, ~~96~~ ~~84~~ 79 bytes

-5 byte thanks to Ismael Miguel's great comments.

```
for($s=AAAA;$x++^$argn/1e3;)$s++;printf('%.2s-%03u-'.$s[2].$s[3],$s,$argn%1e3);

```

Try it online!

I take advantage of the fact that you can increment letters in PHP! So `AAAA++` would become `AAAB` and `AAAZ++` would become `AABA`. I calculate how many times the letters have to be incremented by getting integer part of `input/1000`. Then increment the four characters length that many times and its first two and last two characters will automatically become the left and right side of the plate.

For example for input of `675999` number of letter increments is `(int)(675999 / 1000) = 675`, so `AAAA` will become `AAZZ`.

Finally, the middle number is calculated by `input%1000` and everything is printed in the specified format with help of printf. `%.2s` prints first two characters of the string, `%03u` pads the number in the left with 3 zeros.
> 7 votes

# Answer
## Haskell, ~~85~~ ~~81~~ ~~79~~ 77 bytes

```
([h++'-':n++'-':t|h<-q"AZ",t<-q"AZ",n<-q"099"]!!)
q g=mapM(\_->[g!!0..g!!1])g

```

Try it online!
> 7 votes

# Answer
# C, 88 86 bytes

```
#define d(b)a/b/1000%26+65
f(a){printf("%c%c-%03d-%c%c",d(17576),d(676),a%1000,d(26),d(1));}

```

Pretty simple, it uses division and modulus to extract the fields, adds 'A' for the letters to map them to ASCII characters, and printf formatting for the numbers.

Try it online!
> 7 votes

# Answer
# , ~~56~~ ~~49~~ 46 bytes

```
226950 A.'--',7$_3|.4,@u:65 48+/(4 3#26 10)#:]

```

Try it online!

*-3 bytes thanks to FrownyFrog*

The whole thing is nothing but 7 nested trains -- if that ain't fun, what is?

```
  ┌─ 226950
  ├─ A.
  │        ┌─ '--'
──┤        ├─ ,
  │        │      ┌─ 7
  └────────┤      ├─ $
           │      │   ┌─ _3
           └──────┤   ├─ |.
                  │   │    ┌─ 4
                  └───┤    │     ┌─ ,
                      │    ├─ @ ─┴─ u:
                      └────┤
                           │     ┌─ 65 48
                           │     ├─ / ───── +
                           └─────┤
                                 │       ┌─ '4 3#26 10'
                                 └───────┼─ #:
                                         └─ ]

```
> 6 votes

# Answer
# 05AB1E, ~~25~~ ~~22~~ 20 bytes

```
Au2ããs₄‰`UèX₄+¦'-.øý

```

-2 bytes (and increased the performance by not generating the entire list) thanks to *@Grimy*.

0-based indexing.

Try it online or verify all test cases.

**Explanation:**

```
Au            # Push the lowercase alphabet, and uppercase it
  2ã          # Create all possible pairs by taking the cartesian product with itself:
              #  ["AA","AB","AC",...,"ZY","ZZ"]
    ã         # Get the cartesian product of this list with itself:
              #  [["AA","AA"],["AA","AB"],...,["ZZ","ZZ"]]
s             # Swap to push the (implicit) input
 ₄‰           # Take the divmod-1000 of it
              #  i.e. 7483045 becomes [7483,45]
    `         # Push these values separated to the stack
     U        # Pop and store the remainder part in variable `X`
      è       # Index the integer part into the list of letter-pairs we created earlier
              #  i.e. 7483 will result in ["AL","BV"]
X             # Push the remainder part from variable `X` again
 ₄+           # Add 1000 to it
   ¦          # And remove the leading 1 (so now the number is padded with leading 0s)
              #  i.e. 45 becomes 1045 and then "045"
    '-.ø     '# Surround this with "-" (i.e. "045" becomes "-045-")
        ý     # Join the two pairs of letters by this
              #  i.e. ["AL","BV"] and "-045-" becomes "AL-045-BV"
              # (after which the top of the stack is output implicitly as result)

```

The last part (`s₄‰`UèX₄+¦'-.øý`) could be `I₄÷èI₄+3.£.ý'-ý` for an equal-bytes alternative:
Try it online or verify all test cases.

```
I₄÷           # Push the input, integer-divided by 1000
   è          # Use it to index into the letter-pairs we created earlier
              #  i.e. 7483045 becomes 7483 and then ["AL","BV"]
I₄+           # Push the input again, and add 1000
   3.£        # Only leave the last three digits
              #  i.e. 7483045 becomes 7484045 and then "045"
      .ý      # Intersperse the pair with this
              #  i.e. ["AL","BV"] and "045" becomes ["AL","045","BV"]
        '-ý  '# And join this list by "-"
              #  i.e. ["AL","045","BV"] becomes "AL-045-BV"
              # (after which the top of the stack is output implicitly as result)

```
> 6 votes

# Answer
# JavaScript (Node.js), 82 bytes

```
n=>'32-654-10'.replace(/\d/g,x=>Buffer([x&4?n/10**(x-4)%10+48:n/1e3/26**x%26+65]))

```

Try it online!
> 5 votes

# Answer
# , 101 bytes

```
b=0:3;a=scan()%/%c(10^b,1e3*26^b)%%rep(c(10,26),e=4);intToUtf8(c(a[8:7],-20,a[3:1]-17,-20,a[6:5])+65)

```

Try it online!

Just does the needed arithmetic computations. I saved 5 bytes by including in the vector `a` a useless value at `a[4]`, allowing me to reuse the helper vector `b`.

Consider for example the second character (the `B` in `AB-012-CD`). That character changes every \\$26\times26\times1000=676\\,000\\$ plates, so the value of that character for input `n` is the `n %/% 676000 %% 26`th letter of the alphabet, where `%/%` is integer division and `%%` is modulus in R. The other characters are computed similarly.
> 5 votes

# Answer
# Ruby, 51 bytes

```
->n{[*?A*4..?Z*4][n/1e3][/../]+"-%03d-"%(n%1e3)+$'}

```

Try it online!
> 5 votes

# Answer
# Jelly,  ~~26~~  22 bytes

```
ØAṗ2,`ØDṗ3¤ṭŒp⁸ị2œ?j”-

```

A monadic Link accepting an integer (1-indexed) which yields a list of characters... Crazy-slow since it builds all the plates first!

**Try it online!** (wont complete)
Or try a reduced alphabet version (only "ABC" for the letters).

---

For code which completes in a timely manner here's a 32 byte full-program (0-indexed) which creates the single plate instead using modular arithmetic and numeric base decompression:

```
dȷ+“©L§“£ż’µḢṃØAṙ1¤ḊŒHW€jDḊ€$j”-

```

**Try this one!**
> 4 votes

# Answer
# APL+WIN, 61 bytes

Prompts for integer:

```
m←⎕av[4↑66+n←((4⍴26),1E3)⊤⎕]⋄(2↑m),'-',(¯3↑'00',⍕4↓n),'-',2↓m

```

Try it online! Courtesy of Dyalog Classic
> 3 votes

# Answer
# Charcoal, 33 bytes

```
Ｎθ¹✂Ｉ⁺θφ±³≔⪪⍘⁺Ｘ²⁶¦⁵÷θφα²η¹⊟ηＭ⁹←⊟η

```

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

```
Ｎθ

```

Input the number.

```
¹

```

Print a `-`.

```
✂Ｉ⁺θφ±³

```

Add 1000 to the number, then cast the result to string, and print the last three digits.

```
≔⪪⍘⁺Ｘ²⁶¦⁵÷θφα²η

```

Divide the number by 1000, then add 26⁵, so the conversion to custom base using the uppercase alphabet results in a string of length 6, which is then split into pairs of letters.

```
¹

```

Print a `-`.

```
⊟η

```

Print the last pair of letters.

```
Ｍ⁹←

```

Move to the beginning of the number plate.

```
⊟η

```

Print the rest of the desired letters.
> 3 votes

# Answer
# Perl 6, 42 bytes

```
{S/(..)(\d+)/-$1-$0/}o{('AAAA000'..*)[$_]}

```

Try it online!

Port of Grimy's Perl 5 solution. Slow for large input values.
> 3 votes

# Answer
# Excel, ~~183~~ ~~167~~ ~~155~~ 147 bytes

-16 bytes thanks to @Neil. (6 by using `E3`)

-12 bytes thanks to @Keeta. (`TRUNC` instead of `QUOTIENT`)

-8 bytes thanks to @Jonathan Larouche (`INT` instead of `TRUNC`)

```
=CHAR(65+INT(A1/17576E3))&CHAR(65+MOD(INT(A1/676E3),26))&"-"&TEXT(MOD(A1,1E3),"000")&"-"&CHAR(65+MOD(INT(A1/26E3),26))&CHAR(65+MOD(INT(A1/1E3),26))

```

Concatenates 5 parts:

```
CHAR(65+INT(A1/17576E3))
CHAR(65+MOD(INT(A1/676E3),26))
TEXT(MOD(A1,1E3),"000")
CHAR(65+MOD(INT(A1/26E3),26))
CHAR(65+MOD(INT(A1/1E3),26))

```
> 3 votes

# Answer
# Clean, 107 bytes

```
import StdEnv
A=['A'..'Z']
N=['0'..'9']
$n=[[a,b,'-',x,y,z,'-',c,d]\\a<-A,b<-A,c<-A,d<-A,x<-N,y<-N,z<-N]!!n

```

Try it online!

Defines `$ :: Int -> [Char]` giving the n-th zero-indexed licence plate.
> 2 votes

# Answer
# Japt, 21 bytes

Obscenely slow! Seriously, don't even try to run it!

Tip of the hat to Kevin for making me realise where I was going wrong when fighting to get this working last night.

```
;gBï ï ïq#d0o ùT3 û-5

```

Try it \- limits the number range to `000-005`.

```
;gBï ï ïq#d0o ùT3 û-5     :Implicit input of integer
 g                        :Index into
; B                       :  Uppercase alphabet
   ï                      :  Cartesian product with itself
     ï                    :  Cartesian product of the result with itself
       ï                  :  Cartesian product of that with
         #d0              :    1000
            o             :    Range [0,1000)
              ùT3         :    Left pad each with 0 to length 3
                  û-5     :    Centre pad each with "-" to length 5
        q                 :  Join the first element (the 2 pairs of letters) with the second (the padded digit string)

```
> 2 votes

# Answer
# Forth (gforth), 94 bytes

```
: x /mod 65 + emit ; : f dup 1000 / 17576 x 676 x ." -"swap 0 <# # # # #> type ." -"26 x 1 x ;

```

Try it online!

0-indexed. Input is taken from top of stack

### Code explanation

```
\ extract out some common logic
: x             \ start a new word definition
  /mod          \ divide first argument by second and get both quotient and remainder
  65 +          \ add 65 (ascii A) to quotient
  emit          \ output
;               \ end word definition

: f             \ start a new word definition
  dup 100 /     \ duplicate input and divide by 1000
  17576 x       \ divide by 26^3 and output ascii char
  676 x         \ divide by 26^2 and output ascii char
  ." -"         \ output "-"
  swap 0        \ grab original number and convert to double-cell number
  <# # # # #>   \ convert last 3 chars of number to a string
  type ." -"    \ output string followed by "-"
  26 x          \ divide result of last mod by 26 and output ascii char
  1 x           \ output ascii char for remaining amount
;               \ end word definition

```
> 2 votes

# Answer
# , 78 bytes

```
{sv["-","0"^-4$($:[x mod 1000]),"-"]2 2#(|).Q.A mod[x div 1000*26 xexp(!)4]26}

```

---

```
                                                    x div 1000*26 xexp(!)4     / input (floor) divided by 1000*26 ^ 0 1 2 3
                                                mod[                      ]26  / mod 26
                                           .Q.a                                / alphabet uppercase, indexed into by preceeding lines, for x=1000, we'd get "BAAA"
                                    2 2#(|)                                    / reverse and cut into 2x2 matrix ("AA";"AB")
               ($:[x mod 1000]),"-"                                            / string cast x mod 1000 and append "-"
            -4$                                                                / left pad to length 4, "  0-"
    "-","0"^                                                                   / fill nulls (" ") with "0" and prepend "-"
 sv[              x                ]y                                          / join elems of y by x

```
> 2 votes

# Answer
# T-SQL, 135 bytes

```
select concat(CHAR(65+(@i/17576000)),CHAR(65+(@i/676000)%26),'-',right(1e3+@i%1000,3),'-',CHAR(65+(@i/26000)%26),CHAR(65+(@i/1000)%26))

```
> 2 votes

# Answer
# Julia 1.0, 86 bytes

```
i->(join('A'.+digits(i÷1000,base=26,pad=4))string(i%1000,pad=3)*'-')[[4;3;8;5:8;2;1]]

```

Try it online!
> 2 votes

# Answer
# Python 3, 89 bytes

```
lambda n:h(n//676)+f"-{n%1000:03}-"+h(n)
h=lambda x:'%c%c'%(x//26000%26+65,x//1000%26+65)

```

Try it online!

*-1 byte thanks to mypetlion*
> 1 votes

# Answer
# Python 2, 88 bytes

```
lambda n:g(n/676000)+'-%03d-'%(n%1000)+g(n/1000)
g=lambda n:chr(65+n/26%26)+chr(65+n%26)

```

Try it online!
> 1 votes

# Answer
# C (gcc), ~~136~~ ~~106~~ 105 bytes

```
#define P(i)s[i]=65+x%26;x/=26;
z;s[]=L"  -%03d-  ";f(x){z=x%1000;x/=1e3;P(9)P(8)P(1)P(0)wprintf(s,z);}

```

Try it online!

-7 bytes from celingcat's solution, with additional -23 inspired by it

-1 byte from ceilingcat's solution by changing the `char[]` to a `wchar_t[]` implicitly cast to `int[]`

Uses 0-based indexing.

Explanation/Ungolfed:

```
int s[] = L"  -%03d-  "; // Pre-made wide-string with dashes and ending null byte
                         // and wprintf directive for digits
int z;                   // Temporary variable to store the digit part
void f(int x) {
    z = x % 1000;        // The digits represent x % 1000
    x /= 1000;
    s[9] = 'A' + x % 26; // Place least significant letter
    x /= 26;             // Divide off least significant letter
    s[8] = 'A' + x % 26; // Place second letter
    x /= 26;             // Divide off second letter
    s[1] = 'A' + x % 26; // Place third letter
    x /= 26;             // Divide off third letter
    s[0] = 'A' + x;      // Place fourth letter (Don't need to % 26 because x < 26 now)
    wprintf(s, z); // Print finished string (with x%1000 replacing %03d)
}

```
> 1 votes

# Answer
# Red, ~~130~~ 127 bytes

```
func[n][g: func[a b c][t: copy""loop a[insert t b +(n % c)n: n / c]t]a: g 3 #"0"10
s: g 4 #"A"26 rejoin[s/1 s/2"-"a"-"s/3 s/4]]

```

Try it online!
> 1 votes

# Answer
# MATLAB, 113 bytes

```
c=@(x,p)char(mod(idivide(x,1000*26^p),26)+65);
s=@(n)[c(n,3),c(n,2),num2str(mod(n,1000),'-%03d-'),c(n,1),c(n,0)]

```

---

Explanations:

The first line define a function which will produce a char (from `A` to `Z`), function of 2 inputs. The index number `x` to convert into a plate number, and an integer `p` which will be used as an exponent for 26 (i.e. `26^p`). This second input allow to adjust the calculations for the first alphanumeric plate digit (`p=3`) down to the last one (`p=0`).

For example, for the second digit, cycled every 1000\*26\*26 iterations, the operation: `mod(idivide(x,1000*26^2),26)` return an index between 0 and 25, which is then converted to an ASCII `char` by adding 65 (because the index are `0` based)

The second line simply concatenate characters together. Each alphanumeric character is calculated with the use of the function `c(x,p)`, the numeric character are simply calculated with a `modulo` operation and converted to string.

Each component of the string composing the plate number is as follow:

```
digit #     |    how often is it cycled             |  code
----------------------------------------------------------------
digit 1     | cycle every 1000*26*26*26=1000*26^3   | c(n,3)
digit 2     | cycle every 1000*26*26   =1000*26^2   | c(n,2)
digit 3,4,5 | cycle every iteration                 | num2str(mod(n,1000),'-%03d-')
digit 6     | cycle every 1000*26      =1000*26^1   | c(n,1)
digit 7     | cycle every 1000         =1000*26^0   | c(n,0)

```

---

Since I can't let you try MATLAB online (*edit:* actually you can try it online ), I'll let MATLAB users the possibility to verify the test cases:

```
% chose some test cases
n = uint32([0;1;999;1000;675999;676000;456975999]) ;

% work out their plate numbers
plates = s(n) ;

% display results
fprintf('\n%10s | Plate # \n','Index')
for k=1:numel(n)
    fprintf('%10d : %s\n',n(k),plates(k,:))
end

```

outputs:

```
     Index | Plate #
         0 : AA-000-AA
         1 : AA-001-AA
       999 : AA-999-AA
      1000 : AA-000-AB
    675999 : AA-999-ZZ
    676000 : AB-000-AA
 456975999 : ZZ-999-ZZ

```

---

**Variant:** Note that the option to let `sprintf` or `fprintf` take care of the number to character conversion is possible. It allow to simplify the function `c`, but overall result in a few more bytes in this implementation (119 bytes):

```
c=@(x,p)mod(idivide(x,1000*26^p),26)+65 ;
s=@(n)sprintf('%c%c-%03d-%c%c\n',[c(n,3),c(n,2),mod(n,1000),c(n,1),c(n,0)]')

```
> 1 votes

# Answer
# Kotlin, 93 bytes

```
{i:Int->val c={v:Int->'A'+i/v/1000%26}
""+c(17576)+c(676)+"-%03d-".format(i%1000)+c(26)+c(1)}

```

Try it online!
> 0 votes

# Answer
# Python 3, 161 bytes

```
i,t,u,v,a,c,f=int(input()),1000,676,26,ord('A'),chr,lambda x:c(a+x//v)+c(a+x%v)
m,n=i%t,i//t
e,o=n%u,n//u
print('-'.join([f(o),(3-len(str(m)))*'0'+str(m),f(e)]))

```

Try it online!
> 0 votes

---
Tags: code-golf, string, number, base-conversion
---


# Question
Title: Farkle Fest 2k19: An AI dice game tournament
# Farkle Fest 2k19

In this challenge, we will be playing the semi-popular dice game Farkle.

Farkle is a dice game that has players selecting to save dice or risk rerolling the die for more points to add to their total. Players should use probability, game-state considerations and opponent tendency to make their decisions.

## How to play

Rules lifted from this PDF, which includes scoring. There are some differences that you should note after

> Each player takes turns rolling the dice. When it's your turn, you roll all six dice at the same time. Points are earned every time you roll a 1 or 5, three of a kind, three pairs, a six-dice straight (1,2,3,4,5,6), or two triplets.
>
> If none of your dice earned points, that's a Farkle! Since you earned no points, you pass the dice to the next player.
>
> If you rolled at least one scoring die, you can bank your points and pass the dice to the next player, or risk the points you just earned during this round by putting some or all of the winning die (dice) aside and rolling the remaining dice. The remaining dice may earn you additional points, but if you Farkle, you lose everything you earned during the round.
>
> If all of your dice contribute to the score you re-roll the dice and add to the points already rolled, but a farkle will lose all the points, including rollover. This is called a "hot-streak"
>
> Scoring is based only on the dice in each roll. You can earn points by combining dice from different rolls. You can continue rolling the dice until you either Pass or Farkle. Then the next player rolls the six dice until they Pass or Farkle. Play continues until it is your turn again.
>
> The final round starts as soon as any player reaches 20,000 or more points.
>
> Scoring:
>
> ```
>     five = 50
>     one = 100
>     triple 1 = 1000
>     triple 2 = 200
>     triple 3 = 300
>     triple 4 = 400
>     triple 5 = 500
>     triple 6 = 600
>     one thru six = 1500
>     three pairs = 1500
>     two triplets = 2500
>     four of a kind = 1000
>     five of a kind = 2000
>     six of a kind = 3000
>     farkle = 0
>     three farkles in a row = -1000
>
> ```

Notes:

* There are varying scoring tables. Use the one linked and rewritten above
* Most online versions say something like "You cannot earn points by combining dice from different rolls". This is ***not*** how I play. If you roll triple sixes and reroll and end up with another six you now have quad sixes.
* The ending score has been increased from 10,000 to 20,000. This increases the decision points and decreases randomness.
* Some variants have a "threshold to start getting points" (often around 500). This would prevent you from keeping a roll of less than 500 if your score was 0 (or negative). This rule is ***not*** in effect.

## Challenge

In this challenge, you will write a Python 3 program to play a three player, winner takes all glory game of Farkle

Your program will receive the state of the game, which contains:

> ```
>     index (where you sit at the table)
>     end_score (score required to win (20,000))
>     game_scores (all the players current score)
>     state_variable (space for you to put whatever you want)
>
>     #round values, these change during the round
>     round_score (score of the current set of dice)
>     round_rollover (score from previous "hot streaks")
>     round_dice (current dice)
>     round_set_aside (dice you set aside before rolling)
>     round_used_in_score (lets you know which dice are adding to your score)
>
> ```

---

Players should return an array showing which dice they want to set aside. This should be wrapped in a set\_dice\_aside(self) method

For instance, here's a player that will save dice that add to their score until the score they would get is 500 or greater

```
class GoForFiveHundred(Bot):
    def set_dice_aside(self):
        while (self.round_score + self.round_rollover) < 500:
            return self.round_used_in_score
        return [True, True, True, True, True, True]

```

## Gameplay

The tournament runner can be found here: Farkle\_Fest\_2K19. Run `main.py` to run a tournament. I'll keep it updated with new submissions. Example programs can be found in `farkle_bots.py`. Lots of code was lifted from maxb, many thanks for that framework and code.

A tournament consists of 5000 games per 10 players (rounded up, so 14 players means 10,000 games). Each game will be three random players selected from the pool of players to fill the three positions. Players will not be able to be in the game twice.

## Scoring

The winner of each game is the player with the most points at the end of the game. In the case of a tie at the end of a game all players with the maximum money amount are awarded a point. The player with the most points at the end of the tournament wins. I will post scores as I run the games.

The players submitted will be added to the pool. I added three dumb bots to start.

## Caveats

Do not modify the inputs. Do not attempt to affect the execution of any other program, except via cooperating or defecting. Do not make a sacrificial submission that attempts to recognize another submission and benefit that opponent at its own expense. Standard loopholes are banned.

Limit the time taken by your bot to be ~1s per turn.

Submissions may not duplicate earlier submissions.

If you have any questions, feel free to ask.

## Winning

The competition will stay open indefinitely, as new submissions are posted. However, I will declare a winner (accept an answer) based on the results two month after this question was posted (November 2nd).

Simulation of 5000 games between 5 bots completed in 675.7 seconds Each game lasted for an average of 15.987000 rounds 8 games were tied between two or more bots 0 games ran until the round limit, highest round was 48

```
+----------------+----+--------+--------+------+------+-------+
|Bot             |Win%|    Wins|  Played|   Max|   Avg|Avg win|
+----------------+----+--------+--------+------+------+-------+
|WaitBot         |95.6|    2894|    3028| 30500| 21988|  22365|
|BruteForceOdds  |38.7|    1148|    2967| 25150| 15157|  20636|
|GoForFiveHundred|19.0|     566|    2981| 24750| 12996|  20757|
|GoForTwoGrand   |13.0|     390|    2997| 25450| 10879|  21352|
|SetAsideAll     | 0.2|       6|    3027| 25200|  7044|  21325|
+----------------+----+--------+--------+------+------+-------+

+----------------+-------+-----+
|Bot             |   Time|Time%|
+----------------+-------+-----+
|BruteForceOdds  |2912.70| 97.0|
|WaitBot         |  58.12|  1.9|
|GoForTwoGrand   |  13.85|  0.5|
|GoForFiveHundred|  10.62|  0.4|
|SetAsideAll     |   7.84|  0.3|
+----------------+-------+-----+

```

And the results without WaitBot, which I'm still morally undecided on:

```
+----------------+----+--------+--------+------+------+-------+
|Bot             |Win%|    Wins|  Played|   Max|   Avg|Avg win|
+----------------+----+--------+--------+------+------+-------+
|BruteForceOdds  |72.0|    2698|    3748| 26600| 19522|  20675|
|GoForFiveHundred|37.2|    1378|    3706| 25350| 17340|  20773|
|GoForTwoGrand   |24.3|     927|    3813| 26400| 14143|  21326|
|SetAsideAll     | 0.1|       5|    3733| 21200|  9338|  20620|
+----------------+----+--------+--------+------+------+-------+
+----------------+-------+-----+
|Bot             |   Time|Time%|
+----------------+-------+-----+
|BruteForceOdds  |4792.26| 98.9|
|GoForTwoGrand   |  24.53|  0.5|
|GoForFiveHundred|  18.06|  0.4|
|SetAsideAll     |  13.01|  0.3|
+----------------+-------+-----+

```

# Answer
> 2 votes
# BruteForceOdds

Here's that brute force bot:

```
from main import Controller
from farkle_bots import Bot

scoreDevice = Controller(1, 1, [], 0)

class BruteForceOdds(Bot):
    def set_dice_aside(self):
        stop_score = self.round_score + self.round_rollover
        if self.game_scores[self.index] + stop_score > max(self.game_scores + [self.end_score]):
            # Take the win
            return [True, True, True, True, True, True]

        using = self.round_used_in_score[:]
        if self.round_dice.count(5) < 3:
            for i in range(len(using)):
                if self.round_dice[i] == 5 and not self.round_set_aside[i] and using.count(True) > self.round_set_aside.count(True)+1:
                    using[i] = False
        if self.round_dice.count(1) < 3:
            for i in range(len(using)):
                if self.round_dice[i] == 1 and not self.round_set_aside[i] and using.count(True) > self.round_set_aside.count(True)+1:
                    using[i] = False
        if using.count(True) < 3 and self.round_rollover == 0:
            # Stopping here is basically never a good idea
            return using

        if bruteScore(self.round_dice, using, self.round_rollover) > stop_score:
            return using
        return [True, True, True, True, True, True]

def bruteScore(round_dice, set_aside, base_score):
    base_dice = []
    for i in range(len(round_dice)):
        if(set_aside[i]):
            base_dice.append(round_dice[i])
    totalCount = 0
    totalScore = 0
    for new_dice in allPossibleRolls(len(round_dice) - len(base_dice)):
        dice = base_dice + new_dice
        keep = [True]*len(base_dice)+[False]*len(new_dice)
        farkle, round_score, round_rollover, used_in_score = scoreDevice.score(dice, keep, base_score)
        totalCount += 1
        if not farkle:
            totalScore += round_score + round_rollover
    return totalScore / totalCount

def allPossibleRolls(length):
    if length == 0:
        yield []
        return
    for i in range(1,7):
        for l in allPossibleRolls(length-1):
            yield [i]+l

```

It only fares slightly better than the example program GoForFiveHundred.

EDIT: Made it a bit smarter. Now it does noticeably better than any of the example bots.

# Answer
> 1 votes
# WaitBot

```
class WaitBot(Bot):
	def set_dice_aside(self):
		return [self.round_rollover+self.round_score > 5000]*6

```

Try it online!

This basically takes no dice until the total round score is greater than 5000. Really, it's betting on getting hot streaks before farkles.

This wins about 97% of the time when put up against the default three bots.

Edit: Erm, this may not be valid, since you need to `putting some or all of the winning die (dice) aside`. I'm waiting on confirmation from the asker on this, since the controller allows it.

---
Tags: king-of-the-hill, python, board-game
---


title: From Plate to State

text:
# Question
Title: From Plate to State
This is essentially the inverse of Generate a US License Plate

**Challenge:** Given a string that matches one of the below license plate formats, output all possible states that match that formatting. In the below table `0` stands for a single digit `0` through `9` inclusive, and `A` stands for a single letter `A` through `Z` inclusive. For the purposes of this challenge, we're ignoring states with complex format rules (like Delaware, which has variable number of digits), and ignoring removal of look-alike letters (e.g., `I` and `1`).

```
AAA 000: AK, IA, MS, MP, VT
0000: AS
AAA0000: AZ, GA, WA
000 AAA: AR, KS, KY, LA, ND, OR
0AAA000: CA
AA-00000: CT
AA-0000: DC
AAA A00: FL
AA 00000: IL
000A,000AA,000AAA,AAA000: IN
0AA0000: MD
AAA 0000,0AA A00,AAA 000: MI
000-AAA: MN
00A-000: NV
000 0000: NH
A00-AAA: NJ
000-AAA,AAA-000: NM
AAA-0000: NY, NC, PA, TX, VA, WI
AAA 0000: OH
000AAA: OK
AAA-000: PR
000-000: RI
AAA 000,000 0AA: SC
A00-00A: TN
A00 0AA: UT

```

Examples:

```
B32 9AG
[UT]

1YUC037
[CA]

285 LOR
[AR, KS, KY, LA, ND, OR] (in any order)

285-LOR
[MN, NM] (in any order)

285LOR
[IN, OK] (in any order)

```

**Rules and Clarifications**

* The input string is guaranteed non-empty, and guaranteed to be of one of the above formats
* Behavior if given a format other than the above is undefined
* Input and output can be given by any convenient method
* You can print the result to STDOUT or return it as a function result
* Either a full program or a function are acceptable
* Standard loopholes are forbidden
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins

# Answer
> 15 votes
# JavaScript (ES6),  ~~203 202 201~~  200 bytes

*Saved 1 byte thanks to @NahuelFouilleul*

```
s=>'xMiAZGAWaMIOhNvInxMNNmARKSKYLANDOrNMPrAKIAMIMSMPSCVtAsMdxScRiNhUtDcCtxFlxNYNCPATXVAWiInIlINOkNjCaTn'.match(/[A-Z]*./g)[s.replace(/./g,c=>c<'!'?0:1/c?9:6-~(c+1))*3%47%30].toUpperCase().match(/../g)

```

Try it online!

## How?

### Input conversion

We turn the input string into an integer \\$n\\$ by applying the following substitutions:

* spaces are replaced with \\$0\\$
* digits are replaced with \\$9\\$
* letters are replaced with \\$7\\$
* hyphens are replaced with \\$6\\$

As JS code:

```
c < '!' ?        // if c is a space:
  0              //   replace it with 0
:                // else:
  1 / c ?        //   if c is a digit:
    9            //     replace it with 9
  :              //   else:
    6 - ~(c + 1) //     if c is a hyphen, this gives:
                 //       6 - ~('-1') --> 6 - 0 --> 6
                 //     if c is a letter (e.g. 'A'), this gives:
                 //       6 - ~('A1') --> 6 - ~NaN --> 6 - (-1) --> 7

```

### Hash function

We then apply the following hash function:

$$f(n) = ((3\times n) \bmod 47) \bmod 30$$

This gives a unique ID in \\$\[1..29\]\\$. There's actually a collision between `000AA` and `AAA000` which both result in \\$24\\$, but that's perfectly fine as these plate formats are used in Indiana exclusively.

```
 format     | n        | * 3       | mod 47 | mod 30 | states
------------+----------+-----------+--------+--------+----------------------
  'AAA 000' |  7770999 |  23312997 |   10   |   10   | AK,IA,MI,MS,MP,SC,VT
     '0000' |     9999 |     29997 |   11   |   11   | AS
  'AAA0000' |  7779999 |  23339997 |   32   |    2   | AZ,GA,WA
  '000 AAA' |  9990777 |  29972331 |    8   |    8   | AR,KS,KY,LA,ND,OR
  '0AAA000' |  9777999 |  29333997 |   28   |   28   | CA
 'AA-00000' | 77699999 | 233099997 |   19   |   19   | CT
  'AA-0000' |  7769999 |  23309997 |   18   |   18   | DC
  'AAA A00' |  7770799 |  23312397 |   21   |   21   | FL
 'AA 00000' | 77099999 | 231299997 |   25   |   25   | IL
     '000A' |     9997 |     29991 |    5   |    5   | IN
    '000AA' |    99977 |    299931 |   24   |   24   | IN
   '000AAA' |   999777 |   2999331 |   26   |   26   | IN,OK
   'AAA000' |   777999 |   2333997 |   24   |   24   | IN
  '0AA0000' |  9779999 |  29339997 |   12   |   12   | MD
 'AAA 0000' | 77709999 | 233129997 |   33   |    3   | MI,OH
  '0AA A00' |  9770799 |  29312397 |    1   |    1   | MI
  '000-AAA' |  9996777 |  29990331 |    7   |    7   | MN,NM
  '00A-000' |  9976999 |  29930997 |   34   |    4   | NV
 '000 0000' | 99909999 | 299729997 |   46   |   16   | NH
  'A00-AAA' |  7996777 |  23990331 |   27   |   27   | NJ
  'AAA-000' |  7776999 |  23330997 |    9   |    9   | NM,PR
 'AAA-0000' | 77769999 | 233309997 |   23   |   23   | NY,NC,PA,TX,VA,WI
  '000-000' |  9996999 |  29990997 |   15   |   15   | RI
  '000 0AA' |  9990977 |  29972931 |   44   |   14   | SC
  'A00-00A' |  7996997 |  23990991 |   29   |   29   | TN
  'A00 0AA' |  7990977 |  23972931 |   17   |   17   | UT

```

### State encoding

All state patterns are joined together into a single string, with each pattern ending with a lower case letter. Empty slots are filled with an arbitrary `x`.

```
[ [], [ 'MI' ], [ 'AZ', 'GA', 'WA' ], [ 'MI', 'OH' ], ... ] --> 'xMiAZGAWaMIOh...'

```

We split them back into an array of strings with `match(/[A-Z]*./g)` and pick the correct one according to \\$f(n)\\$.

Finally, the pattern itself is converted to full upper case and split into groups of 2 characters.

# Answer
> 2 votes
# T-SQL, 475 bytes

```
SELECT STUFF(value,1,8,'')
FROM STRING_SPLIT('000 0000NH|000 055 SC|000 555 AR,KS,KY,LA,ND,OR|0000    AS|000-000 RI|0005    IN|00055   IN|000555  IN,OK|000-555 MN,NM|005-000 NV|055 500 MI|0550000 MD|0555000 CA|500 055 UT|500-005 TN|500-555 NJ|55 00000IL|55-0000 DC|55-00000CT|555 000 AK,IA,MI,MS,MP,SC,VT|555 0000MI,OH|555 500 FL|555000  IN|555-000 NM,PR|5550000 AZ,GA,WA|555-0000NY,NC,PA,TX,VA,WI','|')
,i WHERE v LIKE TRIM(REPLACE(REPLACE(LEFT(value,8),5,'[A-Z]'),0,'[0-9]'))

```

Line breaks are for readability only.

Limited to SQL 2017 or higher by use of the `TRIM` function. SQL 2016 (required for `STRING_SPLIT`), is possibly by substituting `RTRIM` at the cost of 1 byte.

Input is taken via pre-existing table \\$i\\$ with varchar field \\$v\\$, per our IO rules

I'm basically doing a reverse `LIKE` match: I expand the pattern of each plate to a full wildcard pattern matching string like `'[A-Z][0-9][0-9] [0-9][A-Z][A-Z]'`, then compare to the input value, and return the matching states (which is combined into a single field).

Might be able to save some more space by GZIP'ing the lengthy string; I'll see if that helps...

# Answer
> 2 votes
# Charcoal, 177 bytes

```
§⪪”}∧▶⧴βμÞ∕×peＨ✂d‽n➙ＭR⁶↙↷◨5⁶;πＮM﹪θＷ:¡✂⧴O^(P↷kⅉχＲ⁺≔º↶∨§º⊞Ｂ⎚×p↔Ｌ\`²‖6'⁶⁹‴XüR⦃N4U⊙ＹＦ⁻ＺＭχLＳ⁸ＣX\hγ”;⌕⪪”{⊟“◨⦄»Ｕ>⌕⁻9“]±R▷Ｑ↔θü&$▷l⁹Ｚ⁼¡⁷×À›¶aA*βＺ³δ¡⟲²Y«№⌕TμN»πX·ＳΣ"εl⊙=3✂S?Ｋ”;⭆Ｓ⎇№αιA⎇Σι⁰ι

```

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

```
                 Ｓ              Input string
                ⭆               Map over characters and join
                  ⎇             If
                     ι          Current character
                   №α           Is an uppercase letter
                      A         Then literal string `A`
                       ⎇        Else if
                         ι      Current character
                        Σ       Is non-zero
                          ⁰     Then digit `0`
                           ι    Else original character
        ⌕                       Find index in
          ”...”                 Compressed string of plates
         ⪪     ;                Split on semicolons
§                               Index into
  ”...”                         Compressed string of states
 ⪪     ;                        Split on semicolons
                                Implicitly print

```

Try all test cases! Link is to verbose version of code. (Slightly different code needed to process multiple cases.)

Unsurprisingly a port of @Arnauld's solution is much shorter at only 121 bytes:

```
§⪪”}∧↨¦↑↧‴q⁰mπi3ＪE⪫³yＳ⪪c)？0≦·ê⊞Þ«ⅉ⁺&±<pAＲιaγ1A↑1L¶⟧/)Vº;Π∧,b✂≦¤ⅉαX⊕|″IνB[w∕¦Ｈ´Gγ§ν⟲^π!⪪¶ςbFü⊟»2”;﹪×³Ｉ⭆Ｓ⎇№αι⁷⎇⁼ι ⁰⎇⁼ι-⁶9⁴⁷

```

Try it online! Link is to verbose version of code. The second modulo by 30 is implicit in the indexing into the array.

# Answer
> 2 votes
# Perl 5 `(-p)`, 165 bytes

Port of @Arnauld's Javascript answer, also upvote him.

```
y/0-8/9/;y/- A-Z/607/;$_=('xMiAZGAWaMIOhNvInxMNNmARKSKYLANDOrNMPrAKIAMIMSMPSCVtAsMdxScRiNhUtDcCtxFlxNYNCPATXVAWiInIlINOkNjCaTn'=~/[A-Z]*./g)[$_*3%47%30];s/../\U$& /g

```

Try it online!

# Answer
> 0 votes
# Python 3, ~~382~~ 378 bytes

```
import re;f=lambda p,l='[A-Z]',r=re.sub,f=re.findall:f(l+'{2}',f(r(l,'1',r('[0-9]','0',p))+l+'+','0000AS0001IN00011IN000111INOK111000IN000 011SC000 111ARKSKYLANDOR000-000RI000-111MNNM001-000NV011 100MI0110000MD0111000CA100-001TN100-111NJ11-0000DC111 100FL111 000AKIAMIMSMPSCVT111-000NMPR1110000AZGAWA11 00000IL11-00000CT111 0000MIOH111-0000NYNCPATXVAWI1100 011UT000 0000NH')[0])

```

Try it online!

Replaces numbers with `0` and letters with `1`, then searches the string for the plate followed by a string of letters. Then it simply returns every non-overlapping pair of letters in that string.

Not the most byte efficient, but a good start (maybe).

I enjoy challenges based on information that can't just be generated.

# Answer
> 0 votes
# 05AB1E, 176 bytes

```
•1–ºʒÉQ÷¦PαN]lā?¨ìÎ₆™@ΔîÅλEŸʒ»ú<Å§a–½ã…ôkƒ¼½Ü%-ò∊aÍÙ•44374в4вε©gIgQi…'-Q'd'a„ðQ)VIεY®Nèè.V}Pë0].•=#îYn«ÈO4êʒIWj∊bÛˆ_ãZÑ"yŠótм‰иÔN–HδÖc°ìSJ9Ç\}ζÎäǝÑïÒ∞V.÷ζkÚ"¿Õнα£!ÉªB…žä•#sÏ`2ô

```

Try it online!

```
•1–ºʒÉQ÷¦PαN]lā?¨ìÎ₆™@ΔîÅλEŸʒ»ú<Å§a–½ã…ôkƒ¼½Ü%-ò∊aÍÙ•44374в4в
                        push all patterns as base 4 integers (0="-", 1=number, 2=letter, 3=" ")

ε                       for each pattern
  ©                       copy it for later use inside another for for-loop
  gIgQi                   if it has the same length, as input
    …'-Q'd'a„ðQ)V           store ["'-Q", "d", "a", "ðQ"] in Y (05AB1E codes for "equals '-', is positive, is letter and equals ' ')
    Iε                      for each letter of input
      Y®Nèè                   get the 05AB1E code corresponding to the current index of the pattern
      .V                      run it
    }
    P                       check if all positions of that pattern were true
  ë                       else
    0                       push false
]

.•=#îYn«ÈO4êʒIWj∊bÛˆ_ãZÑ"yŠótм‰иÔN–HδÖc°ìSJ9Ç\}ζÎäǝÑïÒ∞V.÷ζkÚ"¿Õнα£!ÉªB…žä•#
                        push list of states matching the pattern

sÏ                      get the entry of that list, that is true in the other list
`2ô                        split into groups of 2 letters and print

```

---
Tags: code-golf, string, kolmogorov-complexity
---