title: But, Is It Art?

text:
# Question
Title: But, Is It Art?
But Is It Art? is an esolang created by ais523, where one step is break the program into orthogonally connected "tiles":

```
A BBBB
A B  B
AA CC
A CC

```

Each separate letter shows a different tile. Interestingly, programs in But Is It Art? only rely on the orientations of the tiles themselves, not their placement. This means that the above program is functionally equivalent to

```
 CC    A
CC     A
  BBBB AA
  B  B A

```

But this isn't equivalent to

```
BBB  A
B B AA
 CC  A
  CC A

```

Or to

```
DDD A
DDD AA
 CC ABBBB
CC  AB  B

```

---

You are to take two binary rectangular matrices, \\$A\\$ and \\$B\\$. Each matrix will have zero or more "tiles" consisting of `1`s that are orthogonally connected to zero or more other `1`s. You should then output 2 distinctive consistent values that indicate whether the tiles in \\$A\\$ and \\$B\\$ are equivalent per But Is It Art?'s definition of equivalent grids.

For example,

```
A =         B =
0000111000  11000011
0110010010  10011100
0100011110  00101001
1011000001  10101111
1000000000

```

Are equivalent. If you can't see it, try replacing the `1`s with letters, similar to above, to form groups of differently lettered tiles:

```
A =         B =
0000AAA000  BB0000DD
0BB00A00A0  B00AAA00
0B000AAAA0  00C0A00A
C0DD00000E  E0C0AAAA
C000000000

```

You can assume that the matrices will always be rectangular and will only ever contain `1` and `0`. They will never be empty, but are not guaranteed to contain a `1`, or to be the same dimensions.

You may take these matrices as newline separated strings, with a non-digit, non-newline separator between them; 2D nested arrays; a string representation of a matrix; or any reasonable representation of a binary matrix. You may take input as 2 lists of integers converted from binary, representing the rows (so the example `A` above would be `[56, 402, 286, 705, 512]`)

This is , so the shortest code in bytes wins

## Test cases

| **A** | **B** | result |
| --- | --- | --- |
| ``` 1101110<br>1010010<br>0101110<br>1100000<br>1010100<br>0010101<br>1000101<br>1001110<br>0000110<br>1101011 ``` | ``` 1111100101<br>0111000111<br>0011111101<br>1010000010<br>1101010111<br>0111001010<br>1000111100<br>1100001010<br>1101001000 ``` | false |
| ``` 0110111<br>0011010<br>0101101<br>1111010<br>0101001<br>0000011<br>0100111<br>0000010<br>1101011 ``` | ``` 110000101<br>000000000<br>011011101<br>101101011<br>010110111<br>111101010<br>010100011 ``` | true |
| ``` 11111<br>01100<br>00100<br>10101<br>10010<br>01101<br>10010<br>10001<br>00110 ``` | ``` 11111011011<br>01100000100<br>10101010010<br>10101001001 ``` | true |
| ``` 010010<br>011111<br>110001<br>010001<br>010111<br>101101<br>110001<br>111111 ``` | ``` 000000<br>000000<br>000000<br>000000<br>000000<br>000000<br>000000<br>000000 ``` | false |
| ``` 10<br>01<br> ``` | ``` 1<br>0<br>1 ``` | true |
| ``` 1111111110<br>0111111101<br>1000010000<br>0010001110<br>0110011011<br>0100100010<br>0100011001 ``` | ``` 1111111110<br>0111111101<br>1000010000<br>0010001110<br>0110011011<br>0100100010<br>0100011001 ``` | true |
| ``` 1000<br>0010<br>0110 ``` | ``` 1000<br>1010<br>0001 ``` | false |

# Answer
# , 80 bytes

```
-:&(1/:~@}.(#:i.)@$<@(-"1<./)/.~&(,/)[(*[:>./(0,(,-)=0 1)|.!.0])^:_[*i.@$)&(0,])

```

Try it online!

Rather straight-forward approach.

* `&(0,])` prepend a 0-line, so the first "tile" found is always the 0s
* `[*i.@$` every 1 gets a unique index

```
0 0  0
3 4  0
0 0  8
9 0 11

```
* `[(*[:>./(0,(,-)=0 1)|.!.0])^:_` shift the board into the 4 directions, and reduce to the highest index. So each group tile will have the same index, e.g.:

```
0 0  0
4 4  0
0 0 11
9 0 11

```
* `(#:i.)@$` the coordinates of all the points `0 0, 0 1, 0 2,. 1 0, …`
* `…/.~&(,/)` flatten both lists and group the coordinates by the indices
* `<@(-"1<./)` normalize each group to `0 0`:
* `1/:~@}.` drop the first group (the 0s) and sort the rest
* `-:&` are the results for both inputs equal?
> 8 votes

# Answer
# MATL, ~~44~~ ~~43~~ ~~42~~ 39 bytes

```
,i4&1ZIXKXz!"K@=&fJ*+!t1)-]N@-$XhoXS]X=

```

Inputs: two matrices (numerical 2D arrays), using `;` as row seperator.

Output: `0` for falsy, `1` for truthy.

Try it online! Or verify all test cases.

### How it works

```
,           % Do twice
  i         %   Input: matrix
  4&1ZI     %   Label connected components formed by the value 1, using 4-connectivity.
            %   In the n-th component, 1 is replaced n
  XK        %   Copy this label matrix into clipboard K
  Xz!       %   Nonzeros as a row vector. Gives a vector containing the values 1, 2,
            %   ..., N, where N is the number of connected components and each value
            %   is repeated as many times as the size of that component
  "         %   For each n in that vector. Because of the above mentioned repetitions,
            %   several iterations will give the same result. This is inefficient but
            %   harmless
    K       %     Push label matrix
    @=&f    %     Push row and column indices of occurrences of n, as column vectors
    J*+!    %     Multiply by imaginary unit, add, transpose: combines the two column
            %     vectors into a complex row vector which describes the connected
            %     component with label n
    t1)-    %     Subtract first entry from the vector. This has the effect of
            %     normalizing the *position* of each connected component
  ]         %   End
  N         %   Push current number of elements in the stack
  @-        %   Subtract 0 in the first iteration, or 1 in the second. The result is
            %   the number of components of the latest input (in the second iteration
            %   the bottom of the stack contains a result from the previous input)
  $Xh       %   Take that many elements from the stack and combine them into a cell
            %   array. This cell array contains all row vectors of the components of
            %   the latest input. Each component is repeated as many times as the
            %   size of that component
  o         %   Convert into a matrix, right-padding with zeros if needed
  XS        %   Sort rows (atomically). This has the effect of normalizing the
            %   *order* of the components
]           % End
X=          % Are the two result matrices equal? Implicit display

```
> 8 votes

# Answer
# , 41 40 bytes

```
-:&([:/:~]-/~@#~&~.[:+./ .*^:_~1>:|@-/~)

```

Try it online!

-1 thanks to xash

This J approach was different enough that I thought it deserved its own answer.

We take input as lists of complex numbers representing the coordinates of the ones.

## the idea

1. Create an adjacency matrix of the points, using "distance \<= 1" as the criterion for "adjacent".
2. Matrix multiply by itself until a fixed point. The rows now represent the groups. Rows with the same signature of ones are items in the same group, so we take the unique of the rows.
3. Use these as masks to pick out the actual points of each group.
4. For each of these, create a "subtraction table" of every group element with every other one. This will give a unique signature for the spatial pattern of the group, which is independent of its placement within the grid.
5. Sort these tables.
6. Check if the final two results are the same.
> 6 votes

# Answer
# Jelly, 30 bytes

```
+þ2ŒRBU¤ẎQfðƬṪṢ
Wç¥€`Q1ị_Ɗ€Ṣ)E

```

Try it online!

Accepts input as a list of (1-indexed) coordinates (though it doesn't really matter).

-2 bytes thanks to caird coinheringaahing
-1 byte thanks to Nick Kennedy

This is one of the most fun challenges I've done in Jelly in a while. Thanks for the challenge :)

```
+þ2ŒRBU¤ẎQfðƬṪṢ    Helper link; given a list containing coordinates
                   ^ on the left and the list of filled coordinates
                   ^ on the right, breadth-first fill from those
                   ^ coordinates (initially accepts a singleton list
                   ^ with the starting coordinate)
+þ                 Outer product table on addition between each coordinate and
  2ŒRBU¤           (As a nilad)
  2ŒR              [-2, -1, 0, 1, 2]
     B             Binary; [[-1, 0], [-1], [0], [1], [1, 0]]
     U             Vectorizing reverse; [[0, -1], [-1], [0], [1], [0, 1]]
                   We now have the neighbors of each starting point
        Ẏ          Tighten / flatten once, since outer product table gives a 2D list
         Q         Remove duplicates
          f        Filter to only keep cells that are part of the whole grid itself
           ðƬ      Take that entire previous part and keep running it until
                   ^ the results are no longer unique (i.e. we have filled
                   ^ the whole block) (keeps intermediate values)
             Ṫ     Keep the last of these
              Ṣ    And sort it
Wç¥€`Q1ị_Ɗ€Ṣ)E     Main Link; accepts a list of two matrices
            )      For each of the matrices
    `              With this list as the left and right arguments
   €               For each coordinate
Wç¥                Wrap the coordinate into a singleton list and call the helper
                   ^ link on that with the list of coordinates on the right
     Q             Remove any duplicates
         Ɗ€        For each shape
      1ị           Get the first coordinate
        _          Subtract each coordinate
           Ṣ        Sort it
             E     Are the two results equal?

```
> 5 votes

# Answer
# JavaScript (ES10),  ~~160~~  145 bytes

*Saved 15 bytes thanks to @tsh*

Expects two binary matrices as `(a)(b)`. Returns a Boolean value.

```
a=>b=>(g=m=>m.map((r,Y)=>r.map((v,X)=>(h=(x,y,w=m[y])=>w&&w[x]?[[-1,w[x]=0,1,2].map(d=>d+h(x+d%2,y+--d%2))]:[])(X,Y))).flat(2).sort()+3)(a)==g(b)

```

Try it online!
> 4 votes

# Answer
# , 158 bytes

```
function(a,b,`+`=function(m,`?`=toString,x=seq(l=nrow(m))){for(i in x)x[K]=min(x[K<-as.matrix(dist(m))[i,]<=1]);?sort(by(m,x,function(d)?Map(rank,d)))})+a==+b

```

Try it online!

A function taking two matrices having two columns x,y with the coordinates of 1's and returning TRUE/FALSE.
The order of the coordinates must be the same in the two matrices (e.g. both sorted by column then row).

**Explanation:**

```
function(a,b){                 # matrices a and b
  G=function(m){               # define function G taking a matrix m (same format as a,b)
    x=seq(l=nrow(m))           # init x = 1...nrow of m
    for(i in x){               # for i in 1...nrow of m
      D=as.matrix(dist(m))[i,] #  compute D=euclidean distance of row i of m from all the other rows
      x[D<=1]=min(x[D<=1])     #  replace all vals of x where D<=1 with the min value of x where D<=1
    }                          # (now x contains an equal value for each group of connected tiles)
    B=by(m,x,function(d){      # for each group of connected tiles d (a sub-matrix of m)
      R=Map(rank,d))           #  compute the rank of each vector of coordinates x and y
      toString(R)              #  concat the result into one string
    }                          # (now B = list of string for each group of tiles)
    toString(sort(B))          # sort B and concat into one string
  }                            #
  G(a)==G(b)                   # if G(a) == G(b) then they have the same connected tiles pattern
}                              #

```

**Note:**

we use `function()` keyword 3 times, with the new syntax `\()` of R 4.1.0+ we can save 21 bytes, but unfortunately is not on TIO (yet).
> 2 votes

# Answer
# Charcoal, ~~151~~ 120 bytes

```
Ｆ²«≔⟦⟧θＷＳ«≔⊕Ｌκη≔⁺θＩ⪪⁺κ0¹θ»Ｆη⊞θ⁰≔⟦⟧ζＷΣθ«≔⟦⌕θ¹⟧εＦε«§≔θλ⁰Ｆ⁺λ⟦η¹±¹±η⟧¿§θμ⊞εμ»⊞ζＥε⟦⁻﹪λη﹪⌊εη÷⁻λ⌊εη⟧»≔⟦⟧θＷ⁻ζθＦ№ζ⌊κ⊞θ⌊κ⊞υθ»⁼⊟υ⊟υ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for equivalent, nothing if not. Explanation:

```
Ｆ²«

```

Process two matrices.

```
≔⟦⟧θＷＳ«

```

Start reading the matrix into a flat array.

```
≔⊕Ｌκη

```

Keep track of the width of the matrix, including a safety margin.

```
≔⁺θＩ⪪⁺κ0¹θ

```

Append the current row to the array, including a safety margin.

```
»Ｆη⊞θ⁰

```

Append a safety margin to the bottom of the array.

```
≔⟦⟧ζ

```

Start collecting the tiles.

```
ＷΣθ«

```

Repeat until all tiles have been found.

```
≔⟦⌕θ¹⟧εＦε«

```

Start a breadth-first search for the tile that includes the top leftmost `1`.

```
§≔θλ⁰

```

Mark this cell has having been collected.

```
Ｆ⁺λ⟦η¹±¹±η⟧

```

Check all orthogonally adjacent cells.

```
¿§θμ⊞εμ

```

If this cell is a `1` then collect this cell.

```
»⊞ζＥε⟦⁻﹪λη﹪⌊εη÷⁻λ⌊εη⟧

```

Convert the position of all of the elements of this tile back to coordinates, then subtract the coordinates of the first element of the tile, and save the result to the list of normalised tiles. (Note that the subtraction is consistently off by one for cells to the left of the first cell, but because it's consistent, it won't affect the comparison between tiles.)

```
»≔⟦⟧θＷ⁻ζθＦ№ζ⌊κ⊞θ⌊κ

```

Sort the list of normalised tiles.

```
⊞υθ

```

Save the sorted list.

```
»⁼⊟υ⊟υ

```

Compare the two lists of normalised tiles.
> 1 votes

---
Tags: code-golf, decision-problem, binary-matrix, pattern-matching
---


# Question
Title: Base-2 integer logarithm of 64-bit unsigned integer
**Problem:**

In your choice of language, write the shortest function that returns the floor of the base-2 logarithm of an unsigned 64-bit integer, or –1 if passed a 0. (Note: This means the return type must be capable of expressing a negative value.)

**Test cases:**

Your function must work correctly for all inputs, but here are a few which help illustrate the idea:

```
               INPUT ⟶ OUTPUT

                   0 ⟶ -1
                   1 ⟶  0
                   2 ⟶  1
                   3 ⟶  1
                   4 ⟶  2
                   7 ⟶  2
                   8 ⟶  3
                  16 ⟶  4
               65535 ⟶ 15
               65536 ⟶ 16
18446744073709551615 ⟶ 63

```

**Rules:**

1. You can name your function anything you like.
2. Character count is what matters most in this challenge.
3. You will probably want to implement the function using purely integer and/or boolean artithmetic. However, if you really want to use floating-point calculations, then that is fine so long as you call no library functions. So, simply saying `return n?(int)log2l(n):-1;` in C is off limits even though it would produce the correct result. If you're using floating-point arithmetic, you may use `*`, `/`, `+`, `-`, and exponentiation (e.g., `**` or `^` if it's a built-in operator in your language of choice). This restriction is to prevent "cheating" by calling `log()` or a variant.
4. If you're using floating-point operations (see #3), you aren't required that the return type be integer; only that that the return value is an integer, e.g., floor(log₂(n)).
5. If you're using C/C++, you may assume the existence of an unsigned 64-bit integer type, e.g., `uint64_t` as defined in `stdint.h`. Otherwise, just make sure your integer type is capable of holding any 64-bit unsigned integer.
6. If your langauge does not support 64-bit integers (for example, Brainfuck apparently only has 8-bit integer support), then do your best with that and state the limitation in your answer title. That said, if you can figure out how to encode a 64-bit integer and correctly obtain the base-2 logarithm of it using 8-bit primitive arithmetic, then more power to you!
7. Have fun and get creative!

# Answer
# C,89

Per my comment on the question, here's a quirky way to do it, inspired by this famous function: http://en.wikipedia.org/wiki/Fast\_inverse\_square\_root

```
f(uint64_t x){__float128 y=x;__int128_t i = *(__int128_t*)&y;return x?(i>>112)-16383:-1;}

```

I store the number as a float. Then to extract the exponent of the float, I cast it bitwise to an integer, rightshift the integer and subtract the bias.

Unfortunately to get the last example to run correctly, a 128 bit float is required. A 64 bit float has only 52 bits for the mantissa, so it rounds 18446744073709551615 up to 18446744073709551616 (2^64). The standard IEEE 128-bit float has a 112 bit mantissa (which we shift out and discard) and a bias of 16383 on the exponent. These are the constants you see in the function.

the requirement f(0)=-1 has to be handled with a ternary operator `?:`. Otherwise it would return -16383.

Here's a complete program using type names per GCC. I can't get it to run on visual studio or ideone at the moment, will try later.

```
#include <stdint.h>

uint64_t a;

f(uint64_t x){
  __float128 y=x;
  __int128_t i = *(__int128_t*)&y;
  return x?(i>>112)-16383:-1;
}

main(){
  scanf("%llu",&a);
  printf("%llu %d",a,f(a));
}

```
> 7 votes

# Answer
# C 40 ~~54~~

**Edit** Clever recursive trick by @Kyle - that's creative!

```
int l(uint64_t n){return n?l(n/2)+1:-1;}

```

(Previous version: That's the bare starting point - creativity level 0)

```
int l(uint64_t n){int r=-1;for(;n;n>>=1)r++;return r;}

```

Test: Ideone
> 6 votes

# Answer
# Haskell, 24 bytes

Can't come remotely close to the Golfscript answer, but I think this one in Haskell has everything else beat so far...

```
f 0= -1;f n=f(div n 2)+1

```

E.g.: Running with the test cases provided gives:

```
> map f [0,1,2,3,4,7,8,16,65535,65536,18446744073709551615]
[-1,0,1,1,2,2,3,4,15,16,63]

```
> 6 votes

# Answer
# Golfscript 7 (or 11)

```
2base,(

```

or, if you want the actual function definition:

```
{2base,(}:f

```

you can test it here.

If you consider "base" to be cheating, then add two chars for:

```
{}{2/}/,(

```
> 5 votes

# Answer
# Python 2, 26

```
t=lambda n:len(bin(n+n))-4

```

This is similar to the Python 3 answer by Tim S. However, doubling n and then subtracting 4 from the length has the advantage of working whether n is positive or zero.

If n \> 0, then doubling n adds one to the binary length, so we compensate by subtracting 4 instead of 3. On the other hand, if n = 0, then the function returns -1 as desired.
> 5 votes

# Answer
# APL (Dyalog Unicode), 7 bytes

```
⌊2⍟.5∘⌈

```

Try it online!

# APL (Dyalog Unicode), 13 bytes

```
{⍵=0:¯1⋄⌊2⍟⍵}

```

My first APL answer!

Try it online! (Courtesy of Adám.)
> 4 votes

# Answer
# GNU dc, 30 bytes

```
[_1pq]sz?d0=z[d2/d0<m]dsmxz2-p

```

Takes input from STDIN. Counts the number of times we can divide by 2.

### Test output:

```
$ for i in 0 1 2 3 4 7 8 16 65535 65536 18446744073709551615
> do echo $i | dc log.dc
> done
-1
0
1
1
2
2
3
4
15
16
63
$

```
> 3 votes

# Answer
# J, 11 chars

Uses the length of the base2 representation but for 0 it yields 1 We add the signum of the original number and subtract 2 thus getting the desired values for all n\>=0.

```
   (2-~*+#@#:) 18446744073709551615x  NB. x is for extended precision number
63

```
> 3 votes

# Answer
# Rust, 28 bytes

```
|n|63-n.leading_zeros()as i8

```

Try it on the Rust Playground!

An anonymous function that takes in a u64 and outputs the answer as an i8. Change 63 to 127 and it'll work for u128s too.
> 3 votes

# Answer
# x86\_64 machine language on Linux, ~~11~~ 8 bytes

```
0x0:  83 C8 FF          or eax, -1
0x3:  48 0F BD C7       bsf  rax, rdi
0x7:  C3                ret

```

-3 thanks to @PeterCordes

This uses the "bit scan reverse" instruction to put the index of the most significant `1` bit in `rax`. The `or eax, -1` is to handle the case of zero input. This version no longer depends on ABM or BMI1 instructions and should work on all x86\_64 processors.

To Try it online!, compile and run the following C code

```
(*f)()="\x83\xc8\xff"     // or eax, -1
       "\x48\x0f\xbd\xc7" // bsr rax, rdi
       "\xc3";            // ret

main(){
  printf("%d\n",f(0));
  printf("%d\n",f(1));
  printf("%d\n",f(2));
  printf("%d\n",f(3));
  printf("%d\n",f(4));
  printf("%d\n",f(7));
  printf("%d\n",f(8));
  printf("%d\n",f(16));
  printf("%d\n",f(65535));
  printf("%d\n",f(65536));
  printf("%d\n",f(18446744073709551615));
}

```
> 3 votes

# Answer
## Python 3, 38 bytes

```
def f(n):return(-1,len(bin(n))-3)[n>0]

```

`bin(n)` produces a string like `0b100`, so you have to subtract 3, not just 1. `(a,b)[condition]` is a trick I took from Tips for golfing in Python.
> 2 votes

# Answer
# C, 72

Using a binary split method

```
int k(uint64_t x){int i=64,r=-!x;while(i/=2)x>>i?x>>=i,r+=i:0;return r;}

```

ungolfed, unwound version with lookup table options.

```
#define USETABLE256
int msb(unsigned long long x){
    char ret = -1;

    if (x>0xFFFFFFFF){ ret+=32; x>>=32; }
    if (x>0xFFFF){ ret+=16; x>>=16; }
    if (x>0xFF){  ret+=8;  x>>=8;  }
#ifdef USETABLE256
    return ret + ((const char[256]){
 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
    })[x];
#else
    if (x>0xF){        ret+=4;  x>>=4;  }
#ifdef USETABLE16
    return ret + ((const char[16]){0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4})[x];
#else
    if (x>3){        ret+=2;  x>>=2;  }
    if (x>1){        ret+=1;  x>>=1;  }
    return ret + x;
#endif
#endif
}

```
> 2 votes

# Answer
# Befunge 93 - 23

```
1-&: v
v+1\ _$.@
>\2/:^

```

Limited by implementation to 2^31 or 32-bit signed ints. Given a 64 bit unsigned (128 bit signed?!) implementation this code meets criteria.
> 2 votes

# Answer
## TI-30XB - 19 (Instructions)

I won't actually participate in this contest with the following codes, but I found out this clever solution for my TI-30XB calculator: `log(x)/log(2)+10^12-10^12`. First of all, I wont participate because I clearly used the log function. Second, who actually has TI calculators... Third, this one's probably gonna win because its only 19 instructions. :D (Oh wow, but look at that golfscript code...) I just want to point out that there are more ways to floor a float, if any of you are interested. (For the C programmers its probably still smaller to use int's instead). By the way I am just abusing overflow handeling here. Since the TI-30XB stores floats, adding 10^12 to it will remove everything behind the dot.

## TI-BASIC - 35 bytes

This one is a actual participant, but I bet none of you can execute it... Oh well just buy a TI-84 Plus then :D

```
:PROGRAM:LOG
:0→X
:If N=0
:-1→X
:While N>1
:iPart(N/2→N
:X+1→X
:END
:X

```

You would call the function (Or programs as they are called) like this:

```
:PROGRAM:TEST
:65535→N
:prgmLOG

```

X should now contain the value 15. Also, note that the X on the end of the program can actually be removed if the program is executed using prgmLOG (As shown above), since the X at the end is only used to display the number when the function is executed via the HOME screen. Yes, `While`, `If`, `End` and `iPart(` are one instruction each.
> 2 votes

# Answer
# x87 machine code, ~~27~~ 23 bytes

Binary:

```
00000000: 9bd9 2e15 01d9 e8df 2cd9 f1df 1cad 85c0  ........,.......
00000010: 7902 f7d0 c37f 0f                        y......

```

Listing:

```
9B D9 2E 013F   FLDCW CW            ; set FPU CW register for floor rounding
D9 E8           FLD1                ; 1 * multplier into ST(1)
DF 2C           FILD QWORD PTR[SI]  ; load input into ST(0)
D9 F1           FYL2X               ; ST(0) = ST(1) * log2( ST(0) )
DF 1C           FISTP WORD PTR[SI]  ; store result into [SI]
AD              LODSW               ; result into AX
85 C0           TEST AX, AX         ; was result negative (zero divide)?
79 02           JNS  OKAY           ; if not, return result
F7 D0           NOT  AX             ; otherwise, negate AX (AL = -1)
            OKAY:
C3              RET                 ; return to caller
0F7F        CW  DW  0F7FH           ; x87 control word to round down

```

Callable function input as 64 bit signed `QWORD` at `[SI]`, output in `AL`.

Size notes: checking for Zero and returning an explicit `-1` costs 6 bytes. Also, setting FPU to floor rounding costs 7 bytes.

Input/Output from test program:
> 2 votes

# Answer
## ARMv8, ~~24~~ 12 bytes

OakSim is technically an ARMv7 simulator, but if you want to test all test cases except for the last, you can still use it as reference.

The register widths of ARMv7 are 32 bit. I haven't found a good ARMv8 simulator yet, but the instruction set is backwards compatible, and the register widths should be 64 bit long.

Hexdump:

```
0x00010000: 10 0F 6F E1 3F 00 60 E2 1E FF 2F E1             ..o.?.`.../.

```

(If you're testing on OakSim's ARMv7, here is the respective hexdump:)

```
0x00010000: 10 0F 6F E1 1F 00 60 E2 1E FF 2F E1             ..o...`.../.

```

## Explanation

This is a procedure that expects the argument in `r0`. Output goes to `r0`.

This expects the address of the caller in `lr`, as per the ATPCS (ARM Thumb Procedure Call Standard).

```
log:                  /* Name of our function */
    clz r0, r0        /* r0 = Count Leading Zeroes in r0 */
    rsb r0, r0, 63    /* r0 = 63 - r0 */
                      /* change this number to 31
                         if you're testing on ARMv7 */
    bx lr             /* Branch back to caller */

```

Example call:

```
b test         /* Skip over this procedure */
log:
               /* ommitted to save space */
test:
    mov r0, 0  /* Set input argument to e.g. 0 */
    mov lr, pc /* Set lr to address of program counter */
    b log      /* Jump to the procedure */

```
> 2 votes

# Answer
# K (ngn/k), 13 bytes

```
-1+/|\(64#2)\

```

Try it online!

Uses "The log base 2 of an integer is the same as the position of the highest bit set" as outlined here.

* `(64#2)\` encode as 64 bits
* `|\` cumulative boolean or
* `-1+/` sum and subtract one

If it's ok for an input of `0` to return `0` instead of `-1`, `#1_2\` can be used to save a byte.
> 2 votes

# Answer
# Risky, 5 bytes

```
{?+0-_?:0

```

Try it online!

Uses a built-in log2 function, but since it operates on integers, it's technically allowed.

## Explanation

```
{?+0-_?:0
{         log2(
 ?          input
  +         +
   0        0
          )
    -     -
     _    (
      ?     input
       :    =
        0   0
          )

```

# Risky, 7 bytes

```
!_?}_2-__2-:?

```

Try it online!

Doesn't use a built-in log2 function.

## Explanation

```
!_?}_2-__2-:?
!             length(
 _              (
  ?               input
                )
   }            base-convert
    _           (
     2            2
                )
              )
      -       -
       _      (
        _       (
         2        2
                )
          -     -
           :    (0 ≠
            ?     input
                )
              )

```
> 2 votes

# Answer
## Ruby, 30 bytes

```
f=->n{n>0?n.to_s(2).size-1:-1}

```

E.g.

```
irb(main):019:0> f[0]
=> -1
irb(main):024:0> f[65535]
=> 15
irb(main):025:0> f[65536]
=> 16

```
> 1 votes

# Answer
# Batch - 82

Due to language limitations, this only supports 32-bit ints

```
@set a=-2&set n=%1
:1
@set /aa=%a%+1&set /an=%n%/2&if %n% GTR 0 goto 1
echo %a%

```
> 1 votes

# Answer
# PHP - ~~50~~ 40

My final answer\* inspired by @edc65, who was inspired to do a recursive version from @Kyle

```
function l($n){return $n?l($n>>1)+1:-1;}

```

My original version before the recursive answer was this:

```
function l($n){while($n){$n>>=1;$r++;}return$r-1;}

```

\*I had to use the binary shift (\>\>) because division (/) kept making it a floating point, yielding wildy inaccurate/large answers (doing floating division until it ran out of decimal places and "became 0").
And casting to an (int) or using floor() cost more characters than the simple right shift.
> 1 votes

# Answer
# MMIX, 16 bytes (4 instrs)

Essentially the same as the C answer, except it forces round-down and therefore can use a 64-bit float.

```
00000000: 0a000300 e400c010 3d000034 f8010000  ½¡¤¡ỵ¡ĊÑ=¡¡4ẏ¢¡¡

```

```
log2    FLOTU  $0,ROUND_DOWN,$0
        INCH   $0,#C010
        SR     $0,$0,52
        POP    1,0

```
> 1 votes

# Answer
# Pxem, 56 bytes (content)

Unprintables are as backslash followed by its code point in octal.

```
.c.w\000\001\001.v.c.t.y\002.!.c.m.v\001.+.v.a.m.z\001.-XX.a.v.n.d.a.s-1.p

```

## Usage

* Call this subroutine after setting only one item as input.
* Outputs the result to STDOUT instead of returning, as Pxem cannot have negative values unless given from STDIN.
* Some garbages may return.

## With comments

```
XX.z
# if top is not zero; then
.c.wXX.z
  # stack usage: input, 2^counter, counter(initially zero)
  .a\000\001\001.v.c.tXX.z
  # while input is greater than 2^counter; do
  .a.yXX.z
    # increment counter; done
    .a\002.!.c.m.v\001.+.v.aXX.z
  # if input differs from 2^counter; then decrement counter; fi
  .a.m.z\001.-XX.aXX.z
  # output counter; return
  .a.v.n.dXX.z
# done; output minus one
.a.a.s-1.p

```

Try it online!
> 1 votes

# Answer
# Jelly, 5 bytes

```
BL’_¬

```

Try it online!

## Explanation

```
BL’_¬ Main monadic link
B     Convert to binary
 L    Length
  ’   Decrement
   _  Subtract
    ¬   the argument negated

```
> 1 votes

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

```
n=>n?1+f(n/2n):-1

```

Try it online!

Similar
> 1 votes

# Answer
# PowerShell Core, 38 bytes

```
param($a)for(;$a){$a=$a-shr1;$i++}$i-1

```

Try it online!

With a filter for 39 bytes

Longer and incorrect results with the built-ins :eyes:

## Explanation

```
param($a)for(;$a){ # while a is not 0
$a=$a-shr1         # shift right by 1 the bits of a
$i++}              # increases the counter i by 1
$i-1               # outputs the counter minus one

```
> 1 votes

# Answer
# Julia, 23 bytes

```
!x=ndigits(2x,base=2)-2

```

Try it online!

based on mathmandan's answer
> 1 votes

# Answer
# Wolfram Language (Mathematica), 21 bytes

```
If[#<1,-1,#0[#/2]+1]&

```

Try it online!
> 1 votes

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


title: US Tax Due Dates

text:
# Question
Title: US Tax Due Dates
# Introduction

In a standard\* (e.g. not 2020) tax year, estimated payments are due quarterly according to the schedule outlined in Publication 505.

| Payment Period | Due Date |
| --- | --- |
| January 1 – March 31 | April 15 |
| April 1 – May 31 | June 15 |
| June 1 – August 31 | September 15 |
| September 1 – December 31 | January 15 |

* Saturday, Sunday, holiday rule, fiscal year taxpayers, and January payment exceptions can be ignored for the purpose of this question; use the standard table provided.

# Challenge

Input:

A date/timestamp, either provided as input to your solution (function parameter or stdin) as a string (at a minimum specifying a specific year, month, an day of month) or native `Date` object (or equivalent) or the current (dynamically updated) date/time based on the clock of the executing machine.

Output:

The most specific payment period, one of `Q1`, `Q2`, `Q3`, or `Q4` as a string, either printed to stdout/console or programmatically returned from the function, to which a timely payment made on the input date would be applied.

| Input | Output |
| --- | --- |
| January 16 - April 15 | Q1 |
| April 16 - June 15 | Q2 |
| June 16 - September 15 | Q3 |
| September 16 - January 15 | Q4 |

A day shall commence at 00:00 (midnight) and cover time periods up to but not including 00:00 (midnight) of the following day. The last moment of a given day, to a ms granularity is `23:59:59.999`.

# Answer
# JavaScript (ES6), 53 bytes

Expects a string in `"DD-MM-YYYY"` format.

```
s=>"Q"+"4243131"[[d,m]=s.split`-`,(m*24|d>15)*9%23%7]

```

Try it online!

---

### 39 bytes

If we can just take the month and the day.

```
m=>d=>"Q"+"4243131"[(m*24|d>15)*9%23%7]

```

Try it online!

---

### 35 bytes

As suggested by @ovs, using a larger lookup table with a much simpler formula is actually shorter.

```
m=>d=>"Q"+"_4111223334444"[m+=d>15]

```

Try it online!
> 6 votes

# Answer
# Retina 0.8.2, ~~72~~ 63 bytes

```
\d+
$*
1+-(1{1,5}(1)*)-1{1,15}(1)*
11$3$2$1
(111)*1+
Q$#1
0|5
4

```

Try it online! Link includes test cases. Takes input in `YYYY-MM-DD` format. Explanation:

```
\d+
$*

```

Convert to unary.

```
1+-(1{1,5}(1)*)-1{1,15}(1)*
11$3$2$1

```

Add 2, 3 or 4 to the month depending on whether the month is greater than 5 or the day is greater than 15 or not.

```
(111)*1+
Q$#1

```

Subtract 1 from the month, then integer divide it by 3 and prefix Q to the result. (This is to avoid zero width matches.)

```
0|5
4

```

Change `Q0` and `Q5` to `Q4`.
> 2 votes

# Answer
# , ~~65~~ 62 bytes

```
function(d)paste0("Q",1+sum(c(3,5,8)<el(format(d-15,"%m"):1)))

```

Try it online!

Expects input in R's native Date class. Subtract 15 days from the input, extract the month (as a string such as `"04"`), and convert to numeric with `el(...:1)` (see this tip). We then get the result by adding 1 for each of the values 3, 5, and 8 which are smaller than the result.
> 1 votes

# Answer
# Charcoal, 28 bytes

```
≔Ｉ⪪Ｓ-θ§12344÷⁻§θ¹⁺›¹⁶⊟θ›⁶⊟θ³

```

Try it online! Link is to verbose version of code. Takes input in the form `YYYY-MM-DD`. Explanation:

```
≔Ｉ⪪Ｓ-θ

```

Input the date, split it on `-` and cast to integer.

```
§12344÷⁻§θ¹⁺›¹⁶⊟θ›⁶⊟θ³

```

Take the month, subtract 1 each if the day is less than 16 or the month is less than 6, divide by 3, then cyclically index into the string `12344`, thus casting `-1` and `4` to `4`.
> 0 votes

# Answer
# Python 3.8 (pre-release), 109 bytes

```
lambda n,i=int:'Q'+['?111223334444'[i(k:=(S:=n.split('-'))[1])],'1234'[i(k)//3-1]][k in'1469'and(i(S[0])<16)]

```

Try it online!

Way too long.

The OP has confirmed very kindly that this is the only solution of mine which is valid.
> 0 votes

---
Tags: code-golf, date
---


title: Ordinary Least Squares Regression

text:
# Question
Title: Ordinary Least Squares Regression
I am quite surprised that a variant of linear regression has been proposed for a challenge, whereas an estimation via ordinary least squares regression has not, despite the fact the this is arguably the most widely used method in applied economics, biology, psychology, and social sciences!

For details, check out the Wikipedia page on OLS. To keep things concise, suppose one has a model:

$$Y=\beta\_0+\beta\_1X\_1+\beta\_2X\_2+\dots+\beta\_kX\_k+U$$

where all right-hand side *X* variables—regressors—are linearly independent and are assumed to be exogenous (or at least uncorrelated) to the model error *U*. Then you solve the problem

$$\min\_{\beta\_0,\dots,\beta\_k}\sum\_{i=1}^n\left(Y\_i-\beta\_0-\beta\_1X\_1-\dots-\beta\_kX\_k\right)^2$$

on a sample of size *n*, given observations

$$\left(\begin{matrix}Y\_1&X\_{1,1}&\cdots&X\_{k,1}\\\vdots&\vdots&\ddots&\vdots\\Y\_n&X\_{1,n}&\cdots&X\_{k,n}\end{matrix}\right)$$

The OLS solution to this problem as a vector looks like

$$\hat{\beta}=(\textbf{X}'\textbf{X})^{-1}(\textbf{X}'\textbf{Y})$$

where **Y** is the first column of the input matrix and **X** is a matrix made of **a column of ones** and remaining columns. This solution can be obtained via many numerical methods (matrix inversion, QR decomposition, Cholesky decomposition etc.), so pick your favourite!

*Of course, econometricians prefer slightly different notation, but let’s just ignore them.*

Non other than Gauss himself is watching you from the skies, so do not disappoint one of the greatest mathematicians of all times and write the shortest code possible.

## Task

Given the observations in a matrix form as shown above, estimate the coefficients of the linear regression model via OLS.

## Input

A matrix of values. The first column is always `Y[1], ..., Y[n]`, the second column is `X1[1], ..., X1[n]`, the next one is `X2[1], ..., X2[n]` etc. **The column of ones is not given** (as in real datasets), **but you have to add it first in order to estimate** `beta0` (as in real models).

**NB.** In statistics, regressing on a constant is widely used. This means that the model is `Y = b0 + U`, and the OLS estimate of `b0` is the sample average of `Y`. In this case, the input is just a matrix with one column, `Y`, and it is regressed on a column of ones.

You can safely assume that the variables are not exactly collinear, so the matrices above are invertible. In case your language cannot invert matrices with condition numbers larger than a certain threshold, state it explicitly, and provide a unique return value (that cannot be confused with output in case of success) denoting that the system seems to be computationally singular (`S` or any other unambiguous characters).

## Output

OLS estimates of `beta_0, ..., beta_k` from a linear regression model in an unambiguous format or an indication that your language could not solve the system.

## Challenge rules

* I/O formats are flexible. A matrix can be several lines of space-delimited numbers separated by newlines, or an array of row vectors, or an array of column vectors etc.
* This is , so shortest answer in bytes wins.
* Built-in functions are **allowed** as long as they are tweaked to produce a solution given the input matrix as an argument. That is, the two-byte answer `lm` in **R** is **not** a valid answer because it expects a different kind of input.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs.
* Default loopholes are forbidden.

## Test cases

1. `[[4,5,6],[1,2,3]]` → output: `[3,1]`. Explanation: **X** = \[\[1,1,1\], \[1,2,3\]\], **X'X** = \[\[3,6\],\[6,14\]\], inverse(**X'X**) = \[\[2.333,-1\],\[-1,0.5\]\], **X'Y** = \[15, 32\], and inverse(**X'X**)⋅**X'Y**=\[3, 1\]
2. `[[5.5,4.1,10.5,7.7,6.6,7.2],[1.9,0.4,5.6,3.3,3.8,1.7],[4.2,2.2,3.2,3.2,2.5,6.6]]` → output: `[2.1171050,1.1351122,0.4539268]`.
3. `[[1,-2,3,-4],[1,2,3,4],[1,2,3,4.000001]]` → output: `[-1.3219977,6657598.3906250,-6657597.3945312]` or `S` (any code for a computationally singular system).
4. `[[1,2,3,4,5]]` → output: `3`.

**Bonus points** (to your karma, not to your byte count) if your code can solve very ill-conditioned (quasi-multicollinear) problems (e. g. if you throw in an extra zero in the decimal part of `X2[4]` in Test Case 3) with high precision.

**For fun:** you can implement estimation of standard errors (White’s sandwich form or the simplified homoskedastic version) or any other kind of post-estimation diagnostics to amuse yourself if your language has built-in tools for that (I am looking at you, R, Python and Julia users). In other words, if your language allows to do cool stuff with regression objects in few bytes, you can show it!

# Answer
# , 34 bytes

```
function(x)try(lm(V1~.,x,si=F)$co)

```

Try it online!

Notes:

* Takes input as a data frame (which is what `lm` expects)
* `lm` would in principle work even without formula with input of indicated format, but it is needed for the constant regression case
* `si=F`, short for `singular.ok=FALSE` throws an error for singular case, which is then caught by `try`, eventually returning nothing and printing the error as debug info. Otherwise, the regression would actually return some output, but not the expected one.
> 11 votes

# Answer
# MATL, ~~18 15~~ 10 bytes

```
llZ(GlZ)Y\

```

Basically works the same as my Octave program. Thanks for -5 bytes @LuisMendo! This improvement was achieved by inputting the ones directly into the input instead of deleting a column and concatenating another one as well as some reordering of the steps.

**Explanation**

```
ll            push two ones for later use in the next line
  Z(          implicitly take the input and plug in all ONES in to the FIRST column
    Gl        push input again, push a one for use in the next line
      Z)      get the FIRST column of the input matrix
        Y\    multiply this column with the pseudo inverse of the matrix from the beginnign

```

Try it online!
> 5 votes

# Answer
# Octave, ~~41 33~~ 32 bytes

The whole magic happens at the `\`: This operator left multiplies the second argument with the inverse of the first. If there is no inverse, it uses a suitable pseudo inverse. `x(:,1)` extracts the first column \\$ Y \\$ and `[x(:,1).^0,...]` adds a column of ones to the remaining part \\$ X \\$ such that we also get the intercept `beta0`.

Thanks @LuisMendo for -1 byte!

```
@(x)[(t=x(:,1)).^0,x(:,2:end)]\t

```

Try it online!
> 4 votes

# Answer
# Julia 1.0, 30 bytes

Adapted from @flawr

```
!x=[(t=x[1]).^0 x[2:end]...]\t

```

Try it online!
> 1 votes

---
Tags: code-golf, matrix, statistics
---


# Question
Title: Random Prisoner's Trilemma - Python 3 KOTH
The Prisoner's Dilemma, but with 3 choices, and the payoffs are random!

Each round, your bot recieves a 3x3 grid and chooses a row to play. The grid might be this:

```
4  5  7
3  1  9
9  9  0

```

Each number in the grid is between 0 and 10 (inclusive). Your score for the round is `grid[your_play][their_play]`, and your opponent's is `grid[their_play][your_play]`. You play 100(+/-10) rounds in sequence, keeping any information you wish. The winner is the bot with a higher score at the end (draws are 0.5 wins for both bots).

## Example

Using the grid above:

Player 1: row 2

Player 2: row 2

Both players get 0 points.

---

Player 1: row 1

Player 2: row 0

Player 1 gets 3 points, Player 2 gets 5 points.

# Winning

Each bot will play 10 games of ~100 rounds against each bot (including itself!). Your bot can win in two categories:

* **Score:** the total scores will be summed and the bot with the most points at the end will win.
* **Wins:** a 'win' is counted for the bot with the highest score after the ~100 rounds have been played.

The overall winner will be determined by combining the two tables. A winner will be accepted about 1 week after the most recent entry, but I will probably continue to update the highscore table if new entries are added.

# Technical details

Write two functions in Python 3 with these signatures:

```
def strategize(grid: list[list[int]], store: object) -> int

```

```
def interpret(grid: list[list[int]], moves: tuple(int, int), store: dict) -> None

```
* `strategize` is called each round and should return `0`, `1`, or `2`.
    + `grid` is the 3x3 grid of possible payouts.
    + `store` is an empty dict to store any kind of information you'd like to.
* `interpret` is called after every round.
    + `moves` is a tuple containing (`your_move`, `opponents_move`)

Put your code in the first code block in your answer so the controller can easily pull in your bot.

## Example bots

'Naiive' chooses the row with the highest average payout.

```
def strategize(grid, store):
    sums = [(sum(x), i) for (i, x) in enumerate(grid)]
    return max(sums)[1]

def interpret(grid, moves, store):
    pass

```

'Random' picks a random row.

```
import random

def strategize(grid, store):
    return random.randint(0, 2)

def interpret(grid, moves, store):
    pass

```

# Rules

* No cheating by interfering directly with your opponent (through global variables etc.).
* Your function should be relatively quick to execute - the quicker it is, the better.
* You *may* submit multiple entries.

# Controller, arena

**The controller is available at https://github.com/Nucaranlaeg/KOTH-random-prisoner.**

This controller is largely adapted from https://github.com/jthistle/KOTH-counting.

A couple of example bots are provided along with it to demonstrate how to use it.

`arena.py` is what I'll be using to calculate final scores. It pits each bot against each other bot.

`update.py` will fetch all submitted bots from the contest page.

Using the flag `--c` or `-constant` will cause games to be played without randomizing the grid between rounds, purely for interest's sake.

# Current Results

```
By score:
1: Blendo with 12237.8 points
2: The Student with 11791.8 points
3: Naiive with 11728.2 points
4: Analyst with 11591.9 points
5: Min-Maxer with 11155.3 points
6: Rafaam with 11041.1 points
7: Naive Variation with 10963.1 points
8: Villain with 10853.6 points
9: Gradient-Mehscent with 10809.8 points
10: Gentleman with 10715.1 points
11: WhatDoYouExpect with 10676.6 points
12: Thief with 9687.6 points
13: Minimum Maximizer with 9656.0 points
14: HermitCrab with 9654.5 points
15: crab with 9001.9 points
16: Investigator with 8698.0 points
17: Random with 8653.3 points

By wins:
1: The Student with 15.2/16 wins
2: Blendo with 14.8/16 wins
3: Rafaam with 14.1/16 wins
4: WhatDoYouExpect with 13.9/16 wins
5: Naiive with 11.3/16 wins
6: Analyst with 10.8/16 wins
7: Min-Maxer with 10.4/16 wins
8: Naive Variation with 8.1/16 wins
9: Villain with 8.1/16 wins
10: HermitCrab with 7.3/16 wins
11: crab with 6.4/16 wins
12: Thief with 5.1/16 wins
13: Minimum Maximizer with 3.9/16 wins
14: Gradient-Mehscent with 1.9/16 wins
15: Investigator with 1.6/16 wins
16: Random with 1.5/16 wins
17: Gentleman with 1.5/16 wins

Combined leaderboard (fewer pts = better):
1: Blendo  (3 pts)
1: The Student  (3 pts)
3: Naiive  (8 pts)
4: Rafaam  (9 pts)
5: Analyst  (10 pts)
6: Min-Maxer  (12 pts)
7: Naive Variation  (15 pts)
7: WhatDoYouExpect  (15 pts)
9: Villain  (17 pts)
10: Gradient-Mehscent  (23 pts)
11: Thief  (24 pts)
11: HermitCrab  (24 pts)
13: Minimum Maximizer  (26 pts)
13: crab  (26 pts)
15: Gentleman  (27 pts)
16: Investigator  (31 pts)
17: Random  (33 pts)

```

# Answer
> 4 votes
# Blendo

Performs approximate bayesian inference over mixtures of different opponent strategies, and optimizes the chosen move with respect to the resulting prediction. Optimizes for expected score when ahead, and score difference when behind or almost equal. Also implements self-recognition. Requires NumPy.

```
import random
import numpy as np

def nash(grid):
    payoffs = regrets = zeros = np.zeros(3)
    strategy = np.full((3,), 1. / 3)
    for _ in range(10):
        payoffs = np.dot(grid, strategy)
        v = np.dot(strategy, payoffs)
        regrets = np.maximum(regrets + payoffs - v, zeros) + 1e-9
        strategy = regrets / regrets.sum()
    return strategy

def max_strategy(f):
    def get_strategy(grid):
        values = f(grid)
        strategy = values == np.max(values)
        return strategy / np.sum(strategy)
    return get_strategy

expected = max_strategy(lambda grid: np.sum(grid, axis=1))
maximin = max_strategy(lambda grid: np.min(grid, axis=1))
maxidiag = max_strategy(np.diag)

def strategize(grid, store):
    if not store:
        store['is_me'] = True
        store['side'] = 0
        store['means'] = np.array([0.73336847, -0.38686278, -0.48677562, 0.09995684, -0.06624643, 0.38667801, -0.55640674, -0.1005102])
        store['stds'] = np.array([1.6364209, 0.9467514, 0.79119316, 1.54119291, 1.44484517, 1.73075995, 0.8261992, 0.7124938])
        store['score_delta'] = 0
    grid = np.array(grid)
    delta_grid = grid - grid.T
    predictions = np.array([np.full(3, 1./3), nash(grid), nash(delta_grid), expected(grid), expected(delta_grid), maximin(grid), maximin(delta_grid), maxidiag(grid)]).T
    weights = np.exp(np.random.normal(store['means'], store['stds']))
    weights /= np.sum(weights)
    probabilities = np.dot(predictions, weights)
    store['predictions'] = predictions
    if store['is_me']:
        l, r = max(((i, j) for i in range(3) for j in range(i + 1)), key=lambda t: grid[t[0]][t[1]] + grid[t[1]][t[0]])
        store['sides'] = (l, r)
        if store['side'] == -1:
            return l
        if store['side'] == 1:
            return r
        return random.choice((l, r))
    if store['score_delta'] <= 5:
        grid = delta_grid
    else:
        grid = grid - 1e-9 * grid.T
    return int(np.argmax(np.dot(grid, probabilities)))

def interpret(grid, moves, store):
    predictions = store['predictions'][moves[1]]
    store['score_delta'] += grid[moves[0]][moves[1]] - grid[moves[1]][moves[0]]
    params = np.random.normal(store['means'], store['stds'], (200, 8))
    weights = np.exp(params)
    weights = weights / weights.sum(axis=1, keepdims=True)
    likelihood = np.dot(weights, predictions)
    c = 1. / np.mean(likelihood)
    store['means'] = c * (likelihood[:,None] * params).mean(axis=0)
    store['stds'] = np.sqrt(c * (likelihood[:,None] * (params - store['means'][None,:]) ** 2).mean(axis=0))
    if store['is_me']:
        l, r = store['sides']
        if moves[1] not in (l, r):
            store['is_me'] = False
        else:
            if store['side'] == 0:
                if l != r and moves[0] != moves[1]:
                    if moves[0] == l:
                        store['side'] = -1
                    else:
                        store['side'] = 1
            else:
                if store['side'] == -1 and moves[1] != r:
                    store['is_me'] = False
                elif store['side'] == 1 and moves[1] != l:
                    store['is_me'] = False

```

# ~~Switcheroo~~ No longer Competing

Switches between a few different strategies based on expected performance. Also implements self-recognition to maximally cooperate with itself.

```

import random

def sample(distribution):
    u = random.random()
    for i, p in enumerate(distribution):
        u -= p
        if u <= 0:
            break
    return i

def nash(grid):
    grid = [[grid[i][j] for j in range(3)] for i in range(3)]
    payoffs = [0] * 3
    regrets = [0] * 3
    strategy = [1. / 3] * 3
    for i in range(10):
        for a in range(3):
            payoffs[a] = sum(p * v for p, v in zip(strategy, grid[a]))
        v = sum(p * v for p, v in zip(strategy, payoffs))
        regrets = [max(r + q - v, 0) for r, q in zip(regrets, payoffs)]
        total_regret = sum(regrets)
        if total_regret == 0:
            strategy = [1. / 3] * 3
        else:
            c = 1. / total_regret
            strategy = [r * c for r in regrets]
    return strategy

def expected(grid):
    values = [(sum(row), -sum(col)) for row, col in zip(grid, zip(*grid))]
    v_max = max(values)
    strategy = [int(v == v_max) for v in values]
    c = 1. / sum(strategy)
    return [p * c for p in strategy]

def strategize(grid, store):
    if not store:
        store['outcomes'] = [[1. / 11 for _ in range(11)] for _ in range(2)]
        store['round_number'] = 0
        store['is_me'] = True
        store['side'] = 0
    scores = [max(sum(i * n for i, n in enumerate(a)) / sum(a) for a in (a0, [random.gammavariate(n, 1) for n in a0])) for a0 in store['outcomes']]
    strategy = scores.index(max(scores))
    nash_strategy = nash(grid)
    expected_strategy = expected(grid)
    store['strategies'] = [nash_strategy, expected_strategy]
    if store['is_me']:
        l, r = max(((i, j) for i in range(3) for j in range(i + 1)), key=lambda t: grid[t[0]][t[1]] + grid[t[1]][t[0]])
        store['sides'] = (l, r)
        if store['side'] == -1:
            return l
        if store['side'] == 1:
            return r
        return random.choice((l, r))
    return sample(store['strategies'][strategy])

def interpret(grid, moves, store):
    for i, s in enumerate(store['strategies']):
        for a, p in enumerate(s):
            v = grid[a][moves[1]]
            store['outcomes'][i][v] += p
    if store['is_me']:
        l, r = store['sides']
        if moves[1] not in (l, r):
            store['is_me'] = False
        else:
            if store['side'] == 0:
                if l != r and moves[0] != moves[1]:
                    if moves[0] == l:
                        store['side'] = -1
                    else:
                        store['side'] = 1
            else:
                if store['side'] == -1 and moves[1] != r:
                    store['is_me'] = False
                elif store['side'] == 1 and moves[1] != l:
                    store['is_me'] = False
    store['round_number'] += 1

```

# Answer
> 5 votes
# crab

crab wants everyone to die. crab is happy when everyone else is unhappy. Yes, crab is back.

```
def strategize(grid, store):
    aa = grid[0][0] #aa means '0-0'.
    ab = grid[1][0] #and similarly for the others.
    ac = grid[2][0]
    ba = grid[0][1]
    bb = grid[1][1] #I wish I had a macro to do this.
    bc = grid[2][1]
    ca = grid[0][2]
    cb = grid[1][2]
    cc = grid[2][2]
    a = (aa * ab * ac)/3 # a, b, and c are the respective averages.
    b = (ba * bb * bc)/3
    c = (ca * cb * cc)/3
    if a <= min(b, c):
        return 0
    if b <= min(a, c):
        return 1
    return 2

def interpret(grid, moves, store):
    pass

```

Specifically, it picks the value that hurts the opponent the most.

# Answer
> 4 votes
# Analyst

```
def strategize(grid, store = None):
    nonzero = [a for a in range(3)]
    if len([a for a in grid if not 0 in a]):
        maximum = max(nonzero, key=lambda index: sum(grid[index]) if not 0 in grid[index] else 0)
        if max(grid[maximum]) > 5:
            return maximum
        else:
            return max(nonzero, key=lambda arr: max(grid[arr]))
    return __import__('random').randint(0, 2)
def interpret(grid, moves, store):
    pass

```

Try it online with sample test cases

Analyst is a bot that tries to find the highest average out of nonzero possibilities, if the maximum is not high enough, then look for the index with the highest maximum. If all sublists have zeroes, choose randomly.

# Answer
> 4 votes
# WhatDoYouExpect

```
def strategize(grid, store):
    expected = [0] * 3
    for my_play in range(3):
        for opponent_play in range(3):
            expected[my_play] += grid[my_play][opponent_play] - grid[opponent_play][my_play]
    return expected.index(max(expected))

def interpret(grid, moves, store):
    pass

```

Try it online!

Always plays the move with the maximum expected value.

# Answer
> 4 votes
# Investigator

Plays naive and tit-for-tat for a few rounds, then investigates opponent responses every few rounds to find any adversarial responsive strategies. Following this, it assembles the best countermoves into a graph and executes the most positive cycle. Should be good versus both naive non-responsive opponents and basic responsive adversaries.

**EDIT: In retrospect, the original problem randomizes the scoring grid after each round, which breaks this solution. This would likely do well if the scoring grid isn't randomized though.**

```
def naive(grid):
    return max((sum(grid[move][opp]-grid[opp][move] for opp in range(3)), move) for move in range(3))[1]

def strategize(grid, store):
    if not store:
        store["round"] = 0
        store["responses"] = []
        store["sequence"] = None
    if store["round"] == 0:
        return naive(grid)
    elif store["round"] < 6:
        return store["responses"][-1][1]
    else:
        return store["sequence"][store["round"]%len(store["sequence"])]

def most_common(lst):
    return max(set(lst), key=lst.count)

def recursive_evaluate(start, trail, opponent, response, depth):
    if depth == 6:
        return trail
    trail[0].append(opponent[trail[1][-1]] if len(trail[1]) > 0 else opponent[start])
    trail[1].append(response[trail[1][-1]] if len(trail[1]) > 0 else start)
    return recursive_evaluate(start, trail, opponent, response, depth+1)

def interpret(grid, moves, store):
    store["responses"].append(moves)
    if store["round"] % 6 == 6-1:
        filtered = [[store["responses"][i+1][1] for i in range(store["round"]) if store["responses"][i][0] == me] for me in range(3)]
        default = naive(grid)
        opponent = [most_common(filtered[me]) if len(filtered[me])>0 else default for me in range(3)]
        response = [max((grid[move][opponent[me]]-grid[opponent[me]][move], move) for move in range(3))[1] for me in range(3)]
        evaluate = [recursive_evaluate(start, [[], []], opponent, response, 0) for start in range(3)]
        scoring = [(sum(grid[evaluate[start][1][i]][evaluate[start][0][i]] for i in range(len(evaluate[start][1])))-sum(grid[evaluate[start][0][i]][evaluate[start][1][i]] for i in range(len(evaluate[start][1]))), evaluate[start][1]) for start in range(3)]
        store["sequence"] = max(scoring)[1]
    store["round"] += 1

```

# Answer
> 3 votes
# Min-Maxer

```
def strategize(grid, store):
    max_best_moves = []
    max_best_move_score = float("-inf")

    for my_move in range(3):
        worst_score = min(grid[my_move])
        if worst_score == max_best_move_score: max_best_moves.append(my_move)
        elif worst_score > max_best_move_score:
            max_best_move_score = worst_score
            max_best_moves = [my_move]

    min_best_moves = []
    min_best_move_score = float("inf")

    for my_move in range(3):
        opp_best_score = max(grid[opp_move][my_move] for opp_move in range(3))
        if opp_best_score == min_best_move_score: min_best_moves.append(my_move)
        elif opp_best_score < min_best_move_score:
            min_best_move_score = opp_best_score
            min_best_moves = [my_move]

    best_of_both = [move for move in max_best_moves if move in min_best_moves]
    if best_of_both: return best_of_both[0]
    return max_best_moves[0]

def interpret(grid, moves, store): pass

```

Checks for moves that both maximize the worst case for itself and minimize the best case for its opponent. If there aren't any that are both at once, then it prefers moves that give itself points over sabotaging the opponent.

# Answer
> 2 votes
# Thief

This person is a master pickpocket of credit cards that have expired.

```
def strategize(grid, store):
    if not store:
        store['opmove'] = 3
    if store['opmove'] == 3:
      sums = [(sum(x), i) for (i, x) in enumerate(grid)]
      return max(sums)[1]
    elif grid[store['mymove']][store['opmove']] > grid[store['opmove']][store['mymove']]:
      sums = [(sum(x), i) for (i, x) in enumerate(grid)]
      return max(sums)[1]
    else:
      return store['opmove']

def interpret(grid, moves, store):
    store['opmove'] = moves[1]
    store['mymove'] = moves[0]

```

The idea is that if it's the first round, it'll act like naiive, if it won the last round, it'll act like naiive, but if it lost the last round, it'll unconditionally return the opponents move. It isn't very smart. Please provide recommendations and bug fixes.

v1.0

* Initial write

v1.1

* Rewrote some to use store rather than plain global variables.

# Answer
> 2 votes
# Naive Variation

Naive works well, try to fight against aggressive players by choosing rows where every value has a reasonable payout (i.e. where several means are comparable, prefer rows with lower standard deviation)

```
def std_dev(numbers):
    wgt = 1 / len(numbers)
    mean = sum(numbers) * wgt
    sqdiff_wgt = wgt * sum((number - mean) ** 2 for number in numbers)
    return sqdiff_wgt ** 0.5

def strategize(grid, store=None):
    bestScore = 0
    bestIdx = -1
    for ii, row in enumerate(grid):
        rowSum = sum(row)
        # Avoid numeric inflation
        std = max(std_dev(row), 1)
        score = rowSum/std
        if score > bestScore:
            bestScore = score
            bestIdx = ii

    return bestIdx

def interpret(grid, moves, store):
    pass

```

# Answer
> 1 votes
# Gentleman

This one is kind, and assumes everyone else is too. Optimizes for the opponent being Gentleman and picks the highest scoring option along the diagonal.

```
def strategize(grid, store = None):
    nums = [0,1,2]
    winner = 0
    score = -1
    for i in nums:
        if grid[i][i] > score:
            winner = i
            score = grid[i][i]
    return winner

def interpret(grid, moves, store):
    pass

```

# Answer
> 1 votes
# Gradient-Mehscent

It uses a terrible method of maximizing the score.

```
weightA = 1
weightB = 1

def strategize(grid, store):
    global weightA, weightB
    aa = grid[0][0] #aa means '0-0'.
    ab = grid[1][0] #and similarly for the others.
    ac = grid[2][0]
    ba = grid[0][1]
    bb = grid[1][1] #I wish I had a macro to do this.
    bc = grid[2][1]
    ca = grid[0][2]
    cb = grid[1][2]
    cc = grid[2][2]

    dd = grid[0][0]
    de = grid[0][1]
    df = grid[0][2]
    ed = grid[1][0]
    ee = grid[1][1] #autocorrect is annoying
    ef = grid[1][2]
    fd = grid[2][0]
    fe = grid[2][1]
    ff = grid[2][2]

    a = (aa + ab + ac)/3 # a, b, c, d, e, and f are the respective averages.
    b = (ba + bb + bc)/3
    c = (ca + cb + cc)/3
    d = (dd + de + df)/3
    e = (ed + ee + ef)/3
    f = (fd + fe + ff)/3
    scoreOfZero = (weightA * a + weightB * d)/2
    scoreOfOne = (weightA * b + weightB * e)/2
    scoreOfTwo = (weightA * c + weightB * f)/2
    if scoreOfZero >= max(scoreOfOne, scoreOfTwo):
      return 0
    if scoreOfOne >= max(scoreOfZero, scoreOfTwo):
      return 1
    return 2

def interpret(grid, moves, store):
    aa = grid[0][0] #aa means '0-0'.
    ab = grid[1][0] #and similarly for the others.
    ac = grid[2][0]
    ba = grid[0][1]
    bb = grid[1][1] #I wish I had a macro to do this.
    bc = grid[2][1]
    ca = grid[0][2]
    cb = grid[1][2]
    cc = grid[2][2]

    dd = grid[0][0]
    de = grid[0][1]
    df = grid[0][2]
    ed = grid[1][0]
    ee = grid[1][1] #autocorrect is annoying
    ef = grid[1][2]
    fd = grid[2][0]
    fe = grid[2][1]
    ff = grid[2][2]

    a = (aa + ab + ac)/3 # a, b, c, d, e, and f are the respective averages.
    b = (ba + bb + bc)/3
    c = (ca + cb + cc)/3
    d = (dd + de + df)/3
    e = (ed + ee + ef)/3
    f = (fd + fe + ff)/3
    global weightA, weightB
    simWeightA = weightA + 0.01
    simWeightB = weightB + 0.01
    simScoreOfZero = (simWeightA * a + simWeightB * d)/2
    simScoreOfOne = (simWeightA * b + simWeightB * e)/2
    simScoreOfTwo = (simWeightA * c + simWeightB * f)/2
    if simScoreOfZero >= max(simScoreOfOne, simScoreOfTwo):
      upupscore = grid[0][moves[1]]
    elif simScoreOfOne >= max(simScoreOfZero, simScoreOfTwo):
      upupscore = grid[1][moves[1]]
    else:
      upupscore = grid[2][moves[1]]

    simWeightA = weightA + 0.01
    simWeightB = weightB - 0.01
    simScoreOfZero = (simWeightA * a + simWeightB * d)/2
    simScoreOfOne = (simWeightA * b + simWeightB * e)/2
    simScoreOfTwo = (simWeightA * c + simWeightB * f)/2
    if simScoreOfZero >= max(simScoreOfOne, simScoreOfTwo):
      updownscore = grid[0][moves[1]]
    elif simScoreOfOne >= max(simScoreOfZero, simScoreOfTwo):
      updownscore = grid[1][moves[1]]
    else:
      updownscore = grid[2][moves[1]]
    simWeightA = weightA - 0.01
    simWeightB = weightB + 0.01
    simScoreOfZero = (simWeightA * a + simWeightB * d)/2
    simScoreOfOne = (simWeightA * b + simWeightB * e)/2
    simScoreOfTwo = (simWeightA * c + simWeightB * f)/2
    if simScoreOfZero >= max(simScoreOfOne, simScoreOfTwo):
      downupscore = grid[0][moves[1]]
    elif simScoreOfOne >= max(simScoreOfZero, simScoreOfTwo):
      downupscore = grid[1][moves[1]]
    else:
      downupscore = grid[2][moves[1]]
    simWeightA = weightA - 0.01
    simWeightB = weightB - 0.01
    simScoreOfZero = (simWeightA * a + simWeightB * d)/2
    simScoreOfOne = (simWeightA * b + simWeightB * e)/2
    simScoreOfTwo = (simWeightA * c + simWeightB * f)/2
    if simScoreOfZero >= max(simScoreOfOne, simScoreOfTwo):
      downdownscore = grid[0][moves[1]]
    elif simScoreOfOne >= max(simScoreOfZero, simScoreOfTwo):
      downdownscore = grid[1][moves[1]]
    else:
      downdownscore = grid[2][moves[1]]
    if upupscore >= max(updownscore, downupscore, downdownscore):
      weightA = weightA + 0.01
      weightB = weightB + 0.01
    elif updownscore >= max(upupscore, downupscore, downdownscore):
      weightA = weightA + 0.01
      weightB = weightB - 0.01
    elif downupscore >= max(upupscore, updownscore, downdownscore):
      weightA = weightA - 0.01
      weightB = weightB + 0.01
    else:
      weightA = weightA - 0.01
      weightB = weightB - 0.01

```

## How It Works

It probably doesn't. However, it should slowly move `weightA` and `weightB` so the bot is more effective. It's basically a tiny AI. The real core of Mehscent is the giant interpret function, which just plays around with the weights until something good happens.

# Answer
> 1 votes
# HermitCrab

Very akin to a normal crab, but never picks an option that leaves itself out in the dust if it can help it.

```
def strategize(grid, store = None):
    nums = [0,1,2]
    winner = 0
    opponentScores = [-1, -1, -1]
    for i in nums:
        opponentScores[i] = (grid[0][i]*grid[1][i]*grid[2][i])+(.1*(grid[0][i]+grid[1][i]+grid[2][i]))
    fear = [0]
    fearful = 10
    terror = 0
    for i in nums:
        if min(grid[i]) < fearful:
            fear = [i]
            fearful = min(grid[i])
            terror = 0
        elif min(grid[i]) == fearful:
            terror = terror + 1
            fear.append(min(grid[i]))
    mini = 100
    if terror == 2:
        fear = []
    for i in nums:
        if i not in fear:
            if opponentScores[i] < mini:
                winner = i
                mini = opponentScores[i]
    return winner

def interpret(grid, moves, store):
    pass

```

# Answer
> 1 votes
# Minimum Maximizer

Not to be confused with the other one

```
def strategize(grid, store):
    a = min(grid[0])
    b = min(grid[1])
    c = min(grid[2])
    if a >= min(b, c):
      return 0
    if b >= min(a, c):
      return 1
    return 2
def interpret(grid, moves, store):
    pass

```

# Answer
> 1 votes
# Rafaam

My final entry, came to me last night. Named after my favorite duplicitous multiverse-traveling villain, this optimizes its own success *compared* to its opponent, but sometimes acts kindly, and in doing so, determines if it's facing against itself, possibly changing from cruel to kind.

```
def strategize(grid, store = None):
    if not store:
        store["round"] = 0
        store["opponent"] = 0
    nums = [0,1,2]
    kind = False
    if store["opponent"] == 1:
        kind = True
    elif store["opponent"] == 0 and store["round"] == 2:
        kind = True
    if kind:
        winner = 0
        score = -1
        for i in nums:
            if grid[i][i] > score:
                winner = i
                score = grid[i][i]
        return winner
    scores = []
    for i in nums:
        row = []
        for j in nums:
            row.append((grid[i][j],(grid[i][j]/(grid[j][i]+0.01))))
        scores.append(row)
    safeRows = []
    ratios = [[col[1] for col in row] for row in scores]
    for i in nums:
        non = ratios[i][:i] + ratios[i][(i + 1):]
        if min(non) > 0.95:
            safeRows.append(i)

    scores = []
    for i in nums:
        scores.append((ratios[i][0]+ratios[i][1]+ratios[i][2]-ratios[i][i],i))
    sortedScores = sorted(scores, key=lambda tup:(-tup[0],tup[1]))
    for i in sortedScores:
        if i[1] in safeRows:
            return i[1]
    return sortedScores[0][1]

def interpret(grid, moves, store):
    if moves[0] != moves[1]:
        store["opponent"] = -1
    elif store["round"] == 4 and store["opponent"] == 0:
        store["opponent"] = 1
    store["round"] += 1

```

# Answer
> 0 votes
# Why\_do\_I\_have\_so\_many\_ideas?!?!

It works. It's trash, but it works on Debian Buster with python 3.7.3

```
isFriendlyOne = 0
isFriendlyTwo = 0
def strategize(grid, store):
    global isFriendlyOne, isFriendlyTwo
    aa = grid[0][0] #aa means '0-0'.
    ab = grid[1][0] #and similarly for the others.
    ac = grid[2][0]
    ba = grid[0][1]
    bb = grid[1][1] #I wish I had a macro to do this.
    bc = grid[2][1]
    ca = grid[0][2]
    cb = grid[1][2]
    cc = grid[2][2]

    dd = grid[0][0]
    de = grid[0][1]
    df = grid[0][2]
    ed = grid[1][0]
    ee = grid[1][1] #autocorrect is annoying
    ef = grid[1][2]
    fd = grid[2][0]
    fe = grid[2][1]
    ff = grid[2][2]

    a = (aa + ab + ac)/3 # a, b, c, d, e, and f are the respective averages.
    b = (ba + bb + bc)/3
    c = (ca + cb + cc)/3
    d = (dd + de + df)/3
    e = (ed + ee + ef)/3
    f = (fd + fe + ff)/3
    scoreOfZero = (a + d)/2
    scoreOfOne = (b + e)/2
    scoreOfTwo = (c + f)/2
    if isFriendlyOne != 2:
      if scoreOfZero <= min(scoreOfOne, scoreOfTwo):
        return 0
      if scoreOfOne <= min(scoreOfZero, scoreOfTwo):
        return 1
      return 2
    elif isFriendlyTwo != 2:
      if scoreOfZero <= min(scoreOfOne, scoreOfTwo):
        return 0
      if scoreOfOne <= min(scoreOfZero, scoreOfTwo):
        return 1
      return 2
    else:
      if d >= max(e, f):
        if dd >= max(de, df):
          return 0
        if de >= max(dd, df):
          return 1
        return 2
      if e >= max(d, f):
        if ed >= max(ee, ef):
          return 0
        if ee >= max(ed, ef):
          return 1
        return 2
      if fd >= max(fe, ff):
        return 0
      if fe >= max(fd, ff):
        return 1
      return 2

def interpret(grid, moves, store):
    global isFriendlyOne, isFriendlyTwo
    if not store:
      store['wroteOne'] = False
      store['wroteTwo'] = False
      isFriendlyOne = 0
      isFriendlyTwo = 0
    if moves[0] != moves[1]:
      store['oldMatch'] = True
    if max(isFriendlyOne, isFriendlyTwo) < 1:
      if moves[1] == 0:
        if grid[0][moves[0]] >= max(grid[1][moves[0]], grid[2][moves[0]]):
          if moves[0] > 0:
            isFriendlyOne = 1
            store['wroteOne'] = True
      if moves[1] == 1:
        if grid[1][moves[0]] >= max(grid[2][moves[0]], grid[0][moves[0]]):
          if moves[0] > 1:
            isFriendlyOne = 1
            store['wroteOne'] = True
          elif moves[0] < 1:
            isFriendlyTwo = 1
            store['wroteTwo'] = True
      if moves[1] == 2:
        if grid[2][moves[0]] >= max(grid[1][moves[0]], grid[0][moves[0]]):
          if moves[0] > 2:
            isFriendlyOne = 1
            store['wroteOne'] = True
          elif moves[0] < 2:
            isFriendlyTwo = 1
            store['wroteTwo'] = True
    if store['wroteOne']:
      if isFriendlyTwo == 1:
        isFriendlyOne = 2
    if store['wroteTwo']:
      if isFriendlyOne == 1:
        isFriendlyTwo = 2

```

I ***think*** the new version implements self-recognition? Either this bot or Switcheroo has the most lines, although Switcheroo is vastly more complex. The entire interpret function is just for self-recognition.

# Answer
> 0 votes
# Villain

My personal approach to solving the problem

```
def strategize(grid, store = None):
    nums = [0,1,2]
    safe = [(a, True) if 0 not in a else (a, False) for a in grid]
    safeNums = []
    for i in nums:
        if safe[i][1]:
            safeNums.append(i)
    if len(safeNums) == 1:
        return safeNums[0]
    rudeNums = []
    for i in nums:
        rude = False
        for j in grid:
            if j[i] == 0:
                rude = True
        if rude:
            rudeNums.append(i)
    geniusNums = []
    for i in nums:
        if i in safeNums and i in rudeNums:
            geniusNums.append(i)
    if len(geniusNums) == 1:
        return geniusNums[0]
    if len(geniusNums) > 1:
        winner = geniusNums[0]
        mini = -1
        for i in geniusNums:
            newMin = min(grid[i])
            if newMin > mini:
                winner = i
                mini = newMin
        return winner
    if len(safeNums) > 1:
        winner = safeNums[0]
        mini = -1
        for i in safeNums:
            newMin = min(grid[i])
            if newMin > mini:
                winner = i
                mini = newMin
        return winner
    if len(rudeNums) == 1:
        return rudeNums[0]
    if len(rudeNums) >= 1:
        winner = rudeNums[0]
        mini = -1
        for i in rudeNums:
            newMin = grid[i][0]+grid[i][1]+grid[i][2]
            if newMin > mini:
                winner = i
                mini = newMin
        return winner
    score = 0
    winner = 0
    for i in nums:
        newScore = grid[i][0]+grid[i][1]+grid[i][2]
        if newScore > score:
            score = newScore
            winner = i
    return winner

def interpret(grid, moves, store):
    pass

```

Should be a fine algorithm- first prioritizes safety, then screwing over opponents, then personal score. It doesn't bother minimizing opponent score, only giving them the potential for 0s.

# Answer
> 0 votes
# The Student

My late entry to the competition, spawned originally out of a simple desire to beat naiive, which has been remarkably successful. Eventually it morphed into this monstrosity that attempts to predict opponent moves and tracks likelihood of a some strategies I or people I talked to thought of.

```
import random

def strategize(grid, store):
    possible_round_results = [
        ((0, 0), (grid[0][0], grid[0][0]), 0),
        ((0, 1), (grid[0][1], grid[1][0]), grid[0][1] - grid[1][0]),
        ((0, 2), (grid[0][2], grid[2][0]), grid[0][2] - grid[2][0]),
        ((1, 0), (grid[1][0], grid[0][1]), grid[1][0] - grid[0][1]),
        ((1, 1), (grid[1][1], grid[1][1]), 0),
        ((1, 2), (grid[1][2], grid[2][1]), grid[1][2] - grid[2][1]),
        ((2, 0), (grid[2][0], grid[0][2]), grid[2][0] - grid[0][2]),
        ((2, 1), (grid[2][1], grid[1][2]), grid[2][1] - grid[1][2]),
        ((2, 2), (grid[2][2], grid[2][2]), 0)
    ]

    # Interpret data from Store to try to determine opponent and optimize
    if('facing_self' in store and store['facing_self']):
        # Determine move combination that gives the highest total points
        max_score_result_index = max([(x[1][0] + x[1][1], i) for (i, x) in enumerate(possible_round_results)])[1]
        if(store['should_pick_low'] is None):
            random.seed()
            return possible_round_results[max_score_result_index][0][random.randrange(0,2)]
        elif(store['should_pick_low']):
            return max(possible_round_results[max_score_result_index][0])
        else:
            return min(possible_round_results[max_score_result_index][0])
    opponent_move = -1
    if('opponent_strategy_probabilities' in store):
        opponent_probabilities = [(store['opponent_strategy_probabilities'][x], x) for x in store['opponent_strategy_probabilities']]
        opponent_probabilities.remove((store['opponent_strategy_probabilities']['self'], 'self'))
        most_likely_opponent = max(opponent_probabilities)[1]
        if(most_likely_opponent == 'safe_scorer'):
            # safe_scorer
            opponent_move = 0
            safe_moves = []
            for i in range(0,9,3):
                if(min([possible_round_results[i][2], possible_round_results[i+1][2], possible_round_results[i+2][2]]) >= 0):
                    safe_moves.append((possible_round_results[i][2] + possible_round_results[i+1][2] + possible_round_results[i+2][2], possible_round_results[i][0][0]))
            if(len(safe_moves) > 0):
                opponent_move = max(safe_moves)[1]
            else:
                #resort to naiive_score_differential after loosing out on safety
                opponent_move = max([(possible_round_results[i][2] + possible_round_results[i+1][2] + possible_round_results[i+2][2], possible_round_results[i][0][0]) for i in range(0, 9, 3)])[1]
        elif(most_likely_opponent == 'hurtful'):
            # hurtful
            opponent_move = min([(sum(x), i) for (i, x) in enumerate(grid)])[1]
        elif(most_likely_opponent == 'cooperative'):
            # cooperative
            opponent_move = max([(x[i], i) for (i, x) in enumerate(grid)])[1]
        elif(most_likely_opponent == 'minimize_losses'):
            # minimize_losses
            opponent_move = max([(min(x), i) for (i, x) in enumerate(grid)])[1]
        elif(most_likely_opponent == 'highest_expected_val'):
            # highest_expected_val
            opponent_move = max([(x[2], x[0][1]) for x in possible_round_results])[1]
        elif(most_likely_opponent == 'naiive_score_differential'):
            # naiive_scored_differential
            opponent_move = max([(possible_round_results[i][2] + possible_round_results[i+1][2] + possible_round_results[i+2][2], possible_round_results[i][0][0]) for i in range(0, 9, 3)])[1]
        else:
            # naiive
            opponent_move = max([(sum(x), i) for (i, x) in enumerate(grid)])[1]
    else:
        #assumed naiive
        opponent_move = max([(sum(x), i) for (i, x) in enumerate(grid)])[1]
    score_margin = 10
    if('my_score' in store and store['my_score'] >= store['opponent_score'] + score_margin):
        return max([(x[opponent_move], i) for (i, x) in enumerate(grid)])[1]
    else:
        possible_moves = []
        for result in possible_round_results:
            if(result[0][1] == opponent_move):
                possible_moves.append(result)
        return max([(x[2], i) for (i, x) in enumerate(possible_moves)])[1]

def interpret(grid, moves, store):
    possible_round_results = [
        ((0, 0), (grid[0][0], grid[0][0]), 0),
        ((0, 1), (grid[0][1], grid[1][0]), grid[0][1] - grid[1][0]),
        ((0, 2), (grid[0][2], grid[2][0]), grid[0][2] - grid[2][0]),
        ((1, 0), (grid[1][0], grid[0][1]), grid[1][0] - grid[0][1]),
        ((1, 1), (grid[1][1], grid[1][1]), 0),
        ((1, 2), (grid[1][2], grid[2][1]), grid[1][2] - grid[2][1]),
        ((2, 0), (grid[2][0], grid[0][2]), grid[2][0] - grid[0][2]),
        ((2, 1), (grid[2][1], grid[1][2]), grid[2][1] - grid[1][2]),
        ((2, 2), (grid[2][2], grid[2][2]), 0)
    ]

    # Estimate probability that opponent is using a specific strategy
    naiive_move = max([(sum(x), i) for (i, x) in enumerate(grid)])[1]
    naiive_score_differnetial_move = max([(possible_round_results[i][2] + possible_round_results[i+1][2] + possible_round_results[i+2][2], possible_round_results[i][0][0]) for i in range(0, 9, 3)])[1]
    cooperative_move = max([(x[i], i) for (i, x) in enumerate(grid)])[1]
    minimize_losses_move = max([(min(x), i) for (i, x) in enumerate(grid)])[1]
    highest_expected_val_move = max([(x[2], x[0][1]) for x in possible_round_results])[1]
    hurtful_move = min([(sum(x), i) for (i, x) in enumerate(grid)])[1]
    safe_scorer_move = 0
    safe_moves = []
    for i in range(0,9,3):
        if(min([possible_round_results[i][2], possible_round_results[i+1][2], possible_round_results[i+2][2]]) >= 0):
            safe_moves.append((possible_round_results[i][2] + possible_round_results[i+1][2] + possible_round_results[i+2][2], possible_round_results[i][0][0]))
    if(len(safe_moves) > 0):
        safe_scorer_move = max(safe_moves)[1]
    else:
        #resort to naiive_score_differential after loosing out on safety
        safe_scorer_move = max([(possible_round_results[i][2] + possible_round_results[i+1][2] + possible_round_results[i+2][2], possible_round_results[i][0][0]) for i in range(0, 9, 3)])[1]
    self_move = None
    if(('facing_self' in store) and (store['facing_self'])):
        #find the two possibilities that might have been used, compare to move, and set to move if it matches to maintain self-facing status
        max_score_result_index = max([(x[1][0] + x[1][1], i) for (i, x) in enumerate(possible_round_results)])[1]
        possible_moves = possible_round_results[max_score_result_index][0]
        if(moves[1] == possible_moves[0] or moves[1] == possible_moves[1]):
            self_move = moves[1]
            if(moves[0] < moves[1] and store['should_pick_low'] is None):
                store['should_pick_low'] = True
            elif(moves[0] > moves[1] and store['should_pick_low'] is None):
                store['should_pick_low'] = False
        else:
            self_move = -1
    else:
        self_move = strategize(grid, store)

    # Populate default values for store
    if(not 'num_turns' in store):
        store['num_turns'] = 0
        store['my_score'] = 0
        store['opponent_score'] = 0
        store['opponent_strategy_probabilities'] = {
            'self': 0,
            'naiive': 0, # pick the row with the highest sum
            'naiive_score_differential': 0, # pick the row with the highest average point gain over opponent
            'hurtful': 0, # try to give opponent the column with lowest sum
            'cooperative': 0, # try to behave cooperatively
            'minimize_losses': 0, # pick row with highest minimum
            'highest_expected_val': 0, # pick row with highest sum of score differences
            'safe_scorer': 0 # determine rows with safety, then pick row with highest score differential
        }
        store['facing_self'] = False
        store['should_pick_low'] = None
    store['num_turns'] += 1
    store['my_score'] += grid[moves[0]][moves[1]]
    store['opponent_score'] += grid[moves[1]][moves[0]]

    # Used to tune adaptation of bot
    most_recent_weighting = 5

    if(moves[1] == naiive_move):
        store['opponent_strategy_probabilities']['naiive'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['naiive'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    else:
        store['opponent_strategy_probabilities']['naiive'] = ((store['opponent_strategy_probabilities']['naiive'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    if(moves[1] == naiive_score_differnetial_move):
        store['opponent_strategy_probabilities']['naiive_score_differential'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['naiive_score_differential'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    else:
        store['opponent_strategy_probabilities']['naiive_score_differential'] = ((store['opponent_strategy_probabilities']['naiive_score_differential'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    if(moves[1] == cooperative_move):
        store['opponent_strategy_probabilities']['cooperative'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['cooperative'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    else:
        store['opponent_strategy_probabilities']['cooperative'] = ((store['opponent_strategy_probabilities']['cooperative'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    if(moves[1] == minimize_losses_move):
        store['opponent_strategy_probabilities']['minimize_losses'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['minimize_losses'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    else:
        store['opponent_strategy_probabilities']['minimize_losses'] = ((store['opponent_strategy_probabilities']['minimize_losses'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    if(moves[1] == highest_expected_val_move):
        store['opponent_strategy_probabilities']['highest_expected_val'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['highest_expected_val'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    else:
        store['opponent_strategy_probabilities']['highest_expected_val'] = ((store['opponent_strategy_probabilities']['highest_expected_val'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    if(moves[1] == hurtful_move):
        store['opponent_strategy_probabilities']['hurtful'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['hurtful'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    else:
        store['opponent_strategy_probabilities']['hurtful'] = ((store['opponent_strategy_probabilities']['hurtful'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    if(moves[1] == safe_scorer_move):
        store['opponent_strategy_probabilities']['safe_scorer'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['safe_scorer'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    else:
        store['opponent_strategy_probabilities']['safe_scorer'] = ((store['opponent_strategy_probabilities']['safe_scorer'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    if(moves[1] == self_move):
        store['opponent_strategy_probabilities']['self'] = (most_recent_weighting + (store['opponent_strategy_probabilities']['self'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    else:
        store['opponent_strategy_probabilities']['self'] = ((store['opponent_strategy_probabilities']['self'] * (store['num_turns'] - 1))) / (most_recent_weighting + store['num_turns'] - 1)
    if(store['opponent_strategy_probabilities']['self'] == 1 and store['num_turns'] > 4):
        store['facing_self'] = True
    else:
        store['facing_self'] = False

```

---
Tags: king-of-the-hill, python
---


title: Have you mooed today?

text:
# Question
Title: Have you mooed today?
The Debian Linux distribution (and Debian-based distros, like Ubuntu, Kali and others) uses a package-manager called APT. To install program `foo` you would type into a terminal

```
sudo apt-get install foo

```

One little Easter Egg of APT is the following

```
apt-get moo

```

Which after typing will produce the following output

```
                 (__)
                 (oo)
           /------\/
          / |    ||
         *  /\---/\
            ~~   ~~
..."Have you mooed today?"...

```

You must write a program that produces this EXACT output in as few bytes as possible. (including trailing spaces and a new line)

Here is the same output with `\n` added to represent newline characters, and a `*` to represent trailing spaces

```
                 (__)*\n
                 (oo)*\n
           /------\/*\n
          / |    ||***\n
         *  /\---/\*\n
            ~~   ~~***\n
..."Have you mooed today?"...\n

```

As requested in the comments, here is the md5sum of the mooing.

```
35aa920972944a9cc26899ba50024115  -

```

# Answer
> 6 votes
# Bash, 95 bytes

```
0000000: 7a 63 61 74 3c 3c 27 27 0a 1f 8b 08 01 01 01 01 01  zcat<<''.........
0000011: 02 03 53 40 07 1a f1 f1 9a 0a 5c 98 c2 f9 f9 a8 c2  ..S@......\......
0000022: fa ba 60 10 a3 8f 2c aa af 50 03 a2 6a 40 24 42 58  ..`...,..P..j@$BX
0000033: 0b 28 11 03 54 ab 1f 83 6a 70 5d 1d 8c e0 d2 d3 d3  .(..T...jp]......
0000044: 53 f2 48 2c 4b 55 a8 cc 2f 55 c8 cd cf 4f 4d 51 28  S.H,KU../U...OMQ(
0000055: c9 4f 49 ac b4 57 02 ca 70 01                       .OI..W..p.

```

The above is a reversible hexdump. To create the file, execute

```
xxd -r -c 17 > 55918.sh

```

paste the hexdump and press `Enter`, then `Ctrl` \+ `D`.

To run created file, execute

```
bash 55918.sh 2>&-

```

Any other filename will do.

I chose zopfli as the compressor since it is compatible with the Coreutils program zcat and achieves better compression than gzip, bzip2 and xz.

`zcat<<''` will read the following lines (until EOF) and feed them as input to `zcat`.

Note that zcat will print a warning (since I stripped the checksum of the compressed file), as will bash (since the HEREDOC isn't terminated by an empty line). These warnings are printed to STDERR (suppressed by `2>&-`), which is allowed by default per consensus on Meta.

# Answer
> 11 votes
# CJam, 96

This uses a lot of nasty bytes, so here's a hex dump of it:

```
00000000  22 ee 51 1e 53 41 15 ee  51 20 53 41 15 9a 5f 5a  |".Q.SA..Q SA.._Z|
00000010  b9 5f 41 15 8c 5f 41 f9  38 24 2a 15 7e 55 1c 5f  |._A.._A.8$*.~U._|
00000020  b9 30 5f b9 41 15 a8 26  2a 26 2a 15 36 45 91 c3  |.0_.A..&*&*.6E..|
00000030  ed cb 41 f3 df eb 41 db  20 cb c9 41 e9 df c9 c3  |..A...A. ..A....|
00000040  f3 7f 45 36 15 22 7b 69  32 6d 64 5c 5f 63 5c 37  |..E6."{i2md\_c\7|
00000050  6d 64 22 20 5f 6f 2d 7c  7e 2e 22 3d 2a 3f 7d 2f  |md" _o-|~."=*?}/|

```

You can run the file with the java interpreter; it may be necessary to use ISO-8859-1 encoding, such as:
`java -Dfile.encoding=ISO-8859-1 …`

Try it online

Equivalent (and much longer) ASCII version:

```
[238 81 30 83 65 21 238 81 32 83 65 21 154 95 90 185 95 65 21 140 95 65 249 56 36 42 21 126 85 28 95 185 48 95 185 65 21 168 38 42 38 42 21 54 69 145 195 237 203 65 243 223 235 65 219 32 203 201 65 233 223 201 195 243 127 69 54 21]:c
{i2md\_c\7md" _o-|~."=*?}/

```

Try it online

**Explanation:**

There are 7 characters that have repetitions:  `_o-|~.`. Each of them can be encoded as a number n from 0 to 6. For each repeating sequence, I am encoding both the character's index (n) and the number of repetitions (k) in a single byte: `2 * (k * 7 + n)`, written as a character with that code. And I am encoding any single characters as `2 * c + 1`, where c is the ASCII code. Everything goes in the initial string, and the rest of the program is decoding it:

```
{…}/      for each character in the string
  i       convert to integer (extended-ASCII code)
  2md     integer division by 2, obtaining the quotient (q) and remainder (r)
           r decides whether it's a repetition or single character
  \_      swap q and r, and duplicate q
  c\      convert q to character and move it before the other q
           this is for the r=1 case (single character)
  7md     divide q by 7, obtaining the quotient (k) and remainder (n)
  "…"=    get the corresponding character from that string (decoding n)
  *       repeat the character k times
  ?       use the single character or the repetition, depending on r

```

---

Old version (109):

```
" H(_2)
 H(o2)
 B/-6\/
 A/ | 4|2 3
 9* 2/\-3/\
 C~2 3~2 3
.6"{_'M,48>&{~*}&}/3/"Have you mooed today?"`*N

```

Try it online

# Answer
> 6 votes
# Pyth, 100

```
r"17 (__)
17 (oo)
11 /6-\/
10 / |4 ||3
9 *  /\\3-/\
12 ~~3 ~~3
3.\"Have you mooed today?\"3."9

```

Try it online: Demonstration

`r"string"9` run-length-decodes the string.

### edit:

Here's a 97 char solution: Demonstration. Very likely this is also 97 bytes (in iso-8859-1). But too tired for writing the bytes down and doing an explanation. Tomorrow evening, I guess.

# Answer
> 4 votes
## GolfScript (107 bytes)

This is a very simple encoding: newlines are replaced with `^`, and spaces are run-length-encoded. The result contains some non-printable characters, so I present it here as `xxd` output:

```
0000000: 2711 285f 5f29 015e 1128 6f6f 2901 5e0b  '.(__).^.(oo).^.
0000010: 2f2d 2d2d 2d2d 2d5c 2f01 5e0a 2f01 7c04  /------\/.^./.|.
0000020: 7c7c 035e 092a 022f 5c2d 2d2d 2f5c 015e  ||.^.*./\---/\.^
0000030: 0c7e 7e03 7e7e 035e 2e2e 2e22 4861 7665  .~~.~~.^..."Have
0000040: 0179 6f75 016d 6f6f 6564 0174 6f64 6179  .you.mooed.today
0000050: 3f22 2e2e 2e27 7b2e 3332 3c7b 2220 222a  ?"...'{.32<{" "*
0000060: 7d2a 7d25 225e 222f 6e2a 0a              }*}%"^"/n*.

```

Online demo

Note that this is one character shorter than the corresponding CJam code. The tradeoff is using `'` as the delimiter for the main string (saving two `\`s to escape the `"`), saving an `i` to convert character values to integers in the decoding loop, and getting a free trailing newline; vs having character literals to replace the single-character string literals.

---

Since this question was briefly tagged , I also made a version with only (108) printable characters:

```
'Y(__)I
Y(oo)I
S/------\/I
R/I|L||K
Q*J/\---/\I
T~~K~~K
..."HaveIyouImooedItoday?"...'{.82-.*82<{72-' '*}*}%

```

Instead of encoding the run-lengths of the spaces as characters `^A` to `^R` (and encoding `^J` as `^` to avoid collisions), it leaves newlines untouched and encodes the run-lengths as `I` to `Y`.

Incidentally, my general-purpose GolfScript Kolmogorov program produces a 120-byte program.

# Answer
> 1 votes
# Lua, ~~186~~ 178 bytes

*8 bytes saved thanks to a suggestion by @DJ McMayhem*

```
p=print s=" "a=s:rep(17)b=s:rep(9)p(a.."(__) ")p(a.."(oo) ")p(b.."  /------\\/ ")p(b.." / |    ||   ")p(b.."*  /\\---/\\ ")p(b.."   ~~   ~~   ")p"...\"Have you mooed today?\"..."

```

Ungolfed:

```
p=print --Save the print function for later use
s=" " --Space character
a=s:rep(17) --string.rep(string, times) repeats the given string
b=s:rep(9)
p(a.."(__) ") --print out the lines
p(a.."(oo) ")
p(b.."  /------\\/ ")
p(b.." / |    ||   ")
p(b.."*  /\\---/\\ ")
p(b.."   ~~   ~~   ")
p"...\"Have you mooed today?\"..."

```

# Answer
> 1 votes
# PowerShell, 144 bytes

```
$a="        "
"$a$a (__) "
"$a$a (oo) "
"$a   /------\/ "
"$a  / |    ||   "
"$a *  /\---/\ "
"$a    ~~   ~~   "
'..."Have you mooed today?"...'

```

The above code will work properly in environments that print Unix-style newlines (`\n`). It produces the correct output with, e.g., Pash on Linux.

Mathematically, for PowerShell, having 8 spaces for the `$a` variable is the optimal, as less means too many additional spaces between the variable and the cow to make a `$b` worthwhile, and more means we can't double-up on the first two lines for the head.

# Answer
> 1 votes
# \>\<\>, 217 bytes

```
!v"                 (__) "a"                 (oo) "a"           /------\/ "a"          / |    ||   "a"         *  /\---/\ "a"            ~~   ~~   "a"..."c3*2-"Have you mooed today?"c3*2-"..."a!
 >r>l0)?v;
    ^   o<

```

Unfortunately this is a pretty boring answer. It starts by reading out a string that draws out the entire cow, with newlines made by adding a value of 10 to the stack (a). It then goes into a loop which just draws out the cow.

I originally made a loop to add in a set of spaces, but it was actually more expensive byte wise than just putting spaces in.

EDIT: Forgot that fish is written as "\>\<\>"

# Answer
> 0 votes
# Molecule, 145 bytes

```
"   "_____:a"  (__)
";a____"  (oo)
";a__"  /------\\/
";a__" / |    ||
";a__"*  /\\---/\\
";a____"~~"b"~~
...\"Have you mooed today?\"..."

```

My first time trying to compress ASCII art :P

# Answer
> 0 votes
# Vyxal, 101 bytes

```
‛_oƛ` (`pøṀ22↳,;\/:3-øṀp20↳₴ð,₀`/ | `꘍3\|꘍m+,9`*  /\---/\ `꘍,12‛~~꘍3\~꘍m+,`..."`:₴`λɾ λ• mo⋎Þ ¬¾?`₴Ṙ,

```

Try it Online!

Uses some form of compression.

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