title: Hast Thou Slain the Jabberwock?

text:
# Question
Title: Hast Thou Slain the Jabberwock?
Your task is to output the exact string

```
The Jabberwocky

```

without taking input. Normal rules for input and output apply, so both functions and programs are allowed.

Of course there is a catch, it wouldn't be fun without a catch. Your program, when stripped of non-alphabetic characters, must start the poem The Jabberwocky (case insensitive). To start the poem it must be a continuous substring of the poem starting at the beginning. The empty string is fine (although you probably won't score very well).

Here is the text for reference:

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestoodthejabberwockwitheyesofflamecamewhifflingthroughthetulgeywoodandburbledasitcameonetwoonetwoandthroughandthroughthevorpalbladewentsnickersnackheleftitdeadandwithitsheadhewentgalumphingbackandhastthouslainthejabberwockcometomyarmsmybeamishboyofrabjousdaycalloohcallayhechortledinhisjoytwasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabe

```

Here is a program you can use to test this property.

If you run out of poem to use you **may not** use any additional alphabetic characters.

Alphabetic characters are characters `a`-`z` and `A`-`Z` here is the complete list:

```
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

```

## Scoring

Your program will be scored in the number of non-alphabetic bytes used with fewer being better.

Here is a Haskell program that scores answers. (This assumes inputs are valid)

## Example program

The following program would be valid:

```
twas&*brilliga77812nd Thesli thyt Oves didgy reand Gim bleinth ewab eal lmims ywe""""""""
ret h eb or o g o ve sa n dthemomerAthsoutgrabebewaretheJABBERWOCKmysonthe)(*)()((*98980908(()*(jawsthatbit

```

When stripped down to alphabetic characters it is:

```
twasbrilligandTheslithytOvesdidgyreandGimbleinthewabeallmimsyweretheb orogovesandthemomerAthsoutgrabebewaretheJABBERWOCKmysonthejawsthatbit

```

Which matches the first bit of the poem (case insensitive).

This program would score 59 because it contains these non-alphabetic characters:

```
&*77812           """"""""
          )(*)()((*98980908(()*(

```

# Answer
> 44 votes
## oOo CODE, score 0

*Thanks to Dennis for golfing the Brainfuck code.*

```
TwASbRIlLIgAnDthEsliTHyTOvEsdiDgyreaNdgImbleinthEwaBeaLlmimSywEreThEBoroGoveSAndTheMOmERaTHSoutGRabEbeWArEthEjaBbeRWockMYsONtHEJawsTHaTBiTEThecLawSthATcaTChBeWAReTHeJuBJuBBiRDAndsHUNtHeFRuMIoUSbANdERSnatchheTooKHisvORpaLswORdinhAndLonGtiMetHEmanXomEFoEHeSOUg

```

Try it online!

I've got bad news for this challenge... :(

oOo CODE is just a binary encoding of brainfuck which uses the case of a letter for each bit. So yeah, since the poem is long enough (or the output short enough) to cover a Brainfuck program that prints `The Jabberwocky` (without actually trying hard to golf it), this becomes a trivial optimal answer.

# Answer
> 25 votes
# C, score  ~~104~~   ~~79~~  74

*Thanks to @gastropner for lowering the score to 79 and thanks to @wizzwizz4 for lowering it further to 74!*

```
*t,w;a(s,b,rilligand){*(t//he
=s++)="lithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewareThe Jabberwock\0mysonthejawsthat"[b++]?//i
:121;*t>12e1?*++t//hecl
=0:a//wsthatcatchbewarethejubjubbirdandshunthefrumiou
(s,b);}an;der(s,n){a(//tchhetookhi
s,88);}

```

Try it online!

# Answer
> 21 votes
## Fission 2, score 3

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewaRe"The Jabberwock"mysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestoodthejabberwockwitheyesofflamecamewhifflingthroughthetulgeywoodandburbledasitcameonetwoonetwoandthroughandthroughthevorpalbladewentsnickersnackheleftitdeadandwithitsheadhewentgalumphingbackandhastthouslainthejabberwockcometomyarmsmybeamishboyO

```

Try it online!

### Explanation

We can ignore most of the lowercase letters, they just set an atom's energy to their code point.

```
...Re"The Jabberwock"my...oyO

```

The uppercase `R` is the program's entry point, as it creates an atom going right. As I said, we can ignore the `e`. Then `"` toggles string mode, which just prints all characters it encounters to STDOUT, which gives us `The Jabberwock`. That only leaves the `y`. We could use the `y` that's coming up immediately in `y`, but then we'd have to waste at least one non-letter byte on printing it (`!`) and possibly another on terminating the program.

Instead, we patiently wait for `y` to show up immediately before `o` in the poem. Because that lets us use `O` which prints the character *and* destroys the atom, terminating the program. This way, the only non-letter characters we need are the space and the two quotes.

# Answer
> 15 votes
# Alice, score 7

```
"T/was"bri@lligandtheslithytovesdidgyreandgimbleinthewabeallmimsywe
rethe borogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestoodthejabberwockwitheyesofflamecamewhifflingthroughthetulgeywoodandburbledasitcameonetwoonetwoandthroughandthroughthevorpalbl
adewentsn

```

Try it online!

The `/` makes the IP move diagonally and bounce off the edges, so the instructions actually executed are `"The "ono@`. The `n` command (in ordinal mode) pushes the string "Jabberwocky" if the top of the stack is empty, and `o` outputs the top of the stack.

# Answer
> 13 votes
# Jelly, score  ~~6~~  4

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathSOUTGRABEBEWARE“The Jabberwock”m”y

```

A full program printing the result
(as a monadic link it prints `The Jabberwock` as a side-effect and returns the character `y`)

Inserts the characters `“ ””` into a case-changed prefix of the poem.

This works because:

1. The last `h` before `SOUTGRABEBEWARE“The Jabberwock”m”y` is (at least at the time of writing!) an undefined atom, which makes that all become a new link which takes the default input of `0` and performs some monadic functions, `SOUTGRABEBEWARE`, which yield `1` (see below).
2. `1“The Jabberwock”m` then performs `m`, modulo slicing, on `"The Jabberwock"` with a slice size of `1`, yielding `"The Jabberwock"`.
3. The trailing `”y` is a new leading constant chain so Jelly prints that list of characters and then yields the character `y`, and since it's now the end of the program this then gets printed.

```
 implicit input = 0
S sum             0
O cast to ordinal 0
U upend           [0]
T truthy indices  []
G group           []
R range           []
A absolute value  []
B to-binary       []
E all-equal?      1
B to-binary       [1]
E all-equal?      1
W wrap            [1]
A absolute value  [1]
R range           [[1]]
E all-equal?      1

```

---

Previous 6 byter:

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware
“The Jabberwock”m1“y

```

**Try it online!**

The six non-poem characters are a newline plus `“ ”1“`.

---

Alternative 6s:

```
“T“wasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewaret“he Jabberwock”m2“y

```

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewaret
“The Jabberwockmy”ṪṭṖ

```

# Answer
> 7 votes
# Charcoal, score 3

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware⎚The Jabberwock⌈my

```

**Try it online!**

Inserted the three characters: `⎚ ⌈`

...it also works with the whole poem.

### How?

```
twas ... ware⎚The Jabberwock⌈my - no input
twas ... ware                    - print this text     >  twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware
             ⎚                  - clear the screen    >
               The Jabberwock    - print this text     > The Jabberwock
                             ⌈   - (print) maximum of:
                              my -   this text         > The Jabberwocky

```

# Answer
> 5 votes
# Ruby (`-p`), Score 12

```
$_=#twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware
'The Jabberwock'+#m
?y

```

Try it online!

Abuse all the comments!

With the `-p` flag, ruby will print whatever stored in `$_`. Requires a single line of any input.

# Answer
> 5 votes
# Charcoal, score: ~~5~~ 4

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware⎚The Jabberwock¿m¦y

```

Try it online! Edit: Saved 1 byte thanks to @ASCII-only. Explanation: Translates to the following verbose code:

```
Print("twas...beware");
Clear();
Print("The Jabberwock");
if ("m") Print("y");

```

# Answer
> 4 votes
# Foo, score 5

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware"The Jabberwock"m"y"

```

Try it online!

# Answer
> 4 votes
# \>\<\>, Score: ~~13~~ 12

```
\twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware
\"The Jabberwockmy"$~\sonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestoodthejabberwockwitheyeso
fflamecamewhifflingth>ro<

```

Try it online!

Verification and scoring.

Immediately redirects to the second line, which pushes "The Jabberwockmy" in reverse to the stack. `$~` pops the excess `m` and `>ro<` prints the whole stack, reversing it beforehand.

# Answer
> 3 votes
# PowerShell, Score: ~~19~~ 10

```
#twasbrilligandTheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethe
'The Jabberwock'+#m
'y'

```

Try it online!

Port of Pavel's Ruby answer. Thanks to Jo King for -9 points.

The strings are `+` concatenated together. Once the comments are removed and the code parsed, PowerShell sees this as `'The Jabberwock'+'y'`. That string is left on the pipeline and output is implicit.

# Answer
> 3 votes
# Retina 0.8.2, score: ~~21~~ ~~20~~ ~~18~~ ~~16~~ ~~13~~ ~~8~~ 6

```
|twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware
The Jabberwock0$*my

```

Try it online! Edit: Score reduced by 2 thanks to @MartinEnder.

# Answer
> 3 votes
# C, score 23

```
twasbrilligandtheslithytovesdidgyreandgimble(int**h){//ewabeallmimsyweretheborogovesandthemomerat
*h//soutgrabebeware
="The Jabberwock"//m
"y";}

```

Try it online!

# Answer
> 2 votes
# 05AB1E, score 14

```
"twasbrilligand""The ""slithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethe"Š"Jabberwock"+"my"Š

```

Try it online!

# Answer
> 2 votes
# Yabasic, 13

Thanks for @Pavel's Ruby answer!

```
#twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware
?"The Jabberwock";//m
?"y"

```

Try it online!

# Answer
> 2 votes
# Java (OpenJDK 9), score 11

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware->"The Jabberwock"+//m
"y"

```

Try it online!

### Credits

# Answer
> 2 votes
## VBA, score 5

Run in the Immediate Window:

```
?twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware"The Jabberwock"m"y

```

How it works:

> `?` \- This prints out output as a string

-

> `twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware` \- without Explicit declaration, this is treated as an empty string

-

> `"The Jabberwock"` \- String. When you put 2 variables/strings next to each other, VBA will automatically concatenate them. (2 non-variable strings would require a space so as not to add a double-quote)

-

> `m` \- Another implicit empty-string, automatically concatenated

-

> `"y` \- Another string. Left open, the Immediate Window will automatically close this when it hits the end of the line - again, automatically concatenated

-

1 question-mark, 1 space and 3 double-quotes. VBA sees this as `?"" & "The Jabberwock" & "" & "y"` or `?"The Jabberwocky"`

# Answer
> 2 votes
# Haskell, score 12

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware="The Jabberwock"++{-m-}"y"

```

Try it online!

Defines a zero-argument function `twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware :: String` whose output is `"The Jabberwocky"`.

# Answer
> 1 votes
# Jelly, score: 8

```
“ĠȥṘ®ṖȤ»

```

Try it online!

Just compresses the string, and is an empty string when all non-alphabet characters are removed. Annoyingly, the shortest compressed form, `“81Iȯd»` has alphabetical characters, neither of which are `t` or `w`

# Answer
> 1 votes
# Stax, 11

```
£«≡¿«_→Ä:£◘

```

Run and debug online!

Just a compressed string literal that is in turn packed.

# Answer
> 1 votes
# SOGL V0.12, score 9

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware”The” Jabberwock”:⁄m+ y+

```

Try it Here!

# Answer
> 1 votes
# Canvas, score 5

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware∙The Jabberwockｐm∙yｐ

```

Try it here!

# Answer
> 1 votes
# Pip, score 5

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestOOD|"The Jabberwock"witheyesofflamecamewhifflingthroughthetulge'y

```

Try it online!

Fortunately, lowercase letters in Pip are all variables, which are no-ops in expressions by themselves. The interesting part of the code:

```
OOD|"The Jabberwock"

```

The scanner breaks up `OOD` as `O` followed by `OD`. `OD` is an undefined variable, which evaluates as nil (falsey); we then logical-or this with `"The Jabberwock"`, and `O` outputs it without a newline.

```
'y

```

Single-character string `y`. Since it is the last expression in the program, it is printed.

# Answer
> 1 votes
# SmileBASIC, score 10

```
@twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware?"The Jabberwock";
@m?"y

```

This was pretty much taken directly from the Yabasic answer, and ~~since SB is a better language,~~ we can shorten it by using labels rather than comments, which eliminates the need for some of the line breaks

There is also this alternative solution, for the same size:

```
@twasbrillig ... ?"The Jabberwock"+@my[2]

```

A label inside an expression is treated as a string. (`@my == "@my"`), so taking character 2 gives "y".

# Answer
> 1 votes
# C (gcc), score 58

The useful fact that // style comments + newlines are cheaper than old-style ones comes straight from @wizzwizz4's comment for @Steadybox's answer.

The -m32 flag is required.

Some might be brought to a frumious mood by the lengthy name of the function to call, whereas others might rightly find such objections mimsy; in the end, we must all of us heed the siren song of low scores.

```
twasbrilligan;d(t,h,e,slithytovesdidgyreandgimble)int*h,*e;//wabeallmimsywere
{t--?*h++=*e++,//borogovesan
d(t,h,e):0;}momerathsoutgrabebewar;*e="The Jabberwock\171";mysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoug(h,tsoreste){d(4,h,e);}

```

Try it online!

# Answer
> 1 votes
# Perl 5, subroutine, score 11

```
{twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware;'The Jabberwock'.~'X'}

```

but with the character \x86 (`v134`) instead of the X.

(perlsub says "The signature is part of a subroutine's body. Normally the body of a subroutine is simply a braced block of code.")

# Answer
> 1 votes
# Batch, score 15 11

```
:twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbiteth
@ec%lawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffisht%ho%ughthestood% The Jabberwock%withe%y

```

Basically just `echo The Jabberwocky` with unused variables and labels.

Old version (score 24):

```
:twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestoodthejabberwockwitheyesofflamecamewh
@if %1%fl%i==%ngthroughthetulgeywoodandburbledasitcameonetwoonetwoandthroughandthroughthevorpalbladewentsnickersnackheleftitdeadandwithitsheadhewentgalumphingbackandhastthousla%i n The Jabberwock%cometom%y
:armsmybeamishboyofrabjousdaycalloohcallayh
@echo %*

```

Requires code to be saved in a file named `n.bat` and run from the same directory.

Alternate version which can have any name (score 27):

```
:twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvorpalswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestoodthejabberwockwitheyesofflamecamewh
@if %1%fl%i==%ngthroughthetulgeywoodandburbledasitcameonetwoonetwoandthroughandthroughthevorpalbladewentsnickersnackheleftitdeadandwithitsheadhewentgalumphingbackandhastthousla%i %~n0 The Jabberwock%cometom%y
:armsmybeamishboyofrabjousdaycalloohcallayh
@echo %*

```

Explanation (with variables removed):

```
:twas...                         Label (No labels were used, no goto in the poem)
@if %1i==i %~n0 The Jabberwocky  If no command line arguments, run this batch file again
:arms...                          with the arguments 'The Jabberwocky'
@echo %*                         Echo all arguments

```

# Answer
> 1 votes
# Ruby, 9 non letter bytes

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewarethejabberwockmysonthejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvor=p alswordinhandlongtimethemanxomefoehesoughtsorestedhebythetumtumtreeandstoodawhileinthoughtandasinuffishthoughthestood="The Jabberwock"+withe=?y

```

Try it online!

### Golfed version (for readability):

```
x=p z="The Jabberwock"+w=?y

```

Uses a few long and useless variables. In ruby, you can put `whatever_you_want=` before an expression, and it will still return that expression, just with the side effect of creating an oddly-named variable.

# Answer
> 1 votes
# Self-modifying Brainfuck, score 16

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware␀The Jabberwock␀my<[<<]>[.>]>>.

```

Try it online!

## Explanation

Initially the tape is set up like this:

$$ \begin{aligned} \dots\ \texttt{␀}\ \texttt{T}\ \texttt{h}\ \texttt{e}\ \texttt{␠}\ \texttt{J}\ \texttt{a}\ \texttt{b}\ \texttt{b}\ \texttt{e}\ \texttt{r}\ \texttt{w}\ \texttt{o}\ \texttt{c}\ \texttt{k}\ \texttt{␀}\ \texttt{m}\ \texttt{y}\ \texttt{\<}\ \texttt{\[}\ \texttt{\<}\ \texttt{\<}\ \texttt{\]}\ \texttt{\>}\ \texttt{\[}\ \texttt{.}\ \texttt{\>}\ \texttt{\]}\ \texttt{\>}\ \texttt{\>}\ \texttt{.}\ & \texttt{␀}\ \texttt{␀}\ \dots \\ & \uparrow \end{aligned} $$

Since we want to move to the beginning of the string we use `<[<<]` such that we jump over the first \\$\texttt{␀}\\$ character.

Now we can just move to the \\$\texttt{T}\\$ with `>` and print the whole string with `[.>]` and since we picked the substring where the next \\$\texttt{y}\\$ is not far, we can just jump to it directely and print it with `>>.`.

# Answer
> 0 votes
# BF, 143 bytes (score 143)

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

```

Try it online!

No letters means no poem.

# Alternate (BF, 861 bytes, score 143)

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

```

Now with 100% more poem

# Answer
> 0 votes
# Fission, score 6

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewaRe"The Jabberwock"m"y";

```

Try it online!

# Answer
> 0 votes
# C# (Mono C# Shell), Score 12

```
//twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware
"The Jabberwock"//m
+"y"

```

Try it online!

Mono comes with a program called, well, `csharp`, that lets you run C# programs as a script. It's essentially a wrapper for the REPL, and supports implicit printing.

# Answer
> 0 votes
# APL (Dyalog), score ~~21~~ 14

```
1⌽1↓¯2⌽106↓'twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebewareThe Jabberwockmy'

```

Try it online!

# Answer
> 0 votes
# JavaScript (SpiderMonkey), score 12

```
twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware=>
"The Jabberwock"+//m
"y"

```

Try it online!

# Credits

Shamelessly ripped from this answer for Java.

-2 points from Brian H.

# Answer
> 0 votes
# dc, score ~~14~~ 12

```
#twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware
[The Jabberwock]#myso
n121#thejawsthatbitetheclawsthatcatchbewarethejubjubbirdandshunthefrumiousbandersnatchhetookhisvor
P

```

Try it online!

Rather uninteresting solution, but I'm not sure it can be optimized much more beyond uninteresting. Just comments everything out until the first part of the string, comments out until we hit an `n` to print, then inputs 121 as the ASCII value of 'y' and comments out until we hit a `P` to print.

-1 point thanks to Jo King (and no thanks to my inattention…)

-1 more point when I realized using the ASCII value for 'y' was ultimately shorter.

# Answer
> 0 votes
# APL (Dyalog Unicode), score 10

```
'twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware'⊢'The Jabberwock',⊢/'my'

```

Try it online!

`'my'` the character vector `"my"`

`⊢/` rightmost element; `"y"`

`'The Jabberwock',` prepend the main part; `"The Jabberwocky"`

`'twa``are'⊢` yield that and discard the beginning of the poem

# Answer
> 0 votes
# PHP, score 12

```
<?=#twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware
"The Jabberwock".#m
y;

```

Try it online!

It's interesting that in the poem, it says "he chortled" which contains the word `echo` (ignoring the white space). I tried to use this to my advantage instead of having the `<?=`, but always came out with a higher score that way.

# Answer
> 0 votes
# Befunge-93, 33 17 score

```
^twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesan
<dthemomerathsoutgrabebeware>:#,_@#:"The Jabberwock"m#"y"

```

Try it online!

Golfed 16 score thanks to the suggestion by W W

# Answer
> 0 votes
# CJam, score 8

```
"twasbrilligandtheslithytovesdidgyreandgimbleinthewabeallmimsyweretheborogovesandthemomerathsoutgrabebeware";"The Jabberwock"'m;'y

```

'tis a shame this was so simple, I was enjoying using the `c` to convert numbers to characters and then rearrange them at great expense.

Try it online

Verify online

Explanation:

```
"tw...re";          Discard the first part of the poem
"The Jabberwock"    Push a jabberwock
'm;                 Discard a spare m
'y                  Take the last y

```

---
Tags: code-challenge, kolmogorov-complexity, restricted-source
---


title: JFor? More like XNor

text:
# Question
Title: JFor? More like XNor
As it turns out, Python allows for `1j for` to be compressed to `1jfor`. However, `jfor` sounds like `xnor`. Since all similar-phonic phrases have *something* in common, there must be some property shared between `jfor` and `xnor`.

If we look at the ASCII representation of the first two characters of `jfor` in binary, we see:

```
j:   1101010
f:   1100110
j&f: 1100010

```

Notice that the bitwise AND of `j` and `f` has a streak of `1`s at the beginning, then some `0s`, then a single `1`.

Definition: A pair of numbers meets the JFor property iff their bitwise AND in binary meets the following regex (excluding leading 0s): `/1+0+1+0*/` (1 or more `1`s, followed by 1 or more `0`s, followed by 1 or more `1`s, followed by 0 or more `0`s)

Do the ASCII codes for `x` and `n` meet the JFor property?

```
x:   1111000
n:   1101110
x&n: 1101000

```

Yes! So my hunch was correct; `jfor` and `xnor` sound similar, and they share a property (This means, of course, that `odor` must have that property too).

## Task

Given a pair of numbers, determine if they meet the JFor property.

The two numbers may not be distinct, but they will both be integers from `0` to `255` respectively.

Output may follow your language's conventions for Truthy and Falsey, or you may choose any two consistent, distinct values to represent truthy and falsey respectively.

Your program/function may take input in any reasonable format to represent an ordered pair of integers/bytes.

## Test cases

```
# Truthy:
106 102
110 120
42 26
17 29
228 159
255 253

# Falsey:
85 170
228 67
17 38
255 255
38 120
21 21

```

(Bounty: 50 rep to the shortest answer on July 24 **if** it somehow uses a XOR or XNOR operation; please mention if your submission qualifies)

# Answer
> 23 votes
# Python, 34 bytes

```
lambda a,b:bin(a&b).count('01')==1

```

Try it online!

Although this doesn't use `xor`, I'm xnor.

# Answer
> 5 votes
# Python 2,  ~~42~~  41 bytes

<sup>Uses XOR, `^`</sup>

-1 thanks to Neil (double rather than halve).

```
lambda a,b:bin(a&b^(a&b)*2).count('1')==4

```

**Try it online!**

# Answer
> 4 votes
# perl -Mfeature=bitwise -alp, 41 40 bytes

```
$_=2==(()=sprintf("%b",$_&$F[1])=~/1+/g)

```

Try it online!

## How does it work?

The program reads lines from `STDIN`, expecting two numbers on each line. `1` is printed for pairs of numbers with the jfor property, an empty line for pairs without the jfor property.

The `-p` switch makes that the program loops over each line of the input, making the line available in `$_`. And the end, it will print whatever is in `$_`. The `-l` switch removes the trailing newline. The `-a` switch makes that the input is split on white space, with the components placed in `@F`. In particular, the second number will be in `$F[1]`.

```
$_ & $F [1]

```

Due to the `-Mfeature=bitwise` switch, this makes `&` treat its operands as numbers, and performs a bitwise and on them. This makes that while `$_` contains both numbers, only the first number is considered, as that is what Perl does with a string which is used as a number: if the beginning looks like a number, this is taken. (`atoi`, `atof`, yada, yada, yada). So, we're doing a bitwise and of the two numbers.

```
sprintf ("%b", ...)

```

This returns the result in a binary representation.

```
() = ... =~ /1+/g

```

Find all the sequences of consecutive `1`s. This is assigned to a list (of 0 variables). We're throwing away the results, but assignment itself does have a return value; for a list assignment, the result is the number of elements on the RHS.

```
$_ = 2 == (...)

```

Compares the result (of the list assignment above) to 2. If equal, set `$_` to `1`, else to the empty string.

**Edit**: Saved a byte by looking at sequences of 1, instead of a full pattern.

# Answer
> 4 votes
# Japt `-!`, ~~11~~ 9 bytes

```
r& ¤ÔèA É

```

Try it

```
r& ¤ÔèA É     :Implicit input of integer array
r             :Reduce by
 &            :  Bitwise AND
   ¤          :Convert to binary string
    Ô         :Reverse
     è        :Count the occurrences of
      A       :  10, which gets coerced to a string
        É     :Subtract 1
              :Implicit output of Boolean negation

```

# Answer
> 4 votes
# C (gcc), 53 bytes

```
f(a,b){for(a&=b,b=0;a;a=~a)for(b++;~a&1;a/=2);a=b^4;}

```

Try it online!

Returns `0` if the two numbers do have the JFor property, and truthy otherwise.

# Answer
> 3 votes
# Pip, 11 bytes

```
1=01NTBaBAb

```

Try it online! (Verify all test cases)

The main trick is borrowed from xnor's Python answer: the property is satisfied if the binary representation of the bitwise AND contains the sequence `01` exactly once.

```
1=01NTBaBAb
             a and b are command-line args (implicit)
  01         01 (an integer literal, but treated as a string unless used in a numeric operation)
    N        Count occurrences in:
       aBAb   Bitwise AND of a and b
     TB       Converted to binary
1=           Test whether the number of occurrences equals 1 (0 if not, 1 if so)
             Autoprint (implicit)

```

# Answer
> 2 votes
# Jelly,  ~~9~~  8 bytes

```
&BḄƝċ1=1

```

A dyadic Link accepting which yields `1` if jfor or `0` if not.

**Try it online!** Or see the test-suite.

---

### 8 bytes using XOR

-2 thanks to Neil (double rather than halve).

```
&Ḥ^$BS⁼4

```

Try it online!.

# Answer
> 2 votes
# Python 3, 137 bytes

```
def f(x,y):
	b=format;z='08b';x=b(x,z);y=b(y,z);a=""
	for i in range(8):a+=str(int(x[i])and int(y[i]))
	return int(a[7])+a.count("10")==2

```

Try it online!

# Answer
> 2 votes
# , ~~37~~ ~~34~~ 33 bytes

-3 bytes thanks to Dominic van Essen

```
function(x,y)sum(rle(x&y)$v>0)==2

```

Try it online!

Takes input as raw bytes, as given by `intToBits`. In R, this gives a length 32 vector with the least significant bit first, therefore padded with many zeros. Then compute the run lengths, i.e. sequences of consecutive identical elements. The JFor property is verified if there are exactly two runs of 1s.

---

A (dumb) solution with XOR is:

# , 39 bytes

```
function(x,y)xor(sum(rle(x&y)$v>0)-2,1)

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog Extended), 9 bytes

```
2=≢⊆⍨∧/⊤⎕

```

Try it online!

### How it works

```
2=≢⊆⍨∧/⊤⎕  ⍝ Full program; input = a vector of two numbers
       ⊤⎕  ⍝ Binary representation of two numbers
     ∧/    ⍝ Bitwise AND
   ⊆⍨      ⍝ Extract chunks of ones
2=≢        ⍝ Test if there are exactly two chunks

```

# Answer
> 1 votes
# Charcoal, ~~23~~ 19 bytes

```
≔＆ＮＮθ⁼⁴Σ⍘⁻｜⊗θθ＆⊗θθ²

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean i.e. `-` for JFor, nothing if not. Edit: Switched to my version of @JonathanAllan's answer to save 4 bytes. Explanation:

```
≔＆ＮＮθ

```

Input the two numbers and take their bitwise AND.

```
⁼⁴Σ⍘⁻｜⊗θθ＆⊗θθ²

```

Take the bitwise XOR of twice the number with itself (Charcoal has no XOR operator, so I have to do this longhand) and check that the result (in base 2) has exactly four `1` bits.

# Answer
> 1 votes
# Perl 5 +`-pl`, 35 bytes

```
$_=unpack(B8,$_&<>)=~/^0*1+0+1+0*$/

```

Try it online!

## Explanation

This accepts characters as input to allow using `unpack` to get the first 8 chars of the binary representation of the stringwise `AND` of `$_` (which implicitly contains the input line) and `<>` (which is the following line of input) and checks for the pattern as specified. Prints `1` for JFor pair or the empty string otherwise.

---

# Perl 5 \+ `-pl`, 34 bytes

```
$_=(@a=unpack(B8,$_&<>)=~/1+/g)==2

```

This uses @Abigail's counting approach, thanks @Dominic van Essen!

Try it online!

# Answer
> 1 votes
# Io, 60 bytes

-1 byte thanks to @DLosc.

```
method(x,y,(x&y)asBinary strip("0")occurancesOfSeq("01")==1)

```

Try it online!

# Answer
> 1 votes
# C# (Visual C# Interactive Compiler), 58 bytes

```
a=>b=>Regex.Matches(Convert.ToString(a&b,2),"01").Count==1

```

Try it online!

# Answer
> 1 votes
# APL+WIN, 24 bytes and uses xnor

Prompts for input as a vector of 2 integers:

```
4=+/b≠9↑1↓b←∊×/(⊂9⍴2)⊤¨⎕

```

Try it online! Coutesy of Dyalog Classic

# Answer
> 1 votes
# JavaScript (V8), 44 bytes

```
(a,b)=>(a&b).toString(2).match(/^1+0+1+0*$/)

```

Try it online!

Takes input as two numbers, returns a binary string if they meet the JFor property, otherwise `null`

```
(a,b)=>(~(a^b)&(a|b)).toString(2).match(/^1+0+1+0*$/)

```

Try it online!

The same function, but instead uses an XOR to get the binary string.

# Answer
> 1 votes
# 05AB1E, ~~8~~ 7 bytes (without XOR/XNOR bonus)

```
&b0«ÔCн

```

Outputs `1` for truthy and `0`/`2`/`4` for falsey (only `1` is truthy in 05AB1E, so this is allowed according to rule "*Output may follow your language's conventions for Truthy and Falsey*").

Try it online or verify all test cases.

**8 bytes with XOR bonus:**

```
&x^2вO4Q

```

Port of *@JonathanAllan*'s Python 2 answer.

Try it online or verify all test cases.

**Explanation:**

```
&        # Bitwise-AND the two (implicit) input-integer together
 b       # Convert it to a binary-string
  0«     # Append a trailing 0 at the end
    Ô    # Connected uniquify it
     C   # Convert it from binary back to an integer
         # (which will result in 0/2/10/42; of which only 10 is a truthy test result)
      н  # Pop and leave just the first digit (0/2/1/4, of which only 1 is 05AB1E truthy)
         # (after which the result is output implicitly)

&        # Bitwise-AND the two (implicit) input-integers together
 x       # Double it (without popping)
  ^      # Bitwise-XOR (a&b) with 2*(a&b)
   2в    # Convert this to a binary-list
     O   # Sum that list to get the amount of set bits
      4Q # And check if it's equal to 4
         # (after which the result is output implicitly)

```

The last four bytes has a few alternatives, like `5%3@` or `₆ÍÃĀ`.

# Answer
> 0 votes
# Scala, ~~46~~ ~~45~~ bytes

```
_.&(_).toBinaryString matches "1+0+1+0*"

```

Try it online

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


title: Generate ASCII TetraVex

text:
# Question
Title: Generate ASCII TetraVex
TetraVex is a tile-based edge-matching game that was originally coded by Scott Ferguson for the Microsoft Entertainment Pack 3 back in 1990. The game consists of a grid upon which square tiles are placed. The tiles have numbers or letters on each edge, and the goal is to place all tiles in the grid, with each pair of edges matching, in the fastest time. Since solving TetraVex is known to be NP-Complete, we're instead just going to generate a solved board.

For our purposes, each TetraVex tile is 5 characters wide by 3 tall, and follows the pattern:

```
\ # /
# X #
/ # \

```

where each `#` is replaced with an alphanumeric symbol matching `[A-Z0-9]` (capitals, not lowercase).

When placed on the board, the tiles have additional spaces between them on the grid, in order to differentiate the tiles horizontally from each other. The grid is composed of `|`, `-`, and `+` symbols, as shown below. Note that there is no border on the outside of the gameplay area, and no trailing spaces to the right of the tiles.

```
\ # / | \ # /
# X # | # X #
/ # \ | / # \
------+------
\ # / | \ # /
# X # | # X #
/ # \ | / # \

```

### Input

* Two integers `1 < n,m <= 255` in any convenient format (tuple, array, function argument, etc.). The numbers can be taken in either order (please specify in your answer which order).
* These represent a board of `n` tiles wide by `m` tiles tall.
    + The smallest board output will thus be `2x2` tiles, or `13` characters wide by `7` characters tall.
    + The largest is `255x255` tiles, or `2037` characters wide by `1019` characters tall.

### Output

* An ASCII representation of a TetraVex board of size `n x m`.
* The board must follow the tile construction rules above, and must be a solved board (meaning the paired edges match). Non-paired edges (i.e., the border) can be any legal character.

### Rules

* Each individual tile in the output must be unique.
    + Reflected or rotated tiles count as distinct, since during actual gameplay you're not permitted to rotate or flip the tiles in any manner.
    + For example, a tile with 1 `A` on top and 3 `B`s on the other edges is considered distinct from a tile with 1 `A` on the right and 3 `B`s on the other edges.
* The output must be somewhat non-deterministic, meaning different runs of the code with the same `n` and `m` input should yield different boards. However, in the interests of complexity, not all possible `n x m` boards need have non-zero probability in your output -- only at least two of the possible boards must have non-zero probability of actually being produced.
    + For example, a `3 x 3` board, with full alphanumeric edges, already has somewhere around `36^24 ~= 2.25e37` possible boards. Since that number grows exponentially as the size increases, ensuring equal probability for all boards may become infeasible for many languages.
    + This does mean you could have two separate deterministic code paths produce two separate boards and then simply flip a coin to determine which to output -- that's fine. (For example, starting with the first tile all `A` in one path and all `B` in the other, and then generate the rest of the board using the same algorithm from there will guarantee two unique boards and is allowed)
    + Any of our usual definitions for randomness will suffice for determining this non-zero probability.
    + Rotations or reflections of the board *are* considered "different" boards, but note that you're not guaranteed a square grid, only a rectangular one. ;-)
    + Generating a board and then replacing a certain character with another (e.g., replacing all `A` with `Z`) *is* allowed, provided that each tile in the output is still unique.
* Trailing spaces are not allowed but trailing newline(s) are OK.
* Standard loopholes are forbidden.
* This is , so all usual golfing rules apply, and the shortest code wins.

### Examples

1) Input: `3 3`

```
\ A / | \ B / | \ C /
D X E | E X G | G X I
/ J \ | / K \ | / L \
------+-------+------
\ J / | \ K / | \ L /
M X N | N X O | O X P
/ Q \ | / R \ | / S \
------+-------+------
\ Q / | \ R / | \ S /
T X U | U X V | V X W
/ X \ | / Y \ | / Z \

```

2) Input: `5 3`

```
\ 0 / | \ B / | \ C / | \ A / | \ Z /
D X E | E X F | F X I | I X A | A X Q
/ J \ | / 9 \ | / L \ | / L \ | / 6 \
------+-------+-------+-------+------
\ J / | \ 9 / | \ L / | \ L / | \ 6 /
M X N | N X 4 | 4 X P | P X P | P X T
/ R \ | / R \ | / S \ | / B \ | / K \
------+-------+-------+-------+------
\ R / | \ R / | \ S / | \ B / | \ K /
T X Z | Z X V | V X W | W X J | J X G
/ X \ | / Y \ | / Z \ | / X \ | / A \

```

# Answer
> 3 votes
# CJam, 116

```
26mr:D;q~:B;){[7B),f#10222@#f*2G#)f%_2ew:+23f%\W<26f%]{D+26%'A+}f%~"\/"f*_:$@2/'Xf*[@]'|f*Sf*~_'{f>"-+"f=\@}%2>-3<N*

```

Try it online

Uses only letters.

**Explanation:**

The first observation is that any rectangular piece of a solved board is a solved board. Since the program needs to work up to 255×255, it is enough to solve it for that case and use a piece of that board with the requested dimensions.

I am using a fixed 255×255 board that I determined to be correct. I actually did 256×256 tiles first, choosing 2 numbers per tile (top and left), then copied the other numbers from adjacent tiles, discarding some edge numbers from the last row and last column.

Each tile is first given an associated number, and then I calculate the remainders of that number modulo two other numbers (I used 23 and 26) to get the 2 numbers chosen for that tile.

In order to avoid patterns which lead to duplication, I decided to make the associated numbers pseudo-random and unique. I used my favorite distinct not-very-random number generator, which is based on primitive roots: take a prime number slightly bigger than the desired range (65537) and a small prime number (7), then use the powers of the small number modulo the big number. After a few trials, I found that the combination of 7, 23 and 26 works well, giving 65025 (255²) unique tiles.

For the random factor, I am just applying a random cyclic permutation to the value of each number. Then the numbers (0-25) are converted to letters (A-Z).

Code explanation to follow.

# Answer
> 3 votes
# Ruby 196

This is an anonymous function that takes width and length as arguments and writes to stdout.

```
->m,n{r=rand(9)
t=""
128.times{|h|t<<"%02X"%((h+r)*17%256)}
(m*n*4-m).times{|k|i=k%m;j=k/m
s="\\ #{t[j/4]} / | #{t[i]} X #{t[i+1]} | / #{t[j/4+1]} \\ | ------+-"[j%4*8,8]
i==m-1&&s[5,3]=$/
$><<s}}

```

**Explanation**

Uniqueness of cells is guaranteed by having the contents of each cell correspond to its x,y coordinates, as below. As a result the pattern is always symmetrical about the NW-SE diagonal:

```
00,00 01,00 02,00 03,00 04,00 05,00 06,00 07,00 08,00 09,00 10,00 11,00...
00,01 01,01 02,01 03,01 04,01 05,01 06,01 07,01 08,01 09,01 10,00 11,01...
00,00 01,02 02,02 03,02 04,02 05,02 06,02 07,02 08,02 09,02 10,02 11,02...
.
etc

```

The x values appear on the left and right edges of the tile, and the y values on the top and bottom edges.

The astute will have noticed that we cannot simply write a 2-digit number across each tile, because the edges will not match. What is needed is a sequence of (at least) 255 digits where all combinations are unique. From this we can pick a pair of digits (e.g. 1 and 2) for the first tile , then follow naturally on to the next, where the last number of one tile becomes the first of the next (e.g. 2 and 3).

I use a sequence containing just the hexadecimal digits 0-9A-F because the hexadecimal number representation is more golfable than some other arbitrary base. Therefore I need a 256 digit sequence where every one of the possible 2-digit combinations appears exactly once. Such a sequence is known as a De Bruijn sequence.

I have discovered a very golfy way of generating De Bruijn sequences of subsequence length 2 with digits from even base numbers. We simply take all the numbers from `0` to `b*b/2-1`, multiply them by `b+1`,take the last 2 digits, and concatenate the results. Here is an illustration of the sequence used with a bit more explanation as to how it works for base `b=16`. Basically each line contains all combinations with two of the possible differences between digits, which together add up to 1 or 17 (mod 16). It is necessary to think in modular base 16 arithmetic, where for example `-1` = `+F`.

```
00112233445566778899AABBCCDDEEFF Difference between digits is +1 or +0
102132435465768798A9BACBDCEDFE0F Difference between digits is +2 or +F
2031425364758697A8B9CADBECFD0E1F Difference between digits is +3 or +E
30415263748596A7B8C9DAEBFC0D1E2F     .         .       .       .     .
405162738495A6B7C8D9EAFB0C1D2E3F     .         .       .       .     .
5061728394A5B6C7D8E9FA0B1C2D3E4F     .         .       .       .     .
60718293A4B5C6D7E8F90A1B2C3D4E5F Difference between digits is +7 or +A
708192A3B4C5D6E7F8091A2B3C4D5E6F Difference between digits is +8 or +9

```

Finally, to comply with the random requirement, the pattern can be shifted diagonally by a random number `0..8` so there are 9 possible boards that can be generated.

**ungolfed in test program**

```
f=->m,n{                               #width,height

r=rand(9)                              #pick a random number

t=""                                   #setup empty string and build a DeBruijn sequence
128.times{|h|t<<"%02X"%((h+r)*17%256)} #with all 2-digit combinations of 0-9A-F

(m*n*4-m).times{|k|                    #loop enough for rows*columns, 4 rows per tile, omitting last row.
i=k%m;j=k/m                            #i and j are the x and y coordinates
                                       #lookup the 4 values for the current tile and select the appropriate 8-character segment
                                       # from the 32-character string produced, according to the row of the tile we are on.
s="\\ #{t[j/4]} / | #{t[i]} X #{t[i+1]} | / #{t[j/4+1]} \\ | ------+-"[j%4*8,8]
i==m-1&&s[5,3]=$/                      #if i is on the rightmost row, delete the last 3 charaters of s and replace with \n
$><<s}}                                #print the current horizontal segment of the current tile.

f[20,20]

```

**Output for 20,20 where r=8**

```
\ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \ | / 8 \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 / | \ 8 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \ | / 9 \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 / | \ 9 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \ | / A \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A / | \ A /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \ | / B \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B / | \ B /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \ | / C \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C / | \ C /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \ | / D \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D / | \ D /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \ | / E \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E / | \ E /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \ | / F \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F / | \ F /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 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 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 / | \ 0 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \ | / 2 \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 / | \ 2 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \ | / 1 \
------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------+------
\ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 / | \ 1 /
8 X 8 | 8 X 9 | 9 X 9 | 9 X A | A X A | A X B | B X B | B X C | C X C | C X D | D X D | D X E | E X E | E X F | F X F | F X 1 | 1 X 0 | 0 X 2 | 2 X 1 | 1 X 3
/ 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \ | / 3 \

```

# Answer
> 2 votes
# APL (Dyalog Unicode), 112 bytes

```
⎕CY'dfns'
{⍉¯2↓2↓⍉¯1↓1↓(1,⍨3 7×⍳¨⍵)box⊃⍪/,/⍵↑∘.{(7⍴0 1)\3 3⍴⍺@2 8⊢⍵@4 6,⍨'\//\X'}⍨2,/⎕A[(?5)+16|+\17|⊢∘-\32/⍳8]}

```

Try it online!

An inline function that takes a single argument, a length-2 vector `n m`.

The essential idea is taken from Level River St's Ruby solution, i.e. build a De Bruijn sequence of order 2 on a size-16 alphabet.

The rest of the algorithm is just extracting alphabets (with random offset to the alphabet index), arranging into boxes, taking the top left corner of size of the input, and formatting to match the output format.

A bit of work is offloaded to the `dfns.box` library function, which inserts horizontal and vertical dividers at given indexes using either box-drawing Unicode chars or ASCII.

### How it works

```
⍝ Load library to use the function `box`
⎕CY'dfns'

f←{
  ⍝ Generate the De Bruijn sequence using the observation by Level River St
  idxs←16|+\17|⊢∘-\32/⍳8
                   32/⍳8  ⍝ 1..8, each number copied 32 times
               ⊢∘-\       ⍝ Negate the even indexes (1-based)
            17|           ⍝ Modulo 17; gives 1 16 1 16 ... 2 15 2 15 ... 8 9 8 9
       16|+\              ⍝ Cumul.sum mod 16

  ⍝ Generate tile fragments in one dimension
  axis←2,/⎕A[idxs+?5]
             idxs+?5   ⍝ Add one of 1..5 (random) to all of idxs
          ⎕A[       ]  ⍝ Index into the vector of uppercase letters
       2,/             ⍝ Join adjacent pairs

  ⍝ Generate the matrix of tiles
  mat←⍵↑∘.{(7⍴0 1)\3 3⍴⍺@2 8⊢⍵@4 6,⍨'\//\X'}⍨axis
        ∘.{                                }⍨axis  ⍝ Self outer product over axis
                                  ,⍨'\//\X'  ⍝ '\//\X\//\X'
                   3 3⍴             ⍝ Reshape to 3×3 so the ^ chars form X-frame
                       ⍺@2 8⊢⍵@4 6  ⍝ Place chars of ⍺ vertically, ⍵ horizontally
           (7⍴0 1)\                 ⍝ Insert blanks between columns and outside
      ⍵↑  ⍝ Take n rows and m columns of the entire matrix

  ⍝ Output formatting
  ⍉¯2↓2↓⍉¯1↓1↓(1,⍨3 7×⍳¨⍵)box⊃⍪/,/mat
                             ⊃⍪/,/mat  ⍝ Flatten chars to single matrix
              (          )box  ⍝ Apply box drawing with the options of
                  3 7×⍳¨⍵      ⍝   inserting lines after every 3rd row and 7th col
               1,⍨             ⍝   using ASCII
  ⍉¯2↓2↓⍉¯1↓1↓  ⍝ Fix formatting: drop 1 rows and 2 columns from the outside
}

```

# Answer
> 1 votes
# PowerShell 6, ~~244~~ 254 bytes

De Bruijn sequence is a good idea. Thanks to Level River St

```
param($w,$h)for(;$z='A'..'Z'|?{"Z$x"-notmatch-join"$x$_"[-2..-1]}){$x+=''+$z[0]}$v=random 9
1..$h|%{$y=$_+$v
,(($r=1..$w)|%{"\ $($x[$y+$_-1]) /"})+,($r|%{$x[$_-1]+' X '+$x[$_]})+,($r|%{"/ $($x[$y+$_]) \"})|%{$_-join' | '}
,'-----'*$w*($_-ne$h)-join'-+-'}

```

Try it online!

1. I've adapted my answer from the topic Generate the shortest De Bruijn for the case `{String:'A'..'Z', n:2}`.
2. The script loop by this sequence twice: each tail take two chars by row and by column
3. The shortest De Bruijn sequence contains 676 chars. That's enough for 255 rows and for 255 columns
4. The script add `random 9` to row numbers to comply with the random requirement
5. The last line fixed. Output contains extra trailing newline

No-duplicate test generates `####` strings instead ASCII tails and is looking for duplicates.

---
Tags: code-golf, ascii-art, game, grid, random
---


# Question
Title: Where will the gem-picking robot end up?
Related puzzle: Pathfinder (available on Puzzle Picnic)

## Background

A robot is standing on a cell of a rectangular grid, where each cell has one or more gems except for the one with the robot. The robot can move to a horizontally or vertically adjacent cell in one step, and it picks up one gem from the cell it steps on.

The robot is programmed with which cell to choose for its next step, based on the number of gems each adjacent cell contains. The program is in the form of `a > b > c > ... > z`, which means that the robot prefers to move into the cell with `a` gems, followed by one with `b` gems, and so on. Any such program contains positive integers from 1 to `n` exactly once, where `n` is the length of the program. The robot will never move into any cell with no gems.

If there are multiple highest-priority cells around the robot, or all the cells around it are empty, it will get stuck at that point.

For example, if its program is `1 > 3 > 2` (meaning, it prefers the cell with only one gem the most, followed by the one with 3 gems, and then 2 gems) and the current state looks like this (R is the robot, the numbers are gems):

```
0 3 2
2 R 1
1 2 3

```

Then it will choose the cell on its right because 1 has the highest priority. Assuming the cell with R is empty, it will continue moving down, left, left, right, right, then get stuck since the cells around it have no gems left.

```
0 3 2     0 3 2     0 3 2     0 3 2     0 3 2     0 3 2     0 3 2
2 R 1 --> 2 0 R --> 2 0 0 --> 2 0 0 --> 2 0 0 --> 2 0 0 --> 2 0 0
1 2 3     1 2 3     1 2 R     1 R 2     R 1 2     0 R 2     0 0 R
       R         D         L         L         R         R

```

Using the `1 > 3 > 2` program, it will get stuck at any of the following cases:

```
0 R 0  # all adjacent cells are empty
2 0 1
1 2 2

3 1 0  # there are two 1s around the robot, so it can't decide where to go
2 R 1
1 0 2

```

## Challenge

Given the initial state of the entire grid and the robot's program, find the position (horizontal and vertical coordinates) in the grid where the robot will eventually get stuck.

The initial state contains the numbers between 1 and 9 inclusive, except for a single 0 which denotes the initial position of the robot. The program is guaranteed to contain all positive numbers that appear in the grid, and the program is always valid (contains each of 1 to the maximum value on the grid exactly once).

You can take the input (grid and program) in any suitable format, and output the coordinates in any sensible way.

Standard rules apply. The shortest code in bytes wins.

## Test cases

In the example I/O provided, the program has the highest precedence coming first, and the coordinates are 1-based.

```
Grid:
0 2 1
3 3 2
1 1 3
Program: 3 1 2
Result: 2nd row, 3rd column (Path: DRDRUUD)

Grid: (one row)
0 3 2 3 1 4 4
Program: 4 2 3 1
Result: 1st row, 7th column (Path: RRLRRRRRLRLRLR)

Grid:
0 1 3
3 1 3
2 1 2
Program: 3 1 2
Result: 3rd row, 3rd column (Path: DRRULRDD)

Grid:
2 3 1 2 1
2 0 3 2 2
1 1 3 1 1
Program: 1 3 2
Result: 2nd row, 4th column (Path: DLUUDURRDDRRUULD)

Same grid as above, Program: 3 2 1
Result: 2nd row, 2nd column (Stuck at zero moves)

```

# Answer
# Python 2, ~~205~~ 198 bytes

```
def s(g,w,r):
 p=g.index(0)
 while 1:
    a=[((r+[0]).index(v),n)for n,v in enumerate(g)if(abs(n-p)in[1,w])>(p-n)%w*(p/w!=n/w)];m,n=min(a)
    if~-sum(k[0]==m<len(r)for k in a):return p/w,p%w
    p=n;g[p]-=1

```

*-6 bytes thanks to @ovs*

*-1 byte thanks to @user202729*

Try it online!

Take the input grid as a flattened list with width also passed. Outputs 0-indexed (x,y) coordinates of the final position (I doubt index in the flattened list would be acceptable).

### Explanation:

```
# Function of flattened grid g, width w, pRiorities r
def s(g,w,r):
    # starting position p
    p = g.index(0)
    while 1:
        a = [
            # pair (priority rank of the cell, cell id)
            # priority rank is n for v=0
            ((r+[0]).index(v),n)
            # for each adjacent cell id n with v gems
            for n,v in enumerate(g) if abs(n-p) in [1,w] and (p%w==n%w or p/w==n/w)
        ];
        # min comparison is done by tuple, so it selects one with minimum priority rank
        # m = min priority rank; n = corresponding cell id
        m,n = min(a)
        if sum( # how many adjacent cells
            k[0]==m # have priority rank equal to m
            <len(r) # and the cell value is not 0
            for k in a
        ) ^ 1: # If this count is not 1, then the robot is stuck; return
            return(p/w, p%w)
        # Otherwise, continue with updated position,
        p = n;
        # and take one gem
        g[p] -= 1

```
> 4 votes

# Answer
# Charcoal, 70 bytes

```
≔⪪Ｓ¹θＷＳ⊞υι≔⪫υ¶ηＰη…η⌕η0≔ＥＫＶ⌕θιυＷ⁼¹№υ⌈υ«Ｍ✳⁻χ⊗⌕υ⌈υＰＩ⊖ＫＫ≔ＥＫＶ⌕θκυ»≔⟦ⅈⅉ⟧υ⎚Ｉυ

```

Try it online! Link is to verbose version of code. Takes input as the program in ascending order of priority and then the newline-terminated grid and outputs 0-indexed coordinates. Explanation:

```
≔⪪Ｓ¹θ

```

Input the program as separate characters.

```
ＷＳ⊞υι≔⪫υ¶η

```

Input the grid.

```
Ｐη…η⌕η0

```

Print the grid without moving the cursor, then print the part up to the `0` so that the cursor is now at the starting cell.

```
≔ＥＫＶ⌕θιυ

```

Get the priorities of the neighbours of the starting cell (or `-1` for directions that lie outside the grid).

```
Ｗ⁼¹№υ⌈υ«

```

Repeat while there is exactly one neighbouring cell of highest priority.

```
Ｍ✳⁻χ⊗⌕υ⌈υ

```

Move to that neighbour.

```
ＰＩ⊖ＫＫ

```

Decrement its value.

```
≔ＥＫＶ⌕θκυ

```

Get the priorities of the neighbours of the new cell (or `-1` for illegal directions).

```
»≔⟦ⅈⅉ⟧υ

```

Capture the final position.

```
⎚Ｉυ

```

Clear the grid and output the position.
> 3 votes

# Answer
# JavaScript (ES7),  ~~142~~  130 bytes

Expects `(program)(matrix)`, with highest precedence coming first for the program. Returns `[column, row]`, both 0-indexed.

```
p=>m=>(g=(a,X,Y)=>a.some(k=>m.map((r,y)=>r.map((v,x)=>(X-x)**2+(Y-y)**2-1|v^k||(H=x,V=y,n--)),n=1)|!n)?g(p,H,V,m[V][H]--):[X,Y])``

```

Try it online!

### Commented

```
p => m => (             // p[] = program, m[] = matrix
g = (                   // g is a recursive function taking:
  a,                    //   a[] = list of possible neighbor values,
                        //         from most to least preferred
  X, Y                  //   (X, Y) = current position
) =>                    //
  a.some(k =>           // for each value k in a[]:
    m.map((r, y) =>     //   for each row r[] at position y in m[]:
      r.map((v, x) =>   //     for each value v in r[]:
        (X - x) ** 2 +  //       compute the squared distance
        (Y - y) ** 2    //       between (X, Y) and (x, y)
        - 1 |           //       abort if it's not equal to 1
        v ^ k ||        //       or v is not equal to k
        (               //       otherwise:
          H = x, V = y, //         save (x, y) in (H, V)
          n--           //         decrement n
        )               //
      ),                //     end of inner map()
      n = 1             //     start with n = 1
    )                   //   end of outer map()
    | !n                //   yield a truthy value if n = 0
  ) ?                   // end of some(); if truthy:
    g(                  //   do a recursive call to g:
      p,                //     using a[] = p[]
      H, V,             //     using (X, Y) = (H, V)
      m[V][H]--         //     decrement the cell at (H, V)
    )                   //   end of recursive call
  :                     // else:
    [ X, Y ]            //   we're stuck: return (X, Y)
)``                     // initial call to g with a[] = ['']

```

Because `g` is first called with `a = ['']` and both `X` and `Y` undefined, the test on the squared distance is disabled (because it's always NaN'ish) and `v ^ k` is equal to `0` only if `v == 0`. So the first recursive call is triggered on the `0` cell as expected.
> 3 votes

# Answer
# , 109 bytes

Takes in the program on the left, the grid on the right, and returns the 1-based end position.

```
($-_2&u)@((](r@|.~d{.@/:])`[@.(]2=/@{./:~)[i.(d=:(,-)=i.2){::])^:_)0(]|.~u=:$@]#:(i.~,))_1(r=:-1$!.0~$)@,._,]

```

Try it online!

### How it works

Because I didn't want to handle 3 arguments (program + grid + current position) as this is awkward in tacit J definitions, this approach shifts the grid around with the upper left tile having the robot. A fix point `_2` to reconstruct the end position is in the padding.

```
 _1(r=:…)@,._,]

```

Pad with `_` on the top, and `_1` on the left.

```
 r=:-1$!.0~$

```

This subtracts one from the top left tile. That makes the `_1` to a `_2`, and as we'll use this later again, assign this function to `r`.

```
 0(]|.~u=:$@]#:(i.~,))

```

This is a bit longer than needed, but in this version we can assign `x u y` to find the position of `x` in the grid `y`. Here we use it to shift the grid so the `0` is at the top left – later we'll use it to search for the `_2`.

```
 (…)^:_

```

Until the output of  does not change, i.e. until the robots moves:

```
 (d=:(,-)=i.2)

```

The 4 directions, saved as `d`.

```
 (d=:…){::]

```

Get the numbers at the directions, e.g. `0 0 3 1`.

```
 [i.

```

Find their position in the program with non-found numbers like `0 _ _1` having program length + 1, e.g. with `1 2 3`: `3 3 2 0`.

```
 ](…)`[@.(]2=/@{./:~)

```

If the first 2 items of the sorted indices `0 2 3 3 -> 0 2` are equal, return the grid (stop moving), otherwise …

```
 r@|.~d{.@/:]

```

Sort the directions based on the indices. Take the first one, shift the grid by it and call `r` to subtract 1 from the top left, i.e. the robots takes a gem.

```
 ($-_2&u)@

```

After the robot stopped moving, find the `_2` and subtract its position from the grid size to get the final result.
> 1 votes

# Answer
# C (gcc), <sup>~~289~~ \\$\cdots\\$ ~~246~~</sup> 243 bytes

Saved a whopping ~~37~~ ~~41~~ ~~43~~ 46 bytes thanks to ceilingcat!!!

```
q;c;v;s;d;i;b;u;r;f(g,e,w,p,n)int*g,*p;{r=wcslen(g);for(c=d=0;c-n&&!d;!d&c<n&&--g[r=s])for(c=n,b=4;b--;d=v?q<c?c=q,s=u,0:q>c?d:1:d)for(i=~-(b&2)*(b&1?1:w),v=g[u=r+i]*(u>=0&u<e)*(r%w|~i&&r%w-w+1|i-1),q=0,i=n;i--;)q+=v-p[i]?0:i;*g=r/w;g[1]=r%w;}

```

Try it online!

Inputs the grid as a flat array, the length of that array, the grid width, the program as an array of integers and the length of the program.
Returns the robot's final position (as zero-based row and column) by storing them in the first two positions of the grid.

**Before golfing**

```
new_rank;current_rank;new_value;current_pos;has_doubled;i;news_bits;new_pos;robot_pos;
f(grid,grid_end,grid_width,prog,prog_end)int*grid,*prog;{
    for(robot_pos=0;grid[robot_pos];++robot_pos);
    for(current_rank=has_doubled=0; current_rank!=prog_end && has_doubled == 0;) {
        for(current_rank=prog_end,news_bits=0; news_bits<4; ++news_bits) {
            i = (news_bits&2 - 1)*(news_bits&1?1:grid_width);
            new_pos = robot_pos + i;
            new_value = new_pos >= 0 && new_pos < grid_end?grid[new_pos]:0;
            if((robot_pos%grid_width == 0 && i == -1) ||
               (robot_pos%grid_width == grid_width-1 && i == 1))
                new_value = 0;
            for(i = 0; i < prog_end; ++i)
                if(new_value == prog[i])
                    new_rank = i;
            if(new_value > 0 && new_rank == current_rank) {
                has_doubled = 1;
            }
            if(new_value > 0 && new_rank < current_rank) {
                current_rank = new_rank;
                current_pos = new_pos;
                has_doubled = 0;
            }
        }
        if (has_doubled == 0 && current_rank < prog_end) {
            robot_pos = current_pos;
            --grid[robot_pos];
        }
    }
    grid[0]=robot_pos/grid_width;
    grid[1]=robot_pos%grid_width;
}

```
> 1 votes

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


title: Slowing Down Sped Up Videos

text:
# Question
Title: Slowing Down Sped Up Videos
# Summary

Videos which are sped up every time a particular word is said exist for everything from the Bee Movie to the classic Rick Roll. The goal for this challenge is to figure out how much you'd have to slow down the sped-up video in order to match the duration of the original video.

For example, the original Bee Movie has a duration of 95 minutes. The sped up version is 5:40 or ~5.667 minutes. 95/5.667 = 16.76. We'd have to play the sped up version 16.76x slower in order for the overall duration to match the original movie.

# Inputs

Your program must take in 3 inputs:

1. The duration of the original video (Bee Movie was 95 minutes)
2. The speedup factor per occurence (Bee Movie was 15% or .15)
3. A list of timestamps of occurrences (Bee movie has more than I care to look up/list)

The exact way these are passed in is flexible: 3 separate parameters is my default assumption, but if you want to take in a single list of values and pop the duration/speedup factor off the front that's fine, or take a single string in JSON or whatever format floats your boat, etc.

For the duration: seconds, minutes, or some builtin duration type are all fine.

For the speedup factor of the bee movie, any of 15, .15, or 1.15 could be used to represent the 15% speedup.

You can assume the occurrences are ordered in the most convenient manner, but there *can* be duplicate values (such as multiple characters talking over one another in a movie).

# Output

A scaling factor to make the durations of the original and sped-up video match. The exact format is flexible.

# Examples

```
{"duration": 10, "speedup-factor": 2, "occurrences": [1,2,3,4,5,6,7,8,9]} -> {"slowdown-factor": 5.004887585532747}
{"duration": 500, "speedup-factor": 1.15, "occurrences": [1,2,3, ..., 497, 498, 499]} -> {"slowdown-factor": 65.21739130434779}
{"duration": 100, "speedup-factor": 3, "occurrences": [0]} -> {"slowdown-factor": 3}
{"duration": 100, "speedup-factor": 3, "occurrences": [0, 0, 0]} -> {"slowdown-factor": 27}
{"duration": 100, "speedup-factor": 100, "occurrences": [99.99]} -> {"slowdown-factor": 1.0000990098}

```

<sub>Notes: First two generated programmatically with `100/(sum(1/(2**i) for i in range(10)))` and `500/(sum(1/(1.15**i) for i in range(500)))`. 4th example: 3 * 3 * 3 = 27x speedup, occurring right at the start of the video. Last example calculated by hand with `100/(99.99 + .01/100)`</sub>

# Note

I've kept most of the examples fairly simple, but I believe they cover all the relevant edge cases (a program which solves all of them should be totally correct). If I've left things ambiguous or difficult to parse, let me know and I'll add comments!

# Answer
# Python 2, 47 bytes

```
lambda m,r,l:m/reduce(lambda u,x:u/r+x-x/r,l,m)

```

Try it online!

Takes timestamps sorted in descending order.

The idea is to compute the video duration as a polynomial in the inverse speedup rate `1/r` using Horner's method with coefficients given by the sorted timestamps. This avoids needing to explicitly take the differences of consecutive timestamps. We then divide the duration of the original video by the resulting duration to get the desired slowdown factor.

**53 bytes**

```
f=lambda m,r,l:l==[]or r/(l.pop()*(r-1)/m+1/f(m,r,l))

```

Try it online!

An attempt to write the function fully recursively. While the new duration itself has a clean recursive expression, we want to get the slowdown factor which divides the original duration by the new duration, and this is messier to express recursively.
> 14 votes

# Answer
# Jelly, 10 bytes

```
;ŻIṚḅ⁵İ¤÷@

```

A full program accepting `timestamps original-duration speedup-factor` which prints the necessary slowdown-factor.

**Try it online!**

### How?

Get a list of the durations of film separated by the occurrences (including any zero-length segments), reverse and convert from base slowdown-factor (where this slowdown-factor is the inverse of the given `speedup-factor`), then divide the `original-duration` by that.

```
;ŻIṚḅ⁵İ¤÷@ - Main link: timestamps S, original-duration T
;          - concatenate (T) to (S) -> S+[T]
 Ż         - prefix with a zero (the start of the film) -> [0]+S+[T]
  I        - deltas -> [S[1]-0, S[2]-S[1], ..., S[n]-S[n-1], T-S[n]]
   Ṛ       - reverse -> [T-S[n], S[n]-S[n-1], ..., S[2]-S[1], S[1]-0]
       ¤   - nilad followed by link(s) as a nilad:
     ⁵     -   3rd argument = speedup-factor
      İ    -   inverse -> 1/speedup-factor - call this F
    ḅ      - convert from base -> (T-S[n])×F^(n)+(S[n]-S[n-1])×F^(n-1)+...+(S[2]-S[1])×F^1+(S[1]-0)×F^0
         @ - using swapped arguments (with implicit right argument T):
        ÷  -   division -> T/((T-S[n])×F^(n)+(S[n]-S[n-1])×F^(n-1)+...+(S[2]-S[1])×F^1+(S[1]-0)×F^0)
           - implicit print

```
> 5 votes

# Answer
# Haskell, 32 bytes

```
m%r=(m/).foldr(\x u->u/r+x-x/r)m

```

Try it online!

Port of my Python answer.
> 4 votes

# Answer
# APL (Dyalog Unicode) 18.0, 15 bytes

```
÷⊥⍥÷∘(⊃÷2-/,∘0)

```

Try it online!

# , 16 bytes

```
#.&.:%{.%2-/\,&0

```

Try it online!

Inline tacit functions that take the speedup on the left, and `duration,occurrences` on the right in descending order.

Both code use the same algorithm:

```
÷⊥⍥÷∘(⊃÷2-/,∘0)
    ∘(        )  On the right argument,
           ,∘0   Append zero
        2-/      Take pairwise differences
      ⊃÷         Divide each number above by the head
                 (division by zero is handled by system setting ⎕DIV←1,
                 which gives 0.)
 ⊥⍥÷             Take reciprocal of both args and do base conversion
÷                Take reciprocal of that

#.&.:%{.%2-/\,&0
\----/\--------/  2-train, so apply the right part on the right arg
             ,&0  Append zero
         2-/\     Take pairwise differences
      {.%         Divide each number above by the head
                  (division by zero gives built-in infinity,
                  whose reciprocal is again zero.)
  &.:%            Apply % (reciprocal) to both args
#.                Base conversion
  &.:%            Undo %, which is the same as applying % again

```
> 3 votes

# Answer
# , 20 bytes

Takes the speedup on the left, and the occurrences, length on the right. Calculates the speedup factor.

```
{:@]%%@[#.2-/\0|.@,]

```

Try it online!

### How it works

```
 {:@]%%@[#.2-/\0|.@,] 2 f 50 100
               0   ,] prepend 0:   0 50 100
                |.@   reverse:     100 50 0
           2-/\       differences: 50 50
      %@[             1/n:         0.5
         #.           to base:     75
 {:@]                 last element:100
     %                100/75:      1.3333

```
> 2 votes

# Answer
# 05AB1E, ~~15~~ 11 bytes

*-4 bytes thanks to @KevinCruijssen's port of @JonathanAllan's Jelly answer*

```
ª0š¥RIzβ¹s/

```

Try it online!
> 1 votes

# Answer
# , 49 bytes

```
function(d,f,o)d/diff(c(0,o,d))%*%f^-c(0,seq(!o))

```

Try it online!

Takes the original `d`uration, the speedup `f`actor, and the `o`currences.

Calculates the time between each occurrence `diff(c(0,o,d))`, then multiplies them with the appropriate speedup factors `f^-c(0,seq(!o))` and sums them as a dot product `%*%`. Finally divides `d` by that result.
> 1 votes

# Answer
# Wolfram Language (Mathematica), ~~35~~ 33 bytes

```
s#/Fold[#/s+#2&,{##}-{##2,0}]&

```

Try it online!

Takes input as `f[s][d,o]`, where `o` is a sequence of arguments in decreasing order.
> 1 votes

# Answer
# Pyth, 14 bytes

```
chQu+c-GHeQHEh

```

Try it online!

Port of @xnor's answer to Pyth

## Explanation

```
chQu+c-GHeQHEh
 hQ             : First element from first input
c               : divided by
   u            : value got by reducing from left to right
            E   : the second input
             h  : with default value as first input
                : on lambda G, H:
      -GH       :    G - H
     c   eQ     :    divided by second element from first input
    +      H    :    plus H

```
> 1 votes

# Answer
# Io, 49 bytes

Port of xnor's Python answer.

```
method(m,r,l,m/l prepend(m)reduce(u,x,u/r+x-x/r))

```

Try it online!
> 1 votes

# Answer
# 05AB1E, 18 bytes

```
¤UćV0š¥εyYNm/}OXs/

```

Explaination:

```
¤UćV0š¥εyYNm/}OXs/
¤U                       Extract tail and save duration in X
  ćV                     Extract head and save speedup factor in Y
    0š                   Prepand 0 to the timestamps list
      ¥                  Deltas
       ε     }           map
        y                foreach element
         YNm             factor ** index of element
            /            element / (factor ** index of element) => this will be the duration of this section
              O          sum all up
               Xs        push duration before the result
                 /       division

```

### Input:

A list of numbers in the format: `[speedup_factor, ... timestamps_in_minutes ... , duration_in_minutes]`

### Output:

How much we need to slow down in minutes.

Try it online!
> 0 votes

# Answer
# C (gcc), ~~74~~ 69 bytes

Saved 5 bytes thanks to ceilingcat!!!

```
float f(d,s,o,n,a)float*o,s,a;{for(a=d;n--;)a=a/s+o[n]-o[n]/s;s=d/a;}

```

Try it online!

Port of xnor's Python answer.
> 0 votes

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