title: Is my number a de Polignac number?

text:
# Question
Title: Is my number a de Polignac number?
A number is a de Polignac number if and only if it is **odd** and *cannot* be represented in the form **p + 2n** where **n** is a non-negative integer and **p** is a prime integer.

# Task

Write some code that takes a positive integer and determines if it is a de Polignac number. You may output two distinct values one for true and one for false. You should aim to minimize your byte count.

# Test Cases

For positive cases here's the OEIS

```
1, 127, 149, 251, 331, 337, 373, 509, 599, 701, 757, 809, 877, 905, 907, 959, 977, 997, 1019, 1087, 1199, 1207, 1211, 1243, 1259, 1271, 1477, 1529, 1541, 1549, 1589, 1597, 1619, 1649, 1657, 1719, 1759, 1777, 1783, 1807, 1829, 1859, 1867, 1927, 1969, 1973, ...

```

Here are some negative cases:

```
22, 57

```

# Answer
# Japt, ~~9~~ ~~14~~ 13 bytes

```
o!²mnU dj |Uv

```

Test it online! or Find all de Polignac integers under 1000.

Outputs `1` for falsy inputs and `0` for truthy.

### Explanation

```
 o!²  mnU dj |Uv
Uo!p2 mnU dj |Uv  : Ungolfed
                  : Implicit: U = input integer (e.g. 9)
Uo                : Create the range [0..U), and map each item X to
  !p2             :   2 ** X.               [1, 2, 4, 8, 16, 32, 64, 128, 256]
      m           : Map each of these powers of 2 by
       nU         :   subtracting from U.   [8, 7, 5, 1, -7, -23, -57, -119, -247]
          d       : Return whether any item in the result is
           j      :   prime.                (5 and 7 are, so `true`)
             |    : Take the bitwise OR of this and
              Uv  :   U is divisble by (missing argument = 2).
                  : This gives 1 if U cannot be represented as p + 2^n or if U is even.
                  : Implicit: output result of last expression

```
> 11 votes

# Answer
# JavaScript (ES6),  ~~56 54~~  53 bytes

Returns \\$0\\$ or \\$1\\$.

```
f=(n,p=1,x=y=n-p)=>n>p?y%--x?f(n,p,x):x!=1&f(n,p*2):n

```

Try it online!

### How?

We start with \\$p = 1\\$. We test whether \\$y = n - p\\$ is composite and yield a boolean accordingly. The next test is performed with \\$p \times 2\\$.

As soon as \\$p\\$ is greater than \\$n\\$, we stop the recursion and return \\$n\\$.

The results of all iterations are AND'd together, coercing the boolean values to either \\$0\\$ or \\$1\\$.

Provided that all intermediate results were truthy, we end up with a bitwise test such as:

`1 & 1 & 1 & n`

This gives \\$1\\$ if and only if \\$n\\$ is odd, which is the last condition required to validate the input as a de Polignac number.
> 8 votes

# Answer
# Jelly, ~~11~~ 10 bytes

*Saved 1 byte thanks to @Dennis*

```
Ḷ2*³_ÆPS<Ḃ

```

Try it online!

### How it works

```
Ḷ2*³_ÆPS<Ḃ   Main link. Argument: n (integer)
Ḷ            Lowered range; yield [0, 1, 2, ..., n-1].
 2*          Reversed exponentiation with 2; yield [1, 2, 4, ..., 2**(n-1)].
   ³_        Reversed subtraction with the input; yield [n-1, n-2, n-4, ..., n-2**(n-1)].
     ÆP      Replace each item with 1 if it is prime, 0 otherwise.
       S     Sum; yield a positive integer if any item was prime, 0 otherwise.
         Ḃ   Yield n % 2.
        <    Yield 1 if the sum is less than n % 2, 0 otherwise.
             This yields 1 if and only if the sum is 0 and n is odd.

```
> 8 votes

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

-1 byte thanks to Emigna

```
Ýo-pZ¹È~

```

Outputs `0` for truthy inputs and `1` for falsy inputs.

Try it online!
> 7 votes

# Answer
# Python 2, ~~60~~ ~~57~~ 56 bytes

```
f=lambda n,k=1,p=-1:k/n or(n-k&n-k-p%k>0)&n&f(n,k+1,p*k)

```

Try it online!
> 7 votes

# Answer
# Jelly, 10 bytes

*An alternative 10-byte Jelly submission to the one already posted.*

```
_ÆRBS€’×ḂẠ

```

A monadic link returning **1** for de Polignac numbers and **0** otherwise.

**Try it online!** or see those under 1000.

### How?

```
_ÆRBS€’×ḂẠ - Link: number, n  e.g.  1    3      5                  6                   127
 ÆR        - prime range            []   [2]    [2,3,5]            [2,3,5]             [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127]
_          - subtract from n        []   [1]    [3,2,0]            [4,3,1]             [125,124,122,120,116,114,110,108,104,98,96,90,86,84,80,74,68,66,60,56,54,48,44,38,30,26,24,20,18,14,0]
   B       - convert to binary      []   [[1]]  [[1,1],[1,0],[0]]  [[1,0,0],[1,1],[1]  [[1,1,1,1,1,0,1],[1,1,1,1,1,0,0],[1,1,1,1,0,1,0],[1,1,1,1,0,0,0],[1,1,1,0,1,0,0],[1,1,1,0,0,1,0],[1,1,0,1,1,1,0],[1,1,0,1,1,0,0],[1,1,0,1,0,0,0],[1,1,0,0,0,1,0],[1,1,0,0,0,0,0],[1,0,1,1,0,1,0],[1,0,1,0,1,1,0],[1,0,1,0,1,0,0],[1,0,1,0,0,0,0],[1,0,0,1,0,1,0],[1,0,0,0,1,0,0],[1,0,0,0,0,1,0],[1,1,1,1,0,0],[1,1,1,0,0,0],[1,1,0,1,1,0],[1,1,0,0,0,0],[1,0,1,1,0,0],[1,0,0,1,1,0],[1,1,1,1,0],[1,1,0,1,0],[1,1,0,0,0],[1,0,1,0,0],[1,0,0,1,0],[1,1,1,0],0]
    S€     - sum €ach               []   [1]    [2,1,0]            [1,2,1]             [6,5,5,4,4,4,5,4,3,3,2,4,4,3,2,3,2,2,4,3,4,2,3,3,4,3,2,2,2,3,0]
      ’    - decrement              []   [0]    [1,0,-1]           [0,1,0]             [5,4,4,3,3,3,4,3,2,2,1,3,3,2,1,2,1,1,3,2,3,1,2,2,3,2,1,1,1,2,-1]
        Ḃ  - n mod 2                1    1      1                  0                   1
       ×   - multiply               []   [0]    [1,0,-1]           [0,0,0]             [5,4,4,3,3,3,4,3,2,2,1,3,3,2,1,2,1,1,3,2,3,1,2,2,3,2,1,1,1,2,-1]
         Ạ - all truthy?            1    0      0                  0                   1

```
> 7 votes

# Answer
# Python 2, 99 bytes

```
lambda n:n&1-any(n-2**k>1and all((n-2**k)%j for j in range(2,n-2**k))for k in range(len(bin(n))-2))

```

Try it online!

-4 bytes thanks to Leaky Nun

-2 bytes thanks to Wondercricket

+8 bytes to fix a mistake

-1 byte thanks to Mr. Xcoder

-3 bytes thanks to Einkorn Enchanter

+12 bytes to fix a mistake
> 6 votes

# Answer
# Regex (ECMAScript), 97 bytes

This problem posed an interesting case for working around the problem of lacking non-atomic lookahead. And it's the only time so far that I've had a good reason to put both versions of the power of 2 test, `((x+)(?=\2$))*x$` and `(?!(x(xx)+)\1*$)`, in the same regex, and the only time so far I've needed to protect the prime test against matching 1, as `(?!(xx+)\1+$)xx`, when used in a larger regex.

`^(?!(xx)*$|(x+)((?!(xx+)\4+$).*(?=\2$)((x+)(?=\6$))*x$|(?!(x(xx)+)\7*$).*(?=\2$)(?!(xx+)\9+$)xx))`

Try it online!

```
# For the purposes of these comments, the input number = N.
^
# Assert that N is not the sum of a prime number and a power of 2.
(?!
    (xx)*$                 # Assert that N is odd.
|
    # Since we must cycle through all values for a number X and a corresponding number
    # N-X, this cannot be in an atomic lookahead. The problem then becomes that it
    # consumes characters. Thus we must let X be the larger of the two and N-X be the
    # smaller, and do tests on X followed by tests on N-X. We can't just test X for
    # being prime and N-X for being a power of 2, nor vice versa, because either one
    # could be smaller or larger. Thus, we must test X for being either prime or a
    # power of 2, and if it matches as being one of those two, do the opposite test on
    # N-X.
    # Note that the prime test used below, of the form (?!(xx+)\2+$), has a false match
    # for 0 and 1 being prime. The 0 match is harmless for our purposes, because it
    # will only result in a match for N being a power of 2 itself, thus rejecting
    # powers of 2 as being de Polignac numbers, but since we already require that N is
    # odd, we're already rejecting powers of 2 implicitly. However, the 1 match would
    # break the robustness of this test. There can be de Polignac numbers of the form
    # 2^M+1, for example 262145 and 2097153. So we must discard the 1 match by changing
    # the prime test to "(?!(xx+)\2+$)xx". We only need to do this on the N-X test,
    # though, because as X is the larger number, it is already guaranteed not to be 1.
    (x+)           # \2 = N-X = Smaller number to test for being prime or a power of 2;
                   # tail = X = larger number to test for being prime or a power of 2.
    (
        (?!(xx+)\4+$)      # Test X for being prime.
        .*(?=\2$)          # tail = N-X
        ((x+)(?=\6$))*x$   # Test N-X for being a power of 2. Use the positive version
                           # since it's faster and doesn't have a false match of 0.
    |
        (?!(x(xx)+)\7*$)   # Test X for being a power of 2. Use the negative version
                           # because the testing of X has to be in a lookahead, and
                           # putting the positive version in a positive lookahead would
                           # be worse golf. It doesn't matter that this can have a false
                           # match of 0, because X is guaranteed never to be 0.
        .*(?=\2$)          # tail = N-X
        (?!(xx+)\9+$)xx    # Test N-X for being prime. We must prevent a false match of
                           # 1 for the reason described above.
    )
)

```

# Regex (ECMAScript + molecular lookahead), ~~53~~ 52 bytes

`^(?!(xx)*$|(?*xx+(((x+)(?=\4$))*x$))\2(?!(xx+)\5+$))`

```
# For the purposes of these comments, the input number = N.
^
# Assert that N is not the sum of a prime number and a power of 2.
(?!
    (xx)*$                   # Assert that N is odd.
|
    (?*
        xx+                  # Force N - \2 to be > 1, because the prime test used
                             # below has a false match of 1, which would otherwise
                             # give us false negatives on de Polignac numbers of the
                             # form 2^M+1, such as 262145 and 2097153.
        (((x+)(?=\4$))*x$)   # Cycle through subtracting all possible powers of 2 from
                             # tail, so we can then test {N - {power of 2}} for being
                             # prime.
                             # \2 = the power of 2
    )
    \2                       # tail = N - \2
    (?!(xx+)\5+$)            # Test tail for being prime. If it matches, this will fail
                             # the outside negative lookahead, showing that N is not a
                             # de Polignac number.
)

```

This version is not only much cleaner, but much faster, because instead of having to cycle through all possible ways that N is the sum of two numbers, it can just cycle through subtracting every power of 2 from N and test the difference for being prime.

The molecular lookahead can be easily converted to a variable-length lookbehind:

# Regex (.NET or ECMAScript 2018), ~~55~~ 54 bytes

`^(?!(xx)*$|xx+(((x+)(?=\4$))*x$)(?<=(?<!^\5+(x+x))\2))`

Try it online! (.NET)
Try it online! (ECMAScript 2018)

```
# For the purposes of these comments, the input number = N.
^
# Assert that N is not the sum of a prime number and a power of 2.
(?!
    (xx)*$                 # Assert that N is odd.
|
    xx+                    # Force N - \2 to be > 1, because the prime test used
                           # below has a false match of 1, which would otherwise
                           # give us false negatives on de Polignac numbers of the
                           # form 2^M+1, such as 262145 and 2097153.
    (((x+)(?=\4$))*x$)     # Cycle through subtracting all possible powers of 2 from
                           # tail, so we can then test {N - {power of 2}} for being
                           # prime.
                           # \2 = the power of 2
    (?<=
        (?<!^\5+(x+x))     # Test tail for being prime. If it matches, this will fail
                           # the outside negative lookahead, showing that N is not a
                           # de Polignac number.
        \2                 # tail = N - \2
    )
)

```
> 6 votes

# Answer
# Mathematica, 41 bytes

```
OddQ@#&&!Or@@PrimeQ[#-2^Range[0,Log2@#]]&

```
> 4 votes

# Answer
# Pari/GP, 34 bytes

```
n->n%2*prod(i=0,n,!isprime(n-2^i))

```

Try it online!
> 4 votes

# Answer
# PHP, 75 bytes

prints 1 for truthy and 0 for falsy

```
for($t=1&$argn;0<$d=$n=$argn-2**$i++;$d-1?:$t&=0)for(;--$d&&$n%$d;);echo$t;

```

Try it online!

Try it online! Polignac Integers under 10000
> 4 votes

# Answer
# Brachylog, ~~15~~ 13 bytes

```
/₂ℕ|>ṗ;?-₍ḃ+1

```

Try it online!

Output de Polignac numbers upto 1000.

Returns `false.` for de Polignac numbers and `true.` otherwise.

Based on @LeakyNun's deleted answer, with a few bugfixes (posted with their permission).

*(-2 bytes by using @Jonathan Allan's method to check if the number is a power of two.)*

The given number is not a de Polignac number if:

```
/₂ℕ              It's an even number
   |>ṗ           Or there exists a prime number less than the input
      ;?-₍       which when subtracted from the input
          ḃ      gives a result that has a binary form
           +     such that the sum of the bits
            1    is 1

```
> 4 votes

# Answer
# Jelly, 13 bytes

```
ÆRạl2=Ḟ$o/o‘Ḃ

```

Try it online!

```
ÆRạl2=Ḟ$o/     Main link; argument is z
ÆR             Generate all primes in the range [2..z]
  ạ            Absolute difference with z for each prime
   l2          Logarithm Base 2
     =Ḟ$       For each one, check if it's equal to its floored value (i.e. if it is an integer)
        o/     Reduce by Logical OR to check if any prime plus a power of two equals the z
          o‘Ḃ  Or it's not an odd number. If it's not an odd number, then automatically return 1 (false).

```

Outputs `1` for false and `0` for true.
> 3 votes

# Answer
# Perl 6, 55 bytes

```
{so$_%2&&$_∉((1,2,4...*>$_) [X+] grep &is-prime,^$_)}

```

Try it online!

* `(1, 2, 4 ... * > $_)` is a sequence of the powers of two until the input argument (Perl infers the geometric series from the provided elements).
* `grep &is-prime, ^$_` is the list of prime numbers up to the input argument.
* `[X+]` evaluates the sum of all elements of the cross product of the two series.

I could have done without the `so` for two bytes less, but then it returns two distinct falsy values (`0` and `False`).
> 2 votes

# Answer
# Axiom, 86 bytes

```
f(n:PI):Boolean==(~odd?(n)=>false;d:=1;repeat(n<=d or prime?(n-d)=>break;d:=d*2);n<=d)

```

test and results

```
(21) -> for i in 1..600 repeat if f(i) then output i
   1
   127
   149
   251
   331
   337
   373
   509
   599

```
> 2 votes

# Answer
# Haskell, ~~104~~ 102 bytes

```
p x=[x]==[i|i<-[2..x],x`mod`i<1]
h k|even k=1>2|2>1=notElem k$((+)<$>(2^)<$>[0..k])<*>filter(p)[1..k]

```

**Explanation**

* p is a function that finds prime numbers (very inefficient!)
* Creating a list of `(+)` applied to 2^ partial function which is applied to a list \[0..input\]
* Applying the above to a list filtered 1 to input for primes
* Resulting cartesian product of every possible value is searched to ensure input does not exist in cartesian product
* Guarded to ensure that an even input is automatically false.

UPDATE: Shout out to Einkorn Enchanter for golfing two bytes!
> 2 votes

# Answer
# Common Lisp, 134 bytes

```
(lambda(x)(flet((p(x)(loop for i from 2 below x always(>(mod x i)0))))(or(evenp x)(do((j 1(* j 2))(m()(p(- x j))))((or(>= j x)m)m)))))

```

Return `NIL` when the argument is a Polignac number, `T` otherwise.

Try it online!

Ungolfed:

```
(lambda (n)
  (flet ((prime? (x)                 ; x is prime
           loop for i from 2 below x ; if for i in [2..n-1]
           always (> (mod x i) 0)))  ; is x is not divisible by i
    (or (evenp n)                    ; if n is even is not a Polignac number
        (do ((j 1( * j 2))           ; loop with j = 2^i, i = 0, 1,...
             (m () (prime? (- n j)))); m = n - 2^i is prime?
            ((or (>= j n)            ; terminate if 2^i ≥ n
                 m)                  ; or if n - 2^i is prime
             m)))))                  ; not a polignac if n - 2^i is prime

```
> 1 votes

# Answer
# APL (Dyalog Extended), 12 bytes

```
⍱2∘|⍲0⍭⊢-2*…

```

Try it online!

Anonymous prefix tacit function. Returns 1 for truthy, 0 for falsy.

Largely based on ETHProductions' Japt answer.

Thanks to @Adám for helping with golfing my original answer, and for making Dyalog Extended for that matter.

### How:

```
⍱2∘|⍲0⍭⊢-2*…   ⍝ Tacit prefix function; input will be called ⍵
           …    ⍝ Inclusive Range [0..⍵]
         2*     ⍝ 2 to the power of each number in the range
       ⊢-       ⍝ Subtract each from ⍵
     0⍭         ⍝ Non-primality check on each resulting number
    ⍲           ⍝ Logical NAND
 2∘|            ⍝ Mod 2
⍱               ⍝ Not any (bitwise OR reduction, then negated)

```
> 1 votes

# Answer
# Python 2, 98 bytes

```
lambda x:not(x%2<1or any((lambda x:x>1and all(x%j for j in range(2,x)))(x-2**i)for i in range(x)))

```

Try it online!
> 0 votes

# Answer
# Pyth, 14 bytes

```
&%Q2!smP-^2dQl

```

Try it!
> 0 votes

# Answer
# Julia 0.4, 31 bytes

```
n->n%2*!any(ispow2,n-primes(n))

```

Try it online!
> 0 votes

# Answer
# APL(NARS) 80 chars, 160 bytes

```
∇r←f w;n
r←¯1⋄→0×⍳(w≤0)∨w≥9E9⋄r←0⋄→0×⍳0=2∣w⋄n←r←1
→0×⍳w≤n⋄→3×⍳0πw-n⋄n×←2⋄→2
r←0
∇

```

The function 0π is the function that return its argument is prime or not. For me this function has not be recursive so it is a little more long... Test:

```
  {1=f ⍵:⍵⋄⍬}¨1..1000
1  127  149  251  331  337  373  509  599  701  757  809  877  905  907  959  977  997

```

for input \<=0 or input \>=9E9 it return ¯1 (error)

```
  f¨0 ¯1 ¯2 900000000001
¯1 ¯1 ¯1 ¯1

```
> 0 votes

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

```
x=>{var r=Enumerable.Range(2,x);return x%2>0&r.All(p=>r.Any(d=>d<p&p%d<1)|r.All(n=>x!=p+Math.Pow(2,n-2)));}

```

Try it online!

Not the most efficient code, but seems to work. My original solution filtered for primes before testing them in the formula and it performed much better. The current version is 11 bytes shorter.

```
// input x is an integer
x=>{
  // we need to generate several
  // ranges. since this is verbose,
  // generate 1 and keep a reference
  var r=Enumerable.Range(2,x);
  // this is the main condition
  return
     // input must be odd
     x%2>0&
     // generate all possible p's
     // over our range and ensure that
     // they satisfy the following
     r.All(p=>
       // either p is not prime
       r.Any(d=>d<p&p%d<1)
       |
       // or there is no n that satisfies
       // the formula: x=p+2^n
       r.All(n=>x!=p+Math.Pow(2,n-2))
     );
}

```
> 0 votes

---
Tags: code-golf, number, number-theory, decision-problem
---


title: Split as number, join as string, repeat

text:
# Question
Title: Split as number, join as string, repeat
Consider the process of:

1. Taking a non-negative integer N.
e.g. `27`.
2. Spliting it into integers `N - floor(N/2)` and `floor(N/2)` (a 'bigger' and 'smaller' half) and writing them in that order.
e.g.`27` becomes `14 13`.
3. Removing the space to join the integers into a new, much larger integer.
e.g. `14 13` becomes `1413`.
4. Repeating steps 2 and 3 some desired number of times.
e.g. `1413``707 706``707706``353853 353853``353853353853` → ...

This challenge is about doing exactly this, but not always in base 10.

# Challenge

Write a program that takes in three numbers, B, N, and S:

* B is an integer from 2 to 10 that is the base of N (binary to decimal).
* N is the non-negative integer to apply the splitting-rejoining process to. To make user input easier, it is given as a **string** in base B, not an integer.
* S is a non-negative integer that is the number of times to repeat the splitting-rejoining process.

The output of the program is the string representation of N in base B after S split-join procedures.

When S is `0`, no splits are done, so the output is always N.

When N is `0`, all splits have the form `0 0` and reduce to `0` again, so the output is always `0`.

# Examples

* `B = 10, N = 27, S = 1``1413`
* `B = 10, N = 27, S = 2``707706`
* `B = 9, N = 27, S = 1``1413`
* `B = 9, N = 27, S = 2``652651`
* `B = anything, N = anything, S = 0``N`
* `B = anything, N = 0, S = anything``0`

Table for all B with N = `1` for S = `0` to `7`:

```
B       S=0     S=1     S=2     S=3         S=4             S=5                 S=6                                 S=7
2       1       10      11      101         1110            111111              10000011111                         10000100001000001111
3       1       10      21      1110        202201          101101101100        1201201201212012012011              212100212102121002121212100212102121002120
4       1       10      22      1111        223222          111311111311        2232222232322322222322              11131111131311311111311113111113131131111131
5       1       10      32      1413        432431          213441213440        104220331443104220331442            2433241322130211014044424332413221302110140443
6       1       10      33      1514        535535          245550245545        122553122553122553122552            4125434125434125434125441254341254341254341254
7       1       10      43      2221        11111110        40404044040403      2020202202020220202022020201        10101011010101101010110101011010101101010110101011010100
8       1       10      44      2222        11111111        44444454444444      2222222622222222222226222222        11111113111111111111131111111111111311111111111113111111
9       1       10      54      2726        13581357        62851746285173      3142536758708231425367587081        15212633743485606571782880411521263374348560657178288040
10      1       10      55      2827        14141413        70707077070706      3535353853535335353538535353        17676769267676676767692676771767676926767667676769267676

```

Table for all B with random N for S = `0` to `3`:

```
B       S=0     S=1         S=2                 S=3
2       11011   11101101    11101111110110      11101111110111110111111011
3       2210    11021101    20102012010200      1001212100121210012121001211
4       1113    230223      112112112111        2302302302323023023022
5       101     2323        11341134            31430423143042
6       120     4040        20202020            1010101010101010
7       134     5252        24612461            1230456412304564
8       22      1111        445444              222622222622
9       4       22          1111                505505
10      92      4646        23232323            1161616211616161

```

# Details

* Take input via stdin or the command line. Output to stdout.
* Instead of a program, you may write a function that takes B, N, and S and prints the result normally or returns it (as a string).
* B, N, and S may be taken in any order.
* All inputs that produce outputs whose decimal values are below 232 should work.
* N is represented in the usual way. i.e. most significant digit first and no leading zeros except in zero itself which is written `0`. (Outputting `00` instead of `0` is invalid.)
* **The shortest code in bytes wins.**

Iff you enjoy my challenges, consider giving Block Building Bot Flocks! some love :)

# Answer
> 5 votes
# Pyth, ~~21~~ 19 bytes

```
vujksmjldQc2UiGQvwz

```

Takes input in the format `N\nB\nS`. Try it online: Demonstration or Test harness

### Explanation

```
                      implicit: z = 1st input (N)
                                Q = 2nd input evaluated (B)
 u              vwz   reduce z (evaluated 3rd input) times by:
             iGQ         convert string from base Q to base 10
            U            create a range [0, 1, ..., ^-1]
          c2             split into 2 lists (lengths are N-[N/2] and [N/2])
     m                   map each list d to:
       ld                   their length
      j  Q                  in base Q
    s                    join both lists
  jk                     join the numbers by ""
v                     convert string to int (getting rid of leading zeros)

```

# Answer
> 5 votes
# Pyth, 29 21 bytes

```
jku+j-JiGQK/J2QjKQvwz

```

Really straightforward implementation.

Takes input on stdin in the following format:

```
N
B
S

```

# Answer
> 5 votes
# Mathematica, 101 bytes

```
Nest[a~Function~(b=FromDigits)[Through@((c=IntegerString)@*Ceiling<>c@*Floor)[a/2],#],#2~b~#,#3]~c~#&

```

Uses some `Through` trickery to apply both the ceiling and floor functions. Just ignore the errors.

# Answer
> 5 votes
# CJam, 24 bytes

```
q~:B;{:~Bb_)\]2f/Bfbs}*i

```

Test it here. Takes input as `"N" S B`.

## Explanation

```
q~                       e# Read an eval input.
  :B;                    e# Store the base in B and discard it.
     {               }*  e# Repeat S times.
      :~                 e# Turn the string N into an array of digits.
        Bb               e# Interpret as base B.
          _)\            e# Duplicate and increment. Swap order.
             ]2f/        e# Wrap them in an array and (integer-)divide both by 2.
                 Bfb     e# Convert both to base B.
                    s    e# Flatten into a single string.
                       i e# Convert to an integer to fix the N = 0 case.

```

# Answer
> 3 votes
# JavaScript (*ES6*) 78 ~~79~~

Recursive function. Run snippet to test (Firefox only)

**Edit** 1 byte saved thx @DocMax

```
F=(b,n,s,S=x=>x.toString(b),m=parseInt(n,b))=>m*s?F(b,S(-~m>>1)+S(m>>1),s-1):n

// Ungolfed

U=(b,n,s)=>
{
  var S=x=>x.toString(b) // function to convert in base b
  var m=parseInt(n,b) // string in base b to integer
  if (m==0 || s==0)
    return n
  else
    return F(b,S((m+1)>>1) + S( m>>1 ),s-1)
}

// Test
test=[
  {B: 10, N: '0', S:3, K: '0' }, {B: 10, N: '27', S: 1, K: '1413' }, {B: 10, N: '27', S: 2, K: '707706' }, {B: 9, N: '27', S: 1, K: '1413' }, {B: 9, N: '27', S: 2, K: '652651' }
];

test2=[[2, '11011', '11101101', '11101111110110', '11101111110111110111111011'],[3, '2210', '11021101', '20102012010200', '1001212100121210012121001211'],[4, '1113', '230223', '112112112111', '2302302302323023023022'],[5, '101', '2323', '11341134', '31430423143042' ]  ,[6, '120', '4040', '20202020', '1010101010101010'],[7, '134', '5252', '24612461', '1230456412304564'],[8, '22', '1111', '445444', '222622222622'],[9, '4', '22', '1111', '505505'],[10, '92', '4646', '23232323', '1161616211616161' ]
]
test2.forEach(r=>test.push(
  {B:r[0],N:r[1],S:1,K:r[2]}, {B:r[0],N:r[1],S:2,K:r[3]}, {B:r[0],N:r[1],S:3,K:r[4]}
))

test.forEach(t => (
  r=F(t.B, t.N, t.S),
  B.innerHTML += '<tr><th>'+(r==t.K?'Ok':'Failed')
      +'</th><td>'+t.B +'</td><td>'+t.N
      +'</td><td>'+t.S +'</td><td>'+r +'</td><td>'+t.K +'</td></tr>'
))
```

```
th,td { font-size: 12px; padding: 4px; font-family: helvetica }
```

```
<table><thead><tr>
  <th>Test<th>B<th>N<th>S<th>Result<th>Check
  </tr></thead>
  <tbody id=B></tbody>
</table>
```

# Answer
> 1 votes
# ECMAScript 6, 90 bytes

```
var f=(B,N,S)=>((n,s)=>S?f(B,s(n+1>>1)+s(n>>1),S-1):s(n))(parseInt(N,B),x=>x.toString(B))

```

Defining a recursive function using a variable is not really good style, but it is the shortest code I could come up with in ECMAScript 6.

Getting the corner case `"00" => "0"` right wastes three bytes (`s(n)` instead of simply `N`).

To try it out, you can use Babel's REPL: copy/paste the code and print example invocation results like so: `console.log(f(9, "27", 2))`.

# Answer
> 1 votes
# Common Lisp - 113 characters

```
(lambda(b n s)(dotimes(i s)(setf n(format ()"~vR~vR"b (- #1=(parse-integer n :radix b)#2=(floor #1# 2))b #2#)))n)

```

# Ungolfed

```
(lambda(b n s)
  (dotimes(i s)
    (setf n (format () "~vR~vR" b (- #1=(parse-integer n :radix b)
                                     #2=(floor #1# 2))
                                b #2#)))
  n)

```
* The `~vR` format directive outputs integer in base `v`, where `v` is provided as an arguments to `format`.
* `parse-integer` accepts a `:radix` argument for converting from a specified base.
* `#1=` and `#1#` (respectively assign and use) are reader variables which allow to share common sub-expressions. When expanded, they give the following code:

```
(lambda (b n s)
  (dotimes (i s)
    (setf n
            (format nil "~vr~vr" b
                    (- (parse-integer n :radix b)
                       (floor (parse-integer n :radix b) 2))
                    b (floor (parse-integer n :radix b) 2))))
  n)

```

# Answer
> 0 votes
# Pip, 27 bytes

```
Lcb:+J[(bFB:a)%2i]+b//2TBab

```

Takes base, integer, and number of repetitions as command-line arguments. The algorithm is straightforward, but uses a couple interesting language features:

```
                             a, b, c initialized from cmdline args, and i = 0 (implicit)
Lc                           Do c times:
        bFB:a                Convert b from base a to decimal and assign back to b
      [(     )%2i]           Construct a list containing b%2 and 0 (using i to avoid
                               scanning difficulties)
                  +b//2      Add floor(b/2) to both elements of list; the list now contains
                               b-b//2 and b//2
                       TBa   Convert elements of list back to base a
     J                       Join list
    +                        Coerce to number (necessary to turn 00 into plain 0)
  b:                         Assign back to b
                          b  Print b at the end

```

Pip's scalar type, which represents both numbers and strings, is handy here, as are item-wise operations on lists; unfortunately, parentheses and the two-character operators `FB`, `TB`, and `//` negate any advantage.

Alternate solution, without the intermediate assignment but still 27 bytes:

```
Lcb:+J[bFBa%2i]+bFBa//2TBab

```

# Answer
> 0 votes
# C, 245 bytes

```
int b,z,n,f,r;c(char*t,n){return n?((z=c(t,n/b)),z+sprintf(t+z,"%d",n%b)):0;}main(){char t[99],*p;gets(t);b=atoi(t);f=n=strtol(p=strchr(t,32)+1,0,b);if(!(r=atoi(strchr(p,32)+1)))f=0;while(r--)n=strtol(t+c(t+c(t,n-n/2),n/2)*0,0,b);puts(f?t:"0");}

```

This isn't going to win *anything*, but it was fun to make!

# Answer
> 0 votes
# PHP, ~~115~~ 112 bytes

```
function($b,$n,$s){while($s--)$n=($c=base_convert)(ceil($n=$c($n,$b,10)/2),10,$b).$c(floor($n),10,$b);return$n;}

```

Try it online!

Ungolfed:

```
function split_join_repeat( $b, $n, $s ) {
    // repeat S times
    for( $x=0; $x < $s; $x++ ) {
        // convert N from base B to base 10 for arithmetic
        $n = base_convert( $n, $b, 10 );
        // divide and split in base 10, convert back to base B and join
        $n = base_convert( ceil( $n / 2 ), 10, $b ) .
            base_convert( floor( $n / 2 ), 10, $b );
    }
    return $n;
}

```

Output

```
B = 10, N = 27, S = 1   1413
B = 10, N = 27, S = 2   707706
B = 9, N = 27, S = 1    1413
B = 9, N = 27, S = 2    652651

2   1   10  11  101 1110    111111  10000011111 10000100001000001111
3   1   10  21  1110    202201  101101101100    1201201201212012012011  212100212102121002121212100212102121002120
4   1   10  22  1111    223222  111311111311    2232222232322322222322  11131111131311311111311113111113131131111131
5   1   10  32  1413    432431  213441213440    104220331443104220331442    12141204110401030043301214120411040103004330
6   1   10  33  1514    535535  245550245545    122553122553122553122552    131022143412311313533131022143412311313533
7   1   10  43  2221    11111110    40404044040403  2020202202020220202022020201    40556522600645213204055652260064521320
8   1   10  44  2222    11111111    44444454444444  2222222622222222222226222222    76650460747555347665046074755534
9   1   10  54  2726    13581357    62851746285173  3142536758708231425367587081    4861155667688600048611556676886000
10  1   10  55  2827    14141413    70707077070706  3535353853535335353538535353    17676769267677271767676926767727

```

# Answer
> 0 votes
# Japt, 17 bytes

```
_nW o ó ®ÊsWÃq}gV

```

Try it online!

Takes input in the order S, N, B with N as a singleton list. Accepting N without a singleton list costs 2 bytes.

Explanation:

```
_             }g     #Get the Sth item generated by this function...
                V    #...Starting with N as the 0th item:
 nW                  # Evaluate the previous item as a base B number
    o                # Create a list with that length
      ó              # Divide it into two lists as evenly as possible
        ®   Ã        # For each of those lists:
         Ê           #  Get the length
          sW         #  Convert it to base B
             q       # Join the two strings together

```

# Answer
> 0 votes
# Forth (gforth), 105 bytes

```
: f base ! 0 ?do 0. 2swap >number nip 2drop 2 /mod >r i + r> 0 tuck <# #s 2drop #s #> loop type decimal ;

```

Try it online!

### Explanation

Changes the base to B, then in a loop that runs S times:

* Converts string to a number
* Splits number in 2 halves (one larger than the other if odd)
* Combines the two numbers back into a string

Prints the string when finished and sets the base back to 10 (so we can run multiple times in a row)

### Code Explanation

```
:f                    \ start a new word definition
  base !              \ set the base to B
  0 ?do               \ loop from 0 to S-1 (runs S times)
    0. 2swap          \ places a double-length 0 on the stack behind the string
    >number           \ converts the string to a number in the current base
    nip 2drop         \ get rid of string remainder and second part of double
    2 /mod            \ get the quotient and remainder of dividing by 2
    >r                \ throw the quotient on the return stack
    i                 \ get a copy of the quotient from the return stack
    +                 \ add quotient and remainder
    r>                \ move quotient from return stack to stack
    0 tuck            \ convert both to double-length numbers
    <#                \ start a pictured numeric output
      #s              \ add entire number to output
      2drop           \ drop empty number
      #s              \ add second number to output
    #>                \ convert output to a string and drop number from stack
  loop                \ end loop
  type                \ print output string
  decimal             \ set base back to 10
;                     \ end word definition

```

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


title: Playing Pickomino

text:
# Question
Title: Playing Pickomino
In the game Pickomino, there are several tiles lying in the middle of the table, each with a different positive integer on them. Each turn, the players roll dices in a certain way and get a score, which is a nonnegative integer.

Now the player takes the tile with the highest number that is still lower or equal to their score, removing the tile from the middle and adding it to their stack. If this is not possible because all numbers in the middle are higher than the player's score, the player loses the topmost tile from their stack (which was added latest), which is returned to the middle. If the player has no tiles left, nothing happens.

## The challenge

Simulate a player playing the game against themselves. You get a list of the tiles in the middle and a list of the scores that the player got. Return a list of the tiles of the player after all turns have been evaluated.

## Challenge rules

* You can assume that the list with the tiles is ordered and doesn't contain any integer twice.
* You can take both lists of input in any order you want
* The output has to keep the order of the tiles on the stack, but you can decide whether the list is sorted from top to bottom or from bottom to top.

## General rules

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code (i.e. TIO).
* Adding an explanation for you answer is recommended.

## Example

(taken from the 6th testcase)

```
Tiles: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
Scores: [22, 22, 22, 23, 21, 24, 0, 22]

```

First score is 22, so take the highest tile in the middle \<= 22, which is 22 itself.

```
Middle: [21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
Stack: [22]
Remaining scores: [22, 22, 23, 21, 24, 0, 22]

```

Next score is 22, so take the highest tile in the middle \<= 22. Because 22 is already taken, the player has to take 21.

```
Middle: [23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
Stack: [22, 21]
Remaining scores: [22, 23, 21, 24, 0, 22]

```

Next score is 22, but all numbers \<= 22 are already taken. Therefore, the player loses the topmost tile on the stack (21), which is returned into the middle.

```
Middle: [21, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
Stack: [22]
Remaining scores: [23, 21, 24, 0, 22]

```

Next scores are 23, 21 and 24, so the player takes these tiles from the middle.

```
Middle: [25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
Stack: [22, 23, 21, 24]
Remaining scores: [0, 22]

```

The player busts and scores zero. Therefore, the tile with the number 24 (topmost on the stack) is returned into the middle.

```
Middle: [24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
Stack: [22, 23, 21]
Remaining scores: [22]

```

The last score is 22, but all tiles \<= 22 are already taken, so the player loses the topmost tile on the stack (21).

```
Middle: [21, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
Final Stack and Output: [22, 23]

```

## Test cases

(with the topmost tile last in the output list)

```
Tiles: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
Scores: [26, 30, 21]
Output: [26, 30, 21]

Tiles: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
Scores: [35, 35, 36, 36]
Output: [35, 34, 36, 33]

Tiles: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
Scores: [22, 17, 23, 19, 23]
Output: [23]

Tiles: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
Scores: []
Output: []

Tiles: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
Scores: [22, 17, 23, 19, 23, 0]
Output: []

Tiles: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]
Scores: [22, 22, 22, 23, 21, 24, 0, 22]
Output: [22, 23]

Tiles: [1, 5, 9, 13, 17, 21, 26]
Scores: [6, 10, 23, 23, 23, 1, 0, 15]
Output: [5, 9, 21, 17, 13, 1]

Tiles: []
Scores: [4, 6, 1, 6]
Output: []

```

---

Sandbox

# Answer
# Haskell, ~~119~~ ~~111~~ ~~104~~ 103 bytes

*1 byte saved thanks to Ørjan Johansen*

```
(#)=span.(<)
(a%(b:c))d|(g,e:h)<-b#d=(e:a)%c$g++h|g:h<-a,(i,j)<-g#d=h%c$i++g:j|1>0=a%c$d
(a%b)c=a
([]%)

```

Try it online!

Assumes the tiles are sorted in descending order.

Not much fancy going on here. The first argument is the players pile, the second their scores and the third is the pile in the middle.
> 3 votes

# Answer
# Japt, 24 bytes

Oof! That didn't work out as well as I thought it would!

Takes input in reverse order.

```
®=Va§Z)Ì?NpVjZ:VpNo)nÃN¤

```

Try it or run all test cases on TIO

```
®=Va§Z)Ì?NpVjZ:VpNo)nÃN¤     :Implicit input of N=[U=scores, V=tiles]
®                            :Map each Z in U
 =                           :  Reassign to Z
  Va                         :    0-based index of last element in V (-1 if not found)
    §Z                       :      Less than or equal to Z
      )                      :  End reassignment
       Ì                     :  Sign of difference with -1 (1 if found, 0 if not)
        ?                    :  If truthy (not zero)
         Np                  :    Push to N
           VjZ               :      Remove and return the element at index Z in V
              :              :  Else
               Vp            :    Push to V
                 No          :      Pop the last element of N
                   )         :    End Push
                    n        :    Sort V
                     Ã       :End map
                      N¤     :Slice the first 2 elements (the original inputs) off N

```
> 3 votes

# Answer
# C# (Visual C# Interactive Compiler), ~~159~~ ~~158~~ 154 bytes

Called as `f(tiles)(scores)`

```
n=>m=>{var s=new Stack<int>();m.Add(0);n.ForEach(k=>{var a=m.Except(s).Where(x=>x<=k).Max();if(a<1)m.Add(s.Count<1?0:s.Pop());else s.Push(a);});return s;}

```

If only `System.Void` is actually a return type and not just a placeholder for reflection. I would be able to replace `if(a<1)m.Add(s.Count<1?0:s.Pop());else s.Push(a);` with `var t=a>1?m.Add(s.Count<1?0:s.Pop()):s.Push(a);`, saving two bytes.

Try it online!

```
//Function taking in a list and returning
//another function that takes in another list and returns a stack
n=>m=>{
//Initialize the stack
var s=new Stack<int>();
//Add a zero to the tiles, to ensure no exceptions appear due to accessing
//non-existent elements in an empty collection later
//when we try to filter it later and getting the biggest element
m.Add(0);
//Iterate through our scores
n.ForEach(k=>{
//Create a variable called a, which we will use later
var a=
//Get all the elements in the middle that haven't appeared in our stack
m.Except(s).
//And throw away all elements that are bigger than our current score
Where(x=>x<=k).
//And get the biggest element there, and that is now the value of a
//Without the m.Add(0), we would get an exception here
Max();
//Self-explanatory, if a is less than 1 aka if a equals 0
//Checks if all elements in the middle are bigger than our score
//Except for our self added 0, of course
if(a<1)
//Add 0 to the middle if the stack is empty
//Remember, zeros don't affect the list
m.Add(s.Count<1?0:
//Else pop the stack and add that to the middle
s.Pop());
//If a isn't 0, add a to the stack
else s.Push(a);});
//Afterwards, return the stack
return s;}

```
> 2 votes

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

Same logic as the ES6 version, but takes the tiles as a BigInt bitmask and the scores as an array of BigInts.

```
m=>s=>s.map(g=x=>!x||m>>x&1n?m^=1n<<(x?r.push(x)&&x:r.pop()||~x):g(--x),r=[])&&r

```

Try it online!

---

# JavaScript (ES6),  ~~100 98 94~~  87 bytes

Takes input as `(tiles)(scores)`. The tiles can be passed in any order.

```
t=>s=>s.map(g=x=>m[x]?m[x?r.push(x)&&x:r.pop()]^=1:g(x-1),t.map(x=>m[x]=1,m=[r=[]]))&&r

```

Try it online!

### Commented

```
t => s =>                 // t[] = tiles; s[] = scores
  s.map(g = x =>          // for each score x in s[]:
    m[x] ?                //   if m[x] is set:
      m[                  //     update the 'middle':
        x ?               //       if x is not equal to 0:
          r.push(x) && x  //         push x in the stack r[] and yield x
        :                 //       else:
          r.pop()         //         pop the last value from the stack
                          //         (may be undefined if the stack is empty)
      ] ^= 1              //     toggle the corresponding flag in m[]
    :                     //   else:
      g(x - 1),           //     try again with x - 1
    t.map(x =>            //   initialization of the 'middle': for each value x in t[]:
      m[x] = 1,           //     set m[x]
      m = [r = []]        //     the stack r[] is stored as the first entry of m[],
                          //     which ensures that g will always stop when x = 0
    )                     //   end of initialization
  ) && r                  // end of main loop; return r[]

```
> 2 votes

# Answer
# Perl 6, 89 bytes

```
{my@x;@^a;@^b>>.&{@x=|@x,|(keys(@a∖@x).grep($_>=*).sort(-*)[0]//(try ~@x.pop&&()))};@x}

```

Try it online!

I think there's a few more bytes to be golfed off this...
> 2 votes

# Answer
# Ruby, 77 bytes

```
->t,s,r=[]{s.map{|i|(x=(t-[p]).reject{|j|j>i}.max)?(t-=[x];r<<x):t<<r.pop};r}

```

Try it online!
> 2 votes

# Answer
# Charcoal, 35 bytes

```
Ｆη«≔⌈Φθ¬›κιι¿ι«≔Φθ⁻κιθ⊞υι»¿υ⊞θ⊟υ»Ｉυ

```

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

```
Ｆη«

```

Loop over the scores.

```
≔⌈Φθ¬›κιι

```

Look for the highest available tile.

```
¿ι«

```

If it exists then...

```
≔Φθ⁻κιθ

```

... remove the tile from the middle...

```
⊞υι

```

... and add it to the stack.

```
»¿υ

```

Otherwise, if the stack is not empty...

```
⊞θ⊟υ

```

Remove the latest tile from the stack and return it to the middle.

```
»Ｉυ

```

Print the resulting stack from oldest to newest.
> 1 votes

# Answer
# Python 2, 120 bytes

```
m,s=input()
t=[]
for n in s:
 i=[v for v in m if v<=n]
 if i:v=max(i);t+=[v];m.remove(v)
 else:m+=t and[t.pop()]
print t

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~27~~ 22 bytes

```
vÐy>‹ÏDgĀià©K®së\sª])¨

```

Try it online or verify all test cases.

**Explanation:**

```
v            # Loop `y` over the (implicit) input-list of scores:
 Ð           #  Triplicate the tiles list (takes it as implicit input in the first iteration)
  y>‹        #  Check for each if `y` <= the value in the tiles list
     Ï       #  Only leave the values at the truthy indices
 D           #  Duplicate the remaining tiles
  ¯Êi        #  If this list is not empty:
     à       #   Pop the list, and push its maximum
      ©      #   Store it in the register, without popping
       K     #   Remove it from the tiles list
        ®    #   Push the maximum again
         s   #   Swap the maximum and tiles-list on the stack
    ë        #  Else:
     \       #   Remove the duplicated empty tiles-list from the stack
      sª     #   Add the last tile to the tiles-list
]            # Close the if-else and loop
 )           # Wrap everything on the stack into a list
  ¨          # Remove the last item (the tiles-list)
             # (and output the result implicitly)

```
> 1 votes

# Answer
# Pyth, 32 bytes

```
VE ?JeS+0f!>TNQ=-QeaYJaQ.)|Y]0;Y

```

Try it online here, or verify all the test cases at once here.

There must be room for improvement here somewhere - any suggestions would be much appreciated!

```
VE ?JeS+0f!>TNQ=-QeaYJaQ.)|Y]0;Y   Implicit: Q=input 1 (middle), E=input 2 (scores), Y=[]
VE                            ;    For each score, as N, in the second input:
         f    Q                      Filter Q, keeping elements T where:
          !>TN                         T is not greater than N
                                       (less than or equal is the only standard inequality without a token in Pyth, grrr)
       +0                            Prepend 0 to the filtered list
     eS                              Take the largest of the above (_e_nd of _S_orted list)
    J                                Store the above in J
   ?                                 If the above is truthy:
                   aYJ                 Append J to Y
                  e                    Take last element of Y (i.e. J)
               =-Q                     Remove that element from Q and assign the result back to Q
                                     Else:
                          |Y]0         Yield Y, or [0] if Y is empty
                        .)             Pop the last element from the above (mutates Y)
                      aQ               Append the popped value to Q
                               Y   Print Y

```
> 1 votes

# Answer
# Perl 5 `-apl -MList:Util=max`, 97 bytes

```
$_=$".<>;for$i(@F){(($m=max grep$_<=$i,/\d+/g)&&s/ $m\b//?$s:$s=~s/ \d+$//?$_:$G).=$&}$_=$s;s/ //

```

TIO

reads scores and tiles on next line and prints output.

How

* `-apl` : `-p` to loop over lines and print, `-a` autosplit, `-l` to chomp from input and add newline character to output
* `$_=$".<>` : to read next line (tiles) and prepend a space into default var `$_`
* `for$i(@F){` ... `}` loop `$i` over `@F` fields of current line (scores)
* `(` .. `?` .. `:` .. `).=$&` append previous match to ternary l-value
* `($m=max grep$_<=$i,/\d+/g)&&s/ $m\b//?$s` in case max value found and removed from tiles (`$_`) l-value is scores (`$s`)
* `$s=~s/ \d+$//?$_` otherwise if last number could be removed from scores it's tiles
* `:$G` finally it's garbage because can't occur
* `$_=$s;s/ //` to set scores to default var, and remove leading space
> 1 votes

---
Tags: code-golf, game
---


title: Make a longer lenguage program

text:
# Question
Title: Make a longer lenguage program
Lenguage is a brainfuck dialect that is notorious for breaking source restriction challenges. That is because Lenguage cares only about the length of it's source and not the contents.

First, the length of the program is calculated. Then, said length is converted to binary and left-padded by zeroes to a multiple of 3. The resulting binary string is split into chunks of 3 bits each of which is translated into a brainfuck command as such:

```
000 -> +
001 -> -
010 -> >
011 -> <
100 -> .
101 -> ,
110 -> [
111 -> ]

```

Finally the program is run as brainfuck1.

From here the challenge is pretty simple, write a lenguage program that takes no input and produces an output consisting of one byte repeated integer \\$n\\$ times, where \\$n\\$ is strictly greater than the length of your program.

Answers will be scored in bytes with fewer bytes being better.

Here's a hacky program to calculate lenguage from brainfuck

---

1: For this challenge we will use wrapping cells and a non-wrapping tape.

# Answer
> 15 votes
# 8437495638205698686671 bytes

This translates to the brainfuck program:

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

```

Which prints exactly \\$231584178474632390847141970017375815706539969331281128078915168015826259279614\\$ SOH bytes.

This is calculated by the function

```
f(n)=2*f(n-1)+n
f(0)=0

```

with an input of 255.

### Explanation:

```
-[         Loop 255 times
  >>[>]    Move to the end of a series of positive cells (initially empty)
  +        Add one cell to the end
  [-       Loop over each cell
    >[>]+  Add one cell to the end
    .      Print a SOH byte
    [<]+   Restore current cell
  <]       Move to next cell
<-]        Decrement counter

```

# Answer
> 4 votes
# 9093903938998324939360576240306155985031832511491088836321985855167849863863065731015823 bytes

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

```

Which prints exactly

```
298333629248008269731638612618517353495058861384016275770860733328251135402804732197446995616017112134460464130233444058136509123809012106419446593183683387659250431692751255099808162970657410517657862174602556590616568690423540284801267472920128909691902547970614008613488242333460665145840144517097342073878746293059960326132795671583153307437896728515625000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

```

(\\$250^{255}\\$) NUL bytes.

Credit goes to *@hvd* in this Brainfuck answer, so make sure to upvote him!

**Explanation:**

I was going to write an explanation of my own, but realized *@hvd*'s explanation is already on point, so I'll quote it here instead:

> `>>>>>>` is needed to leave a bit of working space.
>
> `-` produces 255 (*since 0 - 1 = 255 when we have wrapping cells*).
>
> `[[->>>+<<<]------>>>-]` turns this into 255 copies of the value 250, giving a tape that looks like:
>
> ```
> 0 0 0 0 0 0 250 0 0 250 0 0 ... 250 0 0 [0]
>
> ```
>
> `<<<[<<<]+` moves the data pointer back and finishes up the initial data:
>
> ```
> 0 0 0 [1] 0 0 250 0 0 250 0 0 ...
>
> ```
>
> Then comes the loop: `[+...-]` initially sets the 1 to a 2, which gets set back to 1 at the end of the loop. The loop terminates when the loop body already set 2 to 1.
>
> Now, the numbers 2 250 250 250 ... 250 represent a counter, in base 250, with each number one greater than the digit it represents.
>
> * `[>>>]<<<` moves all the way to the right. Since each digit is represented by a non-zero number, this is trivial.
> * `->+[<[+>-]>[-<<<<->+>>------>>]<<<<]>>-` decreases the counter by 1. Starting with the last digit: the digit gets decremented. If it remains positive, we're done. If it turns to zero, set it to 250, and continue with the digit before.
> * `[<<<].>>>` moves the pointer back before the left-most digit, and this is a nice moment to print a NUL byte. Then re-position to exactly the left-most digit, to see if we're done.
>
> To verify correctness, change the initial `-` to `+` to print 2501 NUL bytes, `++` for 2502, etc.

# Answer
> 4 votes
# 19326644346528796447 bytes

Brainfuck code:

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

```

Prints

```
57896044618658097711785492504343953926634992332820282019728792003956564819967

```

null bytes.

It works like this:

```
mem[i]=255;
do
    while(--mem[i]){
        mem[i+1]=mem[i+2]=mem[i];
        mem[i]=1;
        i+=2;
    }
while(mem[--i]);

```

Quite straightforward recursion.

---
Tags: code-golf, brainfuck, self-referential
---


title: Number of \$n\$-carbon alkanes

text:
# Question
Title: Number of \$n\$-carbon alkanes
Given a positive number \\$n\\$, find the number of alkanes with \\$n\\$ carbon atoms, ignoring stereoisomers; or equivalently, the number of unlabeled trees with \\$n\\$ nodes, such that every node has degree \\$\le 4\\$.

This is OEIS sequence A000602.

See also: Paraffins - Rosetta Code

### Example

For \\$n = 7\\$, the answer is \\$9\\$, because heptane has nine isomers:

* **Heptane**: \\$\mathrm{H\_3C-CH\_2-CH\_2-CH\_2-CH\_2-CH\_2-CH\_3}\\$

* **2-Methylhexane**: \\$\mathrm{H\_3C-CH(CH\_3)-CH\_2-CH\_2-CH\_2-CH\_3}\\$

* **3-Methylhexane**: \\$\mathrm{H\_3C-CH\_2-CH(CH\_3)-CH\_2-CH\_2-CH\_3}\\$

* **2,2-Dimethylpentane**: \\$\mathrm{H\_3C-C(CH\_3)\_2-CH\_2-CH\_2-CH\_3}\\$

* **2,3-Dimethylpentane**: \\$\mathrm{H\_3C-CH(CH\_3)-CH(CH\_3)-CH\_2-CH\_3}\\$

* **2,4-Dimethylpentane**: \\$\mathrm{H\_3C-CH(CH\_3)-CH\_2-CH(CH\_3)-CH\_3}\\$

* **3,3-Dimethylpentane**: \\$\mathrm{H\_3C-CH\_2-C(CH\_3)\_2-CH\_2-CH\_3}\\$

* **3-Ethylpentane**: \\$\mathrm{H\_3C-CH\_2-C(CH\_2CH\_3)-CH\_2-CH\_3}\\$

* **2,2,3-Trimethylbutane**: \\$\mathrm{H\_3C-C(CH\_3)\_2-CH(CH\_3)-CH\_3}\\$

Note that 3-methylhexane and 2,3-dimethylpentane are chiral, but we ignore stereoisomers here.

### Test cases

You don't need to handle the case \\$n = 0\\$.

```
intput	output
=============
0	1
1	1
2	1
3	1
4	2
5	3
6	5
7	9
8	18
9	35
10	75
11	159
12	355
13	802
14	1858
15	4347
16	10359
17	24894
18	60523
19	148284
20	366319

```

# Answer
> 11 votes
## CJam (100 98 91 89 83 bytes)

```
1a{_[XX]*\_{_0a*}:E~\{E\_{ff*W%{0@+.+}*}:C~.+2f/}:D~.+C.+3f/1\+}q~:I*DE1$D.-X\+.+I=

```

Takes input from stdin, outputs to stdout. Note that this exploits the licence to not handle input `0` to save two bytes by inlining the definitions of `C` and `D`. Online demo

NB this is *very* slow and memory-inefficient. By trimming arrays a much faster version is obtained (3 bytes more). Online demo.

### Dissection

OEIS gives (modulo an indexing error) the generating function decomposition $$\begin{eqnarray} A000598(x) &=& 1 + x Z(S\_3; A000598(x)) \\ A000678(x) &=& x Z(S\_4; A000598(x)) \\ A000599(x) &=& Z(S\_2; A000598(x) - 1) \\ A000602(x) &=& A000678(x) - A000599(x) + A000598(x^2) \\ \end{eqnarray}$$ where \\$Z(S\_n; f(x))\\$ denotes the cycle index of the symmetric group \\$S\_n\\$ applied to the function \\$f(x)\\$.

I manipulated this into a slightly golfier decomposition, and then looked up the intermediate sequences and discovered that they're also in OEIS:

$$\begin{eqnarray} A000642(x) &=& Z(S\_2, A000598(x)) \\ A000631(x) &=& Z(S\_2, A000642(x)) \\ A000602(x) &=& A000642(x) + x A000642(x^2) - x A000631(x) \end{eqnarray}$$

Earlier versions reused block `C` (convolve two polynomials) from this answer. I've found a much shorter one, but I can't update that answer because it's from a chaining question.

```
1a            e# Starting from [1]...
{             e# Loop I times (see below) to build A000598 by f -> 1 + Z(S_3; f)
  _[XX]*      e#   Copy and double-inflate to f(x^3)
  \_          e#   Flip and copy: stack is f(x^3) f(x) f(x)
  {_0a*}:E~   e#   Assign copy-and-inflate to E and execute
              e#   Stack: f(x^3) f(x) f(x) f(x^2)
  \           e#   Flip
  {           e#   Define and execute block D, which applies f -> Z(S_2;f)
              e#     Stack: ... f
    E\_       e#     Stack: ... f(x^2) f(x) f(x)
    {         e#     Define and execute block C, which convolves two sequences
      ff*     e#       Multiply copies of the second sequence by each term of the first
      W%      e#       Reverse
      {       e#       Fold
        0@+.+ e#         Prepend a 0 to the first and pointwise sum
      }*
    }:C~      e#     Stack: ... f(x^2) f(x)^2
    .+2f/     e#     Pointwise average
  }:D~        e#   Stack: f(x^3) f(x) f(x^2) Z(S_2;f(x))
  .+C         e#   Stack: f(x^3) f(x)*(f(x^2) + Z(S_2;f(x)))
  .+3f/       e#   Add and divide by 3 to finish computing Z(S_3; f)
  1\+         e#   Prepend a 1
}
q~:I          e# Read input to I
*             e# Loop that many times
              e# Stack: I+1 terms of A000598 followed by junk
D             e# Stack: I+1 terms of A000642 followed by junk
E1$D          e# Stack: A000642 A000642(x^2) A000631
.-X\+.+       e# Stack: A000602
I=            e# Extract term I

```

# Answer
> 7 votes
## Alchemist (1547 bytes)

```
_->In_NN+2b+al+g
al+g+0NN->ak
al+g+NN->ah
ah+b->ah+m+d+z+a
ah+0b->C+Z+Q
Z+j+z->Z+j+d
Z+j+0z->M+s
M+g+b->M+g+r
M+g+h->M+g+d
M+g+0b+0h+q->J+U
J+o+h->J+o+m
J+o+a->J+o+d
J+o+0h+0a->2C+an+Q
an+j+h->an+j+d
an+j+0h->aC+s
aC+g->e+am+P
am+l+b->am+l+d
am+l+0b->al+s
ak+b->ak+m+d
ak+0b->C+aj+Q
aj+j+h->aj+j+b
aj+j+0h->I+n
I+f+e->I+f+a
I+f+b->I+f+m+d+z
I+f+0e+0b->C+ai+Q
ai+j+h->ai+j+b
ai+j+0h->aB+n
aB+f->H
H+z->H+d
H+a+e->H
H+0z+0e->G+i
G+i+0b->ag
G+i+b->az+b+n
az+f+0b->Out_a
az+f+b->G+b+n
G+f->G+t
ag+e->ag
ag+0e->af+t
af+i+e->af+i+a
af+i+0e->Out_a
Q->F+s
F+g+b->F+g+y
F+g+A->F+g
F+g+0b+0A->av+o
av+o+0m->w
av+o+m->m+ae+A
ae+m->ae+b
ae+0m->u+n
u+f+b->u+f+m
u+f+e->u+f+E
u+f+A->u+f+k+c
u+f+0b+0e+0A->ad
ad+c->ad+A
ad+0c->ac
ac+y->ac+d+c
ac+0y->ab
ab+c->ab+y
ab+0c->V+l
V+l+0k->x
V+l+k->aa+t
aa+i+0e->W
aa+i+e->Y
Y+E->Y+D+c
Y+0E->X
X+c->X+E
X+0c->aa+i
W+D->W+e
W+0D->V+P
x+E->x
x+d->x
x+b->x+k
x+0E+0d+0b->aw
aw+h->aw+d
aw+0h->aE+s
aE+g->p
p+b->p+2r
p+k->p+d
p+B->p
p+q->p
p+0b+0k+0B+0q->r+q+av+U
w+h->w+d
w+y->w+r
w+C->w+B+q
w+0h+0y+0C->aD+U
aD+o->j
U->au+s
au+g+b->au+g+d
au+g+0b->v
v+d->d+aA+t
aA+i+k->R
aA+i+0k->at
at+B->at+k+c
at+0B->L
L+c->L+B
L+r->L+b
L+0c+0r->as+n
as+f+b->as+f+r
as+f+0b->R
R+0e->K
R+e+q->ar+D+c
ar+e+q->ar+c
ar+0q->aq
aq+c->aq+q
aq+0c->R
K+D->K+e
K+h->K+b
K+0D+0h->ap+P
ap+l+b->ap+l+h
ap+l+0b->v
v+0d+k->v
v+0d+r->v
v+0d+0k+0r->o
s+0d->g
s+d->d+ao+t
ao+i->ao+P
ao+l->s
P->O+c
O+b->2c+O
O+0b->N
N+c->b+N
N+0c+e->O
N+0c+0e->l
n+b->n+c
n+0b->T
T+c->ay
T+0c->e+n
ay+c->b+T
ay+0c->f
t+d->t+c
t+0d->S
S+c->ax
S+0c->e+t
ax+c->d+S
ax+0c->i

```

Online demo.

Note: this is quite slow. If testing with an interpreter which supports applying a rule multiple times at once (e.g. my one \- although make sure you have the latest version which fixes a bug in the parser) then you can get a significant speed-up by adding two rules:

```
T+2c->b+T
S+2c->d+S

```

which inline a route through the existing rules

```
T+c->ay
ay+c->b+T
S+c->ax
ax+c->d+S

```

## Partial dissection

At a high level, this uses the same approach as my CJam answer.

The computation model of Alchemist is essentially the Minsky register machine. However, Alchemist very nicely exposes the equivalence of code and data, and by allowing many tokens on the left hand side of a production rule effectively the state is not constrained to be represented by one atom: we can use a tuple of atoms, and this allows (non-recursive) subroutines. This is very useful for golf. The only things it's really lacking are macros and debuggability.

For arrays I'm using a pairing function which can be implemented quite golfily in RMs. The empty array is represented by \\$0\\$, and the result of prepending \\$x\\$ to array \\$A\\$ is \\$(2A+1)2^x\\$. There is one subroutine to pair: the subroutine is called `P` and it prepends the value of `e` to `b`. There are two subroutines to unpair: `n` unpairs `b` to `e` and `b`; and `t` unpairs `d` to `e` and `d`. This allowed me to save quite a bit of shuffling data between variables, which is important: a single "move" operation

```
a, b = b, 0

```

expands to at least 17 bytes:

```
S+a->S+b
S+0a->T

```

where `S` is the current state and `T` is the next state. A non-destructive "copy" is even more expensive, because it has to be done as a "move" from `a` to `b` and an auxiliary `tmp`, followed by a "move" from `tmp` back to `a`.

## Obfuscation

I aliased various variables to each other and eliminated about 60 states in the process of golfing the program, and many of them didn't have particularly meaningful names anyway, but to fully golf it I wrote an minimiser so the names are now thoroughly indecipherable. Good luck reverse engineering it! Here is the minimiser (in CJam), which makes a few assumptions about the code but could be adapted to minimise other Alchemist programs:

```
e# Obfuscate / minimise Alchemist program

e# Tokenise
qN%[SNS]e_*S%

e# Get token frequencies for substitution purposes, special-casing the I/O ones
_["+" "0" "2" "->" "_" N "In_n" "n" "Out_tmp2" "tmp2"]-
$e`$W%1f=

e# Empirically we want a two-char input for n and a one-char one for tmp2
["In_n" "Out_tmp2" "n" "tmp2"]\+
["In_NN" "Out_a" "NN"] "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"1/:A+ A2m*:e_"NN"a-+
1$,<

er
_s,p

```

# Answer
> 5 votes
# Node.js 11.6.0,  ~~229 223 221~~  218 bytes

Derived from the Java implementation suggested on Rosetta Code.

```
f=(N,L=1,u=[...r=[c=[],1,...Buffer(N)]],k=u[(g=(n,B,S,i,b=B,m,d=0)=>{for(;++b<5;)for(x=c[B]=(d+r[m=n])*(d++?c[B]/d:i),u[S+=n]+=L*2<S&&x,r[S]+=b<4&&x;--m;)g(m,b,S,c[B])})(L,0,1,1),L]-=~(x=r[L++/2])*x>>1)=>L>N?k:f(N,L,u)

```

Try it online!

# Answer
> 1 votes
# Pari/GP, 118 bytes

A direct translation of Peter Taylor's CJam answer.

```
n->(s(k)=subst(a,x,x^k));(z()=(a^2+s(2))/2);a=O(1);for(i=0,n,a=1+x*(a*z()+(s(3)-a^3)/3));a=z();Pol(a+x*(s(2)-z()))\x^n

```

Try it online!

---
Tags: code-golf, sequence, combinatorics, chemistry
---


title: Pinyin Combinations

text:
# Question
Title: Pinyin Combinations
Create a function that takes a string of a pinyin syllable as the argument, and returns true of the combination exists, false otherwise.

Use "v" for "ü".

Here is a full list of combinations. http://www.pinyin.info/rules/initials\_finals.html

Examples

```
f("bu") == true
f("zheng") == true
f("nv") == true
f("ri") == true
f("cei") == false
f("ia") == false
f("kian") == false
f("qa") == false

```

Please, don't do things like scraping webpages or reading input method files to reduce character count. (If you do, the length of the data will be counted toward character count) One of the purposes of this code golf is to see how rules can be simplified. Shortest code wins.

# Answer
## JavaScript 1.6, 503 496 477 characters

```
function g(s){return/^([bfmpw]?o|[yjqx]ua?n|[ln]ve?|ei?|y[aio]ng|w?[ae]ng?|w?ai?|wei|y?ao|y?ou|y[ai]n?|yu?e|[^aeiou]+u)$/.test(s)|(((k=6*("ccsszzdflmnprtbghkjqx".indexOf(s[0])+(f=s[1]=='h')))|(r="a.e.ai.ei.ao.ou.an.ang.en.eng.ong.ua.uo.uai.ui.uan.uang.un.i.ia.ie.iao.iu.ian.iang.in.ing.iong.u.ue".split('.').indexOf(s.slice(f+1))))<0?0:k>84?r>17^k<108:parseInt("009m2f00b8jb009m2f00b7r3009m2n00b8jj1dwcfz0000rtfjba4f1xgbnjfj01rz1uyfb1009nn61b37cv1uyfa5".slice(k,k+6),36)>>r&1)}

```

Fomatted a little bit more readably (barring any errors in breaking the code into a few lines):

```
function _g(s)
{
  f = s[1] == 'h'
  k = "ccsszzdfghjklmnpqrtxb".indexOf(s[0]) * 6
  k += 6 * f
  return /^(weng|[bfmp]?o|[yjqx]ua?n|[ln]ve?|[ae]i?|y[aeiu]|y[aio]ng|[ae]ng?|wang?|wai?|we[in]|w[ou]|y?ao|y?ou?|y[ai]n|yue)$/.test(s) |
         !!(k >= 0 && (1 << "a.e.ai.ei.ao.ou.an.ang.en.eng.ong.u.ua.uo.uai.ui.uan.uang.un.i.ia.ie.iao.iu.ian.iang.in.ing.iong.u.ue".split('.').indexOf(s.slice(f + 1)) & parseInt("00j85300mh2v00j85300mgan00j85b00mh332rsovz0002cp00b8jj00b8jjqmlts000b8jjv2mkfz3uwo3jv203jz3pwvelqmlts000jbaq2m6ewvqmlts03pwvdp".slice(k, k + 6), 36)))
}

```

The zero-initial cases plus a few one-offs are tested with a regular expression. After that, the table is encoded as a (concatenated) series of 6-digit, base-36 numbers, one per initial sound. The lookup then uses a pair of `indexOf` calls and a shift to select the right bit.

Tested against all cells in the table of combinations (filled cells tested for true, empty cells tested for false).

*Edit:* Replaced some of the 36 chars of the base-36 lookup with comparisons since g–, k–, h–, j–, q–, and z– have dense blocks of true/false.

*Edit:* Rearranged the bit test to avoid an unnecessary `!!` and compacted the regex more.
> 4 votes

# Answer
# PHP, 548 characters

Granted, it's likely not optimal, but I wrote a regex to match valid pinyin combinations. Reduced characters by replacing repeating substrings with variables.

## Code

```
<?php $a='?|e(i|ng?)';$b='|o(u|ng)|u';$c='|a?n)?|i(a[on]';$d='(a(ng?|o|i)';$e='|ng?)';$f='(i|ng)?';echo(preg_match("/^([bpm](a(i|o$e$a|u|o|i(e|a[on]$e?)|[pm]ou|m(e|iu)|f(a(ng?)?|ou$a|u)|d$d$a?$b(o|i$c?|e|u)?)|[dtnl]$d?|e$f$b(o$c|e)?)|[jqxy](i(a(o$e?|e|u|o?ng|n)|u(e|a?n))|([zcs]h?|r)i|[nl](ve?|i(n|ang?|u))|[dl]ia|[dt](ing|ui)|[dn]en|diu|([gkh]|[zcs]h?)(e(ng?)|a(o|ng?|i)?|ou|u(o|i|a?n)?)|r(e(ng?)?|a(o$e$b(a?n?|o|i)?)|[gkh](ei|ong|u(a$f))|[zcs]hua$f|([zcs]|[zc]h)ong|(z|[zs]h)ei|a(i|o$e?|ou$a?|w(u|a(i$e?|o|e(i$e))$/",$argv[1]))?"true":"false";

```

## Usage

```
> php pinyin.php bu
> true
> php pinyin.php cei
> false

```
> 1 votes

# Answer
# F#, 681 characters

```
type l=Y|J|Q|X|W|F|B|P|M|N|L|T|D|Z|K|H|Zh|G|Sh|Ch|C|S|R|Iong|Vn|Van|Ia|Iu|In|Iang|Ve|V|Ian|Iao|Ie|Ing|I|Ei|A|Ai|An|Ang|Eng|U|Ao|E|Ou|Uo|Uan|Un|Ui|En|Ong|Ua|Uang|Uai|Ueng|O
let v x=x.GetHashCode()
let n x=J.GetType().GetNestedType("Tags").GetFields().GetValue(v x).ToString().Substring(6).ToLower();
let(^)a b=List.collect(fun x->List.map(fun z-> n x+ n z)b)a
let(-)a b=[v a..v b]
let(&)a b=a@b
let(!)a=[v a]
[<EntryPoint>]
let main a=
 printf"%b"(List.exists(fun x->x=a.[0])(Y-X^Iong-I& !W^Ei-Ui@Ua-O& !F^Ei-A@An-U@ !Ou&(F-N@D-Sh)^ !En&F-M^ !O&B-M^ !In&N-L^Iu-Un& !D^Ia-Iu&B-D^Ian-Ao& !M^E-Ou&Ch-S^A-Ong&T-Sh^Ei-Ui&N-G^ !Ong&K-Ch^Ua-Uai& !R^An-Ua&(Sh-R@ !Z@ !Zh)^ !I&["lia";"pou";"mui"]))
 0

```

Doesn't quite get the syllables without initial consonant correct (Y, W etc).
> 1 votes

# Answer
# APL (Dyalog Extended), 475 bytes

```
s←⊢⊆⍨' '≠⊢
a b c←2097144 131064 1957895
f←{(⊂⍵)∊(12↑v),(s'yi ya ye yao you yan yang yin ying yong yu yue yuan yun wu wa wo wai wei wan wang wen weng nv lv nve lve'),(,⊤(a-8)1966080 393208 1966064 2096720 1966072 1048568a a 2056184a 131048a 7288b 7280 106488b 7280b 0 1958911 73735c c 352263c 24583 1859591c,5⍴7)/,('bpmfdtnlgkhzcs',s'zh ch sh r j q x')∘.,v←'aoe',s'ai ei ao ou an ang en eng ong u ua uo uai ui uan uang un ueng i ia ie iao iu ian iang in ing iong u ue uan un'}

```

Try it online!

Golfing in progress.

### Ungolfed

```
s←{⍵⊆⍨' '≠⍵}
con←s'b p m f d t n l g k h z c s zh ch sh r j q x'
vwl←s'a o e ai ei ao ou an ang en eng ong u ua uo uai ui uan uang un ueng i ia ie iao iu ian iang in ing iong u ue uan un'
tab←con∘.,vwl
bin←,⊤2097136 1966080 393208 1966064 2096720 1966072 1048568 2097144 2097144 2056184 2097144 131048 2097144 7288 131064 7280 106488 131064 7280 131064 0 1958911 73735 1957895 1957895 352263 1957895 24583 1859591 1957895 7 7 7 7 7
all←'aoe',(12↑vwl),(s'yi ya ye yao you yan yang yin ying yong yu yue yuan yun wu wa wo wai wei wan wang wen weng nv lv nve lve'),bin/,tab
f←{(⊂⍵)∊all}

```

Try it online!

The helper function `s` unpacks a space-delimited string:

```
{⍵⊆⍨' '≠⍵}    monadic function taking a string
    ' '≠⍵       0s at spaces, 1s elsewhere
 ⍵⊆⍨            Partition (split at 0s)

```

I first store the possible initial and final strings in the syllable, then make a table `tab` containing the concatenation of each string from the first list with each string from the second list.

Next, I store binary data as a list of integers. Some of the integers are repeated and can therefore be stored in variables, which also allows elision of some spaces.

Each integer is decoded into binary, and represents one row of the table. Each bit in the number represents whether a certain syllable in that row is a valid syllable, with the MSB representing the first column. All invalid syllables are removed from the table.

We flatten the table into a list, add on the forms with no initial consonant as a special case, and finally check if our input is in the list.

Possible further golfing potential:

* Write base64 or base255 encoding
* Reorder the columns and rows to make the numbers smaller.

Python helpful script and test-case generator: Try it online!
> 1 votes

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


title: Magic: the Gathering Combat Golf

text:
# Question
Title: Magic: the Gathering Combat Golf
Magic: the Gathering is a trading card game where, among other things, players play cards representing creatures, which can then attack the other player, or defend against the other player's attacks by blocking.

In this code-golf challenge, your program will be in the place of a Magic player deciding how to block in combat.

---

Each creature has two relevant attributes: Power, and toughness. A creature's power is the amount of damage it can deal in a combat, and its toughness is the amount of damage necessary to destroy it. Power is always at least 0, and toughness is always at least 1.

During combat in Magic, the player whose turn it is declares some of their creatures to be attacking the opponent. Then, the other player, known as the defending player, may assign their creatures as blockers. A creature may block only one creature per combat, but multiple creatures may all block the same creature.

After blockers are declared, the attacking player decides, for each attacking creature that was blocked, how to distribute the damage (equal to its power) that that creature deals to the creatures blocking it.

Then, damage is dealt. Each creature deals damage equal to its power. Attacking creatures that were blocked deal damage as descibed above. Unblocked attacking creatures deal damage to the defending player. Blocking creatures deal damage to the creature they blocked. Creatures belonging to the defending player that did not block deal no damage. (Creatures are not required to block.)

Finally, any creature dealt damage equal to or greater than its toughness is destroyed, and removed from the battlefield. Any amount of damage less than a creature's toughness has no effect.

---

Here's an example of this process:

A creature with power P and toughness T is represented as `P/T`

```
Attacking:
2/2, 3/3
Defending player's creatures:
1/4, 1/1, 0/1
Defending player declares blockers:
1/4 and 1/1 block 2/2, 0/1 does not block.
Attacking player distributes damage:
2/2 deals 1 damage to 1/4 and 1 damage to 1/1
Damage is dealt:
2/2 takes 2 damage, destroyed.
3/3 takes 0 damage.
1/1 takes 1 damage, destroyed.
1/4 takes 1 damage.
0/1 takes 0 damage.
Defending player is dealt 3 damage.

```

---

The defending player has 3 goals in combat: Destroy the opponent's creatures, preserve one's own creatures, and be dealt as little damage as possible. In addition, creatures with more power and toughness are more valuable.

To combine these into a single measure, we will say that the defending player's score from a combat is equal to the sum of the powers and toughnesses of their surviving creatures, minus the sum of the powers and toughnesses of their opponent's surviving creatures, minus one half of the amount of damage dealt to the defending player. The defending player wants to maximize this score, while the attacking player wants to minimize it.

In the combat shown above, the score was:

```
Defending player's surviving creatures:
1/4, 0/1
1 + 4 + 0 + 1 = 6
Attacking player's surviving creature:
3/3
3 + 3 = 6
Damage dealt to defending player:
3
6 - 6 - 3/2 = -1.5

```

If the defending player had not blocked at all in the combat described above, the score would have been

```
8 - 10 - (5/2) = -4.5

```

The optimal choice for the defending player would have been to block the `2/2` with the `1/1` and the `1/4`, and to block the `3/3` with the `0/1`. If they had done so, only `1/4` and the `3/3` would have survived, and no damage would have been dealt to the defending player, making the score

```
5 - 6 - (0/2) = -1

```

---

Your challenge is to write a program which will output the optimal blocking choice for the defending player. "Optimal" means the choice which maximizes the score, given that the opponent distributes damage in the way which minimizes the score, given how you blocked.

This is a maximin: The maximum score over the damage distributions which minimize score for each blocking combination.

---

**Input:** The input will consist of two lists of 2-tuples, where each 2-tuple is of the form (Power, Toughness). The first list will contain the powers and toughnesses of each attacking creature (you opponent's creatures). The second list will contain the powers and toughnesses of each of your creatures.

Tuples and lists may be represented in any convenient format, such as:

```
[[2, 2], [3, 3]]
[[1, 4], [1, 1], [0, 1]]

```

**Output:** The output will consist of a series of 2-tuples, in the form (blocking creature, blocked creature) - that is, one of your creatures followed by one of their creatures. Creatures will be refered to by their index in the input lists. Indexes may be 0 or 1 indexed. Again, any convenient format. Any order is fine. For example, the optimal blocking scenario from above, given the above input, might be represented as:

```
[0, 0]    # 1/4 blocks 2/2
[1, 0]    # 1/1 blocks 2/2
[2, 1]    # 0/1 blocks 3/3

```

**Examples:**

```
Input:
[[2, 2], [3, 3]]
[[1, 4], [1, 1], [0, 1]]
Output:
[0, 0]
[1, 0]
[2, 1]

Input:
[[3, 3], [3, 3]]
[[2, 3], [2, 2], [2, 2]]
Output:
[1, 0]
[2, 0]
or
[1, 1]
[2, 1]

Input:
[[3, 1], [7, 2]]
[[0, 4], [1, 1]]
Output:
[1, 0]
or
[0, 0]
[1, 0]

Input:
[[2, 2]]
[[1, 1]]
Output:

(No output tuples).

```

Input and output may be via STDIN, STDOUT, CLA, function input/return, etc. Standard loopholes apply. This is code-golf: shortest code in bytes wins.

---

To clarify the spec and provide initial ideas, this pastebin provides a reference solution in Python. The `best_block` function is a sample solution to this challenge, and running the program will provide more verbose input and output.

# Answer
> 8 votes
# JavaScript (ES7),  ~~354~~  348 bytes

Takes input as `([attackers], [defenders])`.

```
(a,d,O,M)=>eval(`for(N=(A=a.push([,0]))**d.length;N--;)O=a[X='map'](([P,T],i)=>S-=((g=(n,l)=>n?l[X](([t,S],i)=>g(n-1,b=[...l],b[i]=[t-1,S])):m=l[X](([t,S])=>s+=t>0&&S,s=0)&&s>m?m:s)(P,l[n=0,i][X](m=([p,t])=>[t,p+t,n+=p])),n<T&&P+T)+(l[i]<1?T/2:-m),S=0,d[X]((x,i)=>l[(j=N/A**i%A|0)<A-1&&o.push([i,j]),j].push(x),o=[],l=a[X](_=>[])))&&S<M?O:(M=S,o)`)

```

Try it online!

## Less golfed and formatted

This code is identical to the golfed version, just without the `map` aliases and the `eval()` wrapping for readability.

```
(a, d, O, M) => {
  for(N = (A = a.push([, 0])) ** d.length; N--;)
    O =
      a.map(([P, T], i) =>
        S -=
          (
            (g = (n, l) =>
              n ?
                l.map(([t, S], i) => g(n - 1, b = [...l], b[i] = [t - 1, S]))
              :
                m = l.map(([t, S]) => s += t > 0 && S, s = 0) && s > m ? m : s
            )(
              P,
              l[n = 0, i].map(m = ([p, t]) => [t, p + t, n += p])
            ),
            n < T && P + T
          ) + (
            l[i] < 1 ? T / 2 : -m
          ),
        S = 0,
        d.map((x, i) =>
          l[
            (j = N / A ** i % A | 0) < A - 1 && o.push([i, j]),
            j
          ].push(x),
          o = [],
          l = a.map(_ => [])
        )
      ) && S < M ? O : (M = S, o)
  return O
}

```

## How?

### Initialization and main loop

The first thing we do is add a dummy attacking creature with an undefined power and a toughness of \\$0\\$. The `push` method returns the new number \\$A\\$ of attacking creatures, including this one.

```
A = a.push([, 0])

```

We are going to block this dummy creature instead of blocking no creature at all. This allows some simplifications in the code.

The number of combinations for the defending player can be expressed as \\$A^D\\$, where \\$D\\$ is the number of defenders. We use a *for* loop with the counter \\$N\\$ to iterate over all these possibilities.

```
for(N = (A = a.push([, 0])) ** d.length; N--;)

```

The score of the current iteration and the maximum score are stored in \\$S\\$ and \\$M\\$ respectively. Similarly, the current solution and the best solution are stored in \\$o\\$ and \\$O\\$.

At the end of each iteration, we test whether \\$M\\$ and \\$O\\$ need to be updated.

```
O = (...) && S < M ? O : (M = S, o)

```

### Building our defense

Below is the block of code which is executed at the beginning of each iteration. A new important variable in there is \\$l\\$, which holds a list of blockers for each attacker.

```
d.map((x, i) =>              // for each defender x at position i:
  l[                         //   update l[]:
    (j = N / A ** i % A | 0) //     j = index of the attacker that we're going to block
    < A - 1 &&               //     if this is not the 'dummy' creature:
    o.push([i, j]),          //       add the pair [i, j] to the current solution
    j                        //     use j as the actual index to update l[]
  ].push(x),                 //   push x in the list of blockers for this attacker
  o = [],                    //   initialize o to an empty list
  l = a.map(_ => [])         //   initialize l to an array containing as many empty lists
                             //   that there are attackers
)                            // end of map()

```

### Optimizing the attack

The decisions of the attackers are uncorrelated to each other. The global optimum for the attacking side is the sum of the local optima for each attacker.

We iterate on each attacker of power \\$P\\$ and toughness \\$T\\$ at index \\$i\\$.

```
a.map(([P, T], i) => ...)

```

To find the best decision for an attacker, we first build a new list derived from \\$l\[i\]\\$:

```
l[n = 0, i].map(m = ([p, t]) => [t, p + t, n += p])

```

Each entry in this list contains the toughness of the blocker, followed by its score (power + toughness). While building this list, we also compute \\$n\\$ which is the sum of the powers of all blockers. We'll use it later to test if the attacker is destroyed. (The fact that intermediate sums are stored as a 3rd entry for each blocker is just a golfing trick to save a few bytes. This 3rd entry is not used.)

We now call the recursive function \\$g\\$ with 2 parameters: the power \\$P\\$ of the current attacker and the list defined above. This function tries all possible ways of dispatching the damage points among the blockers.

```
(g = (n, l) =>            // n = remaining damage points; l = list of blockers
  n ?                     // if we still have damage points:
    l.map(([t, S], i) =>  //   for each blocker of toughness t and score S at index i:
      g(                  //     do a recursive call:
        n - 1,            //       decrement the number of damage points
        b = [...l],       //       create a new instance b of l
        b[i] = [t - 1, S] //       decrement the toughness of blocker i
      )                   //     end of recursive call
    )                     //   end of map()
  :                       // else:
    m =                   //   update the best score m (the lower, the better):
      l.map(([t, S]) =>   //     for each blocker of toughness t and score S:
        s += t > 0 && S,  //       add S to s if this blocker has survived
        s = 0             //       start with s = 0
      ) &&                //     end of map()
      s > m ? m : s       //     set m = min(m, s)
)                         //

```

### Updating the defender score

After each iteration on an attacker, we update the defender score with:

```
S -= (n < T && P + T) + (l[i] < 1 ? T / 2 : -m)

```

The left part subtracts the score of the attacker if it has survived. The right part subtracts half the toughness of the attacker if the attack was not blocked at all, or adds the best attacker score otherwise (which is the worst one from the defending side perspective).

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


title: Toasty, Burnt, Brûlée!

text:
# Question
Title: Toasty, Burnt, Brûlée!
It turns out that my toaster is a tad broken. It lost WiFi (You know, it's one of those newfangled smart toasters), and its been going bonkers! Since it no longer works, I've been having to hack into my breakfast's source code and run `Plate.bread.toastAs(3);` every morning. Will you help?

My toaster takes one input: the amount of time you want to toast your bread. This is written as `min:sec`, such as `5:45` or `0:40` (Up to `59:59`). It then returns a specific value for different levels of toastiness:

```
0:00-0:30 = Bread
0:31-1:00 = Warm Bread
1:01-2:00 = Toasty
2:01-3:30 = Burnt
3:31 and up = Brûlée (or Brulee)

```

But here's the catch: my toaster has a broken keyboard! Your code can't contain any semicolons or...colons. This might be harder than the toaster repairman said it would be...

Here are some test cases, so you can...test your cases?

```
0:00 = Bread
5:50 = Brulee or Brûlée
2:00 = Toasty
ChicknMcNuggets = Anything
-1:00 = Anything
0:60 = Anything
1 = Anything
60:00 = Anything
1:00:00 = Anything

```

# Answer
> 3 votes
# Python 2, ~~124~~  ~~118~~ 116

```
t=eval(input().replace("\x3A","."))
print["Bread","Warm Bread","Toasty","Burnt","Brulee"][sum([t>3.3,t>2,t>1,t>.3])]

```

Try it online!

-6 with thanks to @tsh and also thanks for tho TIO test cases.

-2 with a couple of cool tips from @BlackOwlKai

Throws a `ValueError` for invalid inputs that cannot be converted to a float. For numbers less than 0 it returns "Bread" because it is still bread. Guess if we are really strict on ensuring that the input is a valid time it could be done but for me the interesting bit was how to avoid the `:` in Python.

# Answer
> 3 votes
# T-SQL, 409 379 328 318 bytes

```
DECLARE @i varchar(9)DECLARE @a time='0'+CHAR(58)+@i DECLARE @ int=DATEPART(N,@a),@s int=DATEPART(S,@a)SELECT CASE WHEN @<1AND @s<31THEN'Bread'WHEN @<1OR @=1AND @s=0THEN'Warm Bread'WHEN @<2OR @=2AND @s=0THEN'Toasty'WHEN @<3OR @<4AND @s<31THEN'Burnt'ELSE'Brulee'END WHERE LEN(RIGHT(@i,LEN(@i)-CHARINDEX(CHAR(58),@i)))=2

```

*-30 bytes: removed* `AS` *keywords, combined* `DECLARE` *statements (thanks to BradC)*
*-51 bytes: changed declarations/where clause to take advantage of SQL's datetime functionality*
*-10 bytes: changed* `MINUTE` *to* `N` *and* `SECOND` *to* `S` (thanks to BradC)

Did you know that SQL can't natively split strings in any decent capacity? Don't let `STRING_SPLIT` fool you; it doesn't work for this. Or at least, I'm not smart enough to figure it out.

Different from BradC's table-based T-SQL solution.

Ungolfed:

```
-- Input variable
DECLARE @i varchar(9)

-- Time declarations (passes in as form "00:mm:ss")
-- CHAR(58) maps to ':'
DECLARE @a time = '0' + CHAR(58) + @i

-- Integer declarations
DECLARE @ int = DATEPART(N, @a),    -- minutes
        @s int = DATEPART(S, @a)    -- seconds

SELECT CASE
            WHEN @ < 1 AND @x < 31              -- 0:00 - 0:30
                THEN 'Bread'
            WHEN @ < 1 OR @ = 1 AND @x = 0      -- 0:31 - 1:00
                THEN 'Warm Bread'
            WHEN @ < 2 OR @ = 2 AND @x = 0      -- 1:01 - 2:00
                THEN 'Toasty'
            WHEN @ < 3 OR @ < 4 AND @x < 31     -- 2:01 - 3:30
                THEN 'Burnt'
            ELSE 'Brulee'                       -- 3:31 - 59:59
       END

-- Setting input as a time means that you only have to check if the seconds input is two characters, all other checks accounted for
WHERE LEN(RIGHT(@i, LEN(@i) - CHARINDEX(CHAR(58), @i))) = 2

```

# Answer
> 3 votes
# Java 8, 148 bytes

a lambda from `String` to `String`

```
t->{float n=new Float(t.replace("\72","."))\u003breturn n>3.3?"Brulee"\u003an>2?"Burnt"\u003an>1?"Toasty"\u003an>.3?"Warm Bread"\u003a"Bread"\u003b}

```

`\u003b` and `\u003a` are source-level Unicode escape sequences for `;` and `:` respectively.

Try It Online

## Ungolfed

```
t -> {
    float n = new Float(t.replace("\72",".")) \u003b
    return
        n > 3.3 ? "Brulee" \u003a
            n > 2 ? "Burnt" \u003a
            n > 1 ? "Toasty" \u003a
            n > .3 ? "Warm Bread" \u003a
            "Bread"
    \u003b
}

```

## Acknowledgments

# Answer
> 2 votes
# JavaScript (SpiderMonkey), 100 bytes

```
a=>'Bread,Warm Bread,Toasty,Burnt,Brulee'.split`,`[((t=a.replace(/\D/,'.'))>3.3)+(t>2)+(t>1)+(t>.3)]

```

Try it online!

---

# JavaScript (Node.js), 91 bytes

```
a=>[,b='Bread','Warm '+b,o='Toasty',o,u='Burnt',u,u][new Date([70,a])/-~18e5+1|0]||'Brulee'

```

Try it online!

# Answer
> 2 votes
# T-SQL, ~~143 155~~ 145 bytes

```
SELECT TOP 1b FROM i,
(VALUES(31,'Bread'),(61,'Warm Bread'),(121,'Toasty'),(211,'Burnt'),(1E4,'Brulee'))t(a,b)
WHERE a>DATEDIFF(s,0,'0'+CHAR(58)+v)

```

Line breaks are for readability only. Different method than Meerkat's variable-based SQL solution.

Input is taken via pre-existing table **i** with varchar field **v**, per our IO standards. That input table is cross-joined to an in-memory table **t** with our cutoff values (in seconds) and the desired labels.

The magic happens in the `WHERE` clause: `DATEDIFF` calculates the difference in seconds between midnight and our input (with an extra `0:` attached to the front), then returns the lowest matching label (via the `TOP 1`).

Invalid inputs either return an unpredictable value or throw an error:
`Conversion failed when converting date and/or time from character string.`

The question was a little vague, but if needed I can avoid these errors (and return nothing) by adding the following `LIKE` pattern to the `WHERE` clause, bringing the total bytes to **~~238 211~~ 201**:

```
AND RIGHT('0'+v,5)LIKE'[0-5][0-9]'+CHAR(58)+'[0-5][0-9]'

```

**EDIT**: My original shorter submission was failing for inputs over `24:00`, since I was treating it as `hh:mm`. Had to add the `'0'+CHAR(58)+` prefix, which added 12 bytes.

**EDIT 2**: Shaved 27 bytes from the `LIKE` in my alternate version

**EDIT 3**: Removed `ORDER BY` from both versions, as it proved unnecessary in testing. (SQL doesn't *guarantee* sort order will be maintained without an explicit `ORDER BY`, but it seemed to work fine for me in this specific case.)

# Answer
> 2 votes
# PHP, 96 bytes

```
<?=[Bread,"Warm Bread",$t=Toasty,$t,$u=Burnt,$u,$u,Brulee][min(7,2*$argn+substr($argn,-2)/30)]?>

```

requires PHP 5.5 or later. Run as pipe with `-nF` or try it online.

# Answer
> 2 votes
# 05AB1E, ~~43~~ 42 bytes

```
þ30тx330)ć‹O„©Ãº™D#θ‚R.•liSÕô6>Āµ·•6ôÀ«™sè

```

Try it online or verify some more test cases.

**Explanation:**

```
þ                # Leave only the digits of the (implicit) input
                 #  i.e. "1:15" → 115
 30              # Push 30
   т             # Push 100
    x            # Pop and push 100 and 100 doubled (200)
     330         # Push 330
        )        # Wrap the stack into a list: [inputDigits,30,100,200,330]
         ć       # Pop and push the head and rest of array as separated items to the stack
          ‹      # Check for each if its smaller than the head (1=truthy, 0=falsey)
                 #  i.e. [30,100,200,330] and 115 → [1,1,0,0]
           O     # Take the sum of this
                 #  i.e. [1,1,0,0] → 2
„©Ãº™            # Push string "warm bread"
     D#          # Duplicate it, and split it by spaces: ["warm","bread"]
       θ         # And only leave the last element: "bread"
        ‚R       # Pair them into a list, and reverse that list: ["bread","warm bread"]
.•liSÕô6>Āµ·•    # Push string "bruleetoastyburnt"
             6ô  # Split into parts of size 6: ["brulee","toasty","burnt"]
               À # Rotate it once towards the left: ["toasty","burnt", "brulee"]
«                # Merge both lists together:
                 #  ["bread","warm bread","toasty","burnt","brulee"]
 ™               # Titlecase each word: ["Bread","Warm Bread","Toasty","Burnt","Brulee"]
  s              # Swap so the number is at the top of the stack again
   è             # Index it into the list (and output implicitly)
                 #  i.e. 2 → "Toasty"

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*) to understand why `„©Ãº™` is `"warm bread"` and `.•liSÕô6>Āµ·•` is `"bruleetoastyburnt"`.

`þ30тx330)ć` can alternatively be `30тx)DOªsþ` for the same byte-count: Try it online.

# Answer
> 1 votes
# Javascript(ES6+), 180 bytes

Node.js(180 bytes)

```
let f=(s,i=s.split("\u{3a}"),j=i[0]*60+1*i[1],k="Bread",l=assert(new RegExp("^(.|[0-5].)\u{3a}[0-5].$").test(s)))=>eval("(j<31)?k\u{3a}(j<61)?'Warm '+k\u{3a}(j<121)?'Toasty'\u{3a}(j<211)?'Burnt'\u{3a}'Brulee'")

```

Browser(188 bytes):

```
let f=(s,i=s.split("\u{3a}"),j=i[0]*60+1*i[1],k="Bread",l=console.assert(new RegExp("^(.|[0-5].)\u{3a}[0-5].$").test(s)))=>eval("(j<31)?k\u{3a}(j<61)?'Warm '+k\u{3a}(j<121)?'Toasty'\u{3a}(j<211)?'Burnt'\u{3a}'Brulee'")

```

Gotta use those unicode escape sequences :-) just a big chain of ternary operators, with variables defined by default parameters. Also a one-liner, so no semicolon-hungry js

# Answer
> 1 votes
# Perl 6, ~~86 79~~ 67 bytes

*-4 bytes thanks to nwellnhof! -12 bytes by porting tsh's solution*

```
{<<Bread'Warm Bread'Toasty Burnt Brulee>>[sum S/\D/./X>.3,1,2,3.3]}

```

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 97 bytes

```
.+(..)
$*1#$1$*
+`1#
#60$*
#1{211,}
Brulee
#1{121,}
Burnt
#1{61,}
Toasty
#1{31,}
Warm #
#1*
Bread

```

Try it online! Link includes test cases. Explantion:

```
.+(..)
$*1#$1$*

```

Convert the minutes and seconds to unary.

```
+`1#
#60$*

```

Multiply the minutes by 60 and add to the seconds.

```
#1{211,}
Brulee
#1{121,}
Burnt
#1{61,}
Toasty

```

Decode the seconds into the toastiness.

```
#1{31,}
Warm #

```

Decode Warm Bread by noting that `#` (for 0:00) decodes to `Bread`.

```
#1*
Bread

```

If we don't have a toastiness yet then the bread is still cold.

# Answer
> 1 votes
# C (gcc), 130 bytes

```
f(a){if(*strchr(a,58)=48,a=atoi(a),a=(int*[]){"Bread","Warm Bread","Toasty","Burnt","Brulee"}[(a>30)+(a>1e3)+(a>2e3)+(a>3030)]){}}

```

Try it online!

# Answer
> 1 votes
# Japt, 48 bytes

```
`BÎ%
W‡m BÎ%
To†ty
B¨›
BrÔ‡`·g[30LLÑ,330]è<Ur58d

```

Try it online!

Saved 5 bytes by actually reading the tips...

Explanation:

```
`BÎ%...BrÔ‡`·                       Compressed array of possible outputs
             g                      Get the one at the index given by...
                         è          The number of items...
              [30LLÑ,330]           From the list [30,100,200,330]...
                          <Ur58d    Which are less than the input without ":"

```

An extra byte could be saved by outputting in all lower case.

# Answer
> 1 votes
# Snap! 4.2, 257 251 bytes

Minified the text version some more.

I haven't found any answers in Snap!, a visual programming language similar to Scratch, so I'll use scratchblocks2 syntax, pretending that Snap! exclusive blocks are valid in scratchblocks2.

**Try it online!** (click the button with the two arrows to see the code)

```
when gf clicked
ask[]and wait
set[l v]to(split(answer)by(unicode(58)as letter
set [t v]to(((item(1 v)of(l))*(60))+(item(2 v)of(l
if<(t)<[31
say[Bread
else
if<(t)<[61
say[Warm Bread
else
if<(t)<[121
say[Toasty
else
if<(t)<[211
say[Burnt
else
say[Brulee

```

# Answer
> 1 votes
# , ~~127~~ 122 bytes

```
function(t)cut((x=eval(parse(t=t)))[1]*60+tail(x,1),30*c(0:2,4,7,Inf),c("Bread","Warm Bread","Toasty","Burnt","Brulee"),T)

```

Try it online!

Returns a `factor` with the appropriate level.

-5 bytes thanks to JayCe.

# Answer
> 1 votes
# Jelly, ~~43~~ ~~41~~ 40 bytes

```
fØD~~ḌH“Ð2dʠ‘<Sị“¡Ḳḋ\ḞvṾƤSİƓƥeF½ÞØ+®°»Ỵ¤

```

Try it online!

### Explanation (old)

`“¡Ḳḋ\ḞvṾƤSİƓƥeF½ÞØ+®°»` is the compressed string `Warm Bread\nToasty\nBurnt\nBrulee\nBread`, found by the compression optimizer.

```
fØD                               Filter out the non-digits (i.e. colon) from input
   ~~                             Use binary NOT twice to convert to digit list
     Ḍ
      HḞ                        Halve and floor. Now we have "01:45" -> 72.
        “Ç1cƥ‘                    The array [14,49,99,164]
              <                   Vectorized less than
               S                  Sum
fØD~~ḌHḞ“Ç1cƥ‘<S                How many threshold times is input less than?
                                           (0 -> Bread, 4 -> Brulee.)
                ị               Index (note 0ị gives the last list item) into
                       ¤        the new dyadic link given by
                 “...»            The long string, decoded and
                      Ỵ           split by newlines.

```

Inspired by Kamil Drakari's answer.

-2 bytes using snippet `~~Ḍ` from Dennis.

# Answer
> 1 votes
# Runic Enchantments, 118 bytes

```
\>`tttt`,kw,kw,kw,ki
\uqn.3X)?\ . 1C)?\.2C)?\'Ŋ)?\"Brulee"
\D"daerB"L" mraW"/
$L"ytsaoT"L?9"tnruB"L?aL?3 F/

```

Try it online!

Utilizes some unprinting ASCII characters (STX, EOT, SOH, STX, VT, SOH, STX, DC2, SOH, and STX in that order) on the first line, which is reading in a sequence of bytes in the order that they're going to be needed on the stack. 3 divide (`'t'/2` equals `:`) and reflective-write operations are then performed. This puts 3 `:` (duplicate) commands where there are currently `.` (NOP) in order to non-destructively compare the input with the time thresholds. A fourth `:` is left on the stack before reading input.

Time is read in as a string, then split on `:`, and concatenated back into a string. As values above `59:59` do not have any specification on output, values like `1:00:00` will have undefined (but deterministic) output. This string is then converted to a number and compared against 30, 100, 200, and 330 (the byte value of `Ŋ`). `"Bread"` (line 3, executing RTL) is used twice, both for `Bread` and `Warm Bread` results, saving at least 5 bytes.

Saves 1 byte by not having a classic terminator command (`;`) by using `F`izzle on the last line instead. This convinces the parser that the program is guaranteed to terminate without causing it to do so immediately (and, more importantly, not touching the stack). Valid inputs will leave the stack empty so that when it loops around and touches a `w` the IP is terminated for performing an illegal action.

# Answer
> 0 votes
# Javascript, ~~115~~ 101 bytes

*-6 from tsh*

```
d=>[b="Bread","Warm "+b,a="Toasty",a,c="Burnt",c,c][~~(parseInt(d)*1.999+d.slice(-2)/30.1)]||"Brulee"

```

# Answer
> 0 votes
## JavaScript (ES6), 171 bytes

```
(x,y=Math.ceil(x.split(/\D/).reduce((a,b)=>(+a)*60+(+b))/30))=>["Bread","Bread","Warm Bread","Toasty","Toasty","Burnt","Burnt","Burnt","Brulee","Brulee","Brulee"][y>8?8:y]

```

Run some test cases with this Stack Snippet:

```
var f=(x,y=Math.ceil(x.split(/\D/).reduce((a,b)=>(+a)*60+(+b))/30))=>["Bread","Bread","Warm Bread","Toasty","Toasty","Burnt","Burnt","Burnt","Brulee","Brulee","Brulee"][y>8?8:y]

var result = document.getElementById("result");
["0:00", "0:30", "0:31", "1:00", "1:01", "2:00", "2:01", "2:30", "2:31", "3:00", "3:01", "3:30", "3:31", "4:00", "4:01", "4:30", "4:31", "5:00", "6:00"].forEach(x => result.innerHTML += `${x}: ${f(x)}\n`);
```

```
<pre id="result"></pre>
```

# Answer
> 0 votes
## F#, 177 bytes

```
let t i=
 let s=i.ToString().Split(char 58)
 let m=int s.[0]*60+int s.[1]
 if m<31 then"Bread"elif m<61 then"Warm Bread"elif m<121 then"Toasty"elif m<211 then"Burnt"else"Brulee"

```

Try it online!

Thanks to Jo King for straightening out my, umm, needlessly literal interpretation of the challenge...

F# is fairly okay for functions without semi-colons or colons. The only real issue was that I couldn't do `i.Split` directly without a type annotation - F# would not have been able to deduce the type of `i` based on the method call. That would have required defining the type directly in the function, like `let t (i:string)=` which would have been against the rules.

But I could easily get by it by `i.ToString()`, which then allowed me to call `Split` on it. Then `char 58` is a colon character, and after that it's straight-forward.

---
Tags: code-golf, restricted-source
---