问:
Animations with all colours
Last year, there was a very popular challenge to create an image containing every 24-bit RGB colour.

My challenge is to create a smooth animation (24 frames/s say), where the colour of every pixel of every frame is unique.  I will also allow duplication of colours as long as every colour appears the same number of times (greater than 0), since otherwise the animation will have to be short, or the frames small.

I have produced some examples here, based on the winning solution to the 2d version.  Unfortunately, it seems you can't embed videos, so links will have to do.

答:
PHP (+ HTML) + JavaScript

Part 1

generate 256 images with distinct red values from 0 to 255;

green value=row index, blue value=column index

```<code>for($r=$h=256;$r--;){$i=imagecreatetruecolor($g=$h,$h);for(;$g--;)for($b=$h;$b--;)imagesetpixel($i,$g,$b,imagecolorallocate($i,$r,$g,$b));imagepng($i,"$r.png");imagedestroy($i);}
</code>```

Note: Depending on Your PHP implementation, this may throw an internal server error.

If it does, take the lowest number of the images that already have been created, insert <number>, after $r= and run again.

Part 2

loop through these images from 0 to 255 and back (0 and 255 taking 2 frames each)

```<code><img><script>r=d=0;setInterval(()=>{document.images[0].src=r+".png",(d?!r--:(++r)>=256)?r-=(d=!d)?1:-1:r},40);</script>
</code>```

Title: Animations with all colours

Body:
PHP (+ HTML) + JavaScript

Part 1

generate 256 images with distinct red values from 0 to 255;

green value=row index, blue value=column index

for($r=$h=256;$r--;){$i=imagecreatetruecolor($g=$h,$h);for(;$g--;)for($b=$h;$b--;)imagesetpixel($i,$g,$b,imagecolorallocate($i,$r,$g,$b));imagepng($i,"$r.png");imagedestroy($i);}

Note: Depending on Your PHP implementation, this may throw an internal server error.

If it does, take the lowest number of the images that already have been created, insert <number>, after $r= and run again.

Part 2

loop through these images from 0 to 255 and back (0 and 255 taking 2 frames each)

<img><script>r=d=0;setInterval(()=>{document.images[0].src=r+".png",(d?!r--:(++r)>=256)?r-=(d=!d)?1:-1:r},40);</script>


问:
Jimmy these arrays down
My coworker, Jimmy is kinda new to C/C++. He's also kind of a slow learner. Now, to be fair, his code always compiles, but he has some really sloppy habits. For example, everybody knows that you can define an array like this:

```<code>int spam[] = {4, 8, 15, 16, 23, 42};
</code>```

Everybody that is, except for Jimmy. He is convinced that the only way to make an array is like this:

```<code>int spam[6];
spam[0] = 4;
spam[1] = 8;
spam[2] = 15;
spam[3] = 16;
spam[4] = 23;
spam[5] = 42;
</code>```

I keep fixing this for him in code-review, but he won't learn. So I need you to write a tool that automagically does this for him when he commits¹.

The challenge

I want you to write either a full program or a function that takes in a multiline string as input, and outputs the more compact version of the C array. The input will always follow this format, whitespace included:

```<code>identifier_one identifier_two[some_length];
identifier_two[0] = some_number;
identifier_two[1] = some_number;
identifier_two[2] = some_number;
...
identifier_two[some_length - 1] = some_number;
</code>```

In short, the input will always be valid and well defined C. In more detail:

All of the identifiers will be made up of just letters and underscores. The length will always be at least one, and there will never be any missing or out of bounds indexes. You may also assume that the indexes are in order. For example:

```<code>foo bar[3];
bar[0] = 1
bar[2] = 9;
</code>```

<s></s>

```<code>foo bar[1];
bar[0] = 1;
bar[1] = 3;
</code>```

and

```<code>foo bar[3];
bar[2] = 9;
bar[0] = 1
bar[1] = 3
</code>```

are all invalid inputs, and may cause undefined behavior in your submission. You may also assume that all of the numbers will be valid decimal numbers, negative or positive. The input will not have extraneous spaces. The output should always follow this format, whitespace included:

```<code>identifier_one identifier_two[] = {n1, n2, n3, ...};
</code>```

Here is some sample data:

```<code>Input:
spam eggs[10];
eggs[0] = 0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;
eggs[4] = 3;
eggs[5] = 7;
eggs[6] = 888;
eggs[7] = 555;
eggs[8] = 0;
eggs[9] = -2;

Output:
spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};

Input:
char ans[2];
ans[0] = 52;
ans[1] = 50;

Output:
char ans[] = {52, 50};

Input:
blah_blah quux[1];
quux[0] = 105;

Output:
blah_blah quux[] = {105};
</code>```

You may take your input and output in any reasonable format, such as STDIN/STDOUT, function arguments and return value, reading and writing files etc. Standard loopholes apply. The shortest answer in bytes wins!

¹This is passive-aggressive and a terrible idea. You did not get this idea from me.

答:
Haxe, 234 bytes

```<code>function R(L:Array<String>){var S=L[0];var W=S.indexOf(" ");var T=S.substr(0,W),M=S.substring(W+1,S.indexOf("["));var r=[for(i in 1...L.length)L[i].substring(L[i].lastIndexOf(" ")+1,L[i].length-1)].join(', ');return'$T $M[] = {$r};';}
</code>```

Long function names killed this :D

Try the testcases here!

ContentLicense: CC BY-SA 3.0

Title: Jimmy these arrays down

Body:
Haxe, 234 bytes

function R(L:Array<String>){var S=L[0];var W=S.indexOf(" ");var T=S.substr(0,W),M=S.substring(W+1,S.indexOf("["));var r=[for(i in 1...L.length)L[i].substring(L[i].lastIndexOf(" ")+1,L[i].length-1)].join(', ');return'$T $M[] = {$r};';}

Long function names killed this :D

Try the testcases here!


问:
Find the largest number n positions away from n
A sequel to this question.

Task

Given an array of positive integers, find the largest element k for which:

There exists some positive integer distance n, so that the element in the array located n places to the left or right from k equals n.

The array is guaranteed to contain at least one element satisfying this condition.

The shortest code (in bytes) wins. You may choose whichever I/O format you like.

Example

Given the input

```<code>[4, 6, 7, 9, 3, 6, 5, 7, 2]
</code>```

The eligible values are:

The 4, as there is a 7 located 7 positions to its right

The first 6, as there is a 3 located 3 positions to its right

The 3, as there is a 4 located 4 positions to its left

The 5, as there is a 2 located 2 positions to its right

The second 7, as there is a 3 located 3 positions to its left.

Of these values, the largest is 7.

Test cases

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

答:
EXCEL: <s>32</s> 30 bytes

=MAX(IF(A:A-ROW(A:A)<0,A:A,0))

I still cannot believe I got it to be this short...

How to use:

paste this into ANY cell EXCEPT the cells of column A. After pasting, while still editing, press control+shift+enter to correctly enter it.

put your values into column A, 1 value per cell (as per CSV entry).

If you want to find out how this works, I've posted an additional tip in my Tips for golfing in Excel question.


问:
Tips for golfing in Excel?
It's strange that I haven't seen this, as Excel seems to be a valid language for code golfing (despite its 'compiler' not being free).

Excel is somewhat of a wildcard in golfing, being good at golfing challenges of medium complexity, and sometimes simpler challenges as well. More often than not, Excel is good at challenges with string manipulation and mixed string-number manipulation.

What general tips do you have for golfing in Excel? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Excel (NOT VBA). Please, one tip per answer.

答:
Vectorization of arrays of cells:

The tip Vectorization with arrays Shows how you can golf down a function with an array by using specific formatting within the array. It is possible to do the same thing with cells, and will save you many many bytes in the long run. Say you have the following sheet:

And we want to find the highest shelf life of a fruit.

Without Vectorization, one might use the two formulas like so:

And this does give a correct answer, but the Score for this golf is Unconventional, and will probably not be accepted as widely. On top of that, this uses a drag down function (Ew), which makes for a confusing answer.

Instead, We can place the function in column D right on in with the formula in E2. To do this, you replace (in this case B2 and C2) your variables with arrays for the range you want to test. Thus, your formula becomes:

This saves you a few bytes as well as making your entry properly score-able.

Title: Tips for golfing in Excel?


问:
Count even steps of 196 algorithm
In the 196-algorithm one starts from an integer and then adds its reverse to it until a palindrome is reached, like this:

```<code>start -> 5280
5280 + 0825 = 6105
6105 + 5016 = 11121
11121 + 12111 = 23232
-end-
</code>```

Write a function that counts how many even numbers are visited before the algorithm ends. Starting and ending numbers are also counted, so, in the example above, visited are consider the numbers: 5280, 6105, 11121, 23232 but not 825, 5016 and 12111.

Examples:

```<code>f(5280) = 2
f(56) = 1
f(59) = 1
f(89) = 13
</code>```

Extended code golf rules apply: shortest number of instructions and operations (like +,-,mod,print,while,if,...) wins.

答:
Python - 10 operations

```<code>def f(n):
    q=str(n)
    p=q[::-1]
    return 1-n%2+(q!=p and f(n+long(p)))
</code>```

Title: Count even steps of 196 algorithm

Body:
Python - 10 operations

def f(n):
    q=str(n)
    p=q[::-1]
    return 1-n%2+(q!=p and f(n+long(p)))

ContentLicense: CC BY-SA 2.5


答:
dc - 81

```<code>2k864/0k100~[Looplab]0:a[Sevit]1:a[Hexteria]2:a[Sinpad]3:ar4~;ar91~rn32Pn45dPrnPp
</code>```

Expects the epoch time already on the stack so invoke as, e.g.

```<code>dc -e `date +%s` -e '2k864/0k100~[Looplab]0:a[Sevit]1:a[Hexteria]2:a[Sinpad]3:ar4~;ar91~rn32Pn45dPrnPp'
</code>```

to get the current Noxu time or add one character to accept the time from stdin

```<code>?2k864/0k100~[Looplab]0:a[Sevit]1:a[Hexteria]2:a[Sinpad]3:ar4~;ar91~rn32Pn45dPrnPp
</code>```

annotated version

```<code>2 k             # set the precision to 2 decimal places
864 /           # divide the number of seconds by 864 to get fluffsters
0 k             # set the precision back to 0 decimal places
100 ~           # divrem by 100; fluffsters are at the top skizzles under it
[Looplab] 0 :a  # set a[0] to the string Looplab
[Sevit] 1 :a    # set a[1] to Sevit
[Hexteria] 2 :a # set a[2] to Hexteria
[Sinpad] 3 :a   # set a[3] to Sinpad
r               # swap fluffsters and skizzles on the stack
4 ~             # divrem the skizzles by 4; skizzles on top zestpond under it
;a              # use the skizzle as an index into a
r               # swap the skizzle string and zestponds
91 ~            # divrem the zestponds by 91; zestponds on top lulerain under
r               # swap zestponds and lulerains
# now the stack has (from top to bottom)
# lulerains
# zestponds
# skizzle (as the name)
# fluffster
n               # pop and print the lulerains (without a newline)
32 P            # print a space character
n               # pop and print the zestponds
45 d P          # print a - and leave 45 on the top of the stack
r               # swap the 45 and the skizzle name
n               # pop and print the skizzle name
P               # print a - from the 45 that was on the stack
p               # finally print the fluffster (with a newline)
</code>```

When the number of fluffsters is less than 1 there is no leading zero printed, to get the leading zero, it is

```<code>2k864/0k100~[Looplab]0:a[Sevit]1:a[Hexteria]2:a[Sinpad]3:ar4~;ar91~rn32Pn45dPrnPd[0n]sb1>bp
</code>```

at a cost of 10 extra characters (d[0n]sb1>b)

Title: Gregorian to Noxu Time System Conversion

Body:
The world's changing to a new time system!  We need to update our computer programs.  Given an input of epoch time (number of seconds since January 1st, 1970 00:00), print out a time in the new Noxu date-time format.

864 seconds make one Fluffster.  100 Fluffsters make a Skizzle.  There are 4 Skizzles in one Zestpond.  Their names are Looplab, Sevit, Hexteria, and Sinpad.  There are 91 Zestponds in one Lulerain.

The format is Lulerain Zestpond-Skizzle-Fluffster.  Fluffsters are rounded to two decimal places.  An example would be 50 13-Sevit-40.90.

Given that epoch 0 was 0 0-Looplab-00.00, create a program that takes input either via stdin or as a command line argument of any epoch time between 0 and 2^32, and prints out the Noxu equivalent.

Time of edit:

```<code>1357510372 -> 43 14-Sinpad-92.56
</code>```

Random test data:

```<code>675416077 -> 21 43-Sevit-31.57
330585453 -> 10 46-Hexteria-22.05
1328127085 -> 42 20-Sinpad-84.13
837779784 -> 26 58-Looplab-52.53
1240280676 -> 39 39-Sinpad-10.04
122646385 -> 3 81-Sinpad-51.83
1311245658 -> 41 63-Looplab-45.44
57792972 -> 1 76-Looplab-90.01
788388068 -> 25 6-Looplab-86.19
304341865 -> 9 61-Hexteria-47.53
417857784 -> 13 26-Looplab-31.69
671276878 -> 21 31-Sevit-40.83
1259758896 -> 40 5-Looplab-54.28
604286664 -> 19 19-Hexteria-5.86
646395018 -> 20 50-Sevit-42.38
563025133 -> 17 82-Looplab-49.46
96133144 -> 3 5-Looplab-65.21
101542552 -> 3 20-Sinpad-26.10
1006825856 -> 32 1-Sevit-7.70
928867348 -> 29 48-Hexteria-77.95
1235022079 -> 39 24-Hexteria-23.70
439505287 -> 13 88-Hexteria-86.67
99686711 -> 3 15-Sevit-78.14
379859609 -> 12 7-Looplab-52.33
1167091685 -> 37 10-Looplab-0.56
612032437 -> 19 41-Sinpad-70.88
503040778 -> 15 90-Hexteria-23.12
1084809411 -> 34 44-Sinpad-66.45
1105664386 -> 35 14-Sevit-4.15
197303893 -> 6 24-Sinpad-60.99
368559287 -> 11 65-Sevit-73.25
686824300 -> 21 76-Sevit-35.53
196468204 -> 6 22-Sevit-93.75
673542185 -> 21 37-Sinpad-62.71
993063782 -> 31 52-Sevit-79.38
270951743 -> 8 56-Looplab-1.55
1074506753 -> 34 15-Looplab-42.08
198143696 -> 6 27-Sevit-32.98
539601298 -> 17 14-Sevit-38.54
110090607 -> 3 45-Hexteria-19.68
276492708 -> 8 72-Looplab-14.71
113389138 -> 3 55-Looplab-37.43
571578220 -> 18 15-Sinpad-48.87
1238516450 -> 39 34-Hexteria-68.11
742293312 -> 23 54-Sinpad-35.78
1031929490 -> 32 73-Sinpad-62.84
503091914 -> 15 90-Hexteria-82.31
264094386 -> 8 36-Looplab-64.80
483820698 -> 15 34-Sinpad-77.66
548410387 -> 17 39-Sinpad-34.24
</code>```

Body:
dc - 81

2k864/0k100~[Looplab]0:a[Sevit]1:a[Hexteria]2:a[Sinpad]3:ar4~;ar91~rn32Pn45dPrnPp

Expects the epoch time already on the stack so invoke as, e.g.

dc -e `date +%s` -e '2k864/0k100~[Looplab]0:a[Sevit]1:a[Hexteria]2:a[Sinpad]3:ar4~;ar91~rn32Pn45dPrnPp'

to get the current Noxu time or add one character to accept the time from stdin

?2k864/0k100~[Looplab]0:a[Sevit]1:a[Hexteria]2:a[Sinpad]3:ar4~;ar91~rn32Pn45dPrnPp

annotated version

2 k             # set the precision to 2 decimal places
864 /           # divide the number of seconds by 864 to get fluffsters
0 k             # set the precision back to 0 decimal places
100 ~           # divrem by 100; fluffsters are at the top skizzles under it
[Looplab] 0 :a  # set a[0] to the string Looplab
[Sevit] 1 :a    # set a[1] to Sevit
[Hexteria] 2 :a # set a[2] to Hexteria
[Sinpad] 3 :a   # set a[3] to Sinpad
r               # swap fluffsters and skizzles on the stack
4 ~             # divrem the skizzles by 4; skizzles on top zestpond under it
;a              # use the skizzle as an index into a
r               # swap the skizzle string and zestponds
91 ~            # divrem the zestponds by 91; zestponds on top lulerain under
r               # swap zestponds and lulerains
# now the stack has (from top to bottom)
# lulerains
# zestponds
# skizzle (as the name)
# fluffster
n               # pop and print the lulerains (without a newline)
32 P            # print a space character
n               # pop and print the zestponds
45 d P          # print a - and leave 45 on the top of the stack
r               # swap the 45 and the skizzle name
n               # pop and print the skizzle name
P               # print a - from the 45 that was on the stack
p               # finally print the fluffster (with a newline)

When the number of fluffsters is less than 1 there is no leading zero printed, to get the leading zero, it is

2k864/0k100~[Looplab]0:a[Sevit]1:a[Hexteria]2:a[Sinpad]3:ar4~;ar91~rn32Pn45dPrnPd[0n]sb1>bp

at a cost of 10 extra characters (d[0n]sb1>b)


问:
List all ordered partitions of n
The challenge is to list all ordered partitions (composition (combinatorics)) of a given positive integer n. These are the lists of numbers from 1 to n whose sum is n. For example, given input n = 4, the result should be:

4

  1, 3

  3, 1

  2, 2

  2, 1, 1

  1, 2, 1

  1, 1, 2

  1, 1, 1, 1

The result can be in any order, but must contain each ordered partition once. This means that for n = 4, [1, 1, 2], [1, 2, 1] and [2, 1, 1] must all be part of the result.

Here's my own JavaScript code which achieves this:

```<code>function range(n) {
    for (var range = [], i = 0; i < n; range.push(++i));
    return range;
}

function composition(n) {
    return n < 1 ? [[]] : range(n).map(function(i) {
        return composition(n - i).map(function(j) {
            return [i].concat(j);
        });
    }).reduce(function(a, b) {
        return a.concat(b);
    });
}
</code>```

Golfed, ES6 (<s>169</s> <s>167</s> <s>119</s> <s>109</s> <s>105</s> <s>89</s> 85 bytes):

```<code>n=>n?[].concat(...[...Array(n)].map((x,i)=>i+1).map(b=>m(n-b).map(a=>[b,...a]))):[[]]
</code>```

答:
Haskell, 41 bytes

f 1=[[1]]
f n=do a:b<-f$n-1;[1:a:b,a+1:b]
```

Not the shortest Haskell solution, but I like that it doesn't use [..] ranges. Instead, it recursively computes the partitions of n as the partitions of n-1 with either a new 1 at the start or the first value one higher. This makes explicit why there's 2^(n-1) of them.

Title: List all ordered partitions of n

Body:
Haskell, 41 bytes

f 1=[[1]]
f n=do a:b<-f$n-1;[1:a:b,a+1:b]

Not the shortest Haskell solution, but I like that it doesn't use [..] ranges. Instead, it recursively computes the partitions of n as the partitions of n-1 with either a new 1 at the start or the first value one higher. This makes explicit why there's 2^(n-1) of them.


问:
Is it an Odd Word?

Challenge

Given a single word as input, determine if the word is odd or even.

Odd and Even words

Assume the general rules:

```<code>odd + odd = even
even + odd = odd
odd + even = odd
even + even = even
</code>```

In the alphabet, the odd letters are:

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

And the even letters are:

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

The same applies to capital letters (AEIOU are odd and BCDFGHJKLMNPQRSTVWXYZ are even).

You then 'add' each of the letters in the word together. For example, the word cats is equivalent to:

```<code>even + odd + even + even
</code>```

Which simplifies to:

```<code>odd + even
</code>```

Which simplifies further to:

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

So the word cats is odd.

Examples

```<code>Input:  trees
Output: even
</code>```

```<code>Input:  brush
Output: odd
</code>```

```<code>Input:  CAts
Output: odd
</code>```

```<code>Input:  Savoie
Output: even
</code>```

```<code>Input:  rhythm
Output: even
</code>```

Rules

All input will be a single word which will only contain alphabetical characters.

If the word is odd, output a truthy value. If the word is even, output a falsey value.

Winning

The shortest code in bytes wins.

答:
dimwit, 14 bytes (non-competing)

```<code>ar[aeiou]}et}T
</code>```

I thought this would be a fun, simple challenge to start with for a new language.

Explanation

a -  push a new array to the matrix

r[aeiou]} - count occurrences of all values matching the regex "[aeiou]" in the first array (since the first array contains the input), ignoring case, and push that value to the end of the last array.

e - if the last number in the last array is even (which we set to the number of occurrences), perform the next operations up until a closing bracket ("}")

t - stop execution, clear the matrix, and set the first value to be false

} - end of e code block

T - stop execution, clear the matrix, and set the first value to be true

Try it online!

Use the Input field to enter the word.

I'll soon add documentation...

Title: Is it an Odd Word?

Body:
dimwit, 14 bytes (non-competing)

ar[aeiou]}et}T

I thought this would be a fun, simple challenge to start with for a new language.

Explanation

a -  push a new array to the matrix

r[aeiou]} - count occurrences of all values matching the regex "[aeiou]" in the first array (since the first array contains the input), ignoring case, and push that value to the end of the last array.

e - if the last number in the last array is even (which we set to the number of occurrences), perform the next operations up until a closing bracket ("}")

t - stop execution, clear the matrix, and set the first value to be false

} - end of e code block

T - stop execution, clear the matrix, and set the first value to be true

Try it online!

Use the Input field to enter the word.

I'll soon add documentation...


问:
Create a pyramidal matrix
A pyramidal matrix is a square matrix where all numbers increase or decrease from the center point, like the two matrices below:

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

Or:

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

Given a non-zero integer n, create a pyramidal matrix where the numbers goes from 1 to n either in increasing order (if n<0), or decreasing order (if n>0) from the center. If n is even, then there will be 4 center numbers (see the examples).

As always:

Optional input and output format

Number of spaces, delimiter etc. is optional

Test cases:

```<code>1
1

-1
1

5
1  1  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2  1
1  2  3  3  3  3  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  4  5  4  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  3  3  3  3  2  1
1  2  2  2  2  2  2  2  1
1  1  1  1  1  1  1  1  1

-5
5  5  5  5  5  5  5  5  5
5  4  4  4  4  4  4  4  5
5  4  3  3  3  3  3  4  5
5  4  3  2  2  2  3  4  5
5  4  3  2  1  2  3  4  5
5  4  3  2  2  2  3  4  5
5  4  3  3  3  3  3  4  5
5  4  4  4  4  4  4  4  5
5  5  5  5  5  5  5  5  5
</code>```

```<code>2
1  1  1  1
1  2  2  1
1  2  2  1
1  1  1  1

-2
2  2  2  2
2  1  1  2
2  1  1  2
2  2  2  2

-4
4  4  4  4  4  4  4  4
4  3  3  3  3  3  3  4
4  3  2  2  2  2  3  4
4  3  2  1  1  2  3  4
4  3  2  1  1  2  3  4
4  3  2  2  2  2  3  4
4  3  3  3  3  3  3  4
4  4  4  4  4  4  4  4
</code>```

答:
PHP, <s>177</s> 157 bytes

```<code>for($y=-$n=abs($z=$argv[1])+1;++$y<$n;)if($y&&($n&1||$y-1)){for($x=-$n;++$x<$n;)if($x&&($n&1||$x-1)){$v=max(abs($x),abs($y));echo$z<0?$v:$n-$v," ";}echo"
";}
</code>```

run with php -r '

loops through rows and columns, prints the values depending on their distance to the center.

$n=abs($z)+1: The +1 saves a couple of +1 and -1 in later expressions

loops go from -$n+1 (pre-increment in the condition!) to $n-1 (-abs($z) to abs($z))

line/column 0 (and for odd $n: 1) are skipped

($n&1 is true for even columns here! Remember the +1?)

The printing for positive $z also benefits from the +1.

Title: Create a pyramidal matrix

Body:
PHP, <s>177</s> 157 bytes

for($y=-$n=abs($z=$argv[1])+1;++$y<$n;)if($y&&($n&1||$y-1)){for($x=-$n;++$x<$n;)if($x&&($n&1||$x-1)){$v=max(abs($x),abs($y));echo$z<0?$v:$n-$v," ";}echo"
";}

run with php -r '<code>

loops through rows and columns, prints the values depending on their distance to the center.

$n=abs($z)+1: The +1 saves a couple of +1 and -1 in later expressions

loops go from -$n+1 (pre-increment in the condition!) to $n-1 (-abs($z) to abs($z))

line/column 0 (and for odd $n: 1) are skipped

($n&1 is true for even columns here! Remember the +1?)

The printing for positive $z also benefits from the +1.


答:
Python 2.7: 123 122 120 Bytes

probs can still save a few bytes...

from numpy import*
n=input()
N=abs(n)
e=N*2-N%2
a=ones([e,e])
for i in range(N):a[i:e-i,i:e-i]=(i+1)*(n>0)or-n-i
print a```

edit1: N=abs(n) to save 1 byte

edit2: (i+1)*(n>0)or-n-i to save 2 bytes

Title: Create a pyramidal matrix

Body:
A pyramidal matrix is a square matrix where all numbers increase or decrease from the center point, like the two matrices below:

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

Or:

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

Given a non-zero integer n, create a pyramidal matrix where the numbers goes from 1 to n either in increasing order (if n<0), or decreasing order (if n>0) from the center. If n is even, then there will be 4 center numbers (see the examples).

As always:

Optional input and output format

Number of spaces, delimiter etc. is optional

Test cases:

```<code>1
1

-1
1

5
1  1  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2  1
1  2  3  3  3  3  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  4  5  4  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  3  3  3  3  2  1
1  2  2  2  2  2  2  2  1
1  1  1  1  1  1  1  1  1

-5
5  5  5  5  5  5  5  5  5
5  4  4  4  4  4  4  4  5
5  4  3  3  3  3  3  4  5
5  4  3  2  2  2  3  4  5
5  4  3  2  1  2  3  4  5
5  4  3  2  2  2  3  4  5
5  4  3  3  3  3  3  4  5
5  4  4  4  4  4  4  4  5
5  5  5  5  5  5  5  5  5
</code>```

```<code>2
1  1  1  1
1  2  2  1
1  2  2  1
1  1  1  1

-2
2  2  2  2
2  1  1  2
2  1  1  2
2  2  2  2

-4
4  4  4  4  4  4  4  4
4  3  3  3  3  3  3  4
4  3  2  2  2  2  3  4
4  3  2  1  1  2  3  4
4  3  2  1  1  2  3  4
4  3  2  2  2  2  3  4
4  3  3  3  3  3  3  4
4  4  4  4  4  4  4  4
</code>```

Body:
Python 2.7: 123 122 120 Bytes

probs can still save a few bytes...

from numpy import*
n=input()
N=abs(n)
e=N*2-N%2
a=ones([e,e])
for i in range(N):a[i:e-i,i:e-i]=(i+1)*(n>0)or-n-i
print a

edit1: N=abs(n) to save 1 byte

edit2: (i+1)*(n>0)or-n-i to save 2 bytes


答:
Pure Bash, 51

This is a port of @xnor's brilliant answer, using multiple levels of bash expansions to achieve the desired result:

a=$[10**($1-1)]
eval echo \$[${a//0/{+,']\ $[}1'}],
```

Ideone.

The first line is simply an arithmetic expansion to create a variable $a containing 1 followed by n-1 zeros.

The first expansion ${a//0/{+,']\ $[}1'} replaces each 0 in $a with copies of the string {+,']\ $[}1'.  Thus n=4 we get the string 1{+,']\ $[}1'{+,']\ $[}1'{+,']\ $[}1'

This is prefixed with $[ and postfixed with ], to give $[1{+,']\ $[}1'{+,']\ $[}1'{+,']\ $[}1]

This is a brace expansion that expands to $[1+1+1+1], $[1+1+1] 1, $[1+1] $[1+1], $[1+1] 1 1,...

This is finally arithmetically expanded to give the required result.

Careful use of quotes, backslash escaping and eval ensures that the expansions occur in the correct order.

Title: List all ordered partitions of n

Body:
The challenge is to list all ordered partitions (composition (combinatorics)) of a given positive integer n. These are the lists of numbers from 1 to n whose sum is n. For example, given input n = 4, the result should be:

4

  1, 3

  3, 1

  2, 2

  2, 1, 1

  1, 2, 1

  1, 1, 2

  1, 1, 1, 1

The result can be in any order, but must contain each ordered partition once. This means that for n = 4, [1, 1, 2], [1, 2, 1] and [2, 1, 1] must all be part of the result.

Here's my own JavaScript code which achieves this:

```<code>function range(n) {
    for (var range = [], i = 0; i < n; range.push(++i));
    return range;
}

function composition(n) {
    return n < 1 ? [[]] : range(n).map(function(i) {
        return composition(n - i).map(function(j) {
            return [i].concat(j);
        });
    }).reduce(function(a, b) {
        return a.concat(b);
    });
}
</code>```

Golfed, ES6 (<s>169</s> <s>167</s> <s>119</s> <s>109</s> <s>105</s> <s>89</s> 85 bytes):

```<code>n=>n?[].concat(...[...Array(n)].map((x,i)=>i+1).map(b=>m(n-b).map(a=>[b,...a]))):[[]]
</code>```

Body:
Pure Bash, 51

This is a port of @xnor's brilliant answer, using multiple levels of bash expansions to achieve the desired result:

a=$[10**($1-1)]
eval echo \$[${a//0/{+,']\ $[}1'}],

Ideone.

The first line is simply an arithmetic expansion to create a variable $a containing 1 followed by n-1 zeros.

The first expansion ${a//0/{+,']\ $[}1'} replaces each 0 in $a with copies of the string {+,']\ $[}1'.  Thus n=4 we get the string 1{+,']\ $[}1'{+,']\ $[}1'{+,']\ $[}1'

This is prefixed with $[ and postfixed with ], to give $[1{+,']\ $[}1'{+,']\ $[}1'{+,']\ $[}1]

This is a brace expansion that expands to $[1+1+1+1], $[1+1+1] 1, $[1+1] $[1+1], $[1+1] 1 1,...

This is finally arithmetically expanded to give the required result.

Careful use of quotes, backslash escaping and eval ensures that the expansions occur in the correct order.


问:
The Decanting Problem
Given N decanters (0 < N < 10) with that can hold C0 ... CN-1 liters (0 < C < 50) and a goal G liters, please determine if it is possible to reach that goal using only the following actions:

Fill a decanter

Empty a decanter

Pour from one decanter to another until the one being poured to is full or the one being poured from is empty

The goal amount G must be the amount of water in one of the containers at the end. You cannot have a 'output decanter'.

Examples

N: 2

C0: 5

C1: 12

G: 1

Result: Yes

N: 3

C0: 6

C1: 9

C2: 21

G: 5

Result: No

Hint: To calculate if it is possible, check to see if G is divisible by the GCD of the capacities. Also, make sure it will fit in a container.

Remember, this is code-golf, so the code with the lowest number of bytes wins.

Leaderboards

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

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

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

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

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

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

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

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

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

var QUESTION_ID=94202,OVERRIDE_USER=12537;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

```

答:
Haskell, 35 bytes

l%n=n`mod`foldr1 gcd l<1&&any(>=n)l
```

<p>This paper proves a result that vastly simplifies the problem. Prop 1 says that </p>

<blockquote>
  <p>You can achieve a goal exactly when it's both:</p>

  <ul>
  <li>A multiple of the greatest common divisor (gcd) of the capacities, </li>
  <li>At most the maximum capacity</li>
  </ul>
</blockquote>

<p>It's clear why both of these are necessary: all amounts remain multiples of the gcd, and the goal must fit in a container. The key of the result is an algorithm to produce any goal amount that fits these conditions.</p>

<p>Call the operator <code>%</code> like <code>[3,6,12]%9</code>.</p>

<p>A 37-byte alternative:</p>

<pre class="lang-haskell prettyprint-override"><code>l%n=elem n[0,foldr1 gcd l..maximum l]
</code>```

Title: The Decanting Problem

Body:
Haskell, 35 bytes

l%n=n`mod`foldr1 gcd l<1&&any(>=n)l

This paper proves a result that vastly simplifies the problem. Prop 1 says that

You can achieve a goal exactly when it's both:

A multiple of the greatest common divisor (gcd) of the capacities,

At most the maximum capacity

It's clear why both of these are necessary: all amounts remain multiples of the gcd, and the goal must fit in a container. The key of the result is an algorithm to produce any goal amount that fits these conditions.

Call the operator % like [3,6,12]%9.

A 37-byte alternative:

l%n=elem n[0,foldr1 gcd l..maximum l]


答:
Python 2, 109 99 98

n=input()
r=range(1,abs(n)+1)
l=r+r[~n|-2::-1]
for j in l:print[abs((n<0)*~-n+min(i,j))for i in l]
```

<p>Create list</p>

<pre class="lang-python prettyprint-override"><code>l = [1,2,3,4,5,4,3,2,1]
</code>```

and play with it a little.

edit: new way of creating list + thx Lynn for two bytes

Title: Create a pyramidal matrix

Body:
Python 2, 109 99 98

n=input()
r=range(1,abs(n)+1)
l=r+r[~n|-2::-1]
for j in l:print[abs((n<0)*~-n+min(i,j))for i in l]

Create list

l = [1,2,3,4,5,4,3,2,1]

and play with it a little.

edit: new way of creating list + thx Lynn for two bytes


答:
Ruby, 35 bytes

```<code>->n,g{g<=n.max&&1>g%n.reduce(:gcd)}
</code>```

Title: The Decanting Problem

Body:
Given N decanters (0 < N < 10) with that can hold C0 ... CN-1 liters (0 < C < 50) and a goal G liters, please determine if it is possible to reach that goal using only the following actions:

Fill a decanter

Empty a decanter

Pour from one decanter to another until the one being poured to is full or the one being poured from is empty

The goal amount G must be the amount of water in one of the containers at the end. You cannot have a 'output decanter'.

Examples

N: 2

C0: 5

C1: 12

G: 1

Result: Yes

N: 3

C0: 6

C1: 9

C2: 21

G: 5

Result: No

Hint: To calculate if it is possible, check to see if G is divisible by the GCD of the capacities. Also, make sure it will fit in a container.

Remember, this is code-golf, so the code with the lowest number of bytes wins.

Leaderboards

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Ruby, 35 bytes

->n,g{g<=n.max&&1>g%n.reduce(:gcd)}


答:
Haskell, <s>119</s> <s>113</s> <s>110</s> <s>104</s> <s>102</s> 101 bytes

```<code>f x|(h,t)<-splitAt(mod x 2)$[x,x-1..1]++[1.. -x]=foldl(\m n->(n#)<$>(n<$m)#m)[[y]|y<-h]t
x#y=x:y++[x]
</code>```

Returns the matrix as a list of lists of integers, for example: f 2 -> [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]].

How it works:

```<code>            [x,x-1..1]++[1.. -x]      -- make list from x down to 1 followed by
                                      -- 1 to (-x). One of the sublists will be
                                      -- empty. The resulting list contains the
                                      -- numbers of the pyramid from inside to out.
   (h,t)<-splitAt(mod x 2)            -- bind h to the first element if x is odd
                                      -- or to the empty list if x is even
                                      -- bind t to the rest (tail or full list)

foldl (     ) [[y]|y<-h] t            -- fold the following function into t with a
                                      -- starting value of [] if x is even or
                                      -- [[h]] if x is odd

   \m n ->                            -- the current matrix m with the next number
                                      -- n is transformed into a new matrix:

               (n#)<$>(n<$m)#m        -- prepend and append a n to
                                      -- m prepended and append by a line of n's

x#y=x:y++[x]                          -- helper function to prepend and append an
                                      -- element x to a list y
</code>```

Title: Create a pyramidal matrix

Body:
Haskell, <s>119</s> <s>113</s> <s>110</s> <s>104</s> <s>102</s> 101 bytes

f x|(h,t)<-splitAt(mod x 2)$[x,x-1..1]++[1.. -x]=foldl(\m n->(n#)<$>(n<$m)#m)[[y]|y<-h]t
x#y=x:y++[x]

Returns the matrix as a list of lists of integers, for example: f 2 -> [[1,1,1,1],[1,2,2,1],[1,2,2,1],[1,1,1,1]].

How it works:

            [x,x-1..1]++[1.. -x]      -- make list from x down to 1 followed by
                                      -- 1 to (-x). One of the sublists will be
                                      -- empty. The resulting list contains the
                                      -- numbers of the pyramid from inside to out.
   (h,t)<-splitAt(mod x 2)            -- bind h to the first element if x is odd
                                      -- or to the empty list if x is even
                                      -- bind t to the rest (tail or full list)

foldl (     ) [[y]|y<-h] t            -- fold the following function into t with a
                                      -- starting value of [] if x is even or
                                      -- [[h]] if x is odd

   \m n ->                            -- the current matrix m with the next number
                                      -- n is transformed into a new matrix:

               (n#)<$>(n<$m)#m        -- prepend and append a n to
                                      -- m prepended and append by a line of n's

x#y=x:y++[x]                          -- helper function to prepend and append an
                                      -- element x to a list y


问:
Non-transitive dice game
Those of you who like Numberphile would be familiar with Dr. James Grime, who described a non-transitive dice game on his channel.

The game consists of three 6-faced dice:

Die 1: 3,3,3,3,3,6

Die 2: 2,2,2,5,5,5

Die 3: 1,4,4,4,4,4

Two players each select a die to use. They roll them and the higher die wins, best-of-whatever.

Probabilistically, die 1 beats dies 2 with >50% chance. Similarly, die 2 beats die 3, and, interestingly, die 3 beats die 1.

Write a program taking 1, 2 or 3 as input. This indicates the die the user chooses. The program then choose the die that would beat the user and output the results of 21 rolls, and "Computer/User wins with x points"

Rules

Code-golf, votes as tiebreaker

You must use RNG (or the likes) to actually simulate the dice rolls.

I am not too strict on output format. It's okay as long as you show the dices, somehow separate between the 21 rolls (in a way different from how you separate the dice in the same roll), and output that sentence above.

Input can be stdin, command line argument, from screen, etc.

Example

Input

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

Output

```<code>4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 6
1 3
4 3
4 3
1 3
4 3
1 3
4 3
4 3
4 3
4 3
4 6
 Computer wins with 16 points
</code>```

Here, the user chooses die 1 and his rolls are shown on the right column. The program chooses die 3 and beats him.

答:
APL (<s>106</s> 114)

```<code>'Computer' 'User'[1+X],'wins with','points',⍨|Z-21×X←11>Z←+/>/⎕←⍉↑{⍵[{?6}¨⍳21]}¨(↓5 6⍴545170074510753⊤⍨18⍴7)[⎕+⍳2]
</code>```

Explanation:

(↓5 6⍴545170074510753⊤⍨18⍴7)[⎕+⍳2]: The big number is a base-7 representation of the dice. We make a 6x5 matrix containing the values of the dice in the order: 2 3 1 2 3. Ask for user input and add this to the vector 1 2, and select these lines from the matrix. Because the list of dice is shifted, the user now gets the one he selected (on the right) and the computer gets the stronger one.

{⍵[{?6}¨⍳21]}¨: do 21 rolls for each of these two dice.

⎕←⍉↑: put the rolls in matrix form and output them.

Z←+/>/: get the score of the computer (amount of times the computer's value was higher than the user's)

X←11>Z: set X to whether the user won (if 11 is higher than the computer's score).

'Computer' 'User'[1+X]. X is whether the user won.

'wins with','points',⍨|Z-21×X: Z is the computer's score, so if the computer won display Z, otherwise display 21-Z.

Title: Non-transitive dice game

Body:
APL (<s>106</s> 114)

'Computer' 'User'[1+X],'wins with','points',⍨|Z-21×X←11>Z←+/>/⎕←⍉↑{⍵[{?6}¨⍳21]}¨(↓5 6⍴545170074510753⊤⍨18⍴7)[⎕+⍳2]

Explanation:

(↓5 6⍴545170074510753⊤⍨18⍴7)[⎕+⍳2]: The big number is a base-7 representation of the dice. We make a 6x5 matrix containing the values of the dice in the order: 2 3 1 2 3. Ask for user input and add this to the vector 1 2, and select these lines from the matrix. Because the list of dice is shifted, the user now gets the one he selected (on the right) and the computer gets the stronger one.

{⍵[{?6}¨⍳21]}¨: do 21 rolls for each of these two dice.

⎕←⍉↑: put the rolls in matrix form and output them.

Z←+/>/: get the score of the computer (amount of times the computer's value was higher than the user's)

X←11>Z: set X to whether the user won (if 11 is higher than the computer's score).

'Computer' 'User'[1+X]. X is whether the user won.

'wins with','points',⍨|Z-21×X: Z is the computer's score, so if the computer won display Z, otherwise display 21-Z.


答:
Perl, 175 bytes

Includes 1 bytes for -p.

($t,$v,$w)=($_,(abs)x2);$k=$_.$k for 1..$v;map{$r.=$_ for(@v=1..$_-1),$_ x(2*$v---$w%2),reverse@v;$r.=$/}1..$v;$_=$r.~~reverse$r;eval"y/1-$w/$k/"if$t<0;$w%2&&s/

.*//||s;

;
```

<p>(There is a trailing newline that I don't know how to show with the markdown, but you need it).</p>

<p>Needs <code>-p</code> as well as <code>-M5.010</code> or <code>-E</code> to run :</p>

```perl -pE '($t,$v,$w)=($_,(abs)x2);$k=$_.$k for 1..$v;map{$r.=$_ for(@v=1..$_-1),$_ x(2*$v---$w%2),reverse@v;$r.=$/}1..$v;$_=$r.~~reverse$r;eval"y/1-$w/$k/"if$t<0;$w%2&&s/

.*//||s;

;
' <<< 5
```

Damn, this is too long... I'll try some other approaches when I have some time.

Title: Create a pyramidal matrix

Body:
Perl, 175 bytes

Includes 1 bytes for -p.

($t,$v,$w)=($_,(abs)x2);$k=$_.$k for 1..$v;map{$r.=$_ for(@v=1..$_-1),$_ x(2*$v---$w%2),reverse@v;$r.=$/}1..$v;$_=$r.~~reverse$r;eval"y/1-$w/$k/"if$t<0;$w%2&&s/

.*//||s;

;

(There is a trailing newline that I don't know how to show with the markdown, but you need it).

Needs -p as well as -M5.010 or -E to run :

perl -pE '($t,$v,$w)=($_,(abs)x2);$k=$_.$k for 1..$v;map{$r.=$_ for(@v=1..$_-1),$_ x(2*$v---$w%2),reverse@v;$r.=$/}1..$v;$_=$r.~~reverse$r;eval"y/1-$w/$k/"if$t<0;$w%2&&s/

.*//||s;

;
' <<< 5

Damn, this is too long... I'll try some other approaches when I have some time.


答:
Mathematica, 53 bytes

Doesn't beat Martin Ender's answer, which uses the built-in IntegerPartitions function (and built-ins are totally fine by me).  (Nor does it beat feersum's answer, which I didn't see until too late.) But I wanted to practice a golfed recursive function.

```<code>If[#<1,{{}},Join@@Table[#~Append~j&/@#0[#-j],{j,#}]]&
</code>```

Recursively generates all compositions, by generating all possible final numbers j and then calling itself on #-j where # is the input.

Title: List all ordered partitions of n

Body:
Mathematica, 53 bytes

Doesn't beat Martin Ender's answer, which uses the built-in IntegerPartitions function (and built-ins are totally fine by me).  (Nor does it beat feersum's answer, which I didn't see until too late.) But I wanted to practice a golfed recursive function.

If[#<1,{{}},Join@@Table[#~Append~j&/@#0[#-j],{j,#}]]&

Recursively generates all compositions, by generating all possible final numbers j and then calling itself on #-j where # is the input.


答:
Python 2, 109 bytes

n=input()
a=abs(n)
s=a*2-a%2
r=range(s)
for y in r:print[(min,max)[n<0](x+1,s-x,y+1,s-y)-(n<0)*s/2for x in r]
```

Title: Create a pyramidal matrix


答:
Retina, 32 bytes

Byte count assumes ISO 8859-1 encoding.

```<code>.+
$*
+%1`1
!$'¶$`,!
!+
$.&
A`^,
</code>```

Try it online!

Explanation

This works similar to my CJam answer. We go through a list N ones and at each position we take both branches of the binary decision a) increment the last value or b) start a new value at 1.

Stage 1

```<code>.+
$*
</code>```

Convert the input to unary.

Stage 2

```<code>+%1`1
!$'¶$`,!
</code>```

The + tells Retina to execute this stage in a loop until the output stops changing. The % tells it to split the input into lines before applying the stage and join them back together afterwards. By putting the % after the +, Retina splits and rejoins after each iteration. One iteration of the stage makes one of those decisions I mentioned and thereby bifurcates the current set of partitions.

How it actually works is that it matches a 1 (but only the first one as indicated by the 1 in front of the backtick), and replaces it with ! (which we'll use as the unary digit of our output), followed by the remaining 1s on this row (this increments the last value). Then on another line (¶) it prints the prefix of the current line, followed by ,!, which inserts a separator and then starts the next value at 1.

Stage 3

```<code>!+
$.&
</code>```

This converts the runs of ! to decimal integers by replacing them with their length.

Stage 4

```<code>A`^,
</code>```

And finally, we notice that we've generated twice as many lines as we wanted, and half of them start with a , (those where we initially made the decision of splitting, even though there wasn't anything to split after yet). Therefore, we discard all lines that start with a ,.

Title: List all ordered partitions of n

Body:
Retina, 32 bytes

Byte count assumes ISO 8859-1 encoding.

.+
$*
+%1`1
!$'¶$`,!
!+
$.&
A`^,

Try it online!

Explanation

This works similar to my CJam answer. We go through a list N ones and at each position we take both branches of the binary decision a) increment the last value or b) start a new value at 1.

Stage 1

.+
$*

Convert the input to unary.

Stage 2

+%1`1
!$'¶$`,!

The + tells Retina to execute this stage in a loop until the output stops changing. The % tells it to split the input into lines before applying the stage and join them back together afterwards. By putting the % after the +, Retina splits and rejoins after each iteration. One iteration of the stage makes one of those decisions I mentioned and thereby bifurcates the current set of partitions.

How it actually works is that it matches a 1 (but only the first one as indicated by the 1 in front of the backtick), and replaces it with ! (which we'll use as the unary digit of our output), followed by the remaining 1s on this row (this increments the last value). Then on another line (¶) it prints the prefix of the current line, followed by ,!, which inserts a separator and then starts the next value at 1.

Stage 3

!+
$.&

This converts the runs of ! to decimal integers by replacing them with their length.

Stage 4

A`^,

And finally, we notice that we've generated twice as many lines as we wanted, and half of them start with a , (those where we initially made the decision of splitting, even though there wasn't anything to split after yet). Therefore, we discard all lines that start with a ,.


答:
05AB1E, <s>9</s> <s>8</s> 9 bytes

Uses the CP-1252 encoding

```<code>ZU¿%²X>‹‹
</code>```

Explanation

```<code>          # true if
   %      # target size modulo
ZU¿       # gcd of decanter sizes
        ‹ # is smaller than
    ²X>‹  # target size is less than or equal to max decanter size
</code>```

Try it online!

Saved 1 byte utilizing the less than trick from Luis Mendo's MATL answer

Title: The Decanting Problem

Body:
05AB1E, <s>9</s> <s>8</s> 9 bytes

Uses the CP-1252 encoding

ZU¿%²X>‹‹

Explanation

          # true if
   %      # target size modulo
ZU¿       # gcd of decanter sizes
        ‹ # is smaller than
    ²X>‹  # target size is less than or equal to max decanter size

Try it online!

Saved 1 byte utilizing the less than trick from Luis Mendo's MATL answer


问:
Implement tab completion
Tab completion is a useful feature that auto-completes partially written commands.  You're going to be implementing it.

For example, if the available commands were ['apply','apple','apple pie','eat'], then a would complete to  appl, as all of the commands that start with a also start with appl.

Input/Output

You need to input a string, A, and a set of strings, B.

You need to output the longest common prefix of all B that starts with A.

If none of the options starts with A, then return A

You can assume that B is nonempty, and that all strings are nonempty

You cannot assume that any of the options start with A, nor that the common prefix will be longer than A

You can be case sensitive or case insensitive.

You only need to handle printable ASCII

Built-ins that explicitly do this task are allowed

Test cases:

```<code>'a'       ['apply','apple','apple pie','eat'] => 'appl'
'a'       ['apple pie']                       => 'apple pie'
'apple'   ['eat','dine']                      => 'apple'
'program' ['programa','programb']             => 'program'
'*%a('    ['*%a()-T>','*%a()-T<','@Da^n&']    => '*%a()-T'
'a'       ['abs','absolute','answer']         => 'a'
'a'       ['a','abs']                         => 'a'
'one to'  ['one to one','one to many']        => 'one to '
</code>```

Note the trailing space on the last test case

This is a code-golf, so make your answers as short as possible!

答:
Python 2, 122 bytes

```<code>s=input();l=[x for x in input()if x[:len(s)]==s]or[s];i=len(l[0])
while len(l)>1:i-=1;l=set(x[:i]for x in l)
print l.pop()
</code>```

Full program; takes string and list from stdin exactly as given in the examples, except the inputs must be on separate lines.

Verify all test cases

Title: Implement tab completion

Body:
Python 2, 122 bytes

s=input();l=[x for x in input()if x[:len(s)]==s]or[s];i=len(l[0])
while len(l)>1:i-=1;l=set(x[:i]for x in l)
print l.pop()

Full program; takes string and list from stdin exactly as given in the examples, except the inputs must be on separate lines.

Verify all test cases


答:
MATL, 10 bytes

```<code>&Zd\&G<~a<
</code>```

Try it online!

This uses @xnor's approach.

```<code>&Zd    % Take array C as input. Compute the gcd of its elements
\      % Take number G as input. Compute that number modulo the above. Call this A
&G     % Push the two inputs again: C, then G
<~a    % Gives 1 if some element of C is at least G; 0 otherwise. Call this B
<      % Gives true if A is 0 and B is 1; otherwise gives false
</code>```

Title: The Decanting Problem

Body:
MATL, 10 bytes

&Zd\&G<~a<

Try it online!

This uses @xnor's approach.

&Zd    % Take array C as input. Compute the gcd of its elements
\      % Take number G as input. Compute that number modulo the above. Call this A
&G     % Push the two inputs again: C, then G
<~a    % Gives 1 if some element of C is at least G; 0 otherwise. Call this B
<      % Gives true if A is 0 and B is 1; otherwise gives false


答:
EXCEL: 126 bytes

=MAX(MIN(MIN(CELL("row",RC)-1,CELL("col",RC)-1),MIN(((ABS(R1C1)-1)*2+3)-CELL("row",RC),((ABS(R1C1)-1)*2+3)-CELL("col",RC))),0)

Try it online*

Note: this answer uses R1C1 Notation. If you're going to try this yourself. you need to turn that on in Excel options.

the formula given needs to be in every cell present beyond (2,2). Put your desired pyramid size into (1,1).

quick screen-cap of the formula in action:

Here is an Additional picture of some fun with conditional formatting!

*It takes a very long time to update, currently.

Title: Create a pyramidal matrix


答:
JavaScript (ES6), 75 bytes

```<code>(s,a)=>/^(.*).*(\n\1.*)*$/.exec(a.filter(e=>e.startsWith(s)).join`
`)[1]||s
</code>```

Explanation: Filters on all matching prefixes, then joins with newlines and matches against a regex that finds the longest common prefix of all lines. If there are no prefixes then the regex returns an empty string in which case we simply return the original string.

Title: Implement tab completion

Body:
Tab completion is a useful feature that auto-completes partially written commands.  You're going to be implementing it.

For example, if the available commands were ['apply','apple','apple pie','eat'], then a would complete to  appl, as all of the commands that start with a also start with appl.

Input/Output

You need to input a string, A, and a set of strings, B.

You need to output the longest common prefix of all B that starts with A.

If none of the options starts with A, then return A

You can assume that B is nonempty, and that all strings are nonempty

You cannot assume that any of the options start with A, nor that the common prefix will be longer than A

You can be case sensitive or case insensitive.

You only need to handle printable ASCII

Built-ins that explicitly do this task are allowed

Test cases:

```<code>'a'       ['apply','apple','apple pie','eat'] => 'appl'
'a'       ['apple pie']                       => 'apple pie'
'apple'   ['eat','dine']                      => 'apple'
'program' ['programa','programb']             => 'program'
'*%a('    ['*%a()-T>','*%a()-T<','@Da^n&']    => '*%a()-T'
'a'       ['abs','absolute','answer']         => 'a'
'a'       ['a','abs']                         => 'a'
'one to'  ['one to one','one to many']        => 'one to '
</code>```

Note the trailing space on the last test case

This is a code-golf, so make your answers as short as possible!

Body:
JavaScript (ES6), 75 bytes

(s,a)=>/^(.*).*(\n\1.*)*$/.exec(a.filter(e=>e.startsWith(s)).join`
`)[1]||s

Explanation: Filters on all matching prefixes, then joins with newlines and matches against a regex that finds the longest common prefix of all lines. If there are no prefixes then the regex returns an empty string in which case we simply return the original string.


答:
PARI/GP, 31 bytes

Pretty much straightforward. Checking the max (vecmax) is very costly, I wonder if it can be done better.

```<code>f(c,g)=g%gcd(c)<1&&vecmax(c)>=g
</code>```

Title: The Decanting Problem

Body:
PARI/GP, 31 bytes

Pretty much straightforward. Checking the max (vecmax) is very costly, I wonder if it can be done better.

f(c,g)=g%gcd(c)<1&&vecmax(c)>=g


问:
Is this number a prime?
Believe it or not, we do not yet have a code golf challenge for a simple primality test. While it may not be the most interesting challenge, particularly for "usual" languages, it can be nontrivial in many languages.

Rosetta code features lists by language of idiomatic approaches to primality testing, one using the Miller-Rabin test specifically and another using trial division. However, "most idiomatic" often does not coincide with "shortest." In an effort to make Programming Puzzles and Code Golf the go-to site for code golf, this challenge seeks to compile a catalog of the shortest approach in every language, similar to "Hello, World!" and Golf you a quine for great good!.

Furthermore, the capability of implementing a primality test is part of our definition of programming language, so this challenge will also serve as a directory of proven programming languages.

Task

Write a full program that, given a strictly positive integer n as input, determines whether n is prime and prints a truthy or falsy value accordingly.

For the purpose of this challenge, an integer is prime if it has exactly two strictly positive divisors. Note that this excludes 1, who is its only strictly positive divisor.

Your algorithm must be deterministic (i.e., produce the correct output with probability 1) and should, in theory, work for arbitrarily large integers. In practice, you may assume that the input can be stored in your data type, as long as the program works for integers from 1 to 255.

Input

If your language is able to read from STDIN, accept command-line arguments or any other alternative form of user input, you can read the integer as its decimal representation, unary representation (using a character of your choice), byte array (big or little endian) or single byte (if this is your languages largest data type).

If (and only if) your language is unable to accept any kind of user input, you may hardcode the input in your program.

In this case, the hardcoded integer must be easily exchangeable. In particular, it may appear only in a single place in the entire program.

For scoring purposes, submit the program that corresponds to the input 1.

Output

Output has to be written to STDOUT or closest alternative.

If possible, output should consist solely of a truthy or falsy value (or a string representation thereof), optionally followed by a single newline.

The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation.

Additional rules

This is not about finding the language with the shortest approach for prime testing, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted.

Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

The language Piet, for example, will be scored in codels, which is the natural choice for this language.

Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. If anyone wants to abuse this by creating a language where the empty program performs a primality test, then congrats for paving the way for a very boring answer.

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck derivatives like Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

Built-in functions for testing primality are allowed. This challenge is meant to catalog the shortest possible solution in each language, so if it's shorter to use a built-in in your language, go for it.

Unless they have been overruled earlier, all standard code-golf rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf; these are still useful to this question as it tries to compile a catalog as complete as possible. However, do primarily upvote answers in languages where the author actually had to put effort into golfing the code.

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Ruby, 33 bytes

A little longer than other solutions, but doesn't require flags:

require'prime';p$*[0].to_i.prime?

Can be run putting in a file, say prime.rb:

ruby prime.rb 97

Or directly on the command line:

ruby -e "require'prime';p$*[0].to_i.prime?" 97

Title: Is this number a prime?


答:
JavaScript (ES6), 58 bytes

```<code>(n,a)=>a.some(e=>n<=e)&n%a.reduce(g=(d,e)=>d?g(e%d,d):e)<1
</code>```

Another port of @xnor's answer. Yes, I get to use reduce again!

Title: The Decanting Problem

Body:
JavaScript (ES6), 58 bytes

(n,a)=>a.some(e=>n<=e)&n%a.reduce(g=(d,e)=>d?g(e%d,d):e)<1

Another port of @xnor's answer. Yes, I get to use reduce again!


答:
PowerShell v3+, 112 bytes

```<code>param($a,$b)if($c=@($b-like"$a*")){([char[]]$c[0]|%{($i+="$_")}|?{($c-like"$_*").count-eq$c.count})[-1]}else{$a}
</code>```

Takes input as a string $a and an array of strings $b. Uses the -like operator to pull out those elements from $b that (case-insensitive) starts with $a, explicitly cast those as an array @(...) (since the result could be one match as a scalar, in which case indexing later fails), and store that array into $c.

That forms the if clause. If there's nothing in $c (i.e., nothing starts with $a, so the array is empty), then output $a with the else. Otherwise ...

We cast the first element of $c as a char-array and loop through each element, string-concatenating with the previous $i and placing the strings on the pipeline via encapsulating parens. Those are filtered through |?{...} (the Where-Object clause) to verify that the .count of $c is -equal to the .count of things in $c that are -like the substring (i.e., the substring matches everything in $c). Since we're building our substrings in order shortest to longest, we need the last [-1] of the resultant strings.

Test Cases

```<code>PS C:\Tools\Scripts\golfing> $tests=@('a',@('apply','apple','apple pie','eat')),@('a',@('apple pie')),@('apple',@('eat','dine')),@('program',@('programa','programb')),@('one to',@('one to one','one to many')),@('*%a(',@('*%a()-T>', '*%a()-T<', '@Da^n&'))

PS C:\Tools\Scripts\golfing> $tests|%{""+$_[0]+" ("+($_[1]-join',')+") -> "+(.\implement-tab-completion.ps1 $_[0] $_[1])}
a (apply,apple,apple pie,eat) -> appl
a (apple pie) -> apple pie
apple (eat,dine) -> apple
program (programa,programb) -> program
one to (one to one,one to many) -> one to
*%a( (*%a()-T>,*%a()-T<,@Da^n&) -> *%a()-T
</code>```

Title: Implement tab completion

Body:
PowerShell v3+, 112 bytes

param($a,$b)if($c=@($b-like"$a*")){([char[]]$c[0]|%{($i+="$_")}|?{($c-like"$_*").count-eq$c.count})[-1]}else{$a}

Takes input as a string $a and an array of strings $b. Uses the -like operator to pull out those elements from $b that (case-insensitive) starts with $a, explicitly cast those as an array @(...) (since the result could be one match as a scalar, in which case indexing later fails), and store that array into $c.

That forms the if clause. If there's nothing in $c (i.e., nothing starts with $a, so the array is empty), then output $a with the else. Otherwise ...

We cast the first element of $c as a char-array and loop through each element, string-concatenating with the previous $i and placing the strings on the pipeline via encapsulating parens. Those are filtered through |?{...} (the Where-Object clause) to verify that the .count of $c is -equal to the .count of things in $c that are -like the substring (i.e., the substring matches everything in $c). Since we're building our substrings in order shortest to longest, we need the last [-1] of the resultant strings.

Test Cases

PS C:\Tools\Scripts\golfing> $tests=@('a',@('apply','apple','apple pie','eat')),@('a',@('apple pie')),@('apple',@('eat','dine')),@('program',@('programa','programb')),@('one to',@('one to one','one to many')),@('*%a(',@('*%a()-T>', '*%a()-T<', '@Da^n&'))

PS C:\Tools\Scripts\golfing> $tests|%{""+$_[0]+" ("+($_[1]-join',')+") -> "+(.\implement-tab-completion.ps1 $_[0] $_[1])}
a (apply,apple,apple pie,eat) -> appl
a (apple pie) -> apple pie
apple (eat,dine) -> apple
program (programa,programb) -> program
one to (one to one,one to many) -> one to
*%a( (*%a()-T>,*%a()-T<,@Da^n&) -> *%a()-T


问:
Simulate the Universe!
One nice property of a Turing-complete language is that it can be used to write any program, up to and including the simulation of the entire Universe.

Your job is to do exactly that: write a program which simulates the Universe.

Note: although I don't doubt you'll be able to accomplish this task, nowadays I don't have enough spare time to verify whether all 1090 of the particles in your simulation do what they really should do. Therefore, solely to simplify testing and evaluation, it is enough if your universe simulator only works with a single starting particle. To keep things interesting, let's assume this particle is the recently discovered Higgs Boson.

Your universe starts with nothing but a single Higgs Boson of approximately 120 GeV in the middle of it. To not make the output too long, let's make this universe tick at only 10-25 seconds instead of its "usual clock rate" of 5.4×10−44 seconds..

This Higgs boson will decay sooner or later as it has a half-life of 1.6×10−22 seconds, so at every tick of the simulation, it has a 0.0433% chance of decaying. You can check here what it will decay into. To have a central and simplified requirement, I list the branching ratios you should use:

Running the simulation

At each tick of the simulation, the Higgs boson has a 0.0433% chance of decaying. If that happens, it will decay into the following particles, with the listed probabilities (you should use these names in the output):

bottom quark + bottom antiquark (64.8%)

2 W bosons (14.1%)

2 gluons (8.82%)

tau lepton + antitau lepton (7.04%)

charm quark + charm antiquark (3.27%)

2 Z bosons (1.59%)

2 photons (0.223%)

1 Z boson + 1 photon (0.111%)

muon + antimuon (0.0244%)

top quark + top antiquark (0.0216%)

For a total of 100%.

Some of these particles will decay further.

W boson: half-life of 10-25 seconds, this means a 50% chance to decay at every tick into one of the following, with equal probabilities:

positron + neutrino

antimuon + neutrino

antitau lepton + neutrino

Z boson: half-life of 10-25 seconds, this means a 50% chance to decay at every tick into one of the following:

neutrino + antineutrino (20.6%)

electron + positron (3.4%)

muon + antimuon (3.4%)

tau lepton + antitau lepton (3.4%)

down quark + down antiquark (15.2%)

strange quark + strange antiquark (15.2%)

bottom quark + bottom antiquark (15.2%)

up quark + up antiquark (11.8%)

charm quark + charm antiquark (11.8%)

top quark: half-life of 5×10-25 seconds, this means a 12.95% chance to decay at every tick into the following, with equal probabilities:

W boson + down quark

W boson + strange quark

W boson + bottom quark

Of course, the W boson will also soon decay...

The top antiquark behaves similarly to the top quark: it decay into a W boson and a d/s/b antiquark.

All other particles (so all except for the Z and W bosons and top quarks) have a half life many orders of magnitude longer, so to not clutter the output, they are all considered stable for our simulation.

As the universe is largely empty, all the particles will have enough space for themselves and will not interact with each other. Therefore all individual particles are independent from each other in every regard, including the probabilities of splitting.

Output:

Every tick of the simulation, you have to print the contents of the simulated universe into a new line. For example:

```<code>The universe contains 1 Higgs boson.
The universe contains 1 Higgs boson.
The universe contains 1 Higgs boson.
The universe contains 1 Higgs boson.
The universe contains 2 W bosons.
The universe contains 2 W bosons.
The universe contains 1 W boson, 1 positron and 1 neutrino.
The universe contains 1 positron, 1 antitau lepton and 2 neutrinos.
Simulation ended after 0.8 yoctoseconds.
</code>```

The order of the particles in the line is not important. The formatting, however, must be exactly as in the example above, including punctuation and pluralization. If you simulate an entire (mini-) universe, it should look nice (And I wanted to eliminate the abusing of a not sufficiently strict output requirement)

Each line corresponds to 0.1 yoctoseconds, but you will be forgiven if it takes longer than that for your program to print the output.

The simulation ends when only "stable" particles remain.

Scoring

Standard code golf rules apply.

The random number generator can be pseudo-random, but you must seed it if the language doesn't seed it by default. The probability distribution of your RNG must be uniform.

You will get a bonus -10% to the code size if the program takes an integer as an input, and starts with that many Higgs bosons.

Exception for Turing machine enthusiasts.

For those who dare to try their luck with an actual Turing machine or a similar language (like Brainfuck), their task is made easier by the following rule changes (only applicable if the language is a Brainfuck-derivative or otherwise a very simplified Turing-machine, incapable of assignment, lacking an ALU, and values on the tape can only be incremented and decremented by one):

The particle names are simplified to d, s, b, t, u, c for the quarks, v for the neutrino, T for tau lepton, m for muon, g for gluon, p for photon, Z, W and H for the bosons, - for the electron and + for the positron. At each tick, an input with the value of 0 or 1 are provided from the standard input, indicated whether the first unstable particle in the list decays or not.

The example output will therefore become

```<code>H
H
H
H
W W
W W
W + n
+ !T n n
</code>```

答:
C#6, <s>3619</s> <s>3617</s> <s>3611</s> 3586 - 10% = 3227.4 bytes

Program takes two optional arguments for the number of starting Higgs Bosons and the seed to use for the Random class.

```<code>using System;using System.Collections.Generic;class a{List<P>L;List<Q>S;double Y;static void Main(string[]a){a b;b=a.Length<1?new a():a.Length<2?new a(int.Parse(a[0])):new a(int.Parse(a[0]),int.Parse(a[1]));}a(int j=1,int e=1){Random r=new Random(e);L=new List<P>();S=new List<Q>();for(int i=0;i<j;i++)L.Add(new H());while(L.Count>0){List<P>l=new List<P>();foreach(P p in L){List<P>d=p.C(r);if(d!=null)foreach(P y in d){if(y.GetType()==typeof(Q))S.Add((Q)y);else l.Add((P)y);}else l.Add(p);}L=l;Y+=.1;W();}var s=$"Simulation ended after {Y} yoctosecond";if(Y!=1d)s+="s";Console.WriteLine(s+".");}void W(){var t="";Dictionary<string,int>N=new Dictionary<string,int>();int M=0;foreach(P x in L){t=x+"";if(N.ContainsKey(t))N[t]++;else{N.Add(t,1);M++;}}foreach(Q x in S){t=x+"";if(N.ContainsKey(t))N[t]++;else{N.Add(t,1);M++;}}var o="The universe contains ";int i=N.Keys.Count;foreach(var x in N.Keys){i--;if(M==1){o+=$"{N[x]} {x}";if(N[x]!=1)o+="s";}else if(M==2){o+=$"{N[x]} {x}";if(N[x]!=1)o+="s";if(i!=0)o+=" and ";}else{if(i<1){o+=$"and {N[x]} {x}";if(N[x]!=1)o+="s";}else{o+=$"{N[x]} {x}";if(N[x]!=1)o+="s";o+=", ";}}}Console.WriteLine(o+".");}}abstract class P{public static string[]Z=new string[]{"photon","gluon","positron","electron","quark","lepton","muon","neutrino"};public double l;public abstract List<P>D(Random r);public List<P>C(Random r){List<P>d=null;if(r.NextDouble()<l)d=D(r);return d;}}class H:P{public H(){l=.000433;}public override List<P>D(Random r){var d=new List<P>();Action<P>U=d.Add;var n=r.NextDouble();if(n<.648){U(new Q("bottom "+Z[4]));U(new Q("bottom anti"+Z[4]));}else if(n<.789){U(new W());U(new W());}else if(n<.8772){U(new Q(Z[1]));U(new Q(Z[1]));}else if(n<.9476){U(new Q("tau "+Z[5]));U(new Q("antitau "+Z[5]));}else if(n<.9803){U(new Q("charm "+Z[4]));U(new Q("charm anti"+Z[4]));}else if(n<.9962){U(new Z());U(new Z());}else if(n<.99843){U(new Q(Z[0]));U(new Q(Z[0]));}else if(n<.99954){U(new Z());U(new Q(Z[0]));}else if(n<.999784){U(new Q(Z[6]));U(new Q("anti"+Z[6]));}else{U(new T(0>1));U(new T(1>0));}return d;}public override string ToString(){return"Higgs Boson";}}class W:P{public W(){l=.5;}public override List<P> D(Random r){var d=new List<P>();var n=r.NextDouble();d.Add(new Q(Z[7]));if(n<1/3d)d.Add(new Q(Z[2]));else if(n<2/3d)d.Add(new Q("anti"+Z[6]));else d.Add(new Q("antitau "+Z[5]));return d;}public override string ToString(){return"W Boson";}}class Z:P{public Z(){l=.5;}public override List<P>D(Random r){var d=new List<P>();var n=r.NextDouble();Action<P>U=d.Add;var t=Z[4];if(n<.206){U(new Q(Z[7]));U(new Q("anti"+Z[7]));}else if(n<.24){U(new Q(Z[3]));U(new Q(Z[2]));}else if(n<.274){U(new Q(Z[6]));U(new Q("anti"+Z[6]));}else if(n<.308){U(new Q("tau "+Z[5]));U(new Q("antitau "+Z[5]));}else if(n<.46){U(new Q("down "+t));U(new Q("down anti"+t));}else if(n<.612){U(new Q("strange "+t));U(new Q("strange anti"+t));}else if(n<.764){U(new Q("bottom "+t));U(new Q("bottom anti"+t));}else if(n<.882){U(new Q("up "+t));U(new Q("up anti"+t));}else{U(new Q("charm "+t));U(new Q("charm anti"+t));}return d;}public override string ToString(){return"Z Boson";}}class T:P{bool A;public T(bool a){A=a;l=.1295;}public override List<P>D(Random r){var d=new List<P>();var n=r.NextDouble();d.Add(new W());if(n<1/3d)d.Add(new Q("down "+Z[4]));else if(n <2/3.0)d.Add(new Q("strange "+Z[4]));else d.Add(new Q("bottom "+Z[4]));return d;}public override string ToString(){var r=A?"top anti":"top ";return r+Z[4];}}class Q:P{string N;public Q(string n){N=n;}public override List<P>D(Random r){return null;}public override string ToString(){return N;}}
</code>```

I should not have used objects for this, I'll probably try to do a second solution using arrays instead, but it'd probably be similar to the C++ solution posted already.  The number of Higgs Bosons I can handle is severely limited as well, I think at least an hour for H=1,000,000.  Smaller numbers run reasonably well though.

Sample output:

```<code>$ b
// Default h=1,seed=1
The universe contains 1 Higgs Boson.
...
The universe contains 1 bottom quark and 1 bottom antiquark.
Simulation ended after 65.5000000000006 yoctosecond.

$ b 10 12345
The universe contains 10 Higgs Bosons.
The universe contains 9 Higgs Bosons, 1 bottom quark, and 1 bottom antiquark.
The universe contains 8 Higgs Bosons, 2 W Bosons, 1 bottom quark, and 1 bottom antiquark.
The universe contains 8 Higgs Bosons, 1 bottom quark, 1 bottom antiquark, 2 neutrinos, and 2 antitau leptons.
The universe contains 7 Higgs Bosons, 2 bottom quarks, 2 bottom antiquarks, 2 neutrinos, and 2 antitau leptons.
The universe contains 6 Higgs Bosons, 3 bottom quarks, 3 bottom antiquarks, 2 neutrinos, and 2 antitau leptons.
The universe contains 5 Higgs Bosons, 4 bottom quarks, 4 bottom antiquarks, 2 neutrinos, and 2 antitau leptons.
The universe contains 2 W Bosons, 4 Higgs Bosons, 4 bottom quarks, 4 bottom antiquarks, 2 neutrinos, and 2 antitau leptons.
The universe contains 1 W Boson, 4 Higgs Bosons, 4 bottom quarks, 4 bottom antiquarks, 3 neutrinos, 2 antitau leptons, and 1 antimuon.
The universe contains 4 Higgs Bosons, 4 bottom quarks, 4 bottom antiquarks, 4 neutrinos, 2 antitau leptons, and 2 antimuons.
The universe contains 3 Higgs Bosons, 5 bottom quarks, 5 bottom antiquarks, 4 neutrinos, 2 antitau leptons, and 2 antimuons.
The universe contains 2 Higgs Bosons, 6 bottom quarks, 6 bottom antiquarks, 4 neutrinos, 2 antitau leptons, and 2 antimuons.
The universe contains 1 Higgs Boson, 2 W Bosons, 6 bottom quarks, 6 bottom antiquarks, 4 neutrinos, 2 antitau leptons, and 2 antimuons.
The universe contains 1 Higgs Boson, 1 W Boson, 6 bottom quarks, 6 bottom antiquarks, 5 neutrinos, 2 antitau leptons, and 3 antimuons.
The universe contains 1 Higgs Boson, 6 bottom quarks, 6 bottom antiquarks, 6 neutrinos, 2 antitau leptons, 3 antimuons, and 1 positron.
The universe contains 7 bottom quarks, 7 bottom antiquarks, 6 neutrinos, 2 antitau leptons, 3 antimuons, and 1 positron.
Simulation ended after 540.500000000054 yoctoseconds.
</code>```

<s>I'll post the last two lines for the h=1000000 run when it finishes, probably later today.</s> As promised:

```<code>$ b 1000000
(a few hours, 35K lines, and 15MB later)
The universe contains 653391 bottom quarks, 653271 bottom antiquarks, 36336 charm quarks, 36336 charm antiquarks, 176724 gluons, 71397 tau leptons, 165604 antitau leptons, 5626 photons, 288869 neutrinos, 95047 positrons, 95556 antimuons, 5254 strange quarks, 5130 strange antiquarks, 1389 muons, 1081 electrons, 5240 down quarks, 5104 down antiquarks, 6529 antineutrinos, 3862 up quarks, and 3862 up antiquarks.
Simulation ended after 3599.29999999782 yoctoseconds.
</code>```

Title: Simulate the Universe!

Body:
C#6, <s>3619</s> <s>3617</s> <s>3611</s> 3586 - 10% = 3227.4 bytes

Program takes two optional arguments for the number of starting Higgs Bosons and the seed to use for the Random class.

using System;using System.Collections.Generic;class a{List<P>L;List<Q>S;double Y;static void Main(string[]a){a b;b=a.Length<1?new a():a.Length<2?new a(int.Parse(a[0])):new a(int.Parse(a[0]),int.Parse(a[1]));}a(int j=1,int e=1){Random r=new Random(e);L=new List<P>();S=new List<Q>();for(int i=0;i<j;i++)L.Add(new H());while(L.Count>0){List<P>l=new List<P>();foreach(P p in L){List<P>d=p.C(r);if(d!=null)foreach(P y in d){if(y.GetType()==typeof(Q))S.Add((Q)y);else l.Add((P)y);}else l.Add(p);}L=l;Y+=.1;W();}var s=$"Simulation ended after {Y} yoctosecond";if(Y!=1d)s+="s";Console.WriteLine(s+".");}void W(){var t="";Dictionary<string,int>N=new Dictionary<string,int>();int M=0;foreach(P x in L){t=x+"";if(N.ContainsKey(t))N[t]++;else{N.Add(t,1);M++;}}foreach(Q x in S){t=x+"";if(N.ContainsKey(t))N[t]++;else{N.Add(t,1);M++;}}var o="The universe contains ";int i=N.Keys.Count;foreach(var x in N.Keys){i--;if(M==1){o+=$"{N[x]} {x}";if(N[x]!=1)o+="s";}else if(M==2){o+=$"{N[x]} {x}";if(N[x]!=1)o+="s";if(i!=0)o+=" and ";}else{if(i<1){o+=$"and {N[x]} {x}";if(N[x]!=1)o+="s";}else{o+=$"{N[x]} {x}";if(N[x]!=1)o+="s";o+=", ";}}}Console.WriteLine(o+".");}}abstract class P{public static string[]Z=new string[]{"photon","gluon","positron","electron","quark","lepton","muon","neutrino"};public double l;public abstract List<P>D(Random r);public List<P>C(Random r){List<P>d=null;if(r.NextDouble()<l)d=D(r);return d;}}class H:P{public H(){l=.000433;}public override List<P>D(Random r){var d=new List<P>();Action<P>U=d.Add;var n=r.NextDouble();if(n<.648){U(new Q("bottom "+Z[4]));U(new Q("bottom anti"+Z[4]));}else if(n<.789){U(new W());U(new W());}else if(n<.8772){U(new Q(Z[1]));U(new Q(Z[1]));}else if(n<.9476){U(new Q("tau "+Z[5]));U(new Q("antitau "+Z[5]));}else if(n<.9803){U(new Q("charm "+Z[4]));U(new Q("charm anti"+Z[4]));}else if(n<.9962){U(new Z());U(new Z());}else if(n<.99843){U(new Q(Z[0]));U(new Q(Z[0]));}else if(n<.99954){U(new Z());U(new Q(Z[0]));}else if(n<.999784){U(new Q(Z[6]));U(new Q("anti"+Z[6]));}else{U(new T(0>1));U(new T(1>0));}return d;}public override string ToString(){return"Higgs Boson";}}class W:P{public W(){l=.5;}public override List<P> D(Random r){var d=new List<P>();var n=r.NextDouble();d.Add(new Q(Z[7]));if(n<1/3d)d.Add(new Q(Z[2]));else if(n<2/3d)d.Add(new Q("anti"+Z[6]));else d.Add(new Q("antitau "+Z[5]));return d;}public override string ToString(){return"W Boson";}}class Z:P{public Z(){l=.5;}public override List<P>D(Random r){var d=new List<P>();var n=r.NextDouble();Action<P>U=d.Add;var t=Z[4];if(n<.206){U(new Q(Z[7]));U(new Q("anti"+Z[7]));}else if(n<.24){U(new Q(Z[3]));U(new Q(Z[2]));}else if(n<.274){U(new Q(Z[6]));U(new Q("anti"+Z[6]));}else if(n<.308){U(new Q("tau "+Z[5]));U(new Q("antitau "+Z[5]));}else if(n<.46){U(new Q("down "+t));U(new Q("down anti"+t));}else if(n<.612){U(new Q("strange "+t));U(new Q("strange anti"+t));}else if(n<.764){U(new Q("bottom "+t));U(new Q("bottom anti"+t));}else if(n<.882){U(new Q("up "+t));U(new Q("up anti"+t));}else{U(new Q("charm "+t));U(new Q("charm anti"+t));}return d;}public override string ToString(){return"Z Boson";}}class T:P{bool A;public T(bool a){A=a;l=.1295;}public override List<P>D(Random r){var d=new List<P>();var n=r.NextDouble();d.Add(new W());if(n<1/3d)d.Add(new Q("down "+Z[4]));else if(n <2/3.0)d.Add(new Q("strange "+Z[4]));else d.Add(new Q("bottom "+Z[4]));return d;}public override string ToString(){var r=A?"top anti":"top ";return r+Z[4];}}class Q:P{string N;public Q(string n){N=n;}public override List<P>D(Random r){return null;}public override string ToString(){return N;}}

I should not have used objects for this, I'll probably try to do a second solution using arrays instead, but it'd probably be similar to the C++ solution posted already.  The number of Higgs Bosons I can handle is severely limited as well, I think at least an hour for H=1,000,000.  Smaller numbers run reasonably well though.

Sample output:

$ b
// Default h=1,seed=1
The universe contains 1 Higgs Boson.
...
The universe contains 1 bottom quark and 1 bottom antiquark.
Simulation ended after 65.5000000000006 yoctosecond.

$ b 10 12345
The universe contains 10 Higgs Bosons.
The universe contains 9 Higgs Bosons, 1 bottom quark, and 1 bottom antiquark.
The universe contains 8 Higgs Bosons, 2 W Bosons, 1 bottom quark, and 1 bottom antiquark.
The universe contains 8 Higgs Bosons, 1 bottom quark, 1 bottom antiquark, 2 neutrinos, and 2 antitau leptons.
The universe contains 7 Higgs Bosons, 2 bottom quarks, 2 bottom antiquarks, 2 neutrinos, and 2 antitau leptons.
The universe contains 6 Higgs Bosons, 3 bottom quarks, 3 bottom antiquarks, 2 neutrinos, and 2 antitau leptons.
The universe contains 5 Higgs Bosons, 4 bottom quarks, 4 bottom antiquarks, 2 neutrinos, and 2 antitau leptons.
The universe contains 2 W Bosons, 4 Higgs Bosons, 4 bottom quarks, 4 bottom antiquarks, 2 neutrinos, and 2 antitau leptons.
The universe contains 1 W Boson, 4 Higgs Bosons, 4 bottom quarks, 4 bottom antiquarks, 3 neutrinos, 2 antitau leptons, and 1 antimuon.
The universe contains 4 Higgs Bosons, 4 bottom quarks, 4 bottom antiquarks, 4 neutrinos, 2 antitau leptons, and 2 antimuons.
The universe contains 3 Higgs Bosons, 5 bottom quarks, 5 bottom antiquarks, 4 neutrinos, 2 antitau leptons, and 2 antimuons.
The universe contains 2 Higgs Bosons, 6 bottom quarks, 6 bottom antiquarks, 4 neutrinos, 2 antitau leptons, and 2 antimuons.
The universe contains 1 Higgs Boson, 2 W Bosons, 6 bottom quarks, 6 bottom antiquarks, 4 neutrinos, 2 antitau leptons, and 2 antimuons.
The universe contains 1 Higgs Boson, 1 W Boson, 6 bottom quarks, 6 bottom antiquarks, 5 neutrinos, 2 antitau leptons, and 3 antimuons.
The universe contains 1 Higgs Boson, 6 bottom quarks, 6 bottom antiquarks, 6 neutrinos, 2 antitau leptons, 3 antimuons, and 1 positron.
The universe contains 7 bottom quarks, 7 bottom antiquarks, 6 neutrinos, 2 antitau leptons, 3 antimuons, and 1 positron.
Simulation ended after 540.500000000054 yoctoseconds.

<s>I'll post the last two lines for the h=1000000 run when it finishes, probably later today.</s> As promised:

$ b 1000000
(a few hours, 35K lines, and 15MB later)
The universe contains 653391 bottom quarks, 653271 bottom antiquarks, 36336 charm quarks, 36336 charm antiquarks, 176724 gluons, 71397 tau leptons, 165604 antitau leptons, 5626 photons, 288869 neutrinos, 95047 positrons, 95556 antimuons, 5254 strange quarks, 5130 strange antiquarks, 1389 muons, 1081 electrons, 5240 down quarks, 5104 down antiquarks, 6529 antineutrinos, 3862 up quarks, and 3862 up antiquarks.
Simulation ended after 3599.29999999782 yoctoseconds.


答:
Python 2, 112 bytes

```<code>lambda n,h:[a.pop()for a in[{s[:-i]for s in h if s.find(n)==0}for i in range(-len(`h`),0)]+[{n}]if len(a)==1][0]
</code>```

Title: Implement tab completion

Body:
Python 2, 112 bytes

lambda n,h:[a.pop()for a in[{s[:-i]for s in h if s.find(n)==0}for i in range(-len(`h`),0)]+[{n}]if len(a)==1][0]


问:
Decode a Microsoft MS-DOS 5.0 FAT directory entry
The Microsoft FAT file system has a directory table to represent which "files" are in which "folders" on the disk. For the time, these entries crammed a lot of information into a small amount of bits. There are a bunch of technical specifications over on Wiki for the curious, but the challenge here is going to focus on a "simple" decoding of an entry.

Each entry consists of a 32-byte binary word, broken up into several sections. For consistency in this challenge, we'll be using the MS-DOS 5.0 version, the bytes are ordered as big endian, and we're calling byte 0x00 as the left-most, and byte 0x1F as the right-most.

Below is a brief schematic of the relevant sections, and what should be the output for each section (in bold).

The first 11 bytes are the file name in ASCII format (this is where the famous 8.3 filename comes from -- 8 bytes for the file name, 3 bytes for the extension). These are straight ASCII encoding, and should be output as ASCII with a period (.) between.

Note: both the 8 and the 3 parts are padded with spaces to make a full-length entry. The output should ignore spaces (i.e., don't output them).

The file extension may be empty (i.e., all spaces), in which case the output should not output the dot.

Since ASCII only uses the lower 7 bits, the bytes will all have a leading 0.

The next byte (0x0b) is a bitmask of the following:

0x01 Read Only - output RO

0x02 Hidden - output H

0x04 System - output S

0x08 Volume Label - output VL. File size (below) should be output as 0, regardless of its actual entry.

0x10 Subdirectory - output SD. File size (below) should be output as 0, regardless of its actual entry.

0x20 Archive - output A

0x40 Device - ignored for this challenge.

0x80 Reserved - ignored for this challenge.

Since this is a bitmask, multiple flags are possible - all applicable outputs should be concatenated together in any order. For example, 0xff could be ROHSVLSDA (or any other combination).

The next two bytes (0x0c and 0x0d) are not used under MS-DOS 5.0.

The next two bytes (0x0e and 0x0f) are the creation time as follows:

Bits 15 to 11 are the hours in 24-hour format - output 00 to 23

Bits 10 to 5 are the minutes - output 00 to 59

Bits 4 to 0 are the seconds/2 - output 00 to 58 (note that seconds are only in two-second resolution)

For clarification: hhhhhmmmmmmsssss when written big-endian.

The next two bytes (0x10 and 0x11) are the creation date as follows:

Bits 15 to 9 are the year - output 1980 for 0 up to 2107 for 127

Bits 8 to 5 are the months - output 1 to 12 (with or without leading zero)

Bits 4 to 0 are the day - output 0 to 31 (with or without leading zero)

For clarification: yyyyyyymmmmddddd when written big-endian.

The next two bytes (0x12 and 0x13) are the last access date. While used in MS-DOS 5.0, we're ignoring this portion for this challenge.

The next two bytes (0x14 and 0x15) are not used by MS-DOS 5.0.

The next two bytes (0x16 and 0x17) are the last modified time, following the same format as the creation time, above.

The next two bytes (0x18 and 0x19) are the last modified date, following the same format as the creation date, above.

The next two bytes (0x1a and 0x1b) are the cluster location of the file on disk. We're ignoring this portion for this challenge.

The final four bytes (0x1c, 0x1d, 0x1e, and 0x1f) are the file size - output as an unsigned integer, unless the VL or SD flags are set (above), in which case output 0.

Visual representation

```<code>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
\______________________________FILENAME________________________________________________/\_ATTR_/\___NOTUSED____/\_CREATIONTIME_/\_CREATIONDATE_/\__LASTACCESS__/\___NOTUSED____/\_MODIFIEDTIME_/\_MODIFIEDDATE_/\___NOTUSED____/\___________FILESIZE___________/
</code>```

Input

A single 32-byte word (i.e., 256 bits), in whatever format is convenient.

This could be as a string of 1 and 0, as several unsigned ints, an array of Boolean values, etc.

Please specify in your answer what format you're using for input.

You cannot take multiple input (i.e., an array pre-broken into the relevant byte sizes) unless that is the only way for your language to take input. Parsing the input is part of the challenge.

You can assume input to be valid (for example, you don't need to perform date checking to verify that the date is valid).

Bytes that are unused can be all 0, all 1, etc., just so long as they are present. In the below examples, I used all 0 for the unused bytes.

Output

Either printed to screen or returned, the following:

The filename as an ASCII string

The file attributes as an ASCII string

The creation time and creation date, with appropriate separators (colons, slashes, something to distinguish the components)

The modified time and modified date, again with appropriate separators

The file size

The output can be a space-separated or newline-separated single string, separate elements in an array, etc. Please specify in your answer how your output is formatted.

Rules

Standard I/O formats are acceptable.

Either a full program or a function are acceptable.

Standard loopholes are forbidden.

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

Built-ins that perform exactly this function are forbidden.

Examples

```<code>0111000001110010011011110110011101110010011000010110110101101101011010010110111001100111000001100000000000000000101000100100010001001000110101000000000000000000000000000000000010100010010001000100100011010100000000000000000000000000000000001101000000000000

programm.ing HS 20:18:08 2016/06/20 20:18:08 2016/06/20 53248

0010000000100000001000000010000001110000011100000110001101100111001000000010000000100000000101000000000000000000010111010110110000111101100111110000000000000000000000000000000010100010010001000100100011010100000000000000000011110000000100111111001011100001

ppcg SDS 11:43:24 2010/12/31 20:18:08 2016/06/20 0
</code>```

答:
Perl, 249 bytes

Takes 32 bytes as input, output is separated by newlines. unpack is perfect for this kind of binary structure parsing.

```<code>($f,$e,$a,$C,$M,$s)=unpack"A8A3CxxNx4Nx2N",<>;$f=~s/ //g;$e=~s/ //g;printf"%s
@{[map+(RO,H,S,VL,SD,A)[$a&1<<$_?$_:9],0..5]}
"."%02d:%02d:%02d %d/%d/%d
"x2 .$s*!($a&24),$f.".$e"x!!$e,map{$_>>27,$_>>21&63,$_>>15&62,$_/512%128+1980,$_>>5&15,$_&31}$C,$M
</code>```

Some highlights:

The aforementioned unpack.

The turtle operator @{[]} allows to interpolate code in a string. It actually creates an array reference that is then dereferenced.

"$str1"x!!$str2 is a nice way to return $str1 only if $str2 is a non-empty string.

Below is a version that works on real directory entries, with little-endian fields, and only ignoring right padding on the filename and extension (so, e.g. "    ppcg" doesn't have its initial whitespace removed) (254 bytes)

```<code>($f,$e,$a,$C,$M,$s)=unpack"A8A3CxxVx4Vx2V",<>;$f=~s/ +$//;$e=~s/ +$//;printf"%s
@{[map+(RO,H,S,VL,SD,A)[$a&1<<$_?$_:9],0..5]}
"."%02d:%02d:%02d %d/%d/%d
"x2 .$s*!($a&24),$f.".$e"x!!$e,map{$_>>11&31,$_>>5&63,2*$_&63,($_>>25)+1980,$_>>21&15,$_>>16&31}$C,$M
</code>```

Body:
Perl, 249 bytes

Takes 32 bytes as input, output is separated by newlines. unpack is perfect for this kind of binary structure parsing.

($f,$e,$a,$C,$M,$s)=unpack"A8A3CxxNx4Nx2N",<>;$f=~s/ //g;$e=~s/ //g;printf"%s
@{[map+(RO,H,S,VL,SD,A)[$a&1<<$_?$_:9],0..5]}
"."%02d:%02d:%02d %d/%d/%d
"x2 .$s*!($a&24),$f.".$e"x!!$e,map{$_>>27,$_>>21&63,$_>>15&62,$_/512%128+1980,$_>>5&15,$_&31}$C,$M

Some highlights:

The aforementioned unpack.

The turtle operator @{[]} allows to interpolate code in a string. It actually creates an array reference that is then dereferenced.

"$str1"x!!$str2 is a nice way to return $str1 only if $str2 is a non-empty string.

Below is a version that works on real directory entries, with little-endian fields, and only ignoring right padding on the filename and extension (so, e.g. "    ppcg" doesn't have its initial whitespace removed) (254 bytes)

($f,$e,$a,$C,$M,$s)=unpack"A8A3CxxVx4Vx2V",<>;$f=~s/ +$//;$e=~s/ +$//;printf"%s
@{[map+(RO,H,S,VL,SD,A)[$a&1<<$_?$_:9],0..5]}
"."%02d:%02d:%02d %d/%d/%d
"x2 .$s*!($a&24),$f.".$e"x!!$e,map{$_>>11&31,$_>>5&63,2*$_&63,($_>>25)+1980,$_>>21&15,$_>>16&31}$C,$M