# Question
Title: Program that creates larger versions of itself (quine-variant)
You are to write a program that will output source code that is

1. Larger than the original program (character wise)
2. Will print another program larger than itself when run (i.e. the new program is also a valid answer to this challenge) indefinitely

This is code-golf, so shortest answer wins.

# Answer
# GS2 (8636bd8e), 0 bytes

This prints a single newline, which prints two newlines, which prints three newlines, et cetera.

Try it online!
> 107 votes

# Answer
# H9+ : 1 char

```
9

```

That's right. One character. Outputs the lyrics to 99 bottles of beer, which is a valid program. All the extraneous data does not count, but there are plenty of `9`s in there.

The output of the outputted program is the lyrics to 99 bottles of beer 59 times.

This function gives the number of times the lyrics are outputted if you run the program `n` times (if my calculation is correct):

```
f(n) = 59<sup>n-1</sup>
```
> 326 votes

# Answer
# Java 7: 0 chars

Save as file `Blank.java`. If you save it as any other file, replace any instance of `Blank` with the appropriate file name.

Then, run in command line via first compiling, then running. If compiling fails, stop.

I list this as **Java 7** because it might output differently for different versions of Java.

First few outputs (outputted to stderr):

```
Error: Could not find or load main class Blank
```

```
Blank.java:1: error: class, interface, or enum expected
Error: Could not find or load main class Blank
^
Blank.java:1: error: reached end of file while parsing
Error: Could not find or load main class Blank
                                              ^
2 errors
```

```
Blank.java:1: error: class, interface, or enum expected
Blank.java:1: error: class, interface, or enum expected
^
Blank.java:1: error:  expected
Blank.java:1: error: class, interface, or enum expected
                          ^
Blank.java:1: error:  expected
Blank.java:1: error: class, interface, or enum expected
                                     ^
Blank.java:1: error: as of release 5, 'enum' is a keyword, and may not be used as an identifier
Blank.java:1: error: class, interface, or enum expected
                                          ^
  (use -source 1.4 or lower to use 'enum' as an identifier)
Blank.java:1: error: = expected
Blank.java:1: error: class, interface, or enum expected
                                               ^
Blank.java:2: error:  expected
Error: Could not find or load main class Blank
     ^
Blank.java:2: error: ';' expected
Error: Could not find or load main class Blank
      ^
Blank.java:2: error: = expected
Error: Could not find or load main class Blank
                      ^
Blank.java:2: error: = expected
Error: Could not find or load main class Blank
                                   ^
Blank.java:2: error:  expected
Error: Could not find or load main class Blank
                                              ^
Blank.java:3: error: = expected
^
^
Blank.java:3: error: ';' expected
^
 ^
Blank.java:4: error: illegal start of type
Blank.java:1: error: reached end of file while parsing
     ^
Blank.java:4: error: = expected
Blank.java:1: error: reached end of file while parsing
          ^
Blank.java:4: error: illegal start of type
Blank.java:1: error: reached end of file while parsing
           ^
Blank.java:4: error:  expected
Blank.java:1: error: reached end of file while parsing
            ^
Blank.java:4: error: = expected
Blank.java:1: error: reached end of file while parsing
          ^
Blank.java:4: error: illegal start of type
Blank.java:1: error: reached end of file while parsing
           ^
Blank.java:4: error:  expected
Blank.java:1: error: reached end of file while parsing
            ^
Blank.java:4: error: = expected
Blank.java:1: error: reached end of file while parsing
              ^
Blank.java:4: error: ';' expected
Blank.java:1: error: reached end of file while parsing
                   ^
Blank.java:4: error: = expected
Blank.java:1: error: reached end of file while parsing
                                 ^
Blank.java:4: error:  expected
Blank.java:1: error: reached end of file while parsing
                                        ^
Blank.java:4: error: = expected
Blank.java:1: error: reached end of file while parsing
                                         ^
Blank.java:4: error: ';' expected
Blank.java:1: error: reached end of file while parsing
                                              ^
Blank.java:5: error:  expected
Error: Could not find or load main class Blank
     ^
Blank.java:5: error: ';' expected
Error: Could not find or load main class Blank
      ^
Blank.java:5: error: = expected
Error: Could not find or load main class Blank
                      ^
Blank.java:5: error: = expected
Error: Could not find or load main class Blank
                                   ^
Blank.java:5: error:  expected
Error: Could not find or load main class Blank
                                              ^
Blank.java:6: error: = expected
                                              ^
                                              ^
Blank.java:6: error: ';' expected
                                              ^
                                               ^
Blank.java:7: error: reached end of file while parsing
2 errors
        ^
30 errors
```
> 127 votes

# Answer
# GolfScript, 9 chars

```
{.'.~'}.~

```

This code outputs:

```
{.'.~'}{.'.~'}.~

```

which outputs:

```
{.'.~'}{.'.~'}{.'.~'}.~

```

which outputs:

```
{.'.~'}{.'.~'}{.'.~'}{.'.~'}.~

```

and so on.

I believe this is the shortest answer in a "real" Turing-complete programming language so far.

### Explanation:

Basically, the original code above is a "quine-layer": it outputs a normal quine followed by itself.

In GolfScript, any code block literal (e.g. `{foo}`), if left undisturbed on the stack, is a quine. Thus, on its own, `{.'.~'}` simply outputs itself, just like any other code block would.

The `.~` at the end of the code takes the last code block on the stack, duplicates it, and executes the copy. When executed, the code `.'.~'` inside the code block duplicates the topmost item on the stack (i.e. the copy of itself) and appends the string `.~`.

At the end of the program, the GolfScript interpreter stringifies and outputs everything on the stack, which, in this case, consists of one more `{.'.~'}` block than in the input, plus the string `.~`.

### Bonus:

Adding a `]` before the first `.` (to collect all the code blocks on the stack into an array before they're duplicated) makes it grow exponentially:

```
{].'.~'}.~

```

outputs:

```
{].'.~'}{].'.~'}.~

```

which outputs:

```
{].'.~'}{].'.~'}{].'.~'}{].'.~'}.~

```

which outputs:

```
{].'.~'}{].'.~'}{].'.~'}{].'.~'}{].'.~'}{].'.~'}{].'.~'}{].'.~'}.~

```

and so on.
> 125 votes

# Answer
## HQ9+, HQ9++ and similars, 2 characters

```
QQ

```

This is the output:

```
QQQQ

```
> 84 votes

# Answer
# Ruby 27

A very slightly modified version of this (via):

```
puts <<3*3,3
puts <<3*3,3
3

```

The number of times that `puts`-line is printed grows exponentially.

```
$ ruby quine.rb | ruby | ruby
puts <<3*3,3
puts <<3*3,3
puts <<3*3,3
puts <<3*3,3
puts <<3*3,3
puts <<3*3,3
puts <<3*3,3
puts <<3*3,3
puts <<3*3,3
puts <<3*3,3
puts <<3*3,3
puts <<3*3,3
puts <<3*3,3
puts <<3*3,3
puts <<3*3,3
3

$ ruby quine.rb | ruby | ruby | ruby | ruby | ruby | ruby | ruby | wc -l
    3283

```
> 30 votes

# Answer
## Lambda Calculus - 29

A simple lambda term

```
(λu.(u u)(u u))(λu.(u u)(u u))

```

Reducing this term by one beta reduction yields

```
((λu.(u u)(u u))(λu.(u u)(u u)))((λu.(u u)(u u))(λu.(u u)(u u)))

```

And so on and so on. It's a simple variant on the classic `(λu.u u)(λu.u u)` which is a quine in lambda calculus, double self application here means we get twice the output.
> 30 votes

# Answer
# SH script, 9

```
cat $0 $0

```

Grows at exponential rate.

Either run as `sh whatever.sh` or set it as executable.

Windows version is here.
> 25 votes

# Answer
# dc 11

Quite simple:

```
6579792
dfP

```

The first line is repeated once every generation:

```
$ dc growing_quine.dc
6579792
6579792
dfP

$ dc growing_quine.dc | dc | dc
6579792
6579792
6579792
6579792
dfP

```

The last line consists of the following instructions: `d` duplicates the last value put on the stack (6579792) (so that we get one more copy each time we run it), `f` prints the whole stack (which is a bunch of that same number) and `P` prints the number (6579792) out as a byte stream, which displays as `dfP`.
> 20 votes

# Answer
# redcode (recursive solution)

This is the code of the easiest warrior writable in *redcode*, the famous Imp:

```
MOV 0, 1

```

When executed, the code writes a copy of its single instruction at the next address in memory; then executes it, etc.
> 19 votes

# Answer
# Python 3 - 55

```
print(open(__file__).read())
f=lambda:print('f()')
f()

```

This could be made shorter by replacing \__ file\__ with a single character filename and saving the file as that, but I felt this answer was more in the spirit of the question. After one iteration it outputs:

```
print(open(__file__).read())
f=lambda:print('f()')
f()
f()

```
> 15 votes

# Answer
# Smalltalk, 125 61 57

The golf version looks almost unreadable so I'll explain first (and use real identifiers).

This is a variant of the "weirdest-way-to-produce-a-stack-overflow" self modifying method.

The method prints out a hello message, and its current source (for the demonstration only). Then, the code is modified to output a longer string and installed. Finally, the new code is called recursively.

In order to protect myself from an immediate runaway, it lets the user confirm in each cycle.

compile in Object:

```
eatMe_alice
   |msg mySource|

   mySource := thisContext method source.

   '**** Hello Alice' printCR.
   '  ---- my current code is:' printCR.
   mySource printCR.
   '  ---------------' printCR.

   (UserConfirmation confirm:'Again? ') ifTrue:[
       Object compile:
            (mySource
                copyReplaceString:'Hello ','Alice'
                withString:'Hello ','Alice !').
       self eatMe_alice
   ]

```

start the show by sending "eatMe\_alice" to any Object; nil will do:

`nil eatMe_alice`

A nice variant is to not call the new code recursively, but instead iteratively, by unwindig the call stack and reentering into the new method. This has the advantage of not leading to a recursion exception. To do this, replace the recursive call ("self eatMe\_alice") by:

```
thisContext resend

```

Golfing:

Obviously, printing and self calling was not asked for, so the shortest (for golf) is to simply append a comment to my own source and return it. As a side effect, it also gets installed for the next call...

```
x|s|Object compile:(s:=thisContext method source,'""').^s

```
> 7 votes

# Answer
# Evoloop, 9×9 rectangle (81 cells)

The Evoloop cellular automaton included with Golly supports patterns which replicate themselves in a "quine-like" way. Specifically, these patterns each contain a "program"; a pattern reproduces itself by first executing the program (which creates the "body" of the daughter), and then by copying the program into the daughter.

The above applies to the more famous "Langton's Loops" cellular automaton as well as Evoloop, but Evoloop has an interesting difference, which is that it's easy to create a pattern which grows in each successive generation.

(Much *more* interesting, in my opinion, is the fact that Evoloop is a simple cellular automaton which contains patterns which reproduce themselves and evolve in a very life-like manner! I think the only known cellular automata which do this are Evoloop and its descendants. A shortcoming of Evoloop, however, is that there is one particular "best" genome; evolution always eventually converges to this one genome.)

Now, there are two shortcomings to this submission. One is that it's not clear what the "output" of a cellular automaton is. But I think that a self-reproducing automaton is "close enough" to being a quine; it's certainly no less interesting! The other shortcoming is that these patterns don't merely create a single copy of themselves; *each* copy of the original pattern attempts to create infinitely many copies of itself, and these copies end up interacting with each other in a destructive manner. So, I think I've met the requirements of this challenge in spirit, but not in letter.

Without further ado, the pattern is:

```
022222220
270170172
212222202
202000212
272000272
212000202
202222212
271041032
022222250

```

Here's the pattern again, in a format that can be copied and pasted into Golly:

```
x = 9, y = 9, rule = Evoloop
.7B$BG.AG.AGB$BA5B.B$B.B3.BAB$BGB3.BGB$BAB3.B.B$B.5BAB$BGA.DA.CB$.6BE
!

```

Okay, but what does it look like? It looks like this:

In the above animation, you can see the initial pattern create a larger daughter, which creates a larger granddaughter, then a larger great-granddaughter, and finally an even larger great-great-granddaughter which starts to construct a yet larger third-great-granddaughter. If you ran this pattern for a long time, it would keep going on like this forever (or perhaps they would eventually be overtaken by the evolved organisms, which are capable of reproducing much faster; I'm not sure).
> 7 votes

# Answer
# SH script, 12 8 7

Store a file with

```
sed p *

```

in its own, empty directory and run from this directory using `sh [file]` or set executable.

---

Old alternative with **8 characters**, but doesn't need its own directory. Store a file with

```
sed p $0

```

and run using `sh [file]` or set executable.

Old alternative with **12 characters**:

```
sed -i- p $0

```

This will actually output to the program file itself, but where to output was not specified. Replicates itself at an exponential rate.
> 5 votes

# Answer
# JavaScript, 41, 40 chars

```
function f(){console.log(f+"f(f())")}f()

```

The first time you run it it outputs itself with another `;f()` at the end. Subsequent runs of the output results in each "input" source printed twice.

`alert` would be shorter than `console.log` but I don't consider multiple alert dialogs to be "the" output while it seems reasonable to call multiple lines in the console as an output.
> 5 votes

# Answer
# Microscript II, 6 bytes

```
"qp"qp

```

The first iteration adds an extra `qp` to the end, and each successive iteration adds an extra copy of this original program to the beginning.
> 5 votes

# Answer
# Runic Enchantments, 6 bytes

```
"'<S@>

```

Try it online!

This one was weird. All I had to do was remove a `~` from the original quine found by Jo King.

Every additional run appends another `<` to the end, e.g.:

```
"'<S@><<<<<<<<<

```

All of which do nothing.
> 5 votes

# Answer
# Windows .BAT, 25

```
@COPY %~nx0+%~nx0 CON>NUL

```

Grows at exponential rate.

Equivalent SH version here.
> 4 votes

# Answer
**ECMAScript 6 (38 Characters)**

```
(f=_=>'(f='+f+')();(f='+f+')();')();

```

Which outputs:

```
(f=_=>'(f='+f+')();(f='+f+')();')();(f=_=>'(f='+f+')();(f='+f+')();')();

```

**Edit**

You could do (28 characters):

```
(f=_=>'(f='+f+')();'+f())();

```

However it will recurse infinitely and never return anything... but this can be solved by doing something like this (42 characters):

```
(f=_=>_?'(f='+f+')('+_+');'+f(_-1):'')(3);

```

Which will output:

```
(f=_=>_?'(f='+f+')('+_+');'+f(_-1):'')(3);(f=_=>_?'(f='+f+')('+_+');'+f(_-1):'')(2);(f=_=>_?'(f='+f+')('+_+');'+f(_-1):'')(1);

```
> 4 votes

# Answer
# Julia, 66 chars

```
x="print(\"x=\$(repr(x))\\n\$x;\"^2)";print("x=$(repr(x))\n$x;"^2)

```

Output (134 chars):

```
x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);

```

Result of executing the result (268 chars):

```
x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);

```

next result (536 chars):

```
x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);

```

Next result (1072 chars):

```
x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);x="print(\"x=\$(repr(x))\\n\$x;\"^2)"
print("x=$(repr(x))\n$x;"^2);

```

I hope this is according to the rules.

It produces larger output, and the output itself is valid source code that produces larger output again.
> 4 votes

# Answer
# Husk, ~~15~~ 11 bytes

*-4 bytes thanks to Unrelated String*

```
S+s"So+uswg

```

Try it online!

Outputs `So+uswg"So+uswg"` then `S o+uswg"S o + u s w g"` then `S o+uswg"S o + u s w g"`... This is a variant of the usual quine `S+s"S+s"` but with increasing spaces between each character in the string. Currently there's a bug in the parser that prevents double spaces in the code itself, otherwise this could forgo the `u`nique stripping out spaces in the code section and could be 9 bytes.
> 4 votes

# Answer
# Common Lisp, 16 Characters

`(print `(or ,-))`

Granted, it's interactive-only, but being able to reference the current top-level form is probably the single best way to minimize a non-trivial program that meets the specification.

What would be really interesting is what blows up the fastest. Maybe something like

`(print `(progn ,@(loop repeat (length -) collect -)))`
> 3 votes

# Answer
# reticular, 11 bytes, noncompeting

```
"'34'coo1o;

```

This is the standard quine framework, except an extra `1` is printed after each iteration. Try it online!

First few outputs:

```
"'34'coo1o;
"'34'coo1o;1
"'34'coo1o;11
"'34'coo1o;111

```
> 3 votes

# Answer
# 05AB1E, 15 bytes, noncompeting

```
0"DÐ34çý"DÐ34çý

```

Try it online!

Prints `0"DÐ34çý"DÐ34çý"DÐ34çý"DÐ34çý`,
which prints `0"DÐ34çý"DÐ34çý"DÐ34çý"DÐ34çý"DÐ34çý"DÐ34çý"DÐ34çý"DÐ34çý`,
etc.
> 3 votes

# Answer
# , 1 byte

```
'

```

Try it online!

The open quote gives, obviously, the open quote error:

```
|open quote
|   '
|   ^
|[-1] /home/runner/.code.tio

```

Note that, by the nature of J interpreter, **the errors are printed to STDOUT**, not STDERR.

When the above is run as code, it prints:

```
|open quote
|   |   '
|       ^
|[-2] /home/runner/.code.tio

```

Then

```
|open quote
|   |   |   '
|           ^
|[-2] /home/runner/.code.tio

```

and so on. Each time the code runs, the second line is left-padded with four bytes `|`, fulfilling the requirement of this challenge.

# , proper quine variant, 25 bytes

```
echo,~'echo,:~(,quote)'''

```

Try it online!

Outputs

```
echo,:~(,quote)'echo,:~(,quote)'

```

And then it outputs itself twice, on separate lines:

```
echo,:~(,quote)'echo,:~(,quote)'
echo,:~(,quote)'echo,:~(,quote)'

```

then

```
echo,:~(,quote)'echo,:~(,quote)'
echo,:~(,quote)'echo,:~(,quote)'
echo,:~(,quote)'echo,:~(,quote)'
echo,:~(,quote)'echo,:~(,quote)'

```

and so on.

The first output is a simple variant of standard J quine. The added `,:~` concatenates itself vertically, where the resulting 2D array is printed as two rows of the same string.
> 3 votes

# Answer
# Python 2, ~~38~~ ~~37~~ ~~36~~ 34 bytes

-1 bytes thanks to Jo King

```
s='print"s=%r;exec s;"%s+s';exec s

```

Try it online!

---

# Python 3.8 (pre-release), ~~39~~ ~~38~~ 36 bytes

```
exec(s:='print("exec(s:=%r);"%s+s)')

```

Try it online!
> 3 votes

# Answer
# EcmaScript 6 (51 bytes):

```
(_=x=>'(_='+_+Array(x++).join(','+_)+')('+x+')')(2)

```

It produces a longer version of itself, which can produce a longer version of itself, which can produce a longer version of itself, etc. ...
> 2 votes

# Answer
# Underload, 9 bytes

```
(:::aSSS):^

```

Modification on the standard underload quine, which is `(:aSS):aSS`. First, I changed the second `:aSS` into `:^` since it still runs the same code (by duplicating and then running the top item of the stack, which is the stuff inside the bracket) whilst saving bytes. Then I added another `S` to make it so the program gets longer, and added two more `:`s to make it so the program it produces doesn't error.

Try it Online!
> 2 votes

# Answer
# Japt, 12 bytes

```
"iQ ²Ä"iQ ²Ä

```

Try it online!

Based off the Standard Japt quine

## Explanation

For first iteration

```
"iQ ²Ä"       // Take this string.        iQ ²Ä
       iQ     // Insert a quote.          "iQ ²Ä
          ²   // Double.                  "iQ ²Ä"iQ ²Ä
           Ä  // Concatenate 1 to end     "iQ ²Ä"iQ ²Ä1
              // Implicitly output.

```

On Each iteration it will concatenate another `1` to the end of the program
> 2 votes

# Answer
# Jelly, 4 bytes

```
⁾ṘȮv

```

Try it online!

Originally written for a CMC in JHT.

```
⁾ṘȮ     "ṘȮ"
   v    evaluated with the argument
⁾ṘȮ     "ṘȮ".

 Ṙ      Print a Jelly string representation of the argument,
  Ȯ     print the argument,
        then implicitly print it again.

```
> 2 votes

# Answer
# Julia 1.0, 33 bytes

```
a=[show,print]
".|>$([a;a])
".|>a

```

Try it online!

prints (79 bytes):

```
".|>Function[show, print, show, print]\n".|>Function[show, print, show, print]

```

then, the program is doubled each time:

```
".|>Function[show, print, show, print]\n".|>Function[show, print, show, print]
".|>Function[show, print, show, print]\n".|>Function[show, print, show, print]

```

**based on this quine:**

```
".|>[show,print]".|>[show,print]

```

Try it online!
> 2 votes

# Answer
### PHP, 38

```
<?echo fgets(fopen(__FILE__,'r')).';';

```

It will add a semicolon at each run.
> 1 votes

# Answer
## BATCH, 26

Place this code in any .bat file and it will continue to execute (in an infinite loop) and the file will grow as well.

```
echo echo %0 ^>^> %0 >> %0

```
> 1 votes

# Answer
## Batch

```
set d=time
copy c:\>loop.bat /B loop%d%.bat
call c:\>loop.bat

```
> 1 votes

# Answer
**Javascript - 46**

```
(function $(){console.log('('+$+'());$()')}())

```
> 1 votes

# Answer
# PYG (6)

```
P(Q,Q)

```

Prints it's own source code, separated by newlines. The second generation would be

```
P(Q,Q)
P(Q,Q)

```

and so forth.
> 1 votes

# Answer
## OIL, 83 bytes

```
0
0
1
1
1
4
1
11
4
1
11
1
2
2
1
12
18
10
18
1
32
22
1
18
26
4
26
8
18
11
6
17
4
26

```

It first prints two lines with a zero in them, and then compares each line to line 1, if they're equal (which is the case when the file is exhausted), we print what's in cell 26. The resulting output will look the same, except with an added `33`, which doesn't do anything. Next time, another line will be added, and so on.
> 1 votes

# Answer
# Help, WarDoq!, 1 byte.

```
H
```

Prints `Hello, World!`.

Other characters than H are valid (and safe) source code (that print other variants of Hello World).
> 1 votes

# Answer
# Charcoal, non-competing, 32 bytes

```
Ａ´α´´´Ａ´Ｆ´α´⁺´´´´´ι´αaα´ＡＦα⁺´´ια

```

Try it online!

Explanation:

first, go check out this answer on the quine challenge and its explanation.

This program is that program, but with the letter a at the end of the string variable.

```
Ａ                      α            Assign to a
 ´α´´´Ａ´Ｆ´α´⁺´´´´´ι´αa             "α´ＡＦα⁺´´ιαa", but with ´ escape character with each
                                     character, except a
                                     these are the variable being assigned to, and the
                                     rest of the program that is not the string.

                         ´Ａ         Print Ａ to the grid. current grid: "Ａ"
                            Ｆα⁺´´ι  For each character in a, print ´ + character
                                     this results in the escaped version of the string
                                     which is the literal string that is assigned at the
                                     start, plus a escaped. current grid state: "Ａ´α´´´Ａ´Ｆ´α´⁺´´´´´ι´α´a"

                                   α Print a ("α´ＡＦα⁺´´ιαa"), which is the commands after
                                     the string assignment. final grid state vvv:
                                                  "Ａ´α´´´Ａ´Ｆ´α´⁺´´´´´ι´α´aα´ＡＦα⁺´´ιαa"

[implicitly print the grid: "Ａ´α´´´Ａ´Ｆ´α´⁺´´´´´ι´α´aα´ＡＦα⁺´´ιαa", the new program]

```

This new program works in the same way, except for two things:

* the "a" is escaped (which has no effect, as "a" escaped is "a")
* there is an "a" at the end of the program. this "a" will write an extra "a" after the source is produced. thus the program grows slowly
> 1 votes

# Answer
# C, ~~116~~ ~~149~~ ~~197~~ 189 bytes

```
i;main(a){printf(a="i;main(a){printf(a=%c%s%1$c,34,a,i+2);for(i=%d;i--;)",34,a,i+2);for(i=1;i--;)printf(a="printf(a=%c%s%1$c,34,a,34),",34,a);printf(a="0;printf(a=%c%s%1$c,34,a);}",34,a);}

```

### How it works

* `main(a){` declares the main function with an *untyped variable* `a`.
* The first `printf` prints the existing source code and a `for` loop. An integer is `printf`'d into the `for` loop. This is how the multi-quine works - each time the quine program is called, it increments `d`, making the `for` loop run more times.
* The second `printf` is inside the `for` loop and prints itself, so each time the quine program is called, there are more `printf`'s, therefore generating bigger versions of itself. Be warned that this growth is exponential, due to the `for` loop incrementation *and* the multiple `printf`s.
* The third `printf` prints the remaining source code.

Requires POSIX.
> 1 votes

# Answer
# Gol\>\<\>, 5 bytes

```
#H}"'

```

This, I believe, is the smallest growing quine possible in Gol\>\<\>. It duplicates the #H} over and over...

Try it online!
> 1 votes

# Answer
# AsciiDots, 20 bytes

```
($'#a_$93#"$_@("_$-.

```

Try it online!

---

### First run

Sends a dot leftward, printing the characters `(@_$` with a literal and `'` from the ASCII value 39. The dot then turns around and interprets the path as a string, printing the rest of the line.

`(@_$'#a_$93#"$_@("_$-.`

---

### Subsequent runs

Prints `(@_$'` again, as well as a `0`, thanks to the added `@_` from the first run. The `0` ends up on the right side of the `'` symbol, which means that all `0`s printed in a previous run carry over. The dot safely ignores the additional `0`s on its path.

`(@_$'0#a_$93#"$_@("_$-.`

`(@_$'00#a_$93#"$_@("_$-.`

`(@_$'000#a_$93#"$_@("_$-.`
> 1 votes

# Answer
# Bash, 14 bytes

```
cat $0&cat $0&

```

Try it online!
> 1 votes

# Answer
# Keg, ~~18~~ ~~15~~ ~~14~~ ~~13<sup>SBCS</sup>~~ ~~11~~ ~~10<sup>SBCS</sup>~~ ~~9<sup>SBCS</sup>~~ 6<sup>SBCS</sup> bytes

```
`④⑩`④⑩

```

Try it online!

I've gone and done it now! No more ascii around here now folks. This will print:

```
`④⑩`④⑩④⑩

```

Which will print:

```
`④⑩`④⑩`④⑩`④⑩④⑩

```

Which prints:

```
`④⑩`④⑩`④⑩`④⑩`④⑩`④⑩④⑩④⑩

```

And so on.

## Answer History

### 9 bytes

```
`::.,`⑵④⑩

```

This uses the same approach as the 10 byte answer

**Explained**

```
`::.,`⑵④⑩
`::.,`      #Push the string `::.,`
      ⑵     #Double the string
        ④⑩  #Print raw then nice without popping

```

### 10 bytes

```
`::.,`⑵:.,

```

This prints:

```
`::.,::.,`::.,::.,

```

Which prints:

```
`::.,::.,`::.,::.,`::.,::.,`::.,::.,

```

### 11 bytes

```
`::.,`6*:.,

```

This prints:

```
`::.,::.,::.,::.,::.,::.,`::.,::.,::.,::.,::.,::.,

```

Which prints:

```
`::.,::.,::.,::.,::.,::.,`::.,::.,::.,::.,::.,::.,`::.,::.,::.,::.,::.,::.,`::.,::.,::.,::.,::.,::.,`::.,::.,::.,::.,::.,::.,`::.,::.,::.,::.,::.,::.,`::.,::.,::.,::.,::.,::.,`::.,::.,::.,::.,::.,::.,`::.,::.,::.,::.,::.,::.,`::.,::.,::.,::.,::.,::.,`::.,::.,::.,::.,::.,::.,`::.,::.,::.,::.,::.,::.,

```

And so on

Try it online!

### 13 bytes

```
`::.,`!⑨*:(.,

```

Try it online!

This prints:

```
`::.,::.,`::.,::.,

```

Which prints:

```
`::.,::.,`::.,::.,`::.,::.,`::.,::.,

```

And so on.

### 14 bytes

```
`::.,(:.,)`:.,

```

Try it online!

This will create pretty much the same chain as the previous 15-byter.

### 15 bytes

```
`::.,(::.,)`:.,

```

This prints:

```
`::.,(::.,)`::.,(::.,)

```

Which prints:

```
`::.,(::.,)`::.,(::.,)`::.,(::.,)`::.,(::.,)

```

And so on.

Try it online!

### 18 bytes

```
`:::.,(!2/|.,)`:.,

```

Try it online!

This will print

```
`:::.,(!2/|.,)`:::.,(!2/|.,)

```

Which in turn prints:

```
`:::.,(!2/|.,)`:::.,(!2/|.,)`:::.,(!2/|.,)`:::.,(!2/|.,)

```

Which then prints:

```
`:::.,(!2/|.,)`:::.,(!2/|.,)`:::.,(!2/|.,)`:::.,(!2/|.,)`:::.,(!2/|.,)`:::.,(!2/|.,)`:::.,(!2/|.,)`:::.,(!2/|.,)

```

And so on.

Try it online!
> 1 votes

# Answer
# JavaScript (ES6/2015), 12 bytes

```
a=_=>'a=_'+a

```

Try it online!

## with invokation, 23 bytes

```
(a=_=>'(a=_'+a+')()')()

```

Try it online!

Every iteration adds an underscore to the parameter name
> 1 votes

# Answer
# Wolfram Language (Mathematica), 19 bytes

```
ToString[10#0][]&[]

```

Try it online!

Returns `10 (ToString[10 #0][] & )[]`, which, when run, returns `10*10 (ToString[2 #0][] & )[]`. From there, the beginning number is multiplied by 10 at every step, which increases the length of the code by 1.
> 1 votes

# Answer
# Batch, 1 byte

```
a

```

Add prompt at head every time, error is who cares
> 1 votes

# Answer
# \>\<\> (Fish), 14 bytes

```
'rd3*9[r:r]>o<

```

Try it

First iteration duplicates the `:` in the middle: (it actually duplicates itself):

```
'rd3*9[r::r]>o<

```

Then since there are now 2 duplication signs it will duplicate itself twice:

```
'rd3*9[r::::r]>o<

```

etc. doubling each time.

# \>\<\> (Fish), 9 bytes (Boring version)

```
':rd3*>o<

```

Try it

This simply duplicates the `<` at the end:

```
':rd3*>o<<
':rd3*>o<<<

```

etc. So the functionality of the program won't be effected at all. It's basically a comment.
> 1 votes

# Answer
# Pushy, 7 bytes

```
95&34_"

```

Non-competing as the language postdates the challenge. This outputs:

```
95 95 34
__"

```

which in turn outputs:

```
95 95 34
95 95 34
__"

```

and so on. After ~5 runs it looks like this:

```
95 95 34 95 95 34 95 95 34 95 95 34
95 95 34 95 95 34 95 95 34 95 95 34
__"__"__"__"
95 95 34 95 95 34 95 95 34 95 95 34
95 95 34 95 95 34 95 95 34 95 95 34
__"__"__"__"

```
> 0 votes

# Answer
# k

## 41 bytes

```
f:{{(2*#x)#x}"f:",x,";`0:f@$f;"};`0:f@$f;

```

This program prints a copy of itself, and then doubles it. Thus it grows.

## 33 bytes

```
`0:{,//$("`0:";o;"[";x;"1];")}[1]

```

This program prints itself, but with an ever-growing number as the argument. This works in the closed-source interpreter.
> 0 votes

# Answer
## Alice, 14 bytes

```
" <@o&h:2d+2..

```

Try it online!

Subsequent versions will have an increasing number of spaces after the `"`.

### Explanation

```
" <@o&h:2d+2.."   Push the code points of the source code, except for the
                  quotation marks.
<                 Send the IP back west.
"..2+d2:h&o@< "   Push the code points of the source code, except for the
                  quotation marks, in reverse.
..                Make two copies of the space. One will be the additional
                  space, one will be turned into the quotation mark.
2+                Add two, to turn 32 (space) into 34 (quote).
d                 Push the stack depth. This is about twice the number of characters
                  we want to print, because there's still the first copy of the source
                  on the stack. But it's two less than twice that number, because the
                  additional space and the quote aren't duplicated.
2:                Halve the value.
h                 Increment to account for the space and quote.
&                 Repeat the next command that many times.
o                 Print that many characters from the top of the stack.
@                 Terminate the program.

```
> 0 votes

# Answer
# shortC, 99 bytes

```
i;ARa="i;ARa=%c%s%c,34,a,34,i+2);Oi=%d;i--;)",34,a,34,i+2);Oi=2;i--;)Ra="Ra=%c%s%c,34,a,34",34,a,34

```
> 0 votes

# Answer
# Java 8, 92 bytes

```
v->{String s="v->{String s=%c%s%1$c+1;return s.format(s,34,s);}//";return s.format(s,34,s);}

```

Try it online.

Outputs (4 bytes larger):

```
v->{String s="v->{String s=%c%s%1$c+1;return s.format(s,34,s);}//"+1;return s.format(s,34,s);}//

```

Try first output program.

Which outputs (2 bytes larger):

```
v->{String s="v->{String s=%c%s%1$c+1;return s.format(s,34,s);}//1"+1;return s.format(s,34,s);}//1

```

Try second output program.

Which outputs (2 bytes larger):

```
v->{String s="v->{String s=%c%s%1$c+1;return s.format(s,34,s);}//11"+1;return s.format(s,34,s);}//11

```

Try third output program.

etc. (2 bytes larger every new program)

**Explanation:**

-part:

* The `String s` contains the unformatted source code.
* `%s` is used to input this String into itself with the `s.format(...)`.
* `%c`, `%1$c` and the `34` are used to format the double-quotes.
* `s.format(s,34,s)` puts it all together

Challenge part:

* Unformatted source code contains `+1` and `//` to make the output program larger and compilable.
* `+1` adds a 1 to both the unformatted and formatted program.
> 0 votes

# Answer
# Befunge-98 (FBBI), 38 bytes

```
::3a*3+-8jrfjj2,g0_0g,"+2",,1+:3d*`#@_

```

Try it online!
> 0 votes

# Answer
**Python 3, 54 chars**

`print((lambda s:s%s)('print((lambda s:s%%s)(%r)*2);'))`

I simply modified this quine. You can try it simply doing `python this.py | python | python ... | python` many times.

Edit: found this problem on the homepage and discovered too late that it is old.
> 0 votes

# Answer
# C (gcc), 132 bytes

It's not often you get to recycle answers from other questions.

```
x;*s="x;*s=%c%s%c;main(i){for(i=__LINE__;i--;puts(&x));printf(s,34,s,34);}";main(i){for(i=__LINE__;i--;puts(&x));printf(s,34,s,34);}

```

Try it online!
> 0 votes

# Answer
# Haskell, 155 bytes

```
g=putStrLn("n=1"++show n++('-'<$[1..n]));main=(\s->putStr s>>print s>>g)$"g=putStrLn(\"n=1\"++show n++('-'<$[1..n]));main=(\\s->putStr s>>print s>>g)$"
n=2

```

Try it online!
> 0 votes

# Answer
## , 15 bytes

A proper quine, except it grows very oddly.

```
pp34CS+"pp34CS+

```

Iterations (You can see that the output gets between and after the source code... ):

```
pp34CS+pp34CS+"pp34CS+
pp34CS+pp34CS+pp34CS+pp34CS+"pp34CS+pp34CS+

```
> 0 votes

# Answer
# Python 2, 31 bytes

```
s='s=%r;print s%%s*2;';exec s%s

```

Try it online!

the next iterations are:

```
s='s=%r;print s%%s*2;';print s%s*2;s='s=%r;print s%%s*2;';print s%s*2;
# ------------------------------------
s='s=%r;print s%%s*2;';print s%s*2;s='s=%r;print s%%s*2;';print s%s*2;
s='s=%r;print s%%s*2;';print s%s*2;s='s=%r;print s%%s*2;';print s%s*2;
# -------------------------------------
s='s=%r;print s%%s*2;';print s%s*2;s='s=%r;print s%%s*2;';print s%s*2;
s='s=%r;print s%%s*2;';print s%s*2;s='s=%r;print s%%s*2;';print s%s*2;
s='s=%r;print s%%s*2;';print s%s*2;s='s=%r;print s%%s*2;';print s%s*2;
s='s=%r;print s%%s*2;';print s%s*2;s='s=%r;print s%%s*2;';print s%s*2;
# ------------
...

```

# Python 3, 33 bytes

```
a='a=%r;print(a%%a*2);';exec(a%a)

```

Try it online!

```
a='a=%r;print(a%%a*2);';print(a%a*2);a='a=%r;print(a%%a*2);';print(a%a*2);
# ------------------------------------
a='a=%r;print(a%%a*2);';print(a%a*2);a='a=%r;print(a%%a*2);';print(a%a*2);
a='a=%r;print(a%%a*2);';print(a%a*2);a='a=%r;print(a%%a*2);';print(a%a*2);
# -------------------------------------
a='a=%r;print(a%%a*2);';print(a%a*2);a='a=%r;print(a%%a*2);';print(a%a*2);
a='a=%r;print(a%%a*2);';print(a%a*2);a='a=%r;print(a%%a*2);';print(a%a*2);
a='a=%r;print(a%%a*2);';print(a%a*2);a='a=%r;print(a%%a*2);';print(a%a*2);
a='a=%r;print(a%%a*2);';print(a%a*2);a='a=%r;print(a%%a*2);';print(a%a*2);
# ------------
...

```
> 0 votes

# Answer
# C (gcc), 71 bytes

```
#define a(b)*s=#b;b
a(main(){printf("#define a(b)*s=#b;b\na(%s;)",s);})

```

Every iteration adds a semicolon after the closing brace of the main function.

Try it online!
> 0 votes

# Answer
# Lua, 58 bytes

```
f="f=%qprint(f:format(f):rep(9))"print(f:format(f):rep(9))

```

Attempt This Online! Repeats the formatted string 9 times. This is the result of iteration 1:

```
f="f=%qprint(f:format(f):rep(9))"print(f:format(f):rep(9))f="f=%qprint(f:format(f):rep(9))"print(f:format(f):rep(9))f="f=%qprint(f:format(f):rep(9))"print(f:format(f):rep(9))f="f=%qprint(f:format(f):rep(9))"print(f:format(f):rep(9))f="f=%qprint(f:format(f):rep(9))"print(f:format(f):rep(9))f="f=%qprint(f:format(f):rep(9))"print(f:format(f):rep(9))f="f=%qprint(f:format(f):rep(9))"print(f:format(f):rep(9))f="f=%qprint(f:format(f):rep(9))"print(f:format(f):rep(9))f="f=%qprint(f:format(f):rep(9))"print(f:format(f):rep(9))

```
> 0 votes

# Answer
# DipDup, 12 bytes

```
[[_^!]:_:]_:

```

Try it online!

The TIO link is the DipDup interpreter written in Haskell.

Based on my DipDup quine: `[_:]_:`. `[_^!]:` converts a block `[abc]` to `[[abc]_^!]`, which is equivalent to `[abc]` but longer.

This outputs `[[_^!]:_:][_^!]:_:`. After that, `[abc]abc` becomes `[[abc]_^!][abc]_^!` in each step.
> 0 votes

# Answer
# Rust, 61 bytes

```
fn main(){print!("const _:()=();{}",include_str!("main.rs"))}

```

Is it cheating to use `include_str!`? :P In any case, it just keeps adding a dummy constant, growing the program larger every time.
> 0 votes

# Answer
# JavaScript, 33 bytes (27 if alert)

```
f=_=>console.log(`f=${f};f(f())`)

```

Try it:

```
console.log('First execution');

f=_=>console.log(`f=${f};f(f())`)

f();

console.log('After prev execution');

f=_=>console.log(`f=${f};f(f())`);f(f())

console.log('After prev execution');

f=_=>console.log(`f=${f};f(f())`);f(f())
f=_=>console.log(`f=${f};f(f())`);f(f())

console.log('After prev execution');

f=_=>console.log(`f=${f};f(f())`);f(f())
f=_=>console.log(`f=${f};f(f())`);f(f())
f=_=>console.log(`f=${f};f(f())`);f(f())
f=_=>console.log(`f=${f};f(f())`);f(f())

//...
```
> 0 votes

---
Tags: code-golf, quine, code-generation
---


title: Finding the most 'unique' word

text:
# Question
Title: Finding the most 'unique' word
Using you language of choice, write the shortest function/script/program you can that will identify the word with the highest number of *unique* letters in a text.

* Unique letters should include any distinct character using UTF-8 encoding.
    + Upper and lower case versions of the same character are different and distinct; `'a' != 'A'`
* Words are bound by any whitespace character.
* 'Letters' are any symbol which can be represented by a single unicode character.
* The text document must be read in by your code -- no preloading/hard-coding of the text allowed.
* The output should be the word, followed by the count of unique letters.
    + `llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch - 18`
    + Any delimiter/spacing between the two values is up to you, so long as there is at least one character to separate them.
* In the event more than one word exists with the highest count, print all words for that count, with one new line delimiting.
```
superacknowledgement - 16
pseudolamellibranchiate - 16
```
* This is code golf, so shortest code wins.

This answer on English.SE inspired me to create this challenge. The example uses just a word list, but any text should be able to be processed.

# Answer
> 7 votes
## APL (56)

```
{⎕ML←3⋄⊃{⍵,⍴∪⍵}¨W[⍙]⍴⍨↑+/∆∘.=∆←∆[⍙←⍒∆←↑∘⍴∘∪¨W←⍵⊂⍨⍵≠' ']}

```

This is a function (question says that's allowed) that takes a string and returns a matrix of words and unique lengths.

Usage:

```
      {⎕ML←3⋄⊃{⍵,⍴∪⍵}¨W[⍙]⍴⍨↑+/∆∘.=∆←∆[⍙←⍒∆←↑∘⍴∘∪¨W←⍵⊂⍨⍵≠' ']}'The quick brown fox jumps over the lazy dog.'
quick 5
brown 5
jumps 5

```

Explanation:

* `⎕ML←3`: set migration level to 3 (so that  is partition instead of enclose)
* `W←⍵⊂⍨⍵≠' '`: store in `W` the given string, where each partition consists of non-whitespace characters.
* `⍙←⍒∆←↑∘⍴∘∪¨W`: get the amount () of unique () elements in each part (`¨`) of `W`, and store these in , then get the sort order when sorted downwards on this () and store that in .
* `∆[⍙`...`]`: sort  by , so now we have the unique lengths in order.
* `∆∘.=∆←∆`: store the sorted  back in , and see which elements of  are equal.
* `↑+/`: sum the rows (now we know how many elements are equal to each element) and then take the first item (now we know how many elements are equal to the first element, i.e. how many of the words are tied for first place.)
* `W[⍙]⍴⍨`: sort `W` by , and take the first N, where N is the number we just calculated.
* `{⍵,⍴∪⍵}¨`: for each of these, get the word itself and the amount of unique characters in the word
* : format as matrix

# Answer
> 4 votes
## Perl 78 bytes

```
map{push$_[keys{map{$_,1}/./g}]||=[],$_}split for<>;print"$_ $#_
"for@{$_[-1]}

```

Interpretting the restriction *"The text document must be read in by your code"* to mean that command line options that read and parse the input are not allowed. As with the PHP solution below, only characters 10 and 32 are considered to be word delimiters. Input and output are also taken in the same manner.

---

## PHP 128 bytes

```
<?foreach(split(~ßƒõ,fread(STDIN,1e6))as$s){$w[count(count_chars($s,1))][]=$s;}krsort($w)?><?=join($f=~ß.key($w).~õ,pos($w)),$f;

```

The only characters considered to be word delimiters are characer 10, and character 32. The rest, including puncuation, are considered to be part of the word.

This contains a few binary characters, which saves quotation marks, but as a result needs to be saved with an ANSI encoding in order to function properly. Alternatively, this version can be used, which is 3 bytes heavier:

```
<?foreach(split(' |
',fread(STDIN,1e6))as$s){$w[count(count_chars($s,1))][]=$s;}krsort($w)?><?=join($f=' '.key($w).'
',pos($w)),$f;

```

Sample I/O:

input 1:

```
It was the best of times, it was the worst of times, it was the age of wisdom,
it was the age of foolishness, it was the epoch of belief, it was the epoch of
incredulity, it was the season of Light, it was the season of Darkness, it was
the spring of hope, it was the winter of despair, we had everything before us,
we had nothing before us, we were all going direct to Heaven, we were all going
direct the other way - in short, the period was so far like the present period,
that some of its noisiest authorities insisted on its being received, for good
or for evil, in the superlative degree of comparison only.

```

output 1:

```
$ php most-unique.php < input1.dat
incredulity, 11

```

input 2:

```
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis, nisl sit
amet consequat fringilla, justo risus iaculis justo, vel ullamcorper dui tellus
ut enim. Suspendisse lectus risus, molestie sed volutpat nec, eleifend vitae
ligula. Nulla porttitor elit vel augue pretium cursus. Donec in turpis lectus.
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia
Curae; Quisque a lorem eu turpis viverra sodales. Pellentesque justo arcu,
venenatis nec hendrerit a, molestie vitae augue.

```

output 2:

```
$ php most-unique.php < input2.dat
consequat 9
ullamcorper 9
Vestibulum 9

```

# Answer
> 4 votes
# Mathematica 96 115

*Edit*: code now finds all words of the maximum number of characters. I refuse to treat commas as word characters.

```
f@t := With[{r = {#, Length@Union@Characters@#} & /@
StringSplit[t,RegularExpression@"\\W+"]},  Cases[r, {_, Max[r[[All, 2]]]}]]

```

**Examples**

```
f@"It was the best of times,...of comparison only."

```

or

```
f@Import["t1.txt"]

```

> {{"incredulity", 10}, {"superlative", 10}}

---

```
f@"Lorem ipsum... vitae augue."

```

or

```
f@Import["t2.txt"]

```

> {"Vestibulum", 9}

---

**Longer Examples**

```
f@Import["ShakespearesSonnets.txt"]
f@Import["OriginOfSpecies.txt"]
f@Import["DeclarationOfIndependence.txt"]
f@Import["DonQuixoteISpanish.txt"]
f@Import["AliceInWonderland.txt"]
f@Import["UNHumanRightsGerman.txt"]
f@Import["GenesisKJV.txt"]

```

Surprise: The most "unique" word in the *Declaration of Independence* is also the most unique word in *Alice in Wonderland*!

> {"prognosticate", 11}
> {"undiscoverable", 13}
> {"uncomfortable", 12}
> {"regocijadamente", 12}
> {"uncomfortable", 12}
> {"Verpflichtung", 13}
> {"buryingplace", 12}

# Answer
> 4 votes
## Python 2 (110 (98 using file input))

```
import sys
f=lambda x:len(set(x))
a=sys.stdin.read().split()
c=max(map(f,a))
for i in a:
 if f(i)==c:print i,c

```

.

```
f=lambda x:len(set(x))
a=file('a').read().split()
c=max(map(f,a))
for i in a:
 if f(i)==c:print i,c

```

Things to improve: printing (33 characters)

Punctuation is considered letters.

# Answer
> 4 votes
This is my first codegolf, I'm so excited :) Also that means it is probably not any good.

**Groovy 127 117 112 105**

Edit: Since functions seem to be allowed here is one in 105. I also renamed the variables to make the first column read ACDC, because that is important in any kind of source code:

```
A={e={it.toSet().size()}
C=it.text.tokenize()
D=e(C.max{e(it)})
C.grep{e(it)==D}.each{println"$it $D"}}

```

You would call it like that:

```
A(new File("words.txt"))

```

Without function using standard input in **112**:

```
a={it.toSet().size()}
b=System.in.getText().tokenize()
c=a(b.max{a(it)})
b.grep{a(it)==c}.each{println "$it $c"}
```

```
a={it.toSet().size()}
b=System.in.getText().tokenize().sort{-a(it)}
c=a(b[0])
b.grep{a(it)==c}.each{println "$it $c"}
```

```
a={it.toSet().size()}
System.in.getText().tokenize().sort({-a(it)}).groupBy{a(it)}.take(1).each{k,v->v.each{println "$it $k"}}
```

Input: Lorem Ipsum Text from primo

All scripts output:

```
consequat 9
ullamcorper 9
Vestibulum 9

```

Anyone got an idea how to make them more groovy?

# Answer
> 3 votes
## GoRuby 2.0.0 – 66 chars

The solutions below didn't actually find all matches but only one. Here's my final version:

```
a=$<.r.sp.m{|x|[x,x.ch.u.sz]};a.m{|x|s x*' - 'if x.l==a.m_(&:l).l}

```

Examples:

> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis, nisl sit amet consequat fringilla, justo risus iaculis justo, vel ullamcorper dui tellus ut enim. Suspendisse lectus risus, molestie sed volutpat nec, eleifend vitae ligula. Nulla porttitor elit vel augue pretium cursus. Donec in turpis lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque a lorem eu turpis viverra sodales. Pellentesque justo arcu, venenatis nec hendrerit a, molestie vitae augue.

produces:

```
$ ruby golf.rb < input.txt
consequat - 9
ullamcorper - 9
Vestibulum - 9

```

## GoRuby 2.0.0 – 29 chars (not exact output format)

```
s$<.sp.m{|x|[x.ch.u.sz,x]}.mx

```

Expects input from stdin. The output format is a little bit different, though. For example:

```
$ ruby golf.rb < british.1
14
manoeuvrability

```

## GoRuby 2.0.0 – 42 40 chars

```
s$<.r.sp.m{|x|[x.ch.u.sz,x]}.mx.rv*' - '

```

expects input from stdin

## Ruby 1.9.3 - 69 65 chars

```
puts$<.read.split.map{|x|[x.chars.uniq.size,x]}.max.reverse*' - '

```

expects input from stdin (same as above, but without GoRuby abbreviations)

# Answer
> 3 votes
**R - 106 characters**
As a function with the input text as parameter:

```
f=function(t){
s=strsplit
a=sapply
t=s(t," ")[[1]]
w=a(a(s(t,""),unique),length)
n=(w==max(w))
cbind(t[n],w[n])
}

```

And a few examples:

```
f("It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way - in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.")
     [,1]           [,2]
[1,] "incredulity," "11"

f("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis, nisl sit amet consequat fringilla, justo risus iaculis justo, vel ullamcorper dui tellus ut enim. Suspendisse lectus risus, molestie sed volutpat nec, eleifend vitae ligula. Nulla porttitor elit vel augue pretium cursus. Donec in turpis lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque a lorem eu turpis viverra sodales. Pellentesque justo arcu, venenatis nec hendrerit a, molestie vitae augue.")
     [,1]          [,2]
[1,] "consequat"   "9"
[2,] "ullamcorper" "9"
[3,] "Vestibulum"  "9"

```

Or **R - 100 characters**
As a function with the path to the text file as parameter:

```
f=function(t){
t=scan(t,"")
a=sapply
w=a(a(strsplit(t,""),unique),length)
n=(w==max(w))
cbind(t[n],w[n])
}

```

Usage:

```
f("t1.txt")
Read 120 items
     [,1]           [,2]
[1,] "incredulity," "11"

```

# Answer
> 3 votes
# Husk, ~~19~~ ~~13~~ ~~16~~ ~~15~~ 14 bytes

*Edit: -6 bytes by taking inspiration from Shaggy's Japt answer, but then ~~+3~~ ~~+2~~ +1 byte to scrupulously adhere to the output format (without surrounding parentheses and/or quotation marks)*

```
mS+ȯΘs₁→k₁w
Lu

```

Try it online!

```
Lu                  # helper function: get the number of unique letters

¶m§,I₁→k₁w          # main program
¶                   # split result by newlines
 m                  # for each element of list
  §,I₁              # combine itself (I) with result of helper function
      →k₁w          # list:
      →             # last element of
       k w          # groups of words of input, grouped & sorted by
        ₁           # results of helper function

```

# Answer
> 2 votes
## Javascript 163 155 152 162 bytes

This is about as short as I can get it:

```
prompt(x=[]).split(/\s/).forEach(function(a){b={};c=0;a.split('').forEach(function(d){b[d]?1:b[d]=++c});x[c]?x[c].push(a):x[c]=[a]});alert((l=x.length-1)+':'+x[l])
prompt(x=[]).split(/\b/).map(function(a){b={};c=0;a.split('').map(function(d){b[d]?1:b[d]=++c});x[c]?x[c].push(a):x[c]=[a]});alert((l=x.length-1)+':'+x[l])
prompt(x=[]).split(/\s/).map(function(a){b=[c=0];a.split('').map(function(d){b[d]?1:b[d]=++c});x[c]=(x[c]||[]).concat(a)});alert((l=x.length-1)+':'+x[l])

```

```
prompt(x=[]).split(/\s/).map(function(a){b=[c=0];a.split('').map(function(d){b[d]?1:b[d]=++c});x[c]=(x[c]||[]).concat(a)});alert((l=x.length-1)+':'+x[l].join('\n'))

```

In this version `/\s/` separates words based on whitespace, so it includes punctuation, commas, periods, etc as part of words. This is easily changed to `/\b/` to not included them.

I'll see what I can do with for-loops instead of forEaches in a bit.

## I/O:

> It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way - in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.

```
11:incredulity,

```

> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis, nisl sit amet consequat fringilla, justo risus iaculis justo, vel ullamcorper dui tellus ut enim. Suspendisse lectus risus, molestie sed volutpat nec, eleifend vitae ligula. Nulla porttitor elit vel augue pretium cursus. Donec in turpis lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque a lorem eu turpis viverra sodales. Pellentesque justo arcu, venenatis nec hendrerit a, molestie vitae augue.

```
9:consequat
ullamcorper
Vestibulum

```

> A little tired, perhaps. But I feel peaceful. Your success in the ring this morning was, to a small degree, my success. Your future is assured. You will live, secure and safe, Wilbur. Nothing can harm you now. These autumn days will shorten and grow cold. The leaves will shake loose from the trees and fall. Christmas will come, and the snows of winter. You will live to enjoy the beauty of the frozen world, for you mean a great deal to Zuckerman and he will not harm you, ever. Winter will pass, the days will lengthen, the ice will melt in the pasture pond. The song sparrow will return and sing, the frogs will awake, the warm wind will blow again. All these sights and sounds and smells will be yours to enjoy, Wilbur—this lovely world, these precious days…

```
10:Wilbur—this

```

> Nearly all children nowadays were horrible. What was worst of all was that by means of such organizations as the Spies they were systematically turned into ungovernable little savages, and yet this produced in them no tendency whatever to rebel against the discipline of the Party. On the contrary, they adored the Party and everything connected with it... All their ferocity was turned outwards, against the enemies of the State, against foreigners, traitors, saboteurs, thought-criminals. It was almost normal for people over thirty to be frightened of their own children.

```
15:thought-criminals.

```

# Answer
> 2 votes
### Scala 129 chars:

```
def f{
val l=readLine.split(" ").map(s=>(s,s.distinct.length)).sortBy(_._2)
println(l.filter(x=>x._2==l.last._2).mkString)}

```

# Answer
> 2 votes
# Jelly, 13 bytes

```
QL
ḲÇÐṀ,ÇKƊ€Y

```

Try it online!

Just returning the number of unique characters is 6 bytes and just returning the words (no count), is 7 bytes.

## How it works

```
QL - Helper link. Takes a string W on the left
Q  - Deduplicate W
 L - Length
     This returns the number of unique characters in W

ḲÇÐṀ,ÇKƊ€Y - Main link. Takes a string S on the left
Ḳ          - Split S on spaces
  ÐṀ       - Find the words for which the following is maximal:
 Ç         -   The number of unique characters
       Ɗ€  - Over each maximal word:
     Ç     -   Yield the number of unique characters
    ,      -   Pair with the word
      K    -   Join by spaces
         Y - Join by newlines

```

# Answer
> 2 votes
# Japt v2.0a0 `-hR`, 11 bytes

Uses a comma as the delimiter.

```
¸®¸pZâ lÃüÌ

```

Try it

```
¸®¸pZâ lÃüÌ     :Implicit input of string            > "Finding the most unique word"
¸               :Split on spaces                     > ["Finding","the","most","unique","word"]
 ®              :Map each Z
  ¸             :  Split on spaces                   > [["Finding"],["the"],["most"],["unique"],["word"]]
   p            :  Push
    Zâ          :    Z deduplicated                  >   ["Findg","the","most","uniqe","word"]
       l        :    Length                          >   [5,3,4,5,4]
        Ã       :End map                             > [["Finding",5],["the",3],["most",4],["unique",5],["word",4]]
         ü      :Group & sort by
          Ì     :  Last element                      > [[["the",3]],[["most",4],["word",4]],[["Finding",5],["unique",5]]]
                :Implicit output of last element     > [["Finding",5],["unique",5]]
                :  joined with newlines              > "Finding,5\nunique,5"

```

# Answer
> 1 votes
**Python 176 168**

```
w = "".join((open('c')).readlines()).replace("\n", " ").split(" ")
l = sorted(zip([len(set(w[i])) for i in range(len(w))],w,))
print([x for x in l if l[-1][0] == x[0]])

```

# Answer
> 1 votes
# Python3 119

Reads from a file called `a`.

```
r={w:len(set(w))for w in open("a").read().split()};print("\n".join(str((k,v))for k,v in r.items()if v==max(r.values())))

```

Tested with the input texts from @primo:

```
Input 1:
    ('incredulity,', 11)

Input 2:
    ('Vestibulum', 9)
    ('consequat', 9)
    ('ullamcorper', 9)

```

# Answer
> 1 votes
# Haskell, 85 bytes

```
k(a:b)=k(filter(/=a)b)-1
k[]=0
f x=unlines[y++show(k y)|y<-x,all((>=k y).k)x]
f.words

```

Try it online!

This employs one clever trick. Instead of counting up the number of unique characters in each word, it counts down. So `hello` yeilds \\$-4\\$ rather than \\$4\\$. This allows us to use `-` as the delimter later which saves us a tiny bit.

# With more lenient IO, 65 bytes

```
k(a:b)=1+k(filter(/=a)b)
k[]=0
f x=[(y,k y)|y<-x,all((<=k y).k)x]

```

Try it online!

20 bytes were spent just conforming to the archaic IO restrictions. This takes a list of input words and outputs a list of tuples containing the word and the count.

# Answer
> 1 votes
# Zsh, 77 bytes

```
for x;z=`fold -1<<<$x|sort|uniq|wc -l` m=$[z>m?z:m]&&echo $z $x>>p
grep ^$m p

```

Try it Online!

`$z` is a count of the unique letters in each word. `$m` is the maximum `$z`. We write each word and its count to file `p`, then grep for `$m`.

OG: 119 bytes using associative array.

# Answer
> 1 votes
# JavaScript, 147 bytes

With map:

```
t=>(s='',m=new Map(),t.split(' ').map(w=>m.set(w,new Set(w).size)),d=[...m].sort((a,b)=>b[1]-a[1]),d.map(x=>x[1]==d[0][1]&&(s+=x.join('-')+`
`)),s)

```

With plain object

```
t=>(s='',m={},t.split(' ').map(w=>m[w]=new Set(w).size),d=Object.entries(m).sort((a,b)=>b[1]-a[1]),d.map(x=>x[1]==d[0][1]&&(s+=x.join('-')+`
`)),s)

```

Try it:

```
f=t=>(s='',m=new Map(),t.split(' ').map(w=>m.set(w,new Set(w).size)),d=[...m].sort((a,b)=>b[1]-a[1]),d.map(x=>x[1]==d[0][1]&&(s+=x.join('-')+`
`)),s)

console.log(f('It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way - in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.'));

console.log(f('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis, nisl sit amet consequat fringilla, justo risus iaculis justo, vel ullamcorper dui tellus ut enim. Suspendisse lectus risus, molestie sed volutpat nec, eleifend vitae ligula. Nulla porttitor elit vel augue pretium cursus. Donec in turpis lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque a lorem eu turpis viverra sodales. Pellentesque justo arcu, venenatis nec hendrerit a, molestie vitae augue.'));

console.log(f('A little tired, perhaps. But I feel peaceful. Your success in the ring this morning was, to a small degree, my success. Your future is assured. You will live, secure and safe, Wilbur. Nothing can harm you now. These autumn days will shorten and grow cold. The leaves will shake loose from the trees and fall. Christmas will come, and the snows of winter. You will live to enjoy the beauty of the frozen world, for you mean a great deal to Zuckerman and he will not harm you, ever. Winter will pass, the days will lengthen, the ice will melt in the pasture pond. The song sparrow will return and sing, the frogs will awake, the warm wind will blow again. All these sights and sounds and smells will be yours to enjoy, Wilbur—this lovely world, these precious days…'));

console.log(f('Nearly all children nowadays were horrible. What was worst of all was that by means of such organizations as the Spies they were systematically turned into ungovernable little savages, and yet this produced in them no tendency whatever to rebel against the discipline of the Party. On the contrary, they adored the Party and everything connected with it... All their ferocity was turned outwards, against the enemies of the State, against foreigners, traitors, saboteurs, thought-criminals. It was almost normal for people over thirty to be frightened of their own children.'));
```

# Answer
> 1 votes
# Pip `-p`, ~~24~~ 23 bytes

```
(a^:s(Y#*UQ*a)@*My)ZDNy

```

Try It Online!

# Answer
> 1 votes
# JavaScript, ~~76~~ 71 bytes

```
s=>s.split` `.map(w=>(n=new Set(w).size)<s||[w,s=n]).filter(x=>x[1]==s)

```

Try it online!

# Answer
> 1 votes
# Thunno `N`, \\$ 29 \log\_{256}(96) \approx \\$ 23.87 bytes

```
A_ZiDedZULEZZz:zGAJzHAKerA_sj

```

Attempt This Online!

We can save a character if joining by a digit is allowed: Attempt This Online!

#### Explanation

```
A_Zi      # Split the (implicit) input by spaces        ["Finding", "the", "most", "unique", "word"]
    D     # Duplicate this list                         ["Finding", "the", "most", "unique", "word"], ["Finding", "the", "most", "unique", "word"]
     e    # Map over it:                                ["Finding", "the", "most", "unique", "word"]
      dZU #  Uniquify the string                         ["Findg", "the", "most", "uniqe", "word"]
L         #  And get the length                          [5, 3, 4, 5, 4]
 E        # (End map)                                   ["Finding", "the", "most", "unique", "word"], [5, 3, 4, 5, 4]
  ZZ      # Zip this with the split list                [[5, "Finding"], [3, "the"], [4, "most"], [5, "unique"], [4, "word"]]
    z:zG  # Sort and group by:                          [[3, "the"], [4, "most"], [4, "word"], [5, "Finding"], [5, "unique"]]
AJ        #  First element of each                       [3, 4, 4, 5, 5]
  zH      # (End group)                                 [[[3, "the']], [[4, "most"], [4, "word"]], [[5, "Finding"], [5, "unique"]]]
    AK    # Get the last element                        [[5, "Finding"], [5, "unique"]]
      e   # Map over it:                                [[5, "Finding"], [5, "unique"]]
       r  #  Reverse                                     [["Finding", 5], ["unique", 5]]
A_sj      #  And join by spaces                          ["Finding 5", "unique 5"]
          # (N flag joins by newlines)                  "Finding 5", "unique 5"
          # Implicit output

```

# Answer
> 0 votes
## VBScript - 430 / VBA - 420

**VBScript:**

```
Function r(t)
d="Scripting.Dictionary"
Set w=CreateObject(d)
c=1
Do Until c>Len(t)
p=InStr(c,t," ")
i=InStr(c,t,vbCr)
If p<i Then s=i Else s=p
If s=0 Then s=Len(t)+1
f=Mid(t,c,s-c)
If Not w.Exists(f) Then
Set x=CreateObject(d)
For l=1 To Len(f)
n=Mid(f,l,1)
If Not x.Exists(n) Then x.Add n,n
Next
w.Add f,f
y=x.Count
If m=y Then z=f &vbCr &z
If m<y Then m=y:z=f
End If
c=s+1
Loop
r=z &" " &m
End Function

```

**VBA:**

```
Function r(t)
d="Scripting.Dictionary"
Set w=CreateObject(d)
c=1
Do Until c>Len(t)
p=InStr(c,t," ")
i=InStr(c,t,vbCr)
s=IIf(p<i,i,p)
If s=0 Then s=Len(t)+1
f=Mid(t,c,s-c)
If Not w.Exists(f) Then
Set x=CreateObject(d)
For l=1 To Len(f)
n=Mid(f,l,1)
If Not x.Exists(n) Then x.Add n,n
Next
w.Add f,f
y=x.Count
If m=y Then z=f &vbCr &z
If m<y Then m=y:z=f
End If
c=s+1
Loop
r=z &" " &m
End Function

```

# Answer
> 0 votes
# Python 3, 88 bytes

```
lambda s:[(w,len({*w}))for w in s.split()if len({*w})==max(map(len,map(set,s.split())))]

```

Try it online!

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


title: Implement a 2fuck interpreter

text:
# Question
Title: Implement a 2fuck interpreter
*2fuck* is a simple 2D variation on brainfuck. Like traditional brainfuck, there is an 1D memory tape that extends 30000 bytes to the right from its beginning, consisting of values between 0 and 255.

Arithmetic should wrap around, adding 1 to 255 sets the cell to 0, and moving right from memory cell 29999 should move the pointer back to 0. The converse should happen when decrementing or moving left.

The input is an 1D unidirectional string/stream.

It has the following commands:

* `<` change the direction of the instruction pointer to left.
* `>` change the direction of the instruction pointer to right.
* `^` change the direction of the instruction pointer to up.
* `v` change the direction of the instruction pointer to down.
* `[` decrement the data pointer.
* `]` increment the data pointer.
* `-` decrement the value of the tape under the data pointer.
* `+` increment the value of the tape under the data pointer.
* `?` if the value under the data pointer is *not* 0, rotate the instruction pointer counterclockwise 90 degrees.
* `.` Output the value of the tape under the data pointer as a character.
* `,` Read a character from standard input and copy it to the position in the tape under the data pointer. If EOF is reaches this should NOOP.
* Any other character should be ignored.

The instruction pointer starts in the top left corner, moving right, execution terminates if it ever goes out of bounds in any direction, aka when it would be impossible to reach any more instructions.

The program can be passed to the interpreter as a two dimensional array or a simple string featuring line breaks. The input might be passed as an additional parameter or concatenated to the program with a separator like a null byte. However, do not assume that all lines in the program are the same length.

## Test cases

### "Hello World"

```
v                >]++]+++]+++]+[[[[-v
v                           >[v
v         >]++++>?]+]+]-]]+>?[ -v
>++++++++>?]].]- --.+++++++ .. + ++. ]].[-.[.+++.------.--------.]]+.]++.
         ^                      <
                           ^  <
                ^                   <

```

### Cat

Copies the input to the output

```
v     >-v
v  >.>?, v
>,>?
  ^      <
     ^  <

```

## Print the ASCII code page

*Thanks Matteo\_C*

```
v      >-[v
v   >->?]] +[v
v                          >-[++++]v
v                             >-[[. +]]v
v                                            >-v
v                 >-]]++++>?[>?++++ +++ +++.>?[ v
>]->?] -]+ ++ +++>?
                 ^                              <
                                            ^  <
                             ^         <
                          ^        <
   ^         <
      ^   <

```

# Answer
> 9 votes
# C (gcc),  ~~317~~   ~~268~~  250 bytes

```
X,Y=1;E;Z['zz'];P;*Q=Z;main(M,s)char**s;{for(;Q=(Q-Z+'u0')%'u0'+Z,X+0u<Y*(E=strlen(s[Y]),M=M<E?E:M);P%2?Y-=2-P%4:(X+=1-P%4))X<E?write(E=s[Y][X]-45,Q,1),P=E-15?E-17?E-49?E-73?P+(E==18&&*Q%256):3:1:0:2,E-46?E-48?E?E+2?read(~E,Q,1):++*Q:--*Q:++Q:--Q:0;}

```

Try it online!

60 bytes saved(45 direct + some indirect) by c--

Segfault when going down outside of range, correct output

Assume only stdin and stdout. (`/` writes to stderr, but it's fine to ignore them)

# Answer
> 8 votes
# Vyxal, 113 bytes

```
₌L↵r⅛⅛k2T0ẋ⅛k≈N→0{:k□i←+:¾hÞẏ$c¬ßQ→¾h←Þi:¨□›[¨□N$_|`?.,+-][`$v=÷N+&+N+^¼¥k2T%:£~i„+„[¼ḣ⅛:[C$]_]₈%:‟Ȧ⟑;⅛^$[:C₴]∧[‹

```

Try it Online!

It takes the program as a string and the input as a string. Here is a version with 90 cells.

```
₌L↵            # parallel apply length and split on newline
   r           # pad with spaces to given length
    ⅛          # push to global array
     ⅛         # push input to global array
k2T0ẋ⅛         # push a list of 30000 zeros to global array
k≈N→           # save [0, -1] to a variable with empty name
    0          # push 0
# Together this sets up the global array as [code, input, tape],
# the position in a variable and the direction on stack.
{              # start a while loop
 :             # duplicate
  k□i          # index into [[0,1],[1,0],[0,-1],[-1,0]]
     ←         # load variable
      +        # add
# Stack: direction position
:→             # duplicate and store variable
  ¾h           # push the global array and get the first item, this     pushes code
    Þẏ         # multidimensional indices
      $c       # check if it contains current position
        ¬ßQ    # if not stop execution
# Stack: direction
¾h←            # push code and position
   Þi          # index into, this gets the current instruction
     :¨□›[     # if it is an arrow:
¨□N$_          #   convert to integer, negate and remove the previos direction from the stack
     |         # else:
`?.,+-][`$v=÷  #   for each of the characters in the string push 1 if it's equal to current instruction and 0 otherwise
# Stack: direction ? . , + - ] [
N              #   negate
 +             #   sum the top two elements
  &+           #   add top of stack to the register (the register represents the data pointer)
    N+         #   negate and add
      ^        #   reverse the stack
       ¼       #   pop from global array
        ¥      #   push register
# Stack: value_delta , . ? direction tape ptr
30T%:£         #   modulo 30000 and store to the register
      ~i       #   index into without popping
# Stack: value_delta , . ? direction tape ptr value
„+             #   rotate stack left and add
  „            #   rotate stack left
   [           #   if the instruction was ",":
    ¼ḣ⅛        #     pop from global array, extract head, push to global array
               #       this gets the next character from input
       :[C$]_  #     if non-empty conver to number and replace the current value
             ] #   end if
# Stack: . ? direction tape ptr value
₈%             #   modulo 256
  :‟           #   duplicate and rotate stack right
    Ȧ          #   tape[ptr] = value
     ⟑;⅛       #   push tape to global array
        ^$     #   reverse stack and swap the top two items
# Stack: direction ? value .
[:C₴]          #  if instruction was "." print value
     ∧[‹       #  if value != 0 and the instruction was "?" decrement direction

```

# Answer
> 7 votes
# JavaScript (ES6), 224 bytes

*-16 thanks to @l4m2*
*+8 to deal with unpadded input :-(*

Expects `(code)(input)`, where `code` is an array of strings and `input` is an array of bytes. Returns another array of bytes.

```
c=>i=>{for(o=[],T=[x=y=d=p=j=0];c[v=T[p%=3e4]&=255,y]+0&&(c+0)[x];d&=3,x-=~-d%2,y+=~-~-d%2)(q='?[]-+.,v>^<'.indexOf(c[y][x]))>6?d=q:eval("d+=!!v;p+=29999;p++;T[p]--;T[p]++;o.push(v);T[i[j]*0+p]=i[j++]".split`;`[q]);return o}

```

Try it online!

## Commented

### Main code

```
c =>                      // c[] = code, as a list of strings
i => {                    // i[] = input array
  for(                    // main loop:
    o = [],               //   o[] = output array
    T = [                 //   T[] = tape array
      x = y =             //   (x, y) = position of the program pointer
      d =                 //   d = direction
                          //       (0:right, 1:up, 2:left, 3:down)
      p =                 //   p = tape pointer
      j = 0               //   j = input pointer
    ]                     //
    ;                     //   before each iteration:
    c[v = T[p %= 3e4]     //     force the tape pointer in [0 .. 29999]
          &= 255,         //     coerce the current tape cell to a byte
      y                   //     and save it in v
    ] + 0 && (c + 0)[x]   //     stop if we're out of bounds
    ;                     //   after each iteration:
    d &= 3,               //     force d in [0 .. 3]
    x -= ~-d % 2,         //     x <- x + dx
    y += ~-~-d % 2        //     y <- y + dy
  )                       //   at each iteration:
    ( q =                 //     let q be the index
        '?[]-+.,v>^<'     //       in this lookup string
        .indexOf(c[y][x]) //       of the current instruction
    ) > 6 ?               //     if this is a direction instruction:
      d = q               //       update d accordingly
    :                     //     else:
      eval(               //       evaluate some specific code
        "..."             //       (detailed below)
        .split`;`[q]      //       for this instruction, or just do
      );                  //       eval(undefined) if unrecognized
  return o                // end of loop: return the output string
}                         //

```

### Instructions

```
d += !!v                  // '?': conditional 90° turn
p += 29999                // '[': decrement the tape pointer
p++                       // ']': increment the tape pointer
T[p]--                    // '-': decrement the value of the tape
T[p]++                    // '+': increment the value of the tape
o.push(v)                 // '.': output the value of the tape
T[i[j] * 0 + p] = i[j++]  // ',': load a new value from the input

```

# Answer
> 6 votes
# Python, ~~264~~ 260 bytes

*-4 bytes thanks to @gsitcia by replacing `r,x,y,p=[0]*4` with `r=x=y=p=0`*

```
def g(i,t,L=30000):
 d,c=[0]*L,-1;r=x=y=p=0
 while x*y>=0:
  if(s:="v<^>[]-+?.,".find(i[y][x]))==9:print(chr(d[p]))
  d[p]=s>9and-~c<len(t)and ord(t[c:=c+1])or(d[p]+(s==7)-(s==6))%256;r=[r-(s==8and 0<d[p]),s][0<=s<4]%4;x+=r-2&-r;y+=7%~r+1;p=(p+(s==5)-(s==4))%L

```

Attempt This Online!

Since the utilities in Python for taking in single characters from standard input are bad, this program instead takes in the input as a string (and the instructions as a list of strings or a 2D array of characters). It terminates with an error if the pointer goes off the right or bottom edge of the instructions.

# Answer
> 5 votes
# JavaScript

## ~~422...396~~ ~~425...~~372 bytes

```
f=q=>i=>{k=q.split`
`;x=[a=b=p=n=t=d=0,1,0,-1,0];k.every(o=>t=Math.max(t,o.length));m=Array(z=3e4).fill(0);for(u="";a<t&b<k.length&a>=0&b>=0;m[p%=z]&=255,b-=x[d&=3],a+=x[1+d])(c=k[b][a])=="["?p++:c=="]"?p+=z-1:c=="+"?m[p]++:c=="-"?m[p]--:c=="."?u+=String.fromCharCode(m[p]):c==","&n<i.length?m[p]=i.codePointAt(n++):c=="?"&&m[p]?d++:d=(e=">^<v".indexOf(c))+1?e:d;return u}

```

Although JS is not the best language for golfing, it is fun for not being something too obscure and is one where many people would actually try to understand what is going on. In fact, is the most used programming language in the world, so it should not be missed.

If you really want to see all of that running, just click the "Show code snippet" link below and then hit the "Run snippet button" button.

In the snippet code (see below), for legibility, I added spaces and new lines. For golfing purposes, those should not be counted. All but one of the spaces and all but one of the line breaks are unnecessary. So I present the code with spaces and line breaks and remove them before actually running. Also, I added a lot of JS, HTML and CSS for easy testing with different programs and different inputs. Feel free to reuse them if you want to.

```
// Here is the code. For legibility, I added spaces and new lines.
// For golfing purposes, those should not be counted.
// All but one of the spaces are unnecessary.

/// Starts here.
w = q => i => {
  k = q.split`
`;
  x = [a = b = p = n = t = d = 0, 1, 0, -1, 0];
  k.every(o => t = Math.max(t, o.length));
  m = Array(z = 3e4).fill(0);
  for (
      u = "";
      a < t & b < k.length & a >= 0 & b >= 0;
      m[p %= z] &= 255, b -= x[d &= 3], a += x[1 + d]
  ) (c = k[b][a]) == "[" ? p++
      : c == "]" ? p += z - 1
      : c == "+" ? m[p]++
      : c == "-" ? m[p]--
      : c == "." ? u += String.fromCharCode(m[p])
      : c == "," & n < i.length ? m[p] = i.codePointAt(n++)
      : c == "?" && m[p] ? d++
      : d = (e = ">^<v".indexOf(c)) + 1 ? e : d;
  return u
}
/// Ends here.

// How many characters? Take out the spaces and new lines and count them.
// We prepend the "f=" because it would be unfair to not count them.
// We call it f instead of w to ensure that f is the variant without
// spaces and line breaks. The only significant space are the "return u"
// and the `\n` which I special case for them.
const code = ("f=" + w.toString())
    .replace(/ |\n/gi, "")
    .replace("returnu", "return u")
    .replace("``", "`\n`");
const howMany = code.length;
eval(code); // Make f come to existence.
document.querySelector("#howMany").value = "" + howMany;
document.querySelector("#golfed").value = code;

// The Let's run button.
document.querySelector("#run").onclick = () => {
  const program = document.querySelector("#program").value;
  const input = document.querySelector("#input").value;
  const output = f(program)(input);
  document.querySelector("#output").value = output;
}

// Convenience for preloading Hello World, cat and ascii table example programs.

const loader = t => () => document.querySelector("#program").value = t;

const helloWorld = [
  "v                >]++]+++]+++]+[[[[-v",
  "v                           >[v",
  "v         >]++++>?]+]+]-]]+>?[ -v",
  ">++++++++>?]].]- --.+++++++ .. + ++. ]].[-.[.+++.------.--------.]]+.]++.",
  "         ^                      <",
  "                           ^  <",
  "                ^                   <"
].join("\n");
document.querySelector("#helloWorld").onclick = loader(helloWorld);

const cat = [
  "v     >-v",
  "v  >.>?, v",
  ">,>?      ",
  "  ^      <",
  "     ^  <"
].join("\n");
document.querySelector("#cat").onclick = loader(cat);

asciiTable = [
  "v      >-[v",
  "v   >->?]] +[v",
  "v                          >-[++++]v",
  "v                             >-[[. +]]v",
  "v                                            >-v",
  "v                 >-]]++++>?[>?++++ +++ +++.>?[ v",
  ">]->?] -]+ ++ +++>?",
  "                 ^                              <",
  "                                            ^  <",
  "                             ^         <",
  "                          ^        <",
  "   ^         <",
  "      ^   <"
].join("\n");
document.querySelector("#asciiTable").onclick = loader(asciiTable);
```

```
/*
    I used the StackOverflow snippet for making testing easier,
    and I also added a few CSS and HTML for that. Feel free to reuse
    it for other answers.
*/

all {
    width: 100%;
    padding-left: 10px;
    padding-right: 10px;
}

div, input:not(#howMany), textarea {
    width: 90%;
}

textarea {
    height: 200px;
}

.warning {
    color: red;
}

button {
    width: 50%;
}
```

```
<!--
    I used the StackOverflow snippet for making testing easier,
    and I also added a few CSS and HTML for that. Feel free to reuse
    it for other answers.
-->

<div class="all">
    <h2>How many characters?</h2>
    <input type="text" readonly="true" id="howMany" />

    <h2>How is it golfed</h2>
    <input type="text" readonly="true" id="golfed" />

    <h2>Type the program here</h2>

    <textarea id="program"></textarea>

    <button id="helloWorld">Load a Hello World program above</button>
    <br>
    <button id="cat">Load the cat program above</button>
    <br>
    <button id="asciiTable">Load the ASCII table dumper program above</button>

    <h2>Type the input here</h2>
    <input type="text" id="input" value="Some cool input here!"/>

    <h2>And finally...</h2>

    <button id="run">Let's run!</button>

    <div>This is the output</div>
    <textarea type="text" readonly="true" id="output" /></textarea>
</div>
```

### Contributions from comments:

> `q.split("\n");` can be `q.split`\n`;` for -2. – Kevin Cruijssen

> I think what @KevinCruijssen meant was `q.split`literal newline`;` – Jacob

# Answer
> 4 votes
# Pyth, 191 bytes

```
K*30000]0JE=.tQd=G,ZZ=H,1ZW.A+-VlMhBQGhMG=Y@@QhGeG=T@KZ [&qY\v=H,01&qY\^=H,0_1&qY\<=H,_1 0&qY\>=H,1 0&&TqY\?=H,eH_hH &qY\[=tZ&qY\]=hZ&qY\-XZK_1&qY\+XZK1&qY\.pC@KZ&qY\,&J,XKZChJ=tJ=+VGH=%R255K

```

Try it online!

Could definitely be golfed some more. Takes the program as an array of strings first, and any input as the second input. It's very slow since the whole tape is run through mod 255 on every instruction, but here's a TIO link to a version with a tape of length 30 which doesn't time out.

# Answer
> 4 votes
# Charcoal, 126 bytes

```
ＷＳ⊞υιＵＯ⌈ＥυＬιＬυ Ｐ⪫υ¶≔⪪⮌Ｓ¹θ≔Ｅ×³⁰φ⁰η≔⁰ζ≔⁰εＷＫＫ«≔﹪§ηζ²⁵⁶δ≡ι<≔⁴ε>≔⁰ε^≔²εv≔⁶ε[≦⊖ζ]≦⊕ζ-§≔ηζ⊖δ+§≔ηζ⊕δ?≧⁺∧δ²ε.≔⁺ω℅δω,Ｆ¬¬θ§≔ηζ℅⊟θＰ⁰Ｍ✳ε»⎚ω

```

Try it online! Link is to verbose version of code. Takes the program as a list of newline-terminated strings, then the input follows after a blank line (if there is no input you need a second blank line). Explanation:

```
ＷＳ⊞υι

```

Input the program.

```
ＵＯ⌈ＥυＬιＬυ

```

Fill a rectangle of the canvas with spaces.

```
Ｐ⪫υ¶

```

Overprint the program without moving the cursor.

```
≔⪪⮌Ｓ¹θ

```

Split the input into characters and reverse it.

```
≔Ｅ×³⁰φ⁰η

```

Create an array of 30,000 cells.

```
≔⁰ζ

```

Initialise the data pointer.

```
≔⁰ε

```

Initialise the direction pointer.

```
ＷＫＫ«

```

Repeat while the current instruction is not off limits.

```
≔﹪§ηζ²⁵⁶δ

```

Get the value of the cell at the data pointer, modulo 256.

```
≡ι

```

Switch over the current instruction.

```
<≔⁴ε

```

If it's a `<` then set the direction pointer to left.

```
>≔⁰ε

```

If it's a `>` then set the direction pointer to right.

```
^≔²ε

```

If it's a `^` then set the direction pointer to up.

```
v≔⁶ε

```

If it's a `v` then set the direction pointer to down.

```
[≦⊖ζ

```

If it's a `[` then decrement the data pointer.

```
]≦⊕ζ

```

If it's a `]` then increment the data pointer.

```
-§≔ηζ⊖δ

```

If it's a `-` then decrement the cell at the data pointer.

```
+§≔ηζ⊕δ

```

If it's a `+` then increment the cell at the data pointer.

```
?≧⁺∧δ²ε

```

If it's a `+` and the current cell is nonzero then rotate the direction pointer.

```
.≔⁺ω℅δω

```

If it's a `.` then append the character of the current cell to the output string.

```
,Ｆ¬¬θ§≔ηζ℅⊟θ

```

If it's a `,` and the input is not empty then replace the current cell with the ordinal of the next input character.

```
Ｐ⁰

```

Otherwise do nothing. (The newer version of Charcoal on ATO supports `switch_delimited` which avoids this but itself requires two extra bytes anyway.)

```
Ｍ✳ε

```

Move one step in the current direction.

```
»⎚ω

```

Clear the canvas and print the final output string.

# Answer
> 2 votes
# Java 10, ~~343~~ ~~339~~ ~~336~~ 317 bytes

```
m->i->{int l=0,M=30000,x=0,y=0,p=0,d=0,c,I=0,q;for(var t=new byte[M];;d=(q=">^<v?".indexOf(c))<0?d:q>3?t[p]!=0?-~d%3:d:q,p+=c==91?1:c==93?M-1:0,t[p%=M]-=c>42&c<46?c-44:0,System.out.print(c==46?(char)t[p]:""),y+=d%2-d%3%2*2,x+=3%-~d-d-~d%2)if((c=x>=(q=m[y].length)&(l=q>l?q:l)>x?0:m[y][x])==44&I<i.length)t[p]=i[I++];}

```

-3 bytes thanks to *@ceilingcat*.

Input 2fuck program as a 2D array of bytes, and optional input-characters as a second byte-array. Stops the execution of the input-programs with `ArrayIndexOutOfBoundsException`s.

Try it online.

**Explanation:**

```
m->i->{                   // Method with byte-matrix & byte-array parameters and no return
  int l=0,                //  Longest line integer, starting at 0
      M=30000,            //  Memory size, set to 30,000
      x=0,y=0,            //  x,y-coordinates, starting at 0,0
      p=0,                //  Data pointer integer, starting at 0
      d=0,                //  Direction integer, starting at 0 (right)
      c,                  //  Character value, uninitialized
      I=0,                //  Index integer for potential inputs, starting at 0
      q;                  //  Temp integer, uninitialized
  for(var t=new byte[M]   //  Tape byte-array, starting at 30k amount of 0s
      ;                   //  Start an infinite loop:
      ;                   //    After every iteration:
       d=                 //     Update the direction to:
         (q=">^<v?".indexOf(c))
                          //      Set `q` to the index of the character in ">^<v?",
                          //      or -1 if the character is not in this String
         <0?              //      If this `q` is -1, thus not one of those characters:
            d             //       Keep the direction the same
         :q>3?            //      Else-if `q` is 4 (thus '?'):
              t[p]!=0?    //       If the current tape-value at the pointer is 0:
               -~d%3      //        Set the direction to (d+1)%3 (90 degrees counterclockwise)
              :           //       Else ('?', but the tape-value is 0):
               d          //        Keep the direction the same
         :                //       Else (`q` is one of 0,1,2,3 / >,^,<,v):
          q,              //        Set the direction accordingly to this `q`
       p+=                //     Increase the data-pointer by:
          c==91?          //      If the character is '[':
           1              //       Increase the data pointer by 1
          :c==93?         //      Else-if the character is ']':
           M-1            //       Increase the data pointer by 29,999
          :               //      Else (a different character):
           0,             //       Keep the data pointer the same by increasing with 0
       t[p%=M             //     Modulo the data pointer by 30,000
             ]-=          //     Decrease the tape-value at the data pointer by:
                c>42&c<46?//      If the character is 43/44/45 (+/,/-):
                 c-44     //       Decrease it by c-44 (+→-1; ,→0; -→1)
                :         //      Else (a different character):
                 0,       //       Keep the tape-value the same by decreasing with 0
       System.out.print(  //     Print to STDOUT:
         c==46?           //      If the character is '.':
          (char)          //       Convert the following integer to a character:
                t[p]      //        The tape-value at the current data pointer
         :                //      Else (a different character)
          ""),            //       Print an empty string (aka nothing) instead
       y+=d%2-d%3%2*2,    //     Update `y` based on the direction†
       x+=3%-~d-d+-~d%2)  //     Update `x` based on the direction†
    if((c=                //   Set `c` to:
          (q=m[y].length) //    Set `q` to length of the current line
          <=x             //    Check whether `x` is out of bounds for the current line
          &(l=            //    Set `l` to:
              q>l?        //     If `q` (length of the current line) is larger than `l`:
               q          //      Set `l` to this new longest line `q`
              :           //     Else (the current line is shorter than `l`):
               l)         //      Keep `l` the same
           >x             //    Check whether this `l` is larger than `x`
             ?            //    If both these checks were truthy (so `x` is out of bounds
                          //    for the current line, but in bounds for the longest line):
              0           //     Set `c` to 0
             :            //    Else:
              m[y][x]     //     If `x` is in bounds for the current line:
                          //      Set `c` to the `x,y`'th character of the input-program
                          //     If `x` is out of bounds for the full program-block:
                          //      Stop the program with an ArrayIndexOutOfBoundsException
       )==44              //   If the current character `c` is ','
       &I<i.length)       //   and there are input-characters left:
         t[p]=            //    Set the tape-value of the current data pointer to:
              i[I         //     The current input-character (at index `I`)
                 ++];}    //     And increase index `I` by 1 afterwards with `I++`

```

`d` is used to update the `x,y`-coordinate like this:
*(I'm pretty bad at magic numbers, so both can most likely be golfed)*

| `d` | `d%2` | `d%3` | `d%3%2` | `d%3%2*2` | `d%2-d%3%2*2` | `y` |
| --- | --- | --- | --- | --- | --- | --- |
| \\$0\\$ | 0 | 0 | 0 | 0 | \\$0\\$ | `y` |
| \\$1\\$ | 1 | 1 | 1 | 2 | \\$-1\\$ | `y-1` |
| \\$2\\$ | 0 | 2 | 0 | 0 | \\$0\\$ | `y` |
| \\$3\\$ | 1 | 0 | 0 | 0 | \\$1\\$ | `y+1` |

| `d` | `-~d` | `3%-~d` | `3%-~d-d` | `~d` | `~d%2` | `3%-~d-d-~d%2` | `x` |
| --- | --- | --- | --- | --- | --- | --- | --- |
| \\$0\\$ | 1 | 0 | 0 | -1 | -1 | \\$1\\$ | `x+1` |
| \\$1\\$ | 2 | 1 | 0 | -2 | 0 | \\$0\\$ | `x` |
| \\$2\\$ | 3 | 0 | -2 | -3 | -1 | \\$-1\\$ | `x-1` |
| \\$3\\$ | 4 | 3 | 0 | -4 | 0 | \\$0\\$ | `x` |

---
Tags: code-golf, interpreter
---


title: Best Iterated Prisoner's Dilemma Move

text:
# Question
Title: Best Iterated Prisoner's Dilemma Move
## Introduction

In the prisoner's dilemma, two partners in crime are being interrogated, and have the choice to either *betray* their partner or stay silent.

* If both prisoners betray each other, they both get 2 years in prison.
* If neither betrays (both stay silent), they both get 1 year in prison.
* If only one betrays and the other stays silent, then the betrayer gets no prison time, but the other gets 3 years in prison.

In the *iterated* version of the dilemma, this situation is repeated multiple times, so the prisoners can make decisions based on the outcomes of previous situations.

## Challenge

Imagine that you are a player participating in this dilemma against an opponent.

Your opponent is described by a function \\$f: M \mapsto m\\$, where \\$m = \\{s,b\\}\\$ is the set of "moves" player can make (stay silent or betray) and \\$M = \[(m\_{1o}, m\_{1p}), (m\_{2o}, m\_{2p}), \ldots\]\\$ is a list of all the previous moves that your opponent and you made. In other words, given all the moves made in the game so far, the function outputs a new move. (Note that this is *deterministic*; also, the opponent's move can depend on its own previous moves as well as the player's.)

Your code should take as input the opponent's function \\$f\\$ and some number \\$n\\$ and return the maximum reward which the optimal player can receive within \\$n\\$ iterations (i.e. the minimum number of years that the optimal player will stay in jail). You can output this as either a positive or negative integer.

You can use any two distinct symbols to represent the two moves, and the input format for the function is flexible (e.g. it could also take in two different lists for the opponents and player's previous moves.)

Standard loopholes are forbidden. Since this is , the shortest code wins.

## Examples

(All the code examples will be in JavaScript; I will use `0` for the "stay silent" move and `1` for the "betray" move.)

If your opponent always stays silent, i.e. they are defined by the function

```
opponentFunc = (opponentMoves, playerMoves) => 0

```

Then it is in your best interest to always betray, so

```
playerFunc(opponentFunc, 1) //=> [1], reward=0
playerFunc(opponentFunc, 3) //=> [1,1,1], reward=0

```

---

Suppose your opponent employs the "tit for tat" strategy: stay silent on the first move, then does whatever the player did on the previous move. In other words, they are defined by the function

```
opponentFunc = (opponentMoves, playerMoves) => (playerMoves.length==0) ? 0 : playerMoves[playerMoves.length-1]

```

In that case the best actions to take are to stay silent until the final turn, where you betray; i.e.

```
playerFunc(opponentFunc, 1) //=> [1], reward = 0
playerFunc(opponentFunc, 3) //=> [0,0,1], reward = -2

```

Here is a recursive reference implementation in JavaScript:

reward = (opponentMove, playerMove) => [[-1,0],[-3,-2]][opponentMove][playerMove]
playerReward = (oppFunc, n, oppMoves=[], plaMoves=[], oppNextMove = oppFunc(oppMoves,plaMoves)) =>
(n==0) ? 0 : Math.max(
    reward(oppNextMove,0)+playerReward(oppFunc, n-1, oppMoves+[oppNextMove], plaMoves+[0]),
    reward(oppNextMove,1)+playerReward(oppFunc, n-1, oppMoves+[oppNextMove], plaMoves+[1])
)

//Testing
opponentFunc = (opponentMoves, playerMoves) => (playerMoves.length==0) ? 0 : playerMoves[playerMoves.length-1]
console.log(reward(opponentFunc, 5)) //=> -4
```
</code></pre>

# Answer
> 7 votes
# Haskell,  ~~96~~  89 bytes

```
a#b=3-b-2*a
(f%l)0=0
(f%l)t=min(f l#0+(f%((f l,0):l))(t-1))((f l#1+(f%((f l,1):l))(t-1)))

```

Attempt This Online!

-1 byte by Kevin Cruijssen

# Answer
> 4 votes
# JavaScript (ES6),  ~~96 92~~  90 bytes

Expects `(opponentFunc)(n)`, where `opponentFunc` takes a flat array of moves \\$\[m\_{1o},m\_{1p},m\_{2o},m\_{2p},\dots\]\\$ with \\$0\\$ for *silent* and \\$1\\$ for *betray*. Returns a positive integer.

```
F=>m=g=(n,i)=>i>>n?m:g(n,-~i,(h=M=>s=n--&&!(p=i>>n&1)+h([...M,M=F(M),p])+M*2)([])>m?0:m=s)

```

Try it online!

### Encoding

Using \\$0\\$ for *silent* and \\$1\\$ for *betray*, the outcome is defined by the following table:

| p (player) | o (opponent) | years in prison (for the player) |
| --- | --- | --- |
| 0 | 0 | 1 |
| 0 | 1 | 3 |
| 1 | 0 | 0 |
| 1 | 1 | 2 |

which is \\$o\times2+(1-p)\\$, or `o * 2 + !p` as JS code.

### Commented

```
F =>                // F = opponent function
m =                 // m = maximum outcome, initially non-numeric
g = (n, i) =>       // g is the outer recursive function,
                    // trying all possible move sequences
i >> n ?            // if i has reached the upper bound 2**n:
  m                 //   stop and return m
:                   // else:
  g(                //   do a recursive call:
    n,              //     pass n unchanged
    -~i,            //     increment i
    ( h = M =>      //     h is the inner recursive function,
                    //     testing a specific move sequence
      s =           //     save the final score in s
      n-- &&        //     if n is not 0 (decrement afterwards):
      !(p =         //       compute the player's move p,
        i >> n & 1  //       which is the n-th bit of i
      ) +           //       add not(p)
      h(            //       add the result of a recursive call:
        [ ...M,     //         update M[]
          M = F(M), //         by adding the opponent's move
                    //         (reuse M to store it)
          p         //         and the player's move
        ]           //
      ) +           //       end of recursive call
      M * 2         //       add twice the opponent's move
    )([])           //     initial call to h with M[] = []
    > m ? 0 : m = s //     update m to min(m, s)
  )                 //   end of recursive call

```

# Answer
> 3 votes
# Python, 148 bytes

```
lambda g,n:max(product((0,1),repeat=n),key=lambda i:sum([1,3,0,2][k*2+l]for k,l in zip(i,[g(i[:j])for j in range(len(i))])))
from itertools import *

```

Attempt This Online!

# Answer
> 2 votes
# Wolfram Language (Mathematica), 86 bytes

```
If[#2==0,0,Min@Table[2 #1[#3]-i+1+#0[#1,#2-1,Append[#3,{i,#1[#3]}]],{i,0,1}]]&[##,{}]&

```

Try it online!

Full version:

```
ClearAll;

reward[moves_List] := 2 moves[[2]] - moves[[1]] + 1;

(*Tit-For-Tat*)
oppFuncTFT[moves_List] := If[moves == {}, 0,
   moves[[-1, 1]]];

(*Win-Stay,Lose-Switch*)
oppFuncWSLS[moves_List] := If[moves == {}, 0,
   With[{prev = moves[[-1]], switch = Abs[# - 1] &},
    If[reward[Reverse@prev] >= reward[prev], prev[[2]],
     switch[prev[[2]]]]
    ]
   ];

totalPlayerReward[oppFunc_Symbol, n_Integer, moves_List: {}] :=
  With[{oppNextMove = oppFunc[moves]},
   If[n == 0, 0,
    Min[
     reward[{#, oppNextMove}] +
        totalPlayerReward[oppFunc, n - 1,
         Append[moves, {#, oppNextMove}]]
       & /@ {0, 1}
     ]
    ]
   ];

```

# Answer
> 1 votes
# Python, 68 bytes

```
f=lambda o,n,*M:n and min(3**o(M)-p+f(o,n-1,*M,o(M),p)for p in[0,1])

```

Attempt This Online!

The opponent function uses the same interleaved moves format as @Arnauld's answer, outputs a positive number. I used pysearch to find a compact expression for determining the reward.

---
Tags: code-golf
---