title: Blueprint a sestina

text:
# Question
Title: Blueprint a sestina
A sestina is a format of poem that follows an interesting pattern that we can generate. It has six stanzas of six lines each, where the last words of each line in the first stanza make up the line endings in each successive stanza, rotated in a set pattern. (There's also a three-line stanza at the end, but we won't worry about that.) Take a look at the first three stanzas of Elizabeth Bishop's creatively named *Sestina*:

> September rain falls on the house.
> In the failing light, the old grandmother
> sits in the kitchen with the child
> beside the Little Marvel Stove,
> reading the jokes from the almanac,
> laughing and talking to hide her tears.
>
> She thinks that her equinoctial tears
> and the rain that beats on the roof of the house
> were both foretold by the almanac,
> but only known to a grandmother.
> The iron kettle sings on the stove.
> She cuts some bread and says to the child,
>
> It's time for tea now; but the child
> is watching the teakettle's small hard tears
> dance like mad on the hot black stove,
> the way the rain must dance on the house.
> Tidying up, the old grandmother
> hangs up the clever almanac
>
> ...

Note how each line ends with one of the six words "house," "grandmother," "child," "stove," "almanac," or "tears." Not only that, but the words are ordered in the pattern 6–1—5–2—4–3, relative to the previous stanza. It ends up looking like a spiral:

We're still a few years away from programmatically generating a full sestina, but we can create a template featuring the end words of each stanza in proper order. Write a program or function that, given the six line ending words, outputs the blueprint for a sestina, following these rules. Here is the expected result for the input `house grandmother child stove almanac tears`:

```
house
grandmother
child
stove
almanac
tears

tears
house
almanac
grandmother
stove
child

child
tears
stove
house
grandmother
almanac

almanac
child
grandmother
tears
house
stove

stove
almanac
house
child
tears
grandmother

grandmother
stove
tears
almanac
child
house

```

The first stanza is the words in original order, the second stanza is in the order 6-1-5-2-4-3 from the first. The third stanza is that order relative to the second, and so on, all the way to stanza 6.

Assume that the input words will always be only letters, uppercase or lowercase. You can take them as an array of strings or a single string delimited by a non-letter character (space, newline, etc.). In the output, lines are separated by newlines (`0x0A`), and stanzas separated by two newlines. A trailing newline is acceptable.

This is , so shortest code in bytes wins. That being said, it may be shorter to compress the whole poem's structure, but I'd like to see some solutions that base each stanza on the previous.

# Answer
> 1 votes
# Jelly, ~~15~~ 14 bytes

```
620œ?$ÐĿY€j⁷Ḥ¤

```

**TryItOnline!**

### How?

Yey, a use of one of my additions to Jelly! (`œ?`)

```
620œ?$ÐĿY€j⁷Ḥ¤ - Main link: list of words L
      ÐĿ       - loop until no longer unique, collecting intermediate results
     $         -     last two links as a monad
   œ?          -         permutation of right argument (initially L) at index
620            -         620
        Y€     - join with line feeds for €each (the words of each stanza)
          j    - join (the stanzas) with
             ¤ - nilad followed by link(s) as a nilad
           ⁷   -     a line feed
            Ḥ  -     double (two line feeds)

```

# Answer
> 7 votes
# Python, ~~72~~ 64 bytes

```
i,n=input(),'\n';exec"print n.join(i)+n;i=map(i.pop,[-1,0]*3);"*6

```

Takes input through STDIN as a comma separated array of 6 strings and outputs to STDOUT in the format described in the post with an additional trailing newline.

Try It Online! (Ideone)

Also, I am not sure if this is okay to do, but here is a shorter answer in the form of an anonymous lambda function at **59 bytes** that takes in input in the same format as the above answer, and outputs the *program* needed to generate the correct output:

```
lambda i,n='\n':"print n.join(i)+n;i=map(i.pop,[-1,0]*3);"*6

```

Therefore it must be called in the format `exec(<Function Name>(<Array>))`. Again, I am not sure if this is okay to do, so I am adding this as an extra, separate, non-competing answer until someone (maybe even OP) can hopefully clarify if this is okay or not, which I would really appreciate.

# Answer
> 3 votes
# MATL, ~~18~~ 17 bytes

```
0ch5:"t[6l5H4I7])

```

Input is a cell array of strings, in the format

```
{'house' 'grandmother' 'child' 'stove' 'almanac' 'tears'}

```

Try it online!

### Explanation

```
0c          % Push string with a single space, to be used as separator
h           % Input array of 6 strings implicitly and append the above string
5:"         % Repeat 5 times
  t         %   Duplicate the array of strings (previous stanza plus separator)
  [6l5H4I7] %   Push array [6 1 5 2 4 3 7]. The 7th string is the separator, and stays
            %   at the end. The other strings are shuffled as required
  )         %   Index into the array of strings
            % End implicitly
            % Display implicitly

```

# Answer
> 3 votes
# Mathematica, 59 bytes

```
r=Riffle;""<>Flatten@r[NestList[RotateRight,#,5],""]~r~"\n"&

```

The core of this unnamed function is `NestList[RotateRight,#,5]`, which takes an input list of length 6 and creates a list of 6 lists, each rotated in the sestina way. Indeed, if a list of lists-of-strings is acceptable output, then `NestList[RotateRight,#,5]&` does the job in **26 bytes**.

Then, `r[...,""]` inserts an empty string between each of the 6 lists; `Flatten` turns the whole thing into a single list of strings; `~r~"\n"` then inserts a newline between each of those strings; and `""<>` concatenates the whole thing into a single string. Thus the other 33 bytes are just to convert the structured output into a single string.

# Answer
> 2 votes
## Batch, 99 bytes

```
@for %%w in (%*)do @if not .%%w==.%7 echo %%w
@echo(
@if not .%7==...... %0 %6 %1 %5 %2 %4 %3 .%7

```

Explanation: Takes input as command-line parameters. The `%0` causes it to loop around, accumulating `.`s in the originally empty 7th parameter. The extra `.` is because `if` doesn't work on empty strings.

# Answer
> 2 votes
# Ruby, 51 bytes

```
->z{z.map{z[1],z[3],z[5],z[4],z[2],z[0]=z+[""]}*$/}

```

Instead of iterating over the numbers `0..5` as below, we repeat 6 times by iterating over the elements of `z`. In normal usage such as `(0..5).map{|i|puts i}` the code `{}` reads the elements iterated over. In this case the permutations done by the code inside the `{}` do not read the elements iterated over, so we can iterate over the elements of `z` without this interfering with the permutations.

# Ruby, 56 bytes

Takes a 6 element array as a parameter

```
->z{(0..5).map{z[1],z[3],z[5],z[4],z[2],z[0]=z+[""]}*$/}

```

alternate version taking 6 parameters

```
->a,b,c,d,e,f{(0..5).map{b,d,f,e,c,a=a,b,c,d,e,f,""}*$/}

```

With each iteration of `map` we permute `z`. The original version plus a `""` to represent a break between stanzas becomes the output of the `map` (this seventh array element is not needed by the assignment so is ignored). `*$/` converts the arrays to a string, joining everything together with newlines.

# Answer
> 2 votes
## Racket 115 bytes

```
(let p((o(list l))(m 0))(if(> n m)(p(cons(map(λ(x)(list-ref(list-ref o 0)x))'(5 0 4 1 3 2))o)(+ 1 m))(reverse o)))

```

Ungolfed:

```
(define(f l n)
 (let loop ((ol (list l))
             (m 0))
    (if (> n m)
        (loop
         (cons (map
                (λ (x) (list-ref (list-ref ol 0) x))
                '(5 0 4 1 3 2))
               ol)
         (add1 m))
        (reverse ol))))

```

Testing:

```
(f (list "house" "grandmother" "child" "stove" "almanac" "tears") 6)

```

Output:

```
'(("house" "grandmother" "child" "stove" "almanac" "tears")
  ("tears" "house" "almanac" "grandmother" "stove" "child")
  ("child" "tears" "stove" "house" "grandmother" "almanac")
  ("almanac" "child" "grandmother" "tears" "house" "stove")
  ("stove" "almanac" "house" "child" "tears" "grandmother")
  ("grandmother" "stove" "tears" "almanac" "child" "house")
  ("house" "grandmother" "child" "stove" "almanac" "tears"))

```

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


# Question
Title: Add weight to one side of a see-saw to balance it
# Balancing Act

A see-saw (supposedly from the French 'ci-ça', meaning 'this-that') forms a third of the holy trinity of playground equipment, along with the similarly ubiquitous slide and swing. A see-saw is in perfect balance if, and only if, the sum of the moments on each side are equivalent. A see-saw can therefore be balanced by adding a specific quantity of weight to the side with the lower moment sum; achieving this is your goal for this challenge.

# Challenge

Your challenge is to take a depiction of a see-saw as input and output it again, with weight added to one end of the see-saw to balance it.

**Input**

Your program must take, in any reasonable format, an ASCII see-saw such as the following:

```
100             100
-------------------
         ^

```

The first line contains two numbers, each representing weights on the see-saw. Exactly one weight is present on each side, each acting on the very end of its side of the plank. Weights are guaranteed to be integers, and always align with their corresponding end of the plank. These numbers will never overlap the fulcrum (`^`).

The second line represents the 'plank' of the see-saw. Each dash (`-`) represents an equal length to each other dash, with the sole exception of the dash directly over the fulcrum (`^`), which has no length.

The third line represents the fulcrum of the see-saw. This fulcrum is marked by the only character that is not a space on this line, a circumflex ('^'). The fulcrum can be positioned anywhere along the length of the plank in a valid input so long as enough space is left so that the numbers representing weights do not overlap the fulcrum in either the input or the output.

The input is guaranteed to have three lines, and have no white-space prior to or after the characters that constitute the see-saw (excepting, of course, the third line, which requires it).

**Output**

For output, the same see-saw depiction should be printed to stdout, but with one (and only one) of the weights replaced with a larger weight, so as to balance the see-saw. Inputs are guaranteed to make this possible using integers alone. Therefore, weights must be shown without decimal points or any other similar notations. If your language does not use stdout you should go by community / meta consensus on output. Trailing newlines are fine but any other changes to the depiction format are probably not OK.

# Exemplification

**Test Inputs and Corresponding Outputs**

Input 1

```
12                22
--------------------
             ^

```

Output 1

```
12                26
--------------------
             ^

```

---

Input 2

```
42       42
-----------
     ^

```

Output 2

```
42       42
-----------
     ^

```

---

Input 3

```
3             16
----------------
        ^

```

Output 3

```
14            16
----------------
        ^

```

---

Input 4

```
1                56
-------------------
    ^

```

Output 4

```
196              56
-------------------
    ^

```

**Reference Implementation - Python 3**

```
# Takes a list of strings as input
def balance_seesaw(lines):
    weights = [int(w.strip()) for w in lines[0].split()]

    length  = len(lines[1])
    pivot   = lines[2].find("^")
    left_length    = pivot
    right_length   = length - 1 - pivot

    left_torque  = weights[0] * left_length
    right_torque = weights[1] * right_length

    if left_torque > right_torque:
        weights[1] = left_torque // right_length
    elif right_torque > left_torque:
        weights[0] = right_torque // left_length

    weights = [str(w) for w in weights]

    string_gap = " " * (length - sum(len(w) for w in weights))
    lines[0] = weights[0] + string_gap + weights[1]

    print("\n".join(lines))

balance_seesaw(["1                56",
                "-------------------",
                "    ^              "])

```

# Rules

* This is , so the shortest code wins counted in bytes. Check meta if counting bytes is awkward in your language.
* Standard rules/loopholes apply.
* Input must be taken in a reasonable format. A non-exhaustive list of appropriate formats are given as follows:

+ A single string with lines separated by newline characters
    + A list of strings, each string represented a line
    + A 2D Array or Matrix of characters

# Related Challenges

---

# Answer
> 5 votes
# 05AB1E, ~~60~~ ~~51~~ ~~50~~ ~~49~~ ~~47~~ 45 bytes

Saved 10 bytes thanks to Emigna and 1 byte thanks to Adnan.

All input lines must have the same amount of characters.

```
#õKD³'^¡€gDŠ*¬-Os÷1®‚*D0›*+¬?DJg²gs-ð×?¤,²,³,

#                                             Split the first input line on spaces
 õKD                                          Push [first weight, second weight] twice
    ³'^¡€gD                                   Push both lengths from either side of the pivot '^' as an array [left, right] twice
           Š*                                 Multiply by weights to get torque
             ¬-O                              Evaluate rightTorque-leftTorque
                s÷                            Divide by each side's length to get the weights to add: [deltaLeft, deltaRight], keep integer values
                  1®‚                         Push [1,-1]
                     *D                       Yield [deltaLeft, -deltaRight]
                       0›*                    Replace the negative value by 0
                          +                   Add weights: old + deltaWeight
                           ¬?                 Print left weight
                             DJg              Take the size of total decimal representation
                                ²gs-ð×?       Print a string composed of filler spaces between both new weights
                                       ¤,     Print right weight and newline
                                         ²,³, Print the last two lines from input (unchanged)

```

Try it online!

There should be a rule of thumb, like "if your 05AB1E code is longer than 40 bytes, you're probably doing it wrong". It seems so golfable, any idea is welcome!

# Answer
> 5 votes
# JavaScript (ES6), 136

~~Probably not working in Chrome,as it uses destructured assignment and default parameters.~~

Note that the standard JS output method `alert` is particularly unsuited for the task, because of the proportional font used.

```
(m,n,o,[p,q]=m.split(/ +/),l=n.length,h=o.indexOf`^`,g=l-h-1,c=p*h<q*g?q*g:p*h)=>alert((c/h+o).slice(0,h)+(o+c/g).slice(h-l)+`
${n}
`+o)

```

*Less golfed*

```
( m,n,o, // input parameters, 3 strings
  // default parameters used as local variables
  [p,q] = m.split(/ +/), // left and right weight
  l = n.length, // bar length
  h = o.indexOf`^`, // left length
  g = l-h-1, // right length
  // p*h left torque
  // q*g right torque
  c = p*h<q*g ? q*g : p*h // max torque
) => alert( (c/h+o).slice(0,h)+(o+c/g).slice(h-l) // o has enough spaces to pad left and right
     +`\n${n}\n`+o )

```

**Test**

```
F=
(m,n,o,[p,q]=m.split(/ +/),l=n.length,h=o.indexOf`^`,g=l-h-1,c=p*h<q*g?q*g:p*h)=>alert((c/h+o).slice(0,h)+(o+c/g).slice(h-l)+`
${n}
`+o)

function go()
{
  var [a,b,c]=I.value.split('\n')
  if(a.length!=b.length || a.length < c.length)
    alert('The strings are not of the same length')
  else
  {
    if (a.length > c.length)
      c = c+' '.repeat(a.length-c-length)
    F(a,b,c)
  }
}
```

```
<textarea id=I>3             16
----------------
        ^      </textarea>
<button onclick='go()'>go</button>
```

# Answer
> 3 votes
# Perl, 149+2=151 characters

Requires command line options `-p0` (this gives me a 2 byte penalty on top of the 149 bytes in the program itself).

```
($_,$b,$c,$d)=map length,/(\d+) +(.+)
(-+)
( +)/;$r=$d/($c-$d-1);($x,$y)=$1*$r>$2?($1,$1*$r):($2/$r,$2);$_="$x$,$y",$,.=$"while$c>length;$\="
$3
$4^"

```

Explanation:

* The `-p0` switch reads the entire input up to the first NUL byte or EOF. This problem doesn't allow NULs, so we'll get the entire input in the variable `$_` that's used for regexes, etc., by default.
* We start with a regex that parses the input (between the first and second slash). There are several ways we could parse the first weight (e.g. `.+?`), but I can't get it below 3 characters so I may as well use the obvious `\d+`. The second number is at the end of the line so it can be parsed as `.+` (2 characters). The central line is used to determine how wide the scales are; it's parsed as `-+` (many other representations would work). The spaces before the caret on the last line are  `+`. Once the caret (or indeed any nonspace) appears, we ignore the rest of the input.
* Perl automatically captures the four groups of the regex (first weight, second weight, row of hyphens, spaces before the caret) into `$1`, `$2`, `$3`, `$4`. Giving a regex as an argument to `map` additionally uses an array of those groups as the array to map over. We therefore take their lengths; this is a convenient way to store the lengths of `$3` and `$4` without having to write `length` twice. We also overwrite `$_` with the length of `$1`; we don't really care about the value of this (the number of digit in the left input is kind-of useless), but the fact that it's short (`$_`'s length is now the number of digits in the number of digits in the first weight, which is necessarily very small compared to the width of the scales).
* We measure the ratio `$r` in which the scales are divided.
* `$1*$r>$2` checks to see which side is heavier. We store the new weights in `$x` and `$y`; these have very simple calculations once the ratio of weights is known.
* We concatenate `$x`, `$,`, and `$y` into `$_` to produce the top row, then keep adding spaces (`$"` contains a single space by default, and is shorter than a literal space `' '` would be) onto `$,` until it's the same length as the middle row (i.e. has length `$c`). (I chose the variable `$,` as it's a built-in variable that can safely be changed in this context and starts empty by default.) As `length` operates on `$_` by default, we don't need to give it an argument explicitly. I used a Yoda conditional because it needs considerably less disambiguating syntax to parse correctly.
* Finally, I redefine Perl's idea of the output line ending convention (`$\`) to contain the rest of the set of scales (which is the same as in the input, so I can simply use `$3` and `$4` directly to produce the bulk of it). Note that this means that there's no trailing whitespace on the third line; adding it would make the program slightly longer and doesn't seem to serve any purpose, so I left it out.
* At the end of the program, the `-p` switch triggers again; this time, it outputs `$_` followed by a "newline" (`$\`). Because I redefined the output newline, these two implicit prints generate the new set of scales between them (although as a side effect, there's no newline on the output).
* The `-p` switch now tries to read input again, but we already slurped the entire file, so it reads EOF and ends the program.

# Answer
> 1 votes
# PHP, ~~212~~ ~~209~~ 205 bytes

probably golfable

```
preg_match("#(\d+)( +)(\d+)\s*(-+)[\r\n]+( +)\^#",$s=$argv[1],$m);echo preg_replace("#\d+( +)\d+#",(($r=$m[3])>($q=$m[1]*($p=strlen($m[5]))/(-$p-1+$e=strlen($m[4])))?$r*$e/($p+1)-$q=$r:$m[1]).$m[2].$q,$s);

```

Takes input from command line argument; escape newlines. Run with `-r`.

---

Replacing with a placeholder did not work as expected; so I had to add more parens to the first regex.

# Answer
> 1 votes
# Python 2, ~~184~~ 183 bytes

Definitely golfable

```
i=raw_input
j=int
w=map(j,i().split())
W=len(i())
I=i().find('^')
R=W-I-1
a=[w[1]*R/I,w[0]*I/R]
h=a[1]>w[1]
w[h]=j(a[h])
k='\n'
print(' '*(W-len(str(w))+4)).join(map(str,w))+k+'-'*W+k+' '*I+'^'

```

Pretty straightforward. Just take the adjusted weights for adjusting both sides, see which one's larger than the original, and change that one, and output.

EDIT Switched multiplication and division because integer division is evile (thanks to @JonathanAllan for noticing this)

EDIT *-1 byte* Changed `i().index('^')` to `i().find('^')` (thanks to @JonathanAllan \[again!\])

# Answer
> 1 votes
# Befunge, ~~223~~ 217 bytes

```
&:00p&10p~$0>~#<2#+%#1_:20p0~>8#~%#+!#1_:3v
v\g01/g03*g01_v#!\g04`*g01g04:*g03p04-1-p0<
>#g>#0>#0>#/>#<:.2\5>5>#\+/#1:#\_$50p:50g\5>5>#\+/#1:#\_$20g\-v>
1#,>#*-#4:#8_$.55+,20g>:#,1#*-#9\#5_55+,30g>:#,1#*-#8\#4_"^",@>>

```

Try it online!

# Answer
> 0 votes
### C++ 14, 482 bytes

```
include<iostream>#include<string>#include<math.h>usingnamespacestd;intmain(){stringa,b,c,d;intj=0;inte[2];getline(cin,a);getline(cin,b);getline(cin,c);for(inti=0;i<a.size();i){if(isdigit(a.at(i))){while(i<a.size()&&isdigit(a.at(i))){d=a.at(i);i;}e[j]=stoi(d);d="";}}strings(b.size()-(int)log10(e[0])-(int)log10(e[1])-2,'');intl1=(c.size()-1);intl2=(b.size()-c.size());intl=e[0]*l1;intr=e[1]*l2;if(l>r)e[1]=l/l2;elsee[0]=r/l1;cout<<e[0]<<s<<e[1]<<endl;cout<<b<<endl;cout<<c;return0;}

```

more readable version:

```
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int main() {
    string a,b,c,d;
    int j=0;
    int e[2];
    // input
    getline(cin,a);// 1st line
    getline(cin,b);// 2nd line
    getline(cin,c);// 3rd line
    for (int i=0;i<a.size();i++) {
        if(isdigit(a.at(i))){
            while(i<a.size() && isdigit(a.at(i))){
                d+=a.at(i);
                i++;
            }
            e[j++]=stoi(d);
            d="";
        }
    }
    // amount of white space in between 2 numbers
    string s(b.size()-(int)log10(e[0])-(int)log10(e[1])-2,' ');
    int l1 = (c.size()-1);
    int l2 = (b.size()-c.size());
    int l = e[0]*l1;
    int r = e[1]*l2;
    // change the side with smaller torque
    if (l>r)
        e[1]=l/l2;
    else
        e[0]=r/l1;
    // output
    cout<<e[0]<<s<<e[1]<<endl;// 1st line
    cout<<b<<endl;// 2nd line
    cout<<c;// 3rd line
    return 0;
}

```

# Answer
> 0 votes
# Python 3, 235 230 bytes (minimized reference)

I just minimized the reference, since I'm very new to code-golfing.

```
def s(l):
 w,i,t=[int(z.strip())for z in l[0].split()],len(l[1]),l[2].find("^");k,o=i-1-t,w[0]*t;p=w[1]*k
 if o>p:w[1]=o//k
 else:w[0]=p//t
 w=[str(z)for z in w];s=" "*(i-sum(len(z)for z in w));l[0]=w[0]+s+w[1];print("\n".join(l))

```

You use it exactly the same as the example, but the function is `s` instead of `balance_seesaw`.

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


title: Create Fluffy Blocks

text:
# Question
Title: Create Fluffy Blocks
(*randomly inspired by this question*)

Let's make a drawing from some pipes `|` and hyphens `-`. Choosing a subset, if chosen carefully, you can form a rectangular box or block shape (meaning that the corners are formed by `|-` or `-|`). For this challenge, we're concerned only with identifying the corners -- the vertical and horizontal pieces of the block shape can be made of either `|` or `-`, and the block may be hollow.

Here's the original drawing, and the subset showing a block shape.

```
|--|---|     |--|---|
|-|||-|| --> |      |
|------|     |------|

```

However, note that the following subsets from this same example do *not* make a block, because the corners are not all `-|` or `|-`

```
|--|
|-||

||-||
----|

|-|
---

```

Each combination of `-|` or `|-` can only form one corner. This means that the smallest possible block shape is these eight characters

```
|--|
|--|

```

and that these six characters do *not* form a block shape, since the corners are being "doubled up."

```
|-|
|-|

```

The challenge here is to turn these blocks fluffy. How? Replace every hard-edged straight character that forms the block edges (both corners and sides) with a much rounder, fluffier character, in this case, an `o`. But, don't fill in the block - we only want to get rid of the hard edges and sharp corners.

```
|--|---|     oooooooo
|-|||-|| --> o-|||-|o
|------|     oooooooo

```

### Input

A 2D string representation of the pipe/hyphen diagram. Input can be as a multiline string, an array of strings, etc., however is convenient for your language. The input is guaranteed to be rectangular (i.e., every row will be the same length), and will only contain `|` and `-`.

### Output

The same diagram, with the "block" characters replaced with `o` as described above and the remaining characters unchanged. The result can be printed to the screen or STDOUT, returned from a function, etc.

### Rules

* Note that blocks can overlap (see example #8) and blocks can share corners (see example #5).
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

### Examples

```
#1
-|--|
|--|-
|--||

-|--|
oooo-
oooo|

#2
|--|---|
|-|||-||
|------|

oooooooo
o-|||-|o
oooooooo

#3
|||||

|||||

#4
|-----|
||---|-
||---|-
|-----|

ooooooo
ooooooo
ooooooo
ooooooo

#5
-|--|--|
|||-|--|
-|-----|

-ooooooo
|o|-oooo
-ooooooo

#6
|-||-|
|----|

oooooo
oooooo

#7
--|--|-
|-----|

--|--|-
|-----|

#8
|-----|---
||--||-|--
||||--|--|
|-|-||||-|
|--|--|-||
---||---||
---|-----|

ooooooo---
o|--||o|--
o||ooooooo
o-|o||o|-o
ooooooo-|o
---o|---|o
---ooooooo

```

# Answer
> 2 votes
## Perl, 448 bytes

```
$_=<>;$o=$_;~y/-|/Aa/;$N=$_;while($n ne $N){$n=$N;$c=$N;$M=$c;while($c=~s/^(.*?;)??([aA]*?)aA([aA]*)Aa(.*;(?i)\2)aA((?i)\3)Aa(.*)$/\L\1\2\UAA\3AA\L\4\UAA\5AA\L\6/){if($N eq $n){substr($N,(length $1)+(length $2),1)="X"}substr($M,-(length $6)-1,1)="X";$c=~s/^([xa;]*;)?(a*)A(A*)A(a*;)\2a((?i)\3)a/\1\2A\3A\4\2A\5A/;1 while $c=~s/(^|;)(a*)A(a*)A(a*;)\2a((?i)\3)a/\1\2A\3A\4\2A\5A/;while($c=~/A/g){substr($o,(pos $c)-1,1)="o"}$c=$M}}$o=~y/;/\n/;print$o

```

I haven't used perl before so there's going to be *massive* room for improvement here (especially since I was mostly glad to get it working, so haven't tried to optimise it yet). I was a bit disappointed that **the** regular expression language didn't have some of the features I wanted, but I think it does pretty well.

### Usage

Takes input on stdin, with lines semicolon-separated (optionally add a semicolon to the end to make the final printed output end with a newline). Outputs to stdout. Example command:

```
printf -- "-|--|--|;|||-|--|;-|-----|;" | perl boxes.perl

```

### Breakdown

```
$_=<>; # Load input
$o=$_; # Create output variable
~y/-|/Aa/; # Replace - and | with A and a so that we can use case insensitive tricks later
$N=$_;
# For each distinct top-left corner...
while($n ne $N){
    $n=$N;
    $c=$N;
    $M=$c;
    # For each distinct box...
    while($c=~s/^(.*?;)??([aA]*?)aA([aA]*)Aa(.*;(?i)\2)aA((?i)\3)Aa(.*)$/\L\1\2\UAA\3AA\L\4\UAA\5AA\L\6/){
        if($N eq $n){
            # mark top-left corner used (x)
            substr($N,(length $1)+(length $2),1)="X"
        }
        # mark bottom-right corner used (x)
        substr($M,-(length $6)-1,1)="X";

        # Fill in sides of identified box
        $c=~s/^([xa;]*;)?(a*)A(A*)A(a*;)\2a((?i)\3)a/\1\2A\3A\4\2A\5A/;
        1 while $c=~s/(^|;)(a*)A(a*)A(a*;)\2a((?i)\3)a/\1\2A\3A\4\2A\5A/;

        # Replace output chars with "o" where box was found
        while($c=~/A/g){
            substr($o,(pos $c)-1,1)="o"
        }

        # Continue to next box
        $c=$M
    }
}

# Convert to nice output & print
$o=~y/;/\n/;
print$o

```

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


title: Build me a brick road!

text:
# Question
Title: Build me a brick road!
I need help making a brick road to go beside my brick wall!

```
\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \
 \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__
__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\
\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \
 \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__
__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\
\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \
 \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__
__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\
\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \

```

This road is `10` characters long and `70` characters wide, seems familiar right?

We have to stay efficient with this road as well, no input and lowest byte count in some code that produces this pattern in an output wins!

This code-golf puzzle isn't the same as the predecessor mentioned above, as the output requires a different approach rather than just simply outputting what it asks (because the pattern is offscured and not exactly the same). It was purposefully included like this for the puzzle to match the theme of my page and also include a higher difficulty for the user (the original was very simple for some). This was mentioned below in the comments.

# Answer
## Pyke, 19 bytes

```
"\  \__"w�*Tf70L<_X

```

where � is the literal byte 156.

Try it here!
> 1 votes

# Answer
# , 20 bytes

```
123i\  \__ò70|lé
4x

```

Try it online!

As usual, here is a hexdump:

```
0000000: 3132 3369 5c20 205c 5f5f 1bf2 3730 7c6c  123i\  \__..70|l
0000010: e90a 3478                                ..4x

```

Explanation:

```
123                     " 123 times:
   i                    " Insert the following:
    \  \__              " '\  \__'
          <esc>         " Return to normal mode
               ò        " Recursively:
                70|     "   Move to the 70th column
                   l    "   Move one char over
                    é   "   Insert a single newline
4x                      "   Delete 4 characters

```
> 1 votes

# Answer
# Retina, ~~32~~ 31 bytes

```

123$*_

\  \_
S_`(.{70}).{0,4}

```

Try it online!
> 1 votes

# Answer
## PowerShell v2+, ~~58~~ 38 bytes

```
'\  \__'*123-split"(.{70}).{0,4}"-ne''

```

Basically the same as my Build me a brick wall answer, just with additional logic to take the appropriate portions. Thanks to @MartinEnder for saving 20 bytes.

```
PS C:\Tools\Scripts\golfing> .\build-me-a-brick-road.ps1
\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \
 \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__
__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\
\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \
 \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__
__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\
\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \
 \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__
__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\
\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \

```
> 1 votes

# Answer
# Python 2, ~~79~~ 78 bytes

```
for x in range(10):a='\\  \\__';b=a*11+a[:4];print b[x*2:70]+b[4:x*3+4-x]

```

Got there in the end. Just builds a big string, cuts off the beginning and kind of adds the beginning to the end (if that makes sense).

-1 for an unneeded 0

Output:

```
python follow-the-yellow-brick-road.py
\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \
 \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__
__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\
\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \
 \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__
__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\
\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \
 \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__
__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\
\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \__\  \

```
> 1 votes

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


title: Choose the last card in a poker hand

text:
# Question
Title: Choose the last card in a poker hand
Poker hands are ranked from best to worst as follows:

1. Straight flush - five cards of sequential rank, all of the same suit
2. Four of a kind - four cards of the same rank and one card of another rank
3. Full house - three cards of one rank and two cards of another rank
4. Flush - five cards all of the same suit
5. Straight - five cards of sequential rank
6. Three of a kind - three cards of the same rank and two cards of two other ranks
7. Two pair - two cards of the same rank, two cards of another rank and one card of a third rank
8. One pair - two cards of the same rank and three cards of three other ranks
9. High card - five cards not all of sequential rank or of the same suit, and none of which are of the same rank

* Rank = The number on the card (A, K, Q, J, 10, 9, 8, 7, 6, 5, 4, 3, 2). You may choose to use T instead of 10.
* Suit = hearts (h), spades (s), clubs (c) and diamonds (d).

Note that the Ace, `A`, can both be the highest and the lowest number (1 or 14).

A card can be identified by two letters `As` (Ace of spades), `Jc` (Jack of clubs), `7h` (7 of hearts) and so on.

---

### Challenge:

You get four cards from the dealer (four input strings). Find and output the best possible last card you can get.

If there are cards that are equally good then you can choose which to pick.

Input and output formats are optional, but the individual cards must identified as shown above `Jc` and `2h`.

---

### Test cases:

```
Ah Kh Jh 10h
Qh

7d 8h 10c Jd
9d (or 9h, 9c, 9s)

Js 6c 10s 8h
Jc (or Jh, Jd)

Ac 4c 5d 3d
2h (or 2d, 2c, 2s)

5s 9s Js As
Ks

2h 3h 4h 5h
6h

Js Jc Ac Ah
As (or Ad)  <- Note that AAAJJ is better than AAJJJ because A is higher than J

10d 9d 5h 9c
9h (or 9s)

Ah Ac Ad As
Ks (or Kd, Kh, Kc)

4d 5h 8c Jd
Jc (or Js, Jh)

```

This is code golf, so the shortest submission in bytes win.

# Answer
> 13 votes
# Pyth, 73 bytes

```
eo_S+*-5l@\AN}SPMJ+NZSM.:+\AT5+-4l{eMJlM.gPkJ-sM*=T+`M}2Tc4"JQKA""hscd"=Zc

```

This is pretty terrible. Parsing cards, sorting the values, ... Everything takes so many chars. But the approach is interesting.

Try it online: Demonstration or Test Suite

### Explanation:

I generate all 52 cards, remove the four cards of the input, generate a score for each card (score of the hand), and print the card with the maximal score.

The score is a little bit odd. If I compare the score of two completely different hands, it may pick the wrong winner. E.g. a straight would beat 4 aces. But it works, if the first 4 cards are the same in both hands. And my computed score is actually not a value, but a list of values:

* G: First I group the 5 cards by rank and take the lengths: `5h 5d 6c 5s Jd` `->` `[3, 1, 1]`
* F: Then I append 4 minus the number of different suites to this list. `Flush` `->` `3` gets appended, `not flush` `->` `2/1/0` gets appended.
* S: Add another number. `0` if it is not a straight, `4` if it is the straight `A2345`, or `5` if it is a higher straight.

These lists of 4-7 numbers get sorted in decreasing order and the list with maximal value is picked.

Why does this work? Here you see the possible configurations for all types. The letter beside the numbers, tell you with which rule this number got generated.

* Straight flush: `[5S, 3F, 1G, 1G, 1G, 1G, 1G]` or `[4S, 3F, 1G, 1G, 1G, 1G, 1G]`
* Four of a kind: `[4G, 1G, 0F, 0S]`
* Full house: `[3G, 2G, 1F, 0S]` or `[3G, 2G, 0F, 0S]`
* Flush: `[3F, 1G, 1G, 1G, 1G, 1G, 0S]`
* Straight: `[5S, 2F, 1G, 1G, 1G, 1G, 1G]`, `[5S, 1F, 1G, 1G, 1G, 1G, 1G]`, `[5S, 1G, 1G, 1G, 1G, 1G, 0F]`, `[4S, 2F, 1G, 1G, 1G, 1G, 1G]`, `[4S, 1F, 1G, 1G, 1G, 1G, 1G]`, `[4S, 1G, 1G, 1G, 1G, 1G, 0F]`
* Three of a kind: `[3G, 1G, 1G, 1F, 0S]`, `[3G, 1G, 1G, 0F, 0S]`
* Two pair: `[2G, 2G, 2F, 1G, 0S]`, `[2G, 2G, 1F, 1G, 0S]`, `[2G, 2G, 1G, 0F, 0S]`
* One pair: `[2G, 2F, 1G, 1G, 1G, 0S]`, `[2G, 1G, 1G, 1G, 1F, 0S]`, `[2G, 1G, 1G, 1G, 0F, 0S]`
* High card: `[2F, 1G, 1G, 1G, 1G, 1G, 0S]`, `[1F, 1G, 1G, 1G, 1G, 1G, 0S]`, `[1G, 1G, 1G, 1G, 1G, 0S, 0F]`

Pyth compares lists element-wise. So it's obvious that a Straight flush will always beat Four of a kind. Most of the typical poker rules are obvious with these lists. Some seem conflicting.

* A Straight will win against Four of a kind or a Full house: Not a problem. If you have a chance to get Four of a kind / Full house with the river card, than you can't reach a straight at the same time (since you already have 2 or 3 different suites in your hand).
* A Straight will win against a flush. If you can reach a flush and a straight with the river card, then you also can reach a straight flush. And the straight flush has a better score than both the straight and the flush.
* One pair `[2G, 2F, 1G, 1G, 1G, 0S]` will win against some two pair hands. Also no problem. If you get a two pair with the river card, than you had at least one pair before the river. But this means, that you can improve to three of a kind, which is better. So a two pair will actually never be the answer.
* High card `[2F, 1G, 1G, 1G, 1G, 1G, 0S]` will win against some one pair hands. If this is the best score you can reach, before the river you will have 3 cards of one suite and one card of a different suite. But then you can choose the card with one of these two suites and with a value that already appears, and you'll end up with the score `[2F, 2G, ...]`, which is also better.

So this chooses the correct type of solution. But how do I get the best one-pair (out of 4 possibilities), how do I choose the best straight, ...? Because two different one-pair solutions can have the same score.

That's easy. Pyth guaranties stable sorting (when taking the maximum). So I simple generate the cards in the order `2h 2s 2c 2d 3h 3s ... Ad`. So the card with the highest value will automatically be the maximum.

### Implementation details

`=Zc` splits the input string and stores the list of cards in `Z`. `=T+`M}2Tc4"JQKA"` generates the list of ranks `['2', ..., '10', 'J', 'Q', 'K', 'A']` and stores them in `T`. `-sM*T..."hscd"Z` generates each combination of rank with the suites, and removes the cards of `Z`.

`o...` orders these remaining cards by: `lM.gPkJ` the lenght of the groups of the ranks, `+-4l{eMJlM` appends 4 - length(suites), `+*-5l@\AN}SPMJ+NZSM.:+\AT5` appends 0/4/5 depending on suite (generate each substring of length 5 of "A"+T, check if the hand one of them (requires sorting the hand and sorting all subsets), multiply by 5 - number of "A"s in the card), `_S` sorts the list decreasing.

`e` pick the maximum and print.

# Answer
> 4 votes
## JavaScript (ES6), ~~329~~ ~~324~~ ~~317~~ ~~312~~ 309 bytes

```
H=>[..."cdhs"].map(Y=>[...L="AKQJT98765432"].map(X=>~H.indexOf(X+=Y)||([...H,X].map(([R,S])=>a|=eval(S+'|=1<<L.search(R)',F|=S!=H[0][1]),F=a=c=d=h=s=0),x=c|d,y=h|s,c&=d,h&=s,p=c|x&y|h,t=c&y|h&x,(S=a-7681?((j=a/31)&-j)-j?F?c&h?2e4+a:t?t^p?3e4+t:7e4:p?8e4+p:M:4e4+a:F?5e4+a:a:F?6e4:1e4)<M&&(R=X,M=S))),M=1/0)&&R

```

### How it works

For each remaining card in the deck, we compute a hand score `S`. The lower the score, the better the hand.

**Variables used to compute the score**

* `F`: falsy if the hand is a flush
* `c`: bitmask of Clubs
* `d`: bitmask of Diamonds
* `h`: bitmask of Hearts
* `s`: bitmask of Spades
* `x = c | d`: bitmask of Clubs OR Diamonds
* `y = h | s`: bitmask of Hearts OR Spades
* `a`: bitmask of all combined suits
* `p = c & d | x & y | h & s`: pair bitmask (1)
* `t = c & d & y | h & s & x`: three of a kind bitmask (1)

*(1) I wrote these formulas some years ago and used them in several poker engines. They do work. :-)*

**Other formulas**

* `c & d & h & s`: four of a kind bitmask
* `a == 7681`: test for the special straight "A, 2, 3, 4, 5" (0b1111000000001)
* `((j = a / 31) & -j) == j`: test for all other straights

**Score chart**

```
Value    | Hand
---------+--------------------------------------------
0   + a  | Standard Straight Flush
1e4      | Special Straight Flush "A, 2, 3, 4, 5"
2e4 + a  | Four of a Kind
3e4 + t  | Full House
4e4 + a  | Flush
5e4 + a  | Standard Straight
6e4      | Special Straight "A, 2, 3, 4, 5"
7e4      | Three of a Kind
8e4 + p  | Pair
Max.     | Everything else

```

**NB:** We don't have to care about Two-Pair which can't possibly be our best option. (If we already have one pair, we can turn it into a Three of a Kind. And if we already have two pairs, we can turn them into a Full House.)

### Test cases

```
let f =

H=>[..."cdhs"].map(Y=>[...L="AKQJT98765432"].map(X=>~H.indexOf(X+=Y)||([...H,X].map(([R,S])=>a|=eval(S+'|=1<<L.search(R)',F|=S!=H[0][1]),F=a=c=d=h=s=0),x=c|d,y=h|s,c&=d,h&=s,p=c|x&y|h,t=c&y|h&x,(S=a-7681?((j=a/31)&-j)-j?F?c&h?2e4+a:t?t^p?3e4+t:7e4:p?8e4+p:M:4e4+a:F?5e4+a:a:F?6e4:1e4)<M&&(R=X,M=S))),M=1/0)&&R

console.log(f(["Ah", "Kh", "Jh", "Th"]));   // Qh
console.log(f(["7d", "8h", "Tc", "Jd"]));   // 9d (or 9h, 9c, 9s)
console.log(f(["Js", "6c", "Ts", "8h"]));   // Jc (or Jh, Jd)
console.log(f(["Ac", "4c", "5d", "3d"]));   // 2h (or 2d, 2c, 2s)
console.log(f(["5s", "9s", "Js", "As"]));   // Ks
console.log(f(["2h", "3h", "4h", "5h"]));   // 6h
console.log(f(["Js", "Jc", "Ac", "Ah"]));   // As (or Ad)
console.log(f(["Td", "9d", "5h", "9c"]));   // 9h (or 9s)
console.log(f(["Ah", "Ac", "Ad", "As"]));   // Ks (or Kd, Kh, Kc)
console.log(f(["4d", "5h", "8c", "Jd"]));   // Jc (or Js, Jh)
```

# Answer
> 3 votes
# JavaScript (ES6), 307 ~~349~~

This is quite bulky and I'm not sure it's the best approach. ~~Still a little golfable perhaps.~~

```
h=>(r='_23456789TJQKAT',R=x=>r.search(x[0]),M=i=>[...'hcds'].some(s=>h.indexOf(j=h[i][0]+s)<0)&&j,[u,v,w,y]=h.sort((a,b)=>R(a)-R(b)).map(x=>R(x)),[,,d,e,f,g,k]=[...new Set(h+h)].sort(),q=10-u-v-w,s=(z=y>12)&q>0?q:y-u<5&&u*5+q-y,d>r?z?'Kh':'Ah':f>r?M((e>r?v<w:u<v)+1):s?r[s]+g:k?M(3):r[13-z-(w>11)-(v>10)]+g)

```

*Less golfed*

```
h=>(
  // card rank, 1 to 13, 0 unused
  // fake rank 14 is T, to complete a straight JQKA?
  // as I always try to complete a straight going up
  r = '_23456789TJQKAT',

  // R: rank a card
  R = x => r.search(x[0]),

  // M: find a missing card (to complete a same-rank set like a poker)
  // look for a card with the same rank of the card at position i
  // but with a suit not present in the hand
  M = i => [...'hcds'].some(s => h.indexOf(j=h[i][0]+s) < 0) && j,
  h.sort((a, b) => R(a)-R(b) ), // sort hand by rank
  [u,v,w,y] = h.map(x=>R(x)),   // rank of cards 0..3 in u,v,w,y

  // Purpose: look for duplicate rank and/or duplicate suits
  // Put values and suits in d,e,f,g,k, with no duplicates and sorted
  // suits are lowercase and will be at right end
  [,,d,e,f,g,k] = [...new Set(h+h)].sort(),

  // Only if all ranks are different: find the missing value to get a straight
  // or 0 if a straight cannot be obtained
  // The first part manages the A before a 2
  q = 10-u-v-w, s = y>12&q>0 ? q : y - u < 5 && u * 5 + q - y,

  d > r // d is lowercase -> all cards have the same rank
    ? u < 13 ? 'Ah' : 'Kh' // add a K to a poker of A, else add an A
    : e > r // e is lowercase -> 2 distinct ranks
      ? M(v<w ? 2 : 1) // go for a poker or a full house
      : f > r // f is lowercase -> 3 distinct ranks, we have a pair
        ? M(u<v ? 2 : 1) // find the pair and go for 3 of a kind
        : s // all different ranks, could it become a straight?
          ? r[s] + g // if there is only a suit, it will be a flush straight too
          : k // if there are 2 or more different suits
            ? M(3) // go for a pair with the max rank
            : r[13-(y>12)-(w>11)-(v>10)]+g // flush, find the max missing card
)

```

**Test**

```
F=
h=>(r='_23456789TJQKAT',R=x=>r.search(x[0]),M=i=>[...'hcds'].some(s=>h.indexOf(j=h[i][0]+s)<0)&&j,[u,v,w,y]=h.sort((a,b)=>R(a)-R(b)).map(x=>R(x)),[,,d,e,f,g,k]=[...new Set(h+h)].sort(),q=10-u-v-w,s=(z=y>12)&q>0?q:y-u<5&&u*5+q-y,d>r?z?'Kh':'Ah':f>r?M((e>r?v<w:u<v)+1):s?r[s]+g:k?M(3):r[13-z-(w>11)-(v>10)]+g)

output=x=>O.textContent+=x+'\n'

;`Ah Kh Jh Th -> Qh
7d 8h Tc Jd -> 9d 9h 9c 9s
Js 6c Ts 8h -> Jc Jh Jd
Ac 4c 5d 3d -> 2h 2d 2c 2s
5s 9s Js As -> Ks
2h 3h 4h 5h -> 6h
Js Jc Ac Ah -> As Ad
Td 9d 5h 9c -> 9h 9s
Ah Ac Ad As -> Ks Kd Kh Kc
4d 5h 8c Jd -> Jc Js Jh`
.split('\n')
.forEach(s=>{
  var o = s.match(/\w+/g) // input and output
  var h = o.splice(0,4) // input in h, output in o
  var hs = h+''
  var r = F(h)
  var ok = o.some(x => x==r)

  output((ok?'OK ':'KO ')+ hs + ' -> ' + r)
})
```

```
<pre id=O></pre>
```

---
Tags: code-golf, optimization, card-games
---


title: Downgoat-ify Animals!

text:
# Question
Title: Downgoat-ify Animals!
My Downgoat avatar has several distinct features

These features can however also apply to any other animal.

## Specification

Given an image of an animal (technically can be anything), you must apply the Downgoat properties to it.

**Border pixels** are the outer most pixels of the image.

The **background color** is defined as the most common color in the border pixels. When that color is interpreted as an (r, g, b, a) color, with each channel from \[0, 256), the background is defined as the area where the every channel of the given pixels' is within 50 of the "background color".

The process:

* Setting the background and all transparent pixels to `#232323`, `RGBA(35, 35, 35, 1.00)`
* Set all pixels which aren't the background to `#FC0D1B`, `RGBA(252, 13, 27, 1.00)`.
* Vertically reflect the image
* Add the text `-1` in Arial font, in the center of the image. The total height of the text should be 25% of the image's smallest dimension (i.e. `min(width, height) * 0.25`).

## Rules

* Feel free to assume the fonts are already installed
* Your threshold is supposed to be `50`, however you can take this number as input too. You do *not* get any decreased byte count anything for doing this however
* Refer to our image I/O defaults for any questions related to I/O formats.
* Image will always be at least 3x3 in size
* If there is no most common "border pixel color", it doesn't matter which border pixel color you use as the "background color", this however must be consistent.

## Examples

Input:

Output:

---

Input:

Output:

Input:

Output:

---

Input:

Output:

---

Input:

Output:

---

**More examples?**

An online implementation is available here: vihan.org/p/downgoatify/#50

---

This is so shortest code in bytes wins. Good luck!

# Answer
# ImageMagick 7.0.3 + bash + sed, 379 bytes

```
M=magick K=\#232323 P='-chop x%[fx:u[0].h-2]-0+1'
$M $1 -depth 8 ppm:W;$M W $P T;$M W -rotate 90 -shave 1x $P L
C=`$M T L +append -statistic mode +0 txt:-|sed -e "1d;s/.*#/#/;s/ .*//;q"`
$M W -background $K -flatten -fill $K -fuzz 20% -opaque $C +fuzz -fill \#FC0D1B +opaque $K -flip -pointsize %[fx:.282*min\(u[0].w,u[0].h\)] -fill white -draw 'gravity center text 0,0 "-1"' x:

```

# Ungolfed

```
# Make aliases for things we'll use repeatedly
M=magick K=\#232323 P='-chop x%[fx:u[0].h-2]-0+1'

# Copy the input file to a PPM file
$M $1 -depth 8 ppm:W

# Extract the border pixels into "T" (top and bottom), and "L" (left and right)
# PPM files, removing the ends from the "L" because they were already counted
$M W $P T;$M W -rotate 90 -shave 1x $P L

# Put the borders into one strip and reduce to a txt image of the "mode"
# color on stdout, then convert the first pixel to hex format string "C"
C=`$M T L +append -statistic mode +0 txt:-|sed -e "1d;s/.*#/#/;s/ .*//;q"`

# Make background "#232323" and compose transparent pixels against it
# Convert any pixels with color within "fuzz" distance of background to #232323
# Convert any remaining pixels to "#FC0D1B"
# Flip the image vertically
# Determine pointsize for text, 1/5 of min(w,h). 1 pixel == 1.44 points
# Draw text "-1" centered on the image
# Display the result to an X window

$M W -background $K -flatten                     \
-fill $K -fuzz 20% -opaque $C                    \
+fuzz -fill \#FC0D1B +opaque $K                  \
-flip                                            \
-pointsize %[fx:.282*min\(u[0].w,u[0].h\)]       \
-fill white -draw 'gravity center text 0,0 "-1"' \
x:

```

I'm getting a quite different answer for the dennis image, probably because ImageMagick's "-fuzz" computes a sphere with diameter of 2N units in rgb coordinates while the rules call for computing a cube with sides of 101 units in rgb coordinates. Varying the "fuzz" helped some. Also, the JPEG artifacts in the original seem to be interfering with the conversion.
> 11 votes

# Answer
## C, 32-bit Windows, 987 bytes

```
#include <windows.h>
#define A CreateCompatibleDC(c)
#define F z=GetPixel(d,x,y);r=z;g=z>>8;b=z>>16
#define C(X,Y) (X<0||Y<0||X>=s[2]||Y>=s[3]||!GetPixel(e,X,Y))
#define D ((C(x-1,y)||C(x+1,y)||C(x,y-1)||C(x,y+1))&&!C(x,y))
#define E(X,Y) ((Z+X-Y)*(Z+X-Y)<2501)
main(int a,int*n){HDC c,d,e,f,w;int x,y,s[9],z,*o,m,t,Z;unsigned char r,g,b,R,G,B;c=GetDC(w=GetDesktopWindow());d=A;e=A;SelectObject(d,f=LoadImage(0,n[1],0,0,0,16));SelectObject(e,LoadImage(0,n[2],0,0,0,16));GetObject(f,24,s+1);o=LocalAlloc(64/*Fixed,ZeroInit*/,8*s[2]*s[3]);for(x=t=Z=s[1]=s[0]=0;x<s[2];x++)for(y=0;y<s[3];y++)if D{F;for(m=0;m<t&&o[m]!=z;m+=2);o[m]=z;o[m+1]++;t+=2*(m>=t);}for(x=y=1;x<t;x+=2)if(o[x]>o[y])y=x;z=o[y-1];R=z;G=z>>8;B=z>>16;for(x=0;x<s[2];x++)for(y=0;y<s[3];y++){F;SetPixel(c,x,s[3]-y-1,(C(x,y)||(E(r,R)&&E(g,G)&&E(b,B)))?0x232323:0x1B0DFC);}SelectObject(c,CreateFont(-(s[2]>>2),0,0,0,400,0,0,0,0,0,0,0,0,"Arial"));SetBkMode(c,1);SetTextColor(c,0xFFFFFF);DrawText(c,"-1",2,s,37);ReleaseDC(w,c);}

```
* The file is saved with LF as line end, not with CR+LF to save some bytes.
* The program is written in a way that compiler warnings are generated to save some more bytes.
* The file will probably not compile as 64-bit program because the array "`s[]`" is used to do some implicit castings...
* The program takes two images (file names are given via command line):
    + The first image (first command line argument) is the R/G/B image in Windows .BMP format
    + The second image is the Alpha channel (black means: 0%, any other colour means: not 0%); the file is also in .BMP format and must have the same size or be larger than the first image
* The output image is displayed in the left upper corner of the screen
* I couldn't reproduce the boy with the yellow hair. Yellow seems to be too far away (\> 50) from white!

Ungolfed version:

```
#include <windows.h>

/*
 * Although this line costs us 32 bytes
 * Replacing "CreateCompatibleDC(c)" we'll
 * save 42 bytes in the golfed version later
 * so we save 10 bytes using this define!
 */
#define A CreateCompatibleDC(c)

/*
 * Macro: Get a pixel value at (x,y) to z
 * Also get r, g, b
 */
#define F z=GetPixel(d,x,y); \
    r=z; \
    g=z>>8; \
    b=z>>16

/*
 * Macro checking if a pixel is a
 * transparent colour or lies outside the
 * image
 */
#define C(X,Y) (X<0 || Y<0 || X>=s[2] || Y>=s[3] || !GetPixel(e,X,Y))

/*
 * Macro checking if a pixel at (x,y) is a border pixel
 */
#define D ((C(x-1,y) || C(x+1,y) || C(x,y-1) || C(x,y+1)) && !C(x,y))

/*
 * Macro checking if the difference between X and Y is less than 50
 * The variable "Z" must be type "int" and zero. It is used to
 * perform an implicit cast from "BYTE" to "int".
 */
#define E(X,Y) ((Z+X-Y)*(Z+X-Y)<2501)

/*
 * Note that the second argument is "char **",
 * not "int *".
 * We ignore resulting compiler warnings...
 */
main(int a, int * n)
{
    HDC c, d, e, f, w;
    int x, y, s[9], z, *o, m, t, Z;
    unsigned char r, g, b, R, G, B;

    /*
     * Get the HDC handle to the
     * screen (allowing us to create HDCs
     * for accessing bitmap files as well as
     * drawing directly to the screen!)
     */
    c=GetDC(w=GetDesktopWindow());
    /*
     * Create two virtual HDCs for accessing
     * the bitmap files.
     */
    d=A; /* Macro */
    e=A; /* Macro */
    /*
     * Load the two images:
     * The first argument is the image file with
     * the R/G/B channel
     * The second argument is the image file
     * containing the mask defined by the Alpha
     * channel:
     *   Black means = Alpha=0
     *   White means = Alpha>0
     *   (Any other colour means: Alpha>0)
     *
     * Note that "f" is of the type "HBITMAP",
     * not "HDC". We save 4 bytes in the golfed
     * version using HDC instead of HBITMAP and
     * compile the C file with compiler warnings
     * switched off!
     *
     * The second image should have the same size
     * as the first one. However it may be larger
     * than the first one. It must not be smaller!
     */
    SelectObject(d,f=LoadImage(0,n[1],0,0,0,16 /* 16=LR_LOADFROMFILE */));
    SelectObject(e,LoadImage(0,n[2],0,0,0,16));
    /*
     * Get the image information (size)
     */
    GetObject(f,24,s+1);
    /*
     * Search all background colours
     */
    o=LocalAlloc(64 /* Fixed, ZeroInit */,8*s[2]*s[3]);
    for(x=t=Z=s[1]=s[0]=0;x<s[2];x++)
        for(y=0;y<s[3];y++)
            if D
    {
        F; /* Macro */
        for(m=0;m<t && o[m]!=z;m+=2);
        o[m]=z;
        o[m+1]++;
        t+=2*(m>=t);
    }
    /*
     * Search the most common one
     */
    for(x=y=1;x<t;x+=2) if(o[x]>o[y]) y=x;
    z=o[y-1];
    R=z;
    G=z>>8;
    B=z>>16;
    /*
     * Draw the image directly to the screen
     */
    for(x=0;x<s[2];x++)
        for(y=0;y<s[3];y++)
    {
        F; /* Macro */
        /* C and E are macros: */
        SetPixel(c,x,s[3]-y-1,(C(x,y) ||
            (E(r,R) && E(g,G) && E(b,B)))?
            0x232323:0x1B0DFC);
    }
    /*
     * Draw the text over the image
     */
    SelectObject(c,CreateFont(-(s[2]>>2),0,0,0,400,0,0,0,0,0,0,0,0,"Arial"));
    SetBkMode(c,1 /* TRANSPARENT */);
    SetTextColor(c,0xFFFFFF);
    DrawText(c,"-1",2,s,37 /* center, vcenter, singleline */);
    /*
     * Unfortunately DrawText() won't work
     * when not doing this!
     */
    ReleaseDC(w,c);
}

```
> 11 votes

---
Tags: code-golf, graphical-output, image-processing
---


title: Quine Anagrams! (Robbers' Thread)

text:
# Question
Title: Quine Anagrams! (Robbers' Thread)
This is the robbers' thread. For the cops' thread, click here.

### Cops' Task

For the cops' thread, click here.

### Robbers' Task

* Find an uncracked submission on the cops' thread. (A submission may only be cracked once.)
* Unscramble the code to find a working quine.
* Post an answer on the robbers' thread. Include the language, the byte count, the user who posted the scrambled code, a link to that answer, and the unscrambled code.

Here is an example of a robber submission:

> # Python, 29 bytes, Oliver
>
> ```
> _='_=%r;print _%%_';print _%_
>
> ```

### Scoring

The user with the most cracks will be the winner of this section.

# Answer
> 6 votes
# Vim, 22 bytes, Loojvo

```
qtiqtqx0l"tp^V^[^[qx0l"tp

```

Try it online!

Explanation:

```
qt                  " Start recording in register 'q'
  i                 " Enter insert mode
   qtqx0l"tp        " Enter this string
            ^V^[    " Enter a literal 'esc' character
                ^[  " Exit insert mode
                  q " Stop recording

```

At this point, the buffer looks like this:

```
qtqx0l"tp^[

```

And the cursor is on the last column (the 'esc' key).

```
x                   " Delete the esc character
 0l                 " Move to the second character on this line
   "tp              " And paste register 't'

```

# Answer
> 6 votes
## Underload, 20 bytes, ais523

```
(:a~*(*S)):a~*(*S)*S

```

Try it online!

### Explanation

The basic quine in Underload is this:

```
(:aSS):aSS

```

Here is how it works:

```
                                  Stack:               Output:
(:aSS)      # Push string.        (:aSS)
      :     # Duplicate.          (:aSS) (:aSS)
       a    # Wrap in (...).      (:aSS) ((:aSS))
        S   # Print.              (:aSS)               (:aSS)
         S  # Print.                                   (:aSS):aSS

```

The first issue was to reduce the number of `S` we need, because we've only got 3 for use here. We can do this by making use of swapping (`~`) and concatenation (`*`):

```
(:a~*S):a~*S

```

Here, instead of printing twice, we put the `(...)` version and the plain version of the string together and print that only once.

The bigger puzzle is how print an odd number of `*` and `S`. I'm not even sure how I actually arrived at the final solution, but it turns out that we can do this by putting the tail of the output in a separate string. That string itself is duplicated in the first string, but the contents are not, which gives us the extra occurrences of `*` and `S` we need. Here is a breakdown of the final solution:

```
                        Stack:                       Output:
(:a~*(*S))              (:a~*(*S))
          :             (:a~*(*S)) (:a~*(*S))
           a            (:a~*(*S)) ((:a~*(*S)))
            ~           ((:a~*(*S))) (:a~*(*S))
             *          ((:a~*(*S)):a~*(*S))
              (*S)      ((:a~*(*S)):a~*(*S)) (*S)
                  *     ((:a~*(*S)):a~*(*S)*S)
                   S                                 (:a~*(*S)):a~*(*S)*S

```

# Answer
> 6 votes
## MATL, 20 bytes, Luis Mendo

```
'wo&GzL0fk'tl#DwI-ch

```

Try it online!

I've never used MATL before, so my understanding may be slightly off, but this is basically how it works:

```
'wo&GzL0fk' This is a string representation of the code, offset by 3
t           Creates a duplicate copy of the string
l#D         Adds quotes to the second copy
w           Swap the unquoted version to the top of the stack
I-          Offset the characters in that version by 3
c           Convert back to characters
h           Join with the quoted string

```

# Answer
> 4 votes
# Python 2, 54 bytes, Loojvo

```
l= ['l=', ';print l[0],`l`,l[1]'] ;print l[0],`l`,l[1]

```

Had a hard time finding it, as I have basically almost never touched python

# Answer
> 4 votes
# Retina, 20 bytes, Martin Ender

```

\)1S*`\(?
\)1S*`\(?
```

**Try it online**

I found this simply by messing around attempting to create a quine. I found the "shorter quine" that he hinted at first (or a similar one, at least), simply by experimenting (14 bytes):

```

\)1S*`
\)1S*`
```

**Try it online**

It took me about half an hour to an hour. Very clever, Martin!

# Answer
> 3 votes
# JavaScript ES6, 49 bytes, Mama Fun Roll

```
function f(){return    `${(((((k=>f+'')(f)))))}`}

```

Pretty much the standard JS function quine, with a little obfuscation.

# Answer
> 3 votes
## \>\<\>, 36 bytes, Erik the Golfer

```
'''000**rd3*:::?!;od0.!!+..233??dfrr

```

Try it online!

I'm quite sure that this is not the intended solution. However, \>\<\> quines make it fairly easy to get rid of most unwanted characters, except the `'`. Fortunately, the `:` made it quite easy to take care of those as well.

### Explanation

```
'''                                    Push everything except these quotes onto the stack.
   000**                               In effect, pushes a zero.
        r                              Reverse the stack.
         d3*                           Push 39 (the quote character).
            ::                         Make two copies. The stack now holds
                                       a null-terminated representation of the
                                       entire code.
                                       The print loop begins here...
              :                        Duplicate top of stack.
               ?!;                     Terminate if zero.
                  o                    Otherwise, print.
                   d0.                 Jump back to position 13, i.e. the
                                       beginning of the print loop.
                      !!+..233??dfrr   Unused characters.

```

# Answer
> 2 votes
# JavaScript, 147 bytes, jrich

+function e(){window[(w=[``>``]+``)[i=9/9]+w[i+i]+"ert"]('+'+e+'()');"  +./;;;;;=======>[]````````ccddddddeeeeeeeefiinnnnoooooorrrrrrrsttuwwx{}"}()

With all those extra chars, this is definitely not the intended solution :-)

# Answer
> 2 votes
## Haskell, 86 bytes, Laikoni

```
y!r=r:y:r:[y]>>=id;main=putStr$[succ$'!']!"y!r=r:y:r:[y]>>=id;main=putStr$[succ$'!']!"

```

Nice idea to get the `"` via `succ$'!'` (ascii char after `!`). There were some missing chars to get them the usual way, i.e. implicitly via `show` or `print`.

# Answer
> 1 votes
## Befunge, 15 bytes, James Holderness

```
<:0:+1_@#%9,:g-

```

Try it online!

### Explanation

The catch here is that the loop terminates when the current character is divisible by 9, which is only the case for `-`. Hence, that needs to go at the end.

```
<                 Run code from right to left.
              -   There will always be 2 zeros on top of the stack at this
                  point, and this just reduces them to 1 zero.
             g    Get the character at the coordinates given by the top
                  two stack values, (0, 0) initially.
           ,:     Print a copy of that character.
         %9       Modulo 9.
      _@#         Terminate if that is 0.
    +1            Increment the x coordinate.
   :              Duplicate it.
 :0               Push two zeros.

```

# Answer
> 1 votes
## PHP, 110 bytes, Oliver

```
<?php $x='<?php $x=0; echo strtr($x, array(chr(39).$x.chr(39)));'; echo strtr($x, array(chr(39).$x.chr(39)));

```

Thanks, I had fun and the `strtr([])` trick was a new one for me that I hope will save me some bytes in the future.

# Answer
> 0 votes
## Jelly, 3 bytes, Erik the Golfer

```
”ṘṘ

```

Try it online!

There aren't really that many options... (Plus, this is the standard quine.)

# Answer
> 0 votes
## Python 2, 105 bytes, Erik the Golfer

```
a='a=%r;print a%%a ###(((())))**-01::@@@@@[[]]gggiiirrr~';print a%a ###(((())))**-01::@@@@@[[]]gggiiirrr~

```

It's just the standard Python string formatting quine...

# Answer
> 0 votes
## Ruby, 53 bytes, wat

```
puts <<ENDIT*2,"ENDIT"
puts <<ENDIT*2,"ENDIT"
ENDIT

```

Just a modification of the standard heredoc quine:

```
puts <<2*2,2
puts <<2*2,2
2

```

---
Tags: code-golf, quine, cops-and-robbers, permutations
---


title: Magic mirror madness

text:
# Question
Title: Magic mirror madness
## Introduction

I have a room full of *magic mirrors*. They are mysterious artifacts that can duplicate any item, except another magic mirror. More explicitly, a duplicate version of the item will appear on the other side of the mirror, at the same distance. However, if there is another magic mirror in the way on either side, between the duplicating mirror and either item (original or duplicate), the duplicate is not formed. The original item can be either left or right of the mirror, and the duplicate will appear on the other side. Also, the duplicate item can itself be duplicated by another mirror. Items never block the duplication of other items (except by being directly on the position of the would-be duplicate).

## Input

Your input is a string consisting of the characters `.#|`, which represent empty space, items, and magic mirrors. There will always be at least one magic mirror in the input.

## Output

Your output shall be another string where each magic mirror has duplicated every item it can, according to the rules above. You can assume that there will always be an empty space on the spot where a duplicate item appears (so they will no go out of bounds).

## Examples

Consider the input string

```
.#.|.....|......#
 A B     C      D

```

where we have marked some positions for clarity. The mirror `B` duplicates item `A`, which ends up to its right:

```
.#.|.#...|......#
 A B     C      D

```

Mirror `C` then duplicates the new item:

```
.#.|.#...|...#..#
 A B     C      D

```

Mirror `C` cannot duplicate item `A`, since mirror `B` is in the way. It also cannot duplicate item `D`, since mirror `B` is in the way on the other side. Likewise, mirror `B` cannot duplicate item `D` or the duplicate next to it, since mirror `C` is in the way, so this is the correct output.

For another example, consider the input

```
.##..#...|#..##...|..##....#.
 AB  C   DE  FG   H  IJ    K

```

Mirror `D` can duplicate `A` and `B` to the right, and `E` and `G` to the left. `C` and `F` are already duplicates of each other. The string becomes

```
.##.##..#|#..##.##|..##....#.
 AB  C   DE  FG   H  IJ    K

```

Mirror `H` can duplicate `E`, `F`, and the duplicates of `A` and `B` to the right, and `I` to the left. `G` and `J` are already duplicates of each other, and mirror `D` is in the way of `K`. Now we have

```
.##.##..#|#..#####|#####..##.
 AB  C   DE  FG   H  IJ    K

```

Finally, mirror `D` can duplicate the duplicate of `I` to the left. We end up with

```
.#####..#|#..#####|#####..##.
 AB  C   DE  FG   H  IJ    K

```

## Rules and scoring

You can write either a full program or a function. The lowest byte count wins. Submissions that don't use regex engines compete separately from those that do, and may be marked with **(no regex)**.

## Test cases

```
"|" -> "|"
"..|.." -> "..|.."
".#.|..." -> ".#.|.#."
"..#|.#." -> ".##|##."
".#..|....|.." -> ".#..|..#.|.#"
".|..|.#....." -> "#|#.|.#....."
"...|.#...|....#" -> ".##|##...|...##"
"......#|......." -> "......#|#......"
".#.|.....|......#" -> ".#.|.#...|...#..#"
".......|...#.##|...." -> "##.#...|...#.##|##.#"
"...#..||.......#..#...#" -> "...#..||.......#..#...#"
".##|.#....||#||......#|.#" -> ".##|##....||#||.....##|##"
".##..#...|#..##...|..##....#." -> ".#####..#|#..#####|#####..##."
".#|...||...|#...|..##...|#...." -> ".#|#..||.##|##..|..##..#|#..##"
"....#.|...#.|..|.|.....|..#......" -> "..#.#.|.#.#.|.#|#|#.#..|..#.#...."
"..|....|.....#.|.....|...|.#.|..|.|...#......" -> ".#|#...|...#.#.|.#.#.|.#.|.#.|.#|#|#..#......"

```

# Answer
> 10 votes
## Retina, 50 bytes

```
+`([#.])(([#.])*\|(?>(?<-3>[#.])*))(?!\1)[#.]
#$2#

```

Try it online! (The first line enables a linefeed-separated test suite.)

I guess this is the opposite of a (no regex) submission.

### Explanation

This is simply a regex substitution, which is applied repeatedly (`+`) until the string stops changing. I'm using balancing groups to make sure that the two mirrored positions are the same distance from the given mirror (backreferences won't do, since the exact string on both sides of the `|` may be different).

```
([#.])            # Match and capture a non-mirror cell.
(                 # This will match and capture everything up to its corresponding
                  # cell so that we can write it back in the substitution.
  ([#.])*         #   Match zero or more non-mirror cells and push each one onto
                  #   group 3. This counts the distance from our first match to
                  #   the mirror.
  \|              #   Match the mirror.
  (?>             #   Atomic group to prevent backtracking.
    (?<-3>[#.])*  #     Match non-mirror while popping from group 3.
  )               #   There are three reasons why the previous repetition
                  #   might stop:
                  #   - Group 3 was exhausted. That's good, the next position
                  #     corresponds to the first character we matched.
                  #   - We've reached the end of the string. That's fine,
                  #     the last part of the regex will cause the match to fail.
                  #   - We've hit another mirror. That's also fine, because
                  #     the last part of the regex will still fail.
)
(?!\1)            # Make sure that the next character isn't the same as the first
                  # one. We're looking for .|# or #|., not for #|# or .|.
[#.]              # Match the last non-mirror character.

```

This is replaced with `#$2#` which simply replaces both the first and last character of the match with a `#`.

# Answer
> 9 votes
## Perl, 49 bytes

Full credit to @Martin Ender for this one who suggested this regex 15 bytes shorter than mine.

47 bytes of code + `-pl` flags

```
s/([.#])(\||[^|](?2)[^|])(?!\1)[^|]/#$2#/&&redo

```

To run it :

```
perl -plE 's/([.#])(\||[^|](?2)[^|])(?!\1)[^|]/#$2#/&&redo' <<< ".##..#...|#..##...|..##....#."

```

The first (`([.#])`) and last (`(?!\1)[^|]`) parts are the same as in Retina answer (see the explanation over there).
The middle part (`(\||[^|](?2)[^|])`) uses perl recursion (`(?2)`) to match either a mirror (`\|`) or (`|`) two not-mirrors-characters (`[^|]`) separated by the very same pattern (`(?2)`).

---

My older (and uglier) version: `s/([.#])(([^|]*)\|(??{$3=~s%.%[^|]%gr}))(?!\1)[^|]/#$2#/&&redo`

# Answer
> 4 votes
# Haskell (no regex), 117 bytes

```
r=reverse
s=span(<'|')
m=zipWith min
g a|(b,l:c)<-s a,(d,e)<-s c=b++l:g(m(r b++[l,l..])d++e)|0<1=a
f x=m(g x)$r.g.r$x

```

# Answer
> 2 votes
# C, 176 bytes

```
void t(char*a){int x=0;for(int i=0;a[i];i++)if(a[i]=='|'){for(int j=x;a[j]&&j<=i*2-x;j++){if((a[j]==35)&&(a[2*i-j]==46)){a[2*i-j]=35;i=-1;}if((i-j)&&(a[j]=='|'))break;}x=i+1;}}

```

**Ungolfed**

```
void t(char*a)
{
    int x=0;
    for(int i=0;a[i];i++)
        if(a[i]=='|')
        {
            for(int j=x;a[j]&&j<=i*2-x;j++)
            {
                if((a[j]=='#')&&(a[2*i-j]=='.'))
                {
                    a[2*i-j]='#';
                    i=-1;
                    break;
                }
                if((i!=j)&&(a[j]=='|'))
                    break;
            }
            x=i+1;
        }
}

```

# Answer
> 2 votes
# PHP, ~~123~~ ~~117~~ 100 bytes

```
for($t=$argv[1];$t!=$s;)$t=preg_replace("%([.#])(\||[.#](?2)[.#])(?!\g1)[.#]%","#$2#",$s=$t);echo$t;

```

program takes command line argument, regex taken from @Martin Ender/Dada. Run with `-r`.

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

```
s=>s.replace(/#/g,(c,i)=>(g(i,-1),g(i,1)),g=(i,d,j=h(i,d))=>j-h(j=j+j-i,-d)|s[j]!='.'||(s=s.slice(0,j)+'#'+s.slice(j+1),g(j,d)),h=(i,d)=>s[i+=d]=='|'?i:s[i]?h(i,d):-1)&&s

```

Ungolfed:

```
function mirror(s) {
    for (var i = 0; i < s.length; i++) {
        // Reflect each # in both directions
        if (s[i] == '#') s = reflect(reflect(s, i, true), i, false);
    }
    return s;
}
function reflect(s, i, d) {
    // Find a mirror
    var j = d ? s.indexOf('|', i) : s.lastIndexOf('|', i);
    if (j < 0) return s;
    // Check that the destination is empty
    var k = j + (j - i);
    if (s[k] != '.') return s;
    // Check for an intervening mirror
    var l = d ? s.lastIndexOf('|', k) : s.indexOf('|', k);
    if (l != j) return s;
    // Magically duplicate the #
    s = s.slice(0, k) + '#' + s.slice(k + 1);
    // Recursively apply to the new #
    return reflect(s, k, d);
}

```

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


title: The logical quine

text:
# Question
Title: The logical quine
**The challenge**

Simply write a program that outputs its own source code.

Nothing more than a regular quine.

**The problem**

We don't have a computer so we have to run the program on a programmable logic device (such as an FPGA, a CPLD, a gate array ...).

**The rules**

* Any device available on the market (such as a printer connected via Centronics port, an LED display, an RS232 terminal ...) connected to the logic device can be used to output the program.
* If you use any kind of programmable device as output device you are not allowed to put any program logic there!

Example: If you use RS232 to send data to a computer the computer must do nothing but displaying the data received from the RS232. However you are allowed to switch on RS232 options like echoing data back to the logic device if any existing terminal program has this feature.
* Any (recent or historic) "standard" coding (ASCII, UNICODE, EBCDIC, Morse code ...) can be used.
* The program needs only to output its own source code. The file only containing the mapping between VHDL/Verilog/... "wires" and the actual I/O pins, the file containing the compiler settings and similar files are not considered as "source code" and need not to be written.
* You have one clock input pin with the frequency of your choice (if you need that).
* On-chip units (like on-chip SRAM or on-chip multipliers) must not be used.
* For testing the code you can simulate the output device using additional code; of course you may simulate the logic device, too (if you don't have a real one).
* Standard loopholes apply.

**The winner**

* For calculating the size of the program it is assumed that the real output device (e.g. the printer) is connected to some I/O pins of the logic device.
* The code that requires the fewest "LE" cells on my FPGA (Altera EP2C20F484C7) wins.
* If my FPGA is too small (= not large enough for the smallest solution) we compile for the largest one having "LE"-type cells (EP4CGX150DF31I7).
* If that one is still not enough we try the largest one supported by the free-of-charge compiler (EP2AGX260FF35I5).
* If that device is still too small the size of the source code counts.

**Note**

Searching for "quine VHDL" in Google I found at least three quines written in VHDL on the first page!

Unfortunately none of them will work on a real logic device but only in the emulator because the standard output (of the emulator) is used.

Good luck!

# Answer
# Verilog, optimized for area, 130 LE gates

The quine itself (the actual file is encoded in DEC SIXBIT):

```
module q(s,d);inout s,d;wire[0:1023]v=1024'b0110111100101001011001111110110110010110100100001111011010010111010101110101010110010110111100101001011001111110110100100110100100001111011010100111010101110110111000011100111100111010011001111011100000001001000111011010100111000101100111111010100111010111010100100110101101101110111010011111010110111000011011001101111000011110011100111000000010001100001011111100111001011001001001111001010000001100110010011010011001100010001010100111100101010010011000101001011001111010011011100000001010010111011010010010110100010110111010100111011010100001100100011111100000011010010111110101110110100100010110111001011011101001000000001001011011001100111001010000001010100111011010100010110100010110111001011011101001001011011011111001001101011011001001010000000000000000101101101111100100110101101100100101000000110001001000110011001100100100001001011011101001101110101111110101110100000000110011001100100100011011110111101001110010100101111011010000011010010001010000010010010011111101110110011101010001010000010010010100000111100010;reg[9:0]i=759;reg[2:0]j=7;assign d=j<6?j==2:v[i];always@(posedge s)if(j>5)begin i=i+1;j=j&1^!i?7:1;end else j=j+1;endmodule

```

Readable version with comments and a testbench:

```
module q(s,d);
   // Declare the ports. Making them both "inout" is shortest.
   inout s,d;
   // Data storage for the program.
   wire[0:1023]v=1024'b{DATA GOES HERE};
   // i is the current bit number within the program.
   // This is relative to the /end of the data storage/ (not to the start
   // of the program), so it starts at a nonzero value so that the output
   // starts at the start of the program.
   reg[9:0]i=759;
   // When expanding bits to (6-bit) bytes, j is the bit number within
   // the expansion, from 1 for the first bit up to 6 for the last.
   // When not expanding, j is always 7.
   // DEC SIXBIT encoding for 0 is (from MSB to LSB) 010 000.
   // DEC SIXBIT encoding for 1 is (from MSB to LSB) 010 001.
   // We use SSI encoding for the output, so the MSB is sent first.
   reg[2:0]j=7;
   assign d=j<6?j==2:v[i];
   // When we get a strobe:
   always@(posedge s)
     // If we just output a bit, move onto the next bit.
     // We may also need to reset j.
     if(j>5)
       begin
          i=i+1;
          j=j&1^!i?7:1;
       end
     else
       // If we're inside a bit, continue to output that bit.
       j=j+1;
endmodule
// {TESTBENCH BELOW HERE}

`timescale 10ns / 1ns
module testbench();
   reg clock = 0;
   wire data, strobe;

   always
     #1 clock <= !clock;
   initial
     #14304 $finish;

   assign strobe = clock;
   q testquine(.s(strobe),.d(data));

   always @(negedge strobe)
      $display("%d", data);

endmodule // testbench

```

The use of Verilog gives me considerably more control over the low-level details than I'd have with Verity. In particular, it lets me control the clock and reset rules myself. This program's intended for a synchronous serial connection with strobe input `s` and data output `d`. Although each is only used in one direction, I declared them both as bidirectional to save a few bytes; I had to golf the non-data parts of the program down to 1024 bits to be able to use 10-bit logic gates internally (extra bits would be more expensive in area), and it only just scrapes under at 1008, so savings like this are important. In order to save a substantial amount of code, I rely on the FPGA's hardware reset circuitry rather than adding my own, and I merge the strobe and clock inputs (which is an old trick that's kind-of frowned upon nowadays because it makes it hard to keep the clock tree balanced at high clock speeds, but it's useful for golfing.) I hope that's synthesizable; I don't know how well Verilog synthesizers cope with using a bidirectional port as a clock.

The source is encoded in DEC SIXBIT (I'm assuming here that we interpret its single alphabet of letters as lowercase; a Verilog synthesizer would have no reason to use an uppercase interpretation). I used a six-bit character set internally in my other solution, then wasted bytes converting it; it's better to use a character set that's "naturally" six bits wide so that no conversion is necessary. I picked this particular six-bit character set because `0` and `1` differ only in their least significant bit, and only have one other bit set, meaning that the circuitry for converting a binary digit to DEC SIXBIT (i.e. "escaping" a string) can be very simple. Interestingly, the character set in question is missing a newline character; the original program's all on one line not *just* to make it easier to generate, but to make it possible to encode! It's a good thing that Verilog mostly doesn't care about whitespace.

The protocol for sending data to the host is based on Synchronous Serial Interface. I picked it because it's clocked (allowing me to use the clock/strobe trick, and also allowing me to write a portable program that doesn't rely on on-chip timing devices), and because it's very simple (thus I don't have to waste much code implementing it). This protocol doesn't specify a method of specifying where the message ends (the host is supposed to know); in this particular case, I padded the output up to a multiple of 1024 bits with zero bits (a total of 16 padding bits), after which (as required by SSI) the message restarts. (I don't implement an idle mode timer; its purpose is to determine whether to send a new message or whether to repeat the previous message, and as this program always sends its own source code as the message, the distinction isn't visible. You can consider it to be length 0, or infinitely long, depending on your point of view.)

In terms of the actual logic, the most interesting thing is the way that I split up the variables to reduce the amount of area needed on the chip. `i`, the larger register, holds the current "address" within the program's data, and is only ever changed via incrementing it; this means that its logic can be synthesized using the half-adder construction (which, as the name suggests, uses only half the resources that an adder does; this mostly only matters on the smallest FPGAs, larger ones will use 3-input or even 4-input LUTs which are powerful enough that they'll have lots of wasted capacity synthesizing a half-adder). The smaller register, `j`, is basically a state machine state and thus handles most of the program's complex logic. It's small enough that it can be handled entirely via lookup table on a larger FPGA (making the logic basically disappear); in case the program is synthesized for a small FPGA, I chose its encoding in such a way that few parts of the code care about all three of its bits at once.

It's also worth noting that I cyclically permuted the data storage. We can start `i` pointing anywhere inside it, not necessarily at the start. With the arrangement seen here, we can print from the initial value of `i` to the end directly, then print the entire array escaped, then print from the start to the initial value of `i`, in order to print the all the parts of the data in the right places without needing to save and restore the value of `i`. (This trick might be useful for quines in other languages too.)

The source is 1192 6-bit bytes long, the equivalent of 894 8-bit bytes. It's kind-of embarrassing that this contains fewer source bytes than my Verity submission, despite being optimized for something entirely different; this is mostly because Verilog has strings and Verity doesn't, meaning that even though I've encoded the program in binary rather than octal (which is substantially less efficient in terms of source code size), I can encode each byte of the program using six six-bit characters (one for each bit) rather than eight eight-bit characters (four for each octal digit). A Verilog submission that encoded the program in octal would probably be smaller in terms of source code size, but would almost certainly be larger in area.

I don't know how much area this program will end up using; it depends a lot on how powerful the optimizer is in your Verilog synthesizer (because the minimization problem of converting the stored data into a set of logic gates is something that's done in the synthesizer itself; throwing the work onto the synthesizer makes the source code itself much shorter, and thus reduces the area needed to store it). It should have a complexity of O(n log n), though, and thus be much smaller than the O(n²) of the other program. I'd be interested to see the OP try to run it on their FPGA. (It may take quite some time to synthesize, though; there are various steps you can take to optimize a program for compile time but I didn't take any here as it'd cause a larger program = larger area.)
> 7 votes

# Answer
# Verity 0.10, optimized for source code size (1944 bytes)

I originally misread the question and interpreted it as a . That was probably for the best, as it's much easier to write a quine with short source code than short object code under the restrictions in the question; that made the question easy enough that I felt I could reasonably produce an answer, and might work as a stepping stone on the way to a better answer. It also prompted me to use a higher-level language for the input, meaning that I'd need to express less in the program itself. I didn't create Verity as a golfing language for hardware (I was actually hired to create it a while ago in an entirely different context), but there's quite a reminiscence there (e.g. it's substantially higher level than a typical HDL is, and it has much less boilerplate; it's also much more portable than the typical HDL).

I'm pretty sure that the correct solution for short object code involves storing the data in some kind of tree structure, given that the question disallows the use of block ROM, which is where you'd normally store it in a practical program; I might have a go at writing a program that uses this principle (not sure what language, maybe Verity, maybe Verilog; VHDL has too much boilerplate to likely be optimal for this sort of problem) at some point. That would mean that you wouldn't need to pass every bit of the source code to every bit of your "manually created ROM". However, the Verity compiler currently synthesizes the structure of the output based on the precedence and associativity of the input, meaning that it's effectively representing the instruction pointer (thus the index to the lookup table) in unary, and a unary index multiplied by the length of the lookup table gives this O(n²) space performance.

The program itself:

```
import <print>new x:=0$1296in(\p.\z.\a.new y:=(-a 5-a 1-a 1-a 2-a 4-a 2-a 3-a 2-a 6-a 2-a 0-a 3-a 0-a 4-a 4-a 7-a 4-a 2-a 6-a 2-a 5-a 1-a 2-a 2-a 0-a 3-a 6-a 7-a 2-a 2-a 1-a 1-a 3-a 3-a 0-a 4-a 4-a 3-a 2-a 7-a 5-a 7-a 0-a 6-a 4-a 4-a 1-a 6-a 2-a 6-a 1-a 7-a 6-a 6-a 5-a 1-a 2-a 2-a 0-a 5-a 0-a 0-a 4-a 2-a 6-a 5-a 0-a 0-a 6-a 3-a 6-a 5-a 0-a 0-a 5-a 0-a 6-a 5-a 2-a 2-a 1-a 1-a 3-a 3-a 0-a 4-a 5-a 3-a 2-a 7-a 5-a 7-a 0-a 5-a 5-a 5-a 1-a 4-a 4-a 3-a 1-a 5-a 5-a 1-a 2-a 2-a 0-a 4-a 3-a 3-a 4-a 1-a 5-a 1-a 0-a 2-a 1-a 1-a 1-a 4-a 4-a 3-a 6-a 7-a 0-a 6-a 0-a 1-a 3-a 2-a 0-a 5-a 4-a 2-a 0-a 5-a 5-a 1-a 2-a 1-a 0-a 4-a 6-a 3-a 4-a 7-a 3-a 6-a 2-a 6-a 0-a 3-a 4-a 1-a 1-a 1-a 2-a 2-a 0-a 4-a 6-a 3-a 3-a 5-a 1-a 7-a 2-a 6-a 1-a 1-a 0-a 2-a 7-a 2-a 1-a 1-a 0-a 4-a 6-a 3-a 1-a 5-a 3-a 7-a 5-a 1-a 2-a 1-a 0-a 4-a 6-a 3-a 5-a 7-a 5-a 7-a 4-a 6-a 5-a 6-a 0-a 3-a 4-a 1-a 1-a 1-a 2-a 2-a 0-a 4-a 3-a 3-a 4-a 1-a 5-a 1-a 0-a 2-a 1-a 1-a 1-a 4-a 5-a 3-a 6-a 7-a 0-a 6-a 0-a 1-a 3-a 2-a 0-a 5-a 4-a 2-a 0-a 4-a 1-a 7-a 7-a 6-a 3-a 7-a 4-a 2-a 0-a 4-a 3-a 6-a 2-a 6-a 3-a 7-a 4-a 2-a 0-a 5-a 4-a 6-a 0-a 7-a 2-a 0-a 1-a 4-a 5-a 3-a 4-a 4-a 4-a 4-a 3-a 6-a 4-a 4-a 4-a 4-a 3-a 6-a 2-a 6-a 1-a 5-a 3-a 7-a 4-a 2-a 0-a 4-a 4-a 6-a 5-a 6-a 3-a 7-a 5-a 3-a 2-a 7-a 5-a 7-a 1-a 4-a 5-a 3-a 6-a 7-a 6-a 7-a 3-a 6-a 1-a 5-a 1-a 1-a 0-a 2-a 7-a 2-a 1-a 1-a 0-a 4-a 7-a 2-a 7-a 1-a 5-a 1-a 4-a 2-a 3-a 7-a 4-a 3-a 2-a 7-a 5-a 7-a 1-a 4-a 4-a 3-a 6-a 7-a 6-a 7-a 6-a 6-a 1-a 5-a 1-a 5-a 4-a 2-a 6-a 2-a 5-a 1-a 2-a 2-a 0-a 3-a 0-a 5-a 1-a 4-a 4-a 3-a 4-a 4-a 4-a 4-a 6-a 6-a 4-a 4-a 4-a 4-a 3-a 6-a 2-a 6-a 1-a 5-a 0-a 5-a 0-a 0-a 0-a 1-a 6-a 5-a 4-a 3-a 2-a 7-a 5-a 7-a 1-a 4-a 4-a 3-a 6-a 7-a 6-a 7-a 3-a 6-a 2-a 0-a 0-a 1-a 4-a 7-a 4-a 7-a 1-a 6-a 2-a 6-a 1-a 7-a 3-a 6-a 3-a 7-a 0-a 6-a 1-a 5-!x)in while!x>0do(p(if z<32then z+92else z);if z==45then while!y>0do(p 97;p 32;p(48^!y$$3$$32);p 45;y:=!y>>3)else skip;x:=!x>>6))print(!x$$6$$32)(\d.x:=!x>>3^d<<1293;0)

```

More readable:

```
import <print>
new x := 0$1296 in
(\p.\z.\a.
  new y := (-a 5-a 1-
            # a ton of calls to a() omitted...
            -a 1-a 5-!x) in
  while !x>0 do (
    p(if z<32 then z+92 else z);
    if z==45
    then while !y>0 do (
      p 97;
      p 32;
      p(48^!y$$3$$32);
      p 45;
      y:=!y>>3 )
    else skip;
    x:=!x>>6
  )
)(print)(!x$$6$$32)(\d.x:=!x>>3^d<<1293;0)

```

The basic idea is that we store the entire data in the variable `x`. (As usual for a quine, we have a code section and a data section; the data encodes the text of the code, and can also be used to regenerate the text of the data.) Unfortunately, Verity doesn't currently allow very large constants to be written in the source code (it uses OCaml integers during compilation to represent integers in the source, which clearly isn't correct in a language that supports arbitrarily wide integer types) – and besides, it doesn't allow constants to be specified in octal – so we generate the value of `x` at runtime via repeated calls to a function `a`. We could create a void function and call it repeatedly as separate statements, but that would make it hard to identify where to start outputting the text of the data section. So instead, I made `a` return an integer, and use arithmetic to store the data (Verity guarantees that arithmetic evaluates left to right). The data section is encoded in `x` using a single `-` sign; when this is encountered at run time, it's expanded to the full `-a 5-a 1-`, etc., via the use of `y`.

Initializing `y` as a copy of `x` is fairly subtle here. Because `a` returns zero specifically, most of the sum is just zero minus zero minus… and cancels itself out. We end with `!x` (i.e. "the value of `x`"; in Verity, as in OCaml, a variable's name works more like a pointer than anything else, and you have to dereference it explicitly to get at the variable's value). Verity's rules for unary minus are a little complex – the unary minus of `v` is written as `(-v)` – thus `(-0-0-0-!x)` parses as `(-(0-0-0-!x))`, which is equal to `!x`, and we end up initializing `y` as a copy of `x`. (It's also worth noting that Verity is *not* call-by-value, but rather allows functions and operators to choose the order they evaluate things; `-` will evaluate the left argument before the right argument, and in particular, if the left argument has side effects, those will be visible when the right argument is evaluated.)

Each character of the source code is represented using two octal digits. This means that the source code is limited to 64 different characters, so I had to create my own codepage for internal use. The output is in ASCII, so I needed to convert internally; this is what the `(if z<32 then z+92 else z)` is for. Here's the character set I used in the internal representation, in numerical order (i.e. `\` has codepoint 0, `?` has codepoint 63):

```
\]^_`abcdefghijklmnopqrstuvwxyz{ !"#$%&'()*+,-./0123456789:;<=>?

```

This character set gives us most of the characters important for Verity. Notable characters missing are `}` (meaning that we can't create a block using `{}`, but luckily all statements are expressions so we can use `()` instead); and `|` (this is why I had to use an exclusive rather than inclusive OR when creating the value of `x`, meaning I need to initialize it to 0; however, I needed to specify how large it was anyway). Some of the critical characters that I wanted to ensure were in the character set were `<>` (for imports, also shifts), `()` (very hard to write a program that can be parsed without these), `$` (for everything to do with bitwidth), and `\` (for lambdas; theoretically we could work around this with `let…in` but it would be much more verbose).

In order to make the program a bit shorter, I constructed abbreviations for `print` and for `!x$$6$$32` (i.e. "the bottom 6 bits of `!x`, cast to be usable to the `print` library) via temporarily binding them to lambda arguments.

Finally, there's the issue of output. Verity provides a `print` library that's intended for debug output. On a simulator, it prints the ASCII codes to standard output, which is perfectly usable for testing the program. On a physical circuit board, it depends on a `print` library having been written for the particular chip and board surrounding it; there's a `print` library in the Verity distribution for an evaluation board I had access to that prints the output on seven-segment displays. Given that the library will end up taking space on the resulting circuit board, it may be worth using a different language for an optimized solution to this problem so that we can output the bits of the output directly on wires.

By the way, this program is O(n²) on hardware, meaning that it's much worse on a simulator (I suspect O(n⁴); not sure, though, but it was hard enough to simulate that it seems unlikely to be even cubic, and based on how the time reacted to my changes as I was writing the program, the function seems to grow very quickly indeed). The Verity compiler needed 436 optimization passes (which is much, much more than it'd typically use) to optimize the program, and even after that, simulating it was very hard for my laptop. The complete compile-and-simulate run took the following time:

```
real  112m6.096s
user  105m25.136s
sys   0m14.080s

```

and peaked at 2740232 kibibytes of memory. The program takes a total of 213646 clock cycles to run. It does work, though!

Anyway, this answer doesn't really fulfil the question as I was optimizing for the wrong thing, but seeing as there are no other answers yet, this is the best by default (and it's nice to see what a golfed quine would look like in a hardware language). I'm not currently sure whether or not I'll work on a program that aims to produce more optimized ouptut on the chip. (It would likely be a lot larger in terms of source, as an O(n) data encoding would be rather more complex than the one seen here.)
> 2 votes

---
Tags: code-challenge, quine, logic-gates
---