title: Robbers: Crack the regex - Make a snake

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

---

A snake matrix is a square 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

```

Your task is to write a code that takes an input `n` and creates such a matrix, in the same language as a cop post, and with a code that matches the cop's regex. The output format of your code must match the output format of the cop's code.

Please leave a comment under the Cop's post to indicate that you have cracked it.

**Winning criterion:**

The winner will be the user that has cracked the most submissions. In case of a tie, then there will be multiple winners.

# Answer
# Jelly, 9 bytes, cracks @Dennis' answer

```
²sµUFḤ$¦G

```

Try it online!

Should be correct now; I had to rather rethink what I was doing.

## Explanation

The hardest part of this problem is getting a list of the even indices inside the `¦` (which applies an operation at specific indices). Unlike most operations, which use the input to the whole program as a default for the second operand, `¦` uses the most recently seen value as a default (because it conceptually has two left operands, rather than a left and a right operand like most things that take in two values).

However, we can observe that we have a list of numbers, including all integers from 1 to half the input, already in the current value at the time. As such, flattening and doubling it gives us a list of even numbers, including all the even indices (also some other even numbers but we don't care about those). It's even possible to spend one `µ` solely to avoid a parsing ambiguity and still come in within 9 characters.

```
²sµUFḤ$¦G
 s         Split
²          {the list of numbers from 1 to} the square of {the input}
  µ        into a number of pieces equal to {the input};
   U       then reverse
       ¦   the elements at indexes
    F      obtained by flattening the split list
      $    and
     Ḥ     doubling each element in the flattened list;
        G  finally, format it into a grid.

```
> 10 votes

# Answer
# 05AB1E, Emigna

This was my first time using 05AB1E. Got it with a little bit of help. That was fun. :)

```
UXFXLNX*+N2BSR1k_iR}ˆ

```

**Try it online**

**Explanation:**

```
U                       Assign input to X
 XF                     For N in range(0,X):
   XL                   Push list [1 .. X]
     NX*+               Add N*X to each element of the list
         N2BSR1k_       Super clever way to get N%2:
                            not bool(reversed(str(bin(N))).index('1')) (N%2 is odd)
                 iR}    if N%2 is odd, then reverse the list
                    ˆ   Add row to global array
                        Implicit print

```

I actually found this similar program on my own, but the output format is different:

```
UXFXLNX*+N2BSR1k_iR}=

```

**Try it online**

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

```

See the edit history for my previous two attempts.
> 9 votes

# Answer
# Python 2, Dennis

This is a fun token golfing problem.

```
while ord>eval:1;int,eval=int<1and(int,eval+1)or(-input(),1);i=int;ord=i*i;print'%*s'%(-i,(eval+~i+~-eval%-i*~1,eval)[eval/i&1])+'\nt'[:-1<eval%int],

```

Regex verification
> 6 votes

# Answer
# Ohm, Nick Clifford

My first time attempting Ohm.
Really nice language that I look forward to use again :)

```
²@┼σ▓_^è?R

```

**Explanation**

```
²             # square input
 @            # range [1 ... input^2]
  ┼σ          # split in input sized chunks
    ▓         # perform the following block on each element of the array
     _        # current element
      ^è?     # if index is odd
         R    # reverse

```

My first attempt that didn't work as adding an array and an int is not possible:

```
@┼MDR┼+;W

```

My second attempt that didn't match the regex:

```
²@┼σ▓_^MR

```
> 5 votes

# Answer
# 05AB1E, Emigna (2nd submission)

First time working with 05AB1E.

```
VYLUYFYXDˆ+RU

```

Try it online! | Regex verification

**Explanation**

```
VYLUYFYXDˆ+RU  # Implicit input
V              # Save input to Y
 YL            # Push [1 .. Y]
   U           # Save list to X
    YF         # Repeat Y times:
      YX       # Push Y, then X
        Dˆ     # Add X into the global array (could've used X here instead)
          +    # Push X + Y
           R   # Reverse top of stack
            U  # Save updated list to X
               # Implicit loop end
               # Implicit global array print if stack is empty

```
> 5 votes

# Answer
## CJam, Lynn

```
esmpmpmeimtmemqmememqicelic
esmpmpmeimememqmlmtmemoc
esmpmpmeimememqmtmtmtmtmeic
esmpmpmeimememqmtmtmtmtmeic
esmpmpmeimeiscic
esmpmpmeimemeimfsic
esmpmpmeisciscimqmtmemeic
esmpmpmeiscimlmqmqmemeic
esmpmpmeimemomqmqmemeic
esmpmpmeisciscimfsimqic
esmpmpmeimeiscic
esmpmpmeisciscimfsimqic
esmpmpmeimemomqmemqmemtmemoc
esmpmpmeiscic
esmpmpmeimemomeimqmeic
esmpmpmeimemeimqmlmtmeic
esmpmpmeimtmtmqmemtmtmeic
esmpmpmeimemomqmqmtmeic
esmpmpmeimemqmqmemeic
esmpmpmeiscimlmqmqmemeic
esmpmpmeiscimqmtmtmtmqmemeic
esmpmpmeimeimemtmqmemeic
esmpmpmeimeiscimlmlmtmlmtic
esmpmpmeimemeimqmlmtmeic
~~

```

All linefeeds are for cosmetic purposes and can be removed without affecting the program.

Try it online!

### Explanation

After Lynn removed `{|}` from the list of allowed characters, I had to try something new. It turns out we can still construct arbitrary strings and evaluate them as code.

First, we need to get some value onto the stack. The only available built-ins that push something without popping something else first (and without reading the input) are `es`, `ea` and `et`. I'm sure you could start from all of these one way or another, but I went with `es` which pushes the current timestamp. Since I didn't want to make any assumptions about its actual value, I test its primality with `mp` (which gives `0` and `1`) and test that value's primality again to ensure I've got a `0` on the stack. A `1` will be more useful, so we compute `exp(0)` with `me` and turn it into an integer with `i`. So all the numbers start with:

```
esmpmpmei

```

Now we've got a whole bunch of unary maths operators to work with:

```
i    int(x) (floor for positive numbers, ceiling for negative)
me   exp(x)
ml   ln(x)
mq   sqrt(x)
mo   round(x)
mt   tan(x)

```

We can also combine a few built-ins for more elaborate functions of `x`:

```
sci     Extract first digit of x and add 48 (convert to string, convert
        to character, convert to integer).
ceui    Convert to character, convert to upper case, convert to integer.
celi    Convert to character, convert to lower case, convert to integer.
mfsi    Get a sorted list of prime factors of x and concatenate them into
        a new number.
mfseei  Get a sorted list of prime factors, interleave it with 1,2,3,..., and
        concatenate the result into a new number.

```

Using these, we can obtain any number in `0 <= x < 128` (and many others) in less than 10 steps from `1`. I'm sure a much smaller subset of these commands would also suffice. I've written a small Mathematica program, to determine all of these snippets (it's not very readable, sorry):

```
codes = SortBy[
  Select[Nest[Select[DeleteDuplicatesBy[SortBy[Join @@ (Through[{
               List,
               If[1 <= # < 50, {Exp@#, #2 <> "me"}, Nothing] &,
               If[# >= 1, {Log@#, #2 <> "ml"}, Nothing] &,
               If[# > 1, {Sqrt@#, #2 <> "mq"}, Nothing] &,
               {If[# > 0, Floor@#, Ceiling@#], #2 <> "i"} &,
               {Floor[# + 1/2], #2 <> "mo"} &,
               {Tan@#, #2 <> "mt"} &,
               If[NumberQ@# && # >= 0, {First@
                   ToCharacterCode@ToString@#, #2 <> "sci"},
                 Nothing] &,
               If[IntegerQ@# &&
                  32 < # < 65536, {First@
                   ToCharacterCode@
                    ToUpperCase@FromCharacterCode@#, #2 <> "ceui"},
                 Nothing] &,
               If[IntegerQ@# &&
                  32 < # < 65536, {First@
                   ToCharacterCode@
                    ToLowerCase@FromCharacterCode@#, #2 <> "celi"},
                 Nothing] &,
               If[IntegerQ@# && # > 0, ## & @@ {
                   {FromDigits[
                    "" <> (ToString /@ (f =
                    Join @@ Table @@@ FactorInteger@#))], #2 <>
                    "mfsi"},
                   {FromDigits[
                    "" <> (ToString /@
                    MapIndexed[## & @@ {#2[[1]] - 1, #} &, f])], #2 <>
                     "mfeesi"}
                   }, Nothing] &
               }@##] &) @@@ #, StringLength@*Last],
       First], #[[1]] < 1000000 &] &, {{1, "esmpmpmei"}}, 9],
   IntegerQ@# && 0 <= # < 128 &@*First], First]

```

With that, we can simply push an arbitrary list of character codes, converting each of them to a character with `c` afterwards. Once we've pushed the entire code we want to execute, we push `95` (`]`). We eval that one with `~` to wrap all the others in a string, and then we eval that string with `~`.

The actual code run at the end of the program is again:

```
ri__2#,:)/2/[1W]f.%:~<p

```

See my previous solution for an explanation.
> 5 votes

# Answer
# Python 3, TuukkaX

Sorry, the regex you used was too easy to trivialize. No `0`, `#` or ? No problem!

I might've misinterpreted the example output but it's still pretty easy to tweak since I have 45 spare characters left over

```
n=int(input())
print(str(n)+":")
x=1-1
exec("print([*range(1+x*n,1+n*-~x)][::(1,-1)[x%2]]);x+=1;"*n)
"no-op:a_string_that_doesnt_actually_matter"

```
> 4 votes

# Answer
# R, MickyT

```
lets_make_a_snake<-function(n)`for`(i,1:n,cat(i*n+1-`if`(i%%2,n:1,1:n),"\n"))

```

Tests cases:

```
> lets_make_a_snake(4)
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
> lets_make_a_snake(7)
1 2 3 4 5 6 7
14 13 12 11 10 9 8
15 16 17 18 19 20 21
28 27 26 25 24 23 22
29 30 31 32 33 34 35
42 41 40 39 38 37 36
43 44 45 46 47 48 49

```

And regex confirmation: https://regex101.com/r/OB8ZIM/1

I also had:

```
invisible(sapply(1:(n=scan()),function(i)cat(i*n+1-`if`(i%%2,n:1,1:n),"\n")))

```

which gives the same output and match the same regex.
> 4 votes

# Answer
# Röda, fergusq

```
{|i|;a=1;while[a<=i]do;b=a*i-i+1;c=[];while[b<=a*i]do;c+=b;b++;done;{d=[];x=0;while[x<i]do;d+=c[i-x-1];x++;done[d]}if[a%2<1]else{[c]};a++;done;r="||||||"}

```

This is an anonymous function that matches this PCRE regex: `^{(\|[^\/#\s]*){8}$`.

Try it online!
> 4 votes

# Answer
# Bash, @Marcos M

```
sort -n <(seq 1 $((n * n)) | xargs -n$n | sed -n 'p;n'; seq $((n * n)) 1 | xargs -n$n | sort -n | sed -n 'n;p')

```

Prettified:

```
sort -n <(               # feed the stdout of this subshell into stdin for `sort -n`
    seq 1 $((n * n)) |   #   generate 1 2 3 ... n²
        xargs -n$n |     #     add line break every n numbers
        sed -n 'p;n';    #     print only odd lines
    seq $((n * n)) 1 |   #   generate n² ... 3 2 1
        xargs -n$n |     #     add line break every n numbers
        sort -n |        #     reverse all lines (keeping each row decreasing)
        sed -n 'n;p'     #     print only even lines
)

```

The first part of the subcommand will generate `1 2 3 4`, `9 10 11 12`, and the second part will generate `8 7 6 5`, `16 15 14 13`. The outer `sort -n` will properly mix them together to form the snake pattern.

I used the trick in https://superuser.com/a/101760 to print the odd and even lines. Thank you Marcos, really a fun one.
> 4 votes

# Answer
# Javascript, Tom

```
f=(a,i=1,j=0)=>Array(a).fill(0).map(b=>Array(a).fill(0).map(a=>i++)).map(a=>j++%2?a.reverse():a).map(a=>a)

console.log(f(4))
```
> 3 votes

# Answer
# Python 3, @TuukkaX

```
n=int(input());j=0;exec("print([(j-+i%n-n++2*n-0,j+i%n+1)[1&int(i/n)//1^(0x1)//1]*(2*(i%n)*0+2222222//2222222)for i in range(j,j+n)]);j+=n;"*n)

```

---

Slightly analyzing the cop's regex shows a fixed template:

```
________________________"___________i%n____2*n-____i%n__________i/n)//1_____)//1___2*(i%n)____^^^^^^^^^^^^^^^^for i in range(j,____])______"*n)

```

where `_` is any character except `[ '"#]` and `^` is any of `[int()2/]`.

The `"*n)` at the end clearly shows an `eval("..."*n)` or `exec("..."*n)` is going on, so we just need to make sure the `"..."` prints the j-th row.

The `for i in range(j,` is too close to the end of the string, hinting list comprehension without any `if`. So we need to construct the i-th column using those `i%n`, `2*n` stuff.

```
n = int(input())
j=0
exec("""print([
    (
        j - +i%n - n ++ 2*n - 0,    # equivalent to (n + j - i%n) for the decreasing rows
        j + i%n + 1                 # equivalent to (j + i%n + 1 == i + 1) for the increasing rows
    )[1 & int(i/n)//1 ^ (0x1)//1]   # int(i/n)   ->    get row number 0, 1, 2, 3, ...;
                                    # 1 & int(i/n)//1    ->    0 for increasing rows, 1 for decreasing rows,
                                    # 1 & int(i/n)//1 ^ (0x1)//1    ->   flip 0 and 1
    * (2*(i%n)*0+2222222//2222222)  # multiply by the constant 1.
    for i in range(j,j+n)
]); j+=n; "*n)

```
> 3 votes

# Answer
## dc, Mitchell Spector

This was my first entry to a cops and robbers challenge, and I had a lot of fun. The regex needed to be matched was simple, `^[^# !]{59}$`, which basically turned my job into a golfing one, without using those 3 characters. Initially I had difficulties getting below 60 bytes, but I cracked it in the end.

```
?sN0[AP]sP[ddlN~_2*lN+1-r2%*+1+n32P1+dlN%0=PdlNd*>L]dsLxqqq

```

**Try it online!**

**Explanation:**

My code uses one loop with N<sup> 2</sup> iterations, keeping a zero based counter (1D), and calculates what number needs to be printed based on the corresponding matrix row and column (r, c) coordinates.

Example of what I mean, if N = 4:

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

```

It looks complicated, but the intermediary step is helpful. Plus, I've tried using 2 loops from the start, but I ended up above the regex character limit. Number generation at each iteration (zero based):

* if `r % 2 = 0` (normal row), `n = (r * N) + c = counter`
* if `r % 2 = 1` (reversed row), `n = ((r + 1) * N) - c - 1 = counter + N - (2 * c) - 1`

Or all at once, as one based numbering: `n = counter + ((N - (2 * c) - 1) * (r % 2)); n++`

```
?sN0             # read input, save as N, initialize iteration counter
[AP]sP           # macro 'P' that prints a newline (ASCII code 10 = A)
[                # start loop
    ddlN~        # push N, calculate row and column coordinates:
                 #r = int(counter / N), c = counter % N, '~' calculates both
    _2*lN+1-     # c is on top, so this does: N - (2 * c) - 1
    r2%*+        # now r is on top, do: (r % 2) * (previous result) + counter
    1+n32P       # do: n++, print space (ASCII code 32)
    1+           # increment counter
    dlN%0=P      # call macro 'P' every Nth printed number
    dlNd*>L      # if: N * N > counter, repeat loop
]dsLx            # this saves the loop to macro 'L', then executes it
qqq              # my script was shorter, so I added a bunch of quit commands to
                 #fit the regex limit. Use of comments ('#') was prohibited.

```
> 3 votes

# Answer
## PowerShell, ConnorLSW

Crack

```
$mySnakeIndex=1;$seq=1..$args[0];$seq|%{$rowNum=$seq|%{($mySnakeIndex++)};if(!($_%2)){[array]::Reverse($rowNum)};$rowNum-join" "}

```

I started with a smaller solution to the issue and padded my variable names to get the regex to match. Trying to find a use for the colon I suppose was the hardest part to wrap my head around.

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

```

# Explanation

```
# Initialize a counter that starts at one.
$mySnakeIndex=1
# Save the integer array from 1 to the input value.
$seq=1..$args[0]
# For each row of the output...
$seq|%{
    # Build the integer array for this row sequentially
    $rowNum=$seq|%{
        # Increase the integer index while sending it down the pipeline
        ($mySnakeIndex++)}
        # Check if this is and odd row. If so reverse the integer array.
        if(!($_%2)){[array]::Reverse($rowNum)}
        # Take this row and join all the numbers with spaces.
        $rowNum-join" "

```
> 3 votes

# Answer
## CJam, Lynn

Something like this:

```
ri
{s}seu~~ci{zs}seu~~c{a}seu~~|~{w}seu~~z{w}seu~~sc~c{z}seu~~{w}seu~~sc~c{w}seu~~z{w}seu~~sc~c~

{s}seu~~ci{z}seu~~{s}seu~~c{a}seu~~|~{w}seu~~z{w}seu~~sc~c
{s}seu~~ci{z}seu~~{s}seu~~c{a}seu~~|~{w}seu~~z{w}seu~~sc~c
{s}seu~~ci{z}seu~~{s}seu~~c{a}seu~~|~{w}seu~~z{w}seu~~sc~c
{s}seu~~c{a}seu~~|
{s}seu~~c{c}seu~~|
{t}seu~~sc{a}seu~~|
{s}seu~~c{a}seu~~|{w}seu~~z{w}seu~~sc~c
{s}seu~~sc{fb}seu~~||
{s}seu~~sc{i}seu~~|
{s}seu~~sc{fb}seu~~||
{s}seu~~ci{z}seu~~{s}seu~~c{a}seu~~|~{w}seu~~z{w}seu~~sc~c{z}seu~~{w}seu~~sc~c{w}seu~~z{w}seu~~sc~c
{a}seu~~scs
{w}seu~~
{s}seu~~ci{z}seu~~{s}seu~~c{a}seu~~|~{z}seu~~{w}seu~~sc~c
{fb}s{b}s{w}seu~~sc~
{s}seu~~sc{ee}seu~~||
{s}seu~~sc{z}seu~~|{w}seu~~{w}seu~~sc~{w}seu~~{w}seu~~sc~
{t}seu~~sc{a}seu~~|
{~}s{}s{w}seu~~sc~
{t}seu~~sc{c}seu~~|

{s}seu~~ci{z}seu~~{s}seu~~c{a}seu~~|~{z}seu~~{w}seu~~sc~c~
s~
p

```

All whitespace is for... "readability"... and can be omitted to comply with Lynn's regex.

Try it online!

### Explanation

The regex requires that we solve problem using only:

* Lower-case letters.
* `{}`, which can be used to create blocks.
* `|`, mostly used for bitwise OR.
* `~`, "eval" and bitwise NOT (also "dump array", but I'm not going to use it).

Since we have, `~`, if we can construct arbitrary strings, we can run arbitrary code. However, at first it's not obvious how to do that.

The first piece of the puzzle is that blocks are unevaluated bits of code, which can turn into strings with `s`. So `{abc}s` gives us `"{abc}"`. Next, we can use `eu` to convert these strings to upper case.

```
{abc}seu  e# gives "{ABC}"

```

The benefit of this is that upper-case letters are pre-initialised variables, so we can get a lot of constant values by creating such a string, and eval'ing it twice (once to turn the string back into a block and once to execute that block). We can't get all the letters, because some, like `x` aren't valid commands (so CJam will refuse to parse a block containing them). We can't use `f` as is, because it needs to be followed by another command, but we can use `fb` and then OR the two values together. Likewise, we can use `ee` instead of `e`. With that, we can get the numbers `0`, `-1`, `3`, and `10` to `19`. The `-1` is convenient, because if we turn it into a string (`"-1"`) then into a character (`'-`) and then eval it, we can get either subtraction or set difference. Like I said, we can't get `X` (for `1`), but we can take the absolute value of `-1` with `z`.

We can also use `s` to get a string containing a space, and use `c` to turn that into a space *character*:

```
{s}seu~~c

```

This is convenient, because from there we can get lots of useful commands in the lower ASCII range by ORing the space with various numbers. To get some of the characters above code point `48`, we use the character `'0` as the basis instead:

```
{t}seu~~si

```

This is already enough to construct arbitrary strings, because we can get `'+` (addition and string concatenation) from the following snippet:

```
{s}seu~~c{b}seu~~|

```

And we have a literal `1` so we can just push space characters, increment them to the value we need and then concatenate them all together, but that's a bit boring and the code would become massive.

Instead, I've generated `[` and `]` and evalled them, so that all the characters I push in between are wrapped in a string automatically. That's these two lines:

```
{s}seu~~ci{zs}seu~~c{a}seu~~|~{w}seu~~z{w}seu~~sc~c{z}seu~~{w}seu~~sc~c{w}seu~~z{w}seu~~sc~c~

...

{s}seu~~ci{z}seu~~{s}seu~~c{a}seu~~|~{z}seu~~{w}seu~~sc~c~

```

And finally, we'll need `f` and `~` in the string we're generating. While those are valid characters already, we don't have string literals or character literals, so we'd have to generate these as well and building up larger code points from the space is a bit annoying. Instead, I've made use of the set subtraction here, but subtracting two blocks (to get rid of the `{}`):

```
{fb}s{b}s{w}seu~~sc~
...
{~}s{}s{w}seu~~sc~

```

That's pretty much all there is to it. We eval `[`. We push all the characters, obtained by various computations from the few built-in constants we have, `|`, `-` (via eval) and `+` (via eval). We eval `]`. We flatten the entire thing into a string, because at some point I added some strings or numbers into the list. We eval our arbitrary string with `~`.

The `ri...p` are part of the actual final program, but I've extracted them because they don't need encoding.

Finally, this is the program we're actually running:

```
ri___*,:)/2/[1-1]f.%:~<p

ri      e# Read input and convert to integer.
__      e# Make two copies.
_*      e# Square the last copy.
,       e# Turn into range [0 1 ... n^2-1].
:)      e# Increment each to get [1 2 ... n^2].
/       e# Split into chunks of length n, creating a square.
2/      e# Split into pairs of lines.
[1-1]   e# Push [1 -1].
f.%     e# Use this to reverse the second line in each pair. If n was odd,
        e# this will pair a -1 with the last line.
:~      e# Flatten the pairs back into the square.
<       e# Truncate to n lines to get rid of that extraneous -1 for odd inputs.
p       e# Pretty-print.

```
> 3 votes

# Answer
# tinylisp, @DLosc

```
(v(c(h(q(d)))(c(h(q(f)))(q((c(q(n))(q((g(v(h(q(n))))(s(v(h(q(n))))(v(h(q(1)))))())))))))))(v(c(h(q(d)))(c(h(q(mod)))(q((c(c(h(q(x)))(q(y)))(q((i(l(v(h(q(x))))(v(h(q(y)))))x(mod(s(v(h(q(x))))(v(h(q(y)))))y))))))))))(v(c(h(q(d)))(c(h(q(range)))(q((c(c(h(q(x)))(c(h(q(y)))(c(h(q(z)))(q(w)))))(q((i(l(times(v(h(q(z))))(v(h(q(x))))(v(h(q(0)))))(times(v(h(q(z))))(v(h(q(y))))(v(h(q(0))))))(range(v(h(q(x))))(s(v(h(q(y))))(v(h(q(z)))))z(c(s(v(h(q(y))))(v(h(q(z)))))w))w)))))))))(v(c(h(q(d)))(c(h(q(times)))(q((c(c(h(q(x)))(c(h(q(y)))(q(acc))))(q((i(l(v(h(q(x))))(v(h(q(0)))))(times(s(v(h(q(0))))(v(h(q(x)))))(s(v(h(q(0))))(v(h(q(y)))))acc)(i(e(v(h(q(x))))(v(h(q(0)))))acc(times(s(v(h(q(x))))(v(h(q(1)))))y(a(v(h(q(y))))(v(h(q(acc))))))))))))))))(v(c(h(q(d)))(c(h(q(g)))(q((c(c(h(q(n)))(c(h(q(w)))(q(r))))(q((i(l(v(h(q(w))))(v(h(q(0)))))r(g(v(h(q(n))))(s(v(h(q(w))))(v(h(q(1)))))(c(i(e(v(h(q(0))))(mod(v(h(q(w))))(v(h(q(2))))))(range(a(v(h(q(1))))(times(v(h(q(w))))(v(h(q(n))))(v(h(q(0))))))(a(a(v(h(q(1))))(times(v(h(q(w))))(v(h(q(n))))(v(h(q(0))))))n)1())(range(a(times(v(h(q(w))))(v(h(q(n))))(v(h(q(0)))))n)(times(v(h(q(w))))(v(h(q(n))))(v(h(q(0)))))(s(v(h(q(0))))(v(h(q(1)))))()))r)))))))))))

```

Try it online!

This defines a function `f` that returns the answer. It also prints the names of the functions I defined to stdout, but I assume that doesn't matter, since \[we're allowed to choose our output stream\] for code golf, at least. If it's a big deal, I think I can tweak it to not print those. How did I do it? I started with something fairly standard:

```
(d f (q ((n)
  (g n (s n 1) ()))))

(d mod (q((x y)
  (i (l x y) x
    (mod (s x y) y)))))

(d range (q((x y z w)
  (i (l (times z x 0) (times z y 0))
    (range x (s y z) z (c (s y z) w))
    w))))

(d times (q ((x y acc)
  (i (l x 0) (times (s 0 x) (s 0 y) acc)
  (i (e x 0) acc
    (times (s x 1) y (a y acc)))))))

(d g (q ((n w r)
  (i (l w 0) r
    (g n (s w 1)
       (c (i (e 0 (mod w 2))
             (range (a 1 (times w n 0)) (a (a 1 (times w n 0)) n) 1 ())
             (range (a (times w n 0) n) (times w n 0) (s 0 1) ()))
          r))))))

```

Then, I observed that one can transform functions definitions like this:

```
(d mod (q ((x y) (body))))

```

becomes

```
(v(c(h(q(d)))(c(h(q(mod)))(q((c(c(h(q(x)))(q(y)))(q((body)))))))))

```

And function calls like this:

```
(a x y)

```

becomes

```
(a(v(h(q(x))))y)

```

I used this recursive Vim macro, stored in register `q`, to do the second one (I have `jk` mapped to `<Esc>`): `f s(v(h(q(jkea))))jk@q`.

These two transformations were sufficient to eliminate all spaces.
> 3 votes

# Answer
# Swift, @James Webster

```
{n in for j in 0..<n{print((1...n).map{j%2==0 ?$0+j*n:j*n+n+1-$0})}} as(CShort)->()

```

Verification: https://regex101.com/r/7ukrM0/1
> 2 votes

# Answer
# PHP, @JörgHülsermann

```
<?=(function($n,$snake){foreach(array_chunk(range(1,$n*$n),$n)as$i=>$a){if($i%2)$a=array_reverse($a);echo"\n",join('',array_map(function($e){return(sprintf("%3d",$e));},$a));}})($argv[1],'-=-=-=-=-=-=-=-=-=-=-=-=-=-o~')?>

```

---

221 bytes is too long (thus the snake), and the lack of whitespace can be easily worked-around.

Prettified:

```
<?=
(
    function($n, $snake) {
        foreach (array_chunk(range(1, $n*$n), $n) as $i => $a) {
            if($i % 2)
                $a = array_reverse($a);
            echo "\n", join('', array_map(function($e) {
                return (sprintf("%3d", $e));
            }, $a));
        }
    }
)($argv[1], '-=-=-=-=-=-=-=-=-=-=-=-=-=-o~')
?>

```
> 2 votes

# Answer
# Jelly, length 12, @JonathanAllan

```
Ḷ-*m@"s@²$G

```

Try it online!

### How it works

```
Ḷ-*m@"s@²$G  Main link. Argument: n

Ḷ            Unlength; yield [0, ..., n-1].
 -*          Yield [(-1)**0, ..., (-1)**(n-1)].
         $   Combine the two links to the left into a chain.
        ²    Yield n².
      s@     Split [1, ..., n²] into chunks of length n.
   m@"       Take the lists to the right modulo the units to the left, 1 being
             normal order and -1 being reversed.

```
> 2 votes

# Answer
# Jelly, 12 bytes, cracks @JonathanAllan's second answer

```
²sµ;@/€FḤ$¦G

```

Try it online!

## Explanation

This is almost the same as my other answer. I just made two changes:

First, I changed `U` ("reverse each element") to `Ṛ€` ("reverse" "each element"). That doesn't help by itself, because  is also banned.

Then, I changed the  ("reverse") to `;@/` (`/` "fold by" `;` "concatenating" `@` "in the opposite order to the original list"). That avoids all the banned characters, giving a valid solution.

I assume the next step would be to start banning array-manipulation *quicks*, in addition to the atoms.
> 2 votes

# Answer
# Jelly, length 13, @JonathanAllan

```
1r-*Nm@"s@²$G

```

Try it online!

### How it works

```
1r-*Nm@"s@²$G  Main link. Argument: n

1r             Range 1; yield [1, ..., n].
 -*            Yield [(-1)**1, ..., (-1)**n].
   N           Negate each unit.
           $   Combine the two links to the left into a chain.
          ²    Yield n².
        s@     Split [1, ..., n²] into chunks of length n.
     m@"       Take the lists to the right modulo the units to the left, 1 being
               normal order and -1 being reversed.

```
> 2 votes

# Answer
# Jelly, length 14, @JonathanAllan

```
²sµðạ"J×2$$¦GµL.xị"ḅ1µ$

```

Try it online!
> 2 votes

# Answer
# Scala, @Soapy

```
def g(n:Int) = {
    var vec = Vector.fill(0)(Vector.fill(0)(1))
    for (p <- 1 to n) {
        var vec2 = Vector.fill(0)(1)
        for (q <- (p-1)*n+1 to p*n) {
            vec2 = vec2 ++ Vector(q)
        }
        if (p%2==1) vec = vec ++ Vector(vec2)
        else vec = vec ++ Vector(vec2.reverse)

    }
    println(vec)
}

```

Haven't touched Scala in awhile, it was fun to revisit. Unfortunately, this solution misses out on a lot of Scala's cool features.

Try it out here

Regex Confirmation
> 2 votes

# Answer
# QBasic (QB64), @DLosc

Note that since the `.` does not match `\n` (U+000A, LF), the newline here is a `\r` (U+000D, CR).

```
INPUT N:ZERO=N-N:ONE=N/N:FOR I=ZERO TO N-ONE:FOR J=ONE TO N:IF ZERO=I MOD(ONE+ONE)THEN PRINT I*N+J;ELSE PRINT I*N+N-J+ONE;REM
NEXT:PRINT:NEXT

```

Verify:

```
>>> re.match('^([A-Z]+.)+$', 'INPUT N:ZERO=N-N:ONE=N/N:FOR I=ZERO TO N-ONE:FOR J=ONE TO N:IF ZERO=I MOD(ONE+ONE)THEN PRINT I*N+J;ELSE PRINT I*N+N-J+ONE;REM\rNEXT:PRINT:NEXT')
<_sre.SRE_Match object; span=(0, 141), match='INPUT N:ZERO=N-N:ONE=N/N:FOR I=ZERO TO N-ONE:FOR >

```

---

The main difficulty is how to insert a word after the `;`. Thankfully, QB64 treats CR as a newline while Python's regex doesn't, so we could slip a `REM\r` here. Out of the five allowed regex flavors,

So this crack is fine as long as we don't mention JavaScript...
> 2 votes

# Answer
# Python 3, kennytm

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

```

Regex verification
> 2 votes

# Answer
# \>\<\>, torcado

```
!v &0_!
_<>~ao1+>_v_
?______;__>:&:&=?;::2%:}+&:&*{3+0$.
?!v1+:n' 'o:&:&%_
?!v:n' 'o1-:&:&%_

```
> 2 votes

# Answer
# C, @Yimin Rong

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

```

The program cannot contain numbers, but we can get numbers via:

1. `c`, commonly known as "argc", which is always 2.
2. `+` and `-` are available, so we can create 0 with `n-n`, and create 1 with `o=c;--o`.
> 1 votes

# Answer
# PHP, @Ionut Botizan

In the moment I have no better idea to crack the original solution.

Supports n\<=15

It is the first time that I use getopt. Maybe not the best idea to use options as input.

start from the command line like this

```
php hack.php -a=4

```

## Original Regex

Level 1:

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

```

Very nice combination of letters. Feel free to vote up the cops thread.

It blocks me functions like \- strrev \- array\_reverse \- get\_defined\_vars

https://regex101.com/r/5rGTnw/2

Level 2:

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

```

https://regex101.com/r/XtVl9G/1

## Solution

```
 <?php
    error_reporting(~E_NOTICE)&
    define(A,a.chr(E_COMPILE_ERROR-E_NOTICE+E_WARNING))
    &define(B,getopt(A,[])[a])&print_r(array_chunk(
    array_slice(
    array_merge(
    range(E_ERROR,B)
    ,range(E_WARNING*B,E_ERROR+B)
    ,range(E_WARNING*B+E_ERROR,(E_WARNING+E_ERROR)*B)
    ,range(E_PARSE*B,+E_ERROR+(E_WARNING+E_ERROR)*B)
    ,range(E_PARSE*B+E_ERROR,(E_PARSE+E_ERROR)*B)
    ,range((E_PARSE+E_WARNING)*B,+E_ERROR+(E_PARSE+E_ERROR)*B)
    ,range((E_PARSE+E_WARNING)*B+E_ERROR,(E_NOTICE-E_ERROR)*B)
    ,range(E_NOTICE*B,+E_ERROR+(E_NOTICE-E_ERROR)*B)
    ,range(E_NOTICE*B+E_ERROR,(E_NOTICE+E_ERROR)*B)
    ,range((E_NOTICE+E_WARNING)*B,E_ERROR+(E_NOTICE+E_ERROR)*B)
    ,range((E_NOTICE+E_WARNING)*B+E_ERROR,(E_NOTICE+E_WARNING+E_ERROR)*B)
    ,range((E_NOTICE+E_PARSE)*B,E_ERROR+(E_NOTICE+E_WARNING+E_ERROR)*B)
    ,range((E_NOTICE+E_PARSE)*B+E_ERROR,(E_NOTICE+E_PARSE+E_ERROR)*B)
    ,range((E_CORE_ERROR-E_WARNING)*B,E_ERROR+(E_NOTICE+E_PARSE+E_ERROR)*B)
    ,range((E_CORE_ERROR-E_WARNING)*B+E_ERROR,(E_CORE_ERROR-E_ERROR)*B)
    )
    ,B-B,B*B
    ),B)
    )
    ?>

```

Level 2:

```
<?php
define(aa,a.chr(ord(strtoupper(a))-ord(h)+ord(a)))and
define(bb,getopt(aa,[])[a])and
define(us,chr(ord(a)-true-true))and
(prin.t.(us).r)(
(arra.y.(us).chunk)(
(arra.y.(us).slice)(
(arra.y.(us).merge)(
range((ord(b)-ord(a)),bb)
,range((ord(c)-ord(a))*bb,(ord(b)-ord(a))+bb)
,range((ord(c)-ord(a))*bb+(ord(b)-ord(a)),((ord(c)-ord(a))+(ord(b)-ord(a)))*bb)
,range((ord(e)-ord(a))*bb,+(ord(b)-ord(a))+((ord(c)-ord(a))+(ord(b)-ord(a)))*bb)
,range((ord(e)-ord(a))*bb+(ord(b)-ord(a)),((ord(e)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(e)-ord(a))+(ord(c)-ord(a)))*bb,+(ord(b)-ord(a))+((ord(e)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(e)-ord(a))+(ord(c)-ord(a)))*bb+(ord(b)-ord(a)),((ord(e)-ord(a))-(ord(b)-ord(a)))*bb)
,range((ord(e)-ord(a))*bb,+(ord(b)-ord(a))+((ord(e)-ord(a))-(ord(b)-ord(a)))*bb)
,range((ord(e)-ord(a))*bb+(ord(b)-ord(a)),((ord(e)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(e)-ord(a))+(ord(c)-ord(a)))*bb,(ord(b)-ord(a))+((ord(e)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(e)-ord(a))+(ord(c)-ord(a)))*bb+(ord(b)-ord(a)),((ord(e)-ord(a))+(ord(c)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(e)-ord(a))+(ord(e)-ord(a)))*bb,(ord(b)-ord(a))+((ord(e)-ord(a))+(ord(c)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(e)-ord(a))+(ord(e)-ord(a)))*bb+(ord(b)-ord(a)),((ord(e)-ord(a))+(ord(e)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(q)-ord(a))-(ord(c)-ord(a)))*bb,(ord(b)-ord(a))+((ord(e)-ord(a))+(ord(e)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(q)-ord(a))-(ord(c)-ord(a)))*bb+(ord(b)-ord(a)),((ord(q)-ord(a))-(ord(b)-ord(a)))*bb)
)
,bb-bb,bb*bb
),bb)
)
?>

```
> 1 votes

# Answer
# Ruby, @Value Ink

```
->n{(1..n).map{|r|x=(r*n-n+1..r*n).to_a;if(r.modulo(2)==1)then(x)else(x.reverse)end}}#1-2-3-4-5-6--

```

`[(-=Z-~]*` means "I can write anything I like :)"
> 1 votes

# Answer
# PHP, @Ionut Botizan

Once upon a time I remember that PHP has a goto

https://regex101.com/r/m5kNRd/1/

double assigments are alternatives for example Newline under Mac and Linux

solution with tab

```
<?="";
$p="M"&";";
$cr="M"&"-";
$cr="Z"&"*";
$zero=$one=$line=$text="";
$zero++;$zero--;
$a=$zero;
$s="$zero"&"$";
$one=++$one;
$g=$argv{$one};
$dir=$one;
a:++$a;
$line=$dir?"$line$a":"$a$line";
$line=$a%$g?$dir?"$line$p":"$p$line":"$line$cr";
$dir=$a%$g?$dir:$one-$dir;
$text=$a%$g?$text:"$text$line";
$line=$a%$g?$line:"";
echo$a-$g*$g?"":$text;
$a-$g*$g?:exit;
goto a;

```

First I have tought that I must use dynamic spaces

```
<?="";
$cr="M"&"-";
$cr="Z"&"*";
$zero=$one=$line=$text="";
$zero++;$zero--;
$a=$zero;
$s="$zero"&"$";
$one=++$one;
$five=$one+$one+$one+$one+$one;
$ten=$five+$five;
${"v$zero"}="$s$s$s$s$s$s$s";
${"v$one"}="$s$s$s$s$s$s";
${"v$ten"}="$s$s$s$s$s";
$g=$argc-$one;
$g=$argv{$one};
$space=$zero;
$p=${"v$space"};
$dir=$one;
a:++$a;
$a%$ten?:$space++;
$p=${"v$space"}??$p;
$line=$dir?"$line$a":"$a$line";
$line=$a%$g?$dir?"$line$p":"$p$line":"$line$cr";
$dir=$a%$g?$dir:$one-$dir;
$text=$a%$g?$text:"$text$line";
$line=$a%$g?$line:"";
echo$a-$g*$g?"":$text;
$a-$g*$g?:exit;
goto a;

```
> 1 votes

# Answer
# tinylisp, @DLosc

A very straightforward solution, and totally unoptimized :)

```
(d p(q((m n)(s m(s(s 1 1)n)))))(d j(q((f g)(i(l f g)(c f(j(p f 1) g))()))))(d r(q((f g)(i(l f g)(c(s g 1)(r f(s g 1)))()))))(d k(q((m o f g n)(i(l n g)()(c(m f(p f n))(k o m(p f n)(p g 1) n))))))(d f(q((n)(k j r 1 1 n))))

```

Call as `(disp (f 4))`.

* `(p m n)` computes m + n using subtraction `s` (m + n == m - ((1 - 1) - n))
* `(j f g)` generates `(f f+1 f+2 ... g-1)`
* `(r f g)` generates `(g-1 g-2 g-3 ... f)`
* `(k m o f g n)` generate one row of the snake matrix, and then recurve itself for the next row, until n rows are created. The arguments `m`, `o` are substituted by `j`/`r` to generate increasing or decreasing rows. The arguments `f`, `g` are running indices to know which row we are on.
* `(f n)` calls `(k j r 1 1 n)` to start the generation.
> 1 votes

# Answer
# PHP, @Jörg Hülsermann

```
$n=next($argv);$a=array();for($i=0;$i<$n;++$i){$f=$i*$n;$g=$f+++$n;$a{$i}=$i&1?range($g,$f):range($f,$g);}echo(serialize($a));;

```

In PHP, `range(1, 4)` gives `[1, 2, 3, 4]` while `range(4, 1)` gives `[4, 3, 2, 1]`. o\_O.
> 1 votes

# Answer
# Racket Intermediate Student with Lambda, @Brian McCutchon

```
(λ(n)(foldr(λ(p q)(cons((λ(x)(if(even? p)(range(+ x 1)(+ x n 1)1)(range(+ x n)x -1)))(* p n))q))'()(range 0 n 1)))

```

(`λ` can be replaced by `lambda`, both are allowed in the regex.)

Since I can't get TIO to restrict to htdp-intermediate-lambda and I don't want to download a new language, I will just assume it is fine as long as I only use functions given on that page:
`λ` `foldr` `cons` `if` `even?` `range` `+` `*`.

Since TIO does not include the words "list" in the output (it just produces `'((1 2 3 4) (8 7 6 5)`…), if the above crack is rejected, consider this quick fix:

```
(λ(n)(cons 'list(foldr(λ(p q)(cons(cons 'list((λ(x)(if(even? p)(range(+ x 1)(+ x n 1)1)(range(+ x n)x -1)))(* p n)))q))'()(range 0 n 1))))

```
> 1 votes

# Answer
# Mathematica, @Martin Ender (non-competing)

```
((#//Range)+i#-#)~SortBy~(-(-#)^i&)~Table~{i,#} &

```
> 1 votes

# Answer
# QBasic, @DLosc

```
DEFSTR S:CLS:INPUT N:ONE=N\N:TWO=ONE+ONE:FOUR=TWO+TWO:SELECT CASE N:CASE IS<FOUR:FW=ONE:CASE IS<FOUR*TWO+TWO:FW=TWO:CASE ELSE:FW=ONE+TWO:END SELECT:READ S:FOR I=ONE TO N:FOR J=ONE TO N:COL=J*FW+J-FW:LOCATE I+ONE,COL:G=I MOD TWO:F=J*TWO-ONE-N:V=I*N-J+ONE+G*F:PRINT V:LOCATE I+ONE,COL:PRINT S:NEXT:LOCATE I+ONE,N*FW+N+ONE:PRINT S:NEXT:DATA|

```

---

Prettified (`s/:/\n/g`):

```
DEFSTR S
CLS
INPUT N
ONE = N\N
TWO = ONE+ONE
FOUR = TWO+TWO
SELECT CASE N
    CASE IS < FOUR: FW = ONE
    CASE IS < FOUR*TWO+TWO: FW = TWO
    CASE ELSE: FW = ONE+TWO
END SELECT
READ S
FOR I=ONE TO N
    FOR J=ONE TO N
        COL = J*FW+J-FW
        LOCATE I+ONE, COL
        G = I MOD TWO
        F = J*TWO-ONE-N
        V = I*N-J+ONE+G*F
        PRINT V
        LOCATE I+ONE, COL
        PRINT S
    NEXT
    LOCATE I+ONE, N*FW+N+ONE
    PRINT S
NEXT
DATA|

```

Use `LOCATE` to force the output position. Use `DATA`/`READ` to obtain `"|"` without using functions.
> 1 votes

# Answer
# Racket Intermediate Student with Lambda, @Brian McCutchon

```
(λ (n)(((λ (f) (f f))(λ(s)(λ (i a b) (cond [(= i(* n n))'()] [#t(cons(a 1 i)((s s) (+ n i)b a))]))))0((λ (g) (g g))(λ(u)(λ (j i) (cond [(> j n)'()][#t(cons(+ j i)((u u) (+ 1 j)i))]))))((λ(g) (g g))(λ(d) (λ(j i) (cond [(> j n)'()][#t(cons(+(- n j)1 i)((d d) (+ 1 j)i))]))))))

```

Uses this trick to perform recursion without `define`/`letrec`/`let*`, otherwise a pretty standard algorithm. Some spaces cannot be eliminated due to the regex restriction.
> 1 votes

# Answer
# Jelly, 15 bytes, @ais523

```
s@²UJḤ$¦Ȯṛ“”
Ç²s

```

Try it online!
> 0 votes

# Answer
# Jelly, 16 bytes, @ais523

```
s@²UJḤ$¦Ȯṛ“”
Çœ?²s

```

Try it online!
> 0 votes

# Answer
# 05AB1E, mbomb007

Unlikely to be the intended solution :)

**Crack**

```
UXF**XLNNVX*F>}YFR}ˆ

```

**Explanation**

```
U                      # store input in X
 XF                    # X times do:
   **                  # multiply nothing twice
     XL                # range [1 ... input]
       N               # push current iteration number
        NV             # store current iteration number in Y
          X*           # multiply current iteration by input
            F>}        # increment the range that many times
               YFR}    # iteration number times, reverse the range
                   ˆ   # add it to global array
                       # implicitly print global array after program end

```
> 0 votes

# Answer
# Go, @Kristoffer Sall-Storgaard

```
package main

import . "fmt"

const (
    zero = iota
    one
    two
)

func inc(p int) int {
    var bit = one
    for {
        if (p & bit) == zero {
            return p | bit
        }
        p ^= bit
        bit *= two
    }
}

func dec(p int) int {
    var bit = one
    for {
        if (p & bit) == bit {
            return p ^ bit
        }
        p |= bit
        bit *= two
    }
}

func main() {
    var n int
    var i int
    var row = one
    var col = zero
    Scan(&n)
    print("[")
    for n*n > i {
        i = inc(i)
        if col == zero {
            print("[")
        }
        if row%two == one {
            print(i)
        } else {
            var m = row * n
            var c = col
            for c > zero {
                m = dec(m)
                c = dec(c)
            }
            print(m)
        }
        col = inc(col)
        if col == n {
            print("]")
            col = zero
            row = inc(row)
        }
        if i != n*n {
            print(" ")
        }
    }
    print("]")
}

```

---

The regex means we only use one character from `+` to `<`, i.e.

> +,-./:;\<0123456789

The "." is needed for `fmt.Scanf` anyway. Although the character set is restricted, with *unlimited length* we could still write very complex programs.

* The lack of numbers is trivial to workaround, just use `iota` to define constants.
* The lack of `<` is also simple, just use `>` instead.
* The lack of `+` and `-` are trickier. Here I reimplemented `inc(x) == x+1` and `dec(x) == x-1` using bit operations. Perhaps there is an easier way but this isn't a
* The lack of `,` means we cannot use functions with two or more arguments, so `make()` and `append()` are out. There might be other ways to construct an array, but I find printing the output as if it is an array is simpler.
> 0 votes

# Answer
# C#, @Eklipz

```
static int[,]F(int n){var a=new int[n,n];for(int r=n-n,z=r;r<n;++r)for(var c=z;c<n;++c)a[r,c]=n*r+((r&-~z)!=z?n-c:c-~z);;;;;;;;;;;;;;;;;;;;;;;return a;}

```

Uses standard tricks like `z := n - n == 0` and `-~z == 1` to produce the missing numbers.
> 0 votes

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


title: Uni-Dimensional String Golf

text:
# Question
Title: Uni-Dimensional String Golf
# Introduction

You have to simulate playing golf over an input string that represents the green. The 2-character substring `()` represents the hole, and is guaranteed to appear only once in the string.

This is a sample green:

```
ABCDEFGHIJKLM()NOPQRSTUVWXYZ

```

The simulation consists of outputting the characters that the ball falls on after a series of hits that are also passed to your function.

Each hit is represented by a positive integer indicating how many characters the ball will travel, relative to previous position.

# Example

The following input results in the output `G(o)`.

```
7,7,ABCDEFGHIJKLM()NOPQRSTUVWXYZ

```

### Explanation

The input represents two hits of length 7. The output is a string of characters, showing the intermediate positions of the ball. The ball starts to the left of the string, and travels 7 characters to the right, landing on the `G`. As such, that character is the first part of the output.

Then the ball is hit for the second time, and it lands in the hole. In this case, the hole is output with the ball inside, like this: `(o)`.

```
9,7,1,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
I(o)N

```

The output represents the characters the ball has landed on in the same order as in the string.

# Notes

1. The width of the hole is 2. If the ball lands on either parenthesis, the hole is hit.
2. The direction of the hit is always towards the hole, so when the ball ends up to the right of the hole, the next hit will cause the ball to move to the left (and vice versa).
3. The ball might not reach the hole, in which case the position of the ball after the last hit must be output next to the character (in the direction of the hole) the ball is on at the end of the hits. The hole is still included in the output.

> example:
>
> ```
> 28,26,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
> B12()Z
>
> ```
>
> First 28 hit lands on Z at the right of the hole , next 26 hit is as always thowards the hole (left) and lands on B. No more hits left so the distance to the hole (12 characters) is shown next to B

4. If the hits cause the ball to leave the green at some point, discard all remaining hits, and prepend `^` if the ball exits the green to the left, and append `$` if the ball leaves the green via the right side.
5. There might be hits after the putt, in which case those should be discarded, and the hole in the output should not contain an `o`, but an `X`.

# Test cases

```
15,10,3,TOURING()MACHINE
I(o)N

7,HOLEIN()NE
(o)

9,7,1,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
I(o)N

7,7,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
G(o)

28,26,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
B12()Z

2,25,26,27,ABCDEFGHIJKLM()NOPQRSTUVWXYZ
AB()Y13Z

1,1,6,SH()RT
SH()$

2,4,6,TOO()HARD
^O()H

4,8,1,3,3,3,3,3,TAKEIT()ASITCOMES
E(X)IT

```

You have to write a program or function wich accepts a series of positive numbres representing the hits and a \[A..Z\] string with one hole "()" representig the green. Make clear if your input format is different form `7,7,ABCDEFGHIJKLM()NOPQRSTUVWXYZ`

This is code golf, so the submission with the smallest amount of bytes per language wins!

# Answer
## Python 2 - 380 bytes

Try it online

Shorter answer, thanks to @ovs. This one requires list of integers and string as input. Example: 28,26,"ABCDEFGHIJKLM()NOPQRSTUVWXYZ". Check edits for older version, that accepts plain string like "28,26,ABCDEFGHIJKLM()NOPQRSTUVWXYZ"

```
I=input()
c=-1
G=I[c]
I=map(int,I[:c])
u=r=""
L=[u]*len(G)
H=len(G.split('(')[0])
L[H:H+1]='()'
d=1
s=0
f="".join
for h in I:
 s+=1;c+=h*d;d=(1,-1)[H-c<0];T=f(L)
 if H<=c<H+2:u='o'if s==len(I)else'X';break
 if c<0:r="^"+T;break
 if c>len(G):r=T+"$";break
 L[c]=G[c]
else:
 m=H-c if~d else c-H-1
 if d>0:c+=1
 L=L[:c]+[str(m)]+L[c:];r=f(L)
print r or("%s)"%u).join(f(L).split(')'))

```

Explanation (for older version, but approach is same):

```
I=input().split(',')             # split input
G=I[-1]                          # last element - Green
I=map(int,I[:-1])                # convert all other (hits) to int
L=[""]*len(G)                    # empty list of same length as Green, used to ouput
H=len(G.split('(')[0])           # index of hole
L[H]='('                         # hole is always printed
L[H+1]=')'
c=-1                             # current index on Green
d=1                              # direction of hit
u=r=""                           # strings for output and in-hole marker (X)/(o)
s=0                              # number of current hit
for h in I:
    s+=1
    c+=h*d                       # move current by hit * direction
    d=(1,-1)[H-c<0]              # calculate new direction
    T="".join(L)                 # used to remove code duplication
    if H<=c<H+2:                 # if in hole
        u='o'if s==len(I)else'X' # check whether it is last hit or not
        break
    if c<0:                      # if out of Green on the left
        r="^"+T                  # add '^' and join all visited indices
        break
    if c>len(G):                 # if out of Green on the right
        r=T+"$"                  # add '&' after join all visited indices
        break
    L[c]=G[c]                    # mark visited index
else:                            # rare occasion of for-else construction - executes if never break out of loop
                                 # which means, that we are out of hits and not in hole
    m=H-c if~d else c-H-1        # calculate distance to hole
    if d>0:
        c+=1
    L=L[:c]+[str(m)]+L[c:]       # expand L list with distance
    r="".join(L)                 # join list
t="".join(L).split(')')
if r:
    print r                      # ouput r in all cases exept in-hole
else:
    print t[0]+"%s)"%u+t[1]      # output for in-hole cases

```
> 2 votes

# Answer
# Röda, ~~308~~ 299 bytes

```
f g{a=indexOf("()",g)g=g[:a].."oo"..g[a+2:]o=[""]*#g
s=""e=""i=-1{|j|o[i]="X"if[i>=a,i<=a+1]else{i+=j if[i<a]else i-=j if[i>a+1]
{s="^";[]_}if[i<0]else{e="$";[]_}if[i>=#g]else o[i]=g[i:i+1]}}_
o[i].=s..a-i if[i<a,i>=0]
o[i]=i-a-1..o[i]if[i>a+1,i<#g]
[s..o[:a]&""..`(${o[a:a+2]&""})`..o[a+2:]&""..e]}

```

Try it online!

*Saved 8 bytes thanks to Kritixi Lithos!*

Ungolfed:

```
function f(green) {
    /* find the hole */
    hole := indexOf("()", green)
    /* replace () with oo in the green string */
    green := green[:hole].."oo"..green[hole+2:]
    /* initializes the output array: contains an empty string for each yet unvisited place on the green */
    out := [""]*#green
    start := ""
    end := ""
    i := -1
    /* for each number in the stream */
    for j do
        /* if the ball is in the hole, change the output to X */
        if [ i=hole or i=hole+1 ] do
            out[i]="X"
        else
            /* add or subtract the number */
            i+=j if [ i < hole ] else i-=j if [ i > hole+1 ]
            /* if the ball has left the green, stop looping */
            if [ i < 0 ] do
                start = "^"
                break
            done
            if [ i >= #green ] do
                end = "$"
                break
            done
            /* add the visited character to the output array */
            out[i] = green[i:i+1]
        done
    done
    /* add a number next to the last character visited */
    out[i] .= ""..hole-i if [ i < hole and i >= 0 ]
    out[i] = i-hole-1..o[i] if [ i > hole+1 and i < #green ]

    /* return the output */
    return start..out[:hole]&""..`(${out[hole:hole+2]&""})`..out[hole+2:]&""..end
}

```
> 1 votes

---
Tags: code-golf, string, game, balanced-string
---


title: Maximal Skittle Enjoyment

text:
# Question
Title: Maximal Skittle Enjoyment
You've been given a bag of Skittles. Everybody knows that in order to appreciate the different flavors the most, you need to rotate between the flavors.

## Basics:

1. You can only eat 1 skittle at a time
2. The order that you eat your skittles *must* be periodic.
3. Each period cannot contain a particular flavor more than once.
4. Your bag only has so many skittles. You cannot eat more of a particular flavor of skittle than appears in your bag.
5. You want to eat as many skittles as you can (it may not always be possible)

## Examples:

Lets say you start with 3 Red, 2 Blue, and 3 Green skittles:

```
R B G R B G R G       Invalid:  The last R must be followed by a B, not a G
R B G R B G R         Valid, but sub-optimal
R R R                 Valid, but sub-optimal
R G B R G B R G       Valid and optimal
G R B G R B G R       Also valid and optimal (there are multiple good solutions)

```

# Input/Output

* You are passed a non-empty list of positive integers for the color counts. (The above example would be `[3,2,3]`).
* You need to return a list containing valid and optimal ordering.
* Instead of using colors, you will use the indices from input list. (The last example output above would be `[2,0,1,2,0,1,2,0]`).
* Your output may be 0-indexed or 1-indexed. My examples will be 0-indexed

# Test Cases

```
1                          0
4                          0 0 0 0
4 1                        0 0 0 0
3 1                        0 1 0                   or  0 0 0
5 2 2                      0 1 2 0 1 2 0
2 3 5                      2 1 0 2 1 0 2 1         or  1 2 0 1 2 0 1 2
2 4 5                      2 1 2 1 2 1 2 1 2
3 4 5                      2 1 0 2 1 0 2 1 0 2 1   or  1 2 0 1 2 0 1 2 0 1 2
1 1 1 1 1 6                5 0 1 2 3 4 5           (lots of other solutions)
1 1 1 1 1 8                5 5 5 5 5 5 5 5
2 4 6 8                    3 2 1 3 2 1 3 2 1 3 2 1 3 2

```

This is a , so make your solutions as short as possible in your favorite language!

# Answer
## JavaScript (ES6), ~~177~~ 175 bytes

```
a=>a.map((n,i)=>[n,l=i]).sort((a,b)=>a[0]-b[0]).reduce((P,x,i,a)=>(v=a.reduce((p,c,j)=>j<i?p:p+Math.min(c[0],x[0]+1),0))>m?[...Array(m=v)].map((_,k)=>a[l-k%(l+1-i)][1]):P,m=0)

```

### Formatted and commented

```
a => a                              // given an array a:
.map((n, i) => [n, l = i])          // map it to [value, index] arrays / set l = length - 1
.sort((a, b) => a[0] - b[0])        // sort it by values in ascending order
.reduce((P, x, i, a) =>             // for each reference entry x at position i:
  (v = a.reduce((p, c, j) =>        //   for each entry c at position j:
    j < i ?                         //     if c is before x:
      p                             //       keep the previous sum (which is 0)
    :                               //     else:
      p + Math.min(c[0], x[0] + 1), //       add minimum(value[j], value[i] + 1)
    0                               //   initialize the sum at 0
  )) > m ?                          //   if the new sum v is better than our current best m:
    [...Array(m = v)].map((_, k) => //     update m to v and update the result to an array
      a[l - k % (l + 1 - i)][1]     //     of length m filled with indices picked repeatedly
    )                               //     between i and l
  :                                 //   else:
    P,                              //     keep the previous result
  m = 0                             // start with best score m = 0
)                                   // the final result is returned by the outer reduce()

```

### Used formula

Below is a table showing how the formula `F(i, j) = minimum(value[j], value[i] + 1)` is working, here with `i = 0` and the input `[ 5, 2, 2 ]`.

This formula can be interpreted as follows: for each Skittle type, we can select no more than the number of the least available type plus one.

```
 j | Sorted    | value[j] | F(0, j) | Selected        | Output
   | input     |          |         | Skittles        | (starting from bottom left)
---+-----------+----------+---------+-----------------+-----------------------------
 0 | 2 2       |     2    |    2    | [2] [2]         | \
 1 | 1 1       |     2    |    2    | [1] [1]         |  > 0 1 2 0 1 2 0
 2 | 0 0 0 0 0 |     5    |    3    | [0] [0] [0] 0 0 | /

```

### Test cases

```
let f =

a=>a.map((n,i)=>[n,l=i]).sort((a,b)=>a[0]-b[0]).reduce((P,x,i,a)=>(v=a.reduce((p,c,j)=>j<i?p:p+Math.min(c[0],x[0]+1),0))>m?[...Array(m=v)].map((_,k)=>a[l-k%(l+1-i)][1]):P,m=0)

console.log(JSON.stringify(f([ 1                ]))); // 0
console.log(JSON.stringify(f([ 4                ]))); // 0 0 0 0
console.log(JSON.stringify(f([ 4, 1             ]))); // 0 0 0 0
console.log(JSON.stringify(f([ 3, 1             ]))); // 0 1 0
console.log(JSON.stringify(f([ 5, 2, 2          ]))); // 0 2 1 0 2 1 0
console.log(JSON.stringify(f([ 2, 3, 5          ]))); // 2 1 0 2 1 0 2 1
console.log(JSON.stringify(f([ 2, 4, 5          ]))); // 2 1 2 1 2 1 2 1 2
console.log(JSON.stringify(f([ 3, 4, 5          ]))); // 2 1 0 2 1 0 2 1 0 2 1
console.log(JSON.stringify(f([ 1, 1, 1, 1, 1, 6 ]))); // 5 4 3 2 1 0 5
console.log(JSON.stringify(f([ 1, 1, 1, 1, 1, 8 ]))); // 5 5 5 5 5 5 5 5
console.log(JSON.stringify(f([ 2, 4, 6, 8       ]))); // 3 2 1 3 2 1 3 2 1 3 2 1 3 2
```
> 4 votes

# Answer
# Jelly, 22 bytes

```
ċÐ€ṢN
ỤṚ;\Ṛẋ"‘Ṣ$ḣ"ÇLÞṪ

```

1-based indexing.

**Try it online!**

### How?

Repeats each prefix of the indexes sorted by value descending one more time than would be achievable with the given bag of skittles, then removes the final skittle or skittles from each of these as necessary to make them achievable, and returns the one with the most skittles.

The number that should be removed from one extra periodic repetition is just the number with the minimum count across that prefix.

```
ỤṚ;\Ṛẋ"‘Ṣ$ḣ"ÇLÞṪ - Main link                   e.g. [6,4,2,8]
Ụ                - grade up: sort indices by value  [3,2,1,4]
 Ṛ               - reverse                          [4,1,2,3]
   \             - cumulative reduce with
  ;              -     concatenation (get prefixes) [[4],[4,1],[4,1,2],[4,1,2,3]]
    Ṛ            - reverse                          [[4,1,2,3],[4,1,2],[4,1],[4]]
         $       - last two links as a monad
       ‘         -     increment                    [7,5,3,9]
        Ṣ        -     sort                         [3,5,7,9]
      "          - zip with
     ẋ           -     list repetition              [[4,1,2,3,4,1,2,3,4,1,2,3],[4,1,2,4,1,2,4,1,2,4,1,2,4,1,2],[4,1,4,1,4,1,4,1,4,1,4,1,4,1],[4,4,4,4,4,4,4,4,4]]
            Ç    - call last link (1) as a monad    [-1,-1,-1,-1]
          "      - zip with
           ḣ     - head list to (remove excess)     [[4,1,2,3,4,1,2,3,4,1,2],[4,1,2,4,1,2,4,1,2,4,1,2,4,1],[4,1,4,1,4,1,4,1,4,1,4,1,4],[4,4,4,4,4,4,4,4]]
              Þ  - sort by
             L   -     length                       [[4,4,4,4,4,4,4,4],[4,1,2,3,4,1,2,3,4,1,2],[4,1,4,1,4,1,4,1,4,1,4,1,4],[4,1,2,4,1,2,4,1,2,4,1,2,4,1]]
               Ṫ - tail                             [4,1,2,4,1,2,4,1,2,4,1,2,4,1]

ċÐ€ṢN - Link 1: head amounts (negative of skittle excess of each N+1 repeated period)
   Ṣ  - sort                                        [2,4,6,8]
 Ð€   - for each mapped over right argument
ċ     - count                                       [1,1,1,1]
    N - negate                                      [-1,-1,-1,-1]

```
> 2 votes

# Answer
# Python3, ~~174~~ ~~172~~ 167 Bytes

## Idea

Given e.g. 3 Red, 2 Blue, and 3 Green skittles one can arrange them in a grid, sorted by color and amount:

```
r g
r g b
r g b

```

If one tries to eat exactly i skittles, one can at least eat i\*c skittles in total, where c is the number of skittles in the r-th column, e.g. for i=2 one can at least eat 6 skittles.

```
r g
# # #
# # #

```

The only thing left to do is count how many additional skittles can be eaten by an incomplete period.

## Golfed

```
def f(a):
 r=range;f=m=0;s=r(len(a));b=sorted(zip(a,s))[::-1]
 for i in s:
  c=b[i][0];n=-~i*c+sum(c<e[0]for e in b)
  if n>m:f,m=i+1,n
 return[b[j%f][1]for j in r(m)]

```

## Commented

```
def f(a):
    r = range;
    f = m = 0;                          - Some variables we need later on
    s = r(len(a));                      - Integers from 0 to (num_skittles - 1)
    b = sorted(zip(a,s))[::-1]          - Zip with s to remember initial order,
                                          then sort and reverse
    for i in s:
        c = b[i][0]
        n = (i+1)*c                     - If we attempt to eat i different skittles,
                                          we can surely eat (i+1)*c skittles.
          + sum(1 for e in b if e[0]>c) - The additional sum corresponds to an incomplete period.
        if n>m:                         - If a better way of eating skittles is found:
            f,m = i+1,n                 - update variables
    return [b[j%f][1] for j in r(m)]

```

Try it online!

Edit: Replaced `(i+1)` with `-~i` to save 2 bytes.

Edit: -5 bytes thanks to Dead Possum
> 2 votes

---
Tags: code-golf
---


title: How great is your land?

text:
# Question
Title: How great is your land?
In this challenge, you'll calculate how great your land is.

---

Write a program or function that calculates the size of your land, given a wall you have built. You're given a non-empty input string containing a set of 4 distinct characters of your choice that represent the four directions "up", "down", "left" and "right" (I'll use `^ v < >` in this challenge). It's not possible to take 180 degree turns (`<>` or `^v`), but you may cross your wall.

The way you "capture" land is by encircling it with your wall. The wall itself is also considered part of your land. A few examples will make it more clear. I'll use `o` for land that has been encircled by the wall, `x` for the wall itself, and `S` for the starting point of the wall, just to illustrate how the wall is built. The output should be the total size of your land (the number of `o`, `x` and `S` in the test cases below).

```
Input: >>>>
Land: Sxxxx
Output: 5

Input: <<<^^^>>>vv
Land:
xxxx
xoox
xoox
xxxS
Output: 16

Input: <<<^^^>>>v
Land:
xxxx
x  x
x
xxxS
Output: 11

Input: <
Land: xS
Output: 2

Input: >>>>>>vvvvvvvvv<<<<<^^^^>>>>>>>>vvvvvvvvvv<<<<<<<<<<<<<<<^^^^^^^^^>>>vvvvvv<<<<<
Land:
        Sxxxxxx
              x
              x
              x
              x
         xxxxxxxxx
  xxxx   xoooox  x
  xoox   xoooox  x
  xoox   xoooox  x
  xoox   xxxxxx  x
  xoox           x
  xoox           x
xxxxxx           x
  x              x
  x              x
  xxxxxxxxxxxxxxxx
Output: 101

Input: >>vvvv>>^^<<<<^
Land:
Sxx
xox
xxxxx
  xox
  xxx
Output: 17

Input: <<^^^>>>vv
Land:
xxxx
x  x
x  x
xxS
Output: 11   <- Note, diagonal edges do not close the "loop"

```

**Clarifications:**

* You do not need to draw the wall, the output should only be an integer
* The input format is optional. You may take a string with `<>^v`, a list of digits, `(1, -1, i, -i)`, a list of characters `ABCD` etc.

---

This is so the shortest code *in each language* wins. Remember, explanations are important, even in "regular" languages!

# Answer
# Python 2, ~~385~~ ~~345~~ 332 bytes

```
A,I,R=max,min,range
a=b=0
p=[[a,b]]
for i in input():a+=i%2*(2-i);b+=(1-i%2)*(1-i);p+=[a,b],
k,l=zip(*p)
x=A(k)-I(k)+3
y=A(l)-I(l)+3
o=[[1]*y for _ in' '*x]
def g(m,n):
 if 0<o[m][n]and[m+I(k)-1,n+I(l)-1]not in p:o[m][n]=0;[g(i,j)for i in R(A(0,m-1),I(x,m+2))for j in R(A(0,n-1),I(y,n+2))if(i,j)!=(m,n)]
g(0,0)
print sum(map(sum,o))

```

Try it online! or Try all test cases

Input is numerical, 0~3, the 0-index of the symbols here: `>v<^`

```
#starting position
a,b=0
#new list to hold the wall coordinates
p=[[a,b]]

#iterate over the input calculating
#the next coordinate and storing on p
for i in input():
 a=a+i%2*(2-i)
 b=b+(1-i%2)*(1-i)
 p+=[[a,b]]
#i%2*(2-i) and (1-i%2)*(1-i) generate the increment
#of each symbol from last position
# >/0 : (0,1)
# v/1 : (1,0)
# </2 : (0,-1)
# ^/3 : (-1,0)

#transpose the coordinate list
k,l=zip(*p)
#calculate the difference between the max and min values
#to generate the total land size
#adding a border to avoid dead-ends
x=max(k)-min(k)+3
y=max(l)-min(l)+3

#create a matrix of 1's with the total land size
o=[([1]*y) for _ in ' '*x]

#recursive function that sets a cell to 0
#and call itself again on all surrounding cells
def g(m,n):
 #correct the indexes (like negative ones)
 a,b=m+min(k)-1,n+min(l)-1
 #if this cell contains 1 and don't belong to the wall
 if o[m][n]>0 and (a,b) not in p:
  #sets to 0
  o[m][n]=0
  #call again on surrounding cells
  for i in range(max(0,m-1),min(x,m+2)):
   for j in range(max(0,n-1), min(y,n+2)):
    if (i,j)!=(m,n):g(i,j)

#call the recursive function o origin
g(0,0)
#print the sum of the cells
print sum(map(sum,o))

```

This is the resulting matrix:

```
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, **1**, **1**, **1**, **1**, **1**, **1**, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, 0]
[0, 0, 0, **1**, **1**, **1**, **1**, 0, 0, 0, **1**, **1**, **1**, **1**, **1**, **1**, 0, 0, **1**, 0]
[0, 0, 0, **1**, **1**, **1**, **1**, 0, 0, 0, **1**, **1**, **1**, **1**, **1**, **1**, 0, 0, **1**, 0]
[0, 0, 0, **1**, **1**, **1**, **1**, 0, 0, 0, **1**, **1**, **1**, **1**, **1**, **1**, 0, 0, **1**, 0]
[0, 0, 0, **1**, **1**, **1**, **1**, 0, 0, 0, **1**, **1**, **1**, **1**, **1**, **1**, 0, 0, **1**, 0]
[0, 0, 0, **1**, **1**, **1**, **1**, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0]
[0, 0, 0, **1**, **1**, **1**, **1**, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0]
[0, **1**, **1**, **1**, **1**, **1**, **1**, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0]
[0, 0, 0, **1**, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0]
[0, 0, 0, **1**, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, **1**, 0]
[0, 0, 0, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, **1**, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

```
> 6 votes

# Answer
# Octave, ~~83~~ ~~85~~ ~~83~~ 79 bytes

```
@(p)nnz(bwfill(accumarray([real(c=cumsum([0;p])) imag(c)]+nnz(p)+1,1),"holes"))

```

Try it on Octave Online!

A function that takes as input a column vector containing `(1, -1, i, -i)`

Using approach of @lanlock4 's Mathematica answer adding length of the input to coordinates to avoid non positive coordinates, instead of subtracting min of coordinates from them. Saved 4 bytes.

Previous answer:

```
@(p)nnz(bwfill(accumarray((k=[real(c=cumsum([0;p])) imag(c)])-min(k)+1,1),"holes"))

```

Try it on Octave Online!

Changed for better visualization.

Explanation:

```
%compute position of walls
c= cumsum([0;p]) % p should be top padded with a 0
row = real(c);
col = imag(c);
k = [row col];

%offset positions so all positions become positive
pos = k - min(k) +1;
%create a binary array that is 1 for walls and 0 elsewhere
bin = ~~accumarray(pos,1);

        *******
              *
              *
              *
              *
         *********
  ****   *    *  *
  *  *   *    *  *
  *  *   *    *  *
  *  *   ******  *
  *  *           *
  *  *           *
******           *
  *              *
  *              *
  ****************

%use flood fill to fill holes
filled = bwfill(bin, 'holes');

        *******
              *
              *
              *
              *
         *********
  ****   ******  *
  ****   ******  *
  ****   ******  *
  ****   ******  *
  ****           *
  ****           *
******           *
  *              *
  *              *
  ****************

%count number of ones in the filled image
result = nnz(filled)

```
> 3 votes

# Answer
# Haskell, ~~579~~ 530 bytes

```
y=length
i=filter
u i e l=take i l++[e]++drop(i+1)l
k v(r,c)g=u r(u c v(g!!r))g
b(r,c)g=g!!r!!c
w(r,c)s g=case s of{""->j;'<':t->w(r,c-1)t j;'>':t->w(r,c+1)t j;'v':t->w(r+1,c)t j;'^':t->w(r-1,c)t j}where j=k 2(r,c)g
e[]v g=g;e(x:d)v g|elem x v||b x g/=1=e d v g|b x g==1=e(d++(i(\x->notElem x v)$i(\(r,c)->r>=0&&c>=0&&r<y g&&c<y(g!!0))$a x))(x:v)(k 0 x g)
a(r,c)=[(r+1,c+1),(r+1,c),(r+1,c-1),(r,c+1),(r,c-1),(r-1,c+1),(r-1,c),(r-1,c-1)]
m s=(y.i(/=0).concat.e[(0,0)][])(w(l+1,l+1)s(map(\_->map(\_->1)q)q))where l=y s;q=[0..2*l+2]

```

`m` is the main function, which takes a string over `v^<>`, and returns the appropriate integer.

### Ungolfed:

```
import Data.Set hiding (map, filter)

-- Generate a grid full of ones, of width and height 2x+1. We pass the length of
-- the input, and get back a grid that we could never go out of bounds from,
-- even when the input is a straight wall in any direction.
genGrid :: Int  -> [[Int]]
genGrid x = map (\_->map(\_->1) [0..2*x+2]) [0..2*x+2]

-- Update the value of a list l, such that index i now contains the value e
update :: Int -> a -> [a] -> [a]
update i e l = take i l ++ [e] ++ drop (i+1) l

-- scale update to two dimensions
set :: a -> (Int, Int) -> [[a]] -> [[a]]
set val (r,c) g = update r (update c val (g !! r)) g

-- index into a 2D array
at :: (Int, Int) -> [[a]] -> a
at (r,c) g = g !! r !! c

-- Walk the wall path. Replace any 1 we step on with a 2. Start walking from
-- given coordinates, recursively updating the spot we step on as we process
-- the input string.
walk :: (Int, Int) -> String -> [[Int]] -> [[Int]]
walk (r,c) s g = case s of
    "" -> set 2 (r,c) g
    '<':t -> walk (r,c-1) t (set 2 (r,c) g)
    '>':t -> walk (r,c+1) t (set 2 (r,c) g)
    'v':t -> walk (r+1,c) t (set 2 (r,c) g)
    '^':t -> walk (r-1,c) t (set 2 (r,c) g)

-- Given an input string, generate a grid of appropriate size and walk out the
-- wall path starting at the center.
sketch :: String -> [[Int]]
sketch s = let l = length s in walk (l+1,l+1) s (genGrid l)

-- Breadth-first exploration of the 2D grid, but do not pass through walls.
-- Will touch everything that's not part of the land, and mark it as not part
-- of the land. We use a set (a list in the golfed version) to keep track
-- of which coordinates we've already explored.
explore :: [(Int, Int)] -> Set (Int, Int) -> [[Int]] -> [[Int]]
explore [] v g = g
explore (x:cs) v g
    | member x v  = explore cs v g
    | at x g == 2 = explore cs v g
    | at x g == 0 = explore cs v g
    | at x g == 1 =
        explore (cs ++ (filter (\x-> notMember x v) $ filtBound g $ adj x))
            (insert x v) (set 0 x g)

-- Count everything marked as land to get the final total
countLand :: [[Int]] -> Int
countLand = length . filter (/=0) . concat

-- for a given list of coordinates and a 2D grid, filter those coordinates that
-- are within the grid's bounds
filtBound :: [[Int]] -> [(Int, Int)] -> [(Int, Int)]
filtBound g = filter (\(r,c) -> r >= 0 && c >= 0 && r < length g && c < length (g !! 0))

-- Given a coordinate, get all the adjacent coordinates, including diagonally
-- adjacent coordinates.
adj :: (Int, Int) -> [(Int, Int)]
adj (r,c) = [(r+1,c+1),(r+1,c),(r+1,c-1),(r,c+1),(r,c-1),(r-1,c+1),(r-1,c),(r-1,c-1)]

-- The main function
runMain :: String -> Int
runMain = countLand . explore [(0,0)] empty . sketch

-- Print a grid (for debugging & REPL convenience)
printG :: [[Int]] -> String
printG = concat . map ('\n':) . map show

```
> 2 votes

# Answer
## Mathematica, 124 bytes

You probably won't be surprised to learn that Mathematica has a built-in function for measuring the area encircled by a wall. Unfortunately, it's quite bytey: `ComponentMeasurements[..., "FilledCount", CornerNeighbors -> False]`.

With that in mind, here's my full answer. It's a function that takes a list of 1, i, -1 or -i:

```
1/.ComponentMeasurements[SparseArray[{Re@#,Im@#}&/@FoldList[#+#2&,2(1+I)Length@#,#]->1],"FilledCount",CornerNeighbors->1<0]&

```

Explanation:

* `FoldList[#+#2&,2(1+I)Length@#,#]` builds the wall by starting at coordinate 2(1+i)(length of wall) and successively adding the elements of the input list. (We have to start at the ridiculously large coordinate 2(1+i)(length of wall) to ensure that the wall coordinates stay positive, otherwise things break.)
* `SparseArray[{Re@#,Im@#}&/@...->1]` turns these coordinates from complex numbers to pairs of integers, and makes an array with 1s where the wall is and 0s elsewhere.
* `1/.ComponentMeasurements[...,"FilledCount",CornerNeighbors->1<0]&` uses built-in Mathematica magic to measure the area enclosed by the wall.
> 2 votes

# Answer
# PHP\>=5.6.2, 888 Bytes

Online Version

```
<?$h=$v=0;
s($v,$h,S);
for($z=0;$z<strlen($i=$_GET[0]);){
2<($b=$i[$z++])?$h--:($b>1?$v++:($b?$h++:$v--));
$e=max($h,$e);
$w=min($h,$w);
$n=min($v,$n);
$s=max($v,$s);
s($v,$h,X);}
$f=($e-$w+1)*($s-$n+1);
ksort($a);
function i($v,$h){global$a;return isset($a[$v][$h])&&$a[$v][$h]==" ";}
function s($v,$h,$l=" "){global$a;$a[$v][$h]=$l;}
function c($v,$h,$n=1){global$a;
foreach($r=range(-1,$n)as$i)
foreach($r as$j)
if(($i+$j)&&i($v+$i,$h+$j)){if($n)s($v,$h);return 1;}return;}
foreach($a as$v=>$z){
foreach(range($w,$e)as$h){
if(!isset($a[$v][$h])){
if(($v==$s)||($v==$n)||($h==$e)||($h==$w)||c($v,$h,0))s($v,$h);
else$c[]=[$v,$h];}
}ksort($a[$v]);}
while($z){$z=0;
foreach($c as$b=>$w){if(c(...$w)){$z++;unset($c[$b]);}}};
foreach($c as$b=>$w)$a[$w[0]][$w{1}]=O;
foreach($a as $k=>$v){ksort($a[$k]);$g.=join($a[$k])."\n";}echo $g;
echo $f-substr_count($g," ");

```
> 1 votes

---
Tags: code-golf, grid, counting
---


title: Keyboard Encryption

text:
# Question
Title: Keyboard Encryption
# Challenge

Given a string with any characters a-z or A-Z, return an 'encrypted' string, where all characters are replaced by the character next to it (assuming a QWERTY keyboard).

* Case (uppercase, lowercase) **does not matter**.
* The input will **only** have characters a-z and A-Z.

Shortest code in bytes wins.

---

# Example Input and Output

`Foo Foo Bar Bar Python``Gpp Gpp Nst Nst [uyjpm`

`Case does not matter``vSDR fprd mpy ,sYYrT`

# Answer
> 1 votes
# Jelly, 16 bytes

```
ŒlµØqż“[;,”Fṡ2Zy

```

**Try it online!**

### How?

```
ŒlµØqż“[;,”Fṡ2Zy - Main link: string
Œl               - convert to lowercase
  µ              - monadic chain separation
   Øq            - qwerty yield: ["qwertyuiop","asdfghjkl","zxcvbnm"]
      “[;,”      - "[;,"
     ż           - zip: [["qwertyuiop","["],["asdfghjkl",";"],["zxcvbnm",","]
           F     - flatten: "qwertyuiop[asdfghjkl;zxcvbnm,"
            ṡ2   - overlapping pairs: ["qw","we","er","rt","ty","yu","ui","io","op","p[","[a","as","sd","df","fg","gh","hj","jk","kl","l;",";z","zx","xc","cv","vb","bn","nm","m,"]
              Z  - transpose: ["qwertyuiop[asdfghjkl;zxcvbnm","wertyuiop[asdfghjkl;zxcvbnm,"]
               y - translate the lowercased string with that mapping

```

# Answer
> 1 votes
# Python 3, 91 bytes:

```
s='qwertyuiop[asdfghjkl;zxcvbnm,  '
print(''.join(s[s.index(c)+1]for c in input().lower()))

```

---
Tags: code-golf, keyboard, encryption
---


title: Run a game of Flood

text:
# Question
Title: Run a game of Flood
This is a Code Golf challenge.

Flood is a game in which the player is presented with a game board such as this:

On each turn, you choose a colour (on the link above, by clicking a square containing that colour), and the cell in the top-left corner is filled with that colour - this colour will absorb all adjacent cells with the same colour. So, for example, the first turn might be Blue, which will cause the yellow cell in the top corner to turn blue, and merge with the existing blue cell. The next turn might be Purple, which will fill both of the first two cells purple, merging them with the two-cell purple area attached to them. Then you might go Red, then Orange. With this sequence, the board will end up as:

Your task is to write a code that simulates the game, taking in an array or other data format containing the current state of the game, in a suitable format (picture, numbers in a square array, string with numbers indicating the dimensions, anything that can be identified with the game), along with one or more input commands (colours, cells that contain colours, etc - your choice of how to implement the sequence, but you need to explain it).

If (and only if) the input solves the board (causes all cells to be the same colour), then your code should print a message in some format informing the player that the board is cleared or completed. It is up to you how this is done, but it must be clear to any English speaker using the code without requiring separate documentation (so outputting "1" isn't good enough). Note that displaying a completed board is not sufficient.

Some example options for completion output include `win`, `done`, `complete`, or `clear`. If your language doesn't have a nice way to output a longer message, I recommend using `win`.

Whether the input solves the board or not, the code should output (either as function output or as a displayed output) the final state of the board.

The code may take input of moves interactively (from STDIN, to simulate the actual game) or as a code input.

## Scoring

Your goal is to minimise the number of bytes in the function or code.

## Rules and Assumptions

Standard Loopholes are forbidden.

Code must be able to handle non-square boards, with each dimension being anywhere between 6 and 30 cells (more is fine, it must handle this range). It must be able to handle between 3 and 9 distinct colours or "colour" labels (numbers are fine).

You may assume that input is in simplest form - that is, if there are four colours, they will be labelled 1-4, or a-d, or any other similar system as appropriate. You will not need to handle situations such as incorrect inputs, unsimplified inputs (you won't have the numbers 1, 3, 6, and 9, without the others in between, unless it suits your code).

Your answer should include a description of formats, etc.

**Request**: If you believe you have identified a non-standard loophole, and it's definitely a loophole and not in the spirit of the question, please comment to have the loophole closed, rather than posting an answer using it. This is not a rule, *per se*, but an effort to keep the challenge interesting.

# Answer
# Octave, ~~68~~ ~~64~~ ~~94~~ ~~92~~ 83 bytes

```
a=f(a,s)m=a;for k=s;[~,x]=bwfill(a~=k&m,1,1,4);m(x)=0;a(x)=k;end;~m&&puts("win\n");

```

A function that takes as input a matrix `a` and a vector `s` as the sequence of commands and outputs the final state of the board.

Explanation:

```
function a=Flood(a,s)
    m=a;
    for k=s
        [~,x]=bwfill(a~=k&m,1,1,4);
        m(x)=0;
        a(x)=k;
    end
    ~m&&puts("Game Completed\n");
end

```

Usage:

```
num_colors = 4;
a = randi(num_colors, 5 ,7)
s = randi(num_colors, 1 , 15);
Flood(a,s)

```

Use `m` as a mask representing the filled region so far. Repeatedly run commands and flood fill the masked grid from the top left corner.
> 6 votes

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