title: Cops: Make a regex - Make a snake

text:
# Question
Title: Cops: Make a regex - Make a snake
This is the cop's thread. The robber's thread is here.

---

Write a code that takes an input `n` and creates a n-by-n "snake matrix".

A snake matrix is a matrix that follows this pattern:

3-by-3:

```
1  2  3
6  5  4
7  8  9

```

and 4-by-4:

```
1   2   3   4
8   7   6   5
9   10  11  12
16  15  14  13

```

The exact output format is optional. You may for instance output `[[1 2 3],[6 5 4],[7 8 9]]`, or something similar.

You must provide the language name, and a regex that fully matches your code. You can choose how detailed your regex should be. In the extreme, you can write a regex that matches every possible string, in which case it will be very easy to crack your code. You must also provide the output for `n=4`, so that robbers know the exact format you have opted for.

You may use one of the regex-flavors that are available on regex101.com, or the Ruby flavor.

* PCRE (PHP)
* Javascript
* Python
* Golang
* Ruby

You must specify which one you are using.

Notes:

* You must support any reasonably large `n`. You may assume it won't overflow the datatype or memory. If the default datatype is 8-bit signed integers, then you can assume `n<=11`, if it's unsigned 8-bit integers, then you can assume `n<=15`.
* The robbers have to match the submission's output format, except leading/trailing spaces and newlines, since that might have been stripped away by the SE formatting.

**Winning criterion:**

The winner will be the uncracked submission with the shortest regex, measured in number of characters.

If your post has remained uncracked for 7 days, then you may post the intended solution and mark your submission as safe.

# Answer
> 9 votes
# 05AB1E, Cracked by mbomb007

Hopefully fun to crack and not too obvious.

**Regex (PCRE):**

```
^\w*[+\-*\/%]*\w*.{0,2}$

```

**Output n=4:**

```
[[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]]

```

**Original solution**

```
UXFXLNX*+NFR}ˆ

```

# Answer
> 8 votes
# Python 2, length 62, cracked

### Regex (PCRE)

```
^while ((?=\S)[1di\W]|an|eval|nput|nt|or|pr){55}s(?1){45}n...$

```

### Sample output

```
   1    2    3    4
   8    7    6    5
   9   10   11   12
  16   15   14   13

```

# Answer
> 7 votes
# Jelly, length 6, cracked

### Regex (PCRE)

```
^.{9}$

```

### Sample output

```
 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13

```

# Answer
> 6 votes
# R, length 14 Cracked by plannapus

I hope I got this regex right. What I trying to say is 77 characters excluding `<space>`, `#`, `;` and `[`. I tested it here

**Regex**

```
^[^ #;\[]{77}$

```

**Sample output n= 4**

```
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13

```

# Answer
> 6 votes
# 05AB1E, Cracked by Value Ink

Lets kick it up a notch :)
Hopefully a nice puzzle.

**Regex (PCRE)**

```
^\w*..\w*$

```

**Output n=4**

```
[[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]]

```

# Answer
> 6 votes
# \>\<\>, length 49, Cracked by Aaron

### Regex (Javascript)

```
^.{7}\n.{12}\n\?.{6};[^v^]{27}(\n.{13}:&.{2}){2}$

```

### Sample output (n=4)

```
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13

```

Formatting is a bit weird, but checking for number length would have made it a lot longer. Might have gone a bit overboard on the regex, not sure!

Edit: Also I forgot to mention, I use the initial stack (-v flag) for input, not the usual fish input. Sorry!

### Original Code:

```
<v1*2&:
 >:{:}=?v:1+
?^{r0}v;>&:&[r]{&:&2*+}::&:::&*@+@(
+:}=?v>n" "o&:&{1
0~{oa<^v?)*&::&:}

```

Aaron's is a lot simpler! The complexity of my original code is based around the idea of using `n[r]` every n-th number to flip that segment (row), then printing all numbers at once at the end

# Answer
> 5 votes
# Ohm, cracked

Also my first Cops and Robbers challenge, so tell me if there are issues with this pattern (especially since this is a fairly unknown language).

### Regex (PCRE)

```
^\S{6}\W{0,3}\w$

```

### Output (n = 4)

```
[[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]]

```

# Answer
> 5 votes
# Ruby \[cracked\]

First Cops and Robbers challenge. Hope I didn't make this too easy.

EDIT: replaced `\g<1>` with `(?1)` because they're evidently equivalent in PCRE.

### Regex(PCRE)

```
^(\W?\W\w){4}..(?1){2}[(-=Z-~]*(?1){5}\w*(?1)(.)\2$

```

### Output (n=4)

```
[[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]]

```

(Returns an array of arrays. It's a lambda, BTW, but maybe that gives away too much?)

# Answer
> 5 votes
# PHP, 221 Bytes (Cracked)

I hope it is difficult enough.

## Regex (PCRE): 16 Bytes

```
^[^\s/\#6]{221}$

```

No space, No comments, no use of base64\_decode. Have Fun.

## Output

```
  1  2  3  4
  8  7  6  5
  9 10 11 12
 16 15 14 13

```

## Original Code

```
$w=$argv[1];$s="";$r=range(1,$w**2);for($i=0;$i<$w;$i++)if($i%2)array_splice($r,$i*$w,$w,array_reverse(array_slice($r,$i*$w,$w)));foreach(($r)as$v)$s.=str_pad($v,$l=strlen(max($r))+1,"\x20",0);echo(chunk_split($s,$l*$w));

```

# Answer
> 5 votes
# dc, Regex length 12 Cracked by seshoumara!

```
^[^# !]{59}$

```

This regular expression is simple enough that I don't think the flavor of regex matters -- it should work across the board. (Note the space after the # in the regex.)

I've tested all four flavors at regex101.com (PCRE/PHP, Javascript, Python, and Golang), as well as the Ruby version at rubular.com. The dc program matches the regex in all five regex versions.

---

The dc program takes its input on stdin and puts its output on stdout.

Sample output for input 4 (there's a trailing space at the end of each line):

```
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13

```

---

# Original code (added after being cracked)

This has been cracked by @seshoumara. Here's my intended code:

```
?sd[AP]s+0[dddld/2%rld%2*1+ldr-*+1+n2CP1+dld%0=+dvld>l]dslx

```

Explanation:

```
?sd      Input number and store it in register d.
[AP]s+   Macro that prints a newline. The macro is stored in register '+'.
0        Push 0 on the stack, initializing a loop.  (The top of the stack is the index variable.  It will go up to d^2-1.)
[        Start a macro definition.  (The macro will be stored in register l.)
ddd      Push 3 copies of the loop index variable on the stack, so they'll be available later. I'll call this number i.
ld/      Divide the last copy of i by d (integer division); this computes the row of the square that we're in (starting with row 0).
2%       Replace the row number with 0 if the row number is even, with 1 if the row number is odd.
r        Swap the top two items on the stack, so the top item is now the next to last copy of i, and the second item on the stack is the row number mod 2.
ld%      Compute i mod d; this goes from 0 to d-1. It is the column in the square that the next number will be placed in.  (The leftmost column is column 0.)
2*1+     Top of the stack is replaced with 2*(column number)+1.
ldr      Inserts d as the second item on the stack.
-        Computes d-2*(column number)-1.
*        The second item on the stack is the row number mod 2, so multiplying yields 0 if the row number is even, and d-2*(column number)-1 if the row number is odd.
+        Add to the remaining copy of i. The sum is i itself in even-numbered rows, and it's i+d-2*(column number)-1 in odd-numbered rows.

```

The sum at the top of the stack now is the next number we want to print:

* It's easy to see that that's correct if the row number is even, since then the sum is just i.
* For odd-numbered rows, notice that i = d\*(i/d)+(i%d) = d * (row number) + column number. It follows that the sum i+d-2\*(column number)-1 is d * (row number) + column number + d - 2\*(column number)- 1 = d * (row number + 1) - column number - 1, which is the number we want to put in the indicated row and column to ensure that we're counting backwards in the odd-numbered rows.

Returning to the explanation now:

```
n        Print the desired number for the current row and column.
2CP      Print a space.  (2C, which is computed by dc as 20 + 12, is 32, the ASCII code for a space.)
1+       The original copy of i is at the top of the stack; add 1 to it.
dld%0=+  If (the incremented value of) i is a multiple of d, call the macro at register '+', which prints a newline.
dvld>l   If d > sqrt(i) (in other words, if i < d^2), then go back to the top of the loop by calling macro l again.
]dslx    End the macro definition, store the macro in register l, and execute it.

```

# Answer
> 5 votes
# QBasic, regex length 10 (cracked)

### Regex

Should work in any regex flavor, but we'll call it Python flavor.

```
([A-Z]+.)+

```

**NOTE:** My solution uses unformatted QBasic; after formatting, the code doesn't match the regex due to added spaces. (But I *can* tell you that that's the only change that makes a difference. `([A-Z]+ ?. ?)+` still works on the formatted version.)

For testing purposes, I used QB64 with code formatting turned off (under Options \> Code layout). If you don't want to download something, you can also run QBasic online at archive.org (but there you can't turn formatting off).

### Sample output

```
 1  2  3  4
 8  7  6  5
 9  10  11  12
 16  15  14  13

```

# Answer
> 5 votes
# C# net46 (Cracked)

(http://ideone.com/ works)

## Regex PCRE flavor length 58 tested at regex101

```
^sta((?![\d%bh\/]|==|if|(\[.*){4}|(i.*){6}).){142}urn....$

```

Only the method is regexed. Method returns a 2d int\[,\] array (int\[4,4\]) for an input n=4. If printed looks like this:

```
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13

```

This is my first entry into anything like this, let me know if I did anything wrong. Not trying to win by regex length for sure, I'm just interested to see how well I did at preventing cracking :)

Original code:

```
static int[,]g(int n){int l,j,k=n-n,c,s;var _=new int[n,n];var d=n!=n;c=k;c++;s=k;for(l=k;l<n;l++){for(j=k;j<n;j++){_[l,d?n-j-c:j]=++s;}d=!d;}return _;}

```

# Answer
> 5 votes
# Bash, regex length 38, cracked (@kennytm)

```
^sort -n <[1adegnopqrstx$\-*()|'; ]+$

```

Input:

```
n=4; <command>

```

Output:

```
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13

```

# Answer
> 5 votes
# Python 3, 55 bytes (Cracked)

PCRE / Python / Golang flavor.

```
def [triangles=(1,SNAKE)]{27}:print[]SNAKE(--:>or[]{48}

```

*(Be reminded that Full match is required. Assume `^` and `$` when testing.)*

Sample output:

```
[1, 2, 3, 4]
[8, 7, 6, 5]
[9, 10, 11, 12]
[16, 15, 14, 13]

```

---

Original solution:

```
def r(N,S=1,A=1,K=range,E=list):print(E(K(S,S+N))[::A])or(S+N>N*N)or(r(N,S+N,-A,K,E))

```

Should have trimmed 4 bytes :p

# Answer
> 5 votes
# PHP

I hope this will be a fun one! :D

### Output (n=4)

```
[[1,2,3,4],[8,7,6,5],[9,10,11,12],[16,15,14,13]]

```

---

### Level 1: PCRE (length=17) (Cracked by Jörg Hülsermann)

```
^<[^'"\d{vV;<$]+$

```
* No single or double quotes so... no strings!
* No digits!
* No `{` so... no anonymous functions!
* No `v` so... no `eval()`!
* No `;` so... it must be a single statement!
* No `<` so... no `Heredoc` nor multiple PHP blocks!
* The big one! No **$** so... good luck defining variables! \>:D

---

@JörgHülsermann had an interesting approach, but it's not what I had in mind :). Therefore, I'm introducing a new level of difficulty (I promise I have the code that fits this and I'm not just messing with you):

### Level 2: PCRE (length=23) (Cracked by Jörg Hülsermann)

```
^<[^'"\d{v;<$_~|&A-Z]+$

```
* All the restrictions of **Level 1**
* New on this level: none of these `_~|&A-Z`! :)

---

Have fun!

---

### THE ORIGINAL SOLUTION

So, forbidding the `$` meant the variables couldn't be accessed the regular way, but that doesn't mean they can't be used at all! You can still use `extract()/compact()` to import/export variables into the current scope. :)

```
$i = 1;
// can be written as
extract(['i' => 1])

echo $i;
// can be written as
echo compact('i')['i'];

```

However, there's a gotcha: `compact('x')['x']++` wouldn't work because variables in PHP are passed by value... with one exception! Objects.

```
$x = (object) ['i' => 1];
// is
extract(['x' => (object) ['i' => 1]]);

// and
compact('x')['x']->i++;
// works just fine!

```

The rest is easy.

* Numbers `0` and `1` are easily generated by converting `false` and `true` to `int` by prepending them with the `+` sign
* Use `and` and `or` since `&` and `|` are forbidden
* To work around the forbidden quotes, just use undefined constants, which are treated as strings
* To suppress the notices generated by using undefined constants, just use `@`
* The forbidden letter `v` can be generated by using `chr(ord('u') + 1)`, which translates to `@chr(ord(u) + true)` using the above workarounds
* The underscore is similar to the above: `chr(ord('a') - 2)` which translates to `chr(ord(a) - true - true)`
* Calling functions which contain forbidden characters can be done by taking advantage of PHP's `callable` type, which can be a string containing the name of the function. So, you can concatenate undefined constants and single character strings generated by `ord()` to build the name of the function and invoke it like this: `array_reverse()` becomes `(a.rray.chr(ord(a)-true-true).re.chr(ord(u)+true).erse)()` (`array` is a language construct, that's why it's split into the undefined constants `a` and `rray`)
* Take advantage of the fact that, when it comes to conditional and loop constructs, the curly brackets are optional if the construct applies just to the immediately following statement. This means you can do stuff like: `if ($n = $argv[1] and $i = 0) while ($n > $i++ and do_some and other_stuff or exit)`

The logic in human readable code would be:

```
if (
    $x = (object) [
        'result' => [],
        'i' => 0
    ]

    and

    define('n', $argv[1])

    and

    define('un', '_')

    and

    // create the initial set which we'll loop through
    define('segments', array_chunk(range(1, pow(n, 2)), n))
) while (
    // store each odd segment as-is and increment the "pointer"
    ($x->result[] = @segments[$x->i++])

    and

    // store each even segment reversed and increment the "pointer"
    ($x->result[] = @array_reverse(segments[$x->i++]))

    and

    // check if we need to break out of the loop
    n > $x->i

    or

    // exit and output the result if the above is false
    die(json_encode(
        // if n is odd, the above would have copied a NULL entry
        // from the segments, so it needs to be filtered out
        array_filter($x->result)
    ))
)

```

And the unfriendly version that matches the regex:

`<?php if (@extract([x=>(object)[s=>[],i=>+false]])and@define(n,compact(arg.chr(ord(u)+true))[arg.chr(ord(u)+true)][+true]?:+true)and@define(un,chr(ord(a)-true-true))and@define(s,(a.rray.un.chunk)(range(+true,pow(n,true+true)),n)))while((@compact(x)[x]->s[]=s[@compact(x)[x]->i++])and(@compact(x)[x]->s[]=(a.rray.un.re.chr(ord(u)+true).erse)(s[@compact(x)[x]->i++]))and(n>@compact(x)[x]->i)or(@die((json.un.encode)((a.rray.un.filter)(@compact(x)[x]->s)))))?>`

# Answer
> 4 votes
# JavaScript (Cracked)

First time doing a Cops and Robbers challenge, hopefully doing it right.

### Regex (JavaScript)

```
^.*(\.\w+\(.*\)){4}$

```

### Output

An array equal to:

```
[[1,2,3,4],[8,7,6,5],[9,10,11,12],[16,15,14,13]]

```

# Answer
> 4 votes
# Röda 0.12, length 19 (Cracked by @KritixiLithos)

PCRE:

```
^{(\|[^\/#\s]*){8}$

```

Sample output (n=4):

```
[1, 2, 3, 4][8, 7, 6, 5][9, 10, 11, 12][16, 15, 14, 13]

```

Original code:

```
{|n|seq(0,n-1+n%2)|push([{|i|seq(n*i+1,n*i+n)}(_)],[{|j|seq(n*j+n,n*j+1,step=-1)}(_)])|head(n)}

```

Try it online!

# Answer
> 4 votes
# Swift, regex 25 (Cracked)

Right, let's see if I've got the hang of this. This is my first cops and robbers post, so lemme know if I've messed up!

## Regex

*I used javascript flavour on regex101.com*

```
^.{21}print[^/]{49}o.{7}$

```

## Sample Output

```
[1, 2, 3, 4]
[8, 7, 6, 5]
[9, 10, 11, 12]
[16, 15, 14, 13]

```

## Original Code

```
(0..<n).forEach{i in print((0..<n).map{i%2>0 ?(i+1)*n-$0 :i*n+$0+1},separator:",")}

```

# Answer
> 4 votes
# MATL, length 12 (safe)

## Regex

Uses Python flavour:

```
(\w{3}\W){5}

```

## Example output

For `n=4`:

```
 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13

```

---

### Solution

```
txU:GeG:oEq*S5M*TTx!

```

To see how this works, consider input `n=4`.

```
tx   % Implicit input n, duplicate, delete. So this does nothing
     % STACK: 4
U    % Square
     % STACK: 16
:    % Range
     % STACK: [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16]
Ge   % Reshape as an n-row array in column major order
     % STACK: [1  5  9 13;
               2  6 10 14;
               3  7 11 15;
               4  8 12 16]
G:   % Push range [1 2 ... n]
     % STACK: [1  5  9 13;
               2  6 10 14;
               3  7 11 15;
               4  8 12 16]
               [1 2 3 4]
o    % Modulo 2
     % STACK: [1  5  9 13;
               2  6 10 14;
               3  7 11 15;
               4  8 12 16]
              [1  0  1  0]
Eq   % Times 2, minus 1 (element-wise)
     % STACK: [1  5  9 13;
               2  6 10 14;
               3  7 11 15;
               4  8 12 16]
              [1 -1  1 -1]
*    % Multiply (element-wise with broadcast)
     % STACK: [1 -5  9 -13;
               2 -6 10 -14
               3 -7 11 -15
               4 -8 12 -16]
S    % Sort each column
     % STACK: [1 -8  9 -16;
               2 -7 10 -15;
               3 -6 11 -14;
               4 -5 12 -13]
5M   % Push [1 -1 1 -1] again
     % STACK: [1 -8  9 -16;
               2 -7 10 -15;
               3 -6 11 -14;
               4 -5 12 -13]
              [1 -1  1  -1]
*    % Multiply (element-wise with broadcast)
     % STACK: [1  8  9  16;
               2  7 10  15;
               3  6 11  14;
               4  5 12  13]
TTx  % Push [true true] and delete it. So this does nothing
!    % Transpose. Implicitly display
     % STACK: [ 1  2  3  4;
                8  7  6  5;
                9 10 11 12;
               16 15 14 13]

```

# Answer
> 4 votes
# C – regex of 42 characters in length – cracked

Javascript regex as used in regex101.

```
^[-h<=*c+m?{printf("\/a: %d\\',o);}]{137}$

```

Guessing this will be trivial...

```
> main 4
1   2   3   4
8   7   6   5
9   10  11  12
16  15  14  13
>

```

Output is tab-delimited with `\n` after each line.

My solution, here integers 0 - 2 were obtained via `t-t`, `t/t`, and `t`:

```
main(int t,char**a){int o=t-t,i=t/t,m,n,h=atoi(*(a+i));for(m=o;m<h;m++)for(n=o;n<h;n++)printf("%d%c",m*h+(m%t?h-n:n+i),n<h-i?'\t':'\n');}

```

# Answer
> 4 votes
# PHP 7 (Safe)

## Original Code

```
for($z=0,$q="";$z<($x=$argv[1])**2;){$w=($d=intdiv($z,$x))%2?($d+1)*$x-$z%$x:($z+1);for($f=0;$f<(log10($x**2)^0)-(log10($w)^0);$f++)$q.="\x20";$q.=++$z%$x?"$w\x20":"$w\n";}print(rtrim($q));

```

Second Try

## Regex (PCRE): 29 Bytes

```
^[^A-Z#\/\s\>busy_heck]{189}$

```

No space, No comments, no use of base64\_decode.

Many functions are not allowed! underscore

## Output n=11

```
  1   2   3   4   5   6   7   8   9  10  11
 22  21  20  19  18  17  16  15  14  13  12
 23  24  25  26  27  28  29  30  31  32  33
 44  43  42  41  40  39  38  37  36  35  34
 45  46  47  48  49  50  51  52  53  54  55
 66  65  64  63  62  61  60  59  58  57  56
 67  68  69  70  71  72  73  74  75  76  77
 88  87  86  85  84  83  82  81  80  79  78
 89  90  91  92  93  94  95  96  97  98  99
110 109 108 107 106 105 104 103 102 101 100
111 112 113 114 115 116 117 118 119 120 121

```

## Output n=4

```
 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13

```

## Output n=3

```
1 2 3
6 5 4
7 8 9

```

# Answer
> 4 votes
# Jelly, length 14 cracked

cracked by Dennis

```
[^/P-`mvḊ-ṫ€]*

```

Python regex.

Added `m` back in again after I let it slip.

`/` (reduce quick);
from `P` (product) to ``` (monad from dyad quick);
`m` (modulo indexing);
`v` (eval dyad);
from  (dequeue) to  (tail); and
(for each quick)

For an input of `4` mine outputs:

```
 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13

```

...because I formatted a list of lists as a grid with `G`.

# Answer
> 4 votes
# Jelly, length 17 (safe)

```
[^/P-`mvÇ-ıḃ-ṫ€]*

```

Python regex.

Tightening the knot, this bans some more useful things, for your aid here are the banned bytes:

```
/PQRSTUVWXYZ[\]^_`mvÇÐÑ×ØÞßæçðñ÷øþĊċĖėĠġİıḃḄḅḊḋḌḍḞḟḢḣḤḥḲḳḶḷṀṁṂṃṄṅṆṇṖṗṘṙṚṛṠṡṢṣṪṫ€

```

*just under a third of them!*

For an input of `4` mine outputs:

```
 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13

```

...because I formatted a list of lists as a grid with `G`.

### A solution:

```
’:2o1
Ḃ¬aẋ@0
’r0;0ẋ$ẋ1Ŀ¬0¦;2ĿÆ¡œ?⁸²¤s⁸G

```

**Try it online!** / **regex101**

The main trick here is to index into a lexicographically sorted list of the permutations of the natural numbers up to **n<sup>2</sup>** (using `œ?` to avoid building the list of length **n<sup>2</sup>!**), and to split the result into chunks of length **n**. The aforementioned index is found by forming its representation in the factorial number system which is formulaic since the "unsliced" snake is created by permuting elements in a prescribed manner (this may be readily converted to a number with `Æ¡`).

The solution I present uses `Ŀ` to reference previous links as monads (replacing `Ñ` and `Ç`), but multiple `$` in a row could be employed instead to "inline" these helper functions. It also uses `r` since  and `R` are banned.

```
’:2o1 - Link 1, periodic repetitions in the factorial base representation: n
’     - decrement n
 :2   - integer divide by 2
   o1 - or 1 (keep one period in the cases n=1 and n=2)

Ḃ¬aẋ@0 - Link 2, n zeros if n is even, else an empty list: n
Ḃ      - mod 2
 ¬     - not
   ẋ@0 - 0 repeated n times
  a    - and

’r0;0ẋ$ẋ1Ŀ¬0¦;2ĿÆ¡œ?⁸²¤s⁸G - Main link: n                    e.g. 6
’r0                        - inclusive range(n-1, 0)              [5,4,3,2,1,0]
    0ẋ$                    - 0 repeated n times                   [0,0,0,0,0,0]
   ;                       - concatenate (makes one "period")     [5,4,3,2,1,0,0,0,0,0,0,0]
        1Ŀ                 - call link 1 as a monad               2
       ẋ                   - repeat list                          [5,4,3,2,1,0,0,0,0,0,0,0,5,4,3,2,1,0,0,0,0,0,0,0]
           0¦              - apply to index 0 (rightmost index):
          ¬                -     not (make the last 0 a 1)        [5,4,3,2,1,0,0,0,0,0,0,0,5,4,3,2,1,0,0,0,0,0,0,1]
              2Ŀ           - call link 2 as a monad               [0,0,0,0,0,0]
             ;             - concatenate                          [5,4,3,2,1,0,0,0,0,0,0,0,5,4,3,2,1,0,0,0,0,0,0,1,0,0,0,0,0,0]
                Æ¡         - convert from factorial base          45461852049628918679695458739920
                      ¤    - nilad followed by link(s) as a nilad
                    ⁸      -     left argument, n                 6
                     ²     -     square                           36
                  œ?       - lexicographical permutation lookup   [1,2,3,4,5,6,12,11,10,9,8,7,13,14,15,16,17,18,24,23,22,21,20,19,25,26,27,28,29,30,36,35,34,33,32,31]
                       s⁸  - split into chunks of length n        [[1,2,3,4,5,6],[12,11,10,9,8,7],[13,14,15,16,17,18],[24,23,22,21,20,19],[25,26,27,28,29,30],[36,35,34,33,32,31]]
                         G - format as a grid

```

# Answer
> 4 votes
# Powershell, 23 Bytes

Cracked By Matt

```
^.+?%.{42}%.{11}:.{35}$

```

Original Solution:

```
$n="$args";$script:r=0;$a=1..$n|%{$t=++$script:r..($script:r+=$n-1);if(!($_%2)){[Array]::Reverse($t)};,$t};$a|%{$_-join" "}

```

Takes input as argument and outputs to stdout

Hopefully this regex is OK, I don't expect this being too difficult to crack, as I haven't obfuscated much of it, and the regex gives a good few starting points to fill in the gaps, there's one thing in the first segment which is very uncommon in code golf though, which may catch someone out, I think a non-greedy match is required there to make this a bit tougher.

First cops challenge anyway.

```
1..4 | % { "----$_----" ; .\snake-cops.ps1 $_  }
----1----
1
----2----
1 2
4 3
----3----
1 2 3
6 5 4
7 8 9
----4----
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13

```

# Answer
> 4 votes
# Pip, regex length 3 (safe)

The solution is a full program that takes *n* as a command-line argument. It does not use any command-line flags.

### Regex (any flavor)

```
\w+

```

### Sample output

```
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13

```

---

## My solution

```
YENsXaPBsPOyY_MUyFi_MUENsXaIiBA1PsPUPODQENsXiXaPBsX_PBsMRVyEI1PsPUPODQENsXiXaPBsX_PBsMy

```

Try it online!

## Strategy

Here's the code we would *like* to write:

```
Y \,a
F i ,a
 I i%2
  P i*a+_.s M RVy
 E
  P i*a+_.s M y

```

That is:

* Store the numbers 1 through `a` in `y`
* Loop over values of `i` from 0 through `a-1`
* If `i` is odd, reverse y, add `i*a` to each element, concatenate a space to each element, and print
* Otherwise, do the same thing, but without reversing first

### Difficulties

A lot of commands and variables in Pip use letters, but some important ones don't:

* Range and inclusive range (`,` and `\,`)
* Most math operations (`+`, `-`, `*`, `%`, `++`)
* Assignment (`:`)
* We can't have a loop or function body with more than one statement (that would need `{}`)
* We can't use parentheses to enforce precedence

How we get around those limitations:

* `EN`umerate can be used in place of `,`; we just need a string with the number of characters we want, and we need to extract the first element of each sublist in a structure like `[[0 "H"] [1 "i"]]`.
* We don't need to increment anything if we can solve the problem with `F`or loops.
* We can assign to the `y` variable with the `Y`ank operator.
* We can do math with strings: `X` is string multiplication, and `PU`sh (or `PB` "push-back") will concatenate a string to another string in-place. To take the length of a string, we can `EN`umerate it and extract the right number from the resulting list.
* We can use functions as long as they can be written as single-expression lambda functions using `_`.

## Specifics

The building blocks of our program:

### Range

```
_MUENsXa

```

That's `map-unpack(_, enumerate(repeat(space, a)))` in pseudocode. Map-unpack is like Python's `itertools.starmap`: given a list of lists, it calls a function on the items of each sublist. `_` returns its first argument, so `_MU` just gets the first item of each sublist. For example, if a = 3:

```
     sXa  "   "
   EN     [[0 " "] [1 " "] [2 " "]]
_MU       [0 1 2]

```

... which is the same as `,a`.

### Inclusive range

I'm not sure there's a way to do `inclusive-range(1, a)` in a single expression, but fortunately we only need it once, so we can construct it in the `y` variable in three steps.

```
YENsXaPBs

```

In pseudocode, `yank(enumerate(repeat(space, a).push-back(space)))`:

```
   sXa     "   "
      PBs  "    "
 EN        [[0 " "] [1 " "] [2 " "] [3 " "]]
Y          Store that in y

```

Next `POy` pops the first item from `y` and discards it, leaving `[[1 " "] [2 " "] [3 " "]]`.

Finally,

```
Y_MUy

```

That is, `yank(map-unpack(_, y))`: extract the first element of each sublist and yank the resulting list back into `y`. `y` is now `[1 2 3]`.

### Length

```
PODQENaPBs

```

In pseudocode, `pop(dequeue(enumerate(a.push-back(space))))`. The difficulty here is that enumerate only gives us numbers up to `len(a)-1`, but we want `len(a)`. So we first push a space to `a`, lengthening it by one character, and then take `len-1` of the new string.

```
      a     "xyz"
       PBs  "xyz "
    EN      [[0 "x"] [1 "y"] [2 "z"] [3 " "]]
  DQ        [3 " "]
PO          3

```

### Math

Now that we have a way to take the length of strings, we can use strings to do multiplication and addition of numbers:

```
PODQENsXaXbPBs
PODQENsXaPBsXbPBs

```

The first does `sXaXb` to create a string of `a*b` spaces and then takes the length of it; the second does `sXaPBsXb` to push a string of `b` spaces to a string of `a` spaces and then takes the length of it.

The nice part is that all the operators we're using here (`PU`, `PO`, `PB`, `DQ`, `EN`, `X`) can be used with `_` to form lambda expressions. So we can map mathematical transformations to the inclusive range we constructed earlier.

We also need to check `i%2` inside the loop, but this is easily accomplished with bitwise AND: `iBA1`.

### Put them together

The full code, with some added whitespace:

```
YENsXaPBs POy Y_MUy              Get \,a into y
F i _MUENsXa                     For i in ,a
 I iBA1                           If i%2=1
  P sPUPODQENsXiXaPBsX_PBs M RVy   Print sPUi*a+_ M RVy
 EI1                              Elseif 1 (using E would cause a parsing problem)
  P sPUPODQENsXiXaPBsX_PBs M y     Print sPUi*a+_ M y

```

# Answer
> 3 votes
## Mathematica, regex length 11, non-competing, cracked

PCRE flavour:

```
^[^]@]{49}$

```

The correct solution will be a function which takes an integer and returns the output as a nested list like:

```
{{1, 2, 3, 4}, {8, 7, 6, 5}, {9, 10, 11, 12}, {16, 15, 14, 13}}

```

# Answer
> 3 votes
# CJam, PCRE, length 8, cracked

```
^[a-~]*$

```

Example output for 4:

```
[[1 2 3 4] [8 7 6 5] [9 10 11 12] [16 15 14 13]]

```

# Answer
> 3 votes
# tinylisp, regex length 3 (cracked)

You can test tinylisp code at Try it online!

### Regex (any flavor)

```
\S+

```

Time to go hardcore.

### Output

The solution defines a **function** that takes a single integer argument and returns a list like this (for n=4):

```
((1 2 3 4) (8 7 6 5) (9 10 11 12) (16 15 14 13))

```

---

My original code uses the same basic idea Brian McCutchon came up with, building lists and eval'ing them. Here it is in one line:

```
(v(c(h(q(d)))(c(h(q(d')))(c(c(h(q(q)))(c(c()(c(q(arglist))(c(c(h(q(v)))(c(c(h(q(c)))(c(c(h(q(q)))(q(d)))(q(arglist))))()))())))()))()))))(d'(seq-args(c(h(q(start)))(c(h(q(stop)))(c(h(q(step)))())))))(d'(seq(c(c(h(q(accum)))seq-args)(q((i(e(v(h(q(start))))stop)(c(v(h(q(start))))accum)(seq(c(v(h(q(stop))))accum)start(s(v(h(q(stop))))step)step)))))))(d'(f'(c(c(h(q(index)))(c(h(q(size)))seq-args))(q((i(e(v(h(q(index))))size)()(c(seq()start(v(h(q(stop))))step)(f'(a(h(q(1)))index)size(a(v(h(q(stop))))size)(a(v(h(q(start))))size)(s(h(q(0)))step)))))))))(d'(f(q((size)(f'(h(q(0)))size(h(q(1)))size(h(q(1))))))))

```

I used the full construct-and-eval method once, to define a macro `d'` that makes definitions like `d`, but takes its arguments wrapped in a list: so instead of `(d x 42)`, you can do `(d'(x 42))`. Then it was just a matter of rewriting any lists in the definitions that might need whitespace: `(q(a b))` -\> `(c a(q(b)))` -\> `(c(h(q(a)))(q(b)))`.

# Answer
> 3 votes
# CJam, PCRE, length 9, cracked

```
^[a-z~]*$

```

Example output for 4:

```
[[1 2 3 4] [8 7 6 5] [9 10 11 12] [16 15 14 13]]

```

Now `{|}` are banned, too.

# Answer
> 2 votes
# Python3, (PCRE) length 27 (Cracked!)

Regex: `^([^# 0]){115}.{6}(?1){24}$`

My first Cops and Robbers submission.

## Output format

```
4:
[1, 2, 3, 4]
[8, 7, 6, 5]
[9, 10, 11, 12]
[16, 15, 14, 13]

```

Original code: `n=int(input());j=0;exec("print([int(i%n+1+(2*n-(2*(i%n)+1))*((((i/n)//1+1)/2)//1)+(2*(i%n)+1)*int(int(i/n)/2))for i in range(j,j+n)]);j+=n;"*n)`

# Answer
> 2 votes
# Python3, length 162 (Cracked!)

Regex: `^([^"' #]){24}"(?1){11}i%n(?1){4}2\*n-(?1){4}i%n(?1){10}i\/n(\)\/\/1)(?1){5}(?2)(?1){3}2\*\(i%n\)(?1){4}[int()2\/]{16}for i in range\(j,(?1){4}\]\)(?1){6}\"\*n\)$`

Okay, I know, it's *quite* long. Fortunately, it won't be cracked in under a week... :'D.

I think I didn't make a mistake anywhere, that would allow loophole-y answers.

## Output format

```
4:
[1, 2, 3, 4]
[8, 7, 6, 5]
[9, 10, 11, 12]
[16, 15, 14, 13]

```

Original code:`n=int(input());j=0;exec("print([int(i%n+1+(2*n-(2*(i%n)+1))*((((i/n)//1+1)/2)//1)+(2*(i%n)+1)*int(int(i/n)/2))for i in range(j,j+n)]);j+=n;"*n)`

# Answer
> 2 votes
## Actually, Python regex of length 193 (safe)

```
^[^\x00-\x08\x0d-\x13\x16-\x1d\x3f\xa6\xb6\xc1\xe9\xea\xfa\xff]{5}[\x00-\x08\x0d-\x13\x16-\x1d\x3f\xa6\xb6\xc1\xe9\xea\xfa\xff][^\x00-\x08\x0d-\x13\x16-\x1d\x3f\xa6\xb6\xc1\xe9\xea\xfa\xff]{6}$

```

This regex matches the CP437-encoded program source.

Output for `n = 4`:

```
[[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]]

```

Here is a Python 3 program to help with testing:

```
import re
pattern = re.compile(rb'[^\x00-\x08\x0d-\x13\x16-\x1d\x3f\xa6\xb6\xc1\xe9\xea\xfa\xff]{5}[\x00-\x08\x0d-\x13\x16-\x1d\x3f\xa6\xb6\xc1\xe9\xea\xfa\xff][^\x00-\x08\x0d-\x13\x16-\x1d\x3f\xa6\xb6\xc1\xe9\xea\xfa\xff]{6}')
code = b'code here'
print(pattern.match(code) and True or False)

```

Try it online!

---

# Actually, 12 bytes

```
;²R╡"?R"ß*♀ƒ

```

Try it online!

Explanation:

```
;²R╡"?R"ß*♀ƒ
;             duplicate input
 ²R           range(1, n**2+1)
   ╡          split into n-length chunks
    "?R"ß*    "?R"*n
          ♀ƒ  for each chunk: reverse if index is odd (R) else do nothing (?)

```

# Answer
> 2 votes
# Scala, length 40, Cracked

**Regex (PCRE)**

```
[\w\s]+[\w\(\):]+[\w\(\)<\-\s{=;+*%\.}]+

```

**Output (n=4)**

```
Vector(Vector(1, 2, 3, 4), Vector(8, 7, 6, 5), Vector(9, 10, 11, 12), Vector(13, 14, 15, 16))

```

**Code**

```
def x(y:Int)=for(u<-1 to y)yield{val q=for(z<-1 to y;r<- List(z+(y*(u-1))))yield r;if(u%2==1)q else q.reverse}

```

**Ungolfed**

```
def x(y:Int)=
  for(u<-1 to y)
      yield {
          val q=for(z<-1 to y;r<- List(z+(y*(u-1)))) yield r;
          if(u%2==1)
            q
          else
            q.reverse
      }

```

# Answer
> 2 votes
# 05AB1E, length 22 Cracked by Emigna

This is probably too easy.

**Regex (PCRE)**

```
^([E-Z0]*[ˆ>*}<]){7}$

```

**Output**

```
[[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]]

```

**Original Solution**

> `UXL0KVXLˆXGXN>*LYKZL0KVNFR}<>ˆ`

# Answer
> 2 votes
# Jelly, length 12 - cracked

cracked by Dennis

```
^[^ḊḢṚUṖṪ]*$

```

Python regex (although I think all flavours are valid for this pattern).

That's right, none of those lovely array manipulation atoms!
No:

* `Ḋequeue`;
* `Ḣead`;
* `Ṛeversal`;
* `Upend`;
* `Ṗop`; or
* `Ṫail`;

For an input of `4` mine outputs:

```
 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13

```

...because I formatted a list of lists as a grid with `G`.

# Answer
> 2 votes
# Jelly, length 13 cracked

cracked by ais523

```
[^ḊḢṚUmṖṪVv]*

```

Python regex (although I think all flavours are valid for this pattern).

An extension of my previously cracked entry:
I have banned modulo indexing, which I missed and Dennis cleverly used;
I have banned use of the two eval atoms, as they'd allow indirect usage of the banned atoms; and
I have removed the start and end match (`^...$` since it is redundant since a full match is required).

No:

* dequeue;
* head;
* reversal;
* `U` upend;
* `m` modulo indexing;
* pop;
* tail;
* `V` eval; or
* `v` dyadic eval

For an input of `4` mine outputs:

```
 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13

```

...because I formatted a list of lists as a grid with `G`.

# Answer
> 2 votes
# Jelly, length 13 cracked

cracked by Dennis (I forgot to keep `m` ... another incoming)

```
[^/P-`vḊ-ṫ€]*

```

Python regex (although I think all flavours are valid for this pattern).

Severely increased the banned characters from my previous submission:

`/` (reduce quick);
from `P` (product) to ``` (monad from dyad quick);
`v` (eval dyad);
from  (dequeue) to  (tail); and
(for each quick)

For an input of `4` mine outputs:

```
 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13

```

...because I formatted a list of lists as a grid with `G`.

# Answer
> 2 votes
# Jelly, 15 bytes, Cracked

Jelly seems to be quite popular in this challenge. So let's require the use of a totally different algorithm. The regex, PCRE interpreted in Jelly's encoding:

```
[^œŒ]{12}
Çœ?²s

```

Several PCRE matchers, such as `pcregrep` and even `perl` itself, will treat input by default as "unknown 8-bit character set compatible with ASCII"; therefore, they handle Jelly's encoding just fine. (That said, I suspect you need to use `perl` here as many regex matchers dislike newlines in the middle of the regex. I can't just write it as `\n` as that's a byte longer.)

Result for an input of 4:

```
[[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]]

```

## Crack

This ended up being cracked due to a typo in the regex. I'll submit a fixed version.

# Answer
> 2 votes
# tinylisp, regex length 10 (cracked)

You can test tinylisp code at Try it online!

### Regex

Any flavor should work the same, we'll call it Python flavor.

```
[( )1c-s]+

```

Basically this boils down to, "Solve the problem without using the `library`." If that turns out to be too easy, I may post a more restrictive one.

### Output

The solution is a **function** that takes a single integer argument and returns a list like this (for n=4):

```
((1 2 3 4) (8 7 6 5) (9 10 11 12) (16 15 14 13))

```

# Answer
> 2 votes
# PHP (Cracked)

### Output (n=4)

```
1       2       3       4
8       7       6       5
9       10      11      12
16      15      14      13

```

---

### PCRE (length=31)

```
^.{4}[-"$%&*+:;=?{}a-zMZ]+.{4}$

```

Here's another take on this challenge, this time using a whitelist approach.

The notable forbidden characters are `()`, `[]`, `_`, digits and most of the upper case letters.

Looking forward to see what you come up with!

---

### THE ORIGINAL SOLUTION

This one was simpler. Since parenthesis were forbidden, you couldn't use function calls or language constructs like conditionals and loops which meant the infamous `goto` was the solution! \>:D

* The only number my solution requires is `1`, which I defined as `+true`.
* To format the output I used `tab` and `newline` characters, generated using bitwise operators on strings: `"M" & "+"` and `"Z" & "*"` Start by outputting `1`
* Then, I looped through each number and calculated the difference between each column and it's complement, which I multiplied by `0` for odd rows and `1` for even rows and then added to the original number at that position.

So, for `n=4`, `5` would originally be on the first column (`1`) on an odd row.

The difference is `-2 * $column + $n + 1 = 3`, which means `5` becomes `5 + $difference * $multiplier = 5 + 3 * 1 = 8`. So, the first column of row number 2 becomes `8`;

A human readable version of my solution is

```
<?=

$one = $i = 1;
$multiplier = $one - $one;
$n = $argv{$one};

loop:

++$i == $n * $n + $one && die;

$column = $i % $n ?: $n;
$difference = -$column - $column + $n + $one;

print "M"&"+";

$i % $n == $one && print "Z"&"*";

print $i + $difference * $multiplier;

// if not at the end of the row, leave as is
// else convert 0 to 1 and 1 to 0 to apply (or not) the above difference
$multiplier = $i % $n ? $multiplier : -$multiplier + $one;

goto loop

?>

```

My solution that matches the regex was: `<?= $t=$i=+true;$f=$s=$t-$t;$n=$argv{$t};a:++$i==$n*$n+$t&¨$b=$i%$n?:$n;$m=-$b-$b+$n+$t;print"M"&"+";$i%$n==$t&&print"Z"&"*";print$i+$m*$s;$s=$i%$n?$s:-$t*$s+$t;goto a?>`

# Answer
> 2 votes
# Racket Intermediate Student with Lambda, regex length 36 20 22, Cracked by kennytm

Produces a function that takes `n` as input and returns the answer as a list of lists.

### Regex (JS)

```
^((?![nla][peo]|-).)*$

```

### Output

```
(list (list 1 2 3 4) (list 8 7 6 5) (list 9 10 11 12) (list 16 15 14 13))

```

# Answer
> 1 votes
# Go, length 17 cracked

Regex, PCRE:

```
^[^+-<]+.[^+-<]+$

```

Translated roughly, you can use neither of these characters, except once:

```
+ , - . / 0 1 2 3 4 5 6 7 8 9 : ; <

```

The regex matches the full program from `package main` to `func main()` which reads from stdin like so: `echo 4 | go run snake.go`

Output:

```
[[1 2 3 4] [8 7 6 5] [9 10 11 12] [16 15 14 13]]

```

# Answer
> 1 votes
# QBasic, regex length 10 (cracked)

A (hopefully more challenging) variation on my first submission.

### Regex

Same as before. Should work in any regex flavor, but we'll call it Python flavor.

```
([A-Z]+.)+

```

My solution uses unformatted QBasic; after formatting, the code doesn't match the regex due to added spaces. (But `([A-Z]+ ?. ?)+` still works on the formatted version.)

This time, I'm **requiring** that a crack work at archive.org, which allows a bit less flexibility in syntax than QB64 does. ;)

### Sample output

```
|1 |2 |3 |4 |
|8 |7 |6 |5 |
|9 |10|11|12|
|16|15|14|13|

```

(I've used the ASCII pipe character `|` here, but the similar-looking box-drawing character --code point 179 in the code page that QBasic uses--works just as well and makes the chart look a lot nicer. You can insert it in your code by holding down `Alt` and typing 179 on the numpad. \</funfacts\>)

---

My original solution, prettified (to get the regex to match, replace `\n *` with `:`):

```
CLS

DIM SEP AS STRING
READ SEP
INPUT SIZE
NEGONE=NOT ZERO
ONE=ZERO-NEGONE
THREE=ONE+ONE+ONE
TEN=THREE*THREE+ONE

CLS
FIELDWIDTH=ONE
TMP=SIZE*SIZE
DO
  FIELDWIDTH=FIELDWIDTH+ONE
  TMP=TMP\TEN
LOOP WHILE TMP

FROMVAL=ONE
TOVAL=SIZE
DIRECTION=ONE

FOR ROW=ONE TO SIZE
  COL=ONE
  FOR VALUE=FROMVAL TO TOVAL STEP DIRECTION
    LOCATE ROW,COL
    PRINT VALUE
    LOCATE ROW,COL
    PRINT SEP
    COL=COL+FIELDWIDTH
  NEXT
  LOCATE ROW,COL
  PRINT SEP
  TMP=FROMVAL+SIZE
  FROMVAL=TOVAL+SIZE
  TOVAL=TMP
  DIRECTION=ZERO-DIRECTION
NEXT

DATA|

```

# Answer
> 1 votes
# Racket Intermediate Student with Lambda, regex length 27 22 10 (Cracked)

You can run Racket ISL with Lambda at Try it online!.

Produces a function that takes `n` as input and returns the answer as a list of lists. The basic idea is that only one-character words are allowed, possibly prefixed with `con`. Also, besides the `con` exception, every other character must be non-word. Now let's see if any `con` robber can crack it!

### Regex (JS)

```
(con|.\W)+

```

### Output

```
(list (list 1 2 3 4) (list 8 7 6 5) (list 9 10 11 12) (list 16 15 14 13))

```

### Edit 3/14

I've golfed the regex down quite a bit, making it more restrictive in the process. The basic idea of the solution is the same, but since the regex is not equivalent to the previous, I'll count my 7 days starting now. Also, until told otherwise, I'll assume that the answer's requirement for a full match means that `^` and `$` on the regex are implied.

### Original solution

```
(λ (n) (((((λ(f) ((λ (x) (x x)) (λ (x) (f (λ (y)((x x)y)))))) (λ (q) (λ(n) (λ(c) (λ(r) (cond [(< c 0)r][(= 1 1) (((q n) (- c 1))(cons(cond [(= 0((((λ (f) ((λ (x) (x x)) (λ (x) (f (λ (y)((x x)y)))))) (λ (r) (λ(a)(λ (b) (cond [(< a b)a][(= 1 1)((r(- a b)) b)])))))c)2))((((((λ (f) ((λ (x) (x x)) (λ (x) (f (λ (y)((x x)y)))))) (λ (r)(λ (s) (λ(e) (λ(t) (λ(a) (cond [(>= (* t s) (* t e)) a][(= 1 1)((((r s) (- e t)) t) (cons(- e t)a))])))))))(+ 1(* c n))) (+ 1(* c n)n)) 1) '())][(= 1 1) ((((((λ (f) ((λ (x) (x x)) (λ (x) (f (λ (y)((x x)y)))))) (λ (r) (λ(s) (λ(e) (λ(t) (λ(a) (cond [(>= (* t s) (* t e)) a][(= 1 1)((((r s) (- e t)) t) (cons(- e t)a))]))))))) (+ (* c n)n))(* c n))-1) '())]) r))]))))))n) (- n 1)) '()) )

```

Try it online! (Note that the TIO code is slightly different because I've wrapped the solution in `(... 4)` to call it.)

I picked ISL with Lambda over standard Racket on this and my other answer because I wanted to have short regexes and minimize loopholes. To do it, I started with this:

```
(define Y
  (λ (f)
     ((λ (x) (x x))
      (λ (x) (f (λ (y) ((x x) y)))))))

(define % (Y (λ (r) (λ (a) (λ (b)
  (cond [(< a b) a]
        [(= 1 1) ((r (- a b)) b)]))))))

(define range1 (Y (λ (r) (λ (s) (λ (e) (λ (t) (λ (a)
  (cond [(>= (* t s) (* t e)) a]
        [(= 1 1) ((((r s) (- e t)) t) (cons (- e t) a))]))))))))

(define g (Y (λ (q) (λ (n) (λ (c) (λ (r)
  (cond
    [(< c 0) r]
    [(= 1 1)
     (((q n) (- c 1))
      (cons
        (cond [(= 0 ((% c) 2))
               ((((range1 (+ 1 (* c n))) (+ 1 (* c n) n)) 1) '())]
              [(= 1 1) ((((range1 (+ (* c n) n)) (* c n)) -1) '())])
        r))])))))))

(define (f n)
  (((g n) (- n 1)) '()))

```

(Look familiar? I translated this into tinylisp for a certain crack.) `Y` it the applicative-order Y combinator, taken from this blog post. All functions are curried to make using the Y combinator possible. Then I substituted the function bodies in for each reference to a function and turned `f` into a lambda. After that, all I had to do was play with spaces so that I could use `.\W` instead of `.\W+` in my regex.

# Answer
> 1 votes
# Java 8 (Safe)

## Regex (PCRE): 6 Bytes

```
[^yD]*

```

## Output n=4

Output separated by spaces

```
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13

```

## Solution

The difficulty is getting to `System.out` without using the letter `y`. `FileDescriptor` is also forbidden because of `D`. Thus, reflection is heavily used to derive `System`.

```
class Snake {
  public static void main(String[] args) throws Exception {
    int n = Integer.parseInt(args[0]);
    String[][] ret = new String[n][n];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        int d = (i % 2 == 0) ? j + 1: n - j;
        ret[i][j] = "" + (i * n + d);
      }
    }
    String stem = "S" + (char)(1 + (int)'x') + "stem";
    String loaderMethod = "get" + stem + "ClassLoader";
    ClassLoader cl = (ClassLoader)ClassLoader.class.getMethod(loaderMethod).invoke(null);
    Class sClass = cl.loadClass("java.lang." + stem);
    for (int i = 0; i < n; i++) {
      String s = String.join(" ", ret[i]);
      ((java.io.PrintStream)sClass.getField("out").get(null)).println(s);
    }
  }
}

```

# Answer
> 0 votes
# Jelly, 16 bytes, Cracked

> **This is my previous submission with a typo/thinko in the regex fixed.**

Jelly seems to be quite popular in this challenge. So let's require the use of a totally different algorithm. The regex, PCRE interpreted in Jelly's encoding:

```
[^œŒ]{12}
Çœ\?²s

```

Several PCRE matchers, such as `pcregrep` and even `perl` itself, will treat input by default as "unknown 8-bit character set compatible with ASCII"; therefore, they handle Jelly's encoding just fine. (That said, I suspect you need to use `perl` here as many regex matchers dislike newlines in the middle of the regex. I can't just write it as `\n` as that's a byte longer.)

Result for an input of 4:

```
[[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]]

```

## Crack

The crack again rather misses the point of the question, but I'll have to give up on this unless I can find a way to avoid cheating. (The newline and `Ç` was part of that, but @Dennis simply output via stdout rather than via the return value to avoid the issue. Is it acceptable to force a certain sort of I/O in cops-and-robbers challenges?)

# Answer
> 0 votes
# PHP (Cracked)

start from the command line

```
php -r <code> <args>

```

original code

```
$a=array();foreach($r=range(0,($z=$argv{1})-1)as$g)foreach(($r)as$f)$a{$g}{$f}=$g%2?$g*$z+$z-$f:$g*$z+$f+1;echo(serialize($a));

```

## Regex (PCRE): 18 Bytes

```
^[$-2:-?a-}]{127}$

```

## Output n=4

```
a:4:{i:0;a:4:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;}i:1;a:4:{i:0;i:8;i:1;i:7;i:2;i:6;i:3;i:5;}i:2;a:4:{i:0;i:9;i:1;i:10;i:2;i:11;i:3;i:12;}i:3;a:4:{i:0;i:16;i:1;i:15;i:2;i:14;i:3;i:13;}}

```

# Answer
> 0 votes
# \>\<\>, length 27 + 1 for single-line mode = 28

Regex (PCRE), using single-line mode :

```
^(?=(.*\n){3})[^.,\d]{131}$

```

My program takes the input from the stack with `-v`, uses no jumps, no digits, no commas and exactly three linefeeds and 131 chars.

Output for n=4 :

```
1,2,3,4
8,7,6,5
9,10,11,12
16,15,14,13

```

# Answer
> 0 votes
# Ruby (2nd submission)

The outside is mostly the same but my accidenal loophole is more restrictive now. I have many regrets

```
(\W?\W\w){4}..(?1){2}\W{8}(\w.\w)...\2(?1){5}\w*(?1)(.)\3

```

It's a lambda. Output is an array of arrays. Example with (n=4):

```
[[1, 2, 3, 4], [8, 7, 6, 5], [9, 10, 11, 12], [16, 15, 14, 13]]

```

# Answer
> 0 votes
# PHP \>=5.4 (Safe)

Original Solution

```
<?while(+$g<$a=$argv{1})echo(join("\t",$g%2?range($g*$a+$a,$g++*$a+1):range($g*$a+1,$g++*$a+$a))),"\n"?>

```

start from the command line

```
php <file> <args>

```

## Regex (PCRE): 12 Bytes

```
[^ ;#/]{104}

```

## Output n=4

separator is `\t`

```
1   2   3   4
8   7   6   5
9   10  11  12
16  15  14  13

```

# Answer
> 0 votes
# PHP \>=7.0 (Safe)

## Original Solution

```
<?php while($g<$a=$_GET{0})echo($g%2?"\u{202e}":""),join("\t",array_map($g%2?strrev:trim,range($g*$a+1,$g++*$a+$a))),"\n"?>

```

## Regex (PCRE): 30 Bytes

```
<\?php [^; >]{32}\\u[^; >]{82}>

```

Sorry a little mistake the week counts from now

Hint: Use a special unicode Character

## Output n=4

separator is `\t`. Looks like this

```
1   2   3   4
8   7   6   5
9   10  11  12
16  15  14  13

```

## Output n=4

only copy and paste from the output I use `$_GET` and the document sents this header `Content-Type: text/plain;charset=utf-8`

```
1   2   3   4
5  6   7   8
9   10  11  12
31 41  51  61

```

---
Tags: regular-expression, cops-and-robbers, matrix
---


title: That's so meta!

text:
# Question
Title: That's so meta!
# Your Challenge

You must write a program/function etc. that takes a domain name of a StackExchange site and outputs the domain for the meta version of the site passed to it. Examples:

```
stackoverflow.com => meta.stackoverflow.com
codegolf.stackexchange.com => codegolf.meta.stackexchange.com
mathoverflow.net => meta.mathoverflow.net
codereview.stackexchange.com => codereview.meta.stackexchange.com

```

Note: Subdomains are added to `meta.stackexchange.com`. Separate domains have `meta.` prepended. You don't need to worry about `stackexchange.com` or `meta.stackexchange.com` passed.

# Shortest answer in bytes wins!

# Answer
> 1 votes
# Retina, 17

```
\w+\.\w+$
meta.$&

```

Try it online.

# Answer
> 1 votes
# GNU Sed, 20

Score includes +1 for use of `-r`.

```
s/\w+\.\w+$/meta.&/

```

Try it online.

# Answer
> 1 votes
# JavaScript (ES6), ~~41~~ ~~40~~ ~~34~~ 32 bytes

```
s=>s.replace(/\w+\.\w+$/,'meta.$&')

```

```
<input id=a oninput="b.innerText=a.value.replace(/\w+\.\w+$/,'meta.$&')"/>
<p id=b />
```

# Answer
> 1 votes
# Pip, ~~21~~ 20 bytes

```
aR`\w+.\w+$``meta.&`

```

Try it online!

Matches the last two runs of word characters (separated by some other character), to which it prepends `meta.`.

# Answer
> 1 votes
# Python 2, ~~57~~ 54 bytes

```
l=input().split(".");l[:-2]+=["meta"];print".".join(l)

```

Try it online!

Split on periods, insert `"meta"` before the second item from the end, join the list again on periods and print.

# Answer
> 0 votes
# JS (ES6), 59 bytes

```
m="meta.",a=>a.split(".").length-2?a.replace(/\./,"."+m):m+a

```

If the string passed to the function expression has more than 1 `.` in it, a `.meta.` is inserted in the first `.`. Otherwise, `meta.` is appended to that string.

# Answer
> 0 votes
# Jelly, ~~22~~ 19 bytes

```
ṣ”.ṙ-2;“£2v»W¤ṙ2j”.

```

**Try it online!**

### How?

```
ṣ”.ṙ-2;“£2v»W¤ṙ2j”. - Main link: domain string
ṣ”.                 - split at occurrences of '.'
   ṙ-2              - rotate right by -2
             ¤      - nilad followed by link(s) as a nilad
       “£2v»        -     dictionary lookup of "meta"
            W       -     wrap in a list
      ;             - concatenate
              r2    - rotate right by 2
                j”. - join with '.'s

```

# Answer
> 0 votes
# PHP, 48 Bytes

```
echo preg_filter("#\w+\.\w+$#","meta.$0",$argn);

```

but we should better do it like this

```
echo strstr($argn,"meta.")?$argn:preg_filter("#\w+\.\w+$#","meta.$0",$argn);

```

---
Tags: code-golf, string
---


title: Is this a number?

text:
# Question
Title: Is this a number?
# Prelude:

I wanted to train making test cases, so I'm gonna try them on something easy.

# Challenge:

Take any given (string) input (within visible ASCII range) and deduce if it's a number and output something that could be used to evaluate.

# Rules:

* A number will only contain the characters `-0123456789,.`
* Answers are only required to recognise numbers between -1000000000 and 1000000000 (exclusive), but may recognise arbitrarily large numbers.
* You can write a full program or a function.
* If a number, return anything that could be used to discern it and document the output in the description (ex. `My program outputs T if a number, F if not.`).
* Input will be any amount of characters within ASCII range or empty (if empty return whatever you'd output if not a number).
* Numbers could include a decimal point (ex. `3.14`). If they do, they must have at least one digit before the decimal point and at least one after it.
* Numbers could have leading or trailing zeros (ex. `000001.00000`).
* The integer part of a number could be divided for readability into chunks of three digits with commas (ex. `1,000.23456`). In this case they must be divided every three digits from right to left (ex. `1,234,567`, `10,000.202`, `123,234.00`, `0,123.293`).
* Negatives numbers are indicated by a leading `-` (ex. `-1.23`). A leading `+` to indicate a positive number is not permitted, and should result in the falsy output.
* Exceptions are NOT counted as valid and discernible output (except when they can pass outputs to standard out stream (ex. `Exception on line N [...]` can be put in as output for a number/nonnumber if the string is put to standard out stream.

# Test cases:

(assuming the `My program outputs T if a number, F if not.` version)

```
123 -> T [on integer]
-123 -> T [negative numbers need to be handled]
0 -> T [on zero]
123.456 -> T [on floating point]
123,456.789 -> T [on evenly divided by 3 digits with comas]
123456789 -> T [thousand separators are not required]
0000001.00000 -> T [on leading/trailing zeros]
00.00 -> T [on zero and leading/trailing zeros]
999999999.9999999999999999999999999999999999999999999999999999 -> T [on close to the maximum value]
-999999999.9999999999999999999999999999999999999999999999999999 -> T [on close to the minimum value]
 -> F [on empty]
lolz -> F [on non-number value]
n4melyh4xor -> F [on non-number with digits]
  1.2 -> F [on space-padded]
9.3 1.3 -> F [on anyhow separated multiple numbers]
1e5 -> F [no scientific notation]
50cl05e.buty3ts0f4r -> F [on input with letters obscuring the number]
1,2,3,4.5678 -> F [on badly readability-divided number]
1,234.5,678 -> F [on readability-divided floating point part]
.234 -> F [on no leading zero]
+1 -> F [no leading + sign]
1.234.3 -> F [only one decimal point]
12345,678 -> F [on separator stopping mid-way]

```

, least characters is the winner.

# Answer
# Retina, ~~28~~ ~~29~~ ~~31~~ ~~40~~ 34 bytes

```
^-?\d{1,3}((,\d{3})*|\d*)(\.\d+)?$

```

Outputs `1` if truthy, `0` otherwise. As far as I understand, in this case Retina outputs the number of matches the regex has on the input.

Try it online!

Test Suite

### Edits

* Fixed to comply with the "there should be digits after the decimal place" rule
* Fixed to comply with the "handle negatives" rules
* Fixed to comply with the optional comma separators
* Fixed bug with thousands separators as noted by @MartinEnder
* Golfed by removing conditional lookahead

### RegExplanation

```
^-?\d{1,3}((,\d{3})*|\d*)(\.\d+)?$
^                                $  This marks the start and end of regex
 -?                                 Optional hyphen for negative number
   \d{1,3}                          Matches between 1 and 3 digits
          (             )           Capturing group
           (,\d{3})*                 Matches at least zero of comma and three numbers (in the case of separators)
                    |                OR
                     \d*             Matches at least zero digits (in the case of no separators)
                        (\.\d+)?    Matches an optional . and at least one digit (for decimal numbers)

```
> 10 votes

# Answer
# JavaScript, ~~46~~ 49 bytes

This is a direct port of my Retina answer. The only reason I used JS is so that there is an easy way to test the regex using the Snack Snippet below

```
f=s=>/^-?\d{1,3}((,\d{3})*|\d*)(\.\d+)?$/.test(s)

```

---

```
f=s=>/^-?\d{1,3}((,\d{3})*|\d*)(\.\d+)?$/.test(s)
```

```
<input oninput=p.innerText=f(value)><p id=p></p>
```
> 3 votes

# Answer
# Perl 6, 42 bytes

```
{?/^\-?[\d**1..3[\,\d**3]+|\d+][\.\d+]?$/}

```

Try it

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  ? # turn the following into a Bool result

  /  # match implicitly against ｢$_｣

    ^                 # beginning of string

    \- ?              # optional leading ｢-｣

    [

      \d ** 1..3      # 1 to 3 digits
      [
        \,            # comma
        \d ** 3       # three digits
      ]+              # repeat at least once

    |                 # or

      \d+             # at least one digit

    ]

    [ \. \d+ ]?       # ｢.｣ followed by at least one digit optionally

    $  # end of string

  /
}

```
> 2 votes

# Answer
# PHP, 62 bytes

```
<?=preg_match("#^-?(\d+|\d{1,3}(,\d{3})*)(\.\d+)?$",$argv[1]);

```

The builtin cannot handle commas and it accepts scientific notation; so I had to walk the regex way. `<?=is_numeric($argv[1]);` would have been 24 bytes.
> 1 votes

# Answer
# bash/Unix tools, 64 bytes

```
egrep -c '^-?([0-9]+|[0-9]{1,3}(,[0-9]{3})+)(\.[0-9]+)?$'<<<"$1"

```

Save this as a file, and pass the string to be tested as the first argument to the command.

Output is 0 for a non-number, 1 for a number.

If you're willing to accept input from stdin and if you can guarantee that the input consists of just one line, then you can remove the \<\<\<"$1" at the end, resulting in **57 bytes**.

As for the code itself, the -c option to egrep counts the number of matching lines (which will be either 0 or 1).
> 0 votes

# Answer
# Pyth, 25 characters

```
:zCiCM"૧祥쪤"^T6

```

Compresses Kritixi Lithos’ regex.

Try it online. Uses Unicode characters outside the Basic Multilingual Plane, which TIO apparently can’t handle? This little app reports the wrong size for the string, though. This character/byte counter gets it right.
> 0 votes

# Answer
# C89, 195 bytes

```
b,d,c,i;f(char*s){b=*s;for(d=c=i=0;i++,*(s++),d+=*s=='.',c+=*s==',',b=c?i&(i%4!=3)&*s==','?0:b:b;)if(*s==45&!i);else if((*s==32)|(*s==46)|*s==43|!isdigit(*s)&*s!=46&*s!=44)||!(d-1))b=0;return b;}

```

Ungolfed:

```
bool is_base10_number (const char* const str) {

  if(!str[0])return false;

  size_t
    dpts = 0,
    cmas = 0;

  for (size_t i = 0; i < strlen(str); i++) {

    if ((str[i] == '-') && (!i)){
      continue;
    }

    if (
      (str[i] == ' ')
      || (str[0] == '.')
      || (str[0] == '+')
      ||
      (
        (!isdigit(str[i]))
        && (str[i] != '.')
        && (str[i] != ',')
      )
    ) {
      return false;
    }

    dpts += str[i] == '.';
    cmas += str[i] == ',';

    if (cmas) {
      if (i & ((i % 4) != 3) & str[i] == ',') {
        return false;
      }
    }

  }

  if (dpts > 1) { return false; }

  return true;
}

```
> 0 votes

# Answer
## Python 2, 79 bytes

Regex solution

```
import re
lambda s:[s]==re.findall('-?(?:\d{1,3}(?:,\d{3}\d+)(?:\.?\d+)?',s)

-?                                          | Starts with 0-1 dashes
  (?:\d{1,3}(?:,\d{3})+                     | Have 1-3 digits and 1+ (comma followed by 3 digits)
                       |\d+)                | or 1+ digits
                            (?:\.?\d+)?     | Ends with dot and 1+ digits or nothing

```

Try it online
> 0 votes

# Answer
# c#, 75 bytes

```
bool t(string n){double v;return double.TryParse(n.Replace(",",""),out v);}

```
> 0 votes

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


title: Advanced Calculator

text:
# Question
Title: Advanced Calculator
You must write a program that evaluates a string that would be entered into an advanced calculator.

The program must accept input using stdin and output the correct answer. For languages that do no have functions to accept stdin, you may assume the functions `readLine` and `print` to handle these tasks.

**Requirements:**

* Does not use any kind of "eval" functions
* Can handle floating point and negative numbers
* Supports at least the +, -, \*, /, and ^ operators
* Supports brackets and parenthesis for overriding the normal order
* Can handle input containing one **or more** spaces between the operators and numbers
* Evaluates the input using the standard order of operations

## Test Cases

Input

```
10 - 3 + 2

```

Output

```
9

```

---

Input
```
8 + 6 / 3 - 7 + -5 / 2.5

```

Output

```
1

```

---

Input
```
4 + [ ( -3 + 5 ) * 3.5 ] ^ 2 - 12

```

Output

```
41

```

# Answer
> 8 votes
## C++, 640 583

```
string k="[]()+-*/^";stack<double> m;stack<char> n;
#define C(o,x,y) ('^'==o?x<y:x<=y)
#define Q(a) double a=m.top();m.pop();
#define R(o) {Q(b)Q(a)m.push(o=='+'?a+b:o=='-'?a-b:o=='*'?a*b:o=='/'?a/b:o=='^'?pow(a,b):0);n.pop();}
while(!cin.eof()){string s;getline(cin,s,' ');if(s.empty())continue;if('\n'==*--s.end())s.erase(--s.end());(s.size()==1&&s.npos!=k.find(s[0]))?({char c=s[0]=='['?'(':s[0]==']'?')':s[0];while(!n.empty()&&'('!= c&&C(c,k.find(c),k.find(n.top())))R(n.top());')'==c?n.pop():n.push(c);}):m.push(strtod(s.c_str(),0));}while(!n.empty())R(n.top());cout<<m.top()<<endl;

```

**Indented**

```
string k="[]()+-*/^";
stack<double> m;
stack<char> n;
#define C(o,x,y) ('^'==o?x<y:x<=y)
#define Q(a) double a=m.top();m.pop();
#define R(o) {Q(b)Q(a)m.push(o=='+'?a+b:o=='-'?a-b:o=='*'?a*b:o=='/'?a/b:o=='^'?pow(a,b):0);n.pop();}
while(!cin.eof())
{
    string s;
    getline(cin,s,' ');
    if(s.empty())continue;
    if('\n'==*--s.end())s.erase(--s.end());
    (s.size()==1&&s.npos!=k.find(s[0]))?({
        char c=s[0]=='['?'(':s[0]==']'?')':s[0];
        while(!n.empty()&&'('!= c&&C(c,k.find(c),k.find(n.top())))
            R(n.top());
        ')'==c?n.pop():n.push(c);
    }):m.push(strtod(s.c_str(),0));
}
while(!n.empty())
    R(n.top());
cout<<m.top()<<endl;

```

My first code golf, so looking forward to comments & criticism!

# Answer
> 2 votes
# PHP - ~~394~~ ~~354~~ 312 characters

```
<?=e(!$s=preg_split('#\s+#',`cat`,-1,1),$s);function e($P,&$s){$S='array_shift';if(($a=$S($s))=='('|$a=='['){$a=e(0,$s);$S($s);}while($s&&($p=strpos(' +-*/^',$o=$s[0]))&&$p>=$P){$b=e($p+($S($s)!='^'),$s);if($o=='+')$a+=$b;if($o=='-')$a-=$b;if($o=='*')$a*=$b;if($o=='/')$a/=$b;if($o=='^')$a=pow($a,$b);}return$a;}

```

Indented:

```
<?
preg_match_all('#\d+(\.\d+)?|\S#',`cat`,$m);
$s=$m[0];
function e($P) {
        global $s;
        if (strpos(" ([",$s[0])){
                array_shift($s);
                $a=e(0);
                array_shift($s);
        } else {
                $a=array_shift($s);
                if ($a=='-')$a.=array_shift($s);
        }
        while ($s && ($p=strpos(' +-*/^',$o=$s[0])) && $p >= $P) {
                array_shift($s);
                $b = e($p+($o!='^'));
                switch($o){
                case'+':$a+=$b;break;
                case'-':$a-=$b;break;
                case'*':$a*=$b;break;
                case'/':$a/=$b;break;
                case'^':$a=pow($a,$b);
                }
        }
        return $a;
}
echo e(0);

```

# Answer
> 2 votes
# Postscript, 446

This uses the shunting yard algorithm.

```
[/*[/p
2/e{mul}>>/d[/p
2/e{div}>>/+[/p
1/e{add}>>/-[/p
1/e{sub}>>/o[/p
9/e{}>>/c[/p
-1/e{}>>/^[/p
3/e{exp}>>/p
0>>begin/s(%stdin)(r)file 999 string readline pop def
0 1 s length 1 sub{s exch[0 1 255{}for]dup[(\(o)([o)(\)c)(]c)(/d)]{{}forall
put dup}forall
pop
3 copy pop
get
get
put}for{s token not{exit}if
exch/s exch store{cvr}stopped{load
dup/p get
p
le{currentdict end
exch begin/e get exec}{begin}ifelse}if}loop{{e end}stopped{exit}if}loop
=

```

Un-golfed and commented:

```
% We associate the operators with their precedence /p and the executed commend /e
[
  (*)[/p  2 /e{mul}>>
  (d)[/p  2 /e{div}>> % This is division
  (+)[/p  1 /e{add}>>
  (-)[/p  1 /e{sub}>>
  (o)[/p  9 /e{   }>> % This is open bracket
  (c)[/p -1 /e{   }>> % This is close bracket
  (^)[/p  3 /e{exp}>>
  /p 0
>>begin

% Let's read the input string
/s(%stdin)(r)file 999 string readline pop def

% If we want to use the token operator, we have to replace (, [, ), ] and / to get meaningful results
% We use kind of an encoding array (familiar to PostScripters) to map those codes to o, c, and d.
0 1 s length 1 sub{        % index
  s exch                   % string index
  [0 1 255{}for] dup       % string index translationArray translationArray
  [(\(o)  ([o)  (\)c)  (]c)  (/d)] % string index translationArray translationArray reencodeArray
  {                        % string index translationArray translationArray translationString
    {}forall               % string index translationArray translationArray charCode newCharCode
    put dup                % string index translationArray translationArray
  }forall                  % string index translationArray translationArray
  pop                      % string index translationArray
  3 copy pop               % string index translationArray string index
  get                      % string index translationArray charCode
  get                      % string index translatedCharCode
  put                      % -/-
}for

% Now we can actually start interpreting the string
% We use the stack for storing numbers we read and the dictionary stack for operators that are "waiting"
{                          % number*
  s token not{exit}if      % number* string token
  exch /s exch store       % number* token
  % We try to interpret the token as a number
  {cvr}stopped{            % number* token
    % If interpretation as number fails, we have an operator
    load                   % number* opDict
    % Compare operator precedence with last operator on dictstack
    dup /p get             % number* opDict opPrec
    p                      % number* opDict opPrec prevOpPrec
    le {                   % number* opDict
      % If the last operator on the stack has at least the same precedence, execute it
      currentdict end      % number* opDict prevOpDict
      exch begin           % number* prevOpDict
      /e get exec          % number*
    }{                     % number* opDict
      % If last operator doesn't have higher precedence, put the new operator on the dictstack as well
      begin
    }ifelse
  }if
}loop
% If we're finished with interpreting the string, execute all operators that are left on the dictstack
{{e end}stopped{exit}if}loop
=

```

**TODO**: Right-associativity of exponentation

# Answer
> 1 votes
# Python 2,~~339~~ 335 bytes

```
import re
x,s=input(),re.sub
def f(y):
 y,r=s('- ','+ -',y).split(),['^','*','/','+','-']
 for c in r:
  while c in y:d=y.index(c)-1;a,b=map(float,[y[d],y[d+2]]);y=y[:d]+[((a,-a)[a<0]**b,a*b,a/b,a+b,a-b)[r.index(c)]]+y[d+3:]
 return`y[0]`
w=lambda b:s("[([]+[\d+\-*/^ .]*[)\]]",lambda m:f(m.group()[1:]),s(' +',' ',b))
print f(w(w(x)))

```

Try it online!

* -4 bytes by changing str(x) with backticks \`\`!

# Answer
> 0 votes
# Postscript, ~~1000~~ ~~695~~ ~~665~~ 494

Stole ideas from ThomasW. ~~Added feature: accepts strings with or without spaces around operators.~~*\[feature removed\]*

---

Using `ARGUMENTS` is shorter than `%stdin`, and easier to test, to boot!

---

Simplified the substitution to just replace brackets with parens.

```
575(1)10:36 PM:ps 0> gsnd -q -- calc2bg.ps '10 - 3 + 2'
9
576(1)10:37 PM:ps 0> gsnd -q -- calc2bg.ps '8 + 6 / 3 - 7 + -5 / 2.5'
1.0
577(1)10:37 PM:ps 0> gsnd -q -- calc2bg.ps '4 + [ ( -3 + 5 ) * 3.5 ] ^ 2 - 12'
41.0

```

Code:

```
/T[/^[/C{exp}/P 4/X{le}>>/*[/C{mul}/P 3/X{lt}>>/[/C{div}/P
3/X{lt}>>/+[/C{add}/P 2/X{lt}>>/-[/C{sub}/P
2/X{lt}>>>>def[/integertype{}/realtype{}/stringtype{V}/nametype{cvlit/N
exch store{P T N get dup/P get exch/X get exec{exit}if C end}loop T N get
begin}91 40 93 41>>begin/V{0 1 2 index length 1 sub{2 copy get
dup where{exch get}if 3 copy put pop pop}for[/N 0/R 0/P 0/C{}>>begin{token
not{exit}if exch/R exch store dup type exec R}loop{P 0 eq{end exit}if C
end}loop}def ARGUMENTS{V ==}forall

```

Ungolfed and commented:

```
%!
%Shunting-Yard Algorithm using dictstack for operators
%invoke with %gsnd -q -- calc2bg.ps [ 'expr1' ]*

%The operator table. C:code P:precedence X:test(implements associativity)
/T[
    /^[/C{exp}/P 4/X{le}>>
    /*[/C{mul}/P 3/X{lt}>>
    /[/C{div}/P 3/X{lt}>>
    /+[/C{add}/P 2/X{lt}>>
    /-[/C{sub}/P 2/X{lt}>>
>>def

%The type-dispatch dictionary
%numbers: do nothing
%string: recurse
%name: process op
[%/integertype{}/realtype{} %now uses `where` below
/stringtype{V}/nametype{
pstack()=
    cvlit/N exch store %stash cur-op
    {
        P %prec(tos)
        T N get %prec(tos) cur-op-dict
        dup/P get %prec(tos) cur-op-dict prec(cur-op)
        exch/X get %prec(tos) prec(cur-op) test(cur-op)
        exec{exit}if %exit if prec(tos) < || <= prec(cur-op)
/C load ==
        C %pop-and-apply
        end
pstack()=
    } loop
    T N get begin %push cur-op
}>>begin

%substitutions
[91 40 93 41>>begin %replace brackets with parens
/V {
    %pre-process
    0 1 2 index length 1 sub {
        2 copy get
        dup where { exch get } if
        3 copy put pop pop
    } for
dup ==

    [/N 0/R 0/P 0/C{}>>begin %dummy base operator and storage
    { token not{exit}if exch /R exch store %extract token, stash Remainder
pstack(>)=
        %dispatch type procedure
        dup type dup where { pop exec }{ pop } ifelse
    R }loop
pstack()=
    {
        P 0 eq{end exit}if %hit dummy op: exit
/C load ==
        C end %pop and apply
    } loop
} def

ARGUMENTS{V ==}forall %iterate through the command-line arguments

```

---
Tags: code-golf, math
---


title: Very Nice Friedman Numbers

text:
# Question
Title: Very Nice Friedman Numbers
A Friedman Number is a positive integer that is equal to a non-trivial expression which uses its own digits in combination with the operations +, -, \*, /, ^, parentheses and concatenation.

A Nice Friedman Number is a positive integer that is equal to a non-trivial expression which uses its own digits in combination with the same operations, with the digits in their original order.

A Very Nice Friedman Number (VNFN), which I am inventing here, is a Nice Friedman Number which can be written without the less pretty (in my opinion) parts of such an expression. Parentheses, concatenation and unary negation are disallowed.

For this challenge, there are three possible ways of writing an expression without parentheses.

**Prefix:** This is equivalent to left-associativity. This type of expression is written with all operators to the left of the digits. Each operator applies to the following two expressions. For instance:

```
*+*1234 = *(+(*(1,2),3),4) = (((1*2)+3)*4) = 20

```

A VNFN which can be written this way is 343:

```
^+343 = ^(+(3,4),3) = ((3+4)^3) = 343

```

**Postfix:** This is equivalent to right-associativity. It is just like prefix notation, except that the operation go to the right of the digits. Each operator applies to the two previous expressions. For instance:

```
1234*+* = (1,(2,(3,4)*)+)* = (1*(2+(3*4))) = 14

```

A VNFN which can be written this way is 15655:

```
15655^+** = (1,(5,(6,(5,5)^)+)*)* = (1*(5*(6+(5^5)))) = 15655

```

**Infix:** Infix notation uses the standard order of operations for the five operations. For the purposes of the challenge, that order of operations will be defined as follows: Parenthesize `^` first, right associatively. Then, parenthesize `*` and `/` simultaneously, left associatively. Finally, parenthesize `+` and `-` simultaneously, left associatively.

```
1-2-3 = (1-2)-3 = -4
2/3*2 = (2/3)*2 = 4/3
2^2^3 = 2^(2^3) = 256
1^2*3+4 = (1^2)*3+4 = 7

```

A VNFN which can be written this way is 11664:

```
1*1*6^6/4 = (((1*1)*(6^6))/4) = 11664

```

**Challenge:** Given a positive integer, if it can be expressed as a non-trivial expression of its own digits in either prefix, infix or postfix notation, output that expression. If not, output nothing.

**Clarifications:** If multiple representations are possible, you may output any non-empty subset of them. For instance, 736 is a VNFN:

```
+^736 = 736
7+3^6 = 736

```

`+^736`, `7+3^6` or both would all be acceptable outputs.

A "Trivial" expression means one that does not use any operators. This only is relevant for one digit numbers, and means that one digit numbers cannot be VNFNs. This is inherited from the definition of a Friedman Number.

Answers should run in seconds or minutes on inputs under a million.

Related.

**IO:** Standard IO rules. Full program, function, verb or similar. STDIN, command line, function argument or similar. For outputing "Nothing", the empty string, a blank line, `null` or similar, and an empty collection are all fine. Output may be a string delimited with a character that cannot be in a representation, or may be a collection of strings.

**Examples:**

```
127
None

343
^+343

736
736^+
7+3^6

2502
None

15655
15655^+**

11664
1*1*6^6/4
1^1*6^6/4

5
None

```

**Scoring:** This is code golf. Fewest bytes wins.

Also, if you find one, please give a new Very Nice Friedman Number in your answer.

# Answer
# Perl, ~~345~~ ~~334~~ ~~318~~ ~~293~~ ~~263~~ 245B

```
$_='$_=$i=pop;$c=y///c-1;sub f{say if$c&&$i==eval pop=~s/\^/**/gr}A$m)$1$4"})};f"("x$c.$m}globOx$c.$i;A$1$4($m"})};f$m.")"x$c}glob$i.Ox$c;map{f$_}glob joinO,/./g';s!O!"{+,-,*,/,^}"!g;s!A!'map{m{(\d)((?R)|(\d)(?{$m=$3}))(.)(?{$m="'!ge;s!d!D!;eval

```

Call with `perl -M5.10.0 scratch.pl 736`

---

## Results

The first few results that I found are:

```
^+343
736^+
7+3^6
^+/3125
^+^3125
/^+-11664
/^--11664
1-1+6^6/4
/^++14641
^^++14641
1+5^6/1-8
1+5^6^1-8
1+5^6-2-2
1+5^6-2^2
1+5^6+2-4
1+5^6+4^2
-^+^16377
-^-+16377
/^+^16384
/^-+16384

```

---

## Explanation

### Fully ungolfed

I tried to repeat myself as much as possible to make the later golfing easier.

```
#!perl
use 5.10.0;

$_ = $input = pop;

# y///c counts characters in $_
$count = y///c - 1;

sub f {
    say if $count && $input == eval pop =~ s/\^/**/gr
}

# PREFIX
map {
    m{                            # Parses *^+1234
        (\D)                      # $1 = first symbol
        (
            (?R)                  # RECURSE
        |
            (\d)(?{               # $3 = first digit
                $match=$3
            })
        )
        (.)(?{                    # $4 = last digit
            $match="$match)$1$4"
        })
    }x;
    f "(" x $count . $match
}
    # glob expands '{0,1}{0,1}' into 00,01,10,11
    glob "{+,-,*,/,^}" x $count . $input;

# POSTFIX
map {
    m{(\d)((?R)|(\d)(?{$match=$3}))(.)(?{$match="$1$4($match"})};
    f $match. ")" x $count
}
    glob $input . "{+,-,*,/,^}" x $count;

# INFIX
# /./g splits $_ into characters
map { f $_} glob join "{+,-,*,/,^}", /./g

```

### How it's golfed

* Remove whitespace & comments and replace all vars with 1-character version
* Wrap program in `$_=q! ... !;eval`
* Extract strings and substitute them in afterwards.

This gives something like this, from which you can remove the line breaks for the result:

```
$_='
    $_=$i=pop;
    $c=y///c-1;
    sub f{say if$c&&$i==eval pop=~s/\^/**/gr}
    A$m)$1$4"})};f"("x$c.$m}globOx$c.$i;
    A$1$4($m"})};f$m.")"x$c}glob$i.Ox$c;
    map{f$_}glob joinO,/./g
';
s!O!"{+,-,*,/,^}"!g;
s!A!'map{m{(\d)((?R)|(\d)(?{$m=$3}))(.)(?{$m="'!ge;
s!d!D!;
eval

```
> 5 votes

# Answer
## Ruby 2.1.5 only - 213 220 238 + 9 = 247

Not sure how Ruby beats Perl, but here you go...

Run this with a -rtimeout flag (and either -W0 or send your stderr elsewhere).

To make this *slightly* more robust, replace `send([].methods[81],z-1)` with `repeated_permutation(z-1)` and score an extra character (so, **248**).

```
g=$*[0].split //
exit if 2>z=g.size
d=->a,s{$><<a*''&&exit if$*[0].to_i==timeout(2){eval"#{(s*'').gsub(?^,'**')}"}rescue p}
l,r=[?(]*z,[?)]*z
%w{* / + - ^}.send([].methods[81],z-1){|o|d[m=g.zip(o),m]
d[g+o,l.zip(m)+r]
d[o+g,l+g.zip(r,o)]}

```

Basically, go through all permutations of operators and try infix, postfix, and prefix in that order. The `d` method uses `eval` on the second parameter to perform the calculations, catching any DivideByZero or Overflow exceptions.

You need to send stderr to /dev/null, though, or else `eval` will sometimes print warnings like `(eval):1: warning: in a**b, b may be too big`.

While I came up with this ungolfing, I found a way to save three chars!

### Ungolfed (outdated but similar principles):

```
input = $*[0]
digits = input.split //
num_digits = digits.size
exit if 2 > num_digits # one-digit numbers should fail

def print_if_eval print_array, eval_array
  # concatenate the array and replace ^ with **
  eval_string = (eval_array * '').gsub(?^, '**')
  val = eval(eval_string)
  if input.to_i == val
    $><<print_array*''
    exit
  end
rescue
  # this catches any DivideByZero or Overflow errors in eval.
end
# technically, this should be * (num_digits - 1), but as long as we
# have AT LEAST (num_digits - 1) copies of the operators, this works
operators = %w{* / + - ^} * num_digits
left_parens = ['('] * num_digits
right_parens = [')'] * num_digits
operators.permutation(num_digits-1) { |op_set|
  # infix
  # just uses the native order of operations, so just zip it all together
  # 1+2-3*4/5^6
  print_if_eval(digits.zip(op_set),
                digits.zip(op_set))

  # postfix
  # leftparen-digit-operator, repeat; then add right_parens
  # (1+(2-(3*(4/(5^(6))))))
  #
  print_if_eval(digits+op_set,
                (left_parens.zip(digits, op_set) + right_parens))

  # prefix
  # leftparens; then add digit-rightparen-operator, repeat
  # ((((((1)+2)-3)*4)/5)^6)
  print_if_eval(op_set+digits,
                left_parens + digits.zip(right_parens, op_set))
}

```

### Changelog

**247** made this work for larger numbers instead of timing out.

**220** shaved off three chars by declaring paren arrays, and fixed a bug where one-digit numbers were considered VNFNs

**213** initial commit
> 4 votes

# Answer
MATLAB (435 b)

```
n=input('');b=str2num(fliplr(num2str(n)));l=floor(log(b)/log(10));a=unique(nchoosek(repmat('*+-/^', 1,5), l), 'rows');for k=1:numel(a(:,1)),for j=0:2,c=strcat((j>1)*ones(l)*'(',mod(b,10)+48);for i=1:l,c=strcat(c,a(k,i),(j<1)*'(',mod(floor(b/10^i),10)+48,(j>1)*')'); end,c=strcat(c,(j<1)*ones(l)*')');if eval(c(1,:))==n,fprintf('%s%s%s%s\n',c(1,1:(j==1)*numel(c(1,:))),fliplr(a(k,1:(j>1)*l)),(j~=1)*num2str(n),a(k,1:(j<1)*l));end,end,end

```

---

try it here

http://octave-online.net/
> 1 votes

# Answer
## Python 2, 303 bytes

Try it online

```
from itertools import*
n=input()
l=len(n)-1
E=eval
for c in product('+-*/^',repeat=l):
 L=lambda x,y:x.join(map(y.join,zip(n,c+('',)))).replace('^','**')
 C=''.join(c)
 try:
    if`E(L('',''))`==n:print L('','')
    if`E('('*-~l+L('',')'))`==n:print C[::-1]+n
    if`E(L('(','')+')'*l)`==n:print n+C
 except:pass

```

Infix output will contain `**` instead of `^`. If this is not allowed, `.replace('**','^')` will occure and add another 18 bytes

Explanation:

```
# get all possible combinations of operators (with repetitions)
product('+-*/^',repeat=l)

# create string from input and operators like
# if passed '(' and '' will return (a+(b+(c
# if passed '' and ')' will return a)+b)+c)
# if passed '' and '' will return a+b+c
lambda x,y:x.join(map(y.join,zip(n,c+('',)))).replace('^','**')

# evaluate infix
E(L('',''))
# evaluate prefix
E('('*-~l+L('',')'))
# evaluate postfix
E(L('(','')+')'*l)
# all evals need to be inside try-except to handle possible 0 division

# prefix output is need to be swapped (which IMO is not needed)
n:print C[::-1]+n

```
> 0 votes

---
Tags: code-golf, number, arithmetic
---


title: Decode the hidden message!

text:
# Question
Title: Decode the hidden message!
# Introduction

One day, you were just relaxing in your office in the CIA, when suddenly you see an alert on your computer. Your programs have just intercepted hundreds of coded messages! A quick examination reveals the rule for encoding, but you need a program in order to decode fast.

# Challenge

You will be given a list of strings, separated by commas. Each string will contain either:

* Part of the coded message
    + It is part of the coded message if it is **not** in the form `a=b`. Note that it **is** part of the message if it is `ab=c`. Add this string to the coded message.
* Part of the encoding scheme
    + This will be in the form of `a=b`. That means that all a's in the message must be replaced by b's. Note that it could be `a==`, meaning that all a\`s must be replaced with ='s.

Your program must then output the message, decoded using the scheme found.

Other info: Your input will only contain commas for separating the strings. It could contain other characters, like !1#, etc. It will not contain uppercase letters. Bits of decoding info do not decode each other. Only the message is affected by the decoding information. Only one replacement will be given for each character, e.g. no `"io,"i=u","i=g"`

# Examples

Input:`"ta","y=s","y","a=e","b=t","b"," ","j","j=1"`

Output:`test 1`

Input:`"z=p","zota","g=e","yugkb","y=t","u=o","k=s","li","fg","b=="`

Output:`potatoes=life`

Input:`"p","=","==n","ot","p=a","hiz","i=e","z=r"`

Output:`another`

This is , so shortest answer in bytes wins!

# Answer
# Jelly, 19 bytes

```
ḊṖ⁼“=”
ÇÐfKm2yÇÐḟF$

```

**Try it online!**

### How?

```
ḊṖ⁼“=” - Link 1, isMappngElement?: string
Ḋ      - dequeue
 Ṗ     - pop
   “=” - char-list,['=']
  ⁼    - equal?

ÇÐfKm2yÇÐḟF$ - Main link: list of strings
 Ðf          - filter keep:
Ç            -     last link (1) as a monad
   K         - join with spaces
    m2       - modulo 2 slice (every other character)
           $ - last two links as a monad:
        Ðḟ   -     filter discard:
       Ç     -         last link (1) as a monad
          F  -     flatten
      y      - translate right according to the mapping of left

```
> 1 votes

# Answer
# Python 3, 98

```
lambda l:''.join(x*('='!=x[1:-1])for x in l).translate({'='!=x[1:-1]or ord(x[0]):x[2:]for x in l})

```

This `lambda` function receives a list of strings (input) and returns a string (the decoded message).

Examples:

```
>>> f(['ta', 'y=s', 'y', 'a=e', 'b=t', 'b', ' ', 'j', 'j=1'])
'test 1'
>>> f(['z=p', 'zota', 'g=e', 'yugkb', 'y=t', 'u=o', 'k=s', 'li', 'fg', 'b=='])
'potatoes=life'
>>> f(['p', '=', '==n', 'ot', 'p=a', 'hiz', 'i=e', 'z=r'])
'another'

```
> 5 votes

# Answer
# Haskell, 85 bytes

```
f x=[(a,b)|[a,'=',b]<-x]
h x=map(\v->maybe v id$lookup v$f x)$concat[c|c<-x,[]==f[c]]

```

### Usage

```
>h ["p","=","==n","ot","p=a","hiz","i=e","z=r"]
>"another"

```

### Description

`f` creates a lookup table.

`concat[c|c<-x,[]==f[c]]` extracts the message.

`map(\v->maybe v id$lookup v$f x)` perfoms the lookup.
> 2 votes

# Answer
# JavaScript (ES6), 87 bytes

```
(l,s='',d={})=>l.map(v=>/.=./.test(v)?d[v[0]]=v[2]:s+=v)&&[...s].map(c=>d[c]||c).join``

```

```
<input id=a oninput="try{b.innerText=((l,s='',d={})=>l.map(v=>/.=./.test(v)?d[v[0]]=v[2]:s+=v)&&[...s].map(c=>d[c]||c).join``)(eval(`[${a.value}]`))}catch(e){}"/>
<p id=b />
```
> 2 votes

# Answer
# Retina, ~~84~~ ~~82~~ ~~77~~ 74 bytes

Takes a comma-separated list as input. Note the trailing newline

```
^|$
,,
+`,(.=.)(,.*)
$2$1
M!&`(.).*,,.*\1=.|.+,
%`(.).*,$|.*(.)
$1$2
\n|,

```

Try it Online!

**Explanation:**

First, we move all expressions of the form `.=.` to the end of the string and separate these from the message with a double comma (`,,`). This is so that in the next step, we can find all encodings by checking if each character ahead of the `,,` has a matching `=.` afterwards. This is achieved by `M!&`(.).*,,.*\1=.|.+,` which finds all such matches and places them into a linefeed separated list of strings. We then modify each string to only contain either one unencoded character or the encoded version of the character. Finally we replace all linefeeds and commas with the empty string so that our output is formatted nicely.
> 1 votes

# Answer
## Batch, 188 bytes

```
@echo off
set/pm=
set c=
for %%s in (%m%)do call:c %%s "%%c%%%%~s" not
for %%s in (%m%)do call:c %%s "%%c:%%~s%%"
echo %c%
exit/b
:c
set s=%~1
if %3 "%s:~1,1%"=="=" call set c=%~2

```

Explanation: Loops through the list of strings twice (conveniently `for` likes a string in CSV format). The first time, looks for strings that do not contain an `=` as the second character, and concatenates them to the result. The second time, looks for strings that do contain an `=` as the second character, and performs the substitution. (even more conveniently, the substitution is already in Batch format.)
> 0 votes

# Answer
# PHP, 116 Bytes

```
<?foreach($_GET as$i)$i[1]=="="&&strlen($i)==3?$r[]=$i:$s.=$i;foreach($r as$l)$s=str_replace($l[0],$l[2],$s);echo$s;

```

Online Version
> 0 votes

# Answer
# PHP, ~~89~~ 87 bytes

two versions:

```
while(a&$s=$argv[++$i])3==strlen($s)&"="==$s[1]?$t[$s[0]]=$s[2]:$m.=$s;echo strtr($m,$t);
while(a&$s=$argv[++$i])preg_match("#^.=.$#",$s)?$t[$s[0]]=$s[2]:$m.=$s;echo strtr($m,$t);

```

takes input from command line arguments; run with `-nr`.

* loop through arguments creating parameters for `strtr`
(translation if argument contains `=`, message else).
* perform `strtr`.
> 0 votes

# Answer
# 05AB1E, 31 bytes

```
vy'=åyg3Q&iyˆyS}})øJÁ¨`¹¯KJ.Ás‡

```

Try it online!

```
vy              }
  '=åyg3Q&                      # See if it's length 3 with an equals in the mid.
          iyˆyS                 # If so, add to global array, split into chars.
               }
                 )øJÁ¨`         # Transpose, join, and remove the middle =.
                       ¹¯KJ     # Push original input without decryption key.
                           .Ás‡ # Shift stack to the right, swap and transliterate.

```
> 0 votes

---
Tags: code-golf, string, cryptography
---


# Question
Title: Mapping between integer and pronounceable word
### Purpose

The idea is to provide the code necessary to map a 32-bit integer to/from a pronouncable word of 9 characters maximum. That could be useful, for example, to make a serial number easier to remember, or type in a form.

Both the method for translating an integer to the corresponding word and for translating back a word to the corresponding integer are required.

### Rules

There must be a one-to-one mapping between integers and words, and the whole set of 32-bit integers (or, put in another way, any integer from 0 to 4294967295) must be mappable. Although, obviously, not all words will be meaningful, and inputting words that don't map to an integer may have unspecified behavior.

You are free to decide on exactly which set of "pronouncable" words is meaningful, and how the mapping is done, but words must at least follow these rules:

* Only the basic 26 letters (A...Z) should be used as characters. Accents, casing, etc... should not be used to extend the possible combinations.
* 9 characters maximum per word.
* two consonants (BCDFGHJKLMNPQRSTVWXZ - 20 possiblities) should not be placed next to each other (they must be surrounded by vowels).
* two vowels (AEIOUY - 6 possibilities) should not be placed next to each other (they must be surrounded by consonants).

Note: the simplest scheme where you have all words constructed as `CVCVCVCVC` (`C` being a consonant and `V` a vowel) gives 4147200000 combinations, and a 32 bit integer has 4294967296 possible values, so it is not enough. You need to expand the number of combinations, either by allowing shorter words, or by allowing `VCVCVCVCV` combinations, as well.

Other standard rules apply, and standard loopholes are forbidden.

### Inputs/Outputs

For each submission, two pieces of code must be provided:

* One that takes an integer as argument/input and returns/prints the corresponding word
* One that takes a word as argument/input and returns/prints the corresponding integer

Alternatively, you can choose to submit a single piece of code that handles both operations:

* When given an integer as an input, it outputs the corresponding word
* When given a string as an input, it outputs the corresponding integer

### Winning condition

This is a , the answer which has the fewest bytes (when summing both pieces of code, for solutions opting for the separated pieces of code) wins.

# Answer
> 1 votes
## JavaScript (ES6), 205 bytes

```
p=>(a='bcdfghjklmnpqrstvwxzaeiouy',1/p)?[...Array(9)].map(_=>r=a[p%(n=26-n)+(p=p/n|0,n<7)*20]+r,n=p>(p%=4e9)?20:6,r='')&&r:[...p].map(c=>r=r*(n=26-n)+a.search(c)%20,n=a.search(p[r=0])<20?6:20)&&r+(n<7)*4e9

```

Cutoff point between CVCVCVCVC and VCVCVCVCV is 4e9, so starts going wrong at 5244160000 (numeric input) or `zesuwurib` (string input).

# Answer
> 2 votes
# PHP, 353 Bytes

Encoding + Decoding

`is_numeric($argn)` contains the boolean. It is true if the input is an integer.

```
$c=array_diff(range(A,Z),$v=[A,E,I,O,U,Y]);sort($c);if(is_numeric($a=$argn)){$r=($a)%26<6?$v[$a%26]:$c[$a%26-6];$a=$a/26^0;while($a){$z=count($t=in_array($r[0],$v)?$c:$v);$r=$t[$n=$a%$z].$r;$a=$a/$z^0;}echo$r;}else{for($p=1;$i++<strlen($a);){$u=($b=in_array($a[-$i],$c))?$c:$v;$s+=array_flip($u)[$a[-$i]]*$p+($b&$i<2?6:0);$p*=$i>1?count($u):26;}echo$s;}

```

## PHP, 190 Bytes (Encode) + 195 Byte (Decode) = 385 Bytes

## Encoding

```
$c=array_diff(range(A,Z),$v=[A,E,I,O,U,Y]);sort($c);$r=($a=$argn)%26<6?$v[$a%26]:$c[$a%26-6];$a=$a/26^0;while($a){$z=count($t=in_array($r[0],$v)?$c:$v);$r=$t[$n=$a%$z].$r;$a=$a/$z^0;}echo$r;

```

5391360000=26\*120\**4 combinations are available

Online Version Encoding without E\_NOTICE

## Expanded

```
$c=array_diff(range(A,Z),$v=[A,E,I,O,U,Y]);
sort($c); # End of Prepare the two array
$r=($a=$argn)%26<6?$v[$a%26]:$c[$a%26-6]; #base 26 decision input mod 26 <6 end with vowel
$a=$a/26^0; #integer division input with 26
while($a){
    $z=count($t=in_array($r[0],$v)?$c:$v); # use vowel if last entry is consonant and viceversa
    $r=$t[$n=$a%$z].$r; # base 6 or base 20 decision
    $a=$a/$z^0; # divide through base
}echo$r; # Output result

```

## Input =\> Output

```
4294967296 => TYPYQACOV
333 => DAT
1 => E
7 => C
4294967276 => UTOPOQAMI

```

If you need always 9 Byte result please replace `while($a)` with `while(strlen($r)<9)` \+ 10 Bytes

## Decoding

```
$c=array_diff(range(A,Z),$v=[A,E,I,O,U,Y]);sort($c);for($p=1;$i++<strlen($a=$argn);){$u=($b=in_array($a[-$i],$c))?$c:$v;$s+=array_flip($u)[$a[-$i]]*$p+($b&$i<2?6:0);$p*=$i>1?count($u):26;}echo$s;

```

## Expanded

```
$c=array_diff(range("A","Z"),$v=["A","E","I","O","U","Y"]);
sort($c); # End of Prepare the two array
for($p=1;$i++<strlen($a=$argn);){
    $u=($b=in_array($a[-$i],$c))?$c:$v; # find use array for $a[-$i]
    $s+=array_flip($u)[$a[-$i]]*$p+($b&$i<2?6:0); # sum value
    $p*=$i>1?count($u):26; # raise multiple for next item
}echo$s;

```

## Input =\> Output

```
ABABABABE => 1
E => 1
UTOPOQAMI => 4294967276
BABABADAT => 333
DAT => 333
TYPYQACOV => 4294967296

```

Online Version Decoding without E\_NOTICE

## Additional Check

If we need a check if a string is valid.

Add `$x.=$b?:0;` in the end of the decoding loop + 10 Bytes

Replace `echo$s;` with `echo!preg_match('#([01])\1$#',$x)?$s:_;` \+ 32 Bytes

# Answer
> 1 votes
# R, 165 bytes

Encoding and decoding in one function.

This function uses the brute-force method of creating all possible values and then simply returning the index when it's given string input and returning the string when given integer input. As a consequence, it's very slow and uses 16GB+ of memory!

```
function(x){i=c(1,5,9,15,21,25)
d=apply(expand.grid(c<-letters[-i],v<-letters[i],c,v,c,v,c,v,c(c,"")),1,paste,collapse="")
`if`(mode(x)=="numeric",d[x],which(d==x))}

```

4,354,560,000 values are possible. This covers all strings of form CVCVCVCV(C), with the last C being optional.

---
Tags: code-golf, string, integer
---


title: Tetration: (Very) Hard Mode

text:
# Question
Title: Tetration: (Very) Hard Mode
This question is inspired by this one

# Your task

Make a program or function that calculates the Tetration of 2 numbers. Tetration is what "comes next after addition, multiplication, and exponents".

For example, passing in `3` and `3`, this is calculated:

```
3 ^ (3 ^ 3)

```

yielding this:

```
7625597484987

```

Simple, right?

# ***WRONG.***

# Rules

The rules are taken from this question's inspiration.

> ## Rules:
>
> * An integer is 64 bits, signed, two's complement. This is the *only* data type you may work with.
> * **You may only use the following operations. Each of these counts as one operation.**
>     + `n << k`, `n >> k`: Left/right shift `n` by `k` bits. Sign bit is extended in right shift.
>     + `n >>> k`: Right shift but do not extend sign bit. 0's are shifted in.
>     + `a & b`, `a | b`, `a ^ b`: Bitwise AND, OR, XOR.
>     + *\[removed\]*, `a - b` *\[removed\]*: *\[removed\]*, subtract *\[removed\]*
>     + `~b`: Bitwise invert.
>     + `-b`: Two's complement negation.
>     + `a / b`, `a % b`: Divide (integer quotient, rounds towards 0), and modulo.

* Comparison operators (`<=`, `>=`, `>`, `<`, etc.) are allowed but count as one operation.

> ```
>    - Modulo of negative numbers uses the rules [specified in C99](http://stackoverflow.com/a/11720841/616460): `(a/b) * b + a%b`
>
> ```
>
> shall equal `a`. So `5 % -3` is `2`, and `-5 % 3` is `-2`: \- `5 / 3` is `1`, `5 % 3` is `2`, as 1 * 3 + 2 = 5. \- `-5 / 3` is `-1`, `-5 % 3` is `-2`, as -1 * 3 + -2 = -5. \- `5 / -3` is `-1`, `5 % -3` is `2`, as -1 * -3 + 2 = 5. \- `-5 / -3` is `1`, `-5 % -3` is `-2`, as 1 * -3 + -2 = -5. \- Note that Python's `//` floor division operator does not satisfy the "round towards 0" property of division here. \- Assignments do not count as an operation. As in C, assignments evaluate to the value of the left-hand side after the assignment: `a =
>  (b = a + 5)` sets `b` to `a + 5`, then sets `a` to `b`, and counts as one operation. \- Compound assignments may be used `a += b` means `a = a + b` and count as one operation. \- You may use integer constants, they do not count as anything. \- Parentheses to specify order of operations are acceptable. \- You may declare functions. Function declarations can be in any style that is convenient for you but note that 64 bit integers are the *only* valid data type. Function declarations do not count as operations, but a function *call* counts as one. Also, to be clear: Functions may contain multiple `return` statements and `return`s from any point are allowed. The `return` itself does not count as an operation. \- You may declare variables at no cost. \- You may use `while` loops, but you may not use `if` or `for`. Operators used in the `while` condition count towards your score. `while` loops execute as long as their condition evaluates to a *non-zero* value (a "truthy" 0 in languages that have this concept is not a valid outcome). Since early-return is allowed, you are allowed to use `break` as well \- Overflow/underflow is allowed and no value clamping will be done. It is treated as if the operation actually happened correctly and was then truncated to 64 bits.
>
> ## Scoring / Winning Criteria:

...

> This is . Your score is the total number of operations present in your code (as defined above), *not* the total number of operations that are executed at run-time. The following code:
>
> ```
> function example (a, b) {
>     return a + ~b;
> }
>
> function ispowerofnegtwo (input) {
>     y = example(input, 9);
>     y = example(y, 42);
>     y = example(y, 98);
>     return y;
> }
>
> ```
>
> Contains 5 operations: two in the function, and three function calls.
>
> It doesn't matter how you present your result, use whatever is convenient in your language, be it ultimately storing the result in a variable, returning it from a function, or whatever.
>
> The winner is the post that is demonstrably correct (supply a casual or formal proof if necessary) and has the lowest score as described above.
>
> Note: If you'd like to provide a solution in a language that only supports 32-bit integers, you may do so, provided that you sufficiently justify that it will still be correct for 64-bit integers in an explanation.
>
> Also: *Certain* language-specific features may be permitted at no-cost *if they do not evade the rules but are necessary to coerce your language into behaving according to the rules above*. For example (contrived), I will permit a free *not equals 0* comparison in `while` loops, when applied to the condition as a whole, as a workaround for a language that has "truthy" 0's. *Clear attempts to take advantage of these types of things are not allowed* -- e.g. the concept of "truthy" 0 or "undefined" values does not exist in the above ruleset, and so they may not be relied on.

`break`s are allowed, but they count as an operation.

Also, if your language has no concept of 64-bit ints, you may use any other form of number.

# **Note that you are not allowed to use multiplication, exponentiation, or addition.**

# Answer
## Ruby, 13 operations

```
def tetr(a, b)
  def exp(a, b)
    def mult(a, b)
      c = 0; i = 0; while(i > -b) do c -= a; i -= 1; end
      return -c
    end
    c = 1; i = 0; while(i > -b) do c = mult(c, a); i -= 1; end
    return c
  end
  c = a; i = -1; while(i > -b) do c = exp(a, c); i -= 1; end
  return c
end

```

OP has stated that comparison is allowed.
> 2 votes

# Answer
# Wise, ~~31~~ 29

```
:::[:^|>::>^]|[:^?-!]^
::^? [::><^[-~!~-?]^>?->!]^
!:-~[:^&:]^?-&

```

When I saw this question I thought it would be the perfect question to answer in Wise. The way Wise is set up it is impossible to make an answer that does not qualify for this challenge because all of Wise's operations are bitwise.

* `:`, `!`, and `?` are all stack operations which I am considering to be variable assignments so they do not count towards the score
* `[]` constitute a while loop so they don't count towards the score.
* `^`,`|`, and `&` are bitwise XOR, OR, and AND respectively
* `>`,`<` are the bitshifts,
* `~` is bitwise negation and `-` is regular negation.

### Explanation

First we want to take the absolute value of the number so that we can check if the number is a power of 2.

```
:[:^|>::>^]|

```

is a program I wrote a while ago to get the sign bit of a number.

\[:^?-!\]^

will negate the number if the top of the stack is `-1`, that is if our input was negative.

Now that we have a positive number we want to check if it is a power of 2. to do this we take the sum of the digits (in base 2) and check if it is one. To do that we set up a zero on the bottom of the stack:

```
::^?

```

and loop through adding the last digit and dividing by 2 (bit-shifting once)

```
[::><^[-~!~-?]^>?-!]^!

```

While we are doing this we divide a copy of our original input by `-2` (`->`) each time we loop. If the result `-1` and the absolute value of the input was a power of `2` it is a power of `-2`.

Now we subtract one `-~` and take the logical not of the digit sum.

```
[:^&:]^

```

We roll this result to the bottom with `?` and finish up with a logical and with `-&`
> 2 votes

---
Tags: math, number, atomic-code-golf
---