答:
PHP 4.1, 103 bytes

This is based on my answer on https://codegolf.stackexchange.com/a/57883/14732, which was where all the heavy lifting was done.

```<code><?$R=str_repeat;printf($W+$H<3?o:"_%'_".($Z=1+$W*2)."s_
%s-%1$'-{$Z}s-",'',$R('|'.$R(' o',$W).' |
',$H));
</code>```

This answer requires that short_open_tags and register_globals are enabled (which it is enabled by default).

You can pass the values using the keys W and H, over POST, GET, SESSION and COOKIE.

This outputs warnings to STDERR, which aren't errors. According to https://codegolf.meta.stackexchange.com/a/1655/14732, this is acceptable as long as it isn't disallowed in the question.

Removing the warnings costs me 2 bytes.

Title: Print a Lego piece

Body:
This challenge is a simple ascii-art one. Given two inputs, describing the height and width of a Lego piece, you have print an ASCII art representation of it.

Here is how the Lego pieces are supposed to look:

```<code>(4, 2)

___________
| o o o o |
| o o o o |
-----------

(8, 2)

___________________
| o o o o o o o o |
| o o o o o o o o |
-------------------

(4, 4)

___________
| o o o o |
| o o o o |
| o o o o |
| o o o o |
-----------

(3, 2)

_________
| o o o |
| o o o |
---------

(1, 1)

o
</code>```

If you can't tell from the test-cases, the top and bottom are width*2+3 underscores and dashes, and each row has pipes for the sides, o's for the little things, and everything is separated by spaces.

The only exception for this is (1, 1), which is just a single o.

You will never get 0 for any of the dimensions.

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

var QUESTION_ID=84050,OVERRIDE_USER=31343;function answersUrl(e){return"http://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"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<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:
PHP 4.1, 103 bytes

This is based on my answer on https://codegolf.stackexchange.com/a/57883/14732, which was where all the heavy lifting was done.

<?$R=str_repeat;printf($W+$H<3?o:"_%'_".($Z=1+$W*2)."s_
%s-%1$'-{$Z}s-",'',$R('|'.$R(' o',$W).' |
',$H));

This answer requires that short_open_tags and register_globals are enabled (which it is enabled by default).

You can pass the values using the keys W and H, over POST, GET, SESSION and COOKIE.

This outputs warnings to STDERR, which aren't errors. According to https://codegolf.meta.stackexchange.com/a/1655/14732, this is acceptable as long as it isn't disallowed in the question.

Removing the warnings costs me 2 bytes.


问:
Reverse odd runs
Inspiration.

Task

Reverse runs of odd numbers in a given list of 2 to 215 non-negative integers.

Examples

0 1 → 0 1

1 3 → 3 1

1 2 3 → 1 2 3

1 3 2 → 3 1 2

10 7 9 6 8 9 → 10 9 7 6 8 9

23 12 32 23 25 27 → 23 12 32 27 25 23

123 123 345 0 1 9 → 345 123 123 0 9 1

答:
Jelly, 10 bytes

```<code>Ḃ¬ðœpUżx@F
</code>```

Try it online! or verify all test cases.

How it works

```<code>Ḃ¬ðœpUżx@F  Main link. Argument: A (array)

Ḃ           Bit; return the parity bit of each integer in A.
 ¬          Logical NOT; turn even integers into 1's, odds into 0's.
  ð         Begin a new, dyadic link.
            Left argument: B (array of Booleans). Right argument: A
   œp       Partition; split A at 1's in B.
     U      Upend; reverse each resulting chunk of odd numbers.
       x@   Repeat (swapped); keep only numbers in A that correspond to a 1 in B.
      ż     Zipwith; interleave the reversed runs of odd integers (result to the
            left) and the flat array of even integers (result to the right).
         F  Flatten the resulting array of pairs.
</code>```

ContentLicense: CC BY-SA 3.0

Title: Reverse odd runs

Body:
Jelly, 10 bytes

Ḃ¬ðœpUżx@F

Try it online! or verify all test cases.

How it works

Ḃ¬ðœpUżx@F  Main link. Argument: A (array)

Ḃ           Bit; return the parity bit of each integer in A.
 ¬          Logical NOT; turn even integers into 1's, odds into 0's.
  ð         Begin a new, dyadic link.
            Left argument: B (array of Booleans). Right argument: A
   œp       Partition; split A at 1's in B.
     U      Upend; reverse each resulting chunk of odd numbers.
       x@   Repeat (swapped); keep only numbers in A that correspond to a 1 in B.
      ż     Zipwith; interleave the reversed runs of odd integers (result to the
            left) and the flat array of even integers (result to the right).
         F  Flatten the resulting array of pairs.


问:
Can you Golf Golf?
You are required to generate a random 18-hole golf course.

Example output:

```<code>[3 4 3 5 5 4 4 4 5 3 3 4 4 3 4 5 5 4]
</code>```

Rules:

Your program must output a list of hole lengths for exactly 18 holes

Each hole must have a length of 3, 4 or 5

The hole lengths must add up to 72 for the entire course

Your program must be able to produce every possible hole configuration with some non-zero-probability (the probabilities of each configuration need not be equal, but feel free to claim extra kudos if this is the case)

答:
J, 20 18 17 characters

```<code>(?~18){4+(,-)?9#2
</code>```

This works in the same way as the previous answer except that the 9 random digits are either 0 or 1 and are negated before being appended. This means there are as many -1s as there are 1s. Adding 4 gives me a list of 3s, 4s and 5s that add up to 72 every time.

Previous answer:

```<code>({~?~@#)3+(,2-])?9#3
</code>```

Generates the first 9 holes randomly ?9#3, then copies and inverts them (,2-]) (turns a 3 into a 5 and a 5 into a 3) to generate the final 9. This guarantees that the total will be 72 (since every 3 will have a matching 5 the average total per hole will be 4 and 4x18=72). It then randomly shuffles the result ({~?~@#) to ensure that every combination is possible.

Title: Can you Golf Golf?

Body:
J, 20 18 17 characters

(?~18){4+(,-)?9#2

This works in the same way as the previous answer except that the 9 random digits are either 0 or 1 and are negated before being appended. This means there are as many -1s as there are 1s. Adding 4 gives me a list of 3s, 4s and 5s that add up to 72 every time.

Previous answer:

({~?~@#)3+(,2-])?9#3

Generates the first 9 holes randomly ?9#3, then copies and inverts them (,2-]) (turns a 3 into a 5 and a 5 into a 3) to generate the final 9. This guarantees that the total will be 72 (since every 3 will have a matching 5 the average total per hole will be 4 and 4x18=72). It then randomly shuffles the result ({~?~@#) to ensure that every combination is possible.


答:
Python3, 96 bytes

Saved a lot of bytes thanks to Leaky Nun!

```<code>o=l=[]
for c in input().split():
 if int(c)%2:l=[c]+l
 else:o+=l+[c];l=[]
print(" ".join(o+l))
</code>```

Title: Reverse odd runs

Body:
Inspiration.

Task

Reverse runs of odd numbers in a given list of 2 to 215 non-negative integers.

Examples

0 1 → 0 1

1 3 → 3 1

1 2 3 → 1 2 3

1 3 2 → 3 1 2

10 7 9 6 8 9 → 10 9 7 6 8 9

23 12 32 23 25 27 → 23 12 32 27 25 23

123 123 345 0 1 9 → 345 123 123 0 9 1

Body:
Python3, 96 bytes

Saved a lot of bytes thanks to Leaky Nun!

o=l=[]
for c in input().split():
 if int(c)%2:l=[c]+l
 else:o+=l+[c];l=[]
print(" ".join(o+l))


Title: Reverse odd runs

Body:
C, 107 bytes

i;b[65536];f(){for(;i;)printf("%d ",b[--i]);}main(n){for(;~scanf("%d",&n);)n%2||f(),b[i++]=n,n%2||f();f();}


答:
Python 2, <s>79</s> <s>75</s> 73 bytes

def f(x):
 i=j=0
 for n in x+[0]:
    if~n%2:x[i:j]=x[i:j][::-1];i=j+1
    j+=1
```

This is a function that modifies its argument in place. Second indentation level is a tabulator.

Test it on Ideone.

Title: Reverse odd runs

Body:
Python 2, <s>79</s> <s>75</s> 73 bytes

def f(x):
 i=j=0
 for n in x+[0]:
    if~n%2:x[i:j]=x[i:j][::-1];i=j+1
    j+=1

This is a function that modifies its argument in place. Second indentation level is a tabulator.

Test it on Ideone.


答:
Python 2, <s>75</s> <s>68</s> 63 bytes

5 bytes thanks to Dennis.

And I have outgolfed Dennis.

Credits to Byeonggon Lee for the core of the algorithm.

o=t=[]
for i in input():o+=~i%2*(t+[i]);t=i%2*([i]+t)
print o+t
```

Ideone it!

Old version: 75 bytes

Title: Reverse odd runs

Body:
Python 2, <s>75</s> <s>68</s> 63 bytes

5 bytes thanks to Dennis.

And I have outgolfed Dennis.

Credits to Byeonggon Lee for the core of the algorithm.

o=t=[]
for i in input():o+=~i%2*(t+[i]);t=i%2*([i]+t)
print o+t

Ideone it!

Old version: 75 bytes


答:
Python 2, 78 75 bytes

```<code>def r(l):
 def k(n):o=~n%2<<99;k.i+=o*2-1;return k.i-o
 k.i=0;l.sort(key=k)
</code>```

Super hacky :)

Title: Reverse odd runs

Body:
Python 2, 78 75 bytes

def r(l):
 def k(n):o=~n%2<<99;k.i+=o*2-1;return k.i-o
 k.i=0;l.sort(key=k)

Super hacky :)


答:
Pyth, <s>29</s> 28 bytes

```<code>JYVQ=+J*%hN2+YN=Y*%N2+NY;+JY
</code>```

Test suite.

Direct translation of my python answer (when has translating from python to pyth become a good idea?)

Title: Reverse odd runs

Body:
Pyth, <s>29</s> 28 bytes

JYVQ=+J*%hN2+YN=Y*%N2+NY;+JY

Test suite.

Direct translation of my python answer (when has translating from python to pyth become a good idea?)


问:
Print the "even" permutations of symmetric group Sn in cyclic notation

THE TASK

DEFINITIONS

Consider the points {1,2,3,4,5} and all their permutations. We can find the total number of possible permutations of these 5 points by a simple trick: Imaging filling 5 slots with these points, the first slot will have 5 possible numbers, the second 4 (as one has been used to fill the first slot) the third 3 and so on. Thus the total number of Permutations is 5*4*3*2*1; this would be 5! permutations or 120 permutations. We can think of this as the symmetric group S5, and then Symmetric Group Sn would have n! or (n*n-1*n-2...*1) permutations.

An "even" permutation is one where there is an even number of even length cycles. It is easiest to understand when written in cyclic notation, for example (1 2 3)(4 5) permutes 1->2->3->1 and 4->5->4 and has one 3 length cycle (1 2 3) and one 2 length cycle (4 5). When classifying a permutation as odd or even we ignore odd length cycles and say that this permutation [(1 2 3)(4 5)] is odd as it has an odd number {1} of even length cycles.
Even examples:

(1)(2 3)(4 5) = two 2 length cycle | EVEN |

(1 2 3 4 5) = no even length cycles | EVEN | * note that if no even length cycles are present then the permutation is even.

Odd Examples:

(1 2)(3 4 5) = one 2 length cycle | ODD |

(1)(2 3 4 5) = one 4 length cycle | ODD |

As exactly half of the permutations in any Symmetric Group are even we can call the even group the Alternating Group N, So as S5 = 120 A5 = 60 permutations.

NOTATION

Permutations should, for this at least, be written in cyclic notation where each cycle is in different parenthesis and each cycle goes in ascending order. For example (1 2 3 4 5) not (3 4 5 1 2). And for cycles with a single number, such as: (1)(2 3 4)(5) the single / fixed points can be excluded meaning (1)(2 3 4)(5) = (2 3 4). But the identity {the point where all points are fixed (1)(2)(3)(4)(5)} should be written as () just to represent it.

THE CHALLENGE

I would like you to, in as little code possible, take any positive integer as an input {1,2,3,4...} and display all the permutations of the Alternating Group An where n is the input / all the even permutations of Sn. For example:

```<code>Input = 3
()
(1 2 3)
(1 3 2)
</code>```

and

```<code>Input = 4
()
(1 2)(3 4)
(1 3)(2 4)
(1 4)(2 3)
(1 2 3)
(1 3 2)
(1 2 4)
(1 4 2)
(1 3 4)
(1 4 3)
(2 3 4)
(2 4 3)
</code>```

And as with in the examples I would like for all cycles of one length to be elided, and as for the identity: outputs of  nothing, () {not only brackets but with whatever you are using to show different permutations} or id are acceptable.

EXTRA READING

You can find more information here:

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

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

GOOD LUCK

And as this is codegolf whoever can print the Alternating Group An's permutations in the shortest bytes wins.

答:
J, 53 bytes

```<code>[:(<@((>:@|.~]i.<./)&.>@#~1<#@>)@C.@#~1=C.!.2)!A.&i.]
</code>```

The cycles in each permutation are represented as boxed arrays since J will zero-pad ragged arrays.

If the output is relaxed, using 41 bytes

```<code>[:((1+]|.~]i.<./)&.>@C.@#~1=C.!.2)!A.&i.]
</code>```

where each permutation may contain one-cycles and zero-cycles.

Usage

```<code>   f =: [:(<@((>:@|.~]i.<./)&.>@#~1<#@>)@C.@#~1=C.!.2)!A.&i.]
   f 3
┌┬───────┬───────┐
││┌─────┐│┌─────┐│
│││1 2 3│││1 3 2││
││└─────┘│└─────┘│
└┴───────┴───────┘
   f 4
┌┬───────┬───────┬─────────┬───────┬───────┬───────┬───────┬─────────┬───────┬───────┬─────────┐
││┌─────┐│┌─────┐│┌───┬───┐│┌─────┐│┌─────┐│┌─────┐│┌─────┐│┌───┬───┐│┌─────┐│┌─────┐│┌───┬───┐│
│││2 3 4│││2 4 3│││1 2│3 4│││1 2 3│││1 2 4│││1 3 2│││1 3 4│││1 3│2 4│││1 4 2│││1 4 3│││2 3│1 4││
││└─────┘│└─────┘│└───┴───┘│└─────┘│└─────┘│└─────┘│└─────┘│└───┴───┘│└─────┘│└─────┘│└───┴───┘│
└┴───────┴───────┴─────────┴───────┴───────┴───────┴───────┴─────────┴───────┴───────┴─────────┘
</code>```

For the alternative implemenation,

```<code>   f =: [:((1+]|.~]i.<./)&.>@C.@#~1=C.!.2)!A.&i.]
   f 3
┌─────┬─┬─┐
│1    │2│3│
├─────┼─┼─┤
│1 2 3│ │ │
├─────┼─┼─┤
│1 3 2│ │ │
└─────┴─┴─┘
</code>```

Body:
J, 53 bytes

[:(<@((>:@|.~]i.<./)&.>@#~1<#@>)@C.@#~1=C.!.2)!A.&i.]

The cycles in each permutation are represented as boxed arrays since J will zero-pad ragged arrays.

If the output is relaxed, using 41 bytes

[:((1+]|.~]i.<./)&.>@C.@#~1=C.!.2)!A.&i.]

where each permutation may contain one-cycles and zero-cycles.

Usage

   f =: [:(<@((>:@|.~]i.<./)&.>@#~1<#@>)@C.@#~1=C.!.2)!A.&i.]
   f 3
┌┬───────┬───────┐
││┌─────┐│┌─────┐│
│││1 2 3│││1 3 2││
││└─────┘│└─────┘│
└┴───────┴───────┘
   f 4
┌┬───────┬───────┬─────────┬───────┬───────┬───────┬───────┬─────────┬───────┬───────┬─────────┐
││┌─────┐│┌─────┐│┌───┬───┐│┌─────┐│┌─────┐│┌─────┐│┌─────┐│┌───┬───┐│┌─────┐│┌─────┐│┌───┬───┐│
│││2 3 4│││2 4 3│││1 2│3 4│││1 2 3│││1 2 4│││1 3 2│││1 3 4│││1 3│2 4│││1 4 2│││1 4 3│││2 3│1 4││
││└─────┘│└─────┘│└───┴───┘│└─────┘│└─────┘│└─────┘│└─────┘│└───┴───┘│└─────┘│└─────┘│└───┴───┘│
└┴───────┴───────┴─────────┴───────┴───────┴───────┴───────┴─────────┴───────┴───────┴─────────┘

For the alternative implemenation,

   f =: [:((1+]|.~]i.<./)&.>@C.@#~1=C.!.2)!A.&i.]
   f 3
┌─────┬─┬─┐
│1    │2│3│
├─────┼─┼─┤
│1 2 3│ │ │
├─────┼─┼─┤
│1 3 2│ │ │
└─────┴─┴─┘


Title: Reverse odd runs

Body:
J, <s>33</s> <s>31</s> 30 bytes

[:;]<@(A.~2-@|{.);.1~1,2|2-/\]

Usage

   f =: [:;]<@(A.~2-@|{.);.1~1,2|2-/\]
   f 0 1
0 1
   f 1 3
3 1
   f 1 2 3
1 2 3
   f 1 3 2
3 1 2
   f 10 7 9 6 8 9
10 9 7 6 8 9
   f 23 12 32 23 25 27
23 12 32 27 25 23
   f 123 123 345 0 1 9
345 123 123 0 9 1


答:
JavaScript (ES6) <s>70</s> 66 bytes

Edit 4 bytes saved thx @Neil

```<code>a=>[...a,[]].map(x=>x&1?o=[x,...o]:r=r.concat(o,x,o=[]),r=o=[])&&r
</code>```

Title: Reverse odd runs

Body:
JavaScript (ES6) <s>70</s> 66 bytes

Edit 4 bytes saved thx @Neil

a=>[...a,[]].map(x=>x&1?o=[x,...o]:r=r.concat(o,x,o=[]),r=o=[])&&r

ContentLicense: CC BY-SA 4.0


答:
GolfScript, 27 chars

```<code>{;18{3.rand+}*].{+}*72-}do`
</code>```

Uses the same rejection sampling method as sgrieve's Python solution.  Thus, every valid output actually is equally likely.

Title: Can you Golf Golf?

Body:
You are required to generate a random 18-hole golf course.

Example output:

```<code>[3 4 3 5 5 4 4 4 5 3 3 4 4 3 4 5 5 4]
</code>```

Rules:

Your program must output a list of hole lengths for exactly 18 holes

Each hole must have a length of 3, 4 or 5

The hole lengths must add up to 72 for the entire course

Your program must be able to produce every possible hole configuration with some non-zero-probability (the probabilities of each configuration need not be equal, but feel free to claim extra kudos if this is the case)

Body:
GolfScript, 27 chars

{;18{3.rand+}*].{+}*72-}do`

Uses the same rejection sampling method as sgrieve's Python solution.  Thus, every valid output actually is equally likely.


问:
It's Life, Jim, but not as we know it
You probably know Conway's Game of Life, the famous cellular automaton invented by mathematician John Conway. Life is a set of rules that, together, allow you to simulate a two-dimensional board of cells. The rules decide which cells on the board live and  which ones die. With some imagination, you could say that Life is a zero-player game: a game with the objective to find patterns with interesting behavior, like the famous glider.

A zero-player game... Until today. You are to write a program that plays the Game of Life - and plays it to win, King of the Hill-style. Your opponent (singular) of course tries to do the same. The winner is either the last bot with any live cells, or the player with the most live cells after 10000 generations.

Game rules

The rules are almost the same as normal (B3/S23) Life:

A live cell with fewer than two friendly neighbors dies from starvation.

A live cell with two or three friendly neighbors survives.

A live cell with more than three friendly neighbors dies from overpopulation.

A dead cell with exactly three neighbors of the same player comes alive to fight for that player provided there are no enemy neighbors.

...but after each generation, both you and your opponent get the opportunity to intervene. You can awake up to a maximum of 30 cells to fight for you. (Who goes first is decided by the server.)

The board is a (x,y) cells square. All squares are initially dead. The borders do not wrap around (this is not a torus-shaped world) and are permanently dead.

This is is a contest in the spirit of Battlebots and Core Wars. There is a central server that will run bots and it can be found here

Protocol

The arena server speaks a simple JSON protocol communicated through argv

Where Values is a JSON encoded string

y_size: the maximum y coords of tiles before they vanish

x_size: the maximum x coords of tiles before they vanish

tick_id: the current tick number

board: a dictionary with keys in the form '(y,x)' and values in the form bot_id (int)

bot_id: tiles in the board with this id are yours

Example:

```<code> {"y_size":2000,"x_size":2000,"board":{},"bot_id":1,"tick_id":1}

</code>```

Telling the server your choice:

Send the server a list of tiles to turn to your colour.

Only those that are empty will be changed

Nested coords list format

[[0,0], [0,1], [100,22]...]

NOTE: Your bot doesn't have to update the tiles at all - the server does the updating itself

Competition rules

If your implementation fails to follow the protocol, the turn it does will be forfeited; The server will assume no change in state

You are not allowed to willfully take advantage of a fault in the arena server.

Have your AI decide on moves in a sane time. Please send your next move as  fast as reasonably possible.

Finally, please be nice to the server. It's there for your enjoyment.

Not following these rules can lead to disqualification.

In the event of a tie, both players have 1 win added to their total

Running the controller yourself

The source for the controller can be found here. There are 2 ways of running the controller:

Competition mode (terminal)

Setup with python3 get_answers.py

Run an all v all competition with each bot pitting it against every other.

Testing mode (GUI)

Run python3 nice_gui.py

Click Pull Answers

If you want to add your own answer to try it before posting, click File -> Add manual answer and find the file and choose the language it's written in.

If your language isn't present ping me and I'll try to get it installed on the server I will run it on (installation and running instructions would be nice too!)

Choose 2 bots to pit against each other

Click Run

Watch the game...

Installation

Requires python3

get_answers requires bs4 and html5lib

controller requires a way of running .sh files (MinGW on windows)

Scoring

The bot with the most wins starting from <s>12/07/2016 (12th July)</s>   14/07/2016 (14th July, couldn't work out how to run a bot) wins.

Help with the controller/gui can be asked in this chat room

This question has been in development since 2014 and was the most upvoted question in the sandbox. Special Thanks goes to Wander Nauta (original author and concept), PPCG Chat (comments and help) and anyone who commented in the sandbox post (more comments).

答:
Python, GuyWithAGun

He's a guy, he's got a gun; he's mad. He just dumps glider guns everywhere with no regard to what anyone else is doing

```<code>import random, copy
import sys, json

args = json.loads(sys.argv[1])
bot_id = args["bot_id"]
x_size = args["x_size"]
y_size = args["y_size"]
tick_id = args["tick_id"]
board = args["board"]

start_squares = [[0,5],[2,5],[1,6],[2,6],
                 [35,3],[36,3],[35,4],[36,4]]
gun = [[11,5],[11,6],[11,7],
       [12,4],[12,8],
       [13,3],[13,9],
       [14,3],[14,9],
       [15,6],
       [16,4],[16,8],
       [17,5],[17,6],[17,7],
       [18,6],
       [21,3],[21,4],[21,5],
       [22,3],[22,4],[22,5],
       [23,2],[23,6],
       [25,1],[25,2],[25,6],[25,7]]

templates = [start_squares, gun]

def add_squares(pos, coords):
    new_squares = copy.deepcopy(coords)
    for coord in new_squares:
        coord[0]+=pos[0]
        coord[1]+=pos[1]
    return new_squares

def get_latest_pos():
    seed, template_id = divmod(tick_id, 2)
    random.seed(seed)
    cur_pos = [random.randrange(y_size),
               random.randrange(x_size)]
    cur_template = templates[template_id]
    try:
        return add_squares(cur_pos, cur_template)
    except IndexError:
        return []

move = get_latest_pos()

print json.dumps(move)
</code>```

Title: It's Life, Jim, but not as we know it

Body:
Python, GuyWithAGun

He's a guy, he's got a gun; he's mad. He just dumps glider guns everywhere with no regard to what anyone else is doing

import random, copy
import sys, json

args = json.loads(sys.argv[1])
bot_id = args["bot_id"]
x_size = args["x_size"]
y_size = args["y_size"]
tick_id = args["tick_id"]
board = args["board"]

start_squares = [[0,5],[2,5],[1,6],[2,6],
                 [35,3],[36,3],[35,4],[36,4]]
gun = [[11,5],[11,6],[11,7],
       [12,4],[12,8],
       [13,3],[13,9],
       [14,3],[14,9],
       [15,6],
       [16,4],[16,8],
       [17,5],[17,6],[17,7],
       [18,6],
       [21,3],[21,4],[21,5],
       [22,3],[22,4],[22,5],
       [23,2],[23,6],
       [25,1],[25,2],[25,6],[25,7]]

templates = [start_squares, gun]

def add_squares(pos, coords):
    new_squares = copy.deepcopy(coords)
    for coord in new_squares:
        coord[0]+=pos[0]
        coord[1]+=pos[1]
    return new_squares

def get_latest_pos():
    seed, template_id = divmod(tick_id, 2)
    random.seed(seed)
    cur_pos = [random.randrange(y_size),
               random.randrange(x_size)]
    cur_template = templates[template_id]
    try:
        return add_squares(cur_pos, cur_template)
    except IndexError:
        return []

move = get_latest_pos()

print json.dumps(move)


问:
What's the second non-repeating character?
Based on this question from Code Review

Given a non-empty string of printable ASCII characters, output the second non-repeating character. For example, for input DEFD, output F.

Input

A single string, in any suitable format.

Output

The second character that doesn't repeat, when reading left-to-right, again in a suitable format.

The output character is case-insensitive.

If no such character exists (e.g., all characters repeat), output an empty string.

Rules

The algorithm should ignore case. That is, D and d count as the same character.

Either a full program or a function are acceptable.

The input string will be guaranteed non-empty (i.e., at least one character in length).

The input string is ASCII. Any valid character could repeat, not just alphanumeric (this includes spaces).

Standard loopholes are forbidden.

This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples

Input is on first line, output is on second line.

```<code>DEFD
F

FEED
D

This is an example input sentence.
x

...,,,..,,!@
@

ABCDefgHijklMNOPqrsTuVWxyz
B

AAAAAABBBBB

Thisxthis

This this.
.
</code>```

答:
C#, 143 bytes

```<code>char c(string s){var l=s.Select(o=>Char.ToLower(o)).GroupBy(x=>x).Where(n=>n.Count()<2).Select(m=>m.Key).ToList();return l.Count()>1?l[1]:' ';}
</code>```

Body:
C#, 143 bytes

char c(string s){var l=s.Select(o=>Char.ToLower(o)).GroupBy(x=>x).Where(n=>n.Count()<2).Select(m=>m.Key).ToList();return l.Count()>1?l[1]:' ';}


问:
Reverse stdin and place on stdout
Requirements:

Take an input on stdin including new lines / carriage returns of unlimited length (only bounded by system memory; that is, there is no inherent limit in the program.)

Output the reverse of the input on stdout.

Example:

Input:

```<code>Quick brown fox
He jumped over the lazy dog
</code>```

Output:

```<code>god yzal eht revo depmuj eH
xof nworb kciuQ
</code>```

Shortest wins.

Leaderboard:

var QUESTION_ID=242,OVERRIDE_USER=61563;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<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

```

答:
Pyke, 1 byte (noncompetitive)

```<code>_
</code>```

Try it here!

Title: Reverse stdin and place on stdout

Body:
Pyke, 1 byte (noncompetitive)

_

Try it here!


问:
AGM Series Hole 1: Calculate the Arithmetic–Geometric Mean
This question was inspired by this HNQ.

About the series

This question is now part of a series about the AGM method. This first post in the series will be about actually calculating the AGM. You may treat this like any other code golf challenge, and answer it without worrying about the series at all. However, there is a leaderboard across all challenges.

What is the Arithmetic–Geometric Mean

The Arithmetic–Geometric Mean of two numbers is defined as the number that repeatedly taking the arithmetic and geometric means converges to. Your task is to find this number after some n iterations.

Clarifications

You take three numbers, a, b, n in any reasonable format.

For n iterations, take the arithmetic and geometric mean of a and b and set those to a and b.

For two numbers a and b, the arithmetic mean is defined as (a + b) / 2.

The geometric mean is defined as √(a * b).

a and b should be approaching each other.

Then, output both a and b.

You don't have to worry about float imprecision and such.

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

Test Cases

```<code>[0, [24, 6]] -> [24, 6]
[1, [24, 6]] -> [15.0, 12.0]
[2, [24, 6]] -> [13.5, 13.416407864998739]
[5, [24, 6]] -> [13.458171481725616, 13.458171481725616]
[10, [100, 50]] -> [72.83955155234534, 72.83955155234534]

The next one is 1/Gauss's Constant:
[10, [1, 1.41421356237]] -> [1.198140234734168, 1.1981402347341683]
</code>```

Leaderboard

Stolen from Martin's series.

The following snippet will generate a leaderboard across all challenges of the series.

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

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

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

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

/* Configuration */

var QUESTION_IDs = [66068]; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!.FjwQBrX2KXuFkv6p2lChi_RjzM19";

/* App */

var answers = [], page = 1, currentQ = -1;

function answersUrl(index) {
  return "http://api.stackexchange.com/2.2/questions/" +  QUESTION_IDs.join(";") + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function getAnswers() {
  $.ajax({
    url: answersUrl(page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      if (data.has_more) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SIZE_REG = /\d+(?=[^\d&]*(?:<(?:s>((?!>).)*<\/s>|((?!>).)+>)[^\d&]*)*$)/;
var NUMBER_REG = /\d+/;
var LANGUAGE_REG = /^#*\s*([^\n,]+)(?=,)/;//

function shouldHaveHeading(a) {
  var pass = false;
  var lines = a.body_markdown.split("\n");
  try {
    pass |= /^#/.test(a.body_markdown);
    pass |= ["-", "="]
              .indexOf(lines[1][0]) > -1;
    pass &= LANGUAGE_REG.test(a.body_markdown);
  } catch (ex) {}
  return pass;
}

function shouldHaveScore(a) {
  var pass = false;
  try {
    pass |= SIZE_REG.test(a.body_markdown.split("\n")[0]);
  } catch (ex) {}
  if (!pass) console.log(a);
  return pass;
}

function getAuthorName(a) {
  return a.owner.display_name;
}

function getAuthorId(a) {
  return a.owner.user_id;
}

function process() {
  answers = answers.filter(shouldHaveScore)
                   .filter(shouldHaveHeading);
  answers.sort(function (a, b) {
    var aB = +(a.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0],
        bB = +(b.body_markdown.split("\n")[0].match(SIZE_REG) || [Infinity])[0];
    return aB - bB
  });

  var users = {};
  answers.forEach(function (a) {
    var headline = a.body_markdown.split("\n")[0];
    var question = QUESTION_IDs.indexOf(a.question_id);
    var size = parseInt((headline.match(SIZE_REG)||[0])[0]);
    var language = headline.match(LANGUAGE_REG)[1];
    var user = getAuthorName(a);
    var userId = getAuthorId(a);
    if (!users[userId]) users[userId] = {name: user, nAnswer: 0, answers: []};
    if (!users[userId].answers[question]) {
      users[userId].answers[question] = {size: Infinity};
      users[userId].nAnswer++;
    }
    if (users[userId].answers[question].size > size) {
      users[userId].answers[question] = {size: size, link: a.share_link}
    }
  });

  var sortedUsers = [];
  for (var userId in users)
    if (users.hasOwnProperty(userId)) {
      var user = users[userId];
      user.score = 0;
      user.completedAll = true;
      for (var i = 0; i < QUESTION_IDs.length; ++i) {
        if (user.answers[i])
          user.score += user.answers[i].size;
        else
          user.completedAll = false;
      }
      sortedUsers.push(user);
    }

  sortedUsers.sort(function (a, b) {
    if (a.nAnswer > b.nAnswer) return -1;
    if (b.nAnswer > a.nAnswer) return 1;
    return a.score - b.score;
  });

  var place = 1;
  for (var i = 0; i < sortedUsers.length; ++i) {
    var user = sortedUsers[i];
    var row = '
'+ place++ +'.	'+user.name+'	';
    for (var j = 0; j < QUESTION_IDs.length; ++j) {
      var answer = user.answers[j];
      if (answer)
        row += ''+answer.size+'	';
      else
        row += '	';
    }
    row += '	';
    if (user.completedAll)
      row += ''+user.score+'	';
    else
      row += ''+user.score+'	';
    row += '
';
    $("#users").append(row);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#leaderboard {
  width: 500px;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}

td.total {
  font-weight: bold;
  text-align: right;
}

td.missing {
  background: #bbbbbb;
}</code>```

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

Leaderboard

    Missing scores are shown as grey cells. A grey total indicates that the user has not participated in all challenges and is not eligible for the overall victory yet.

	User
        #1
        	Total

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

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

```

答:
Java, <s>103</s> <s>96</s> 84 bytes

String f(int n,double a,double b){return n>0?f(n-1,(a+b)/2,Math.sqrt(a*b)):a+","+b;}
```

<p>Verify all testcases.</p>

<p>Old version (96 bytes):</p>

<pre class="lang-java prettyprint-override"><code>String f(int n,double a,double b){for(;n>0;a=(a+b)/2,b=Math.sqrt((b-2*a)*b))n--;return a+","+b;}
</code>```

Old version (103 bytes):

String f(int n,double a,double b){double t;for(;n>0;t=(a+b)/2,b=Math.sqrt(a*b),a=t)n--;return a+","+b;}
```

Body:
Java, <s>103</s> <s>96</s> 84 bytes

String f(int n,double a,double b){return n>0?f(n-1,(a+b)/2,Math.sqrt(a*b)):a+","+b;}

Verify all testcases.

Old version (96 bytes):

String f(int n,double a,double b){for(;n>0;a=(a+b)/2,b=Math.sqrt((b-2*a)*b))n--;return a+","+b;}

Old version (103 bytes):

String f(int n,double a,double b){double t;for(;n>0;t=(a+b)/2,b=Math.sqrt(a*b),a=t)n--;return a+","+b;}


问:
Add two numbers
Input: Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their sum. Use the same format for output integers as input integers. For example, the input 5 16 would lead to the output 21.

Restrictions: No standard loopholes please. This is code-golf, answer in lowest amount of bytes wins.

Notes: This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is.

Test cases:

```<code>1 2 -> 3
14 15 -> 29
7 9 -> 16
-1 8 -> 7
8 -9 -> -1
-8 -9 -> -17
</code>```

Or as CSV:

```<code>a,b,c
1,2,3
14,15,29
7,9,16
-1,8,7
8,-9,-1
-8,-9,-17
</code>```

Leaderboard

var QUESTION_ID=84260,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<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

```

答:
Perl 5.10, 8 bytes

The two numbers to add must be on 2 separate lines for this one to work:

```<code>say<>+<>
</code>```

Try this one here.

One with input on the same line (14 + 1 bytes for -a flag)

```<code>say$F[0]+$F[1]
</code>```

Try it here!

One with input on the same line (19 + 1 bytes for -a flag)

```<code>map{$s+=$_}@F;say$s
</code>```

Try this one here.

Another one, by changing the array default separator (19 + 1 bytes for -a flag as well)

```<code>$"="+";say eval"@F"
</code>```

Try this one here!

Title: Add two numbers

Body:
Perl 5.10, 8 bytes

The two numbers to add must be on 2 separate lines for this one to work:

say<>+<>

Try this one here.

One with input on the same line (14 + 1 bytes for -a flag)

say$F[0]+$F[1]

Try it here!

One with input on the same line (19 + 1 bytes for -a flag)

map{$s+=$_}@F;say$s

Try this one here.

Another one, by changing the array default separator (19 + 1 bytes for -a flag as well)

$"="+";say eval"@F"

Try this one here!


答:
x86 machine code, 43 bytes

In hex:

```<code>FC31C031C95641AC84C0740E3C6172F63C7A77F28066FFDFEBEC5EAC49740B89F751F2AE5974F44A77F1C3
</code>```

Function takes a pointer to the input string in (E)SI and an integer in (E)DX and returns the (E)DX-th non-repeating character or zero if there's no such character. As a side-effect it converts the string to upper case.

Disassembly:

```<code>fc             cld
31 c0          xor    eax,eax
31 c9          xor    ecx,ecx
56             push   esi
_loop0:                         ;Search for the NULL char,
41             inc    ecx       ;counting the length in the process
ac             lodsb
84 c0          test   al,al
74 0e          je     _break0   ;NULL found, break
3c 61          cmp    al,0x61   ;If char is
72 f6          jb     _loop0    ;between 'a' and 'z'
3c 7a          cmp    al,0x7a   ;convert this char
77 f2          ja     _loop0    ;to uppercase in-place
80 66 ff df    and    byte ptr [esi-0x1],0xdf
eb ec          jmp    _loop0
_break0:
5e             pop    esi       ;Reset pointer to the string
_loop:                          ;ECX=string length with NULL
ac             lodsb            ;Load next char to AL
49             dec    ecx
74 0b          je     _ret      ;End of string found, break (AL==0)
89 f7          mov    edi,esi   ;EDI points to the next char
51             push   ecx
f2 ae          repnz scasb      ;Search for AL in the rest of the string
59             pop    ecx
74 f4          je     _loop     ;ZF==1 <=> another instance found, continue
4a             dec    edx
77 f1          ja     _loop     ;If not yet the EDX-th non-rep char, continue
_ret:
c3             ret
</code>```

Title: What's the second non-repeating character?

Body:
Based on this question from Code Review

Given a non-empty string of printable ASCII characters, output the second non-repeating character. For example, for input DEFD, output F.

Input

A single string, in any suitable format.

Output

The second character that doesn't repeat, when reading left-to-right, again in a suitable format.

The output character is case-insensitive.

If no such character exists (e.g., all characters repeat), output an empty string.

Rules

The algorithm should ignore case. That is, D and d count as the same character.

Either a full program or a function are acceptable.

The input string will be guaranteed non-empty (i.e., at least one character in length).

The input string is ASCII. Any valid character could repeat, not just alphanumeric (this includes spaces).

Standard loopholes are forbidden.

This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples

Input is on first line, output is on second line.

```<code>DEFD
F

FEED
D

This is an example input sentence.
x

...,,,..,,!@
@

ABCDefgHijklMNOPqrsTuVWxyz
B

AAAAAABBBBB

Thisxthis

This this.
.
</code>```

Body:
x86 machine code, 43 bytes

In hex:

FC31C031C95641AC84C0740E3C6172F63C7A77F28066FFDFEBEC5EAC49740B89F751F2AE5974F44A77F1C3

Function takes a pointer to the input string in (E)SI and an integer in (E)DX and returns the (E)DX-th non-repeating character or zero if there's no such character. As a side-effect it converts the string to upper case.

Disassembly:

fc             cld
31 c0          xor    eax,eax
31 c9          xor    ecx,ecx
56             push   esi
_loop0:                         ;Search for the NULL char,
41             inc    ecx       ;counting the length in the process
ac             lodsb
84 c0          test   al,al
74 0e          je     _break0   ;NULL found, break
3c 61          cmp    al,0x61   ;If char is
72 f6          jb     _loop0    ;between 'a' and 'z'
3c 7a          cmp    al,0x7a   ;convert this char
77 f2          ja     _loop0    ;to uppercase in-place
80 66 ff df    and    byte ptr [esi-0x1],0xdf
eb ec          jmp    _loop0
_break0:
5e             pop    esi       ;Reset pointer to the string
_loop:                          ;ECX=string length with NULL
ac             lodsb            ;Load next char to AL
49             dec    ecx
74 0b          je     _ret      ;End of string found, break (AL==0)
89 f7          mov    edi,esi   ;EDI points to the next char
51             push   ecx
f2 ae          repnz scasb      ;Search for AL in the rest of the string
59             pop    ecx
74 f4          je     _loop     ;ZF==1 <=> another instance found, continue
4a             dec    edx
77 f1          ja     _loop     ;If not yet the EDX-th non-rep char, continue
_ret:
c3             ret


答:
MATL, 20 bytes

```<code>TiodgvYsG8XQ!"@gto?P
</code>```

Input is a column array, using ; as separator.

Try it online!

Explanation

Consider as an example the input array [1;2;3;5;7;4;6;7;9]. The first part of the code, Tiodgv, converts this array into [1;1;1;0;0;1;0;1;0], where 1 indicates a change of parity. (Specifically, the code obtains the parity of each entry of the input array, computes consecutive differences, converts nonzero values to 1, and prepends a 1.)

Then Ys computes the cumulative sum, giving [1;2;3;3;3;4;4;5;5]. Each of these numbers will be used as a label, based on which the elements of the input will be grouped. This is done by G8XQ!, which splits the input array into a cell array containing the groups. In this case it gives {[1] [2] [3;5;7] [4;6] [7;9]}.

The rest of the code iterates (") on the cell array. Each constituent numeric array is pushed with @g. to makes a copy and computes its parity. If (?) the result is truthy, i.e. the array contents are odd, the array is flipped (P).

The stack is implicitly displayed at the end. Each numeric vertical array is displayed, giving a list of numbers separated by newlines.

Title: Reverse odd runs

Body:
Inspiration.

Task

Reverse runs of odd numbers in a given list of 2 to 215 non-negative integers.

Examples

0 1 → 0 1

1 3 → 3 1

1 2 3 → 1 2 3

1 3 2 → 3 1 2

10 7 9 6 8 9 → 10 9 7 6 8 9

23 12 32 23 25 27 → 23 12 32 27 25 23

123 123 345 0 1 9 → 345 123 123 0 9 1

Body:
MATL, 20 bytes

TiodgvYsG8XQ!"@gto?P

Input is a column array, using ; as separator.

Try it online!

Explanation

Consider as an example the input array [1;2;3;5;7;4;6;7;9]. The first part of the code, Tiodgv, converts this array into [1;1;1;0;0;1;0;1;0], where 1 indicates a change of parity. (Specifically, the code obtains the parity of each entry of the input array, computes consecutive differences, converts nonzero values to 1, and prepends a 1.)

Then Ys computes the cumulative sum, giving [1;2;3;3;3;4;4;5;5]. Each of these numbers will be used as a label, based on which the elements of the input will be grouped. This is done by G8XQ!, which splits the input array into a cell array containing the groups. In this case it gives {[1] [2] [3;5;7] [4;6] [7;9]}.

The rest of the code iterates (") on the cell array. Each constituent numeric array is pushed with @g. to makes a copy and computes its parity. If (?) the result is truthy, i.e. the array contents are odd, the array is flipped (P).

The stack is implicitly displayed at the end. Each numeric vertical array is displayed, giving a list of numbers separated by newlines.


答:
Jolf, 1 byte

Interpreter.

```<code>u
</code>```

Take sum of list.

Or, for two bytes, +j, takes two inputs seperated by double newline.

Title: Add two numbers

Body:
Input: Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their sum. Use the same format for output integers as input integers. For example, the input 5 16 would lead to the output 21.

Restrictions: No standard loopholes please. This is code-golf, answer in lowest amount of bytes wins.

Notes: This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is.

Test cases:

```<code>1 2 -> 3
14 15 -> 29
7 9 -> 16
-1 8 -> 7
8 -9 -> -1
-8 -9 -> -17
</code>```

Or as CSV:

```<code>a,b,c
1,2,3
14,15,29
7,9,16
-1,8,7
8,-9,-1
-8,-9,-17
</code>```

Leaderboard

var QUESTION_ID=84260,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<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:
Jolf, 1 byte

Interpreter.

u

Take sum of list.

Or, for two bytes, +j, takes two inputs seperated by double newline.


答:
C#, <s>179</s> <s>178</s> 177 bytes

```<code>s=>{var o=new List<int>();var l=new Stack<int>();foreach(var n in s.Split(' ').Select(int.Parse)){if(n%2>0)l.Push(n);else{o.AddRange(l);o.Add(n);l.Clear();}}return o.Concat(l);}
</code>```

I use a C# lambda. You can try it on .NETFiddle.

The code less minify:

```<code>s => {
    var o=new List<int>();var l=new Stack<int>();
    foreach (var n in s.Split(' ').Select(int.Parse)) {
        if (n%2>0)
            l.Push(n);
        else {
            o.AddRange(l);
            o.Add(n);
            l.Clear();
        }
    }
    return o.Concat(l);
};
</code>```

Kudos to Byeonggon Lee for the original algorithm.

Title: Reverse odd runs

Body:
C#, <s>179</s> <s>178</s> 177 bytes

s=>{var o=new List<int>();var l=new Stack<int>();foreach(var n in s.Split(' ').Select(int.Parse)){if(n%2>0)l.Push(n);else{o.AddRange(l);o.Add(n);l.Clear();}}return o.Concat(l);}

I use a C# lambda. You can try it on .NETFiddle.

The code less minify:

s => {
    var o=new List<int>();var l=new Stack<int>();
    foreach (var n in s.Split(' ').Select(int.Parse)) {
        if (n%2>0)
            l.Push(n);
        else {
            o.AddRange(l);
            o.Add(n);
            l.Clear();
        }
    }
    return o.Concat(l);
};

Kudos to Byeonggon Lee for the original algorithm.


问:
Array Sandwiches
(Adapted from Problem C of the first qualifier of the ACM Programming Contest of 2012/2013)

You have several arrays, named \$A_1, A_2, ... , A_n\$, each sorted in ascending order. Every item in the array will be a 32-bit integer.

A sandwich is a set of indices \$j_1, j_2, ... , j_n\$ such that \$A_1[j_1] ≤ A_2[j_2] ≤ ... ≤ A_n[j_n]\$. \$A_i[0]\$ is the first element of \$A_i\$.

Given some arrays, output every possible sandwich that you can have from those arrays, separated by a newline.

If there is somehow a built-in function which does this in your language, don't use it.

Input can be given in any way, output must be separated with whitespace, but can given in any order.

Test Case:

```<code>[[1, 5, 7, 10], [2, 6, 6, 8, 12], [4, 5, 9]]
</code>```

Output:

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

Test Case:

```<code>[[10, 20, 30], [1, 2, 3]]
</code>```

Output:

Shortest code wins.

答:
Python, 149 141 140

```<code>import itertools as I;x=input();r=range;print[p for p in I.product(*map(r,map(len,x)))if all(x[i][p[i]]<=x[i+1][p[i+1]]for i in r(len(x)-1))]
</code>```

Python has a useful itertools library that can generate permutations. This just iterates over all possible permutations of valid indices and checks whether they satisfy the criteria.

I think I can make this shorter, still working on it.

Edit: Now all one line for your reading (in)convenience!

Title: Array Sandwiches

Body:
Python, 149 141 140

import itertools as I;x=input();r=range;print[p for p in I.product(*map(r,map(len,x)))if all(x[i][p[i]]<=x[i+1][p[i+1]]for i in r(len(x)-1))]

Python has a useful itertools library that can generate permutations. This just iterates over all possible permutations of valid indices and checks whether they satisfy the criteria.

I think I can make this shorter, still working on it.

Edit: Now all one line for your reading (in)convenience!


问:
Distinct Sieves
Given a list of integers, create a boolean mask such that the true indices can be used to filter the distinct values from the list. Which index is selected as the true one does not matter as long as only one of them is selected for each set of indices corresponding to identical values.

The input will be a non-empty list of non-negative integers in a format suitable for your language and the output will be a list of boolean values following the specification above. You are allowed to use your own definitions of truthy and falsy values in the output list.

In my examples below, I define 1 to be truthy and 0 to be falsy.

```<code>[5, 4, 7, 1]  Input
[1, 1, 1, 1]  Output
              Select only the values with with true indicies in the sieve
[5  4  7  1]  Contains zero duplicate values

[5, 9, 7, 5, 6, 0, 5]
[0, 1, 1, 1, 1, 1, 0]
[   9, 7, 5, 6, 0   ]
</code>```

Test Cases

When there is an or, it means that there are multiple valid outputs. If there is a trailing ellipsis ... after the or, it means that not all of the possible outputs were listed.

```<code>[0] = [1]

[55] = [1]

[32, 44] = [1, 1]

[0, 0] = [1, 0] or [0, 1]

[9001, 9001, 9001] = [1, 0 , 0] or [0, 1, 0] or [0, 0, 1]

[5, 4, 7, 1] = [1, 1, 1, 1]

[1, 2, 3, 4, 3, 5] = [1, 1, 1, 1, 0, 1] or
                     [1, 1, 0, 1, 1, 1]

[5, 9, 7, 5, 6, 0, 5] = [1, 1, 1, 0, 1, 1, 0] or
                        [0, 1, 1, 1, 1, 1, 0] or
                        [0, 1, 1, 0, 1, 1, 1]

[0, 8, 6, 6, 3, 8, 7, 2] = [1, 1, 1, 0, 1, 0, 1, 1] or
                           [1, 0, 0, 1, 1, 1, 1, 1] or
                           [1, 0, 1, 0, 1, 1, 1, 1] or
                           [1, 1, 0, 1, 1, 0, 1, 1]

[45, 47, 47, 45, 24, 24, 24, 8, 47, 41, 47, 88]
= [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1] or ...

[154, 993, 420, 154, 154, 689, 172, 417, 790, 175, 790, 790, 154, 172, 175, 175, 420, 417, 154, 175, 172, 175, 172, 993, 689, 993, 993, 790]
= [1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] or ...
</code>```

Rules

This is code-golf so the shortest solution wins.

Builtins are allowed!

You are allowed to use your own definitions of truthy and falsy values in the output list. If you choose to do so, please state your definitions.

The input will be a non-empty list of non-negative integers.

You are free to choose between outputting only one of the sieves or multiple or even all of them. As long as each sieve is valid, it will be accepted.

答:
Java, 96 bytes

void s(int[]a){for(int i=0,j,n=a.length,b=1;i<n;a[i++]=b,b=1)for(j=i+1;j<n;)b=a[i]==a[j++]?0:b;}
```

<p>Modifies the array in-place. Favours the last occurrence.</p>

<p>The truthy value is <code>1</code> while the falsey value is <code>0</code>.</p>

<p>Verify all testcases.</p>

<p>Ungolfed:</p>

<pre class="lang-java prettyprint-override"><code>void sieve(int[]a){
    int n = a.length;
    for(int i=0;i<n;i++){
        int b = 1;
        for(int j=i+1;j<n;j++){
            if(a[i] == a[j]){
                b = 0;
            }
        }
        a[i] = b;
    }
}
</code>```

Title: Distinct Sieves

Body:
Java, 96 bytes

void s(int[]a){for(int i=0,j,n=a.length,b=1;i<n;a[i++]=b,b=1)for(j=i+1;j<n;)b=a[i]==a[j++]?0:b;}

Modifies the array in-place. Favours the last occurrence.

The truthy value is 1 while the falsey value is 0.

Verify all testcases.

Ungolfed:

void sieve(int[]a){
    int n = a.length;
    for(int i=0;i<n;i++){
        int b = 1;
        for(int j=i+1;j<n;j++){
            if(a[i] == a[j]){
                b = 0;
            }
        }
        a[i] = b;
    }
}


问:
Minimum base to count to a string

The Challenge

Input: alphanumeric string. You can assume that the string will only contain the characters [0-9A-Z]. This can come from a parameter, command line, or STDIN. Digits are always before letters in terms of the base. Think like an extended version of HEX.

Output X,Y Such that Y is the minimum base required to parse the string and X is the decimal value of the input string in that base.

Examples

Input: "1"

Output: 1,2

Input: "HELLOWORLD"

Output: 809608041709942,33

Scoring: This is a golf, so shortest code in bytes wins.

答:
PHP (>=5.4), 90

(-2 for an anoynomous function in PHP 7; 74 for a snippet)

```<code>function f($s){$b+=7*(8>$b=ord(max(str_split($s)))-54);return[base_convert($s,$b,10),$b];}
</code>```

Thanks @user34736 for the -54(+8) idea; saved two bytes on my -54/-47 approach.

The function returns an array instead of printing the result.
+/-0 for printing:

```<code>function f($s){$b+=7*(8>$b=ord(max(str_split($s)))-54);echo base_convert($s,$b,10),",$b";}
</code>```

but a return value is easier to test:

```<code>function test($x,$y,$e){static $h='<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';echo"$h<tr><td>$x</td><td>$y</td><td>$e</td><td>",(strcmp($y,$e)?'N':'Y'),"</td></tr>";$h='';}
foreach([1=>'1,2','HELLOWORLD'=>'809608041709942,33','ILOVECODEGOLF'=>'21537319965321352644,32','POTATO'=>'627732894,30','1FISH2FISH'=>'22338345482731,29']as$x=>$e)test($x,implode(',',f($x)),$e);echo'</table>';
</code>```

Title: Minimum base to count to a string

Body:
PHP (>=5.4), 90

(-2 for an anoynomous function in PHP 7; 74 for a snippet)

function f($s){$b+=7*(8>$b=ord(max(str_split($s)))-54);return[base_convert($s,$b,10),$b];}

Thanks @user34736 for the -54(+8) idea; saved two bytes on my -54/-47 approach.

The function returns an array instead of printing the result.
+/-0 for printing:

function f($s){$b+=7*(8>$b=ord(max(str_split($s)))-54);echo base_convert($s,$b,10),",$b";}

but a return value is easier to test:

function test($x,$y,$e){static $h='<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';echo"$h<tr><td>$x</td><td>$y</td><td>$e</td><td>",(strcmp($y,$e)?'N':'Y'),"</td></tr>";$h='';}
foreach([1=>'1,2','HELLOWORLD'=>'809608041709942,33','ILOVECODEGOLF'=>'21537319965321352644,32','POTATO'=>'627732894,30','1FISH2FISH'=>'22338345482731,29']as$x=>$e)test($x,implode(',',f($x)),$e);echo'</table>';


答:
Fuzzy Octo Guacamole, 1 byte

```<code>a
</code>```

A function that takes inputs from the top of the stack and outputs by pushing to the stack.

Example running in the REPL:

```<code>>>> 8 9 :
[8,9]
>>> a :
17
</code>```

Title: Add two numbers

Body:
Fuzzy Octo Guacamole, 1 byte

a

A function that takes inputs from the top of the stack and outputs by pushing to the stack.

Example running in the REPL:

>>> 8 9 :
[8,9]
>>> a :
17


答:
GoLScript, 1 byte (non-competiting)

```<code>K
</code>```

Adds the top 2 numbers on the stack. That's it.

Now how to push them on to the stack, I have no clue. I don't think it's possible.. cough @CᴏɴᴏʀO'Bʀɪᴇɴ cough

Title: Add two numbers

Body:
GoLScript, 1 byte (non-competiting)

K

Adds the top 2 numbers on the stack. That's it.

Now how to push them on to the stack, I have no clue. I don't think it's possible.. cough @CᴏɴᴏʀO'Bʀɪᴇɴ cough


问:
Read numbers in the base of the largest digit and write it using underscores
This isn't as much a "challenge" as "a unique problem that there are no built-in functions to solve." Basically, you need to do this:

Read some lines of numbers from stdin. These lines may contain trailing or preceding whitespace, and there may be empty lines. No lines will contain "just whitespace" other than a newline. Each non-empty line will have exactly one number. This:

```<code> 123

456\t
</code>```

(where \t is a tab) is considered valid input.

Read the numbers in the input in base N+1, where N is the largest digit in any of the lines. In this case, the largest digit is 6, so the numbers would be read in base 7, resulting in 6610 and 23710.

Find the sum of the numbers. The sum of 6610 and 23710 is 30310.

Convert the sum back to base N+1 again. We'd convert 30310 to base 7, which would be 6127.

For each digit, print that many underscores, followed by a space. The last digit should instead be followed by a newline or a space and a newline. In our example, that would be ______ _ __\n or ______ _ __ \n, where \n is the newline character.

Here's an example in Python:

```<code>import sys

def convert_to_base(n, b):
    'Convert `n` to base `b`'
    res = []
    while n:
        res.append(n % b)
        n /= b
    return res[::-1]

# read the lines, discarding empty ones and stripping any whitespace
lines = map(str.strip, filter(None, list(sys.stdin)))
# find the largest digit, and add 1 to it to make our base
base = max(map(max, (map(int, line) for line in lines)))+1
# read the lines in the base and sum them
result = sum(int(line, base) for line in lines)
# print the result in the original base using underscores, separated by spaces
for number in convert_to_base(result, base):
    print '_'*number,
# print a newline
print
</code>```

This is code golf: the shortest program wins!

答:
PHP, <s>188</s> 182

```<code>function f($s){$b=max(str_split($s))+1;foreach(preg_split('/\s/',$s)as$x)$m+=base_convert($x,$b,10);foreach(str_split(base_convert($m,10,$b))as$d)echo' ',str_repeat('_',$d);echo'
</code>```

';}

prints a leading blank instead of a trailing one. if not accepted, add +1.

breakdown:

```<code>function f($s)
{
    $b=max(str_split($s))+1;           // find base
    foreach(preg_split('/\s/',$s)as$x) // extract all words and loop
        $m+=base_convert($x,$b,10);    // convert, sum up
    foreach(str_split(base_convert($m,10,$b))as$d) // convert back, split into array, loop
        echo' ',str_repeat('_',$d);    // print underscores
    echo'
';                                     // append newline
}
</code>```

I wonder if there is a golfier approach to this ...

Body:
PHP, <s>188</s> 182

function f($s){$b=max(str_split($s))+1;foreach(preg_split('/\s/',$s)as$x)$m+=base_convert($x,$b,10);foreach(str_split(base_convert($m,10,$b))as$d)echo' ',str_repeat('_',$d);echo'

';}

prints a leading blank instead of a trailing one. if not accepted, add +1.

breakdown:

function f($s)
{
    $b=max(str_split($s))+1;           // find base
    foreach(preg_split('/\s/',$s)as$x) // extract all words and loop
        $m+=base_convert($x,$b,10);    // convert, sum up
    foreach(str_split(base_convert($m,10,$b))as$d) // convert back, split into array, loop
        echo' ',str_repeat('_',$d);    // print underscores
    echo'
';                                     // append newline
}

I wonder if there is a golfier approach to this ...


答:
Jelly, <s>34</s> 28 bytes

```<code>L€’SḂ
ṙLR$Ṃµ€Ṣ
Œ!ŒṖ€;/Ç€ÑÐḟQ
</code>```

Try it here.

Explanation

Each line in a Jelly program defines a function; the bottom one is “main”.

The first line defines a function that tests whether a cycle product is odd.

```<code>L€      Length of each
  ’     Add 1 to each length
   S    Take the sum
    Ḃ   Modulo 2
</code>```

The second line normalizes a partition of a permutation of [1…n] into a cycle product as follows:

```<code>     µ€    For each list X in the partition:
ṙLR$          Rotate X by each element in [1…length(X)].
    Ṃ         Get the lexicographically smallest element.
              Thus, find the rotation so that the smallest element is in front.
       Ṣ   Sort the cycles in the partition.
</code>```

This will turn e.g. (4 3)(2 5 1) into (1 2 5)(3 4).

Here is the main program. It takes an argument n from the command line, and:

```<code>Œ!              Compute all permutations of [1…n].
  ŒṖ€           Compute all partitions of each permutation.
     ;/         Put them in one big list.
       Ç€       Normalize each of them into a cycle product.
         ÑÐḟ    Reject elements satisfying the top function,
                i.e. keep only even cycle products.
            Q   Remove duplicates.
</code>```

Title: Print the "even" permutations of symmetric group Sn in cyclic notation

Body:
THE TASK

DEFINITIONS

Consider the points {1,2,3,4,5} and all their permutations. We can find the total number of possible permutations of these 5 points by a simple trick: Imaging filling 5 slots with these points, the first slot will have 5 possible numbers, the second 4 (as one has been used to fill the first slot) the third 3 and so on. Thus the total number of Permutations is 5*4*3*2*1; this would be 5! permutations or 120 permutations. We can think of this as the symmetric group S5, and then Symmetric Group Sn would have n! or (n*n-1*n-2...*1) permutations.

An "even" permutation is one where there is an even number of even length cycles. It is easiest to understand when written in cyclic notation, for example (1 2 3)(4 5) permutes 1->2->3->1 and 4->5->4 and has one 3 length cycle (1 2 3) and one 2 length cycle (4 5). When classifying a permutation as odd or even we ignore odd length cycles and say that this permutation [(1 2 3)(4 5)] is odd as it has an odd number {1} of even length cycles.
Even examples:

(1)(2 3)(4 5) = two 2 length cycle | EVEN |

(1 2 3 4 5) = no even length cycles | EVEN | * note that if no even length cycles are present then the permutation is even.

Odd Examples:

(1 2)(3 4 5) = one 2 length cycle | ODD |

(1)(2 3 4 5) = one 4 length cycle | ODD |

As exactly half of the permutations in any Symmetric Group are even we can call the even group the Alternating Group N, So as S5 = 120 A5 = 60 permutations.

NOTATION

Permutations should, for this at least, be written in cyclic notation where each cycle is in different parenthesis and each cycle goes in ascending order. For example (1 2 3 4 5) not (3 4 5 1 2). And for cycles with a single number, such as: (1)(2 3 4)(5) the single / fixed points can be excluded meaning (1)(2 3 4)(5) = (2 3 4). But the identity {the point where all points are fixed (1)(2)(3)(4)(5)} should be written as () just to represent it.

THE CHALLENGE

I would like you to, in as little code possible, take any positive integer as an input {1,2,3,4...} and display all the permutations of the Alternating Group An where n is the input / all the even permutations of Sn. For example:

```<code>Input = 3
()
(1 2 3)
(1 3 2)
</code>```

and

```<code>Input = 4
()
(1 2)(3 4)
(1 3)(2 4)
(1 4)(2 3)
(1 2 3)
(1 3 2)
(1 2 4)
(1 4 2)
(1 3 4)
(1 4 3)
(2 3 4)
(2 4 3)
</code>```

And as with in the examples I would like for all cycles of one length to be elided, and as for the identity: outputs of  nothing, () {not only brackets but with whatever you are using to show different permutations} or id are acceptable.

EXTRA READING

You can find more information here:

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

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

GOOD LUCK

And as this is codegolf whoever can print the Alternating Group An's permutations in the shortest bytes wins.

Body:
Jelly, <s>34</s> 28 bytes

L€’SḂ
ṙLR$Ṃµ€Ṣ
Œ!ŒṖ€;/Ç€ÑÐḟQ

Try it here.

Explanation

Each line in a Jelly program defines a function; the bottom one is “main”.

The first line defines a function that tests whether a cycle product is odd.

L€      Length of each
  ’     Add 1 to each length
   S    Take the sum
    Ḃ   Modulo 2

The second line normalizes a partition of a permutation of [1…n] into a cycle product as follows:

     µ€    For each list X in the partition:
ṙLR$          Rotate X by each element in [1…length(X)].
    Ṃ         Get the lexicographically smallest element.
              Thus, find the rotation so that the smallest element is in front.
       Ṣ   Sort the cycles in the partition.

This will turn e.g. (4 3)(2 5 1) into (1 2 5)(3 4).

Here is the main program. It takes an argument n from the command line, and:

Œ!              Compute all permutations of [1…n].
  ŒṖ€           Compute all partitions of each permutation.
     ;/         Put them in one big list.
       Ç€       Normalize each of them into a cycle product.
         ÑÐḟ    Reject elements satisfying the top function,
                i.e. keep only even cycle products.
            Q   Remove duplicates.


答:
APL, 32 bytes

```<code>{⊃1↓⍵/⍨1=+/∘.=⍨(⎕UCS ⍵)+32×⍵∊⎕A}
</code>```

Try it || All test cases

Explanation:

```<code>                (⎕UCS ⍵)+32×⍵∊⎕A  Add 32 to uppercase letters
            ∘.=⍨                    Make an equality matrix
          +/                        Check how many matches
    ⍵/⍨1=                           Keep elements with 1 match
  1↓                                Drop the first one
⊃                                   Return the second one
</code>```

I was about to post it with 16 bytes, but the I realized it had to be case-insensitive...

Body:
APL, 32 bytes

{⊃1↓⍵/⍨1=+/∘.=⍨(⎕UCS ⍵)+32×⍵∊⎕A}

Try it || All test cases

Explanation:

                (⎕UCS ⍵)+32×⍵∊⎕A  Add 32 to uppercase letters
            ∘.=⍨                    Make an equality matrix
          +/                        Check how many matches
    ⍵/⍨1=                           Keep elements with 1 match
  1↓                                Drop the first one
⊃                                   Return the second one

I was about to post it with 16 bytes, but the I realized it had to be case-insensitive...


问:
Sequence avoiding near collision

Task

Find a sequence of all numbers between min and max where every number differs from every other number in the sequence by at least "d" digits.

Example of sub-sequence

For min = 0, max = 1000 and d = 2, the following is part of one possible solution sequence:

123 ← Good

132 ← Good

145 ← Good

146 ← Bad

Notes

This is a bit practical. I was thinking about this as a problem that has kept cropping up over the years. Basically it's a pattern in URL shorteners / prize codes / conference room codes / etc...

I'd like to be able to hand out codes from a list, and have each code be:
A - Simple to type, and B - Be somewhat unlikely to accidentally conflict with another code because of a typing mistake.

There's no reason to work in base ten. I've expressed the problem that way for clarity, but in real cases we'd take advantage of letters as well.

Sub-Note

This is not that practical. If you use just six "digits" (allowing numbers and capital letters), then you have over two billion choices. That seems like plenty for most cases except for the URL shortener. Still I was thinking it would be nice to be able to generate a random number from that space and be able to quickly check that it was at least "d" different from all others that had been handed out up to that point. Generating a solution sequence is not quite the same problem, but it seemed interesting and I'm hoping that someone comes up with a clever way to structure the data in order to make it efficient to search for these near collisions.

答:
Here's a terrible, brute force way of generating a sequence. I haven't attempted to do much to make it fast, though there are probably several simple gains to be had here. I'm trying to think of a way to make this at least a couple of orders of magnitude faster rather than finding improvements of a few percent.</p>

```<code>public static IEnumerable<int> GetDifferentCodes(int min, int digits, int minDifference)
{
    var max = Math.Pow(10, digits) - 1;
    var goodCodes = new List<int>();
    var goodCodeDigits = new List<short[]>();

    for (var i = min; i < max; i++)
    {
        var newDigits = GetDigits(i, digits);

        if (!goodCodeDigits.All(goodCode => HasMinDiff(goodCode, newDigits, digits, minDifference)))
            continue;
        goodCodes.Add(i);
        goodCodeDigits.Add(newDigits);
    }
    return goodCodes;
}

private static readonly int[] Powers = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000};

private static short[] GetDigits(int num, int digits)
{
    var ret = new short[digits];
    for (var i = 0; i < digits; i++)
    {
        ret[i] = (short) ((num/Powers[i]) % 10);
    }
    return ret;
}

private static bool HasMinDiff(short[] goodDigits, short[] digitsToCheck, int digits, int minDiff)
{
    var difference = 0;
    for (var i = 0; i < digits; i++)
    {
        if (goodDigits[i] == digitsToCheck[i]) continue;
        if (++difference >= minDiff) return true;
    }
    return false;
}
</code>```

Title: Sequence avoiding near collision

Body:
Here's a terrible, brute force way of generating a sequence. I haven't attempted to do much to make it fast, though there are probably several simple gains to be had here. I'm trying to think of a way to make this at least a couple of orders of magnitude faster rather than finding improvements of a few percent.

public static IEnumerable<int> GetDifferentCodes(int min, int digits, int minDifference)
{
    var max = Math.Pow(10, digits) - 1;
    var goodCodes = new List<int>();
    var goodCodeDigits = new List<short[]>();

    for (var i = min; i < max; i++)
    {
        var newDigits = GetDigits(i, digits);

        if (!goodCodeDigits.All(goodCode => HasMinDiff(goodCode, newDigits, digits, minDifference)))
            continue;
        goodCodes.Add(i);
        goodCodeDigits.Add(newDigits);
    }
    return goodCodes;
}

private static readonly int[] Powers = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000};

private static short[] GetDigits(int num, int digits)
{
    var ret = new short[digits];
    for (var i = 0; i < digits; i++)
    {
        ret[i] = (short) ((num/Powers[i]) % 10);
    }
    return ret;
}

private static bool HasMinDiff(short[] goodDigits, short[] digitsToCheck, int digits, int minDiff)
{
    var difference = 0;
    for (var i = 0; i < digits; i++)
    {
        if (goodDigits[i] == digitsToCheck[i]) continue;
        if (++difference >= minDiff) return true;
    }
    return false;
}


答:
APL, <s>21</s> 20 bytes

```<code>{∊⌽¨⍵⊂⍨e⍲¯1↓0,e←2|⍵}
</code>```

Try it || All test cases

Explanation:

```<code>                  2|⍵ Select all the odd numbers
                e←    Save that to e
              0,      Append a 0
           ¯1↓        Delete the last element
         e⍲           NAND it with the original list of odd numbers
     ⍵⊂⍨             Partition the list: (even)(even)(odd odd odd)(even)
  ⌽¨                 Reverse each partition
 ∊                    Flatten the list
</code>```

Edit: Saved a ~ thanks to De Morgan's laws

Title: Reverse odd runs

Body:
APL, <s>21</s> 20 bytes

{∊⌽¨⍵⊂⍨e⍲¯1↓0,e←2|⍵}

Try it || All test cases

Explanation:

                  2|⍵ Select all the odd numbers
                e←    Save that to e
              0,      Append a 0
           ¯1↓        Delete the last element
         e⍲           NAND it with the original list of odd numbers
     ⍵⊂⍨             Partition the list: (even)(even)(odd odd odd)(even)
  ⌽¨                 Reverse each partition
 ∊                    Flatten the list

Edit: Saved a ~ thanks to De Morgan's laws


答:
Pyth, 14 bytes

```<code>s_McQshMBx0%R2

           %R2Q   Take all elements of the input list modulo 2
         x0       Get the indices of all 0s
      hMB         Make a list of these indices and a list of these indices plus 1
     s            Concatenate them
   cQ             Chop the input list at all those positions
 _M               Reverse all resulting sublists
s                 Concatenate them
</code>```

Test cases

Title: Reverse odd runs

Body:
Pyth, 14 bytes

s_McQshMBx0%R2

           %R2Q   Take all elements of the input list modulo 2
         x0       Get the indices of all 0s
      hMB         Make a list of these indices and a list of these indices plus 1
     s            Concatenate them
   cQ             Chop the input list at all those positions
 _M               Reverse all resulting sublists
s                 Concatenate them

Test cases


问:
Tips for code-golfing in C#
What general tips do you have for golfing in C#? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C# (e.g. "remove comments" is not an answer). Please post one tip per answer.

-- borrowed from marcog's idea ;)

答:
In C#, we are not allowed to do if(n%2) to check if n is a even number. If we do, we get a cannot implicity convert int to bool. A naive handling would be to do:

```<code>if(n%2==0)
</code>```

A better way is to use:

```<code>if(n%2<1)
</code>```

I used this to gain one byte here.

note that this only works for positive numbers, as -1%2==-1, it is considered even with this method.

ContentLicense: CC BY-SA 2.5

Title: Tips for code-golfing in C#

Body:
In C#, we are not allowed to do if(n%2) to check if n is a even number. If we do, we get a cannot implicity convert int to bool. A naive handling would be to do:

if(n%2==0)

A better way is to use:

if(n%2<1)

I used this to gain one byte here.

note that this only works for positive numbers, as -1%2==-1, it is considered even with this method.


答:
JavaScript (Firefox 30-57), <s>220</s> <s>218</s> <s>212</s> 211 bytes

```<code>f=(a,p)=>a[2]?[for(i of a)for(j of f(a.filter(m=>m!=i),p,p^=1))[i,...j]]:[[a[p],a[p^1]]]
</code>```

Sadly 88 bytes only suffices to generate the alternating group as a list of permutations of a, so it then costs me an additional <s>132</s> <s>130</s> <s>124</s> 123 bytes to convert the output to the desired format:

```<code>n=>f([...Array(n).keys()],0).map(a=>a.map((e,i)=>{if(e>i){for(s+='('+-~i;e>i;[a[e],e]=[,a[e]])s+=','+-~e;s+=')'}},s='')&&s)
</code>```

I've managed to trim my ES6 version down to <s>222</s> <s>216</s> 215 bytes:

```<code>n=>(g=(a,p,t=[])=>a[2]?a.map(e=>g(a.filter(m=>m!=e),p,[...t,e],p^=1)):[...t,a[p],a[p^1]].map((e,i,a)=>{if(e>i){for(s+='('+-~i;e>i;[a[e],e]=[,a[e]])s+=','+-~e;s+=')'}},s='')&&r.push(s))([...Array(n).keys(r=[])],0)&&r
</code>```

Body:
JavaScript (Firefox 30-57), <s>220</s> <s>218</s> <s>212</s> 211 bytes

f=(a,p)=>a[2]?[for(i of a)for(j of f(a.filter(m=>m!=i),p,p^=1))[i,...j]]:[[a[p],a[p^1]]]

Sadly 88 bytes only suffices to generate the alternating group as a list of permutations of a, so it then costs me an additional <s>132</s> <s>130</s> <s>124</s> 123 bytes to convert the output to the desired format:

n=>f([...Array(n).keys()],0).map(a=>a.map((e,i)=>{if(e>i){for(s+='('+-~i;e>i;[a[e],e]=[,a[e]])s+=','+-~e;s+=')'}},s='')&&s)

I've managed to trim my ES6 version down to <s>222</s> <s>216</s> 215 bytes:

n=>(g=(a,p,t=[])=>a[2]?a.map(e=>g(a.filter(m=>m!=e),p,[...t,e],p^=1)):[...t,a[p],a[p^1]].map((e,i,a)=>{if(e>i){for(s+='('+-~i;e>i;[a[e],e]=[,a[e]])s+=','+-~e;s+=')'}},s='')&&r.push(s))([...Array(n).keys(r=[])],0)&&r


问:
Print a table of numbers in decimal and 2**i bases
Computers live by binary. All programmers know binary.

But the 2**x bases are often neglected as non-practical, while they have beautiful relations to binary.

To show you one example of such a beatiful relation, 19 will be my testimonial.

```<code>19 10011 103 23 13 j
</code>```

19 is decimal, included for clarity.

10011 is 19 in binary.

103, in base 4 is made starting from binary this way:

log2(4) == 2, let us remember two.

Pad 10011 so that it has a multiple of 2 length -> 010011

Take digits 2 by 2 from left to right and treat them as 2-digits binary numbers:

01 -> 1

00 -> 0

11 -> 3

Done, 10011 in base-4 is 103.

For base 8, do the same but 3-by-3 as log2(8) = 3.

Pad 010011

010 -> 2

011 -> 3

23, Done.

For base 16, do the same but 4-by-4 as log2(16) = 4.

Pad 00010011

0001 -> 1

0011 -> 3

13, Done.

Task

Given a max number as input, you shall output a table

```<code>base-ten-i base-two-i base-four-i base-eight-i base-sixteen-i base-thirtytwo-i
</code>```

for i that goes from 0 to n inclusive. Binary numbers are the epitome of the absolute minimum needed to work, so your code should be as short as possible.

Restrictions and bonuses

Base-ten -> binary and binary -> Base-ten built-ins are considered loopholes as Base-a -> Base-b are.

If you generate all the 2**i (for i > 2) bases by using the relations over mentioned you get a *0.6 bonus, but general base conversions (written by yourself) are allowed.

Example table

```<code>> 32
0 0 0 0 0 0
1 1 1 1 1 1
2 10 2 2 2 2
3 11 3 3 3 3
4 100 10 4 4 4
5 101 11 5 5 5
6 110 12 6 6 6
7 111 13 7 7 7
8 1000 20 10 8 8
9 1001 21 11 9 9
10 1010 22 12 a a
11 1011 23 13 b b
12 1100 30 14 c c
13 1101 31 15 d d
14 1110 32 16 e e
15 1111 33 17 f f
16 10000 100 20 10 g
17 10001 101 21 11 h
18 10010 102 22 12 i
19 10011 103 23 13 j
20 10100 110 24 14 k
21 10101 111 25 15 l
22 10110 112 26 16 m
23 10111 113 27 17 n
24 11000 120 30 18 o
25 11001 121 31 19 p
26 11010 122 32 1a q
27 11011 123 33 1b r
28 11100 130 34 1c s
29 11101 131 35 1d t
30 11110 132 36 1e u
31 11111 133 37 1f v
32 100000 200 40 20 10
</code>```

答:
PHP, <s>232</s> <s>230</s> <s>233</s> 217 * 0.6 = 130.2

no chance beating the golfing languages, but I liked the challenge.

```<code>for(;$d<=$n;$d++){echo'
',$d|0;for($k=$d,$b='';$k;$k>>=1)$b=($k&1).$b;for($w=1;$w<6;$w++,print" $z"|' 0')for($z='',$k=strlen($b);-$w<$k-=$w;$z=($e>9?chr($e+87):$e).$z)for($e=0,$y=1,$j=$w;$j--;$y*=2) $e+=$y*$b[$j+$k];}
</code>```

usage: prepend $n=32; or replace $n with 32 (or any other non-negative integer); call via cli

If that is not accepted, replace $n with $_GET[n] (+6/+3.6) and call either in the browser

or on cli with php-cgi -f bases.php -n=32

Replace the line break with
 or prepend ```</code> to test in browser</li>
<li>may throw notices for undefined variables and unintialized string offsets in newer PHP versions.<br />
Remove E_NOTICE from error_reporting (prepend <code>error_reporting(0);</code>) to suppress them.</li>
<li>tested in 5.6</li>
</ul>
<p>break down:</p>
```for(;$d<=$n;$d++) // loop decimal $d from 0 to $n
{
    echo'
',$d|0; // print line break and decimal
    for($k=$d,$b='';$k;$k>>=1)$b=($k&1).$b; // convert $d to binary
    for($w=1;$w<6;$w++,
        print" $z"|' 0' // print number generated in inner loop (echo doesn´t work here)
    )
        for($z='',$k=strlen($b);-$w<$k-=$w; // loop from end by $w
            $z=($e>9?chr($e+87):$e).$z // prepend digit created in body
        )
            for($e=0,$y=1,$j=$w;$j--;$y*=2) $e+=$y*$b[$j+$k]; // convert chunk to 2**$w
}
```
<p>major edit:</p>
<ul>
<li>used some index magic to revamp the inner loop -> now works backwards on the whole string (no more padding, no more splitting or copying the binary)</li>
<li>moved parts of the loop bodies to the heads to eliminate braces</li>
<li>had to add <s>7</s> 4 bytes to fix the decimal 0 results after the revamp</li>
</ul>
<h1>non-bonus version, 142 bytes</h1>
```for(;$d<=$n;$d++,print'
',$d|0)for($w=1;$w<6;$w++,print" $z"|' 0')for($k=$d,$y=1,$z='';$k&&$y<<=$w;$k>>=$w)$z=(9<($e=$k%$y)?chr($e+87):$e).$z;
```

PHP beats Python?

Even if I added the 6 (3.6) bytes to make the snippet a program, I´d still beat Python (223*0.6=133.8 or 148 non-bonus vs. 158). Amazing.

Body:
PHP, <s>232</s> <s>230</s> <s>233</s> 217 * 0.6 = 130.2

no chance beating the golfing languages, but I liked the challenge.

for(;$d<=$n;$d++){echo'
',$d|0;for($k=$d,$b='';$k;$k>>=1)$b=($k&1).$b;for($w=1;$w<6;$w++,print" $z"|' 0')for($z='',$k=strlen($b);-$w<$k-=$w;$z=($e>9?chr($e+87):$e).$z)for($e=0,$y=1,$j=$w;$j--;$y*=2) $e+=$y*$b[$j+$k];}

usage: prepend $n=32; or replace $n with 32 (or any other non-negative integer); call via cli

If that is not accepted, replace $n with $_GET[n] (+6/+3.6) and call either in the browser

or on cli with php-cgi -f bases.php -n=32

Replace the line break with <br> or prepend <pre> to test in browser

may throw notices for undefined variables and unintialized string offsets in newer PHP versions.

Remove E_NOTICE from error_reporting (prepend error_reporting(0);) to suppress them.

tested in 5.6

break down:

for(;$d<=$n;$d++) // loop decimal $d from 0 to $n
{
    echo'
',$d|0; // print line break and decimal
    for($k=$d,$b='';$k;$k>>=1)$b=($k&1).$b; // convert $d to binary
    for($w=1;$w<6;$w++,
        print" $z"|' 0' // print number generated in inner loop (echo doesn´t work here)
    )
        for($z='',$k=strlen($b);-$w<$k-=$w; // loop from end by $w
            $z=($e>9?chr($e+87):$e).$z // prepend digit created in body
        )
            for($e=0,$y=1,$j=$w;$j--;$y*=2) $e+=$y*$b[$j+$k]; // convert chunk to 2**$w
}

major edit:

used some index magic to revamp the inner loop -> now works backwards on the whole string (no more padding, no more splitting or copying the binary)

moved parts of the loop bodies to the heads to eliminate braces

had to add <s>7</s> 4 bytes to fix the decimal 0 results after the revamp

non-bonus version, 142 bytes

for(;$d<=$n;$d++,print'
',$d|0)for($w=1;$w<6;$w++,print" $z"|' 0')for($k=$d,$y=1,$z='';$k&&$y<<=$w;$k>>=$w)$z=(9<($e=$k%$y)?chr($e+87):$e).$z;

PHP beats Python?

Even if I added the 6 (3.6) bytes to make the snippet a program, I´d still beat Python (223*0.6=133.8 or 148 non-bonus vs. 158). Amazing.


答:
Python3 - 189, 167, 166 150 bytes

```<code>for i in range(int(input())+1):f=lambda b,n=i,c="0123456789abcdefghijklmnopqrstuv":n<b and c[n]or f(b,n//b)+c[n%b];print(i,f(2),f(4),f(8),f(16),f(32))
</code>```

Saved 16 bytes with the help of @LeakyNun!

Bonus version - 296 * 0.6 = 177.6 279 * 0.6 = 167.4 bytes

```<code>p=lambda b,c:"".join(str(int(b[i:i+c],2))for i in range(0,len(b),c))
z=lambda s:len(s)%2 and s or "0"+s
for i in range(int(input())+1):f=lambda n,b,c="0123456789abcdefghijklmnopqrstuv":n<b and c[n]or f(n//b,b)+c[n%b];v=f(i,2);d=z(v);print(i,v,p(d,2),p(d,3),p(d,4),p(d,5),f(i,32))
</code>```

Slightly more readable version of the bonus version.

```<code>p=lambda b,c:"".join(str(int(b[i:i+c],2))for i in range(0,len(b),c))
z=lambda s:len(s)%2 and s or "0"+s
for i in range(int(input())+1):
    f=lambda n,b,c="0123456789abcdefghijklmnopqrstuv":n<b and c[n] or f(n//b,b) + c[n%b]
    v=f(i,2)
    d=z(v)
    print(i,v,p(d,2),p(d,3),p(d,4),p(d,5),f(i,32))
</code>```

Title: Print a table of numbers in decimal and 2**i bases

Body:
Computers live by binary. All programmers know binary.

But the 2**x bases are often neglected as non-practical, while they have beautiful relations to binary.

To show you one example of such a beatiful relation, 19 will be my testimonial.

```<code>19 10011 103 23 13 j
</code>```

19 is decimal, included for clarity.

10011 is 19 in binary.

103, in base 4 is made starting from binary this way:

log2(4) == 2, let us remember two.

Pad 10011 so that it has a multiple of 2 length -> 010011

Take digits 2 by 2 from left to right and treat them as 2-digits binary numbers:

01 -> 1

00 -> 0

11 -> 3

Done, 10011 in base-4 is 103.

For base 8, do the same but 3-by-3 as log2(8) = 3.

Pad 010011

010 -> 2

011 -> 3

23, Done.

For base 16, do the same but 4-by-4 as log2(16) = 4.

Pad 00010011

0001 -> 1

0011 -> 3

13, Done.

Task

Given a max number as input, you shall output a table

```<code>base-ten-i base-two-i base-four-i base-eight-i base-sixteen-i base-thirtytwo-i
</code>```

for i that goes from 0 to n inclusive. Binary numbers are the epitome of the absolute minimum needed to work, so your code should be as short as possible.

Restrictions and bonuses

Base-ten -> binary and binary -> Base-ten built-ins are considered loopholes as Base-a -> Base-b are.

If you generate all the 2**i (for i > 2) bases by using the relations over mentioned you get a *0.6 bonus, but general base conversions (written by yourself) are allowed.

Example table

```<code>> 32
0 0 0 0 0 0
1 1 1 1 1 1
2 10 2 2 2 2
3 11 3 3 3 3
4 100 10 4 4 4
5 101 11 5 5 5
6 110 12 6 6 6
7 111 13 7 7 7
8 1000 20 10 8 8
9 1001 21 11 9 9
10 1010 22 12 a a
11 1011 23 13 b b
12 1100 30 14 c c
13 1101 31 15 d d
14 1110 32 16 e e
15 1111 33 17 f f
16 10000 100 20 10 g
17 10001 101 21 11 h
18 10010 102 22 12 i
19 10011 103 23 13 j
20 10100 110 24 14 k
21 10101 111 25 15 l
22 10110 112 26 16 m
23 10111 113 27 17 n
24 11000 120 30 18 o
25 11001 121 31 19 p
26 11010 122 32 1a q
27 11011 123 33 1b r
28 11100 130 34 1c s
29 11101 131 35 1d t
30 11110 132 36 1e u
31 11111 133 37 1f v
32 100000 200 40 20 10
</code>```

Body:
Python3 - 189, 167, 166 150 bytes

for i in range(int(input())+1):f=lambda b,n=i,c="0123456789abcdefghijklmnopqrstuv":n<b and c[n]or f(b,n//b)+c[n%b];print(i,f(2),f(4),f(8),f(16),f(32))

Saved 16 bytes with the help of @LeakyNun!

Bonus version - 296 * 0.6 = 177.6 279 * 0.6 = 167.4 bytes

p=lambda b,c:"".join(str(int(b[i:i+c],2))for i in range(0,len(b),c))
z=lambda s:len(s)%2 and s or "0"+s
for i in range(int(input())+1):f=lambda n,b,c="0123456789abcdefghijklmnopqrstuv":n<b and c[n]or f(n//b,b)+c[n%b];v=f(i,2);d=z(v);print(i,v,p(d,2),p(d,3),p(d,4),p(d,5),f(i,32))

Slightly more readable version of the bonus version.

p=lambda b,c:"".join(str(int(b[i:i+c],2))for i in range(0,len(b),c))
z=lambda s:len(s)%2 and s or "0"+s
for i in range(int(input())+1):
    f=lambda n,b,c="0123456789abcdefghijklmnopqrstuv":n<b and c[n] or f(n//b,b) + c[n%b]
    v=f(i,2)
    d=z(v)
    print(i,v,p(d,2),p(d,3),p(d,4),p(d,5),f(i,32))


答:
APL, 6 bytes

```<code>⍳∘⍴∊⍳⍨
</code>```

Try it

Explanation:

```<code>   ⍳⍨  For each character in the string, get the index of its first occurrence
⍳∘⍴     Make a list 1 .. length of input
  ∊    Check if each index is present
</code>```

Title: Distinct Sieves

Body:
Given a list of integers, create a boolean mask such that the true indices can be used to filter the distinct values from the list. Which index is selected as the true one does not matter as long as only one of them is selected for each set of indices corresponding to identical values.

The input will be a non-empty list of non-negative integers in a format suitable for your language and the output will be a list of boolean values following the specification above. You are allowed to use your own definitions of truthy and falsy values in the output list.

In my examples below, I define 1 to be truthy and 0 to be falsy.

```<code>[5, 4, 7, 1]  Input
[1, 1, 1, 1]  Output
              Select only the values with with true indicies in the sieve
[5  4  7  1]  Contains zero duplicate values

[5, 9, 7, 5, 6, 0, 5]
[0, 1, 1, 1, 1, 1, 0]
[   9, 7, 5, 6, 0   ]
</code>```

Test Cases

When there is an or, it means that there are multiple valid outputs. If there is a trailing ellipsis ... after the or, it means that not all of the possible outputs were listed.

```<code>[0] = [1]

[55] = [1]

[32, 44] = [1, 1]

[0, 0] = [1, 0] or [0, 1]

[9001, 9001, 9001] = [1, 0 , 0] or [0, 1, 0] or [0, 0, 1]

[5, 4, 7, 1] = [1, 1, 1, 1]

[1, 2, 3, 4, 3, 5] = [1, 1, 1, 1, 0, 1] or
                     [1, 1, 0, 1, 1, 1]

[5, 9, 7, 5, 6, 0, 5] = [1, 1, 1, 0, 1, 1, 0] or
                        [0, 1, 1, 1, 1, 1, 0] or
                        [0, 1, 1, 0, 1, 1, 1]

[0, 8, 6, 6, 3, 8, 7, 2] = [1, 1, 1, 0, 1, 0, 1, 1] or
                           [1, 0, 0, 1, 1, 1, 1, 1] or
                           [1, 0, 1, 0, 1, 1, 1, 1] or
                           [1, 1, 0, 1, 1, 0, 1, 1]

[45, 47, 47, 45, 24, 24, 24, 8, 47, 41, 47, 88]
= [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1] or ...

[154, 993, 420, 154, 154, 689, 172, 417, 790, 175, 790, 790, 154, 172, 175, 175, 420, 417, 154, 175, 172, 175, 172, 993, 689, 993, 993, 790]
= [1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] or ...
</code>```

Rules

This is code-golf so the shortest solution wins.

Builtins are allowed!

You are allowed to use your own definitions of truthy and falsy values in the output list. If you choose to do so, please state your definitions.

The input will be a non-empty list of non-negative integers.

You are free to choose between outputting only one of the sieves or multiple or even all of them. As long as each sieve is valid, it will be accepted.

Body:
APL, 6 bytes

⍳∘⍴∊⍳⍨

Try it

Explanation:

   ⍳⍨  For each character in the string, get the index of its first occurrence
⍳∘⍴     Make a list 1 .. length of input
  ∊    Check if each index is present