问:
What's the chance that I'll win a door prize?
My local ACM chapter gives out door prizes to people who come to the meetings. You get an increased chance of winning if you solve the programming puzzle, however (but I always solve that puzzle). Thus, some people have 1 entry, while others have 2. But wait! The way the raffle program works is not by adding in another entry when someone solves the puzzle. Instead, it keeps track of the number of "lives" a person has, decrementing that if that person is chosen in each pass of it's random sampling algorithm. So it works like this:

```<code>Doorknob: 1.  xnor: 2.  Justin: 2.  Alex: 1.  Dennis: 2.
</code>```

Then the program randomly chooses one of [Doorknob, xnor, Justin, Alex, Dennis], decrements the number (say it chooses Justin):

```<code>Doorknob: 1.  xnor: 2.  Justin: 1.  Alex: 1. Dennis: 2.
</code>```

And repeats. If someone's number of "lives" goes to 0 (let's choose Justin again), they're removed from the list:

```<code>Doorknob: 1.  xnor: 2.  Alex: 1.  Dennis: 2.
</code>```

This continues until there's one person left; that person is the winner.

Now the real question is, what was the probability that I would have won?

You will be given two inputs:

n. This is the number of people entered into the challenge

k. This is the number of people (of those n) who have 2 lives. This number always includes you.

So if I had a function p and called p(10, 5), that would be the probability of winning the prize where there are 10 people total, 5 of which only have 1 life, whereas 5 (including you) have 2 lives.

You are expected to output the probability of winning either exactly, or as a decimal. At any rate, answers must be accurate up to and including the 4th decimal place after the decimal point. Whether or not you round to that digit is up to you.

Your solution may be a randomized solution which outputs the answer to the 4th decimal place with high probability. You may assume that the built in RNG you use is truly random, and it must output the correct answer with at least 90% probability.

Furthermore, your code need only work for n, k <= 1000, although I did provide test cases larger than that for those curious.

Test Cases

Note: some of these are general formulae.

```<code>n,    k   |  output
----------+---------
1,    1   |  1
2,    2   |  0.5
2,    1   |  0.75
3,    1   |  11/18 = 0.611111111
1000, 1   |  0.007485470860550352
4,    3   |  0.3052662037037037
k,    k   |  1/k
n,    1   |  (EulerGamma + PolyGamma[1 + n])/n    (* Mathematica code *)
          |  (γ + ψ(1 + n))/n
10,   6   |  0.14424629234373537
300,  100 |  0.007871966408910648
500,  200 |  0.004218184180294532
1000, 500 |  0.0018008560286627948
---------------------------------- Extra (not needed to be a valid answer)
5000, 601 |  0.0009518052922680399
5000, 901 |  0.0007632938197806958
</code>```

For another few checks, take p(n, 1) * n as follows:

```<code>n     |  output
------+---------
1     | 1
2     | 1.5
3     | 1.8333333333333335
10    | 2.928968253968254
100   | 5.1873775176396215
-------------------------- Extra (not needed to be a valid answer)
100000| 12.090146129863305
</code>```

答:
Pyth, 34 bytes

```<code>Mc|!*HJ-GHch*J+*tHgGtH*gtGHKh-GHKG
</code>```

Test suite

Defines a deterministic memoized recursive function g taking n, k as arguments.  g 1000 500 returns 0.0018008560286627952 in about 18 seconds (not included in the above test suite because it times out the online interpreter).

An approximate Python 3 translation would be

@memoized
def g(n,k):
    return (not k*(n-k) or (1+(n-k)*((k-1)*g(n,k-1)+g(n-1,k)*(n-k+1)))/(n-k+1))/n
```

Body:
Pyth, 34 bytes

Mc|!*HJ-GHch*J+*tHgGtH*gtGHKh-GHKG

Test suite

Defines a deterministic memoized recursive function g taking n, k as arguments.  g 1000 500 returns 0.0018008560286627952 in about 18 seconds (not included in the above test suite because it times out the online interpreter).

An approximate Python 3 translation would be

@memoized
def g(n,k):
    return (not k*(n-k) or (1+(n-k)*((k-1)*g(n,k-1)+g(n-1,k)*(n-k+1)))/(n-k+1))/n


问:
Partial factorisations of a positive integer
A collection of positive integers d_1 d_2 ... d_k is a factorisation of a positive integer n if

```<code>d_1 * d_2 * ... * d_k = n
</code>```

Each positive integer has a unique prime factorisation, but in general they also have factorisations in which some of the terms are composite. E.g.

```<code>12 = 6 * 2 = 4 * 3 = 3 * 2 * 2
</code>```

Write a program, function, verb, or similar which takes as input a single positive integer and returns or prints a complete list of its distinct factorisations. The factorisations may be produced in any order, and their terms may be in any order, but no two should be permutations of each other. Factorisations may not include 1 with two exceptions: for input n you may give the factorisation n*1 instead of n; and for input 1 you may give the factorisation 1 instead of the empty list.

You may assume that the input will be in the range of a signed 32-bit integer. If the output is as a string, there should be a clear distinction between the delimitation of numbers within a factorisation and the delimitation of the factorisations, but it is not necessary (for example) for the factors to be joined with an *.

Your code should be capable of handling any valid input within 10 minutes on a reasonable desktop machine.

Examples

```<code>1                  [[]]
                or [[1]]
                or [[1 1]]

7                  [[7]]
                or [[7 1]]
                or [[1 7]]

12                 [[12] [6 2] [4 3] [2 3 2]]
                or variants

16                 [[2 2 2 2] [2 2 4] [2 8] [4 4] [16]]
                or variants

901800900          a list of 198091 factorisations

1338557220         a list of 246218 factorisations
</code>```

答:
Haskell, 56 bytes

_!1=[[]]
i!n=[j:f|j<-[i..n],mod n j<1,f<-j!div n j]
(2!)
```

<p><code>(2!)(1338557220::Int)</code> prints in five minutes on my laptop, when compiled with <code>ghc -O3</code>.</p>

<h1>Haskell, 62 bytes, but much faster</h1>

<pre class="lang-hs prettyprint-override"><code>i!n|i*i>n=[[n]]|0<1=[i:f|mod n i<1,f<-i!div n i]++(i+1)!n
(2!)
</code>```

(2!)(1338557220::Int) prints in a quarter of a second on my laptop, when compiled with ghc -O3.

ContentLicense: CC BY-SA 3.0

Body:
Haskell, 56 bytes

_!1=[[]]
i!n=[j:f|j<-[i..n],mod n j<1,f<-j!div n j]
(2!)

(2!)(1338557220::Int) prints in five minutes on my laptop, when compiled with ghc -O3.

Haskell, 62 bytes, but much faster

i!n|i*i>n=[[n]]|0<1=[i:f|mod n i<1,f<-i!div n i]++(i+1)!n
(2!)

(2!)(1338557220::Int) prints in a quarter of a second on my laptop, when compiled with ghc -O3.


答:
Python, <s>252</s> <s>313</s> <s>312</s> <s>311</s> <s>145</s> <s>141</s> <s>137</s> <s>135</s> <s>103</s> <s>84</s> 83 bytes

This is largely based on Anders Kaseorg's Pyth answer. Any golfing suggestions welcome. Try it online!

Edit: 19 bytes golfed thanks to Dennis. Fixed a typo in the code and added a TIO link.

g=lambda n,m=2:[[n]]+[j+[d]for d in range(m,int(n**.5)+1)if n%d<1for j in g(n/d,d)]
```

<p><strong>Ungolfed:</strong></p>

<pre class="lang-python prettyprint-override"><code>def g(n, m=2):
    a = [[n]]
    s = int(n**.5) + 1
    for d in range(m, s):
        if n%d == 0:
            for j in g(n/d, d):
                a.append([d]+j)
    return a
</code>```

Title: Partial factorisations of a positive integer

Body:
A collection of positive integers d_1 d_2 ... d_k is a factorisation of a positive integer n if

```<code>d_1 * d_2 * ... * d_k = n
</code>```

Each positive integer has a unique prime factorisation, but in general they also have factorisations in which some of the terms are composite. E.g.

```<code>12 = 6 * 2 = 4 * 3 = 3 * 2 * 2
</code>```

Write a program, function, verb, or similar which takes as input a single positive integer and returns or prints a complete list of its distinct factorisations. The factorisations may be produced in any order, and their terms may be in any order, but no two should be permutations of each other. Factorisations may not include 1 with two exceptions: for input n you may give the factorisation n*1 instead of n; and for input 1 you may give the factorisation 1 instead of the empty list.

You may assume that the input will be in the range of a signed 32-bit integer. If the output is as a string, there should be a clear distinction between the delimitation of numbers within a factorisation and the delimitation of the factorisations, but it is not necessary (for example) for the factors to be joined with an *.

Your code should be capable of handling any valid input within 10 minutes on a reasonable desktop machine.

Examples

```<code>1                  [[]]
                or [[1]]
                or [[1 1]]

7                  [[7]]
                or [[7 1]]
                or [[1 7]]

12                 [[12] [6 2] [4 3] [2 3 2]]
                or variants

16                 [[2 2 2 2] [2 2 4] [2 8] [4 4] [16]]
                or variants

901800900          a list of 198091 factorisations

1338557220         a list of 246218 factorisations
</code>```

Body:
Python, <s>252</s> <s>313</s> <s>312</s> <s>311</s> <s>145</s> <s>141</s> <s>137</s> <s>135</s> <s>103</s> <s>84</s> 83 bytes

This is largely based on Anders Kaseorg's Pyth answer. Any golfing suggestions welcome. Try it online!

Edit: 19 bytes golfed thanks to Dennis. Fixed a typo in the code and added a TIO link.

g=lambda n,m=2:[[n]]+[j+[d]for d in range(m,int(n**.5)+1)if n%d<1for j in g(n/d,d)]

Ungolfed:

def g(n, m=2):
    a = [[n]]
    s = int(n**.5) + 1
    for d in range(m, s):
        if n%d == 0:
            for j in g(n/d, d):
                a.append([d]+j)
    return a


问:
Removing unique elements from string
I came upon this question, because it seems to be very common use-case to find unique characters in string. But what if we want to get rid of them?

Input contains only lower case alphabets. Only letters from a to z are used. Input length may be from 1 to 1000 characters.

Example:

input: helloworld

output: llool

Objective: Shortest code wins

Language: Any of the top 20 of TIOBE languages

答:
PHP - 70

```<code>while($x<strlen($s)){$c=$s[$x];echo substr_count($s,$c)>1?$c:'';$x++;}
</code>```

with asumption $s = 'helloworld'.

Title: Removing unique elements from string

Body:
PHP - 70

while($x<strlen($s)){$c=$s[$x];echo substr_count($s,$c)>1?$c:'';$x++;}

with asumption $s = 'helloworld'.


问:
Golf all the 16 logic gates with 2 inputs and 1 output!
For example, the gate A and B is a logic gate with 2 inputs and 1 output.

There are exactly 16 of them, because:

each logic gate takes two inputs, which can be truthy or falsey, giving us 4 possible inputs

of the 4 possible inputs, each can have an output of truthy and falsey

therefore, there are 2^4 possible logic gates, which is 16.

Your task is to write 16 programs/functions which implement all of them separately.

Your functions/programs must be independent.

They are valid as long as they output truthy/falsey values, meaning that you can implement A or B in Python as lambda a,b:a+b, even if 2 is produced for A=True and B=True.

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

0,0,1,0 (A and not B)

0,0,1,1 (A)

0,1,0,0 (not A and B)

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

1,0,1,1 (B implies A)

1,1,0,0 (not A)

1,1,0,1 (A implies B)

1,1,1,0 (nand)

1,1,1,1 (true)

Where the first number is the output for A=false, B=false,
the second number is the output for A=false, B=true,
the third number is the output for A=true, B=false,
the fourth number is the output for A=true, B=true.

Leaderboard

var QUESTION_ID=82938,OVERRIDE_USER=48934;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+(?:\.\d+)?)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;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

```

答:
Coconut, 88 bytes

0000 [].sort
0001 (*)
0010 (>)
0011 round
0100 (<)
0101 range
0110 (^)
0111 (|)
1000 (not)..(|)
1001 (==)
1010 (a,b)->b<1
1011 pow
1100 (a,b)->a<1
1101 (<=)
1110 (not)..(*)
1111 slice
```

Coconut is an extension of Python. Every valid program in Python is also valid in Coconut.

Credits to xnor for some of the functions.

Body:
Coconut, 88 bytes

0000 [].sort
0001 (*)
0010 (>)
0011 round
0100 (<)
0101 range
0110 (^)
0111 (|)
1000 (not)..(|)
1001 (==)
1010 (a,b)->b<1
1011 pow
1100 (a,b)->a<1
1101 (<=)
1110 (not)..(*)
1111 slice

Coconut is an extension of Python. Every valid program in Python is also valid in Coconut.

Credits to xnor for some of the functions.


Title: Golf all the 16 logic gates with 2 inputs and 1 output!

Body:
For example, the gate A and B is a logic gate with 2 inputs and 1 output.

There are exactly 16 of them, because:

each logic gate takes two inputs, which can be truthy or falsey, giving us 4 possible inputs

of the 4 possible inputs, each can have an output of truthy and falsey

therefore, there are 2^4 possible logic gates, which is 16.

Your task is to write 16 programs/functions which implement all of them separately.

Your functions/programs must be independent.

They are valid as long as they output truthy/falsey values, meaning that you can implement A or B in Python as lambda a,b:a+b, even if 2 is produced for A=True and B=True.

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

0,0,1,0 (A and not B)

0,0,1,1 (A)

0,1,0,0 (not A and B)

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

1,0,1,1 (B implies A)

1,1,0,0 (not A)

1,1,0,1 (A implies B)

1,1,1,0 (nand)

1,1,1,1 (true)

Where the first number is the output for A=false, B=false,
the second number is the output for A=false, B=true,
the third number is the output for A=true, B=false,
the fourth number is the output for A=true, B=true.

Leaderboard

var QUESTION_ID=82938,OVERRIDE_USER=48934;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+(?:\.\d+)?)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;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

```

Body:
Golfscript, 36 bytes

0000 ;
0001 ~*
0010 ~>
0011 ~;
0100 ~<
0101 ~\;
0110 ~^
0111 ~|
1000 ~*!
1001 ~=
1010 ~\;!
1011 ~?
1100 ~;!
1101 ~>!
1110 ~*!
1111

Online interpreter.


答:
Pyth, 29 bytes

```<code>Msam+Ldgd/Hdf!%HT>S@H2tG]]Hg2

M                                def g(G, H):
                   @H2             square root of H
                  S                1-indexed range up to floor
                 >    tG           all but first G − 1 elements
            f                      filter for elements T such that:
              %HT                    H mod T
             !                       is false (0)
   m                               map for elements d:
       gd/Hd                         g(d, H/d)
    +Ld                              prepend d to each element
  a                     ]]H        append [[H]]
 s                                 concatenate
                           g2Q   print g(2, input)
</code>```

Try it online

Runs in twenty seconds for 1338557220 on my laptop.

Body:
Pyth, 29 bytes

Msam+Ldgd/Hdf!%HT>S@H2tG]]Hg2

M                                def g(G, H):
                   @H2             square root of H
                  S                1-indexed range up to floor
                 >    tG           all but first G − 1 elements
            f                      filter for elements T such that:
              %HT                    H mod T
             !                       is false (0)
   m                               map for elements d:
       gd/Hd                         g(d, H/d)
    +Ld                              prepend d to each element
  a                     ]]H        append [[H]]
 s                                 concatenate
                           g2Q   print g(2, input)

Try it online

Runs in twenty seconds for 1338557220 on my laptop.


问:
Do X without Y
Usually, it is said that "Doing X without Y" can be a trap to beginners writing challenges (source). However, I am cocky and think that I can definitely make an X without any Ys. Randomly. Oh yes, this will be good.

Challenge: Given an odd integer n greater than or equal to 1, output an ex of side length n made of random printable ascii characters sans "y" and "Y", and the space. All allowed characters must have a nonzero chance of occurring, but not necessarily uniform. This is a code-golf so the shortest code in bytes wins. You should, however, randomize each char--that is, the struts of the ex shouldn't be equal, unless if by chance.

The chars to appear

```<code>!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXZ[\]^_`abcdefghijklmnopqrstuvwxz{|}~"
</code>```

Constructing the ex

Side length 1:

```<code>x
</code>```

Side length 3:

```<code>x x
 x
x x
</code>```

Side length 5:

```<code>x   x
 x x
  x
 x x
x   x
</code>```

etc.

Example outputs

```<code>input
output
empty line

3
h 2
 ^
9 5

1
:

5
D   1
 W z
  W
 q j
W   1
</code>```

Example implementation

You do not need to handle invalid inputs.

function generate(sideLength){
    var result = "";
    var INNER = "@"
    for(var i = 0; i < sideLength; i++){
        var p = i < sideLength / 2 ? i : sideLength - i - 1;
        result += " ".repeat(p) + ((sideLength / 2 | 0) == p ? "" : INNER) + " ".repeat(Math.max(sideLength - p * 2 - 2, 0)) + INNER + "\n";
    }

    return result.replace(RegExp(INNER, "g"), function(e){
        let c = "y";
        while(c === "y" || c === "Y"){
            c = String.fromCharCode((Math.random() * 94) + 33 | 0);
        }
        return c;
    });
}

function print(v){
    output.innerHTML = "";
    output.appendChild(document.createTextNode(v));
}

function update(){
    var n = Number(input.value);
    if(n !== Math.floor(n)) print("error: " + n + " is not an integer.");
    else if(n % 2 === 0)    print("error: " + n + " is not odd.");
    else if(n < 1)          print("error: " + n + "is less than one.");
    else                    print(generate(n));
}

input.onchange = update;

update();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  font-family: Consolas, monospace;
}

#output {
  white-space: pre;
}</code>```

<input id="input" min=1 value=1 type=Number>

```

答:
x86 machine code, 70 bytes

```<code>60 89 d7 31 db 43 88 ce b2 fe 49 d1 e1 87 da 0f
c7 f0 24 7f 3c 22 72 f7 48 3c 79 74 f2 3c 59 74
ee aa 49 7c 1c 00 df 79 06 86 f7 42 43 eb f6 f6
c3 01 74 03 b0 0a aa 51 88 f9 b0 20 f3 aa 59 eb
cc c6 07 00 61 c3
</code>```

My executable code, disassembled:

```<code>0000003d <myheh>:
  3d:   60                      pusha
  3e:   89 d7                   mov    %edx,%edi
  40:   31 db                   xor    %ebx,%ebx
  42:   43                      inc    %ebx
  43:   88 ce                   mov    %cl,%dh
  45:   b2 fe                   mov    $0xfe,%dl
  47:   49                      dec    %ecx
  48:   d1 e1                   shl    %ecx

0000004a <myloop>:
  4a:   87 da                   xchg   %ebx,%edx

0000004c <myrand>:
  4c:   0f c7 f0                rdrand %eax
  4f:   24 7f                   and    $0x7f,%al
  51:   3c 22                   cmp    $0x22,%al
  53:   72 f7                   jb     4c <myrand>
  55:   48                      dec    %eax
  56:   3c 79                   cmp    $0x79,%al
  58:   74 f2                   je     4c <myrand>
  5a:   3c 59                   cmp    $0x59,%al
  5c:   74 ee                   je     4c <myrand>
  5e:   aa                      stos   %al,%es:(%edi)
  5f:   49                      dec    %ecx
  60:   7c 1c                   jl     7e <mydone>

00000062 <mylab>:
  62:   00 df                   add    %bl,%bh
  64:   79 06                   jns    6c <myprint>
  66:   86 f7                   xchg   %dh,%bh
  68:   42                      inc    %edx
  69:   43                      inc    %ebx
  6a:   eb f6                   jmp    62 <mylab>

0000006c <myprint>:
  6c:   f6 c3 01                test   $0x1,%bl
  6f:   74 03                   je     74 <myprint1>
  71:   b0 0a                   mov    $0xa,%al
  73:   aa                      stos   %al,%es:(%edi)

00000074 <myprint1>:
  74:   51                      push   %ecx
  75:   88 f9                   mov    %bh,%cl
  77:   b0 20                   mov    $0x20,%al
  79:   f3 aa                   rep stos %al,%es:(%edi)
  7b:   59                      pop    %ecx
  7c:   eb cc                   jmp    4a <myloop>

0000007e <mydone>:
  7e:   c6 07 00                movb   $0x0,(%edi)
  81:   61                      popa
  82:   c3                      ret
</code>```

It is a function that receives the size of the X in ecx, and a pointer to the output buffer in edx.

It fills the output buffer sequentially with bytes. There are 2 * n - 1 iterations (equal to the number of non-space characters to output). At each iteration, it does the following:

Generate a random number

Fiddle with the number to fit it into range; if it's bad, go back and generate anew

Print the random character

Print a newline (every other iteration)

Print the proper number of spaces

Conversion from a random number to a random character is not remarkable:

```<code>myrand:
    rdrand eax;
    and al, 7fh;
    cmp al, 22h;
    jb myrand;
    dec eax;
    cmp al, 'y';
    je myrand;
    cmp al, 'Y';
    je myrand;
</code>```

The interesting part is the calculation of the number of spaces. It must generate the following numbers (example for N=9):

```<code>7    1
5    2
3    3
1    4

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

The numbers are taken alternatingly from two arithmetic progressions. The first one goes down with step -2, and the second one goes up with step 1. When the first progression arrives at -1 (in the middle of the X), there is a glitch (-1 is removed), and then the progressions change direction.

The progressions are stored in registers ebx and edx - the high parts bh and dh store the current number, and the low parts bl and dl store the step. To alternate between the progressions, the code swaps the registers with xchg.

When the progression arrives at -1 (around the mylab label), it increases both registers, switching the steps from -2, 1 to -1, 2. This also changes the roles of the registers, so then it swaps the high parts of the registers.

At the end of the function, it stores a zero byte to indicate an end of string.

Title: Do X without Y

Body:
x86 machine code, 70 bytes

60 89 d7 31 db 43 88 ce b2 fe 49 d1 e1 87 da 0f
c7 f0 24 7f 3c 22 72 f7 48 3c 79 74 f2 3c 59 74
ee aa 49 7c 1c 00 df 79 06 86 f7 42 43 eb f6 f6
c3 01 74 03 b0 0a aa 51 88 f9 b0 20 f3 aa 59 eb
cc c6 07 00 61 c3

My executable code, disassembled:

0000003d <myheh>:
  3d:   60                      pusha
  3e:   89 d7                   mov    %edx,%edi
  40:   31 db                   xor    %ebx,%ebx
  42:   43                      inc    %ebx
  43:   88 ce                   mov    %cl,%dh
  45:   b2 fe                   mov    $0xfe,%dl
  47:   49                      dec    %ecx
  48:   d1 e1                   shl    %ecx

0000004a <myloop>:
  4a:   87 da                   xchg   %ebx,%edx

0000004c <myrand>:
  4c:   0f c7 f0                rdrand %eax
  4f:   24 7f                   and    $0x7f,%al
  51:   3c 22                   cmp    $0x22,%al
  53:   72 f7                   jb     4c <myrand>
  55:   48                      dec    %eax
  56:   3c 79                   cmp    $0x79,%al
  58:   74 f2                   je     4c <myrand>
  5a:   3c 59                   cmp    $0x59,%al
  5c:   74 ee                   je     4c <myrand>
  5e:   aa                      stos   %al,%es:(%edi)
  5f:   49                      dec    %ecx
  60:   7c 1c                   jl     7e <mydone>

00000062 <mylab>:
  62:   00 df                   add    %bl,%bh
  64:   79 06                   jns    6c <myprint>
  66:   86 f7                   xchg   %dh,%bh
  68:   42                      inc    %edx
  69:   43                      inc    %ebx
  6a:   eb f6                   jmp    62 <mylab>

0000006c <myprint>:
  6c:   f6 c3 01                test   $0x1,%bl
  6f:   74 03                   je     74 <myprint1>
  71:   b0 0a                   mov    $0xa,%al
  73:   aa                      stos   %al,%es:(%edi)

00000074 <myprint1>:
  74:   51                      push   %ecx
  75:   88 f9                   mov    %bh,%cl
  77:   b0 20                   mov    $0x20,%al
  79:   f3 aa                   rep stos %al,%es:(%edi)
  7b:   59                      pop    %ecx
  7c:   eb cc                   jmp    4a <myloop>

0000007e <mydone>:
  7e:   c6 07 00                movb   $0x0,(%edi)
  81:   61                      popa
  82:   c3                      ret

It is a function that receives the size of the X in ecx, and a pointer to the output buffer in edx.

It fills the output buffer sequentially with bytes. There are 2 * n - 1 iterations (equal to the number of non-space characters to output). At each iteration, it does the following:

Generate a random number

Fiddle with the number to fit it into range; if it's bad, go back and generate anew

Print the random character

Print a newline (every other iteration)

Print the proper number of spaces

Conversion from a random number to a random character is not remarkable:

myrand:
    rdrand eax;
    and al, 7fh;
    cmp al, 22h;
    jb myrand;
    dec eax;
    cmp al, 'y';
    je myrand;
    cmp al, 'Y';
    je myrand;

The interesting part is the calculation of the number of spaces. It must generate the following numbers (example for N=9):

7    1
5    2
3    3
1    4

     3
1    2
3    1
5    0
7

The numbers are taken alternatingly from two arithmetic progressions. The first one goes down with step -2, and the second one goes up with step 1. When the first progression arrives at -1 (in the middle of the X), there is a glitch (-1 is removed), and then the progressions change direction.

The progressions are stored in registers ebx and edx - the high parts bh and dh store the current number, and the low parts bl and dl store the step. To alternate between the progressions, the code swaps the registers with xchg.

When the progression arrives at -1 (around the mylab label), it increases both registers, switching the steps from -2, 1 to -1, 2. This also changes the roles of the registers, so then it swaps the high parts of the registers.

At the end of the function, it stores a zero byte to indicate an end of string.


答:
JavaScript (ES6), 83 bytes

```<code>f=(n,a=[],m=2,i=m)=>{for(;i*i<=n;i++)n%i<1&&f(n/i,[...a,i],i);console.log(...a,n)}
</code>```

Only borrowed @AndersKaseorg's square root trick because it ended up saving me bytes overall. Prints 1 for an input of 1, otherwise doesn't print 1s.

Body:
JavaScript (ES6), 83 bytes

f=(n,a=[],m=2,i=m)=>{for(;i*i<=n;i++)n%i<1&&f(n/i,[...a,i],i);console.log(...a,n)}

Only borrowed @AndersKaseorg's square root trick because it ended up saving me bytes overall. Prints 1 for an input of 1, otherwise doesn't print 1s.


Body:
Binary lambda calculus, 216 bits = 27 bytes

Uses the Church numerals 0 = λx. λy. y, 1 = λx. x as booleans.

0,0,0,0 (false): 0000000010 = λa. λb. λx. λy. y

0,0,0,1 (and): 000001011000111010 = λa. λb. b (λx. a) b

0,0,1,0 (A and not B): 0000010111010000010 = λa. λb. a b (λx. λy. y)

0,0,1,1 (A): 0000110 = λa. λb. a

0,1,0,0 (not A and B): 00011000001110 = λa. a (λx. λy. a)

0,1,0,1 (B): 000010 = λa. λb. b

0,1,1,0 (xor): 00011000011000110 = λa. a (λx. x (λy. x))

0,1,1,1 (or): 00011000110 = λa. a (λx. a)

1,0,0,0 (nor): 00000101011101010000010 = λa. λb. a b b (λx. λy. y)

1,0,0,1 (xnor): 0001011000110000110110 = λa. a (λx. a) (λb. b a)

1,0,1,0 (not B): 0000011000110 = λa. λb. b (λx. b)

1,0,1,1 (B implies A): 00000110110 = λa. λb. b a

1,1,0,0 (not A): 000001110001110 = λa. λb. a (λx. a)

1,1,0,1 (A implies B): 0010 = λa. a

1,1,1,0 (nand): 000001100111000110 = λa. λb. b (a (λx. b))

1,1,1,1 (true): 00000010 = λa. λb. λx. x

Binary lambda calculus, 292 bits = 36.5 bytes

Uses the Church booleans true = λx. λy. x, false = λx. λy. y.

0,0,0,0 (false): 0000000010 = λa. λb. λx. λy. y

0,0,0,1 (and): 000001011011010 = λa. λb. b a b

0,0,1,0 (A and not B): 0000010110000010110 = λa. λb. b (λx. λy. y) a

0,0,1,1 (A): 0000110 = λa. λb. a

0,1,0,0 (not A and B): 000110000010 = λa. a (λx. λy. y)

0,1,0,1 (B): 000010 = λa. λb. b

0,1,1,0 (xor): 0000010111001011000001011010 = λa. λb. a (b (λx. λy. y) a) b

0,1,1,1 (or): 00011010 = λa. a a

1,0,0,0 (nor): 00000000010111101001011111010110 = λa. λb. b (λx. λy. y) (a b (λx. λy. x))

1,0,0,1 (xnor): 00000101110100101101100000110 = λa. λb. a b (b a (λx. λy. x))

1,0,1,0 (not B): 000000000101111010110 = λa. λb. λx. λy. b y x

1,0,1,1 (B implies A): 00000101101100000110 = λa. λb. b a (λx. λy. x)

1,1,0,0 (not A): 0000000001011111010110 = λa. λb. λx. λy. a y x

1,1,0,1 (A implies B): 00000101110100000110 = λa. λb. a b (λx. λy. x)

1,1,1,0 (nand): 000000000101111001011111010110110 = λa. λb. b (a (λx. λy. y) b) (λx. λy. x)

1,1,1,1 (true): 00000000110 = λa. λb. λx. λy. x


问:
Can Mario go to the end of this map
Create a program that determines, given an input of the path, whether Mario can reach the end, denoted by E, from the start, denoted by S.

A path will look something like this:

```<code>S = E
=====
</code>```

In a path, the various symbols and what they represent are:

=: wall/floor/ceiling. Mario cannot walk through wall , and cannot fall past a floor, or jump past a ceiling (he would hit his head)

  (space): air. Mario can walk through this, and jump through it, and fall through it

S: air, except showing where Mario starts. This will always appear in the left-most column of the input, at ground level.

E: air, except showing where Mario wants to get. This will always appear in the right-most column of the input, at ground level.

The input will have spaces at every place where Mario could walk.

Mario can only move forward; in this example Mario cannot get to the goal

```<code>S
===

 ===
   E
====
</code>```

nor can he in this one

```<code>    E
   ==
==
  #==
==
   ==
==
S  ==
======
</code>```

However, he can reach the space denoted by # (which will not appear in input), because he can jump up to four cells high; Mario is superhuman. As another example of his superhumanity:

```<code>S
=
=
=
=
=
= #
= =
=
=
=
=     E
=======
</code>```

Mario can get to the E by falling the great distance, surviving, and walking calmly to E. Note that he cannot reach the #, because Mario falls straight down.

Mario can jump really high, but not very far forward by comparison.

```<code>S   E
== ==
 = =
</code>```

Mario may attempt to jump the gap, but he will fail, and fall straight in. he cannot reach the end.

Mario can reach the goal in all of these examples:

```<code> E
 =
 =
 =
S=
==
</code>```

```<code> =
 =   E
S=   =
==   =
 =   =
 =====
</code>```

```<code>S
=

=  E
====
</code>```

This is code golf, so fewest bytes wins!

答:
Grime, 46 bytes (non-competing)

```<code>A=\E|[S ]&<\ {,-4}/0/./* \ /*/A/\=/./*>
n`\S&A
</code>```

I have updated Grime several times after this challenge was posted, so this answer is not eligible for winning.
Some of the changes are so new that I haven't been able to get them into TIO, but once I do, you can try out the program.
In any case, my repository contains a version that handles this code correctly.

The program prints 1 if Mario can reach the goal, and 0 if not.
The input has to contain spaces in all places Mario needs to visit.
For general inputs, I have the following 57-byte solution:

```<code>A=\E|[ \bS]&<[ \b]{,-4}/0/[]/* [ \b]/*/A/\=/[]/*>
nb`\S&A
</code>```

Explanation

The high-level explanation is that the nonterminal A, defined on the first line, matches a 1×1 sub-rectangle of the input where Mario can reach the goal.
A is defined as either the literal E (Mario is already at the goal), or as a 1×1 pattern that's on the left column of some 2×n rectangle containing a valid Mario jump to another match of A on the right column.
The second line counts the number of matches of A that also contain the start character S, and prints that.

Here's a break-down of the code:

```<code>A=\E|[ S]&<\ {,-4}/0/./* \ /*/A/\=/./*>
A=                                       Define A as
  \E|                                    a literal E, or
     [ S]&                               a literal space or S
          <                           >  contained in a larger rectangle
                                         that this bracketed expression matches.
           \ {,-4}/0/./*                 Left half of the bracketed expression:
           \ {,-4}                        Rectangle of spaces with height 0-4,
                  /                       below that
                   0                      the 1x1 rectangle we're currently matching,
                    /.                    below that any 1x1 rectangles
                      /*                  stacked any number of times vertically.
                         \ /*/A/\=/./*   Right half of the bracketed expression:
                         \ /*             Spaces stacked vertically,
                             /A           below that another match of A,
                               /\=        below that a literal =,
                                  /./*    below that 1x1 rectangles stacked vertically.
</code>```

The idea is that the \ {,-4} part on the left matches the space through which Mario jumps upward, and the \ /* part on the right matches the space trough which he then falls down.
We require that he lands on a match of A (since we want to reach the goal) that's on top of a =.
The vertical stacks below both columns will simply guarantee that the columns have the same height, so we can concatenate them (which is what the single space in the middle does).
Here's an ASCII art diagram of an example jump, broken into the aforementioned rectangles, and with spaces replaced by *s:

```<code>Left column:     Right column:   +---+---+
a = \ {,-4}      d = \ /*        | * | * |
b = 0            e = A           +   +   + d
c = ./*          f = \=          | * | * |
                 g = ./*       a +   +---+
                                 | * | * | e
                                 +   +---+
                                 | * | = | f
                                 +---+---+
                               b | S | = |
                                 +---+   | g
                               c | = | * |
                                 +---+---+
</code>```

On the second line, the option n triggers counting of all matches, instead of finding the first match.
In the general solution, the spaces can also be special out-of-input characters, and option b causes the input to be padded with out-of-input characters.

I hope all of this makes sense!

Title: Can Mario go to the end of this map

Body:
Grime, 46 bytes (non-competing)

A=\E|[S ]&<\ {,-4}/0/./* \ /*/A/\=/./*>
n`\S&A

I have updated Grime several times after this challenge was posted, so this answer is not eligible for winning.
Some of the changes are so new that I haven't been able to get them into TIO, but once I do, you can try out the program.
In any case, my repository contains a version that handles this code correctly.

The program prints 1 if Mario can reach the goal, and 0 if not.
The input has to contain spaces in all places Mario needs to visit.
For general inputs, I have the following 57-byte solution:

A=\E|[ \bS]&<[ \b]{,-4}/0/[]/* [ \b]/*/A/\=/[]/*>
nb`\S&A

Explanation

The high-level explanation is that the nonterminal A, defined on the first line, matches a 1×1 sub-rectangle of the input where Mario can reach the goal.
A is defined as either the literal E (Mario is already at the goal), or as a 1×1 pattern that's on the left column of some 2×n rectangle containing a valid Mario jump to another match of A on the right column.
The second line counts the number of matches of A that also contain the start character S, and prints that.

Here's a break-down of the code:

A=\E|[ S]&<\ {,-4}/0/./* \ /*/A/\=/./*>
A=                                       Define A as
  \E|                                    a literal E, or
     [ S]&                               a literal space or S
          <                           >  contained in a larger rectangle
                                         that this bracketed expression matches.
           \ {,-4}/0/./*                 Left half of the bracketed expression:
           \ {,-4}                        Rectangle of spaces with height 0-4,
                  /                       below that
                   0                      the 1x1 rectangle we're currently matching,
                    /.                    below that any 1x1 rectangles
                      /*                  stacked any number of times vertically.
                         \ /*/A/\=/./*   Right half of the bracketed expression:
                         \ /*             Spaces stacked vertically,
                             /A           below that another match of A,
                               /\=        below that a literal =,
                                  /./*    below that 1x1 rectangles stacked vertically.

The idea is that the \ {,-4} part on the left matches the space through which Mario jumps upward, and the \ /* part on the right matches the space trough which he then falls down.
We require that he lands on a match of A (since we want to reach the goal) that's on top of a =.
The vertical stacks below both columns will simply guarantee that the columns have the same height, so we can concatenate them (which is what the single space in the middle does).
Here's an ASCII art diagram of an example jump, broken into the aforementioned rectangles, and with spaces replaced by *s:

Left column:     Right column:   +---+---+
a = \ {,-4}      d = \ /*        | * | * |
b = 0            e = A           +   +   + d
c = ./*          f = \=          | * | * |
                 g = ./*       a +   +---+
                                 | * | * | e
                                 +   +---+
                                 | * | = | f
                                 +---+---+
                               b | S | = |
                                 +---+   | g
                               c | = | * |
                                 +---+---+

On the second line, the option n triggers counting of all matches, instead of finding the first match.
In the general solution, the spaces can also be special out-of-input characters, and option b causes the input to be padded with out-of-input characters.

I hope all of this makes sense!


答:
PHP - 83 78

```<code><?for($a=$argv[1];$i<strlen($a);$r[$a[$i++]]++)foreach($ras$k=>$c)if($c>1)echo$k
</code>```

Improved version:

```<code><?for($s=$argv[1];$x<strlen($s);$c=$s[$x++]) echo substr_count($s,$c)>1?$c:'';
</code>```

Of course this needs notices to be turned off

Edit: Improvement inspired by @hengky mulyono

I am so bad at codegolf :)

Title: Removing unique elements from string

Body:
I came upon this question, because it seems to be very common use-case to find unique characters in string. But what if we want to get rid of them?

Input contains only lower case alphabets. Only letters from a to z are used. Input length may be from 1 to 1000 characters.

Example:

input: helloworld

output: llool

Objective: Shortest code wins

Language: Any of the top 20 of TIOBE languages

Body:
PHP - 83 78

<?for($a=$argv[1];$i<strlen($a);$r[$a[$i++]]++)foreach($ras$k=>$c)if($c>1)echo$k

Improved version:

<?for($s=$argv[1];$x<strlen($s);$c=$s[$x++]) echo substr_count($s,$c)>1?$c:'';

Of course this needs notices to be turned off

Edit: Improvement inspired by @hengky mulyono

I am so bad at codegolf :)


问:
Big or Little Endian
Write a program or function that outputs an L if run on a little endian architecture or a B if run on a big endian architecture. Lower case output l or b is also acceptable.

There is no input.

Scoring is code golf, so the code with the fewest bytes wins.

Edit: As per the comments below, I am clarifying that the entry must be able to run on either architecture.

I believe that there is only one answer that this affects, and that answer has clearly indicated that this is the case.

答:
R, <s>28</s> 23 bytes

```<code>substr(.Platform$endian,1,1)
</code>```

.Platform$endian returns big if run on big endian and little if on little. Here, using substr, it returns the first letter of the output, so either b or l.

As endian is the only object starting with an e contained in object .Platform we can reduce it thanks to partial matching to the following 23 bytes code:

```<code>substr(.Platform$e,1,1)
</code>```

Title: Big or Little Endian

Body:
R, <s>28</s> 23 bytes

substr(.Platform$endian,1,1)

.Platform$endian returns big if run on big endian and little if on little. Here, using substr, it returns the first letter of the output, so either b or l.

As endian is the only object starting with an e contained in object .Platform we can reduce it thanks to partial matching to the following 23 bytes code:

substr(.Platform$e,1,1)


答:
ProgFk, <s>18.5</s> 17.5 bytes

As ProgFk's instructions are specified in nibbles, the below code is given in hexadecimal, one logic gate per line and with spaces in between the bytes.

```<code>3
E1
DE 2D
<empty>
DE 1
1
E3
E2
E2 D
E3 D
1D
DE 2
D
DE 1D
E1 D
4
</code>```

Explanation

ProgFk is a tape-based esolang (similar to Brainfuck) where each cell is a bit and instructions are given as nibbles (4 bytes). Instructions operate on the cell pointed to by the instruction pointer. Input is given in the first and second cells (with A and B being the first and second cells respectively), and the instruction pointer starts at the first cell. Output is stored in the first cell.

Each instruction used is explained below.

```<code>1   Increment the instruction pointer.
2   Decrement the instruction pointer.
3   Set the current bit to 0.
4   Set the current bit to 1.
D   Perform a NOT on the current bit.
E   The next instruction is an extended instruction.

Extended instructions:
1   Set the current bit to the current bit AND the next bit.
2   Set the current bit to the current bit OR the next bit.
3   Set the current bit to the current bit XOR the next bit.
6   Swap the current bit and the next bit.
</code>```

Saved a byte thanks to @LeakyNun!

Body:
ProgFk, <s>18.5</s> 17.5 bytes

As ProgFk's instructions are specified in nibbles, the below code is given in hexadecimal, one logic gate per line and with spaces in between the bytes.

3
E1
DE 2D
<empty>
DE 1
1
E3
E2
E2 D
E3 D
1D
DE 2
D
DE 1D
E1 D
4

Explanation

ProgFk is a tape-based esolang (similar to Brainfuck) where each cell is a bit and instructions are given as nibbles (4 bytes). Instructions operate on the cell pointed to by the instruction pointer. Input is given in the first and second cells (with A and B being the first and second cells respectively), and the instruction pointer starts at the first cell. Output is stored in the first cell.

Each instruction used is explained below.

1   Increment the instruction pointer.
2   Decrement the instruction pointer.
3   Set the current bit to 0.
4   Set the current bit to 1.
D   Perform a NOT on the current bit.
E   The next instruction is an extended instruction.

Extended instructions:
1   Set the current bit to the current bit AND the next bit.
2   Set the current bit to the current bit OR the next bit.
3   Set the current bit to the current bit XOR the next bit.
6   Swap the current bit and the next bit.

Saved a byte thanks to @LeakyNun!


问:
Verify a Tower of Hanoi solution
If you don't know what the Tower of Hanoi is, I'll explain it briefly: There are three rods and some discs each of which has a different size. In the beginning all discs are on the first tower, in sorted order: The biggest one is at the bottom, the smallest at the top. The goal is to bring all the discs over to the third rod. Sounds easy? Here's the catch: You can't place a disc on top of a disc that is smaller than the other disc; you can only hold one disc in your hand at a time to move them to another rod and you can only place the disc on rods, not on the table, you sneaky bastard.

ascii example solution:

```<code>  A      B      C
  |      |      |
 _|_     |      |
__|__    |      |

  A      B      C
  |      |      |
  |      |      |
__|__   _|_     |

  A      B      C
  |      |      |
  |      |      |
  |     _|_   __|__

  A      B      C
  |      |      |
  |      |     _|_
  |      |    __|__
</code>```

Challenge

There are three rods called A,B and C. (You can also call them 1,2 and 3 respectivly if that helps) In the beginning all n discs are on rod A(1).

Your challenge is to verify a solution for the tower of hanoi. You'll need to make sure that:

In the end all n discs are on rod C(3).

For any given disc at any given state there is no smaller disc below it.

No obvious errors like trying to take discs from an empty rod or moving discs to nonexistant rods.

(the solution does not have to be optimal.)

Input

Your program will receive two inputs:

The number of discs n (an integer)

The moves which are taken, which will consist of a set of tuples of: (tower to take the currently uppermost disc from),(tower to take this disc to) where each tuple refers to a move. You can choose how they are represented. For example something like the following ways of representing the solution for n=2 which I've drawn in ascii above. (I'll use the first one in the test cases, because it's easy on the eyes):

"A->B ; A->C ; B->C"

[("A","B"),("A","C"),("B","C")]

[(1,2),(1,3),(2,3)]

"ABACBC"

[1,2,1,3,2,3]

Output

Truthy, if the conditions that can be found under "challenge" hold.

Falsy, if they don't.

Test cases:

True:

```<code>n=1, "A->C"

n=1, "A->B ; B->C"

n=2, "A->B ; A->C ; B->C"

n=2, "A->C ; C->B ; A->C ; B->C"

n=2, "A->C ; A->B ; C->B ; B->A ; B->C ; A->C"

n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"

n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C ; B->C"
</code>```

False:

3rd one suggested by @MartinEnder, 7th by @Joffan

```<code>n=1, "A->B"

n=1, "C->A"

n=2, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"

n=2, "A->B ; A->C ; C->B"

n=2, "A->C ; A->B ; C->B ; B->A"

n=2, "A->C ; A->C"

n=3, "A->B ; A->D; A->C ; D->C ; A->C"

n=3, "A->C ; A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"

n=3, "A->C ; A->B ; C->B ; A->B ; B->C ; B->A ; B->C ; A->C"

n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; C->B"

n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C"

n=4, "A->B ; A->B ; A->B ; A->C ; B->C ; B->C ; B->C"
</code>```

This is code-golf, shortest solution wins. Standard rules and loopholes apply. No batteries included.

答:
JavaScript (ES6), 108

n=>s=>!s.some(([x,y])=>s[y][s[y].push(v=s[x].pop())-2]<v|!v,s=[[...Array(s=n)].map(_=>s--),[],[]])&s[2][n-1]
```
<p><strong>Input format:</strong> function with 2 arguments</p>
<ul>
<li>arg 1, numeric, number of rings</li>
<li>arg 2, array of strings, each string 2 characters '0','1','2'</li>
</ul>
<p><strong>Output:</strong> return 1 if ok, 0 if invalid, exception if nonexisting rod</p>
<p><strong>Less golfed</strong> and explained</p>
<pre class="lang-js prettyprint-override"><code>n=>a=>(
  // rods status, rod 0 full with an array n..1, rod 1 & 2 empty arrays
  s = [ [...Array(t=n)].map(_=>t--), [], [] ],
  // for each step in solution, evaluate function and stop if returns true
  err = a.some( ([x,y]) => {
    v = s[x].pop(); // pull disc from source rod
    // exception is s[x] is not defined
    if (!v) return 1; // error source rod is empty
    l = s[y].push(v); // push disc on dest rod, get number of discs in l
    // exception is s[y] is not defined
    if(s[y][l-2] < v) return 1; // error if undelying disc is smaller
  }),
  err ? 0 // return 0 if invalid move
  : s[2][n-1]; // il all moves valid, ok if the rod 2 has all the discs
)
</code>```

Test
Note: the first row of the Test function is needed to convert the input format given in the question to the input expected by my function

F=
n=>s=>!s.some(([x,y])=>s[y][s[y].push(v=s[x].pop())-2]<v|!v,s=[[...Array(s=n)].map(_=>s--),[],[]])&s[2][n-1]

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

Test=s=>s.split`\n`.map(r=>[+(r=r.match(/\d+|.->./g)).shift(),r.map(x=>(parseInt(x[0],36)-10)+''+(parseInt(x[3],36)-10))])
.forEach(([n,s],i)=>{
  var r
  try {
    r = F(+n)(s);
  }
  catch (e) {
    r = 'Error invalid rod';
  }
  Out(++i+' n:'+n+' '+s+' -> '+r)
})

Out('OK')
Test(`n=1, "A->C"
n=1, "A->B ; B->C"
n=2, "A->B ; A->C ; B->C"
n=2, "A->C ; C->B ; A->C ; B->C"
n=2, "A->C ; A->B ; C->B ; B->A ; B->C ; A->C"
n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"
n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C ; B->C"`)

Out('\nFail')
Test( `n=1, "A->B"
n=1, "C->A"
n=2, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"
n=2, "A->B ; A->C ; C->B"
n=2, "A->C ; A->B ; C->B ; B->A"
n=2, "A->C ; A->C"
n=3, "A->B ; A->D; A->C ; D->C ; A->C"
n=3, "A->C ; A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"
n=3, "A->C ; A->B ; C->B ; A->B ; B->C ; B->A ; B->C ; A->C"
n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; C->B"
n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C"
n=4, "A->B ; A->B ; A->B ; A->C ; B->C ; B->C ; B->C"`)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id=O>``````

Title: Verify a Tower of Hanoi solution

Body:
JavaScript (ES6), 108

n=>s=>!s.some(([x,y])=>s[y][s[y].push(v=s[x].pop())-2]<v|!v,s=[[...Array(s=n)].map(_=>s--),[],[]])&s[2][n-1]

Input format: function with 2 arguments

arg 1, numeric, number of rings

arg 2, array of strings, each string 2 characters '0','1','2'

Output: return 1 if ok, 0 if invalid, exception if nonexisting rod

Less golfed and explained

n=>a=>(
  // rods status, rod 0 full with an array n..1, rod 1 & 2 empty arrays
  s = [ [...Array(t=n)].map(_=>t--), [], [] ],
  // for each step in solution, evaluate function and stop if returns true
  err = a.some( ([x,y]) => {
    v = s[x].pop(); // pull disc from source rod
    // exception is s[x] is not defined
    if (!v) return 1; // error source rod is empty
    l = s[y].push(v); // push disc on dest rod, get number of discs in l
    // exception is s[y] is not defined
    if(s[y][l-2] < v) return 1; // error if undelying disc is smaller
  }),
  err ? 0 // return 0 if invalid move
  : s[2][n-1]; // il all moves valid, ok if the rod 2 has all the discs
)

Test
Note: the first row of the Test function is needed to convert the input format given in the question to the input expected by my function

F=
n=>s=>!s.some(([x,y])=>s[y][s[y].push(v=s[x].pop())-2]<v|!v,s=[[...Array(s=n)].map(_=>s--),[],[]])&s[2][n-1]

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

Test=s=>s.split`\n`.map(r=>[+(r=r.match(/\d+|.->./g)).shift(),r.map(x=>(parseInt(x[0],36)-10)+''+(parseInt(x[3],36)-10))])
.forEach(([n,s],i)=>{
  var r
  try {
    r = F(+n)(s);
  }
  catch (e) {
    r = 'Error invalid rod';
  }
  Out(++i+' n:'+n+' '+s+' -> '+r)
})

Out('OK')
Test(`n=1, "A->C"
n=1, "A->B ; B->C"
n=2, "A->B ; A->C ; B->C"
n=2, "A->C ; C->B ; A->C ; B->C"
n=2, "A->C ; A->B ; C->B ; B->A ; B->C ; A->C"
n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"
n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C ; B->C"`)

Out('\nFail')
Test( `n=1, "A->B"
n=1, "C->A"
n=2, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"
n=2, "A->B ; A->C ; C->B"
n=2, "A->C ; A->B ; C->B ; B->A"
n=2, "A->C ; A->C"
n=3, "A->B ; A->D; A->C ; D->C ; A->C"
n=3, "A->C ; A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"
n=3, "A->C ; A->B ; C->B ; A->B ; B->C ; B->A ; B->C ; A->C"
n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; C->B"
n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C"
n=4, "A->B ; A->B ; A->B ; A->C ; B->C ; B->C ; B->C"`)

<pre id=O></pre>


问:
Coin Change Problem Enumeration Using N Coins And Each Denomination
The coin change problem is very well documented. Given an infinite supply of coins of denominations x_1 to x_m you need to find the number of combinations which add up to y. For example, given x = {1,2,3} and y = 4 we have four combinations:

{1,1,1,1}

{1,1,2}

{1,3}

{2,2}

Introduction

There are several variations of the coin change problem. In this variation  we have two additional restrictions:

Every denomination must be used at least once.

Exactly a fixed number of coins must be used in total.

For example, given x = {1,2,3}, y = 36 and n = 15 where n is the total number of coins that must be used, we get four combinations:

{1,2,2,2,2,2,2,2,3,3,3,3,3,3,3} (1 ones, 7 twos, 7 threes)

{1,1,2,2,2,2,2,3,3,3,3,3,3,3,3} (2 ones, 5 twos, 8 threes)

{1,1,1,2,2,2,3,3,3,3,3,3,3,3,3} (3 ones, 3 twos, 9 threes)

{1,1,1,1,2,3,3,3,3,3,3,3,3,3,3} (4 ones, 1 twos, 10 threes)

Challenge

The challenge is to write a function enumerate in the language of your choice which enumerates all the combinations as described above given:

The list of denominations. For example {1,5,10,25}. You may use either lists or arrays.

A non-negative integer y that denotes the sum of every combination.

A non-negative integer n that denotes the total number of coins.

The order of the arguments doesn't matter. Pointfree functions are allowed.

The output of the enumerate function must be a list of combinations. Each combination must be unique and it must be a list of n integers which add up to y. Every denomination must appear at least once in each combination and no combination must be missing. The ordering of the integers and the combinations doesn't matter. You may use either lists or arrays for the output.

Keep in mind the following edge cases:

If both y and n are zero and the list of denominations is empty then the output is a list of one combination, the empty combination (i.e. {{}}).

Otherwise, if y is zero, n is zero or the list of denominations is empty then the output is a list of zero combinations (i.e. {}).

More generally, if y is less than the sum of the denominations or n is less than the number of denominations then the output is a list of zero combinations.

Scoring will be based on the size of the entire program in bytes. Note that this includes the enumerate function, helper functions, import statements, etc. It does not include test cases.

答:
MATL, 22 bytes

```<code>Z^!S!Xu!tsi=Z)"1G@m?@!
</code>```

Input order is: array of denominations, number of coins taken (n), desired sum (y).

Each combination is displayed on a different line. Empty output is displayed as an empty string (so nothing).

Try it online!

The code runs out of memory in the online compiler for the example in the challenge, but works offline with a standard, reasonably modern computer:

```<code>>> matl
 > Z^!S!Xu!tsi=Z)"1G@m?@!
 >
> [1 2 3]
> 15
> 36
1 1 1 1 2 3 3 3 3 3 3 3 3 3 3
1 1 1 2 2 2 3 3 3 3 3 3 3 3 3
1 1 2 2 2 2 2 3 3 3 3 3 3 3 3
1 2 2 2 2 2 2 2 3 3 3 3 3 3 3
</code>```

Explanation

```<code>Z^      % Implicitly input array of denomminations and number of coins n. Compute
        % Cartesian power. This gives 2D array with each "combination"
        % on a different row
!S!     % Sort each row
Xu      % Deduplicate rows
!       % Transpose: rows become columns. Call this array A
ts      % Push a copy, compute sum of each column
i       % Input y (desired sum)
=       % Logical array that contains true if the "combination" has the desired sum
Z)      % Keep only those columns in array A
"       % For each column
  1G    %   Push array of denominations again
  @     %   Push current column
  m     %   Is each denomination present in the column?
  ?     %   If so
    @!  %     Push current column again. Transpose into a row
        %   End if
        % End for
        % Implicitly display stack contents
</code>```

Body:
MATL, 22 bytes

Z^!S!Xu!tsi=Z)"1G@m?@!

Input order is: array of denominations, number of coins taken (n), desired sum (y).

Each combination is displayed on a different line. Empty output is displayed as an empty string (so nothing).

Try it online!

The code runs out of memory in the online compiler for the example in the challenge, but works offline with a standard, reasonably modern computer:

>> matl
 > Z^!S!Xu!tsi=Z)"1G@m?@!
 >
> [1 2 3]
> 15
> 36
1 1 1 1 2 3 3 3 3 3 3 3 3 3 3
1 1 1 2 2 2 3 3 3 3 3 3 3 3 3
1 1 2 2 2 2 2 3 3 3 3 3 3 3 3
1 2 2 2 2 2 2 2 3 3 3 3 3 3 3

Explanation

Z^      % Implicitly input array of denomminations and number of coins n. Compute
        % Cartesian power. This gives 2D array with each "combination"
        % on a different row
!S!     % Sort each row
Xu      % Deduplicate rows
!       % Transpose: rows become columns. Call this array A
ts      % Push a copy, compute sum of each column
i       % Input y (desired sum)
=       % Logical array that contains true if the "combination" has the desired sum
Z)      % Keep only those columns in array A
"       % For each column
  1G    %   Push array of denominations again
  @     %   Push current column
  m     %   Is each denomination present in the column?
  ?     %   If so
    @!  %     Push current column again. Transpose into a row
        %   End if
        % End for
        % Implicitly display stack contents


问:
Guard your can with your life!

Lets Play Kick The Can!

Although Moogie is the current winner, if anyone can take his crown they are encouraged to do so

Kick the can is a children's game. Involving one defender, and multiple attackers. Today it is no longer such a game! Your job is to write a bot that plays it, to win, king-of-the-hill style!

https://en.wikipedia.org/wiki/Kick_the_can

There are some key differences in this game. The first key difference is that the game is multiplayer (5v5). The second key difference is that both sets of bots can kill and eliminate enemy players with both mines and thrown bombs! Bots can not see any mines (regardless of distance) or players at greater than five blocks away!

The map is a maze as follows.

This maze is procedurally generated by first creating a maze using a depth first recursive backtracking algorithm. And then placing the shown holes in (as well as make the maze more "imperfect". The maze is 65x65 blocks wide, and zero indexed. Thus the blue flag (can) is at 1,1 and the red flag (can) is at 63,63. Blue team spawns at 2,2 and 3,3 4,4 etc. red team spawns at 62,62 and 61,61, 60,60 etc. The blocks in cyan are bots on the blue team, and the blocks in magenta are red bots. The game is always five versus five. Each bot on the team will use your code (but may store other instance variables (or create local files) to keep track of state and differentiate roles.

Gameplay

Mines can be placed as you can see in gray. And bombs can be thrown a maximum distance of up to four blocks. These travel for up to four blocks through walls and other players killing only the enemies which stand in your way. After each step they have a 40% chance of falling away. So they have 100% chance of 1 range 60% at 2 range 36% at 3 range and 21.6% at three range Placing a mine or throwing a bomb takes one team ammo. This starts at 0 and can be increased by collecting the orange boxes. Note that four (4) of these ammo caches will be conveniently centered. The Bots are lined up in an array of two red and two blue. I.E RRRRRBBBBB. Gaurding the flag is permitted, but beware that being near the flag(i.e less than five blocks) results in slowness, and only allows movent. every three turns. The Arena picks a random starter for each turn. I.E The order can be RBBBBBRRRRR BBBBBRRRRR BBBRRRRRBB etc..

Objective

Program your five bots (each has the same class file) to successfully navigate the maze and touch the opposing can while being careful not to accidentally knock over ones own can, or step on a mine.

Programming

The arena and bot entries are currently in Java however a stdin/out wrapper exists for other languages.

The arena code will be made available but here is the relevant details.

Bot Class

```<code>public class YourUniqueBotName extends Bot{
public YourUniqueBotName(int x , int y, int team){
super(x,y,team);
//optional code
}
public Move move(){//todo implement this method
//it should output  a Move();
//A move has two paramaters
//direction is from 0 - 3 as such
//         3
//       2-I-0
//         1
// a direction of 4 or higher means a no-op (i.e stay still)
//And a MoveType. This movetype can be
//MoveType.Throw
//MoveType.Mine
//MoveType.Defuse defuse any mine present in the direction given
//MoveType.Move
}
}
</code>```

Key Methods Available

Note that using any techniques to modify or access data you should generally not have access to is not permitted and will result in disqualification.

```<code>Arena.getAmmo()[team];//returns the shared ammo cache of your team

Arena.getMap();//returns an integer[] representing the map. Be careful since all enemies more than 5 blocks away (straight line distance) and all mines are replaced with constant for spaces
//constants for each block type are provided such as Bot.space Bot.wall Bot.mine Bot.redTeam Bot.blueTeam Bot.redFlag Bot.blueFlag

Arena.getAliveBots();//returns the number of bots left

getX();//returns a zero indexed x coordinate you may directly look at (but not change X)

getY();//returns a zero indexed y coordinate (y would work to, but do not change y's value)

//Although some state variables are public please do not cheat by accessing modifying these
</code>```

StdIn/Out wrapper Interface Specification

The interface consists of two modes: initialisation and running.

During initialisation mode, a single INIT frame is sent via stdout. This frame's specification is as follows:

```<code>INIT
{Team Membership Id}
{Game Map}
TINI
</code>```

Where:
{Team Membership Id} is an single character: R or B. B meaning blue team, R meaning red team.

{Game Map} is a series of rows of ascii characters representing one row of the map. The following ascii characters are valid:
    F = blue flag
    G = red flag
    O = open space
    W = wall

The game will then proceed to send game frames over stdout to each bot as so:

```<code>FRAME
{Ammo}
{Alive Bot Count}
{Bot X},{Bot Y}
{Local Map}
EMARF
</code>```

Where:

{Ammo} is a string of digits, value will be 0 or greater
{Alive Bot Count} is a string of digits, value will be 0 or greater
{Box X} is a string of digits representing the X co-ordinate of the bot on the game map. Value will be 0 <= X < Map Width.
{Box Y} is a string of digits representing the Y co-ordinate of the bot on the game map. Value will be 0 <= Y < Map Height.
{Local Map} is a series of rows of ascii characters representing the whole map surrounding the bot. The following ascii characters are valid:
    F = blue flag
    G = red flag
    O = open space
    W = wall
    R = red team bot
    B = blue team bot
    M = mine
    A = ammo

The Controller expects that your bot will then output (to stdout) a single line response in the format:

```<code>{Action},{Direction}
</code>```

Where:

{Action} is one of:
    Move
    Defuse
    Mine
    Throw

{Direction} is a single digit between 0 and 4 inclusive. (see direction information earlier)

NOTE: all strings will be delimited by \n End of Line character.

This will be an elimination tournament. My sample bots will participate as fillers, but I will not award myself the win. In the event of a victory by one of my bots, the title goes to the second place member, and will continue until there is a bot which is not one of mine. Each match consists of 11 rounds of kick the can. If neither team has won a single match by then they both are eliminated. If there is a tie of non-zero score one tie breaker match will be played. If a tie remains both are eliminated. Later rounds may consist of more matches. The seeding of the tournament will be based on the number of upvotes as of 7/31/16 (date subject to change).

Each match lasts 4096 turns. A victory grants one point. A tie or loss grants zero points. Good luck!

Feel free to look at the code or critique it at this GitHub Repo.

https://github.com/rjhunjhunwala/BotCTF/blob/master/src/botctf/Arena.java

Note that I do not have interpreters for too many languages on my computer, and I may need volunteers to run the simulation on their computer. Or I can download the language interpreter. Please ensure that your bots.

Respond in a reasonable amount of time (say 250 ms)

Will not damage my host machine

答:
NavPointBot, Java 8

Bot is white/blue

This bot nominates a leader from friendly bots each frame that will then assign nav points for each bot to navigate to.

Initally, all bots are on ammo depot finding duty, then two bots are assigned as guards with the remainder looking for ammo and then attacking the enemy flag.

I have found that the game is very dependant on the starting location of depots. As such i cannot really say that this bot is better than any others.

Run with java NavPointBot

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

public final class NavPointBot implements Serializable
{
    private static final int[][] offsets = new int[][]{{-1,0},{0,-1},{1,0},{0,1}};
    private static final List<int[]> navPointsBlue = Arrays.asList(new int[][]{{1,2},{2,1}});
    private static final List<int[]> navPointsRed = Arrays.asList(new int[][]{{63,62},{62,63}});
    transient private static int mapWidth=0;
    transient private static int mapHeight=0;
    transient private char[][] map;
    transient private char team;
    transient private int ammo;
    transient private int botsAlive;
    transient private int enemyFlagX;
    transient private int enemyFlagY;
    private int frameCount;
    private int botX;
    private int botY;
    private String id;
    private int navPointX;
    private int navPointY;

    transient static Object synchObject = new Object(); // used for file read/write synchronisation if multiple instances are run in the same VM

    final static class Data implements Serializable
    {
        int frameCount;
        boolean[][] diffusedMap = new boolean[mapWidth][mapHeight];
        Map<String,NavPointBot> teamMembers = new HashMap<>();
    }

    interface DistanceWeigher
    {
        double applyWeight(NavPointBot p1Bot, PathSegment p1);
    }

    static class PathSegment
    {
        public PathSegment(int tileX, int tileY, int fscore, int gscore, PathSegment parent, int direction, int targetX, int targetY)
        {
            super();
            this.tileX = tileX;
            this.tileY = tileY;
            this.fscore = fscore;
            this.gscore = gscore;
            this.parent = parent;
            this.direction = direction;
            this.targetX = targetX;
            this.targetY = targetY;
        }
        public PathSegment(PathSegment parent)
        {
            this.parent = parent;
            this.targetX = parent.targetX;
            this.targetY = parent.targetY;
        }
        int tileX;
        int tileY;
        int fscore;
        int gscore;
        int direction;
        PathSegment parent;
        int targetX;
        int targetY;
    }

    public static void main(String[] args) throws Exception
    {
        new NavPointBot(UUID.randomUUID().toString());
    }

    private NavPointBot(String id) throws Exception
    {
        this.id = id;
        System.err.println("NavPointBot ("+id+") STARTED");

        Data data;
        while(true)
        {
            String line=readLine(System.in);

            // decode initial frame
            if ("INIT".equals(line))
            {
                // read team membership
                team = readLine(System.in).charAt(0);

                // get the map
                line = readLine(System.in);

                List<char[]> mapLines = new ArrayList<>();
                while(!"TINI".equals(line))
                {
                    mapLines.add(line.toCharArray());
                    line = readLine(System.in);
                }
                map = mapLines.toArray(new char[][]{});
                mapHeight = map.length;
                mapWidth = map[0].length;

                out:
                for (int y = 0; y<mapHeight;y++)
                {
                    for (int x=0; x<mapWidth;x++)
                    {
                        if (map[y][x]==(team=='B'?'G':'F'))
                        {
                            enemyFlagX = x;
                            enemyFlagY = y;
                            break out;
                        }
                    }
                }
                data = readSharedData();
                data.diffusedMap=new boolean[mapWidth][mapHeight];
                writeSharedData(data);

            }
            else
            {
                System.err.println("Unknown command received: "+line);
                return;
            }

            line = readLine(System.in);
            while (true)
            {
                // decode frame
                if ("FRAME".equals(line))
                {
                    frameCount = Integer.parseInt(readLine(System.in));
                    ammo = Integer.parseInt(readLine(System.in));
                    botsAlive = Integer.parseInt(readLine(System.in));
                    line = readLine(System.in);
                    String[] splits = line.split(",");
                    botX = Integer.parseInt(splits[0]);
                    botY = Integer.parseInt(splits[1]);

                    // get the map
                    line = readLine(System.in);

                    int row=0;
                    while(!"EMARF".equals(line))
                    {
                        map[row++] = line.toCharArray();
                        line = readLine(System.in);
                    }
                }
                else
                {
                    System.err.println("Unknown command received: "+line);
                    return;
                }

                data = readSharedData();

                // this bot is nomitated to be the leader for this frame
                if (data.frameCount<frameCount || (frameCount==0 && data.frameCount > 3))
                {
                    data.frameCount=frameCount;

                    List<NavPointBot> unassignedBots = new ArrayList<>(data.teamMembers.values());

                    // default nav points to be enemy flag location.
                    unassignedBots.forEach(t->{t.navPointY=enemyFlagY;t.navPointX=enemyFlagX;});

                    // after 700 frames assume dead lock so just storm the flag, otherwise...
                    if (frameCount<700)
                    {
                        // if the after the initial rush then we will assign guard(s) while we have enemies
                        if (frameCount>70 && botsAlive > data.teamMembers.size())
                        {
                            Map<NavPointBot, PathSegment> navPointDistances = assignBotShortestPaths(unassignedBots,team=='B'?navPointsBlue:navPointsRed,true, new DistanceWeigher() {

                                @Override
                                public double applyWeight( NavPointBot owner ,PathSegment target) {
                                    return target.gscore;
                                }
                            });
                            navPointDistances.keySet().forEach(s->{s.navPointX=navPointDistances.get(s).targetX;s.navPointY=navPointDistances.get(s).targetY;});
                        }

                        // the remaining bots will go to ammo depots with a preference to the middle ammo depots
                        List<int[]> ammoDepots = new ArrayList<>();
                        for (int y = 0; y<mapHeight;y++)
                        {
                            for (int x=0; x<mapWidth;x++)
                            {
                                if (map[y][x]=='A')
                                {
                                    ammoDepots.add(new int[]{x,y});
                                }
                            }
                        }

                        System.err.println("ammoDepots: "+ammoDepots.size());
                        if (ammoDepots.size()>0)
                        {
                            Map<NavPointBot, PathSegment> ammoDistances = assignBotShortestPaths(unassignedBots,ammoDepots,true, new DistanceWeigher() {

                                @Override
                                public double applyWeight( NavPointBot owner ,PathSegment target) {
                                    return target.gscore + (Math.abs(target.targetX-mapWidth/2)+Math.abs(target.targetY-mapHeight/2)*10);
                                }
                            });

                            // assign ammo depot nav points to closest bots
                            ammoDistances.keySet().forEach(s->{s.navPointX=ammoDistances.get(s).targetX;s.navPointY=ammoDistances.get(s).targetY;});
                        }
                    }

                    System.err.println("FRAME: "+frameCount+" SET");
                    data.teamMembers.values().forEach(bot->System.err.println(bot.id+" nav point ("+bot.navPointX+","+bot.navPointY+")"));
                    System.err.println();
                }

                // check to see if enemies are in range, if so attack the closest
                List<int[]> enemies = new ArrayList<>();
                for (int y = 0; y<mapHeight;y++)
                {
                    for (int x=0; x<mapWidth;x++)
                    {
                        if (map[y][x]==(team=='B'?'R':'B'))
                        {
                            int attackDir = -1;
                            int distance = -1;
                            if (x==botX && Math.abs(y-botY) < 4) { distance =  Math.abs(y-botY); attackDir = botY-y<0?1:3;}
                            if (y==botY && Math.abs(x-botX) < 4) { distance =  Math.abs(x-botX); attackDir = botX-x<0?0:2;}
                            if (attackDir>-1)
                            {
                                enemies.add(new int[]{x,y,distance,attackDir});
                            }
                        }
                    }
                }

                enemies.sort(new Comparator<int[]>() {

                    @Override
                    public int compare(int[] arg0, int[] arg1) {
                        return arg0[2]-arg1[2];
                    }
                });

                String action;

                // attack enemy if one within range...
                if (enemies.size()>0)
                {
                    action = "Throw,"+enemies.get(0)[3];
                }
                else
                {
                    // set action to move to navpoint
                    PathSegment pathSegment = pathFind(botX,botY,navPointX,navPointY,map,true);
                    action = "Move,"+pathSegment.direction;

                    // clear mines if within 5 spaces of enemy flag

                    if ((team=='B' && botX>=mapWidth-5 && botY>=mapHeight-5 ) ||
                        (team=='R' && botX<5 && botY<5 ))
                    {
                        if (!data.diffusedMap[pathSegment.parent.tileX][pathSegment.parent.tileY])
                        {
                            action = "Defuse,"+pathSegment.direction;
                            data.diffusedMap[pathSegment.parent.tileX][pathSegment.parent.tileY]=true;
                        }
                    }

                }

                writeSharedData(data);
                System.out.println(action);
                line = readLine(System.in);
            }
        }
    }

    /**
     * assigns bots to paths to the given points based on distance to the points with weights adjusted by the given weigher implementation
     */
    private Map<NavPointBot, PathSegment> assignBotShortestPaths(List<NavPointBot> bots, List<int[]> points, boolean exact, DistanceWeigher weigher) {

        Map<Integer,List<PathSegment>> pathMap = new HashMap<>();
        final Map<PathSegment,NavPointBot> pathOwnerMap = new HashMap<>();

        for (NavPointBot bot : bots)
        {
            for(int[] navPoint: points)
            {
                List<PathSegment> navPointPaths = pathMap.get((navPoint[0]<<8)+navPoint[1]);
                if (navPointPaths == null)
                {
                    navPointPaths = new ArrayList<>();
                    pathMap.put((navPoint[0]<<8)+navPoint[1],navPointPaths);
                }
                PathSegment path = pathFind(bot.botX,bot.botY,navPoint[0],navPoint[1],map,exact);
                pathOwnerMap.put(path, bot);
                navPointPaths.add(path);
            }
        }

        // assign bot nav point based on shortest distance
        Map<NavPointBot, PathSegment> results = new HashMap<>();
        for (int[] navPoint: points )
        {
            List<PathSegment> navPointPaths = pathMap.get((navPoint[0]<<8)+navPoint[1]);

            if (navPointPaths !=null)
            {
                Collections.sort(navPointPaths, new Comparator<PathSegment>() {

                    @Override
                    public int compare(PathSegment p1, PathSegment p2) {

                        NavPointBot p1Bot = pathOwnerMap.get(p1);
                        NavPointBot p2Bot = pathOwnerMap.get(p2);
                        double val = weigher.applyWeight(p1Bot, p1) - weigher.applyWeight(p2Bot, p2);
                        if (val == 0)
                        {

                            return p1Bot.id.compareTo(p2Bot.id);
                        }
                        return val<0?-1:1;
                    }
                });

                for (PathSegment shortestPath : navPointPaths)
                {
                    NavPointBot bot = pathOwnerMap.get(shortestPath);

                    if (!results.containsKey(bot) )
                    {
                        results.put(bot,shortestPath);
                        bots.remove(bot);
                        break;
                    }
                }
            }
        }
        return results;
    }

    /**
     * reads in the previous bot's view of teammates aka shared data
     */
    private Data readSharedData() throws Exception
    {
        synchronized(synchObject)
        {
            File dataFile = new File(this.getClass().getName()+"_"+team);

            Data data;
            if (dataFile.exists())
            {
                FileInputStream in = new FileInputStream(dataFile);
                try {
                    java.nio.channels.FileLock lock = in.getChannel().lock(0L, Long.MAX_VALUE, true);
                    try {
                        ObjectInputStream ois = new ObjectInputStream(in);
                        data = (Data) ois.readObject();
                    } catch(Exception e)
                    {
                        System.err.println(id+": CORRUPT shared Data... re-initialising");
                        data = new Data();
                    }
                    finally {
                        lock.release();
                    }
                } finally {
                    in.close();
                }
            }
            else
            {
                System.err.println(id+": No shared shared Data exists... initialising");
                data = new Data();
            }

            //purge any dead teammates...
            for (NavPointBot bot : new ArrayList<>(data.teamMembers.values()))
            {
                if (bot.frameCount < frameCount-3 || bot.frameCount > frameCount+3)
                {
                    data.teamMembers.remove(bot.id);
                }
            }

            // update our local goals to reflect those in the shared data
            NavPointBot dataBot = data.teamMembers.get(id);
            if (dataBot !=null)
            {
                this.navPointX=dataBot.navPointX;
                this.navPointY=dataBot.navPointY;
            }

            // ensure that we are a team member
            data.teamMembers.put(id, this);

            return data;
        }
    }

    private void writeSharedData(Data data) throws Exception
    {
        synchronized(synchObject)
        {
            File dataFile = new File(this.getClass().getName()+"_"+team);
            FileOutputStream out = new FileOutputStream(dataFile);

            try {
                java.nio.channels.FileLock lock = out.getChannel().lock(0L, Long.MAX_VALUE, false);
                try {
                    ObjectOutputStream oos = new ObjectOutputStream(out);
                    oos.writeObject(data);
                    oos.flush();
                } finally {
                    lock.release();
                }
            } finally {
                out.close();
            }
        }
    }

    /**
     * return the direction to move to travel for the shortest route to the desired target location
     */
    private PathSegment pathFind(int startX, int startY, int targetX,int targetY,char[][] map,boolean exact)
    {
        // A*
        if (startX==targetX && startY==targetY)
        {
            return new PathSegment(targetX,targetY,0, 0,null,4,targetX,targetY);//PathSegment.DEFAULT;
        }
        else
        {
            int[][] tileIsClosed = new int[mapWidth][mapHeight];

            // find an open space in the general vicinity if exact match not required
            if (!exact)
            {
                out:
                for (int y=-1;y<=1;y++)
                {
                    for (int x=-1;x<=1;x++)
                    {
                        if (startX == targetX+x && startY==targetY+y)
                        {
                            return new PathSegment(targetX,targetY,0, 0,null,4,targetX,targetY);//PathSegment.DEFAULT;
                        }
                        else if (targetY+y>=0 && targetY+y<mapHeight && targetX+x>=0 && targetX+x < mapWidth && map[targetY+y][targetX+x]=='O')
                        {
                            targetX+=x;
                            targetY+=y;
                            break out;
                        }
                    }
                }
            }

            PathSegment curSegment = new PathSegment(targetX,targetY,1,1,null,4,targetX,targetY);
            PathSegment newSegment;
            Set<PathSegment> openList = new HashSet<PathSegment>();
            openList.add(curSegment);

            do
            {
                if (openList.isEmpty())
                {
                    break;
                }
              PathSegment currentBestScoringSegment = openList.iterator().next();
              //  Look for the lowest F cost square on the open list
              for (PathSegment segment : openList)
              {
                if (segment.fscore<currentBestScoringSegment.fscore)
                {
                  currentBestScoringSegment = segment;
                }
              }
              curSegment = currentBestScoringSegment;

              // found path
              if (startX==curSegment.tileX && startY==curSegment.tileY)
              {
                break;
              }

              // if not in closed list
              if (tileIsClosed[curSegment.tileX][curSegment.tileY]==0)
              {
                    // Switch it to the closed list.
                    tileIsClosed[curSegment.tileX][curSegment.tileY]=1;
                    // remove from openlist
                    openList.remove(curSegment);

                    // add neigbours to the open list if necessary
                    for (int i=0;i<4;i++)
                    {

                        int surroundingCurrentTileX=curSegment.tileX+offsets[i][0];
                        int surroundingCurrentTileY=curSegment.tileY+offsets[i][1];
                        if (surroundingCurrentTileX>=0 && surroundingCurrentTileX<mapWidth &&
                            surroundingCurrentTileY>=0 && surroundingCurrentTileY<mapHeight )
                        {
                            newSegment = new PathSegment( curSegment);
                            newSegment.tileX = surroundingCurrentTileX;
                            newSegment.tileY = surroundingCurrentTileY;
                            newSegment.direction = i;

                            switch(map[surroundingCurrentTileY][surroundingCurrentTileX])
                            {
                                case 'W':
                                case 'F':
                                case 'G':
                                    continue;
                            }

                          int surroundingCurrentGscore=curSegment.gscore+1 + ((surroundingCurrentTileX!=startX && surroundingCurrentTileY!=startY && map[surroundingCurrentTileY][surroundingCurrentTileX]==team)?20:0);//+map[surroundingCurrentTileY][surroundingCurrentTileX]!='O'?100:0;
                          newSegment.gscore=surroundingCurrentGscore;
                          newSegment.fscore=surroundingCurrentGscore+Math.abs( surroundingCurrentTileX-startX)+Math.abs( surroundingCurrentTileY-startY);
                          openList.add(newSegment);
                        }
                    }
              }
              else
              {
                  // remove from openlist
                  openList.remove(curSegment);
              }
            } while(true);

            return curSegment;
        }
     }

    /**
     * Reads a line of text from the input stream. Blocks until a new line character is read.
     * NOTE: This method should be used in favor of BufferedReader.readLine(...) as BufferedReader buffers data before performing
     * text line tokenization. This means that BufferedReader.readLine() will block until many game frames have been received.
     * @param in a InputStream, nominally System.in
     * @return a line of text or null if end of stream.
     * @throws IOException
     */
    private static String readLine(InputStream in) throws IOException
    {
       StringBuilder sb = new StringBuilder();
       int readByte = in.read();
       while (readByte>-1 && readByte!= '\n')
       {
          sb.append((char) readByte);
          readByte = in.read();
       }
       return readByte==-1?null:sb.toString();

    }

}
```

Title: Guard your can with your life!


问:
Lithp Tranthlator
My friend made a lisp translator the other day, that is to say it took a string and converted s=>th and S=>Th. It was quite long and I thought that it could be golfed.

So the task is to make a program/function that takes an input string, translates it in to lisp and outputs the string

Test case

```<code>Sam and Sally like Sheep        Tham and Thally like Thheep
Sally likes sausages            Thally liketh thauthageth
Sally sells seashells           Thally thellth theathhellth
</code>```

Note that it doesn't matter that h gets repeated all the time

This is code golf so shortest answer wins

答:
Thilicon, 13 byteth

```<code>i`s|th``S|Th`
</code>```

Pretty simple. i to get input, and the rest of it is replacing stuff. Output is implicit.

Title: Lithp Tranthlator

Body:
Thilicon, 13 byteth

i`s|th``S|Th`

Pretty simple. i to get input, and the rest of it is replacing stuff. Output is implicit.


Title: Removing unique elements from string

Body:
K, 18

{x@&x in&~1=#:'=x}


问:
Hofstadter Q-sequence

Definition

a(1) = 1

a(2) = 1

a(n) = a(n-a(n-1)) + a(n-a(n-2)) for n > 2 where n is an integer

Task

Given positive integer n, generate a(n).

Testcases

```<code>n  a(n)
1  1
2  1
3  2
4  3
5  3
6  4
7  5
8  5
9  6
10 6
11 6
12 8
13 8
14 8
15 10
16 9
17 10
18 11
19 11
20 12
</code>```

Reference

Obligatory OEIS A005185

答:
Python, <s>45</s> 40 bytes

a=lambda n:n<3or a(n-a(n-1))+a(n-a(n-2))
```

Simple naïve interpretation of the challenge.

Saved 5 bytes thanks to @LeakyNun!

Title: Hofstadter Q-sequence

Body:
Python, <s>45</s> 40 bytes

a=lambda n:n<3or a(n-a(n-1))+a(n-a(n-2))

Simple naïve interpretation of the challenge.

Saved 5 bytes thanks to @LeakyNun!


答:
Haskell, <s>39</s> 37 Bytes

```<code>h n|n<3=1|n>2=h(n-h(n-1))+h(n-h(n-2))
</code>```

exactly like described in the challenge, using guards

Title: Hofstadter Q-sequence

Body:
Definition

a(1) = 1

a(2) = 1

a(n) = a(n-a(n-1)) + a(n-a(n-2)) for n > 2 where n is an integer

Task

Given positive integer n, generate a(n).

Testcases

```<code>n  a(n)
1  1
2  1
3  2
4  3
5  3
6  4
7  5
8  5
9  6
10 6
11 6
12 8
13 8
14 8
15 10
16 9
17 10
18 11
19 11
20 12
</code>```

Reference

Obligatory OEIS A005185

Body:
Haskell, <s>39</s> 37 Bytes

h n|n<3=1|n>2=h(n-h(n-1))+h(n-h(n-2))

exactly like described in the challenge, using guards


答:
C#, 51 44 bytes

```<code>int a(int n)=>n<3?1:a(n-a(n-1))+a(n-a(n-2));
</code>```

i wonder if this can be shortened by making it anonymous
thanks pinkfloydx33!

Title: Hofstadter Q-sequence

Body:
C#, 51 44 bytes

int a(int n)=>n<3?1:a(n-a(n-1))+a(n-a(n-2));

i wonder if this can be shortened by making it anonymous
thanks pinkfloydx33!


答:
Jelly, <s>15</s> 14 bytes

```<code>2Rạ⁸ß€$⁺Sµ1>?2
</code>```

Try it online! or verify all test cases (takes a few seconds).

How it works

```<code>2Rạ⁸ß€$⁺Sµ1>?2  Main link. Argument: n (integer)

2R              Yield [1, 2].
      $         Combine the previous three links into a monadic chain.
   ⁸                Yield n.
  ạ                 Take the absolute difference of the return value and n.
    ß€              Recursively call the main link on each result.
       ⁺            Duplicate the chain.
                    The first copy maps [1, 2] to [a(n - 1), a(n - 2)].
                    The second copy maps [a(n - 1), a(n - 2)] to
                    [a(n - a(n - 1)), a(n - a(n - 2))].
        S           Take the sum.
         µ          Combine all links to the left into a chain.
            ?       If...
           > 2          n is greater than 2, call the chain.
          1         Else, return 1.
</code>```

Title: Hofstadter Q-sequence

Body:
Jelly, <s>15</s> 14 bytes

2Rạ⁸ß€$⁺Sµ1>?2

Try it online! or verify all test cases (takes a few seconds).

How it works

2Rạ⁸ß€$⁺Sµ1>?2  Main link. Argument: n (integer)

2R              Yield [1, 2].
      $         Combine the previous three links into a monadic chain.
   ⁸                Yield n.
  ạ                 Take the absolute difference of the return value and n.
    ß€              Recursively call the main link on each result.
       ⁺            Duplicate the chain.
                    The first copy maps [1, 2] to [a(n - 1), a(n - 2)].
                    The second copy maps [a(n - 1), a(n - 2)] to
                    [a(n - a(n - 1)), a(n - a(n - 2))].
        S           Take the sum.
         µ          Combine all links to the left into a chain.
            ?       If...
           > 2          n is greater than 2, call the chain.
          1         Else, return 1.