答:
Python 3 <s>223</s> <s>222</s> 165 Bytes

Okay, I know this isn't the prettiest answer out there, and I'm sure it can be golfed down quite a bit, but I was just messing around and seeing what I could do

Shout out to mbomb007 for the tips on whitespace and comparators
Also, I saw my online character counter was taking all the tabs and turning them into spaces, so the count is a lot less than I originally had

```<code>def u(a):
 m,r,x=9,0,len(a)
 for i in range(x):
    d=0
    if a[i]<'1':
     for j in range(x):
        if a[j]>'0':d+=float((j-i)**-2)
     if d<m:r=i;m=d
 return a[:r]+'1'+a[r+1:]
</code>```

Showing revised whitespace:

```<code>def u(a):
<sp> m,r,x=9,0,len(a)
<sp> for i in range(x):
<tab> d=0
<tab> if a[i]<'1':
<tab><sp> for j in range(x):
<tab><tab> if a[j]>'0':d+=float((j-i)**-2)
<tab><sp> if d<m:r=i;m=d
<sp> return a[:r]+'1'+a[r+1:]
</code>```

Original:

```<code>def u(a):
    m,r,x=9,0,len(a)
    for i in range(x):
        d=0
        if a[i]!='1':
            for j in range(x):
                if a[j]=='1':d+=float(1/(j-i)**2)
            if d<m:r=i;m=d
    return a[:r]+'1'+a[r+1:]
</code>```

This expects a string passed to it of 1's and 0's like "10001" and returns a string "10101"

Edit: Changed 1/float((j-i)**2) to float((j-i)**-2)

Title: Positional Bathroom Etiquette

Body:
Background

Bathroom Etiquette, when pertaining to the available urinals, states that the next urinal to be filled in should be the one that minimizes the total discomfort. The total discomfort equation is given by the following set of equations:

```
<b>dist(x,y)</b> = linear distance between person x and person y in Urinal Units
<b>discomfort(x)</b> = sum(1/(dist(x,y)*dist(x,y))) for all persons y excluding person x
<b>total_Discomfort</b> = sum(discomfort(x)) for all x
```

A more in depth paper dealing with a similar (not the exact same) problem can be found here: (Thanks to @Lembik for alerting me to this amazing whitepaper!)

Input/Output

Given an input of a empty and full urinals, output the resulting set of urinals with the addition of one person. If there is a tie for a position the urinals should fill in left to right. The output should be in the same format as the input.

If given a case with full urinals, return the input.

The input will always have at least one urinal defined.

Test Cases

```
<b>INPUT     -> OUTPUT</b>
1000001   -> 1001001
101010101 -> 111010101
100       -> 101
00000     -> 10000
1111111   -> 1111111
0100      -> 0101
101000    -> 101001
```

Rules

This is code-golf, so shortest code in bytes wins. Standard loop-holes are forbidden.

Body:
Python 3 <s>223</s> <s>222</s> 165 Bytes

Okay, I know this isn't the prettiest answer out there, and I'm sure it can be golfed down quite a bit, but I was just messing around and seeing what I could do

Shout out to mbomb007 for the tips on whitespace and comparators
Also, I saw my online character counter was taking all the tabs and turning them into spaces, so the count is a lot less than I originally had

def u(a):
 m,r,x=9,0,len(a)
 for i in range(x):
    d=0
    if a[i]<'1':
     for j in range(x):
        if a[j]>'0':d+=float((j-i)**-2)
     if d<m:r=i;m=d
 return a[:r]+'1'+a[r+1:]

Showing revised whitespace:

def u(a):
<sp> m,r,x=9,0,len(a)
<sp> for i in range(x):
<tab> d=0
<tab> if a[i]<'1':
<tab><sp> for j in range(x):
<tab><tab> if a[j]>'0':d+=float((j-i)**-2)
<tab><sp> if d<m:r=i;m=d
<sp> return a[:r]+'1'+a[r+1:]

Original:

def u(a):
    m,r,x=9,0,len(a)
    for i in range(x):
        d=0
        if a[i]!='1':
            for j in range(x):
                if a[j]=='1':d+=float(1/(j-i)**2)
            if d<m:r=i;m=d
    return a[:r]+'1'+a[r+1:]

This expects a string passed to it of 1's and 0's like "10001" and returns a string "10101"

Edit: Changed 1/float((j-i)**2) to float((j-i)**-2)


问:
Positional Bathroom Etiquette

Background

Bathroom Etiquette, when pertaining to the available urinals, states that the next urinal to be filled in should be the one that minimizes the total discomfort. The total discomfort equation is given by the following set of equations:

```
<b>dist(x,y)</b> = linear distance between person x and person y in Urinal Units
<b>discomfort(x)</b> = sum(1/(dist(x,y)*dist(x,y))) for all persons y excluding person x
<b>total_Discomfort</b> = sum(discomfort(x)) for all x
```

A more in depth paper dealing with a similar (not the exact same) problem can be found here: (Thanks to @Lembik for alerting me to this amazing whitepaper!)

Input/Output

Given an input of a empty and full urinals, output the resulting set of urinals with the addition of one person. If there is a tie for a position the urinals should fill in left to right. The output should be in the same format as the input.

If given a case with full urinals, return the input.

The input will always have at least one urinal defined.

Test Cases

```
<b>INPUT     -> OUTPUT</b>
1000001   -> 1001001
101010101 -> 111010101
100       -> 101
00000     -> 10000
1111111   -> 1111111
0100      -> 0101
101000    -> 101001
```

Rules

This is code-golf, so shortest code in bytes wins. Standard loop-holes are forbidden.

答:
PHP, 135  bytes

```<code>$a=explode(1,$argv[1]);$b=0;foreach($a as$c=>$d){$l=strlen($d);if($l>$b){$b=$l;$e=$c;}}if($b)$a[$e][intval($b/2)]=1;echo implode(1,$a);
</code>```

I'm sure there's a considerably quicker way of doing it, but I've got a fuzzy head and can't think of one!

Old code

The code without minification:

```<code>$a=explode(1,$argv[1]);
$b=0;
foreach($a as $c=>$d){
    $l=strlen($d);
    if($l>$b){
        $b=$l;
        $e=$c;
    }
}
if($b){
    $a[$e][intval($b/2)]=1;
}
echo implode(1,$a);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Positional Bathroom Etiquette

Body:
PHP, 135  bytes

$a=explode(1,$argv[1]);$b=0;foreach($a as$c=>$d){$l=strlen($d);if($l>$b){$b=$l;$e=$c;}}if($b)$a[$e][intval($b/2)]=1;echo implode(1,$a);

I'm sure there's a considerably quicker way of doing it, but I've got a fuzzy head and can't think of one!

Old code

The code without minification:

$a=explode(1,$argv[1]);
$b=0;
foreach($a as $c=>$d){
    $l=strlen($d);
    if($l>$b){
        $b=$l;
        $e=$c;
    }
}
if($b){
    $a[$e][intval($b/2)]=1;
}
echo implode(1,$a);


问:
Leyland Numbers
Given a natural number \$n\$, return the \$n\$-th Leyland number.

Leyland Number

Leyland numbers are positive integers \$k\$ of the form

$$k = x^y + y^x$$

Where \$x\$ and \$y\$ are integers strictly greater than 1.

They are enumerated in ascending order.

EDIT: @DigitalTrauma suggested I include following "definition":

Imagine we throw \$x^y+y^x\$ in a bag for all possible values of \$x\$ and \$y\$, and avoid throwing in duplicates. Then we sort that bag. The sorted bag is our sequence.

Details

You may use 0 or 1 based indexing, whatever suits you best.

Your program must be able to output at least all Leyland numbers less than the maximum of signed 32-bit integers. (The last Leyland number below this limit is 1996813914, at index 82.)

Test cases

The first few terms are following:

```<code>8, 17, 32, 54, 57, 100, 145, 177, 320, 368, 512, 593, 945, 1124
</code>```

A076980 in OEIS, except for the first entry. Note that because of that additional first entry, the indices on OEIS are shifted by one.

More can be found in the OEIS b-file

答:
R, <s>58</s> 54 bytes

1-indexed. Eliminated 4 bytes by using pryr::r instead of function.

```<code>unique(sort(outer(2:99,2:9,pryr::f(x^y+y^x))))[scan()]
</code>```

Explanation

For all numbers from 2 to 99, and 2 to 9,

```<code>                  2:99,2:9
</code>```

apply the function x^y+y^x. This generates a 98x8 matrix.

```<code>            outer(2:99,2:9,pryr::f(x^y+y^x))
</code>```

Sort this matrix (coercing it to a vector):

```<code>       sort(outer(2:99,2:9,pryr::f(x^y+y^x)))
</code>```

Remove all non-unique values:

```<code>unique(sort(outer(2:99,2:9,pryr::f(x^y+y^x))))
</code>```

Read n from stdin, and fetch the nth number from the list:

```<code>unique(sort(outer(2:99,2:9,pryr::f(x^y+y^x))))[scan()]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Leyland Numbers

Body:
R, <s>58</s> 54 bytes

1-indexed. Eliminated 4 bytes by using pryr::r instead of function.

unique(sort(outer(2:99,2:9,pryr::f(x^y+y^x))))[scan()]

Explanation

For all numbers from 2 to 99, and 2 to 9,

                  2:99,2:9

apply the function x^y+y^x. This generates a 98x8 matrix.

            outer(2:99,2:9,pryr::f(x^y+y^x))

Sort this matrix (coercing it to a vector):

       sort(outer(2:99,2:9,pryr::f(x^y+y^x)))

Remove all non-unique values:

unique(sort(outer(2:99,2:9,pryr::f(x^y+y^x))))

Read n from stdin, and fetch the nth number from the list:

unique(sort(outer(2:99,2:9,pryr::f(x^y+y^x))))[scan()]


问:
Markov Chain Quine
A simple Markov Model will be used in this question. For more information about Markov Chains, see http://setosa.io/ev/markov-chains/.

Take a string. For this example, we will use the word:

```<code>reader
</code>```

Now, for each character, take the characters that appear after each occurence of the character in the string. (`^` represents the start of the string and `$` represents the end)

```<code>`^` -> {'r'}       # After the start of the string, there is an `r`.
'r' -> {'e', `$`}  # After the first `r` (*r*eader), there is an `e`
                   # after the second (reade*r*), there is the end of the string.
'e' -> {'a', 'r'}
'a' -> {'d'}
'd' -> {'e'}
</code>```

Now, starting from the start of the string, pick randomly from one of the characters in the next set. Append this character and then pick from the characters in its next set, and so on until you get to the end. Here are some example words:

```<code>r
rereader
rer
readereader
</code>```

If a character appears after another character multiple times, it is more likely to be chosen. For example, in cocoa can, after a c, there is a two thirds of a chance of getting an o and a one thirds chance of getting an a.

```<code>'c' -> {'o', 'o', 'a'}
</code>```

Challenge

Create a program that takes no input and outputs a random string generated using a Markov Chain, like above, where the input to the chain is the program's source.

The program must have at least two characters, two of which must be the same (To prevent "boring" chains that only have one output)

You can modify the model to use bytes instead of characters if you wish, but change "characters" to "bytes" in rule 1

The program should output strings randomly with the expected frequency in theory

This is code-golf, so the shortest program wins!

答:
Perl 5, 81 bytes

Based on the standard quine and my answer to this question:

$_=q{@$=a^E;@$="\$_=q{$_};eval"=~/(?<=\Q$@\E).?/g,print$@while$@=$$[rand@$]};eval
```
<p>Try it online!</p>
<p>As with the faux source code answer, this sometimes produces valid Perl, but very infrequently (<2%):</p>
<pre class="lang-perl prettyprint-override"><code><span class="math-container">$$$_=al
$_=a^E;eval
$_=al
$$</span>=q{<span class="math-container">$$]};eval
$@=a^E;@whil
$_=q{@\E;e$]};evaleva^E;eval
$$</span>=q{@<span class="math-container">\$_=a^E;evant$@$="=$$]};evaleval
$_=q{@whind@$_=$]};eval
$_=q{@\$@=~/(?<=\$[rilevale$=ant$[rint$_};evaleval
$_=aleval
$_=q{@$_};@whil
$$=q{@$=q{@$=\E;evand@whint$_};eva^E).?<=$=~/g,prand@$_=al"\E;e$@\E).?/g,prant$_};evaleval
$_=\$</span>_=~/g,prind@=q{$]};@$@\Q$$$_};e$@$_=q{@$_=~/g,pril
$_=q{$=aleval"\E;evaleva^E;eva^E).?/g,pra^E;eva^E).?/(?/g,print$@$_};eval
$@=q{$_=~/(?<="\$_};eval
</code>```

Title: Markov Chain Quine

Body:
Perl 5, 81 bytes

Based on the standard quine and my answer to this question:

$_=q{@$=a^E;@$="\$_=q{$_};eval"=~/(?<=\Q$@\E).?/g,print$@while$@=$$[rand@$]};eval

Try it online!

As with the faux source code answer, this sometimes produces valid Perl, but very infrequently (<2%):

$$$_=al
$_=a^E;eval
$_=al
$$=q{$$]};eval
$@=a^E;@whil
$_=q{@\E;e$]};evaleva^E;eval
$$=q{@\$_=a^E;evant$@$="=$$]};evaleval
$_=q{@whind@$_=$]};eval
$_=q{@\$@=~/(?<=\$[rilevale$=ant$[rint$_};evaleval
$_=aleval
$_=q{@$_};@whil
$$=q{@$=q{@$=\E;evand@whint$_};eva^E).?<=$=~/g,prand@$_=al"\E;e$@\E).?/g,prant$_};evaleval
$_=\$_=~/g,prind@=q{$]};@$@\Q$$$_};e$@$_=q{@$_=~/g,pril
$_=q{$=aleval"\E;evaleva^E;eva^E).?/g,pra^E;eva^E).?/(?/g,print$@$_};eval
$@=q{$_=~/(?<="\$_};eval


问:
Trick or Treat polyglot
Since Halloween is coming up I thought I might start a fun little code golf challenge!

The challenge is quite simple. You have to write a program that outputs either trick or treat.

"The twist?" you may ask. Well let me explain:

Your program has to do the following:

Be compilable/runnable in two different languages. Different versions of the same language don't count.

When you run the program in one language it should output trick and the other should output treat. The case is irrelevant and padding the string with whitespace characters are allowed (see examples).

This is code-golf,  so the solution with the fewest bytes wins.

A few explanations:

Valid outputs (Just for the words not for running the code in the two languages. Also adding quotes to signalize the beginning or end of the output. Do not include them in your solution!):

```<code>"trick"

"Treat"

"    TReAt"

"
     tRICk          "
</code>```

Invalid outputs:

```<code>"tri ck"

"tr
eat"

"trck"
</code>```

I'm interested to see what you can come up with! Happy Golfing!

I'd like to note that this is my first challenge so if you have suggestions on this question please leave them in the form of a comment.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code># Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code># Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code># Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the leaderboard snippet:

```<code># [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

var QUESTION_ID=97472,OVERRIDE_USER=23417;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i,TAGS_REG = /(<([^>]+)>)/ig;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Python 3 / JavaScript, 46 bytes

There weren't any "true" Python/JavaScript polyglot answers yet, so I figured I'd try my hand at writing one:

```<code>a=1//2;alert=print
alert(["trick","treat"][a])
</code>```

Python 3

This is how Python sees the code:

a=1//2;alert=print
alert(["trick","treat"][a])
```

<p><code>//</code> is integer division in Python 3, so <code>a=1//2;</code> sets variable <code>a</code> to <code>0</code>. Then <code>alert=print</code> sets the variable <code>alert</code> to the function <code>print</code> so that we can use <code>alert</code> to output.</p>

<p>In the next line, <code>alert</code> is called on the item at index <code>a</code> in the array <code>["trick","treat"]</code>. Since <code>a</code> is <code>0</code> and <code>alert</code> is <code>print</code>, this prints <code>"trick"</code>.</p>

<h3>JavaScript</h3>

<p>This is how JS sees the code:</p>

<pre class="lang-js prettyprint-override"><code>a=1//2;alert=print
alert(["trick","treat"][a])
</code>```

The first line is parsed as a=1; the rest is simply a comment. This sets variable a to 1.

The second line, much like in Python, alerts the item at index a in ["trick","treat"]. Since a is 1, this alerts "treat".

Title: Trick or Treat polyglot

Body:
Python 3 / JavaScript, 46 bytes

There weren't any "true" Python/JavaScript polyglot answers yet, so I figured I'd try my hand at writing one:

a=1//2;alert=print
alert(["trick","treat"][a])

Python 3

This is how Python sees the code:

a=1//2;alert=print
alert(["trick","treat"][a])

// is integer division in Python 3, so a=1//2; sets variable a to 0. Then alert=print sets the variable alert to the function print so that we can use alert to output.

In the next line, alert is called on the item at index a in the array ["trick","treat"]. Since a is 0 and alert is print, this prints "trick".

JavaScript

This is how JS sees the code:

a=1//2;alert=print
alert(["trick","treat"][a])

The first line is parsed as a=1; the rest is simply a comment. This sets variable a to 1.

The second line, much like in Python, alerts the item at index a in ["trick","treat"]. Since a is 1, this alerts "treat".


问:
Output a googol copies of a string
I am interested in seeing programs which don't ask for any input, print a googol copies of some nonempty string, no less, no more, and then stop. A googol is defined as \$10^{100}\$, i.e., 1 followed by a hundred 0's in decimal.

Example output:

```<code>111111111111111111111111111111111111111111111111111111111111111111111111...
</code>```

or

```<code>Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
...
</code>```

The string can also be entirely composed of white space or special symbols. The only exception to identical copies of a fixed string is if your language decorates the output in some way that can not be prevented, but could be trivially undone in a wrapper script, like prepending a line number to each line. The wrapper script in such cases need not be provided.

You can assume your computer will never run out of time, but other than that, your program must have a reasonable demand of resources. Also, you must respect any restrictions that the programming language of your choice poses, for example, you can not exceed a maximum value allowed for its integer types, and at no point more than 4 GB of memory must be needed.

In other words, the program should in principle be testable by running it on your computer. But because of the extent of this number you will be expected to prove that the number of copies of the string it outputs is exactly 10^100 and that the program stops afterwards. Stopping can be exiting or halting or even terminating due to an error, but if so, the error must not produce any output that could not easily be separated from the program's output.

This is code-golf,  so the solution with the fewest bytes wins.

Example solution (C, ungolfed, 3768 bytes)

```<code>#include <stdio.h>

int main() {
  int a00, a01, a02, a03, ..., a99;
  for(a00 = 0; a00 < 10; a00++)
  for(a01 = 0; a01 < 10; a01++)
  for(a02 = 0; a02 < 10; a02++)
  for(a03 = 0; a03 < 10; a03++)
  ...
  for(a99 = 0; a99 < 10; a99++)
    puts("1");
  return 0;
}
</code>```

答:
LiveCode, 83 bytes

```<code>on g c
   if c=100 then
      put 1 after fld 1
   else
      repeat 10
         g c+1
      end repeat
   end if
end g
</code>```

Logically pretty straightforward, but validated by changing the test value for c. Set it to 1, you get ten 1's. Set it to 2, you get 100. Set it to 3 you get 1,000, etc.

LiveCode automatically formats with leading spaces, but it's not required for the code to work.

The argument c will default to empty, and in LiveCode it's perfectly fine to add 1 to empty (and results in 1).

LiveCode can write to stdout, but it's a visual environment and putting text into a field is more common.

Title: Output a googol copies of a string

Body:
LiveCode, 83 bytes

on g c
   if c=100 then
      put 1 after fld 1
   else
      repeat 10
         g c+1
      end repeat
   end if
end g

Logically pretty straightforward, but validated by changing the test value for c. Set it to 1, you get ten 1's. Set it to 2, you get 100. Set it to 3 you get 1,000, etc.

LiveCode automatically formats with leading spaces, but it's not required for the code to work.

The argument c will default to empty, and in LiveCode it's perfectly fine to add 1 to empty (and results in 1).

LiveCode can write to stdout, but it's a visual environment and putting text into a field is more common.


问:
Implement a Truth-Machine
A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

Gets a number (either 0 or 1) from STDIN.

If that number is 0, print out 0 and terminate.

If that number is 1, print out 1 forever.

Challenge

Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

take input from STDIN or an acceptable alternative

If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program

must output to STDOUT or an acceptable alternative

If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.

when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory

the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of code-golf must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Javascript, <s>33</s> 32 Bytes

```<code>i=prompt();do{alert(i)}while(+i)
</code>```

uses the +i syntax (thanks ETHproductions)

Old 1

```<code>i=prompt();do{alert(i)}while(i>0)
</code>```

Title: Implement a Truth-Machine

Body:
Javascript, <s>33</s> 32 Bytes

i=prompt();do{alert(i)}while(+i)

uses the +i syntax (thanks ETHproductions)

Old 1

i=prompt();do{alert(i)}while(i>0)


答:
Dip, 6 bytes

```<code>?_1p?0
</code>```

Body must be at least 30 characters; you entered 19.

Title: Implement a Truth-Machine

Body:
A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

Gets a number (either 0 or 1) from STDIN.

If that number is 0, print out 0 and terminate.

If that number is 1, print out 1 forever.

Challenge

Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

take input from STDIN or an acceptable alternative

If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program

must output to STDOUT or an acceptable alternative

If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.

when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory

the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of code-golf must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
Dip, 6 bytes

?_1p?0

Body must be at least 30 characters; you entered 19.


问:
Generate antsy permutations

Introduction

I defined the class of antsy permutations in an earlier challenge.
As a reminder, a permutation p of the numbers from 0 to r-1 is antsy, if for every entry p[i] except the first, there is some earlier entry p[i-k] such that p[i] == p[i-k] ± 1.
As a fun fact, I also stated that for r ≥ 1, there are exactly 2r-1 antsy permutations of length r.
This means that there is a one-to-one correspondence between the antsy permutations of length r and the binary vectors of length r-1.
In this challenge, your task is to implement such a correspondence.

The task

Your task is to write a program or function that takes in a binary vector of length 1 ≤ n ≤ 99, and outputs an antsy permutation of length n + 1.
The permutation can be either 0-based of 1-based (but this must be consistent), and the input and output can be in any reasonable format.
Furthermore, different inputs must always give different outputs; other than that, you are free to return whichever antsy permutation you want.

The lowest byte count wins.

Example

The (0-based) antsy permutations of length 4 are

```<code>0 1 2 3
1 0 2 3
1 2 0 3
1 2 3 0
2 1 0 3
2 1 3 0
2 3 1 0
3 2 1 0
</code>```

and your program should return one of them for each of the eight bit vectors of length 3:

```<code>0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
</code>```

答:
Jelly, <s>12</s> <s>11</s> 10 bytes

```<code>ḟẋLṭ+
0;ç/
</code>```

Try it online! or generate all permutations of length 4.

How it works

```<code>0;ç/   Main link. Argument: B (bit array)

0;     Prepend a 0 to B.
  ç/   Reduce [0] + B by the helper link.

ḟẋLṭ+  Helper link. Left argument: A (array or 0). Right argument: b (bit)

 ẋ     Repeat A b times, yielding A or [].
ḟ      Filter false; remove the elements of A or [] from A.
  L    Get the length of the resulting array.
       This yield len(A) if b = 0 and 0 if b = 1.
    +  Add b to all elements of A.
   ṭ   Tack; append the result to the left to the result to the right.
</code>```

Title: Generate antsy permutations

Body:
Jelly, <s>12</s> <s>11</s> 10 bytes

ḟẋLṭ+
0;ç/

Try it online! or generate all permutations of length 4.

How it works

0;ç/   Main link. Argument: B (bit array)

0;     Prepend a 0 to B.
  ç/   Reduce [0] + B by the helper link.

ḟẋLṭ+  Helper link. Left argument: A (array or 0). Right argument: b (bit)

 ẋ     Repeat A b times, yielding A or [].
ḟ      Filter false; remove the elements of A or [] from A.
  L    Get the length of the resulting array.
       This yield len(A) if b = 0 and 0 if b = 1.
    +  Add b to all elements of A.
   ṭ   Tack; append the result to the left to the result to the right.


答:
JavaScript (ES6), 52 bytes

```<code>v=>[...v,l=0].map(x=>x?l++:h--,h=v.length).reverse()
</code>```

Test it out:

f=v=>[...v,l=0].map(x=>x?l++:h--,h=v.length).reverse()
g=v=>console.log(f((v.match(/[01]/g)||[]).map(x=>+x)))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input oninput="g(this.value)" value="010"></code>```

Explanation

This takes advantage of the fact that when an antsy permutation is reversed, each item is either 1 more than the maximum of the previous low entries, or 1 less than the minimum of the previous high entries. By denoting a higher item as a 0 and a lower item as a 1, we can create an exact one-to-one correspondance between the antsy permutations of length n and the binary vectors of length n - 1.

The best I could do with Dennis' technique is <s>57</s> 51 bytes:

```<code>v=>v.reduce((x,n)=>[...x.map(i=>i+n),!n*++j],[j=0])
v=>v.map(n=>x=[...x.map(i=>i+n),!n*++j],x=[j=0])&&x
</code>```

xnor's solution is 56 (saved 1 byte thanks to @Neil):

```<code>l=>[1,...l].map((x,i)=>i*!x+eval(l.slice(i).join`+`||0))
</code>```

Title: Generate antsy permutations

Body:
Introduction

I defined the class of antsy permutations in an earlier challenge.
As a reminder, a permutation p of the numbers from 0 to r-1 is antsy, if for every entry p[i] except the first, there is some earlier entry p[i-k] such that p[i] == p[i-k] ± 1.
As a fun fact, I also stated that for r ≥ 1, there are exactly 2r-1 antsy permutations of length r.
This means that there is a one-to-one correspondence between the antsy permutations of length r and the binary vectors of length r-1.
In this challenge, your task is to implement such a correspondence.

The task

Your task is to write a program or function that takes in a binary vector of length 1 ≤ n ≤ 99, and outputs an antsy permutation of length n + 1.
The permutation can be either 0-based of 1-based (but this must be consistent), and the input and output can be in any reasonable format.
Furthermore, different inputs must always give different outputs; other than that, you are free to return whichever antsy permutation you want.

The lowest byte count wins.

Example

The (0-based) antsy permutations of length 4 are

```<code>0 1 2 3
1 0 2 3
1 2 0 3
1 2 3 0
2 1 0 3
2 1 3 0
2 3 1 0
3 2 1 0
</code>```

and your program should return one of them for each of the eight bit vectors of length 3:

```<code>0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
</code>```

Body:
JavaScript (ES6), 52 bytes

v=>[...v,l=0].map(x=>x?l++:h--,h=v.length).reverse()

Test it out:

f=v=>[...v,l=0].map(x=>x?l++:h--,h=v.length).reverse()
g=v=>console.log(f((v.match(/[01]/g)||[]).map(x=>+x)))

<input oninput="g(this.value)" value="010">

Explanation

This takes advantage of the fact that when an antsy permutation is reversed, each item is either 1 more than the maximum of the previous low entries, or 1 less than the minimum of the previous high entries. By denoting a higher item as a 0 and a lower item as a 1, we can create an exact one-to-one correspondance between the antsy permutations of length n and the binary vectors of length n - 1.

The best I could do with Dennis' technique is <s>57</s> 51 bytes:

v=>v.reduce((x,n)=>[...x.map(i=>i+n),!n*++j],[j=0])
v=>v.map(n=>x=[...x.map(i=>i+n),!n*++j],x=[j=0])&&x

xnor's solution is 56 (saved 1 byte thanks to @Neil):

l=>[1,...l].map((x,i)=>i*!x+eval(l.slice(i).join`+`||0))


问:
Play a game of Yahtzee
In the game Yahtzee, players take turns rolling 5 6-sided dice up to three times per turn, possibly saving dice between rolls, and then selecting a category they wish to use for their roll. This continues until there are no more categories (which happens after 13 turns). Then, players' scores are tallied, and the player with the highest score wins.

The categories are as follows ("sum of dice" means adding up the number of pips on the specified dice):

Upper Section

Aces: sum of the dice showing 1 pip

Twos: sum of the dice showing 2 pips

Threes: sum of the dice showing 3 pips

Fours: sum of the dice showing 4 pips

Fives: sum of the dice showing 5 pips

Sixes: sum of the dice showing 6 pips

Lower Section

Three of a Kind: 3 dice with same value, score is sum of all dice

Four of a Kind: 4 dice with same value, score is sum of all dice

Full House: 3 dice with one value and 2 with another, score is 25

Small Straight: 4 sequential dice, score is 30

Large Straight: 5 sequential dice, score is 40

Yahtzee: all 5 dice with same value, score is 50

Chance: any combination of dice, score is sum of all dice

There are a few rules about the category choices:

If a player chooses a category that does not match their roll, they receive a score of 0 for that category.

If a player earns a score of at least 63 in the upper section, they receive 35 bonus points.

If a player has rolled a Yahtzee but the Yahtzee category is already taken (by another Yahtzee - filling in 0 for a miss doesn't count), they receive a bonus of 100 points. This bonus is awarded for every Yahtzee after the first.

Additionally, the player must still choose to fill in a category. They must choose the upper section category corresponding to their roll (e.g. a roll of 5 6's must be placed in the Sixes category). If the corresponding upper section category has already been used, the Yahtzee may be used for a lower section category (in this case, choosing Full House, Small Straight, or Large Straight awards the normal amount of points rather than 0). If all of the lower section categories are taken, then the Yahtzee may be applied to an unused upper section category, with a score of 0.

The Challenge

In this challenge, the competitors will play 1000 games of Yahtzee. At the end of each game, the submission(s) that scored the highest will receive 1 point. After all of the games are finished, the submission with the most points will win. If there is a tie, additional games will be played with only the tied submissions until the tie is broken.

Controller

The complete controller code can be found on this GitHub repository. Here are the public interfaces with which players will be interacting:

public interface ScorecardInterface {

    // returns an array of unused categories
    Category[] getFreeCategories();

    // returns the current total score
    int getScore();

    // returns the current Yahtzee bonus
    int getYahtzeeBonus();

    // returns the current Upper Section bonus
    int getUpperBonus();

    // returns the current Upper Section total
    int getUpperScore();

}
```

<pre class="lang-java prettyprint-override"><code>public interface ControllerInterface {

    // returns the player's scorecard (cloned copy, so don't try any funny business)
    ScorecardInterface getScoreCard(Player p);

    // returns the current scores for all players, in no particular order
    // this allows players to compare themselves with the competition,
    //  without allowing them to know exactly who has what score (besides their own score),
    //  which (hopefully) eliminates any avenues for collusion or sabotage
    int[] getScores();

}
</code>```

public enum Category {
    ACES,
    TWOS,
    THREES,
    FOURS,
    FIVES,
    SIXES,
    THREE_OF_A_KIND,
    FOUR_OF_A_KIND,
    FULL_HOUSE,
    SMALL_STRAIGHT,
    LARGE_STRAIGHT,
    YAHTZEE,
    CHANCE;

    // determines if the category is part of the upper section
    public boolean isUpper() {
        // implementation
    }

    // determines if the category is part of the lower section
    public boolean isLower() {
        // implementation
    }

    // determines if a given set of dice fits for the category
    public boolean matches(int[] dice) {
        // implementation
    }

    // calculates the score of a set of dice for the category
    public int getScore(int[] dice) {
        // implementation
    }

    // returns all categories that fit the given dice
    public static Category[] getMatchingCategories(int[] dice) {
        // implementation
    }
}
```

<pre class="lang-java prettyprint-override"><code>public class TurnChoice {

    // save the dice with the specified indexes (0-4 inclusive)
    public TurnChoice(int[] diceIndexes) {
        // implementation
    }

    // use the current dice for specified category
    public TurnChoice(Category categoryChosen) {
        // implementation
    }

}

public abstract class Player {

    protected ControllerInterface game;

    public Player(ControllerInterface game) {
        this.game = game;
    }

    public String getName() {
        return this.getClass().getSimpleName();
    }

    // to be implemented by players
    // dice is the current roll (an array of 5 integers in 1-6 inclusive)
    // stage is the current roll stage in the turn (0-2 inclusive)
    public abstract TurnChoice turn(int[] dice, int stage);

}
</code>```

Additionally, there are some utility methods in Util.java. They are mainly there to simplify the controller code, but they can be used by players if they desire.

Rules

Players are not allowed to interact in any way except using the Scorecard.getScores method to see the current scores of all players. This includes colluding with other players or sabotaging other players via manipulating parts of the system that are not part of the public interface.

If a player makes an illegal move, they will not be allowed to compete in the tournament. Any issues that cause illegal moves must be resolved prior to the running of the tournament.

If additional submissions are made after the tournament is run, a new tournament will be run with the new submission(s), and the winning submission will be updated accordingly. I make no guarantee of promptness in running the new tournament, however.

Submissions may not exploit any bugs in the controller code that cause it to deviate from the actual game rules. Point out bugs to me (in a comment and/or in a GitHub issue), and I'll fix them.

Use of Java's reflection tools is forbidden.

Any language which runs on the JVM, or can be compiled to Java or JVM bytecode (such as Scala or Jython) can be used, so long as you supply any additional code needed to interface it with Java.

Final Comments

If there is any utility method you would like me to add to the controller, simply ask in the comments and/or make an issue on GitHub, and I'll add it, assuming it doesn't allow for rule breaking or expose information to which players are not privy. If you want to write it yourself and create a pull request on GitHub, even better!

答:
Aces and Eights

Well, this took a lot longer than I would have liked thanks to how busy I've been lately.

package mego.yahtzee;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import static mego.yahtzee.Category.*;

public class AcesAndEights extends Player {
    private Category[] freeCategories, matchingCategories, usableCategories;

    public AcesAndEights(ControllerInterface game) {
        super(game);
    }

    @Override
    public TurnChoice turn(int[] dice, int stage) {
        List<Integer> holdIndices = new java.util.ArrayList<>();

        freeCategories = game.getScoreCard(this).getFreeCategories();

        matchingCategories = Category.getMatchingCategories(dice);
        Arrays.sort(matchingCategories);

        usableCategories = Arrays.stream(freeCategories)
                                 .filter(this::isMatchingCategory)
                                 .toArray(Category[]::new);
        Arrays.sort(usableCategories);

        if (isMatchingCategory(YAHTZEE))
            return doYahtzeeProcess(dice);

        if (isUsableCategory(FULL_HOUSE))
            return new TurnChoice(FULL_HOUSE);

        if (stage == 0 || stage == 1) {
            if (isMatchingCategory(THREE_OF_A_KIND)) {
                int num = 0;
                for (int i : dice) {
                    if (Util.count(Util.boxIntArray(dice), i) >= 3) {
                        num = i;
                        break;
                    }
                }
                for (int k = 0; k < 5; k++) {
                    if (dice[k] == num)
                        holdIndices.add(k);
                }
                return new TurnChoice(toIntArray(holdIndices.toArray(new Integer[0])));
            }

            if (isFreeCategory(LARGE_STRAIGHT) || isFreeCategory(SMALL_STRAIGHT)) {
                if (isUsableCategory(LARGE_STRAIGHT))
                    return new TurnChoice(LARGE_STRAIGHT);

                if (isMatchingCategory(SMALL_STRAIGHT)) {
                    if (!isFreeCategory(LARGE_STRAIGHT))
                        return new TurnChoice(SMALL_STRAIGHT);

                    int[] arr = Arrays.stream(Arrays.copyOf(dice, 5))
                                      .distinct()
                                      .sorted()
                                      .toArray();
                    List<Integer> l = Arrays.asList(Util.boxIntArray(dice));
                    if (Arrays.binarySearch(arr, 1) >= 0 && Arrays.binarySearch(arr, 2) >= 0) {
                        holdIndices.add(l.indexOf(1));
                        holdIndices.add(l.indexOf(2));
                        holdIndices.add(l.indexOf(3));
                        holdIndices.add(l.indexOf(4));
                    }
                    else if (Arrays.binarySearch(arr, 2) >= 0 && Arrays.binarySearch(arr, 3) >= 0) {
                        holdIndices.add(l.indexOf(2));
                        holdIndices.add(l.indexOf(3));
                        holdIndices.add(l.indexOf(4));
                        holdIndices.add(l.indexOf(5));
                    }
                    else {
                        holdIndices.add(l.indexOf(3));
                        holdIndices.add(l.indexOf(4));
                        holdIndices.add(l.indexOf(5));
                        holdIndices.add(l.indexOf(6));
                    }
                    return new TurnChoice(toIntArray(holdIndices.toArray(new Integer[0])));
                }
            }

            if (isFreeCategory(FULL_HOUSE)) {
                int o = 0, t = o;
                for (int k = 1; k <= 6; k++) {
                    if (Util.count(Util.boxIntArray(dice), k) == 2) {
                        if (o < 1)
                            o = k;
                        else
                            t = k;
                    }
                }

                if (o > 0 && t > 0) {
                    for (int k = 0; k < 5; k++) {
                        if (dice[k] == o || dice[k] == t)
                            holdIndices.add(k);
                    }
                    return new TurnChoice(toIntArray(holdIndices.toArray(new Integer[0])));
                }
            }
        }
        else {
            Arrays.sort(freeCategories, Comparator.comparingInt((Category c) -> c.getScore(dice))
                                                  .thenComparingInt(this::getPriority)
                                                  .reversed());
            return new TurnChoice(freeCategories[0]);
        }

        return new TurnChoice(new int[0]);
    }

    private TurnChoice doYahtzeeProcess(int[] dice) {
        if (isUsableCategory(YAHTZEE))
            return new TurnChoice(YAHTZEE);

        Category c = Util.intToUpperCategory(dice[0]);
        if (isUsableCategory(c))
            return new TurnChoice(c);

        Category[] arr = Arrays.stream(freeCategories)
                               .filter(x -> x.isLower())
                               .sorted(Comparator.comparing(this::getPriority)
                                                 .reversed())
                               .toArray(Category[]::new);
        if (arr.length > 0)
            return new TurnChoice(arr[0]);

        Arrays.sort(freeCategories, Comparator.comparingInt(this::getPriority));
        return new TurnChoice(freeCategories[0]);
    }

    private boolean isFreeCategory(Category c) {
        return Arrays.binarySearch(freeCategories, c) >= 0;
    }

    private boolean isMatchingCategory(Category c) {
        return Arrays.binarySearch(matchingCategories, c) >= 0;
    }

    private boolean isUsableCategory(Category c) {
        return Arrays.binarySearch(usableCategories, c) >= 0;
    }

    private int getPriority(Category c) {
        switch (c) {
            case YAHTZEE: return -3;        // 50 points
            case LARGE_STRAIGHT: return -1; // 40 points
            case SMALL_STRAIGHT: return -2; // 30 points
            case FULL_HOUSE: return 10;     // 25 points
            case FOUR_OF_A_KIND: return 9;  // sum
            case THREE_OF_A_KIND: return 8; // sum
            case SIXES: return 7;
            case FIVES: return 6;
            case FOURS: return 5;
            case THREES: return 4;
            case TWOS: return 3;
            case ACES: return 2;
            case CHANCE: return 1;          // sum
        }
        throw new RuntimeException();
    }

    private int[] toIntArray(Integer[] arr) {
        int[] a = new int[arr.length];
        for (int k = 0; k < a.length; k++)
            a[k] = arr[k];
        return a;
    }
}
```

The bot looks for patterns in the dice that could match certain categories and holds the necessary ones. It immediately chooses a high-priority matching category if one's found; otherwise it chooses a category that yields the highest score. Scores nearly 200 points per game on average.

Title: Play a game of Yahtzee

Body:
Aces and Eights

Well, this took a lot longer than I would have liked thanks to how busy I've been lately.

package mego.yahtzee;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import static mego.yahtzee.Category.*;

public class AcesAndEights extends Player {
    private Category[] freeCategories, matchingCategories, usableCategories;

    public AcesAndEights(ControllerInterface game) {
        super(game);
    }

    @Override
    public TurnChoice turn(int[] dice, int stage) {
        List<Integer> holdIndices = new java.util.ArrayList<>();

        freeCategories = game.getScoreCard(this).getFreeCategories();

        matchingCategories = Category.getMatchingCategories(dice);
        Arrays.sort(matchingCategories);

        usableCategories = Arrays.stream(freeCategories)
                                 .filter(this::isMatchingCategory)
                                 .toArray(Category[]::new);
        Arrays.sort(usableCategories);

        if (isMatchingCategory(YAHTZEE))
            return doYahtzeeProcess(dice);

        if (isUsableCategory(FULL_HOUSE))
            return new TurnChoice(FULL_HOUSE);

        if (stage == 0 || stage == 1) {
            if (isMatchingCategory(THREE_OF_A_KIND)) {
                int num = 0;
                for (int i : dice) {
                    if (Util.count(Util.boxIntArray(dice), i) >= 3) {
                        num = i;
                        break;
                    }
                }
                for (int k = 0; k < 5; k++) {
                    if (dice[k] == num)
                        holdIndices.add(k);
                }
                return new TurnChoice(toIntArray(holdIndices.toArray(new Integer[0])));
            }

            if (isFreeCategory(LARGE_STRAIGHT) || isFreeCategory(SMALL_STRAIGHT)) {
                if (isUsableCategory(LARGE_STRAIGHT))
                    return new TurnChoice(LARGE_STRAIGHT);

                if (isMatchingCategory(SMALL_STRAIGHT)) {
                    if (!isFreeCategory(LARGE_STRAIGHT))
                        return new TurnChoice(SMALL_STRAIGHT);

                    int[] arr = Arrays.stream(Arrays.copyOf(dice, 5))
                                      .distinct()
                                      .sorted()
                                      .toArray();
                    List<Integer> l = Arrays.asList(Util.boxIntArray(dice));
                    if (Arrays.binarySearch(arr, 1) >= 0 && Arrays.binarySearch(arr, 2) >= 0) {
                        holdIndices.add(l.indexOf(1));
                        holdIndices.add(l.indexOf(2));
                        holdIndices.add(l.indexOf(3));
                        holdIndices.add(l.indexOf(4));
                    }
                    else if (Arrays.binarySearch(arr, 2) >= 0 && Arrays.binarySearch(arr, 3) >= 0) {
                        holdIndices.add(l.indexOf(2));
                        holdIndices.add(l.indexOf(3));
                        holdIndices.add(l.indexOf(4));
                        holdIndices.add(l.indexOf(5));
                    }
                    else {
                        holdIndices.add(l.indexOf(3));
                        holdIndices.add(l.indexOf(4));
                        holdIndices.add(l.indexOf(5));
                        holdIndices.add(l.indexOf(6));
                    }
                    return new TurnChoice(toIntArray(holdIndices.toArray(new Integer[0])));
                }
            }

            if (isFreeCategory(FULL_HOUSE)) {
                int o = 0, t = o;
                for (int k = 1; k <= 6; k++) {
                    if (Util.count(Util.boxIntArray(dice), k) == 2) {
                        if (o < 1)
                            o = k;
                        else
                            t = k;
                    }
                }

                if (o > 0 && t > 0) {
                    for (int k = 0; k < 5; k++) {
                        if (dice[k] == o || dice[k] == t)
                            holdIndices.add(k);
                    }
                    return new TurnChoice(toIntArray(holdIndices.toArray(new Integer[0])));
                }
            }
        }
        else {
            Arrays.sort(freeCategories, Comparator.comparingInt((Category c) -> c.getScore(dice))
                                                  .thenComparingInt(this::getPriority)
                                                  .reversed());
            return new TurnChoice(freeCategories[0]);
        }

        return new TurnChoice(new int[0]);
    }

    private TurnChoice doYahtzeeProcess(int[] dice) {
        if (isUsableCategory(YAHTZEE))
            return new TurnChoice(YAHTZEE);

        Category c = Util.intToUpperCategory(dice[0]);
        if (isUsableCategory(c))
            return new TurnChoice(c);

        Category[] arr = Arrays.stream(freeCategories)
                               .filter(x -> x.isLower())
                               .sorted(Comparator.comparing(this::getPriority)
                                                 .reversed())
                               .toArray(Category[]::new);
        if (arr.length > 0)
            return new TurnChoice(arr[0]);

        Arrays.sort(freeCategories, Comparator.comparingInt(this::getPriority));
        return new TurnChoice(freeCategories[0]);
    }

    private boolean isFreeCategory(Category c) {
        return Arrays.binarySearch(freeCategories, c) >= 0;
    }

    private boolean isMatchingCategory(Category c) {
        return Arrays.binarySearch(matchingCategories, c) >= 0;
    }

    private boolean isUsableCategory(Category c) {
        return Arrays.binarySearch(usableCategories, c) >= 0;
    }

    private int getPriority(Category c) {
        switch (c) {
            case YAHTZEE: return -3;        // 50 points
            case LARGE_STRAIGHT: return -1; // 40 points
            case SMALL_STRAIGHT: return -2; // 30 points
            case FULL_HOUSE: return 10;     // 25 points
            case FOUR_OF_A_KIND: return 9;  // sum
            case THREE_OF_A_KIND: return 8; // sum
            case SIXES: return 7;
            case FIVES: return 6;
            case FOURS: return 5;
            case THREES: return 4;
            case TWOS: return 3;
            case ACES: return 2;
            case CHANCE: return 1;          // sum
        }
        throw new RuntimeException();
    }

    private int[] toIntArray(Integer[] arr) {
        int[] a = new int[arr.length];
        for (int k = 0; k < a.length; k++)
            a[k] = arr[k];
        return a;
    }
}

The bot looks for patterns in the dice that could match certain categories and holds the necessary ones. It immediately chooses a high-priority matching category if one's found; otherwise it chooses a category that yields the highest score. Scores nearly 200 points per game on average.


答:
Python 3, <s>574</s> <s>471</s> 347 bytes

I'll probably work on this some more, considering the other Python solution is like a fifth of this one :[.

```<code>def a(I):
 D,l,r={},len(I),range
 for i in r(l):
  if I[i]<1:
   n,t,n[i]=I[:],[],1
   for j in r(l):
    if n[j]>0:
     q,Q=[],0
     for k in r(l):
      if k!=j and n[k]>0:q.append((k-j,j-k)[k<j])
     for i in q:Q+=1/(i**2)
    t.append(Q)
   T=sum(t)
   if T not in D.keys():D[T]=i
 if len(D)>0:I[D[min(D.keys())]]=1
 print(I)
</code>```

Well that's much better now that I've learned you can use single spaces.

Title: Positional Bathroom Etiquette

Body:
Python 3, <s>574</s> <s>471</s> 347 bytes

I'll probably work on this some more, considering the other Python solution is like a fifth of this one :[.

def a(I):
 D,l,r={},len(I),range
 for i in r(l):
  if I[i]<1:
   n,t,n[i]=I[:],[],1
   for j in r(l):
    if n[j]>0:
     q,Q=[],0
     for k in r(l):
      if k!=j and n[k]>0:q.append((k-j,j-k)[k<j])
     for i in q:Q+=1/(i**2)
    t.append(Q)
   T=sum(t)
   if T not in D.keys():D[T]=i
 if len(D)>0:I[D[min(D.keys())]]=1
 print(I)

Well that's much better now that I've learned you can use single spaces.


问:
Interlace strings
Your challenge is to write a program or function that, when given two strings of equal length, swaps every other character and outputs/returns the resulting strings in either order.

Examples

```<code>"Hello," "world!" --> "Hollo!" "werld,"
"code" "golf" --> "codf" "gole"
"happy" "angry" --> "hnpry" "aagpy"
"qwerty" "dvorak" --> "qvertk" "dworay"
"1, 2, 3" "a, b, c" --> "1, b, 3" "a, 2, c"
"3.141592653589" "2.718281828459" --> "3.111291623489" "2.748582858559"
"DJMcMayhem" "trichoplax" --> "DrMcMoylex" "tJichapham"
"Doorknob" "Downgoat" --> "Doonkoot" "Dowrgnab"
"Halloween" "Challenge" --> "Hhlloeegn" "Caallwnee"
</code>```

Rules

The strings will only contain ASCII chars (32-126).

The strings will always be the same length, and will never be empty.

You may accept input in any suitable format: separate parameters, items in an array, separated by one or more newlines, even concatenated. The only restriction is that one string must come fully before the other (e.g. a1\nb2\nc3 for "abc", "123" is invalid).

The output may be in either order (i.e. you can start swapping from the first or the second char), and in any valid format mentioned above. (2-item array, separated by newline(s), concatenated, etc.)

Scoring

This is code-golf, so the shortest code in bytes for each language wins.

答:
QBIC, 112 bytes

QBIC can streamline a lot of the QBasic boilerplate, but the main MID$engine still needs to be done in QBasic because QBIC lacks a substring-function. Still, saves me 60 bytes.

```<code>;;_LA|~a%2=1|A=A+@ | B=B+C][1,a,2|X=X+$MID$(A$,b,1)+MID$(B$,b+1,1):Y$=Y$+MID$(B$,b,1)+MID$(A$,b+1,1)|]?_tX|,_tY|
</code>```

Title: Interlace strings

Body:
QBIC, 112 bytes

QBIC can streamline a lot of the QBasic boilerplate, but the main MID$engine still needs to be done in QBasic because QBIC lacks a substring-function. Still, saves me 60 bytes.

;;_LA|~a%2=1|A=A+@ | B=B+C][1,a,2|X=X+$MID$(A$,b,1)+MID$(B$,b+1,1):Y$=Y$+MID$(B$,b,1)+MID$(A$,b+1,1)|]?_tX|,_tY|


答:
MS-DOS machine code (.COM file), 126 bytes

(A 63-byte variant would be possible if the program was allowed to read its own code.)

The first half (63 bytes) of the program are code and look like this:

```<code>FC BE<3F>01 AC 50 88 C2 B4 02 CD 21 E8 1A 00 59
4E AC 81 FE<7E>01 7C 03 BE<3F>01 38 C1 75 F2 FE
CA 75 EE 81 FE<3F>01 75 DB 8A 16 00 80 31 C0 8E
D8 31 C9 AC 00 C2 E2 FB 0E 1F 88 16 00 80 C3
</code>```

The second half (63 bytes) are data and are a 1:1 copy of the code.

(In the 63-byte variant reading its own code, the bytes marked with "<>" have different values and the second half of the program is not present.)

I'm also not sure about the random generator's probability distribution:

The program uses the fact that the clock counters and other information modified by interrupts are stored in segment 0 to generate random numbers.

Converted to assembly code the program looks like this:

```<code># 0x100:
    cld                # Ensure SI is being incremented
    mov si, programEnd # Move SI to the first byte of the copy of the program
nextOutput:
    lodsb              # Load one byte of the program ...
    push ax            # ... save it to the stack ...
    mov dl, al         # ... and output it!
    mov ah, 2
    int 0x21
    call pseudoRandom  # Create a random number (in DL)
    pop cx             # Take the stored byte from the stack
    dec si             # Go back to the last byte loaded
nextSearch:
    lodsb              # Load the next byte
                       # If we loaded the last byte ...
    cmp si, 2*programEnd-0x100
    jl notEndOfProgram # ... the next byte to be loaded ...
    mov si, programEnd # ... is the first byte of the program.
notEndOfProgram:
    cmp cl, al         # If the byte loaded is not equal to ...
                       # ... the last byte written then ...
    jne nextSearch     # ... continue at nextSearch!
    dec dl             # Decrement the random number and ...
    jnz nextSearch     # ... continue at nextSearch until the ...
                       # ... originally random number becomes zero.
    cmp si, programEnd # If the last byte read was not the last byte ...
    jnz nextOutput     # ... of the program then output the next ...
                       # ... byte!

    # Otherwise fall through to the random number generator
    # whose "RET" instruction will cause the program to stop.

    # The random number generator:
pseudoRandom:
    mov dl, [0x8000]   # Load the last random number generated
                       # (Note that this is uninitialized when
                       # this function is called the first time)
    xor ax, ax         # We use segment 0 which contains the ...
    mov ax, ds         # ... clock information and other data ...
                       # ... modified by interrupts!
    xor cx, cx         # Prepare for 0x10000 loops so ...
                       # ... all bytes in the segment are processed ...
                       # ... once and the value of SI will be ...
                       # ... unchanged in the end!
randomNext:
    lodsb              # Load one byte
    add dl, al         # Add that byte to the next random number
    loop randomNext    # Iterate over all bytes
    push cs            # Restore the segment
    pop ds
    mov [0x8000], dl   # Remember the random number
    ret                # Exit sub-routine

programEnd:
    ## Place a copy of the code as data here ##
</code>```

Title: Markov Chain Quine

Body:
A simple Markov Model will be used in this question. For more information about Markov Chains, see http://setosa.io/ev/markov-chains/.

Take a string. For this example, we will use the word:

```<code>reader
</code>```

Now, for each character, take the characters that appear after each occurence of the character in the string. (`^` represents the start of the string and `$` represents the end)

```<code>`^` -> {'r'}       # After the start of the string, there is an `r`.
'r' -> {'e', `$`}  # After the first `r` (*r*eader), there is an `e`
                   # after the second (reade*r*), there is the end of the string.
'e' -> {'a', 'r'}
'a' -> {'d'}
'd' -> {'e'}
</code>```

Now, starting from the start of the string, pick randomly from one of the characters in the next set. Append this character and then pick from the characters in its next set, and so on until you get to the end. Here are some example words:

```<code>r
rereader
rer
readereader
</code>```

If a character appears after another character multiple times, it is more likely to be chosen. For example, in cocoa can, after a c, there is a two thirds of a chance of getting an o and a one thirds chance of getting an a.

```<code>'c' -> {'o', 'o', 'a'}
</code>```

Challenge

Create a program that takes no input and outputs a random string generated using a Markov Chain, like above, where the input to the chain is the program's source.

The program must have at least two characters, two of which must be the same (To prevent "boring" chains that only have one output)

You can modify the model to use bytes instead of characters if you wish, but change "characters" to "bytes" in rule 1

The program should output strings randomly with the expected frequency in theory

This is code-golf, so the shortest program wins!

Body:
MS-DOS machine code (.COM file), 126 bytes

(A 63-byte variant would be possible if the program was allowed to read its own code.)

The first half (63 bytes) of the program are code and look like this:

FC BE<3F>01 AC 50 88 C2 B4 02 CD 21 E8 1A 00 59
4E AC 81 FE<7E>01 7C 03 BE<3F>01 38 C1 75 F2 FE
CA 75 EE 81 FE<3F>01 75 DB 8A 16 00 80 31 C0 8E
D8 31 C9 AC 00 C2 E2 FB 0E 1F 88 16 00 80 C3

The second half (63 bytes) are data and are a 1:1 copy of the code.

(In the 63-byte variant reading its own code, the bytes marked with "<>" have different values and the second half of the program is not present.)

I'm also not sure about the random generator's probability distribution:

The program uses the fact that the clock counters and other information modified by interrupts are stored in segment 0 to generate random numbers.

Converted to assembly code the program looks like this:

# 0x100:
    cld                # Ensure SI is being incremented
    mov si, programEnd # Move SI to the first byte of the copy of the program
nextOutput:
    lodsb              # Load one byte of the program ...
    push ax            # ... save it to the stack ...
    mov dl, al         # ... and output it!
    mov ah, 2
    int 0x21
    call pseudoRandom  # Create a random number (in DL)
    pop cx             # Take the stored byte from the stack
    dec si             # Go back to the last byte loaded
nextSearch:
    lodsb              # Load the next byte
                       # If we loaded the last byte ...
    cmp si, 2*programEnd-0x100
    jl notEndOfProgram # ... the next byte to be loaded ...
    mov si, programEnd # ... is the first byte of the program.
notEndOfProgram:
    cmp cl, al         # If the byte loaded is not equal to ...
                       # ... the last byte written then ...
    jne nextSearch     # ... continue at nextSearch!
    dec dl             # Decrement the random number and ...
    jnz nextSearch     # ... continue at nextSearch until the ...
                       # ... originally random number becomes zero.
    cmp si, programEnd # If the last byte read was not the last byte ...
    jnz nextOutput     # ... of the program then output the next ...
                       # ... byte!

    # Otherwise fall through to the random number generator
    # whose "RET" instruction will cause the program to stop.

    # The random number generator:
pseudoRandom:
    mov dl, [0x8000]   # Load the last random number generated
                       # (Note that this is uninitialized when
                       # this function is called the first time)
    xor ax, ax         # We use segment 0 which contains the ...
    mov ax, ds         # ... clock information and other data ...
                       # ... modified by interrupts!
    xor cx, cx         # Prepare for 0x10000 loops so ...
                       # ... all bytes in the segment are processed ...
                       # ... once and the value of SI will be ...
                       # ... unchanged in the end!
randomNext:
    lodsb              # Load one byte
    add dl, al         # Add that byte to the next random number
    loop randomNext    # Iterate over all bytes
    push cs            # Restore the segment
    pop ds
    mov [0x8000], dl   # Remember the random number
    ret                # Exit sub-routine

programEnd:
    ## Place a copy of the code as data here ##


答:
Python 2, <s>62</s> 60 bytes

x=0,
for n in input():x=[t-n+1for t in x]+[n*len(x)]
print x
```

Thanks to @xnor for golfing off 2 bytes!

Test it on Ideone.

Title: Generate antsy permutations

Body:
Python 2, <s>62</s> 60 bytes

x=0,
for n in input():x=[t-n+1for t in x]+[n*len(x)]
print x

Thanks to @xnor for golfing off 2 bytes!

Test it on Ideone.


问:
Produce Dürer's magic square

The challenge

Output an array or string representation of Dürer's famous magic square:

that is,

```<code>16  3  2 13
 5 10 11  8
 9  6  7 12
 4 15 14  1
</code>```

Some properties of this square, which can perhaps be exploited, are:

It contains each integer from 1 to 16 exactly once

The sum of each column or row, as well as the the sum of each of the two diagonals, is the same. This is the defining property of a magic square. The sum is the magic constant of the square.

In addition, for this particular square, the sum of each of the four quadrants also equals the magic constant, as do the sum of the center four squares and the sum of the corner four squares.

Rules

Bultins that generate magic squares are not allowed (such as Matlab's magic or Mathematica's MagicSquare). Any other builtin can be used.

The code can be a program or a function.

There is no input.

The numbers must be in base 10. The output format is flexible as usual. Some possibilities are:

A nested array (either function output, or its string representation, with or without separators, any type of matching brackets):

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

A 2D array:

```<code>{16, 3, 2, 13; 5, 10, 11, 8; 9, 6, 7, 12; 4, 15, 14, 1}
</code>```

An array of four strings, or a string consisting of four lines. The numbers may be right-aligned

```<code>16  3  2 13
 5 10 11  8
 9  6  7 12
 4 15 14  1
</code>```

or left-aligned

```<code>16 3  2  13
5  10 11  8
9  6  7  12
4  15 14  1
</code>```

A string with two different separators for row and column, such as

```<code>16,3,2,13|5,10,11,8|9,6,7,12|4,15,14,1
</code>```

The output format should clearly differentiate rows and columns. For example, it is not allowed to output a flat array, or a string with all numbers separated by spaces.

Code golf. Shortest wins.

Title: Produce Dürer's magic square

Body:
Ruby, 60 bytes - first attempt

%w(f21c 49a7 856b 3ed0).map{|i|i.chars.map{|i|i.to_i(16)+1}}

Ruby, 45 bytes - cheap

puts '16,3,2,13|5,10,11,8|9,6,7,12|4,15,14,1'


答:
Pyth - 17 bytes

Base conversion. This unfortunately beats @xnor's approach

```<code>c4jC"úz(ás¸H"17
</code>```

Try it online here.

Title: Produce Dürer's magic square

Body:
The challenge

Output an array or string representation of Dürer's famous magic square:

that is,

```<code>16  3  2 13
 5 10 11  8
 9  6  7 12
 4 15 14  1
</code>```

Some properties of this square, which can perhaps be exploited, are:

It contains each integer from 1 to 16 exactly once

The sum of each column or row, as well as the the sum of each of the two diagonals, is the same. This is the defining property of a magic square. The sum is the magic constant of the square.

In addition, for this particular square, the sum of each of the four quadrants also equals the magic constant, as do the sum of the center four squares and the sum of the corner four squares.

Rules

Bultins that generate magic squares are not allowed (such as Matlab's magic or Mathematica's MagicSquare). Any other builtin can be used.

The code can be a program or a function.

There is no input.

The numbers must be in base 10. The output format is flexible as usual. Some possibilities are:

A nested array (either function output, or its string representation, with or without separators, any type of matching brackets):

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

A 2D array:

```<code>{16, 3, 2, 13; 5, 10, 11, 8; 9, 6, 7, 12; 4, 15, 14, 1}
</code>```

An array of four strings, or a string consisting of four lines. The numbers may be right-aligned

```<code>16  3  2 13
 5 10 11  8
 9  6  7 12
 4 15 14  1
</code>```

or left-aligned

```<code>16 3  2  13
5  10 11  8
9  6  7  12
4  15 14  1
</code>```

A string with two different separators for row and column, such as

```<code>16,3,2,13|5,10,11,8|9,6,7,12|4,15,14,1
</code>```

The output format should clearly differentiate rows and columns. For example, it is not allowed to output a flat array, or a string with all numbers separated by spaces.

Code golf. Shortest wins.

Body:
Pyth - 17 bytes

Base conversion. This unfortunately beats @xnor's approach

c4jC"úz(ás¸H"17

Try it online here.


问:
Find the Wavy Words!
(Note: this is an easier spin-off of my previous challenge Find the Infinity Words!, which is a spin-off of my other previous challenge Find the Swirling Words! :) )

Definition of a Wavy Word:

If you connect with curves all the characters of a Wavy Word on the alphabet (A-Z) you obtain the path of a wave continuously going toward right or toward left and never changing direction, like in the diagrams below.

A Wavy Word can be:

Raising if each consecutive character is at the right (on the alphabet) of the previous one.

Decreasing if each consecutive character is at the left (on the alphabet) of the previous one.

All the even connection must be down, all the odd connections must be up.

You can ignore upper/lowercase or consider/convert all to upper case or all to lower case.

The input words are only characters in the alphabet range of A-Z, no spaces, no punctuation, or symbols.

If a word has double characters, like "SPOON", you must collapse the doubles to one character: "SPOON" > "SPON" (because if you go from O to O is zero distance).

The Wavy Words will contain at least 3 distinct characters (even after doubles collapsing).

Here there are some examples:

Task:

Write a full program or function that will take a word from standard input and will output if it is a Wavy Word or not, and in positive case, output if it is raising or decreasing. The output can be True/False/Null, 2/1/0, 1/Null/0, -1/0/1, NO/WR/WD, etc, you decide how to represent it.

Test cases:

```<code>WAVY WORDS:
  ADEPT, BEGIN, BILL, BOSS, BOOST, CHIMP,
  KNOW, SPONGE, SPOON, TROLL, WOLF

ADEPT  > YES > RAISING
BEGIN  > YES > RAISING
BILL   > YES > RAISING
BOSS   > YES > RAISING
BOOST  > YES > RAISING
CHIMP  > YES > RAISING
KNOW   > YES > RAISING
SPONGE > YES > DECREASING
SPOON  > YES > DECREASING
TROLL  > YES > DECREASING
WOLF   > YES > DECREASING

NOT WAVY WORDS:
  WATCH, EARTH, NINON, FOO, BAR, WAVE, SELECTION,
  YES, NO, DEFINITION, WATER, WINE, CODE, AAAHHHH, I, MM, ABCA
</code>```

Rules:

Shortest code wins.

Optional Task:

Find, as a list, as many Wavy Words as you can in an English dictionary, and the longest as well. You can take for example as reference the complete list of English words here.

答:
Javascript (ES6), 84 80 78 bytes

```<code>i=>new Set(s=[...i]).size>2?[i,s.reverse().join``].indexOf(s.sort().join``):-1
</code>```

Where wavy increasing is 0, decreasing is 1, and -1 is not wavy.

Thanks to @Neil for helping me save 2 bytes.

Title: Find the Wavy Words!

Body:
Javascript (ES6), 84 80 78 bytes

i=>new Set(s=[...i]).size>2?[i,s.reverse().join``].indexOf(s.sort().join``):-1

Where wavy increasing is 0, decreasing is 1, and -1 is not wavy.

Thanks to @Neil for helping me save 2 bytes.


问:
Convert to Bubble Letters
So I was playing around with my compose key, and found some cool things, one of them being that by pressing compose + ( + alphanumeric + ), you get that character inside a bubble, like so: ⓐ.

Your task in this challenge is simple, to convert ordinary text to bubble letter text.

Here are the ascii chars, the bubble characters and their Unicode code points:

```<code>0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
⓪①②③④⑤⑥⑦⑧⑨ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ
9450 9312 9313 9314 9315 9316 9317 9318 9319 9320 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436 9437 9438 9439 9440 9441 9442 9443 9444 9445 9446 9447 9448 9449 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413 9414 9415 9416 9417 9418 9419 9420 9421 9422 9423
</code>```

Your input will contain only printable ascii characters, and if a character cannot be bubbleified, leave it as is.

This is code-golf, so shortest code in bytes wins!

Note: This is not isomorphic to my earlier challenge about small-caps conversion since unlike small-caps, bubble letters are in a mostly contiguous segment of code-points, allowing for more interesting approaches.

Title: Convert to Bubble Letters

Body:
Java, 747 bytes

String a(String...A){for(int i=1;i<A.length-1;i+=2)A[0]=A[0].replace(A[i],A[i+1]);return A[0];}String b(String B){return a(B,"0","⓪","1","①","2","②","3","③","4","④","5","⑤","6","⑥","7","⑦","8","⑧","9","⑨","a","ⓐ","b","ⓑ","c","ⓒ","d","ⓓ","e","ⓔ","f","ⓕ","g","ⓖ","h","ⓗ","i","ⓘ","j","ⓙ","k","ⓚ","l","ⓛ","m","ⓜ","n","ⓝ","o","ⓞ","p","ⓟ","q","ⓠ","r","ⓡ","s","ⓢ","t","ⓣ","u","ⓤ","v","ⓥ","w","ⓦ","x","ⓧ","y","ⓨ","z","ⓩ","A","Ⓐ","B","Ⓑ","C","Ⓒ","D","Ⓓ","E","Ⓔ","F","Ⓕ","G","Ⓖ","H","Ⓗ","I","Ⓘ","J","Ⓙ","K","Ⓚ","L","Ⓛ","M","Ⓜ","N","Ⓝ","O","Ⓞ","P","Ⓟ","Q","Ⓠ","R","Ⓡ","S","Ⓢ","T","Ⓣ","U","Ⓤ","V","Ⓥ","W","Ⓦ","X","Ⓧ","Y","Ⓨ","Z","Ⓩ");}

If the source code may only contain ASCII characters, then replace every non-ASCII character with \uINSERTRESPECTIVECODEPOINTINHEXADECIMALHERE. Doing so results in a 933-byte program.


问:
Decode Baby-talk!
When babies open their mouths, they're not just spewing gibberish. They're actually talking in a highly advanced, adult-proof cipher...

The Baby-talk Cipher

When a baby talks, it could look something like gogooa gagooook aagaaoooy
Each single-space separated section represents a character (so the example above represents 3 characters).

To decipher a section, we must count number of As and Os it contains. However, we only count those which are adjacent to another vowel. For example, the A in 'gag' would not count, but both the A and O in 'gaog' would.

Counting the example above would look like this:

```<code>Section    | Num Os | Num As

gogooa     | 2      | 1
gagooook   | 4      | 0
aagaaoooy  | 3      | 4
</code>```

We then use these values to convert the input into plaintext on a Polybius square. This is a 5x5 representation of the English alphabet, omitting 'J' (please note that, in baby-talk, 0-counting rules apply to the table):

```<code>  0 1 2 3 4
0 A B C D E
1 F G H I K
2 L M N O P
3 Q R S T U
4 V W X Y Z
</code>```

Using the number of Os as the column, and number of As as the row, we find which character each section represents:

```<code>Section    | Num Os | Num As | Character

gogooa     | 2      | 1      | (2,1) -> H
gagooook   | 4      | 0      | (4,0) -> E
aagaaoooy  | 3      | 4      | (3,4) -> Y
</code>```

Which tells us that the baby was just saying "HEY".

Notes:

- If a section representing a character has more than 4 As or Os, ignore the extras, because 4 is the maximum value on the table.
- For this task, Y is not a vowel - only A, E, I, O and U.

The Challenge

Your task is to create a full program which takes one input, a word in baby-speak, and prints it in plaintext.

Your program must be able to take input in uppercase, lowercase, and a mix of both.

The input will only contain ASCII alphabet letters (A-Z and a-z), with single spaces to seperate the baby words.

The output text can be in any case.

You should the take the input from STDIN and print the plaintext on STDOUT. If your language does not have these, use the nearest equivalent.

This is code-golf, so the shortest code in bytes wins - but any solution is welcome.

Test Cases

```<code>'GLOOG KAKAAOOO ARGOOO OOOOOGUGUU' -> CODE
'oaka pooopaa gaau augu' -> GOLF
'Aoao U oOOAoa oaoAoo aoAoAOa' -> NAPPY
'GUG gAGaA gOougOou' -> ALE
'OOaGOG GoGOOoGoU gAA bLAA GOUGoOUgAIGAI' -> HELLO
</code>```

答:
brainfuck, 656 bytes

```<code>+[[>>>,[>++++[<-------->-]]<]<<[>]<-[+[<+>>+<-]----[>>+<<----]>>+[<[-<]<[>]>>-]-<[[-]>+<]>[[-[->]<<+>]<->>>]<<<[>>>+<<<-]<<-]>>>>>[[<+>>+<-]----[>-<----]>--[----<]<[>]>[----<]<[>]>[------<]<[>]>[------<]<[>]><+>[[-]<->]>>]<<<[>->]<[<]>[>[<<<<<+>>>>>>+<-]<<<<]<[-]>>>>[<[>[>+<-]<-]>[-]->[<+>-]>>]<<<[-<----[>-<----]>[>+>+<<-]+>[<->[-]<]<[<]>[[<<<]<+>>>>[>>>]<<<-]>+>--------------[<->[-]]<[-<<<<[<<<]>+>>[>>>]>]<<<<]<[<+<+>>-]>++++[<<[->]>[<]>-]+<<[[-]++++<[-]>>]>[<]<<[>+<-]>>+>->[>+>+<<-]<++++[>>[-<]<[>]<-]>>[[-]++++>[-]]<<<[>]<->>>>[<+>-]<[<<<+>>>-]<<<<[>+++++<-]>[>+>+<<-]<++++++++[>>[-<]<[>]<-]>>[[-]>+<]----[>+<----]>++.[-]+>>>,[<++++[>--------<-]]>]
</code>```

This was a pretty good way to kill a couple of hours.

Requires a brainfuck interpreter that uses 8-bit wrapping cells, allows you to go left from cell 0 and returns 0 if , is used when stdin is empty. In my experience, these are the most common settings.

This program does not consider Y a vowel, but if OP wants it to it's an easy fix.

It seems like writing this would be a daunting task but if you have some familiarity with the language there's nothing surprising or new in the code. Standard brainfuck tactics: Read the input but make sure you leave a couple of empty cells between each byte, use those empty cells to store data about the input, use the data you stored to decide how to transform it and spit something out at the end. In this case it was get the input, set it all to uppercase, figure out which cells are vowels, throw that information away after using it to determine which cells are next to vowels, set everything that isn't next to a vowel to some value that will never be relevant so they're not in the way later, and you're basically done. From there you just have to count your As and Os, multiply As by 5 and add the number of Os, special case anything above 8 to avoid J and output. I did choose to handle this one word at a time, rather than taking the whole input at once, so I had to set up the part of the code that reads stdin to break at 0 or 32, but that's not too big of a problem (just wrap the subtraction by 32 in a conditional so it doesn't happen if the value is already 0, then correct for any < or > instructions you missed later).

I don't know how helpful it will be because I wrote it mostly to keep my thoughts straight rather than as a real explanation, but here's the code with my comments and its original indentation:

```<code>+[[>>>,[>++++[<-------->-]]<]get an entire word of input
                            each character lowered by 32
                            two empty cells between characters
                            stops when reaching a space or null byte

any lowercase letters have become uppercase; anything with a value below 65 used
to be an uppercase character; fix it

<<[>]<-[+                for each character until hitting 1:
  [<+>>+<-]              make a backup
  subtract 64 from the character but stop if it hits 0
  ----[>>+<<----]>>+     generate the number 64
  [                      64 times:
    <[                     if the character is not 0:
      -                    subtract 1
      <                    go to a guaranteed 0 cell to break the loop
    ]

    we're either on the character or to the left of it; sync up
    <[>]

  >>-]
  -<[[-]>+<]>            logical NOT of character

  [                      if logical NOT returns true:
    [-[->]<<+>]<-          add 32 to backup of character
  >>>]

  <<<[>>>+<<<-]          move copy over to make room
<<-]
  >>>>>[                 for each character:
  [<+>>+<-]              make copies
  ----[>-<----]>--       check if it's A
  [----<]<[>]>           check if it's E
  [----<]<[>]>           check if it's I
  [------<]<[>]>         check if it's O
  [------<]<[>]>         check if it's U

  IF YOU NEED TO ADD Y; THIS IS THE PLACE

  <+>[[-]<->]            logical NOT to complete vowel check
>>]

<<<[                if the last char is a vowel; prevent a side effect
  >->
]

<[<]>[                 for each character:
  >[                     if it's a vowel:
    <<<<<+>>>>>>+<-          leave a flag to the left and right to show that a
  ]                          vowel is adjacent
<<<<]

<[-]>                  clean up a side effect left behind if first char is vowel

>>>[                   for each char:
  <[                     if it's adjacent to a vowel:
    >[>+<-]<-              move it to the side
  ]
  >[-]-                otherwise; destroy it
  >[<+>-]              move backup over if it exists (subtracting 1)
>>]

all characters without a vowel beside them have been set to 255
all characters with a vowel beside them are set to itself minus 1

notable charaters are: 'A' minus 1 = 64
                       'O' minus 1 = 78

<<<[                 for each character:
  -<----[>-<----]      subtract 64
  >[>+>+<<-]           make a copy
  +>[<->[-]<]<[<]>     logical NOT

  [[<<<]<+>>>>[>>>]<<<-] if NOT returns true; record an A

  >+>--------------  subtract 14 from backup

  [<->[-]]<          logical NOT
  [-<<<<[<<<]>+>>[>>>]>] if NOT returns true; record an O
<<<<]

<[<+<+>>-]           make a backup of A count
>++++[<<[->]>[<]>-]  subtract 4 but don't go below 0
+<<[                   if the char was greater than 3:
  [-]++++<[-]>>          put 4 there
]
>[<]                  resynchronise
<<[>+<-]              if there were fewer than 4 As put the number back

same thing but for the O count

>>+>->[>+>+<<-]       make a backup of O count
<++++[>>[-<]<[>]<-]   subtract 4 but don't go below 0
>>[                     if the char was greater than 3:
  [-]++++>[-]             put 4 there
]
<<<[>]                resynchronise
<->>>>[<+>-]          if there were fewer than 4 Os put the number back

<[<<<+>>>-]<<<<[>+++++<-] A*5 plus B = index of character to output

>[>+>+<<-]            make a backup
<++++++++[>>[-<]<[>]<-] subtract 8 but don't go below 0
>>[[-]>+<]            if the result is nonzero it is late enough in the alphabet
                      that it must be increased by 1 to exclude J as a possible
                      output
----[>+<----]>++      add 65 to make it a letter
.[-]+>>>,             output and get new input
[<++++[>--------<-]]> sub 32 if not 0
]
</code>```

Title: Decode Baby-talk!

Body:
brainfuck, 656 bytes

+[[>>>,[>++++[<-------->-]]<]<<[>]<-[+[<+>>+<-]----[>>+<<----]>>+[<[-<]<[>]>>-]-<[[-]>+<]>[[-[->]<<+>]<->>>]<<<[>>>+<<<-]<<-]>>>>>[[<+>>+<-]----[>-<----]>--[----<]<[>]>[----<]<[>]>[------<]<[>]>[------<]<[>]><+>[[-]<->]>>]<<<[>->]<[<]>[>[<<<<<+>>>>>>+<-]<<<<]<[-]>>>>[<[>[>+<-]<-]>[-]->[<+>-]>>]<<<[-<----[>-<----]>[>+>+<<-]+>[<->[-]<]<[<]>[[<<<]<+>>>>[>>>]<<<-]>+>--------------[<->[-]]<[-<<<<[<<<]>+>>[>>>]>]<<<<]<[<+<+>>-]>++++[<<[->]>[<]>-]+<<[[-]++++<[-]>>]>[<]<<[>+<-]>>+>->[>+>+<<-]<++++[>>[-<]<[>]<-]>>[[-]++++>[-]]<<<[>]<->>>>[<+>-]<[<<<+>>>-]<<<<[>+++++<-]>[>+>+<<-]<++++++++[>>[-<]<[>]<-]>>[[-]>+<]----[>+<----]>++.[-]+>>>,[<++++[>--------<-]]>]

This was a pretty good way to kill a couple of hours.

Requires a brainfuck interpreter that uses 8-bit wrapping cells, allows you to go left from cell 0 and returns 0 if , is used when stdin is empty. In my experience, these are the most common settings.

This program does not consider Y a vowel, but if OP wants it to it's an easy fix.

It seems like writing this would be a daunting task but if you have some familiarity with the language there's nothing surprising or new in the code. Standard brainfuck tactics: Read the input but make sure you leave a couple of empty cells between each byte, use those empty cells to store data about the input, use the data you stored to decide how to transform it and spit something out at the end. In this case it was get the input, set it all to uppercase, figure out which cells are vowels, throw that information away after using it to determine which cells are next to vowels, set everything that isn't next to a vowel to some value that will never be relevant so they're not in the way later, and you're basically done. From there you just have to count your As and Os, multiply As by 5 and add the number of Os, special case anything above 8 to avoid J and output. I did choose to handle this one word at a time, rather than taking the whole input at once, so I had to set up the part of the code that reads stdin to break at 0 or 32, but that's not too big of a problem (just wrap the subtraction by 32 in a conditional so it doesn't happen if the value is already 0, then correct for any < or > instructions you missed later).

I don't know how helpful it will be because I wrote it mostly to keep my thoughts straight rather than as a real explanation, but here's the code with my comments and its original indentation:

+[[>>>,[>++++[<-------->-]]<]get an entire word of input
                            each character lowered by 32
                            two empty cells between characters
                            stops when reaching a space or null byte

any lowercase letters have become uppercase; anything with a value below 65 used
to be an uppercase character; fix it

<<[>]<-[+                for each character until hitting 1:
  [<+>>+<-]              make a backup
  subtract 64 from the character but stop if it hits 0
  ----[>>+<<----]>>+     generate the number 64
  [                      64 times:
    <[                     if the character is not 0:
      -                    subtract 1
      <                    go to a guaranteed 0 cell to break the loop
    ]

    we're either on the character or to the left of it; sync up
    <[>]

  >>-]
  -<[[-]>+<]>            logical NOT of character

  [                      if logical NOT returns true:
    [-[->]<<+>]<-          add 32 to backup of character
  >>>]

  <<<[>>>+<<<-]          move copy over to make room
<<-]
  >>>>>[                 for each character:
  [<+>>+<-]              make copies
  ----[>-<----]>--       check if it's A
  [----<]<[>]>           check if it's E
  [----<]<[>]>           check if it's I
  [------<]<[>]>         check if it's O
  [------<]<[>]>         check if it's U

  IF YOU NEED TO ADD Y; THIS IS THE PLACE

  <+>[[-]<->]            logical NOT to complete vowel check
>>]

<<<[                if the last char is a vowel; prevent a side effect
  >->
]

<[<]>[                 for each character:
  >[                     if it's a vowel:
    <<<<<+>>>>>>+<-          leave a flag to the left and right to show that a
  ]                          vowel is adjacent
<<<<]

<[-]>                  clean up a side effect left behind if first char is vowel

>>>[                   for each char:
  <[                     if it's adjacent to a vowel:
    >[>+<-]<-              move it to the side
  ]
  >[-]-                otherwise; destroy it
  >[<+>-]              move backup over if it exists (subtracting 1)
>>]

all characters without a vowel beside them have been set to 255
all characters with a vowel beside them are set to itself minus 1

notable charaters are: 'A' minus 1 = 64
                       'O' minus 1 = 78

<<<[                 for each character:
  -<----[>-<----]      subtract 64
  >[>+>+<<-]           make a copy
  +>[<->[-]<]<[<]>     logical NOT

  [[<<<]<+>>>>[>>>]<<<-] if NOT returns true; record an A

  >+>--------------  subtract 14 from backup

  [<->[-]]<          logical NOT
  [-<<<<[<<<]>+>>[>>>]>] if NOT returns true; record an O
<<<<]

<[<+<+>>-]           make a backup of A count
>++++[<<[->]>[<]>-]  subtract 4 but don't go below 0
+<<[                   if the char was greater than 3:
  [-]++++<[-]>>          put 4 there
]
>[<]                  resynchronise
<<[>+<-]              if there were fewer than 4 As put the number back

same thing but for the O count

>>+>->[>+>+<<-]       make a backup of O count
<++++[>>[-<]<[>]<-]   subtract 4 but don't go below 0
>>[                     if the char was greater than 3:
  [-]++++>[-]             put 4 there
]
<<<[>]                resynchronise
<->>>>[<+>-]          if there were fewer than 4 Os put the number back

<[<<<+>>>-]<<<<[>+++++<-] A*5 plus B = index of character to output

>[>+>+<<-]            make a backup
<++++++++[>>[-<]<[>]<-] subtract 8 but don't go below 0
>>[[-]>+<]            if the result is nonzero it is late enough in the alphabet
                      that it must be increased by 1 to exclude J as a possible
                      output
----[>+<----]>++      add 65 to make it a letter
.[-]+>>>,             output and get new input
[<++++[>--------<-]]> sub 32 if not 0
]


答:
Matlab, <s>38</s> 35 bytes

Anonymous function:

```<code>@()['pcbm';'ejkh';'ifgl';'dnoa']-96
</code>```

Direct printing (38 bytes):

```<code>disp(['pcbm';'ejkh';'ifgl';'dnoa']-96)
</code>```

In Matlab best way to produce an array of integers is though a string.

Title: Produce Dürer's magic square

Body:
Matlab, <s>38</s> 35 bytes

Anonymous function:

@()['pcbm';'ejkh';'ifgl';'dnoa']-96

Direct printing (38 bytes):

disp(['pcbm';'ejkh';'ifgl';'dnoa']-96)

In Matlab best way to produce an array of integers is though a string.


答:
Perl, 33 bytes

Includes +1 for -p

Give vector as string without spaces on STDIN:

```<code>antsy.pl <<< 110
</code>```

antsy.pl:

```<code>#!/usr/bin/perl -p
s%^|.%y/0//+($&?++$a:$b--).$"%eg
</code>```

Title: Generate antsy permutations

Body:
Perl, 33 bytes

Includes +1 for -p

Give vector as string without spaces on STDIN:

antsy.pl <<< 110

antsy.pl:

#!/usr/bin/perl -p
s%^|.%y/0//+($&?++$a:$b--).$"%eg


答:
05AB1E, 15 bytes

```<code>16Lœ•iPNÍš¯•è4ä
</code>```

Explanation

```<code>16L              # range [1 ... 16]
   œ             # compute all permutations of the range
    •iPNÍš¯•è    # take the permutation at index 19800593106059
             4ä  # split the permutation into 4 parts
</code>```

The index of the permutation was found using the formula:

a*15! + b*14! + c*13!+ ... + o*1! + p*0!

Where the variables are replaced with the number of succeeding elements which are smaller than the number at the current index for each number in the target list

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

which for our sought after permutation is

a=15, b=2, c=1, d=10, e=2, f=6, g=6, h=4, i=4, j=2, k=2, l=2, m=1, n=2 o=1, p=0

This gives us the formula:
15*15!+2*14!+1*13!+10*12!+2*11!+6*10!+6*9!+4*8!+4*7!+2*6!+2*5!+2*4!+1*3!+2*2!+1*1!+0*0!

which is equal to 19800593106059.

Title: Produce Dürer's magic square

Body:
05AB1E, 15 bytes

16Lœ•iPNÍš¯•è4ä

Explanation

16L              # range [1 ... 16]
   œ             # compute all permutations of the range
    •iPNÍš¯•è    # take the permutation at index 19800593106059
             4ä  # split the permutation into 4 parts

The index of the permutation was found using the formula:

a*15! + b*14! + c*13!+ ... + o*1! + p*0!

Where the variables are replaced with the number of succeeding elements which are smaller than the number at the current index for each number in the target list

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

which for our sought after permutation is

a=15, b=2, c=1, d=10, e=2, f=6, g=6, h=4, i=4, j=2, k=2, l=2, m=1, n=2 o=1, p=0

This gives us the formula:
15*15!+2*14!+1*13!+10*12!+2*11!+6*10!+6*9!+4*8!+4*7!+2*6!+2*5!+2*4!+1*3!+2*2!+1*1!+0*0!

which is equal to 19800593106059.


答:
Jelly, <s>13</s> 12 bytes

```<code>J_þTİ²SiṂ$Ṭo
</code>```

Try it online! or Verify all test cases.

Explanation

```<code>J_þTİ²SiṂ$Ṭo  Input: boolean array A
J             Indices, returns [1, 2, ..., len(A)]
   T          Truthy indices, returns the indices which have a truthy value
 _þ           Form the subtraction (_) table (þ) between them
    İ         Inverse, find the reciprocal of each
     ²        Square each
      S       Sum the sublists column-wise
         $    Monadic chain
        Ṃ       Minimum
       i        Find the first index of that
          Ṭ   Untruth indices, returns a boolean array with 1's at those indices
           o  Logical OR between that and A, and return
</code>```

Title: Positional Bathroom Etiquette

Body:
Background

Bathroom Etiquette, when pertaining to the available urinals, states that the next urinal to be filled in should be the one that minimizes the total discomfort. The total discomfort equation is given by the following set of equations:

```
<b>dist(x,y)</b> = linear distance between person x and person y in Urinal Units
<b>discomfort(x)</b> = sum(1/(dist(x,y)*dist(x,y))) for all persons y excluding person x
<b>total_Discomfort</b> = sum(discomfort(x)) for all x
```

A more in depth paper dealing with a similar (not the exact same) problem can be found here: (Thanks to @Lembik for alerting me to this amazing whitepaper!)

Input/Output

Given an input of a empty and full urinals, output the resulting set of urinals with the addition of one person. If there is a tie for a position the urinals should fill in left to right. The output should be in the same format as the input.

If given a case with full urinals, return the input.

The input will always have at least one urinal defined.

Test Cases

```
<b>INPUT     -> OUTPUT</b>
1000001   -> 1001001
101010101 -> 111010101
100       -> 101
00000     -> 10000
1111111   -> 1111111
0100      -> 0101
101000    -> 101001
```

Rules

This is code-golf, so shortest code in bytes wins. Standard loop-holes are forbidden.

Body:
Jelly, <s>13</s> 12 bytes

J_þTİ²SiṂ$Ṭo

Try it online! or Verify all test cases.

Explanation

J_þTİ²SiṂ$Ṭo  Input: boolean array A
J             Indices, returns [1, 2, ..., len(A)]
   T          Truthy indices, returns the indices which have a truthy value
 _þ           Form the subtraction (_) table (þ) between them
    İ         Inverse, find the reciprocal of each
     ²        Square each
      S       Sum the sublists column-wise
         $    Monadic chain
        Ṃ       Minimum
       i        Find the first index of that
          Ṭ   Untruth indices, returns a boolean array with 1's at those indices
           o  Logical OR between that and A, and return


Title: Positional Bathroom Etiquette

Body:
Python, <s>165</s> <s>163</s> <s>158</s> <s>147</s> <s>141</s> <s>140</s> 139 bytes

def u(p):e=enumerate;a=[(sum((i-j)**-2for j,y in e(p)if"0"<y),i)for i,x in e(p)if"1">x];return a and p[:min(a)[1]]+"1"+p[min(a)[1]+1:] or p