问:
Count up folks!

Introduction

It may sound strange, but we haven't got ONE challenge for counting from 1 to n, inclusive.

This is not the same thing. That one is a (closed) not well-explained challenge.

This is not the same thing. That one is about counting up indefinitely.

Challenge

Write a program or function that prints every integer from 1 to n inclusive.

Rules

You can get n any way.

You can assume that n will always be a positive integer.

You can get n in any base, but you should always output in decimal.

Output must be separated by any character (or pattern) not in 0123456789. Non-decimal leading or trailing characters are allowed (for example when using arrays such as [1, 2, 3, 4, 5, 6]).

Standard loopholes are denied.

We want to find the shortest approach in each language, not the shortest language, so I will not accept any answer.

You must update your answer(s) after this edit, answers posted before the last edit must comply with the change rule about standard loopholes (I didn't want to deny them, but I didn't want to make the community roar, so I denied them).

You can use any post-dating language version (or language). You cannot use any language or language version made just for this challenge.

Bonuses

20%

Your program must be able to count at least up to 18446744073709551615 (2^64-1). For example, if a new datatype is the only way to support big integers, you must construct it. If your language does not have any way to support huge integers up to 2^64-1, the upper limit of that particular language must be supported instead.

EDIT: I've changed the limit from 2^64 to 2^64-1 to allow more answers.

EDIT: I made the 2^64-1 rule a bonus, since there has not been much interest in this challenge. If your answer supports 2^64-1, you can now edit it to include the bonus. Also, you can post an answer not supporting it, if it is shorter.

答:
Piet, 64 Codels

With codelsize 20:

Npiet trace images

First loop:

Remaining trace for n=2:

Notes

No Piet answer yet? Let me fix that with my first ever Piet program! This could probably be shorter with better rolls and less pointer manipulation though...

The upper supported limit depends on the implementation of the interpreter. It would theoretically be possible to support arbitraryly large numbers with the right interpreter.

The delimeter is ETX (Ascii 3), however this cannot be properly displayed in this answer so I'll just leave them out. It works in the console:

Output

```<code>Input:  1
Output: 1

Input:  20
Output: 1234567891011121314151617181920

Input:  100
Output: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100

Undefined behaviour:

Input:  -1
Output: 1

Input:  0
Output: 1
</code>```

Npiet trace for n=2

```<code>trace: step 0  (0,0/r,l nR -> 1,0/r,l lB):
action: in(number)
? 2
trace: stack (1 values): 2

trace: step 1  (1,0/r,l lB -> 2,0/r,l nB):
action: push, value 1
trace: stack (2 values): 1 2

trace: step 2  (2,0/r,l nB -> 3,0/r,l nG):
action: duplicate
trace: stack (3 values): 1 1 2

trace: step 3  (3,0/r,l nG -> 4,0/r,l dY):
action: out(number)
1
trace: stack (2 values): 1 2

trace: step 4  (4,0/r,l dY -> 5,0/r,l lY):
action: push, value 1
trace: stack (3 values): 1 1 2

trace: step 5  (5,0/r,l lY -> 6,0/r,l lG):
action: add
trace: stack (2 values): 2 2

trace: step 6  (6,0/r,l lG -> 7,0/r,l lR):
action: duplicate
trace: stack (3 values): 2 2 2

trace: step 7  (7,0/r,l lR -> 10,0/r,l nR):
action: push, value 3
trace: stack (4 values): 3 2 2 2

trace: step 8  (10,0/r,l nR -> 12,0/r,l dR):
action: push, value 2
trace: stack (5 values): 2 3 2 2 2

trace: step 9  (12,0/r,l dR -> 13,0/r,l lB):
action: roll
trace: stack (3 values): 2 2 2

trace: step 10  (13,0/r,l lB -> 14,0/r,l lG):
action: duplicate
trace: stack (4 values): 2 2 2 2

trace: step 11  (14,0/r,l lG -> 15,2/d,r nG):
action: push, value 3
trace: stack (5 values): 3 2 2 2 2

trace: step 12  (15,2/d,r nG -> 15,3/d,r dG):
action: push, value 1
trace: stack (6 values): 1 3 2 2 2 2

trace: step 13  (15,3/d,r dG -> 14,3/l,l lR):
action: roll
trace: stack (4 values): 2 2 2 2

trace: step 14  (14,3/l,l lR -> 13,1/l,r lC):
action: greater
trace: stack (3 values): 0 2 2

trace: step 15  (13,1/l,r lC -> 11,1/l,r nC):
action: push, value 3
trace: stack (4 values): 3 0 2 2

trace: step 16  (11,1/l,r nC -> 10,1/l,r lB):
action: multiply
trace: stack (3 values): 0 2 2

trace: step 17  (10,1/l,r lB -> 9,1/l,r nY):
action: pointer
trace: stack (2 values): 2 2

trace: step 18  (9,1/l,r nY -> 7,1/l,r dY):
action: push, value 2
trace: stack (3 values): 2 2 2

trace: step 19  (7,1/l,r dY -> 6,1/l,r lY):
action: push, value 1
trace: stack (4 values): 1 2 2 2

trace: step 20  (6,1/l,r lY -> 5,1/l,r nM):
action: roll
trace: stack (2 values): 2 2

trace: step 21  (5,1/l,r nM -> 4,1/l,r dM):
action: push, value 3
trace: stack (3 values): 3 2 2

trace: step 22  (4,1/l,r dM -> 3,1/l,r lG):
action: pointer
trace: stack (2 values): 2 2

trace: step 23  (3,1/d,r lG -> 2,3/l,l nG):
action: push, value 3
trace: stack (3 values): 3 2 2

trace: step 24  (2,3/l,l nG -> 2,2/u,r lY):
action: out(char)

trace: stack (2 values): 2 2
trace: white cell(s) crossed - continuing with no command at 2,0...

trace: step 25  (2,2/u,r lY -> 2,0/u,r nB):

trace: step 26  (2,0/u,r nB -> 3,0/r,l nG):
action: duplicate
trace: stack (3 values): 2 2 2

trace: step 27  (3,0/r,l nG -> 4,0/r,l dY):
action: out(number)
2
trace: stack (2 values): 2 2

trace: step 28  (4,0/r,l dY -> 5,0/r,l lY):
action: push, value 1
trace: stack (3 values): 1 2 2

trace: step 29  (5,0/r,l lY -> 6,0/r,l lG):
action: add
trace: stack (2 values): 3 2

trace: step 30  (6,0/r,l lG -> 7,0/r,l lR):
action: duplicate
trace: stack (3 values): 3 3 2

trace: step 31  (7,0/r,l lR -> 10,0/r,l nR):
action: push, value 3
trace: stack (4 values): 3 3 3 2

trace: step 32  (10,0/r,l nR -> 12,0/r,l dR):
action: push, value 2
trace: stack (5 values): 2 3 3 3 2

trace: step 33  (12,0/r,l dR -> 13,0/r,l lB):
action: roll
trace: stack (3 values): 2 3 3

trace: step 34  (13,0/r,l lB -> 14,0/r,l lG):
action: duplicate
trace: stack (4 values): 2 2 3 3

trace: step 35  (14,0/r,l lG -> 15,2/d,r nG):
action: push, value 3
trace: stack (5 values): 3 2 2 3 3

trace: step 36  (15,2/d,r nG -> 15,3/d,r dG):
action: push, value 1
trace: stack (6 values): 1 3 2 2 3 3

trace: step 37  (15,3/d,r dG -> 14,3/l,l lR):
action: roll
trace: stack (4 values): 2 3 2 3

trace: step 38  (14,3/l,l lR -> 13,1/l,r lC):
action: greater
trace: stack (3 values): 1 2 3

trace: step 39  (13,1/l,r lC -> 11,1/l,r nC):
action: push, value 3
trace: stack (4 values): 3 1 2 3

trace: step 40  (11,1/l,r nC -> 10,1/l,r lB):
action: multiply
trace: stack (3 values): 3 2 3

trace: step 41  (10,1/l,r lB -> 9,1/l,r nY):
action: pointer
trace: stack (2 values): 2 3
trace: white cell(s) crossed - continuing with no command at 9,3...

trace: step 42  (9,1/d,r nY -> 9,3/d,l nR):
</code>```

Title: Count up folks!

Body:
Piet, 64 Codels

With codelsize 20:

Npiet trace images

First loop:

Remaining trace for n=2:

Notes

No Piet answer yet? Let me fix that with my first ever Piet program! This could probably be shorter with better rolls and less pointer manipulation though...

The upper supported limit depends on the implementation of the interpreter. It would theoretically be possible to support arbitraryly large numbers with the right interpreter.

The delimeter is ETX (Ascii 3), however this cannot be properly displayed in this answer so I'll just leave them out. It works in the console:

Output

Input:  1
Output: 1

Input:  20
Output: 1234567891011121314151617181920

Input:  100
Output: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100

Undefined behaviour:

Input:  -1
Output: 1

Input:  0
Output: 1

Npiet trace for n=2

trace: step 0  (0,0/r,l nR -> 1,0/r,l lB):
action: in(number)
? 2
trace: stack (1 values): 2

trace: step 1  (1,0/r,l lB -> 2,0/r,l nB):
action: push, value 1
trace: stack (2 values): 1 2

trace: step 2  (2,0/r,l nB -> 3,0/r,l nG):
action: duplicate
trace: stack (3 values): 1 1 2

trace: step 3  (3,0/r,l nG -> 4,0/r,l dY):
action: out(number)
1
trace: stack (2 values): 1 2

trace: step 4  (4,0/r,l dY -> 5,0/r,l lY):
action: push, value 1
trace: stack (3 values): 1 1 2

trace: step 5  (5,0/r,l lY -> 6,0/r,l lG):
action: add
trace: stack (2 values): 2 2

trace: step 6  (6,0/r,l lG -> 7,0/r,l lR):
action: duplicate
trace: stack (3 values): 2 2 2

trace: step 7  (7,0/r,l lR -> 10,0/r,l nR):
action: push, value 3
trace: stack (4 values): 3 2 2 2

trace: step 8  (10,0/r,l nR -> 12,0/r,l dR):
action: push, value 2
trace: stack (5 values): 2 3 2 2 2

trace: step 9  (12,0/r,l dR -> 13,0/r,l lB):
action: roll
trace: stack (3 values): 2 2 2

trace: step 10  (13,0/r,l lB -> 14,0/r,l lG):
action: duplicate
trace: stack (4 values): 2 2 2 2

trace: step 11  (14,0/r,l lG -> 15,2/d,r nG):
action: push, value 3
trace: stack (5 values): 3 2 2 2 2

trace: step 12  (15,2/d,r nG -> 15,3/d,r dG):
action: push, value 1
trace: stack (6 values): 1 3 2 2 2 2

trace: step 13  (15,3/d,r dG -> 14,3/l,l lR):
action: roll
trace: stack (4 values): 2 2 2 2

trace: step 14  (14,3/l,l lR -> 13,1/l,r lC):
action: greater
trace: stack (3 values): 0 2 2

trace: step 15  (13,1/l,r lC -> 11,1/l,r nC):
action: push, value 3
trace: stack (4 values): 3 0 2 2

trace: step 16  (11,1/l,r nC -> 10,1/l,r lB):
action: multiply
trace: stack (3 values): 0 2 2

trace: step 17  (10,1/l,r lB -> 9,1/l,r nY):
action: pointer
trace: stack (2 values): 2 2

trace: step 18  (9,1/l,r nY -> 7,1/l,r dY):
action: push, value 2
trace: stack (3 values): 2 2 2

trace: step 19  (7,1/l,r dY -> 6,1/l,r lY):
action: push, value 1
trace: stack (4 values): 1 2 2 2

trace: step 20  (6,1/l,r lY -> 5,1/l,r nM):
action: roll
trace: stack (2 values): 2 2

trace: step 21  (5,1/l,r nM -> 4,1/l,r dM):
action: push, value 3
trace: stack (3 values): 3 2 2

trace: step 22  (4,1/l,r dM -> 3,1/l,r lG):
action: pointer
trace: stack (2 values): 2 2

trace: step 23  (3,1/d,r lG -> 2,3/l,l nG):
action: push, value 3
trace: stack (3 values): 3 2 2

trace: step 24  (2,3/l,l nG -> 2,2/u,r lY):
action: out(char)

trace: stack (2 values): 2 2
trace: white cell(s) crossed - continuing with no command at 2,0...

trace: step 25  (2,2/u,r lY -> 2,0/u,r nB):

trace: step 26  (2,0/u,r nB -> 3,0/r,l nG):
action: duplicate
trace: stack (3 values): 2 2 2

trace: step 27  (3,0/r,l nG -> 4,0/r,l dY):
action: out(number)
2
trace: stack (2 values): 2 2

trace: step 28  (4,0/r,l dY -> 5,0/r,l lY):
action: push, value 1
trace: stack (3 values): 1 2 2

trace: step 29  (5,0/r,l lY -> 6,0/r,l lG):
action: add
trace: stack (2 values): 3 2

trace: step 30  (6,0/r,l lG -> 7,0/r,l lR):
action: duplicate
trace: stack (3 values): 3 3 2

trace: step 31  (7,0/r,l lR -> 10,0/r,l nR):
action: push, value 3
trace: stack (4 values): 3 3 3 2

trace: step 32  (10,0/r,l nR -> 12,0/r,l dR):
action: push, value 2
trace: stack (5 values): 2 3 3 3 2

trace: step 33  (12,0/r,l dR -> 13,0/r,l lB):
action: roll
trace: stack (3 values): 2 3 3

trace: step 34  (13,0/r,l lB -> 14,0/r,l lG):
action: duplicate
trace: stack (4 values): 2 2 3 3

trace: step 35  (14,0/r,l lG -> 15,2/d,r nG):
action: push, value 3
trace: stack (5 values): 3 2 2 3 3

trace: step 36  (15,2/d,r nG -> 15,3/d,r dG):
action: push, value 1
trace: stack (6 values): 1 3 2 2 3 3

trace: step 37  (15,3/d,r dG -> 14,3/l,l lR):
action: roll
trace: stack (4 values): 2 3 2 3

trace: step 38  (14,3/l,l lR -> 13,1/l,r lC):
action: greater
trace: stack (3 values): 1 2 3

trace: step 39  (13,1/l,r lC -> 11,1/l,r nC):
action: push, value 3
trace: stack (4 values): 3 1 2 3

trace: step 40  (11,1/l,r nC -> 10,1/l,r lB):
action: multiply
trace: stack (3 values): 3 2 3

trace: step 41  (10,1/l,r lB -> 9,1/l,r nY):
action: pointer
trace: stack (2 values): 2 3
trace: white cell(s) crossed - continuing with no command at 9,3...

trace: step 42  (9,1/d,r nY -> 9,3/d,l nR):


问:
Golf Text into DNA

Text to DNA golf

Challenge

Convert input into a DNA output.

Algorithm

Convert text into ASCII code points (e.g. codegolf -> [99, 111, 100, 101, 103, 111, 108, 102])

String the ASCII codes together (e.g. 99111100101103111108102)

Convert to binary (e.g. 10100111111001101001011010001000011001101011011110000110010111111011000000110)

Pad 0s onto the end to make an even number of characters (e.g. 101001111110011010010110100010000110011010110111100001100101111110110000001100)

Replace 00 with A, 01 with C, 10 with G, and 11 with T (e.g. GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA)

Output

Test Cases

```<code>codegolf > GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA
ppcg > GGCTAATTGTCGCACTT
} > TTGG (padding)
</code>```

Specifications

This is code-golf

Your program must accept spaces in input.

Your program must work for codegolf.

答:
Python 3, 130 bytes.

Saved 2 bytes thanks to vaultah.

Saved 6 bytes thanks to Kevin Lau - not Kenny.

I hate how hard it is to convert to binary in python.

def f(x):c=bin(int(''.join(map(str,map(ord,x)))))[2:];return''.join('ACGT'[int(z+y,2)]for z,y in zip(*[iter(c+'0'*(len(c)%2))]*2))
```
<p>Test cases:</p>
<pre class="lang-python prettyprint-override"><code>assert f('codegolf') == 'GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA'
assert f('ppcg') == 'GGCTAATTGTCGCACTT'
</code>```

ContentLicense: CC BY-SA 3.0

Title: Golf Text into DNA

Body:
Python 3, 130 bytes.

Saved 2 bytes thanks to vaultah.

Saved 6 bytes thanks to Kevin Lau - not Kenny.

I hate how hard it is to convert to binary in python.

def f(x):c=bin(int(''.join(map(str,map(ord,x)))))[2:];return''.join('ACGT'[int(z+y,2)]for z,y in zip(*[iter(c+'0'*(len(c)%2))]*2))

Test cases:

assert f('codegolf') == 'GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA'
assert f('ppcg') == 'GGCTAATTGTCGCACTT'


答:
05AB1E, 23 bytes

Code:

```<code>SÇJb00«2÷¨C3210"TGCA"‡á
</code>```

Uses CP-1252 encoding. Try it online!.

Title: Golf Text into DNA

Body:
Text to DNA golf

Challenge

Convert input into a DNA output.

Algorithm

Convert text into ASCII code points (e.g. codegolf -> [99, 111, 100, 101, 103, 111, 108, 102])

String the ASCII codes together (e.g. 99111100101103111108102)

Convert to binary (e.g. 10100111111001101001011010001000011001101011011110000110010111111011000000110)

Pad 0s onto the end to make an even number of characters (e.g. 101001111110011010010110100010000110011010110111100001100101111110110000001100)

Replace 00 with A, 01 with C, 10 with G, and 11 with T (e.g. GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA)

Output

Test Cases

```<code>codegolf > GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA
ppcg > GGCTAATTGTCGCACTT
} > TTGG (padding)
</code>```

Specifications

This is code-golf

Your program must accept spaces in input.

Your program must work for codegolf.

Body:
05AB1E, 23 bytes

Code:

SÇJb00«2÷¨C3210"TGCA"‡á

Uses CP-1252 encoding. Try it online!.


问:
KOTH: Every coin has two sides
Final results available

Introduction

After my previous KOTH with heavy themes (fantasy war, worldwide pandemic...), I'm back with a new lighthearted game. This time, you are facing off in a "board game-like" situation. A pile of upside down coins is placed at the center of a really big table, and you are determined to get your share of the loot!

Glossary

Coins: Tokens that can either be flipped or unflipped.

  Unflipped: Coins placed on the table with their value pointing down. This is the default state of the coins.

  Flipped: Coins placed on the table with their value pointing up.

  Local: Refers to your pile of coins.

  Global: Refers to the pile of coins at the center.

Principle

At the start of the game, each player starts with 0 points and 0 coins (flipped or unflipped). The game is turn-based. During their turn, players can take up to 3 actions interacting either with the pile of coins at the center of the table, their own pile of coins or with other players.

Play order is defined randomly at the start of the game. The order of the players in the argument list represents the turn order, and it goes from left to right in that list. "Next" and "Previous" refer respectively to "on the right in that list" and "on the left in that list" with a loop if you're the last of either side.

The game lasts for 50 rounds or until there are 0 coins at the center at the end of a player turn (meaning that you will finish your 3 actions even if the pile is empty after your first action, and you can put back coins to let the game continue). The starting number of global coins is defined randomly with this formula:

```<code>(2 ^ nb_players) + (nb_players * 10) - random(1 + (nb_players ^ 2))`
</code>```

Each action will get you points (or make you lose some) and at the end of the game, each coin you have will be added to your points (-1 for unflipped, +2 for flipped). The player with the highest score wins.

The controller provides you with input via command arguments, and your program has to output via stdout.

Syntax

Input

Each time your program is called, it will receive arguments in this format:

Round;YourPlayerId;Coins;PlayerId_Points_Flipped_Unflipped;PlayerId_Points_Flipped_Unflipped;...

Rounds are 1-indexed.

Example input

6;2;52;1_20_3_12;0_-2_0_1;2_12_1_0

Here, you see it is the 6th round and you are player 2. There are 52 coins in the central pile. You have 12 points, 1 flipped coin and 0 unflipped coin. Points can be negative.

Output

You have to output three characters (no space, no separator), which each correspond to one action you'll take this turn. The order of the characters determine the order of the actions. You can output the same actions multiple times. In case there is not enough coins to complete your action, it will use the maximum of available coins and count points only for the coins used.

N: Do Nothing

1: Take 1 coin from the central pile [Effects: +1 local unflipped / -1 point / -1 global unflipped]

2: Take 2 coins from the central pile [Effects: +2 local unflipped / -2 points / -2 global unflipped]

3: Take 3 coins from the central pile [Effects: +3 local unflipped / -3 points / -3 global unflipped]

A: Put back 1 coin from your pile [Effects: -1 local unflipped / +1 point / +1 global unflipped]

B: Put back 2 coins from your pile [Effects: -2 local unflipped / +2 points / +2 global unflipped]

C: Put back 3 coins from your pile [Effects: -3 local unflipped / +3 points / +3 global unflipped]

X: Remove 1 coin from your pile [Effects: -1 local unflipped / 0 point]

Y: Remove 2 coins from your pile [Effects: -2 local unflipped / 0 point]

Z: Remove 3 coins from your pile [Effects: -3 local unflipped / 0 point]

R: Rotate coins to previous player [Effects: -1 point per unflipped received, +2 points per flipped received / applies to all players]

T: Rotate coins to next player [Effects: -1 point per unflipped received, +2 points per flipped received / applies to all players]

F: Flip 1 coin [Effects: -1 local unflipped / +1 local flipped / +2 point]

U: Unflip 1 coin [Effects: +1 local unflipped / -1 local flipped / -2 point]

Example output

2FF : Takes two coins and flips two coin, scoring -2 + 2 + 2 = 2 points

If your output is incorrect, controller will assume NNN.

Controller

You can find the controller on GitHub. It also contains two samplebots, written in Java.
To make it run, check out the project and open it in your Java IDE. The entry point in the main method of the class Game. Java 8 required.

To add bots, first you need either the compiled version for Java (.class files) or the sources for interpreted languages. Place them in the root folder of the project. Then, create a new Java class in the players package (you can take example on the already existing bots). This class must implement Player to override the method String getCmd(). The String returned is the shell command to run your bots. You can for example make a Ruby bot work with this command : return "C:\Ruby\bin\ruby.exe MyBot.rb";. Finally, add the bot in the players array at the top of the Game class.

Rules

Bots should not be written to beat or support specific other bots.

Writing to files is allowed. Please write to"yoursubmissionname.txt", the folder will be emptied before a game starts. Other external resources are disallowed.

Your submission has 1 second to respond.

Provide commands to compile and run your submissions.

Supported Languages

I'll try and support every language, but it needs to be available online for free. Please provide instructions for installation if you're not using a "mainstream" language.

As of right now, I can run : Java 6-7-8, PHP, Ruby, Perl, Python 2-3, Lua, R, node.js, Haskell, Kotlin, C++ 11.

Final results

These are the results of 100 games (points are added up) :

```<code>1. BirdInTheHand: 1017790
2. Balance: 851428
3. SecondBest: 802316
4. Crook: 739080
5. Jim: 723440
6. Flipper: 613290
7. Wheeler: 585516
8. Oracle: 574916
9. SimpleBot: 543665
10. TraderBot: 538160
11. EgoisticalBot: 529567
12. RememberMe: 497513
13. PassiveBot: 494441
14. TheJanitor: 474069
15. GreedyRotation: 447057
16. Devil: 79212
17. Saboteur: 62240
</code>```

Individual results of the games are available here : http://pasted.co/63f1e924 (with starting coins and number of rounds per game).

A bounty of 50 reputations is awarded to the winner : Bird In The Hand by Martin Büttner.

Thank you all for your participation, see you next KOTH~

答:
Saboteur, Python 2

import random
moves = '3R'
print '33' + ''.join(random.choice(moves))
```

The randomness means it probably won't sabotage very well, but later I think I'll have it wait til the 'end' (how many turns/coins are left) and THEN rotate, after looking at the nearby reachable players to steal from... actually only doing one rotation seems really poor, considering other people are also likely to use rotations. I don't think this'll work very well...

Title: KOTH: Every coin has two sides

Body:
Saboteur, Python 2

import random
moves = '3R'
print '33' + ''.join(random.choice(moves))

The randomness means it probably won't sabotage very well, but later I think I'll have it wait til the 'end' (how many turns/coins are left) and THEN rotate, after looking at the nearby reachable players to steal from... actually only doing one rotation seems really poor, considering other people are also likely to use rotations. I don't think this'll work very well...


Title: Golf Text into DNA

Body:
Ruby, 80 bytes

->s{s=s.bytes.join.to_i.to_s 2;s+=?0*(s.size%2)
s.gsub(/../){"ACGT"[$&.to_i 2]}}


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

```<code>OVBs2UḄị“GCTA
</code>```

Try it online! or verify all test cases.

How it works

```<code>OVBs2UḄị“GCTA    Main link. Argument: s (string)

O                Ordinal; replace each character with its code point.
 V               Eval. This converts the list to a string before evaluating, so it
                 returns the integer that results of concatenating all the digits.
  B              Binary; convert from integer to base 2.
   s2            Split into chunks of length 2.
     U           Upend; reverse the digits of each chunk.
                 Reversing means that we would have to conditionally PREPEND a zero
                 to the last chunk, which makes no difference for base conversion.
      Ḅ          Unbinary; convert each chunk from base 2 to integer.
                 `UḄ' maps:
                     [0, 1   ] -> [1,    0] -> 2
                     [1, 0(?)] -> [0(?), 1] -> 1
                     [1, 1   ] -> [1,    1] -> 3
                     [0, 0(?)] -> [0(?), 0] -> 0
       ị“GCTA    Replace each number by the character at that index.
                 Indexing is 1-based, so the indices are [1, 2, 3, 0].
</code>```

Title: Golf Text into DNA

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

OVBs2UḄị“GCTA

Try it online! or verify all test cases.

How it works

OVBs2UḄị“GCTA    Main link. Argument: s (string)

O                Ordinal; replace each character with its code point.
 V               Eval. This converts the list to a string before evaluating, so it
                 returns the integer that results of concatenating all the digits.
  B              Binary; convert from integer to base 2.
   s2            Split into chunks of length 2.
     U           Upend; reverse the digits of each chunk.
                 Reversing means that we would have to conditionally PREPEND a zero
                 to the last chunk, which makes no difference for base conversion.
      Ḅ          Unbinary; convert each chunk from base 2 to integer.
                 `UḄ' maps:
                     [0, 1   ] -> [1,    0] -> 2
                     [1, 0(?)] -> [0(?), 1] -> 1
                     [1, 1   ] -> [1,    1] -> 3
                     [0, 0(?)] -> [0(?), 0] -> 0
       ị“GCTA    Replace each number by the character at that index.
                 Indexing is 1-based, so the indices are [1, 2, 3, 0].


答:
Java, 194 bytes

```<code>String a(int[]a){String s="",r=s;for(int i:a)s+=i;s=new BigInteger(s).toString(2)+0;for(int i=0,y,n=48;i<(s.length()/2)*2;r+=s.charAt(i++)==n?y==n?'A':'G':y==n?'C':'T')y=s.charAt(i++);return r;}
</code>```

Ungolfed

```<code>String a(int[] a) {
    String s = "", r = s;
    for (int i : a) s += i;
    s = new BigInteger(s).toString(2) + 0;
    for (int i = 0, y, n = 48; i < (s.length() / 2) * 2;
        r += s.charAt(i++) == n
                 ? y == n
                 ? 'A'
                 : 'G'
                 : y == n
                 ? 'C'
                 : 'T')
        y = s.charAt(i++);
    return r;
}
</code>```

Note

Input is an array of chars (which should count as a form of String), parameter is of type int[] because thats one byte saved over char[].

Output

```<code>Input:  codegolf
Output: GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA

Input:  .
Output: GTG

Input:  }
Output: TTGG

Input:  wow
Output: TGATAGTTGTGCTG

Input:  programming puzzles
Output: GTGTCAGAGTTGAAGGCCGTTCCGCAGTGCATTTGGCTCGTCTGGTGTCTACTAGCCTGCGAGAGGAGTTACTTTGGATCCTTGACTTGT
</code>```

Title: Golf Text into DNA

Body:
Java, 194 bytes

String a(int[]a){String s="",r=s;for(int i:a)s+=i;s=new BigInteger(s).toString(2)+0;for(int i=0,y,n=48;i<(s.length()/2)*2;r+=s.charAt(i++)==n?y==n?'A':'G':y==n?'C':'T')y=s.charAt(i++);return r;}

Ungolfed

String a(int[] a) {
    String s = "", r = s;
    for (int i : a) s += i;
    s = new BigInteger(s).toString(2) + 0;
    for (int i = 0, y, n = 48; i < (s.length() / 2) * 2;
        r += s.charAt(i++) == n
                 ? y == n
                 ? 'A'
                 : 'G'
                 : y == n
                 ? 'C'
                 : 'T')
        y = s.charAt(i++);
    return r;
}

Note

Input is an array of chars (which should count as a form of String), parameter is of type int[] because thats one byte saved over char[].

Output

Input:  codegolf
Output: GGCTTGCGGCCGGAGACGCGGTCTGACGCCTTGTAAATA

Input:  .
Output: GTG

Input:  }
Output: TTGG

Input:  wow
Output: TGATAGTTGTGCTG

Input:  programming puzzles
Output: GTGTCAGAGTTGAAGGCCGTTCCGCAGTGCATTTGGCTCGTCTGGTGTCTACTAGCCTGCGAGAGGAGTTACTTTGGATCCTTGACTTGT


问:
Find the positive divisors!

Definition

A number is positive if it is greater than zero.

A number (A) is the divisor of another number (B) if A can divide B with no remainder.

For example, 2 is a divisor of 6 because 2 can divide 6 with no remainder.

Goal

Your task is to write a program/function that takes a positive number and then find all of its divisors.

Restriction

You may not use any built-in related to prime or factorization.

The complexity of your algorithm must not exceed O(sqrt(n)).

Freedom

The output list may contain duplicates.

The output list does not need to be sorted.

Scoring

This is code-golf. Shortest solution in bytes wins.

Testcases

```<code>input    output
1        1
2        1,2
6        1,2,3,6
9        1,3,9
</code>```

答:
c#, 87 bytes

```<code>void f(int r){for(int i=1;i<=Math.Sqrt(r);i++){if(r%i==0)Console.WriteLine(i+" "+r/i);}
</code>```

i do not know if this works for all numbers, i suspect it does.

but the complexity is right, so thats already something isnt it

Title: Find the positive divisors!

Body:
c#, 87 bytes

void f(int r){for(int i=1;i<=Math.Sqrt(r);i++){if(r%i==0)Console.WriteLine(i+" "+r/i);}

i do not know if this works for all numbers, i suspect it does.

but the complexity is right, so thats already something isnt it


Title: Find the positive divisors!

Body:
Definition

A number is positive if it is greater than zero.

A number (A) is the divisor of another number (B) if A can divide B with no remainder.

For example, 2 is a divisor of 6 because 2 can divide 6 with no remainder.

Goal

Your task is to write a program/function that takes a positive number and then find all of its divisors.

Restriction

You may not use any built-in related to prime or factorization.

The complexity of your algorithm must not exceed O(sqrt(n)).

Freedom

The output list may contain duplicates.

The output list does not need to be sorted.

Scoring

This is code-golf. Shortest solution in bytes wins.

Testcases

```<code>input    output
1        1
2        1,2
6        1,2,3,6
9        1,3,9
</code>```

Body:
Ruby, 56 bytes

->n{a=[];(1..Math.sqrt(n)).map{|e|a<<e<<n/e if n%e<1};a}


问:
Tips for golfing in MATL
MATL is a golfing language created by Luis Mendo. MATL has proven to be highly competitive, often beating submissions in other golfing languages such as Pyth, CJam and Jelly.

What are some useful tips for golfing in MATL? (As always, one tip per answer, please!)

For the record, MATL can be tested online here.

Documentation can be found on Github

答:
Get the index of the first non-zero element, if any

The f function gives the indices of all non-zero elements of an array. Often you want the index of the first nonzero element. That would be f1): apply f and pick its first element. But if the original array doesn't contain any non-zero value f will output an empty array ([]), and trying to pick its first element will give an error.

A common, more robust requirement is to obtain the index of the first element if there is at least one, and [] otherwise. This could be done with an if branch after f, but that's byte-expensive. A better way is fX<, that is, apply the minimum function X< to the output of f. X< returns an empty array when its input is an empty array.

Try it online! (Note that an empty array is not displayed at all). Or see an example of this  at work here.

Title: Tips for golfing in MATL


答:
Bird in the Hand, Ruby

def deep_copy(o)
  Marshal.load(Marshal.dump(o))
end

ID = 0
PTS = 1
FLP = 2
UFL = 3

round, id, global, *players = ARGV[0].split(';')
round = round.to_i
id = id.to_i
global = global.to_i

players.map!{ |s| s.split('_').map(&:to_i) }

nplayers = players.size

my_pos = players.find_index { |i, p, f, u| i == id }

state = {
    round: round,
    id: id,
    global: global,
    players: players,
    my_pos: my_pos,
    me: players[my_pos],
    prev_p: players[my_pos-1],
    next_p: players[(my_pos+1)%nplayers],
    ends_game: round == 50 && my_pos == nplayers-1,
    score: 0
}

moves = {
    'N' => ->s{deep_copy(s)},
    '1' => ->s{t = deep_copy(s); coins = [1, t[:global]].min; t[:global] -= coins; t[:me][UFL] += coins; t[:score] -= coins; t},
    '2' => ->s{t = deep_copy(s); coins = [2, t[:global]].min; t[:global] -= coins; t[:me][UFL] += coins; t[:score] -= coins; t},
    '3' => ->s{t = deep_copy(s); coins = [3, t[:global]].min; t[:global] -= coins; t[:me][UFL] += coins; t[:score] -= coins; t},
    'A' => ->s{t = deep_copy(s); coins = [1, t[:me][UFL]].min; t[:global] += coins; t[:me][UFL] -= coins; t[:score] += coins; t},
    'B' => ->s{t = deep_copy(s); coins = [2, t[:me][UFL]].min; t[:global] += coins; t[:me][UFL] -= coins; t[:score] += coins; t},
    'C' => ->s{t = deep_copy(s); coins = [3, t[:me][UFL]].min; t[:global] += coins; t[:me][UFL] -= coins; t[:score] += coins; t},
    'X' => ->s{t = deep_copy(s); coins = [1, t[:me][UFL]].min; t[:me][UFL] -= coins; t},
    'Y' => ->s{t = deep_copy(s); coins = [2, t[:me][UFL]].min; t[:me][UFL] -= coins; t},
    'Z' => ->s{t = deep_copy(s); coins = [3, t[:me][UFL]].min; t[:me][UFL] -= coins; t},
    'F' => ->s{t = deep_copy(s); coins = [1, t[:me][UFL]].min; t[:me][UFL] -= coins; t[:me][FLP] += coins; t[:score] += 2*coins; t},
    'U' => ->s{t = deep_copy(s); coins = [1, t[:me][FLP]].min; t[:me][FLP] -= coins; t[:me][UFL] += coins; t[:score] -= 2*coins; t},
    'R' => ->s{
        t = deep_copy(s)
        (-1...t[:players].size-1).each do |i|
            t[:players][i][FLP] = s[:players][i+1][FLP]
            t[:players][i][UFL] = s[:players][i+1][UFL]
        end
        t[:score] += 2*t[:me][FLP] - t[:me][UFL];
        t
    },
    'T' => ->s{
        t = deep_copy(s)
        (0...t[:players].size).each do |i|
            t[:players][i][FLP] = s[:players][i-1][FLP]
            t[:players][i][UFL] = s[:players][i-1][UFL]
        end
        t[:score] += 2*t[:me][FLP] - t[:me][UFL];
        t
    }
}

results = {}

'N123ABCXYZFURT'.each_char { |c1|
    s1 = moves[c1][state]
    'N123ABCXYZFURT'.each_char { |c2|
        s2 = moves[c2][s1]
        'N123ABCXYZFURT'.each_char { |c3|
            s3 = moves[c3][s2]
            s3[:ends_game] ||= s3[:global] == 0
            results[c1+c2+c3] = s3
        }
    }
}

endingMoves = results.keys.select{|k| results[k][:ends_game]}

endingMoves.each{|k| results[k][:score] += 2*results[k][:me][FLP] - results[k][:me][UFL]}

$> << results.keys.shuffle.max_by {|k| results[k][:score]}
```

If neither of us has a bug in their programs, the main algorithm of this is likely very similar to Mathias's Oracle. Based on the assumption that prior to the final round we can't know which coins we'll end up with, we evaluate the current set of moves purely based on the points received immediately, ignoring completely what sort of coins we'll end up with. Since there are only 143 = 2744 possible move sets we can easily simulate all of them to figure out how many points they'll bring.

However, if a move set ends the game (either because it reduces the global pot to zero, or because this is round 50 and we're the last one to move), then it also takes into account the coins owned at the end of the move set to determine the move set's value. I first considered terminating the game whenever possible, but this would result in the horrible move 333 when there are only 9 coins left in the pot.

If there are multiple move sets giving the same result, we choose a random one. (I might change this to bias it in favour of game-terminating move sets.)

Title: KOTH: Every coin has two sides

Body:
Final results available

Introduction

After my previous KOTH with heavy themes (fantasy war, worldwide pandemic...), I'm back with a new lighthearted game. This time, you are facing off in a "board game-like" situation. A pile of upside down coins is placed at the center of a really big table, and you are determined to get your share of the loot!

Glossary

Coins: Tokens that can either be flipped or unflipped.

  Unflipped: Coins placed on the table with their value pointing down. This is the default state of the coins.

  Flipped: Coins placed on the table with their value pointing up.

  Local: Refers to your pile of coins.

  Global: Refers to the pile of coins at the center.

Principle

At the start of the game, each player starts with 0 points and 0 coins (flipped or unflipped). The game is turn-based. During their turn, players can take up to 3 actions interacting either with the pile of coins at the center of the table, their own pile of coins or with other players.

Play order is defined randomly at the start of the game. The order of the players in the argument list represents the turn order, and it goes from left to right in that list. "Next" and "Previous" refer respectively to "on the right in that list" and "on the left in that list" with a loop if you're the last of either side.

The game lasts for 50 rounds or until there are 0 coins at the center at the end of a player turn (meaning that you will finish your 3 actions even if the pile is empty after your first action, and you can put back coins to let the game continue). The starting number of global coins is defined randomly with this formula:

```<code>(2 ^ nb_players) + (nb_players * 10) - random(1 + (nb_players ^ 2))`
</code>```

Each action will get you points (or make you lose some) and at the end of the game, each coin you have will be added to your points (-1 for unflipped, +2 for flipped). The player with the highest score wins.

The controller provides you with input via command arguments, and your program has to output via stdout.

Syntax

Input

Each time your program is called, it will receive arguments in this format:

Round;YourPlayerId;Coins;PlayerId_Points_Flipped_Unflipped;PlayerId_Points_Flipped_Unflipped;...

Rounds are 1-indexed.

Example input

6;2;52;1_20_3_12;0_-2_0_1;2_12_1_0

Here, you see it is the 6th round and you are player 2. There are 52 coins in the central pile. You have 12 points, 1 flipped coin and 0 unflipped coin. Points can be negative.

Output

You have to output three characters (no space, no separator), which each correspond to one action you'll take this turn. The order of the characters determine the order of the actions. You can output the same actions multiple times. In case there is not enough coins to complete your action, it will use the maximum of available coins and count points only for the coins used.

N: Do Nothing

1: Take 1 coin from the central pile [Effects: +1 local unflipped / -1 point / -1 global unflipped]

2: Take 2 coins from the central pile [Effects: +2 local unflipped / -2 points / -2 global unflipped]

3: Take 3 coins from the central pile [Effects: +3 local unflipped / -3 points / -3 global unflipped]

A: Put back 1 coin from your pile [Effects: -1 local unflipped / +1 point / +1 global unflipped]

B: Put back 2 coins from your pile [Effects: -2 local unflipped / +2 points / +2 global unflipped]

C: Put back 3 coins from your pile [Effects: -3 local unflipped / +3 points / +3 global unflipped]

X: Remove 1 coin from your pile [Effects: -1 local unflipped / 0 point]

Y: Remove 2 coins from your pile [Effects: -2 local unflipped / 0 point]

Z: Remove 3 coins from your pile [Effects: -3 local unflipped / 0 point]

R: Rotate coins to previous player [Effects: -1 point per unflipped received, +2 points per flipped received / applies to all players]

T: Rotate coins to next player [Effects: -1 point per unflipped received, +2 points per flipped received / applies to all players]

F: Flip 1 coin [Effects: -1 local unflipped / +1 local flipped / +2 point]

U: Unflip 1 coin [Effects: +1 local unflipped / -1 local flipped / -2 point]

Example output

2FF : Takes two coins and flips two coin, scoring -2 + 2 + 2 = 2 points

If your output is incorrect, controller will assume NNN.

Controller

You can find the controller on GitHub. It also contains two samplebots, written in Java.
To make it run, check out the project and open it in your Java IDE. The entry point in the main method of the class Game. Java 8 required.

To add bots, first you need either the compiled version for Java (.class files) or the sources for interpreted languages. Place them in the root folder of the project. Then, create a new Java class in the players package (you can take example on the already existing bots). This class must implement Player to override the method String getCmd(). The String returned is the shell command to run your bots. You can for example make a Ruby bot work with this command : return "C:\Ruby\bin\ruby.exe MyBot.rb";. Finally, add the bot in the players array at the top of the Game class.

Rules

Bots should not be written to beat or support specific other bots.

Writing to files is allowed. Please write to"yoursubmissionname.txt", the folder will be emptied before a game starts. Other external resources are disallowed.

Your submission has 1 second to respond.

Provide commands to compile and run your submissions.

Supported Languages

I'll try and support every language, but it needs to be available online for free. Please provide instructions for installation if you're not using a "mainstream" language.

As of right now, I can run : Java 6-7-8, PHP, Ruby, Perl, Python 2-3, Lua, R, node.js, Haskell, Kotlin, C++ 11.

Final results

These are the results of 100 games (points are added up) :

```<code>1. BirdInTheHand: 1017790
2. Balance: 851428
3. SecondBest: 802316
4. Crook: 739080
5. Jim: 723440
6. Flipper: 613290
7. Wheeler: 585516
8. Oracle: 574916
9. SimpleBot: 543665
10. TraderBot: 538160
11. EgoisticalBot: 529567
12. RememberMe: 497513
13. PassiveBot: 494441
14. TheJanitor: 474069
15. GreedyRotation: 447057
16. Devil: 79212
17. Saboteur: 62240
</code>```

Individual results of the games are available here : http://pasted.co/63f1e924 (with starting coins and number of rounds per game).

A bounty of 50 reputations is awarded to the winner : Bird In The Hand by Martin Büttner.

Thank you all for your participation, see you next KOTH~

Body:
Bird in the Hand, Ruby

def deep_copy(o)
  Marshal.load(Marshal.dump(o))
end

ID = 0
PTS = 1
FLP = 2
UFL = 3

round, id, global, *players = ARGV[0].split(';')
round = round.to_i
id = id.to_i
global = global.to_i

players.map!{ |s| s.split('_').map(&:to_i) }

nplayers = players.size

my_pos = players.find_index { |i, p, f, u| i == id }

state = {
    round: round,
    id: id,
    global: global,
    players: players,
    my_pos: my_pos,
    me: players[my_pos],
    prev_p: players[my_pos-1],
    next_p: players[(my_pos+1)%nplayers],
    ends_game: round == 50 && my_pos == nplayers-1,
    score: 0
}

moves = {
    'N' => ->s{deep_copy(s)},
    '1' => ->s{t = deep_copy(s); coins = [1, t[:global]].min; t[:global] -= coins; t[:me][UFL] += coins; t[:score] -= coins; t},
    '2' => ->s{t = deep_copy(s); coins = [2, t[:global]].min; t[:global] -= coins; t[:me][UFL] += coins; t[:score] -= coins; t},
    '3' => ->s{t = deep_copy(s); coins = [3, t[:global]].min; t[:global] -= coins; t[:me][UFL] += coins; t[:score] -= coins; t},
    'A' => ->s{t = deep_copy(s); coins = [1, t[:me][UFL]].min; t[:global] += coins; t[:me][UFL] -= coins; t[:score] += coins; t},
    'B' => ->s{t = deep_copy(s); coins = [2, t[:me][UFL]].min; t[:global] += coins; t[:me][UFL] -= coins; t[:score] += coins; t},
    'C' => ->s{t = deep_copy(s); coins = [3, t[:me][UFL]].min; t[:global] += coins; t[:me][UFL] -= coins; t[:score] += coins; t},
    'X' => ->s{t = deep_copy(s); coins = [1, t[:me][UFL]].min; t[:me][UFL] -= coins; t},
    'Y' => ->s{t = deep_copy(s); coins = [2, t[:me][UFL]].min; t[:me][UFL] -= coins; t},
    'Z' => ->s{t = deep_copy(s); coins = [3, t[:me][UFL]].min; t[:me][UFL] -= coins; t},
    'F' => ->s{t = deep_copy(s); coins = [1, t[:me][UFL]].min; t[:me][UFL] -= coins; t[:me][FLP] += coins; t[:score] += 2*coins; t},
    'U' => ->s{t = deep_copy(s); coins = [1, t[:me][FLP]].min; t[:me][FLP] -= coins; t[:me][UFL] += coins; t[:score] -= 2*coins; t},
    'R' => ->s{
        t = deep_copy(s)
        (-1...t[:players].size-1).each do |i|
            t[:players][i][FLP] = s[:players][i+1][FLP]
            t[:players][i][UFL] = s[:players][i+1][UFL]
        end
        t[:score] += 2*t[:me][FLP] - t[:me][UFL];
        t
    },
    'T' => ->s{
        t = deep_copy(s)
        (0...t[:players].size).each do |i|
            t[:players][i][FLP] = s[:players][i-1][FLP]
            t[:players][i][UFL] = s[:players][i-1][UFL]
        end
        t[:score] += 2*t[:me][FLP] - t[:me][UFL];
        t
    }
}

results = {}

'N123ABCXYZFURT'.each_char { |c1|
    s1 = moves[c1][state]
    'N123ABCXYZFURT'.each_char { |c2|
        s2 = moves[c2][s1]
        'N123ABCXYZFURT'.each_char { |c3|
            s3 = moves[c3][s2]
            s3[:ends_game] ||= s3[:global] == 0
            results[c1+c2+c3] = s3
        }
    }
}

endingMoves = results.keys.select{|k| results[k][:ends_game]}

endingMoves.each{|k| results[k][:score] += 2*results[k][:me][FLP] - results[k][:me][UFL]}

$> << results.keys.shuffle.max_by {|k| results[k][:score]}

If neither of us has a bug in their programs, the main algorithm of this is likely very similar to Mathias's Oracle. Based on the assumption that prior to the final round we can't know which coins we'll end up with, we evaluate the current set of moves purely based on the points received immediately, ignoring completely what sort of coins we'll end up with. Since there are only 143 = 2744 possible move sets we can easily simulate all of them to figure out how many points they'll bring.

However, if a move set ends the game (either because it reduces the global pot to zero, or because this is round 50 and we're the last one to move), then it also takes into account the coins owned at the end of the move set to determine the move set's value. I first considered terminating the game whenever possible, but this would result in the horrible move 333 when there are only 9 coins left in the pot.

If there are multiple move sets giving the same result, we choose a random one. (I might change this to bias it in favour of game-terminating move sets.)


答:
Jim, Ruby

based on Martin Büttner's Greedy Rotation.

```<code>PlayerId = 0
Points = 1
Flipped = 2
Unflipped = 3

round, id, global, *players = ARGV[0].split(';')
round = round.to_i
id = id.to_i
global = global.to_i

if(round == 1)
    print '3FF'
    exit
end

players.map!{ |s| s.split('_').map(&:to_i) }

nplayers = players.size

my_pos = players.find_index { |a| a[PlayerId] == id }

coin_vals = players.map{|a| a[Flipped]*2 - a[Unflipped]}

move = [-1,1].max_by{|s|
    swap_gain = coin_vals.rotate(s)
    scores = (0...nplayers).map{|i|
        swap_gain[i]+players[i][Points]
    }
    scores.delete_at(my_pos)-scores.max
}
if move == 1
    print 'R'
else
    print 'T'
end

print ['1F', 'FF'][rand 2]
</code>```

will rotate one way or the other, depending on what will give him the most points compared to the best other player. Then, he flips for quick cash.

Title: KOTH: Every coin has two sides

Body:
Jim, Ruby

based on Martin Büttner's Greedy Rotation.

PlayerId = 0
Points = 1
Flipped = 2
Unflipped = 3

round, id, global, *players = ARGV[0].split(';')
round = round.to_i
id = id.to_i
global = global.to_i

if(round == 1)
    print '3FF'
    exit
end

players.map!{ |s| s.split('_').map(&:to_i) }

nplayers = players.size

my_pos = players.find_index { |a| a[PlayerId] == id }

coin_vals = players.map{|a| a[Flipped]*2 - a[Unflipped]}

move = [-1,1].max_by{|s|
    swap_gain = coin_vals.rotate(s)
    scores = (0...nplayers).map{|i|
        swap_gain[i]+players[i][Points]
    }
    scores.delete_at(my_pos)-scores.max
}
if move == 1
    print 'R'
else
    print 'T'
end

print ['1F', 'FF'][rand 2]

will rotate one way or the other, depending on what will give him the most points compared to the best other player. Then, he flips for quick cash.


问:
Shortest Unique Substring
Given (on STDIN, as command line arguments, or as function arguments) two distinct non-empty strings, find and return the shortest substring of the first string which is not a substring of the second. If no such substring exists, you may return the empty string, return any string which isn't a substring of the original string, or throw an exception. If you are returning from a function, you may also return null (or undefined, None, etc.) in this case. If multiple such substrings are tied for the shortest, you may return any one of them.

Strings can consist of any printable ascii characters.

Input given on STDIN will be given with one string on each line. At your request, a single empty line may be added at the end of the input.

This is code golf, so the shortest valid program wins.

SOME TEST CASES

INPUT:

```<code>STRING ONE
STRING TWO
</code>```

OUTPUT:

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

INPUT:

```<code>A&&C
A&$C
</code>```

VALID OUTPUTS:

```<code>&&
&C
</code>```

INPUT:

(Two randomly-generated 80-letter strings)

```<code>QIJYXPYWIWESWBRFWUHEERVQFJROYIXNKPKVDDFFZBUNBRZVUEYKLURBJCZJYMINCZNQEYKRADRYSWMH
HAXUDFLYFSLABUCXUWNHPSGQUXMQUIQYRWVIXGNKJGYUTWMLLPRIZDRLFXWKXOBOOEFESKNCUIFHNLFE
</code>```

ALL VALID OUTPUTS:

```<code>AD
BJ
BR
CZ
DD
EE
ER
EY
EY
FF
FJ
FW
FZ
HE
IJ
IN
IW
JC
JR
JY
KL
KP
KR
KV
LU
MH
MI
NB
NQ
OY
PK
PY
QE
QF
QI
RA
RB
RF
RO
RV
RY
RZ
SW
UE
UH
UN
UR
VD
VQ
VU
WB
WE
WI
WU
XN
XP
YI
YK
YK
YM
YS
YW
YX
ZB
ZJ
ZN
ZV
</code>```

答:
Python, 82 bytes

```<code>g=lambda u:{u}|g(u[1:])|g(u[:-1])if u else{''}
f=lambda s,t:min(g(s)-g(t),key=len)
</code>```

Usage: f('A&&C', 'A&$C') -> returns '&&'

Raises ValueError if there is no suitable substring.

Explanation:

g=lambda u:{u}|g(u[1:])|g(u[:-1])if u else{''} recursively creates a set of the substrings of u
  f=lambda s,t:min(g(s)-g(t),key=len) takes the shortest substring from the set difference

Title: Shortest Unique Substring

Body:
Python, 82 bytes

g=lambda u:{u}|g(u[1:])|g(u[:-1])if u else{''}
f=lambda s,t:min(g(s)-g(t),key=len)

Usage: f('A&&C', 'A&$C') -> returns '&&'

Raises ValueError if there is no suitable substring.

Explanation:

g=lambda u:{u}|g(u[1:])|g(u[:-1])if u else{''} recursively creates a set of the substrings of u
  f=lambda s,t:min(g(s)-g(t),key=len) takes the shortest substring from the set difference


问:
Tips for golfing in Factor
What general tips do you have for golfing in Factor? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Factor (e.g. "remove comments" is not an answer).</p>

答:
math.unicode

this thing is a golfing jewel. http://docs.factorcode.org/content/vocab-math.unicode.html

Here, I should let it speak for itself.

```<code>Word    Stack effect    Equivalent   (Byte  Char) Savings (best case)
¬       ( obj -- ? )    not           1     2
²       ( m -- n )      2 ^ , 2^      1     2
³       ( m -- n )      3 ^           1     2
¹       ( m -- n )      1 ^           1     2
¼       ( -- value )    1/4 , 1 4 /   1     2
½       ( -- value )    1/2           1     2
¾       ( -- value )    3/4           1     2
×       ( x y -- z )    *             -1    0
÷       ( x y -- z )    /             -1    0
Π       ( seq -- n )    product       5     6
Σ       ( seq -- n )    sum           1     2
π       ( -- pi )       pi            0     0
φ       ( -- n )        phi           1     2
‰       ( m -- n )      1000 /        4     5
‱       ( m -- n )      10000 /       5     6
ⁿ       ( x y -- z )    ^             -1    0
⅓       ( -- value )    1/3           1     2
⅔       ( -- value )    2/3           1     2
⅕       ( -- value )    1/5           1     2
⅖       ( -- value )    2/5           1     2
⅗       ( -- value )    3/5           1     2
⅘       ( -- value )    4/5           1     2
⅙       ( -- value )    1/6           1     2
⅚       ( -- value )    5/6           1     2
⅛       ( -- value )    1/8           1     2
⅜       ( -- value )    3/8           1     2
⅝       ( -- value )    5/8           1     2
⅞       ( -- value )    7/8           1     2
</code>```

Those are the simple constants. Now for the functions:

```<code>Word    Stack effect        Equivalent  (Byte  Char) Savings (best case)
∀       ( seq quot -- ? )   all?         1    3
∃       ( seq quot -- ? )   any?         1    3
∄       ( seq quot -- ? )   none?        2    4
∈       ( elt seq -- ? )    member?      4    6
∉       ( elt seq -- y )    ∈ ¬          3    2
∋       ( seq elt -- ? )    swap member? 9    11
∌       ( seq elt -- y )    ∋ ¬          3    2
−       ( x y -- z )        -            -1   0
∕       ( x y -- z )        /            -1   0
∖       ( s1 s2 -- set )    diff         1    3
√       ( x -- y )          sqrt         1    3
∛       ( x -- y )          ⅓ ^          2    2
∜       ( x -- y )          ¼ ^          2    2
∞       ( -- value )        1/0.         1    3
∧       ( o1 o2 -- ? )      and          0    2
∨       ( o1 o2 -- ? )      or           -1   1
∩       ( s1 s2 -- set )    intersect    6    8
∪       ( s1 s2 -- set )    union        2    4
≠       ( o1 o2 -- ? )      = ¬          1    2
≤       ( x y -- ? )        <=           -1   1
≥       ( x y -- ? )        >=           -1   1
⊂       ( s1 s2 -- ? )      subset?      4    6
⊃       ( s1 s2 -- ? )      superset?    6    8
⊄       ( s1 s2 -- ? )      ⊂ ¬          3    2
⊅       ( s1 s2 -- ? )      ⊃ ¬          3    2
⊼       ( o1 o2 -- ? )      ∧ ¬          3    2
⊽       ( o1 o2 -- ? )      or ¬         2    3
⌈       ( x -- y )          floor        2    4
⌊       ( x -- y )          ceiling      4    6
</code>```

Yes, I did make that table by hand, and yes, I did the math in my head, so there might be some, er, wrong numbers. I'll go write a program to do it for me, now :P

Title: Tips for golfing in Factor

Body:
math.unicode

this thing is a golfing jewel. http://docs.factorcode.org/content/vocab-math.unicode.html

Here, I should let it speak for itself.

Word    Stack effect    Equivalent   (Byte  Char) Savings (best case)
¬       ( obj -- ? )    not           1     2
²       ( m -- n )      2 ^ , 2^      1     2
³       ( m -- n )      3 ^           1     2
¹       ( m -- n )      1 ^           1     2
¼       ( -- value )    1/4 , 1 4 /   1     2
½       ( -- value )    1/2           1     2
¾       ( -- value )    3/4           1     2
×       ( x y -- z )    *             -1    0
÷       ( x y -- z )    /             -1    0
Π       ( seq -- n )    product       5     6
Σ       ( seq -- n )    sum           1     2
π       ( -- pi )       pi            0     0
φ       ( -- n )        phi           1     2
‰       ( m -- n )      1000 /        4     5
‱       ( m -- n )      10000 /       5     6
ⁿ       ( x y -- z )    ^             -1    0
⅓       ( -- value )    1/3           1     2
⅔       ( -- value )    2/3           1     2
⅕       ( -- value )    1/5           1     2
⅖       ( -- value )    2/5           1     2
⅗       ( -- value )    3/5           1     2
⅘       ( -- value )    4/5           1     2
⅙       ( -- value )    1/6           1     2
⅚       ( -- value )    5/6           1     2
⅛       ( -- value )    1/8           1     2
⅜       ( -- value )    3/8           1     2
⅝       ( -- value )    5/8           1     2
⅞       ( -- value )    7/8           1     2

Those are the simple constants. Now for the functions:

Word    Stack effect        Equivalent  (Byte  Char) Savings (best case)
∀       ( seq quot -- ? )   all?         1    3
∃       ( seq quot -- ? )   any?         1    3
∄       ( seq quot -- ? )   none?        2    4
∈       ( elt seq -- ? )    member?      4    6
∉       ( elt seq -- y )    ∈ ¬          3    2
∋       ( seq elt -- ? )    swap member? 9    11
∌       ( seq elt -- y )    ∋ ¬          3    2
−       ( x y -- z )        -            -1   0
∕       ( x y -- z )        /            -1   0
∖       ( s1 s2 -- set )    diff         1    3
√       ( x -- y )          sqrt         1    3
∛       ( x -- y )          ⅓ ^          2    2
∜       ( x -- y )          ¼ ^          2    2
∞       ( -- value )        1/0.         1    3
∧       ( o1 o2 -- ? )      and          0    2
∨       ( o1 o2 -- ? )      or           -1   1
∩       ( s1 s2 -- set )    intersect    6    8
∪       ( s1 s2 -- set )    union        2    4
≠       ( o1 o2 -- ? )      = ¬          1    2
≤       ( x y -- ? )        <=           -1   1
≥       ( x y -- ? )        >=           -1   1
⊂       ( s1 s2 -- ? )      subset?      4    6
⊃       ( s1 s2 -- ? )      superset?    6    8
⊄       ( s1 s2 -- ? )      ⊂ ¬          3    2
⊅       ( s1 s2 -- ? )      ⊃ ¬          3    2
⊼       ( o1 o2 -- ? )      ∧ ¬          3    2
⊽       ( o1 o2 -- ? )      or ¬         2    3
⌈       ( x -- y )          floor        2    4
⌊       ( x -- y )          ceiling      4    6

Yes, I did make that table by hand, and yes, I did the math in my head, so there might be some, er, wrong numbers. I'll go write a program to do it for me, now :P


答:
Mathematica, 108 bytes

```<code>{"A","C","G","T"}[[IntegerDigits[Mod[Floor@Log2@#,2,1]#&@FromDigits[""<>ToString/@ToCharacterCode@#],4]+1]]&
</code>```

Takes a string as input, and outputs a list of bases.

Title: Golf Text into DNA

Body:
Mathematica, 108 bytes

{"A","C","G","T"}[[IntegerDigits[Mod[Floor@Log2@#,2,1]#&@FromDigits[""<>ToString/@ToCharacterCode@#],4]+1]]&

Takes a string as input, and outputs a list of bases.


问:
Automatic house-builder
Automatic house building nanobots have been fabricated, and it's your job to code them.

Here is the house created by input 7 4 2

```<code>  /-----/|
 /     / |
|-----|  |
|     |  |
|     | /
|_____|/
</code>```

The input is a string containing the house's dimensions.

7 is the width.

```<code>|_____|

---7---
</code>```

4 is the height.

```<code>|
|
|
|
</code>```

2 is the depth

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

Given this input, can you create the house?

Your code must be as small as possible so that it can fit in the robots.

Notes

The smallest dimensions you will be given as input are 3 2 2. Your program can do anything with dimensions that are smaller than 3 2 2.

Testcases

```<code>3 2 10

          /-/|
         / / |
        / / /
       / / /
      / / /
     / / /
    / / /
   / / /
  / / /
 / / /
|-| /
|_|/
</code>```

答:
Python 3.5, 328 326 313 305 295 248 bytes

(Thanks to Kevin Lau for the tip about reducing the size of the ternary statements!)

```<code>def s(w,h,d):R,M=range,max;S,V,L=' |/';O=w-2;D=d-M(0,d-h);Q=h-M(0,h-d);print('\n'.join([S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))]+[V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)]))
</code>```

Takes input as 3 integers in the order of width, height, depth. Will golf more over time wherever I can.

Try it online! (Ideone)

Explanation:

For the purposes of this explanation, assume the function was executed with the arguments (3,2,3) where 3 is the width (w), 2 is the height (h), and 3 is the depth (d). That being said, let me begin by showing the main part of the entire function:

```<code>'\n'.join([S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))]+[V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)])
</code>```

Here, the two lists that make up the entire "house" are created and then joined together by literal new lines (\n). Let's call them list a and list b respectively, and analyze each one of them:

Here is where list a is created:

```<code>[S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))]
</code>```

This list contains the first d lines of the house. Here, i is each number in the range 0=>(d-(d-h))+d-h where d-h=0 if negative or zero. To start, d-i spaces are added to the list, followed by a / and then whatever is returned by a compressed conditional statement. In this conditional statement, w-2 number of spaces are returned if i>1. Otherwise the same number of - are returned. Then, these are followed up by another /, and then spaces, where the number of spaces now depends on whether or not i<=d-(d-h)-1. If it is, then i spaces are added. Otherwise, h-1 spaces are added. Finally, this is all topped off by either a / or a |, where | is added if i<=d-(d-h)-1, otherwise a / is added. In this case of a 3x2x3 prism, this would be returned by list a:

```<code>      /-/|
     / / |
    / / /
</code>```

Here is where list b is created:

```<code>[V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)]`
</code>```

This lists contains the rest of the lines of the prism. In this list, i is each integer in the range (h-(h-d))+h-d=>0 where h-d=0 if negative or zero. To start this list off, firstly a | is added since these lines always start with a |. Then, either a space, -, or _ is added depending on whether or not i=h or i<2. If i<2, then a _ is added. Otherwise, a - is added if i=h, or a space is added if i>h or i<h or i>2. After this decision has been made, then w-2 number of the chosen character is added. After this, another | is added, and then either i-1 or d number of spaces are added. If i>h-(h-d), then a d number of spaces are added. Otherwise, i-1 number of spaces are added. Finally, this is all topped off with either a | or a /, in which a | is added if i>h-(h-d), or a / is added if i<=h-(h-d). In the case of a 3x2x3 prism, list b returns:

```<code>    |-| /
    |_|/
</code>```

After the 2 lists have been created, they are finally joined with literal new lines (\n) using '\n'.join(). This is your completed prism, and in this case, would come to look like this:

```<code>       /-/|
      / / |
     / / /
    |-| /
    |_|/
</code>```

Title: Automatic house-builder

Body:
Python 3.5, 328 326 313 305 295 248 bytes

(Thanks to Kevin Lau for the tip about reducing the size of the ternary statements!)

def s(w,h,d):R,M=range,max;S,V,L=' |/';O=w-2;D=d-M(0,d-h);Q=h-M(0,h-d);print('\n'.join([S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))]+[V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)]))

Takes input as 3 integers in the order of width, height, depth. Will golf more over time wherever I can.

Try it online! (Ideone)

Explanation:

For the purposes of this explanation, assume the function was executed with the arguments (3,2,3) where 3 is the width (w), 2 is the height (h), and 3 is the depth (d). That being said, let me begin by showing the main part of the entire function:

'\n'.join([S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))]+[V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)])

Here, the two lists that make up the entire "house" are created and then joined together by literal new lines (\n). Let's call them list a and list b respectively, and analyze each one of them:

Here is where list a is created:

[S*(d-i)+L+' -'[i<1]*O+L+S*[h-1,i][i<=D-1]+'/|'[i<=D-1]for i in R(D+M(0,d-h))]

This list contains the first d lines of the house. Here, i is each number in the range 0=>(d-(d-h))+d-h where d-h=0 if negative or zero. To start, d-i spaces are added to the list, followed by a / and then whatever is returned by a compressed conditional statement. In this conditional statement, w-2 number of spaces are returned if i>1. Otherwise the same number of - are returned. Then, these are followed up by another /, and then spaces, where the number of spaces now depends on whether or not i<=d-(d-h)-1. If it is, then i spaces are added. Otherwise, h-1 spaces are added. Finally, this is all topped off by either a / or a |, where | is added if i<=d-(d-h)-1, otherwise a / is added. In this case of a 3x2x3 prism, this would be returned by list a:

      /-/|
     / / |
    / / /

Here is where list b is created:

[V+[' -'[i==h],'_'][i<2]*O+V+S*[i-1,d][i>Q]+'/|'[i>Q]for i in R(Q+M(0,h-d),0,-1)]`

This lists contains the rest of the lines of the prism. In this list, i is each integer in the range (h-(h-d))+h-d=>0 where h-d=0 if negative or zero. To start this list off, firstly a | is added since these lines always start with a |. Then, either a space, -, or _ is added depending on whether or not i=h or i<2. If i<2, then a _ is added. Otherwise, a - is added if i=h, or a space is added if i>h or i<h or i>2. After this decision has been made, then w-2 number of the chosen character is added. After this, another | is added, and then either i-1 or d number of spaces are added. If i>h-(h-d), then a d number of spaces are added. Otherwise, i-1 number of spaces are added. Finally, this is all topped off with either a | or a /, in which a | is added if i>h-(h-d), or a / is added if i<=h-(h-d). In the case of a 3x2x3 prism, list b returns:

    |-| /
    |_|/

After the 2 lists have been created, they are finally joined with literal new lines (\n) using '\n'.join(). This is your completed prism, and in this case, would come to look like this:

       /-/|
      / / |
     / / /
    |-| /
    |_|/


答:
Ruby, 70 bytes

Collects all substrings of a certain length from the first string, and if there is one that isn't in the second string, return it.

->a,b{r=p;(1..l=a.size).map{|i|(0...l).map{|j|b[s=a[j,i]]?0:r||=s}};r}
```

Title: Shortest Unique Substring

Body:
Given (on STDIN, as command line arguments, or as function arguments) two distinct non-empty strings, find and return the shortest substring of the first string which is not a substring of the second. If no such substring exists, you may return the empty string, return any string which isn't a substring of the original string, or throw an exception. If you are returning from a function, you may also return null (or undefined, None, etc.) in this case. If multiple such substrings are tied for the shortest, you may return any one of them.

Strings can consist of any printable ascii characters.

Input given on STDIN will be given with one string on each line. At your request, a single empty line may be added at the end of the input.

This is code golf, so the shortest valid program wins.

SOME TEST CASES

INPUT:

```<code>STRING ONE
STRING TWO
</code>```

OUTPUT:

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

INPUT:

```<code>A&&C
A&$C
</code>```

VALID OUTPUTS:

```<code>&&
&C
</code>```

INPUT:

(Two randomly-generated 80-letter strings)

```<code>QIJYXPYWIWESWBRFWUHEERVQFJROYIXNKPKVDDFFZBUNBRZVUEYKLURBJCZJYMINCZNQEYKRADRYSWMH
HAXUDFLYFSLABUCXUWNHPSGQUXMQUIQYRWVIXGNKJGYUTWMLLPRIZDRLFXWKXOBOOEFESKNCUIFHNLFE
</code>```

ALL VALID OUTPUTS:

```<code>AD
BJ
BR
CZ
DD
EE
ER
EY
EY
FF
FJ
FW
FZ
HE
IJ
IN
IW
JC
JR
JY
KL
KP
KR
KV
LU
MH
MI
NB
NQ
OY
PK
PY
QE
QF
QI
RA
RB
RF
RO
RV
RY
RZ
SW
UE
UH
UN
UR
VD
VQ
VU
WB
WE
WI
WU
XN
XP
YI
YK
YK
YM
YS
YW
YX
ZB
ZJ
ZN
ZV
</code>```

ContentLicense: CC BY-SA 4.0


问:
Draw a phi triangle
Clarification: Basically, you need to make this

Euler's totient function has the name phi.

Let's try to calculate phi(8)

First, list all numbers 8 and under backwards, not including 0 or under

```<code>8
7
6
5
4
3
2
1
</code>```

Now find which numbers don't share a factor with 8 (1 doesn't count), and place a # in their place.

```<code>8
#
6
#
4
#
2
#
</code>```

Remove the numbers.

```<code>#

#

#

#
                                                 -
</code>```

Now do this, but string the outputs together in a triangle

```<code>        9
       88
      777
     6666
    55555
   444444
  3333333
 22222222
111111111
---------
123456789
</code>```

# out non-factor sharing numbers

```<code>        9
       8#
      7##
     6#66
    5####
   4#4#4#
  3##3##3
 2#2#2#2#
#########
</code>```

Remove numbers:

```<code>        #
       ##
      #
     ####
    # # #
   ## ##
  # # # #
#########
</code>```

This would be the output for input 9 (since 9 columns.)

Leading + trailing newlines allowed.

答:
SQL (PostGreSQL9.4), 239 <s>291</s> bytes

Creates a prepared statement that can be executed.  I'm sure I can probably take quite a few bytes out of this, but I'll have to pick away at it later.
Does a cross join on a range of 1 to n.  Calculates the GCD in a lateral join.  Where the GCD is 1 and the series A is greater than series B output a '#' otherwise a space.  Aggregate the results up into a string grouped by series B.

```<code>prepare p(int)as
select string_agg(coalesce(CASE WHEN b<=a AND x=1THEN'#'END,' '),'')from generate_series(1,$1)a,generate_series(1,$1)b,LATERAL(SELECT MAX(G)x FROM generate_series(1,LEAST(a,b))g WHERE a%g+b%g=0)g
group by b
order by b desc
</code>```

Run in the following way

```<code>execute p(13)

string_agg
----------------

            #
           ##
          # #
         ## #
        # # #
       ######
      #   # #
     #### ###
    # # # # #
   ## ## ## #
  # # # # # #
#############
</code>```

And cleaned up with

```<code>deallocate p
</code>```

Title: Draw a phi triangle

Body:
SQL (PostGreSQL9.4), 239 <s>291</s> bytes

Creates a prepared statement that can be executed.  I'm sure I can probably take quite a few bytes out of this, but I'll have to pick away at it later.
Does a cross join on a range of 1 to n.  Calculates the GCD in a lateral join.  Where the GCD is 1 and the series A is greater than series B output a '#' otherwise a space.  Aggregate the results up into a string grouped by series B.

prepare p(int)as
select string_agg(coalesce(CASE WHEN b<=a AND x=1THEN'#'END,' '),'')from generate_series(1,$1)a,generate_series(1,$1)b,LATERAL(SELECT MAX(G)x FROM generate_series(1,LEAST(a,b))g WHERE a%g+b%g=0)g
group by b
order by b desc

Run in the following way

execute p(13)

string_agg
----------------

            #
           ##
          # #
         ## #
        # # #
       ######
      #   # #
     #### ###
    # # # # #
   ## ## ## #
  # # # # # #
#############

And cleaned up with

deallocate p


答:
Ruby, 145 bytes

Returns a list of strings. Each element in the list corresponds to a line. If a multiline string must be returned, add 3 bytes to add *$/ right before the last bracket.

```<code>->w,h,d{s=' ';(0..m=d+h-1).map{|i|(i<d ?s*(d-i)+?/:?|)+(i<1||i==d ??-:i==m ??_ :s)*(w-2)+(i<d ? ?/:?|)+(i<h ?s*[i,d].min+?|:s*[m-i,h-1].min+?/)}}
</code>```

Title: Automatic house-builder

Body:
Automatic house building nanobots have been fabricated, and it's your job to code them.

Here is the house created by input 7 4 2

```<code>  /-----/|
 /     / |
|-----|  |
|     |  |
|     | /
|_____|/
</code>```

The input is a string containing the house's dimensions.

7 is the width.

```<code>|_____|

---7---
</code>```

4 is the height.

```<code>|
|
|
|
</code>```

2 is the depth

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

Given this input, can you create the house?

Your code must be as small as possible so that it can fit in the robots.

Notes

The smallest dimensions you will be given as input are 3 2 2. Your program can do anything with dimensions that are smaller than 3 2 2.

Testcases

```<code>3 2 10

          /-/|
         / / |
        / / /
       / / /
      / / /
     / / /
    / / /
   / / /
  / / /
 / / /
|-| /
|_|/
</code>```

Body:
Ruby, 145 bytes

Returns a list of strings. Each element in the list corresponds to a line. If a multiline string must be returned, add 3 bytes to add *$/ right before the last bracket.

->w,h,d{s=' ';(0..m=d+h-1).map{|i|(i<d ?s*(d-i)+?/:?|)+(i<1||i==d ??-:i==m ??_ :s)*(w-2)+(i<d ? ?/:?|)+(i<h ?s*[i,d].min+?|:s*[m-i,h-1].min+?/)}}


问:
Survival Game - Create Your Wolf

The Board

The Board is a two dimensional array of cells. Cells are populated by Animals. Every day, all Animals on the Board simultaneously make one move. If two or more Animals move to the same cell, they fight until one remains. The possible moves and attacks are as follows:

Moves - { Move.UP, Move.RIGHT, Move.DOWN, Move.LEFT, Move.HOLD }

Attacks - { Attack.ROCK, Attack.PAPER, Attack.SCISSORS, Attack.SUICIDE }

Animals fight by playing Rock-Paper-Scissors. Standard rules apply but with two modifications. First, you may commit suicide at any time. Second, a tie is broken pseudorandomly. If more than two Animals collide, two are pseudorandomly selected to fight until one remains.

The Players

Animal behavior and appearance is as follows.

Lion

Represented by the character L. Moves DOWN, RIGHT, then repeats. Pseudorandomly attacks with PAPER or SCISSORS.

Bear

Represented by the character B. Moves DOWN x 4, RIGHT x 4, UP x 4, LEFT x 4, then repeats. Attacks with PAPER.

Stone

Represented by the character S. Moves HOLD. Attacks with ROCK.

Wolf

Only wolves that are submitted as an answer will be included. Represented by 'W'. Moves with any Move. Attacks with any Attack

You will implement the Wolf by filling in the blanks in the following template. All submissions must be in Java and must be contained in a single file. Alternatively, @ProgrammerDan has written a wrapper class that extends the competition to non-java submissions.

// Optional code here
public class Wolf extends Animal {
    // Optional code here
    public Wolf() { super('W'); /* Optional code here */ }
    public Attack fight(char opponent) { /* Required code here. Must return an Attack. */ }
    public Move move() { /* Required code here. Must return a Move. */ }
    // Optional code here
}
```

The submission with the highest average number of living wolves after five trials with 1,000 iterations wins. I will update the winner each time a new answer is posted (but not within the first 24 hours).

Tools

You are provided with a small map of your immediate surroundings in the following form.

char[][] surroundings A zero indexed, 3 by 3 matrix of characters that represent nearby animals. Empty tiles are represented by a space character (' '). You are at surroundings[1][1]. For example, to your right would be surroundings[1][2], and above you is surroundings[0][1]. Your surroundings are updated just before being asked to move, but may be out of date when asked to fight.

You may persist data between invocations of your Wolf, Move requests, and Attack requests. You may neither read from nor modify files created by another Wolf class.

You are provided with the size of the map in the following form

int MAP_SIZE

Assumptions

All submission will compete on the same board against all other submissions as well as Lions, Bears, and Stones

The board is a square with sides of length sqrt(n+3)*20 where n is the number of submissions. All sides wrap, so you can safely move in any direction infinitely.

Simulation begins at ~25% board capacity with 100 of each Animal pseudorandomly distributed across the board.

If an Animal throws an exception when asked to move, that Animal will HOLD

If an Animal throws an exception when asked to fight, that Animal will SUICIDE

If an Animal has no letter when the controller checks, that Animal will immediately die

Getting Started and Testing Instructions

The tools you need to test your submission can be found here. The following files should be available at that link.

ExampleRun.gif - A 5-10 second gif of the program running.

Scoreboard - The latest results of the competition.

Wild.jar - An executable that you can run to watch the premade Animals run around.

Wild.zip - The NetBeans project that houses the controller program with a few premade Animals added. Use this to develop your submission.

WildPopulated.zip - Same as above, but with and about 40 submissions added for you to test against. The GUI has also been removed because of performance issues. The results will simply appear a few moments after you run. The non-Java submissions are commented out because they require extra downloads and effort. Use this to test your submission against the field.

Wolf.txt -  A naive implementation of the Wolf class in Java. You may use and expand that implementation without crediting me.

To test your class:

Download Wild.zip

Rename your Wolf.java and Wolf class to something unique

Add your UniquelyNamedWolf.java file to Wild\src\animals\

In the Wild class, add your class to classes array, like this.

Class[] classes = { UniquelyNamedWolf.class, Bear.class, Lion.class, Stone.class, Wolf.class };

Rebuild and run

I also included another project containing all of the submissions, for testing purposes. I creatively named it "WildPopulated". The three or four non-Java wolves were commented out, because getting them to run requires a lot of extra work and downloads. The one I posted should run with zero extra work. The GUI was also commented out for the sake of speed.

Scoreboard April 22, 2014

The Scoreboard has been moved to Google Drive. View it here. It will be updated on a casual basis (i.e., when I get to it) as new submissions come in.

Side Challenge - NoHOLD

Removed because no (as in zero) participation. It wasn't part of the original challenge anyway.

答:
SittingWolf

```<code>package animals;

public class SittingWolf extends Animal {
    public SittingWolf() {
        super('W');
    }
    public Attack fight(char enemy) {
        switch (enemy) {
            case 'B': // Bear: paper
            case 'L': // Lion: paper or scissors
                return Attack.SCISSORS;
            case 'S': // Stone: rock
                return Attack.PAPER;
            default:
                return Attack.values()[(int)(Math.random() * 3)];
        }
    }
    public Move move() {
        return Move.HOLD;
    }
}
</code>```

Just sits there (hold).

Title: Survival Game - Create Your Wolf

Body:
SittingWolf

package animals;

public class SittingWolf extends Animal {
    public SittingWolf() {
        super('W');
    }
    public Attack fight(char enemy) {
        switch (enemy) {
            case 'B': // Bear: paper
            case 'L': // Lion: paper or scissors
                return Attack.SCISSORS;
            case 'S': // Stone: rock
                return Attack.PAPER;
            default:
                return Attack.values()[(int)(Math.random() * 3)];
        }
    }
    public Move move() {
        return Move.HOLD;
    }
}

Just sits there (hold).


问:
Calculate ISBN-13 check digit
Write a function which, given the first 12 digits of an ISBN-13 code, will calculate the entire ISBN via calculating and appending an appropriate check digit.

Your function's input is a string containing the first 12 digits of the ISBN. Its output is a string containing all 13 digits.

Formal specification

Write a function which, when given a string s consisting entirely of exactly 12 decimal digits (and no other characters), returns a string t with the following properties:

t consists of exactly 13 decimal digits (and no other characters);

s is a prefix of t;

the sum of all digits in odd positions in t (i.e. the first, third, fifth, etc.), plus three times the sum of all digits in even positions in t (i.e. the second, fourth, sixth, etc), is a multiple of 10.

Example / test case

Input

978030640615

Output

9780306406157

Victory condition

As a code-golf challenge, the shortest answer wins.

Title: Calculate ISBN-13 check digit

Body:
Perl, 53 chars

sub i{($_)=@_;s/(.)(.)/$s+=$1+$2*3/ger;$_.(10-$s)%10}


问:
Showcase of Languages

Notes

This thread is open and unlocked only because the community decided to make an exception. Please do not use this question as evidence that you can ask similar questions here. Please do not create additional showcase questions.

This is no longer a popularity-contest, nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes.

This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible.

How this works

All answers should include the name of the programming language at the top of the post, prefixed by a #.

Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language.

Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions.

The snippets do not need to be related. In fact, snippets that are too related may be redundant.

Since this is not a contest, all programming languages are welcome, whenever they were created.

Answers that contain more than a handful of code snippets should use a Stack Snippet to collapse everything except the factoid and one of the snippets.

Whenever possible, there should be only one answer per programming language. This is a community wiki, so feel free to add snippets to any answer, even if you haven't created it yourself. There is a Stack Snippet for compressing posts, which should mitigate the effect of the 30,000 character limit.

Answers that predate these guidelines should be edited. Please help updating them as needed.

Current answers, sorted alphabetically by language name

$.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/44680/answers?site=codegolf&filter=withbody",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('
' + temp.innerText || temp.textContent + '');}}})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="http://codegolf.stackexchange.com"><ul id="list"></ul></code>```

答:
Batch

Factoid

Batch uses commands that the Windows command line uses. A bunch of these were inherited from the (ancient) MS-DOS.

Length 1

```<code>:
</code>```

This creates an empty label.  In Batch, empty labels are perfectly legal, even if they don't do anything.

Length 2

```<code>at
</code>```

This command schedules commands and programs to be run at a specified time. The batch file must be granted elevated administrator privileges for this to work.

Length 3

```<code>rem
</code>```

A command that discards parameters supplied after it. This essentially comments out text.

Length 4

```<code>echo
</code>```

With four characters, we can finally print text! This will print out whatever comes after it.

Length 5

```<code>start
</code>```

As one of the most simple commands, this just opens up a separate command-prompt window. Nothing too complicated about this at all.

Length 6

```<code>chkdsk
</code>```

This command also requires elevated administrator privileges. This command is short for "check disk". It does what it says; it checks a disk and provides a status report.

Length 7

```<code>replace
</code>```

This command is used to replace one file with another. The file names are passed as parameters to the command.

Length 8

```<code>shutdown
</code>```

This command can shutdown your computer. It has a variety of parameters, and like setting shutdown time, a shutdown comment, or aborting the shutdown.

Title: Showcase of Languages

Body:
Batch

Factoid

Batch uses commands that the Windows command line uses. A bunch of these were inherited from the (ancient) MS-DOS.

Length 1

:

This creates an empty label.  In Batch, empty labels are perfectly legal, even if they don't do anything.

Length 2

at

This command schedules commands and programs to be run at a specified time. The batch file must be granted elevated administrator privileges for this to work.

Length 3

rem

A command that discards parameters supplied after it. This essentially comments out text.

Length 4

echo

With four characters, we can finally print text! This will print out whatever comes after it.

Length 5

start

As one of the most simple commands, this just opens up a separate command-prompt window. Nothing too complicated about this at all.

Length 6

chkdsk

This command also requires elevated administrator privileges. This command is short for "check disk". It does what it says; it checks a disk and provides a status report.

Length 7

replace

This command is used to replace one file with another. The file names are passed as parameters to the command.

Length 8

shutdown

This command can shutdown your computer. It has a variety of parameters, and like setting shutdown time, a shutdown comment, or aborting the shutdown.


问:
A simple TCP server
Write a program or function that listens for incoming TCP traffic on port N. It offers a simple service: it calculates sum of IP address fields of incoming connection and returns.

Program or function reads integer N from arguments or stdin. It listens to incoming TCP connections on port N. When someone connects to that port, the program calculates sum of its IP address fields and sends it back to the client with trailing newline and closes connection.

Port number N is a valid port, and 210 < N < 215

Trailing newline can be either \nor \r\n

You can use either IPv4 or IPv6. Since IPv6 addresses are written in hexadecimal form, you must also provide result in same format, for example 2001:0db8:0000:0042:0000:8a2e:0370:7334 => 12ecd.

This is code-golf. Standard rules and loopholes apply.

Example

You run your server with ./server 1234. The server is now running and waiting for connections on port 1234. Then a client from 127.0.0.1 connects to your server. Your server performs a simple calculation: 127+0+0+1 => 128 and sends the result to the client (with trailing newline): 128\n. Then server closes connection and waits for next client.

Leaderboard

var QUESTION_ID=76379,OVERRIDE_USER=20569;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

```

答:
NodeJS, (IPv4 and IPv6) 105 Bytes

```<code>require("net").createServer(s=>s.end(eval(s.remoteAddress.replace(/[:.]/g,"+"))).listen(process.argv[2])
</code>```

Explanation:

```<code>require("net")               # TCP library
 .createServer(              # Create the server
   s=>                       # Socket is s
    s.end(                   # Print and end the connection
     eval(                   # Treat the following string like JavaScript
      s.remoteAddress        # The IP address (IPv4 or IPv6, depending on connection)
       .replace(/.|:/g, "+") # Replace all . and : with +
 )))                         # Close server response
 .listen(process.argv[2])    # Listen on the third index of the arg array (["node", "filename.js", "first arg"])
</code>```

Title: A simple TCP server

Body:
NodeJS, (IPv4 and IPv6) 105 Bytes

require("net").createServer(s=>s.end(eval(s.remoteAddress.replace(/[:.]/g,"+"))).listen(process.argv[2])

Explanation:

require("net")               # TCP library
 .createServer(              # Create the server
   s=>                       # Socket is s
    s.end(                   # Print and end the connection
     eval(                   # Treat the following string like JavaScript
      s.remoteAddress        # The IP address (IPv4 or IPv6, depending on connection)
       .replace(/.|:/g, "+") # Replace all . and : with +
 )))                         # Close server response
 .listen(process.argv[2])    # Listen on the third index of the arg array (["node", "filename.js", "first arg"])


问:
Counting triangles with integer perimeter
Mary has given John two sticks of lengths a and b respectively, where a and b are positive integers.

John is very curious.

He would like to know how many triangles with integer perimeter can be formed, by having one additional side.

Please help him find it out.

(This is my first time composing this kind of stupid stories in coding problems, so forgive me if it is too stupid.)

Specs

Given two integers a and b, find the number of triangles with integer perimeter that can be formed, by having one additional side.

Details

Congruent triangles are congruent.

Flat triangles are flat out uncounted.

Zero-sided triangles are counted zero times.

Scoring

This is code-golf. Shortest solution in bytes wins.

Testcases

```<code>a b output
1 2 1
3 3 5
9 7 13
</code>```

答:
J, 7 bytes

```<code>1-~2*<.
</code>```

This is a tacit verb.

```<code>1-~2*<.
1-~      reflexive minus (i.e. R - 1)
   2*    double
     <.  lesser of
</code>```

Body:
J, 7 bytes

1-~2*<.

This is a tacit verb.

1-~2*<.
1-~      reflexive minus (i.e. R - 1)
   2*    double
     <.  lesser of


答:
Jolf, 4 bytes

```<code>m±♀j
</code>```

Replace ♀ with a literal \x12 byte, or try it here!

Explanation

```<code>m±♀j
  ♀j  min of j and implicit input
m±    2*(^)-1
</code>```

Title: Counting triangles with integer perimeter

Body:
Mary has given John two sticks of lengths a and b respectively, where a and b are positive integers.

John is very curious.

He would like to know how many triangles with integer perimeter can be formed, by having one additional side.

Please help him find it out.

(This is my first time composing this kind of stupid stories in coding problems, so forgive me if it is too stupid.)

Specs

Given two integers a and b, find the number of triangles with integer perimeter that can be formed, by having one additional side.

Details

Congruent triangles are congruent.

Flat triangles are flat out uncounted.

Zero-sided triangles are counted zero times.

Scoring

This is code-golf. Shortest solution in bytes wins.

Testcases

```<code>a b output
1 2 1
3 3 5
9 7 13
</code>```

Body:
Jolf, 4 bytes

m±♀j

Replace ♀ with a literal \x12 byte, or try it here!

Explanation

m±♀j
  ♀j  min of j and implicit input
m±    2*(^)-1


问:
Minimize Those Ones
Your task is to build a natural number using the fewest number of ones and only the operators + or -. For example, the number seven can be written 1+1+1+1+1+1+1=7, but it can also be written as 11-1-1-1-1=7. The first one uses 7 ones, while the latter only uses 6. Your task is to return the minimum number of ones that can be used given the input of some natural number, n.

This is code golf, so the shortest valid code in bytes wins.

Test cases

Input => Output

```<code>0 => 2 (since 1-1=0)
7 => 6
121 => 6
72 => 15
1000 => 7
2016 => 21
</code>```

答:
Pyth, <s>19</s> 16 bytes

```<code>ffqQvs+R1Y^c3"+-
</code>```

Test suite

Brute force algorithm. The necessary strings are generated by taking all lists whose elements are ['+', '-', ''] of length equal to the number of 1s being tested, appending a 1 to each, and concatenating to a single string. These strings are then evaluated and compared with the input. This is repeated until a successful string is found.

Some strings with a leading + or - are tested, but this isn't a problem. It would be if the input was negative though.

It can run up to length 9 before it becomes too slow.

Explanation:

```<code>ffqQvs+R1Y^c3"+-
ffqQvs+R1Y^c3"+-"T    Implicit variable introduction
                      Q = eval(input())
f                     Starting with T = 1 and counting upwards, repeat until true.
                      The value of T where the result is first true is output.
           c3"+-"     Chop "+-" into thirds, giving ['+', '-', '']
          ^      T    Form every list with those elements of length T.
 f                    Filter over those lists, lambda var Y.
      +R1Y            Append a 1 to each element of the list.
     s                Concatenate.
    v                 Eval.
  qQ                  Compare for equality with the input.
                      The inner filter will let through the successful cases.
                      The outer filter will stop when there is a successful case.
</code>```

Title: Minimize Those Ones

Body:
Pyth, <s>19</s> 16 bytes

ffqQvs+R1Y^c3"+-

Test suite

Brute force algorithm. The necessary strings are generated by taking all lists whose elements are ['+', '-', ''] of length equal to the number of 1s being tested, appending a 1 to each, and concatenating to a single string. These strings are then evaluated and compared with the input. This is repeated until a successful string is found.

Some strings with a leading + or - are tested, but this isn't a problem. It would be if the input was negative though.

It can run up to length 9 before it becomes too slow.

Explanation:

ffqQvs+R1Y^c3"+-
ffqQvs+R1Y^c3"+-"T    Implicit variable introduction
                      Q = eval(input())
f                     Starting with T = 1 and counting upwards, repeat until true.
                      The value of T where the result is first true is output.
           c3"+-"     Chop "+-" into thirds, giving ['+', '-', '']
          ^      T    Form every list with those elements of length T.
 f                    Filter over those lists, lambda var Y.
      +R1Y            Append a 1 to each element of the list.
     s                Concatenate.
    v                 Eval.
  qQ                  Compare for equality with the input.
                      The inner filter will let through the successful cases.
                      The outer filter will stop when there is a successful case.