问:
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>```

答:
PHP, 989 - 10% = 890.1 bytes

Sub 1K baby! Thanks vsz, this was a really fun challenge. So many ways to go about it and very hard to verify your output is correct.

The program can take a command line argument to specify the starting number of Higgs bosons, e.g. php universe_simulator.php 5

```<code><?eval(gzinflate(base64_decode('bVNdb9Q6EH3nV4TVSEm0ozRpt/uBcRGlQLlw4QIFWqxQuYm7mza1s4mzdEH73+84WUqFyINzjn1mfMaaAcmltgWDC35hrDU3DDKeLWRN4JC2GqMZLPmylfU1g4Y3tpZ6rhhY7lvZeqWqrNE+A821am1daMMuTa1ktgjUbVWaXAU++jiAn3Jz0xqNIKFbLMKFR/9l96c127LMsdx81z3v0RJVqTJbU4J56dIcF/N548Eh9kk1VgtDTrAyTdHJoNnma7rsFq2p+p0OLLHd0rZjX1yur7QMQtnAKoRKZIs6GA6hGI5HYcphxSDn4g0/EFEcx6O9PRQiGo+mKI7weZqiiCbTGYpTPO3IdDLZRfEaX3dsNpqMUTzDjz2bxhT9Al/2bDYm5Rmebdl0RIfv8N2WzvZHjv46nU2mxJ/iv44nKE7wU0ofnjpj++Qp2aHwt/ifO991+Cm+3WqfOUT47Jc22o3J1mEviPb2qZhjfNWRfdK/xw8dHjuDv6tE8Rm/9EXOpvfq2CPVP/3F0Ww8vu+yq5zwJ3dzsju7M/qqf67O6Icek/y5Q4RP/pQf35O/v5Mf9fKUQctlXcv1+WVRlkFMfVbPVyJJnzxK8E3IYM1j9n1RlCp4CLfhT7jlCYMrLtK7pu3DM9Nqe76SZauaAFrXEtf8wLXFlUj5AFYe9Qdcp4MogNVB8sRv/Ee+HzKVLYxX1Wp+XquqlBk1/w4G4humwxB2aBA8qXNIaB5OFsprdbFSdaO8zGgrC914g+jKFJomxvMRrsJoED0YhHfeoPXISEFGbFhcBpALsGlXRcyI02TmQbgzV25G8xt5G4SPeS8SsdP94H+R/M7eK5OU7si6/D8oPOtC+1ep2saZwCiKaD9JQ3ZBodds0+pGWToRUNDmZgPrIY8StnHPMfhY3LSltIXRntK5yj15aVXtwdpbm8yaRlH1eUOFsv8B')));
</code>```

Here's the same thing with line breaks for, uh... "readability"...

```<code><?eval(gzinflate(base64_decode('bVNdb9Q6EH3nV4TVSEm0ozRpt/uBcRGlQLlw4QIFWqxQuYm7
mza1s4mzdEH73+84WUqFyINzjn1mfMaaAcmltgWDC35hrDU3DDKeLWRN4JC2GqMZLPmylfU1g4Y3tpZ6
rhhY7lvZeqWqrNE+A821am1daMMuTa1ktgjUbVWaXAU++jiAn3Jz0xqNIKFbLMKFR/9l96c127LMsdx8
1z3v0RJVqTJbU4J56dIcF/N548Eh9kk1VgtDTrAyTdHJoNnma7rsFq2p+p0OLLHd0rZjX1yur7QMQtnA
KoRKZIs6GA6hGI5HYcphxSDn4g0/EFEcx6O9PRQiGo+mKI7weZqiiCbTGYpTPO3IdDLZRfEaX3dsNpqM
UTzDjz2bxhT9Al/2bDYm5Rmebdl0RIfv8N2WzvZHjv46nU2mxJ/iv44nKE7wU0ofnjpj++Qp2aHwt/if
O991+Cm+3WqfOUT47Jc22o3J1mEviPb2qZhjfNWRfdK/xw8dHjuDv6tE8Rm/9EXOpvfq2CPVP/3F0Ww8
vu+yq5zwJ3dzsju7M/qqf67O6Icek/y5Q4RP/pQf35O/v5Mf9fKUQctlXcv1+WVRlkFMfVbPVyJJnzxK
8E3IYM1j9n1RlCp4CLfhT7jlCYMrLtK7pu3DM9Nqe76SZauaAFrXEtf8wLXFlUj5AFYe9Qdcp4MogNVB
8sRv/Ee+HzKVLYxX1Wp+XquqlBk1/w4G4humwxB2aBA8qXNIaB5OFsprdbFSdaO8zGgrC914g+jKFJom
xvMRrsJoED0YhHfeoPXISEFGbFhcBpALsGlXRcyI02TmQbgzV25G8xt5G4SPeS8SsdP94H+R/M7eK5OU
7si6/D8oPOtC+1ep2saZwCiKaD9JQ3ZBodds0+pGWToRUNDmZgPrIY8StnHPMfhY3LSltIXRntK5yj15
aVXtwdpbm8yaRlH1eUOFsv8B')));
</code>```

Some output:

```<code>The universe contains 2 Higgs bosons.
[...]
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 2 neutrinos, 1 positron, 1 antimuon, 1 bottom antiquark and 1 bottom quark.
Simulation ended after 153.2 yoctoseconds.
</code>```

Title: Simulate the Universe!

Body:
PHP, 989 - 10% = 890.1 bytes

Sub 1K baby! Thanks vsz, this was a really fun challenge. So many ways to go about it and very hard to verify your output is correct.

The program can take a command line argument to specify the starting number of Higgs bosons, e.g. php universe_simulator.php 5

<?eval(gzinflate(base64_decode('bVNdb9Q6EH3nV4TVSEm0ozRpt/uBcRGlQLlw4QIFWqxQuYm7mza1s4mzdEH73+84WUqFyINzjn1mfMaaAcmltgWDC35hrDU3DDKeLWRN4JC2GqMZLPmylfU1g4Y3tpZ6rhhY7lvZeqWqrNE+A821am1daMMuTa1ktgjUbVWaXAU++jiAn3Jz0xqNIKFbLMKFR/9l96c127LMsdx81z3v0RJVqTJbU4J56dIcF/N548Eh9kk1VgtDTrAyTdHJoNnma7rsFq2p+p0OLLHd0rZjX1yur7QMQtnAKoRKZIs6GA6hGI5HYcphxSDn4g0/EFEcx6O9PRQiGo+mKI7weZqiiCbTGYpTPO3IdDLZRfEaX3dsNpqMUTzDjz2bxhT9Al/2bDYm5Rmebdl0RIfv8N2WzvZHjv46nU2mxJ/iv44nKE7wU0ofnjpj++Qp2aHwt/ifO991+Cm+3WqfOUT47Jc22o3J1mEviPb2qZhjfNWRfdK/xw8dHjuDv6tE8Rm/9EXOpvfq2CPVP/3F0Ww8vu+yq5zwJ3dzsju7M/qqf67O6Icek/y5Q4RP/pQf35O/v5Mf9fKUQctlXcv1+WVRlkFMfVbPVyJJnzxK8E3IYM1j9n1RlCp4CLfhT7jlCYMrLtK7pu3DM9Nqe76SZauaAFrXEtf8wLXFlUj5AFYe9Qdcp4MogNVB8sRv/Ee+HzKVLYxX1Wp+XquqlBk1/w4G4humwxB2aBA8qXNIaB5OFsprdbFSdaO8zGgrC914g+jKFJomxvMRrsJoED0YhHfeoPXISEFGbFhcBpALsGlXRcyI02TmQbgzV25G8xt5G4SPeS8SsdP94H+R/M7eK5OU7si6/D8oPOtC+1ep2saZwCiKaD9JQ3ZBodds0+pGWToRUNDmZgPrIY8StnHPMfhY3LSltIXRntK5yj15aVXtwdpbm8yaRlH1eUOFsv8B')));

Here's the same thing with line breaks for, uh... "readability"...

<?eval(gzinflate(base64_decode('bVNdb9Q6EH3nV4TVSEm0ozRpt/uBcRGlQLlw4QIFWqxQuYm7
mza1s4mzdEH73+84WUqFyINzjn1mfMaaAcmltgWDC35hrDU3DDKeLWRN4JC2GqMZLPmylfU1g4Y3tpZ6
rhhY7lvZeqWqrNE+A821am1daMMuTa1ktgjUbVWaXAU++jiAn3Jz0xqNIKFbLMKFR/9l96c127LMsdx8
1z3v0RJVqTJbU4J56dIcF/N548Eh9kk1VgtDTrAyTdHJoNnma7rsFq2p+p0OLLHd0rZjX1yur7QMQtnA
KoRKZIs6GA6hGI5HYcphxSDn4g0/EFEcx6O9PRQiGo+mKI7weZqiiCbTGYpTPO3IdDLZRfEaX3dsNpqM
UTzDjz2bxhT9Al/2bDYm5Rmebdl0RIfv8N2WzvZHjv46nU2mxJ/iv44nKE7wU0ofnjpj++Qp2aHwt/if
O991+Cm+3WqfOUT47Jc22o3J1mEviPb2qZhjfNWRfdK/xw8dHjuDv6tE8Rm/9EXOpvfq2CPVP/3F0Ww8
vu+yq5zwJ3dzsju7M/qqf67O6Icek/y5Q4RP/pQf35O/v5Mf9fKUQctlXcv1+WVRlkFMfVbPVyJJnzxK
8E3IYM1j9n1RlCp4CLfhT7jlCYMrLtK7pu3DM9Nqe76SZauaAFrXEtf8wLXFlUj5AFYe9Qdcp4MogNVB
8sRv/Ee+HzKVLYxX1Wp+XquqlBk1/w4G4humwxB2aBA8qXNIaB5OFsprdbFSdaO8zGgrC914g+jKFJom
xvMRrsJoED0YhHfeoPXISEFGbFhcBpALsGlXRcyI02TmQbgzV25G8xt5G4SPeS8SsdP94H+R/M7eK5OU
7si6/D8oPOtC+1ep2saZwCiKaD9JQ3ZBodds0+pGWToRUNDmZgPrIY8StnHPMfhY3LSltIXRntK5yj15
aVXtwdpbm8yaRlH1eUOFsv8B')));

Some output:

The universe contains 2 Higgs bosons.
[...]
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 1 Higgs boson, 2 neutrinos, 1 positron and 1 antimuon.
The universe contains 2 neutrinos, 1 positron, 1 antimuon, 1 bottom antiquark and 1 bottom quark.
Simulation ended after 153.2 yoctoseconds.


问:
Prime counting function

Introduction

The Prime Counting Function, also known as the Pi function \$\pi(x)\$, returns the amount of primes less than or equal to x.

Challenge

Your program will take an integer x which you can assume to be positive, and output a single integer equal to the amount of primes less than or equal to x. This is a code-golf challenge, so the winner will be the program with the fewest bytes.

You may use any language of your choosing provided that it existed before this challenge went up, but if the language has a built-in prime-counting function or a primality checking function (such as Mathematica), that function cannot be used in your code.

Example Inputs

Input:

1

Output:

0

Input:

2

Output:

1

Input:

5

Output:

3

A000720 - OEIS

答:
Jelly, 3 bytes

```<code>!Æv
</code>```

Try it online!

How it works

```<code>!Æv  Main link. Argument: n

!    Compute the factorial of n.
 Æv  Count the number of distinct prime factors.
</code>```

ContentLicense: CC BY-SA 4.0

Title: Prime counting function

Body:
Jelly, 3 bytes

!Æv

Try it online!

How it works

!Æv  Main link. Argument: n

!    Compute the factorial of n.
 Æv  Count the number of distinct prime factors.

ContentLicense: CC BY-SA 3.0


问:
Find the minimum and maximum integers in an array, without using builtins

Challenge

Given an array of integers, received from stdin, function arguments, program arguments, or some other method:

Output only the minimum and maximum numbers in the array, through a return value, stdout, or other fitting methods.

Example session

```<code>> minmax( {0, 15, 2, 3, 7, 18, -2, 9, 6, -5, 3, 8, 9, -14} )
-14 18
</code>```

Reference implementation

```<code>// C++14

void minmax(std::vector<int> v) {
    int min = v[0]; int max = v[0];
    for(auto it : v) {
        if (*it < min)
            min = *it;
        if (*it > max)
            max = *it;
    }
    std::cout << min << ' ' << max << std::endl;
}
</code>```

Rules

You may not use a built-in function to calculate the values.

Standard loopholes disallowed.

Creative implementations encouraged.

This is code-golf, shortest answer wins but will not be selected.

Clarifications

If the array contains 1 element you need to output it twice.

If the minimum and maximum values are the same, you need to output them both.

Body:
C, <s>83</s> <s>81</s> 79 bytes

m,M;f(a,s)int*a;{for(m=M=*a;s--;++a)*a<m?m=*a:*a>M?M=*a:0;printf("%i %i",m,M);}


问:
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>```

答:
Actually, <s>17</s> 16 bytes

This answer is partially based on Luis Mendo's MATL answer. Golfing suggestions welcome. Try it online!

```<code>;╗R`╜R∙i`M`Σ╜=`░
</code>```

Ungolfing

```<code>         Implicit input n.
;╗       Duplicate n and save a copy of n to register 0.
R        Take the range of [1..n].
`...`M   Map the following function over the range. Variable k.
  ╛R       Push n from register 0 and take the range [1..n] again.
  ∙        Take the k-th Cartesian power of the range.
  i        Flatten that product.
`...`░   Push values of the previous map where the following function returns a truthy value.
          Variable L.
  Σ        Push sum(L).
  ╜        Push n from register 0.
  =        Check if sum(L) == n.
         Implicit return.
</code>```

Title: List all ordered partitions of n

Body:
Actually, <s>17</s> 16 bytes

This answer is partially based on Luis Mendo's MATL answer. Golfing suggestions welcome. Try it online!

;╗R`╜R∙i`M`Σ╜=`░

Ungolfing

         Implicit input n.
;╗       Duplicate n and save a copy of n to register 0.
R        Take the range of [1..n].
`...`M   Map the following function over the range. Variable k.
  ╛R       Push n from register 0 and take the range [1..n] again.
  ∙        Take the k-th Cartesian power of the range.
  i        Flatten that product.
`...`░   Push values of the previous map where the following function returns a truthy value.
          Variable L.
  Σ        Push sum(L).
  ╜        Push n from register 0.
  =        Check if sum(L) == n.
         Implicit return.


答:
Actually, <s>17</s> <s>16</s> 15 bytes

This is an interesting fork of Martin Ender's CJam answer (the one with the Cartesian product), with a difference in implementation that I thought was interesting. When one of Martin's strings start with an increment, the errors prevent that string from being evaluated. In Actually, the error is suppressed and the string is evaluated anyway. This ends up giving the compositions of every k in the range [1..n].

Rather than try to remove the extra compositions, I took the n-1th Cartesian power of "1u" appended a "1" to the beginning of each string. This trick gives only the compositions of n. It is, unfortunately, longer than Martin's answer.

Golfing suggestions welcome. Try it online!

```<code>D"1u"∙`1@Σ£ƒk`M
</code>```

Ungolfing

```<code>         Implicit input n.
D        Decrement n.
"1u"∙    Take the (n-1)th Cartesian power of the string "1u".
          In Actually, 1 pushes 1 to the stack and u is increment.
`...`M   Map the following function over the Cartesian power. Variable s.
  1@       Push a 1 to be used later.
  Σ        Summing a list of chars joins the chars into one string.
  £ƒ       Turn s into a function and call it immediately on the 1 in the stack.
  k        Take the whole stack and wrap in a list. This is a composition of n.
         Implicit return.
</code>```

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:
Actually, <s>17</s> <s>16</s> 15 bytes

This is an interesting fork of Martin Ender's CJam answer (the one with the Cartesian product), with a difference in implementation that I thought was interesting. When one of Martin's strings start with an increment, the errors prevent that string from being evaluated. In Actually, the error is suppressed and the string is evaluated anyway. This ends up giving the compositions of every k in the range [1..n].

Rather than try to remove the extra compositions, I took the n-1th Cartesian power of "1u" appended a "1" to the beginning of each string. This trick gives only the compositions of n. It is, unfortunately, longer than Martin's answer.

Golfing suggestions welcome. Try it online!

D"1u"∙`1@Σ£ƒk`M

Ungolfing

         Implicit input n.
D        Decrement n.
"1u"∙    Take the (n-1)th Cartesian power of the string "1u".
          In Actually, 1 pushes 1 to the stack and u is increment.
`...`M   Map the following function over the Cartesian power. Variable s.
  1@       Push a 1 to be used later.
  Σ        Summing a list of chars joins the chars into one string.
  £ƒ       Turn s into a function and call it immediately on the 1 in the stack.
  k        Take the whole stack and wrap in a list. This is a composition of n.
         Implicit return.


问:
Create a FizzBuzz compiler
Welcome to the world of compiler golf. Your task is to write a program that generates another program to play a variant of FizzBuzz on spec.

Your compiler

Write a compiler that generates variants of the FizzBuzz program to spec. The spec of this variant is expressed in the form of an array of integer/string pairs.

The input may be in any form that is convenient to your language. (My examples use n:xxxx, but this is just for illustrative purposes.)

Each integer input may only be used once per invocation of your compiler.

The integer of each pair will have a value of at least one.

The string of each pair will be made of only exactly four ASCII letters.

The output must be a single complete program that conforms to the rules below.

The output may be in any convenient form, as long as it is a textual program. (So no returning lambda expressions.)

Behavior is undefined for inputs not conforming to the above rules.

Your generated FizzBuzz program

The program generated by your compiler will take a single integer, n, as input. It will output a sequence of numbers starting from one up to and including n, replacing numbers with FizzBuzz strings when required.

The generated program must be in the same language as the compiler.

The input n may be in any form convenient to your language.

n will have a value of at least one.

A number that is a multiple of at least one of the integers input to the compiler must be replaced by all of the strings paired with those integers joined together.

A number that is not to be replaced by a FizzBuzz string must be output in decimal ASCII.

For example;

```<code>> GenFizzBuzz 3:Fizz 5:Buzz
> a.out 5
1
2
Fizz
4
Buzz
</code>```

Scoring

Your entry will be scored by the length of the programs your compiler generates added to the length of your compiler. Run your compiler many times with each the following parameters and add the lengths of the generated programs together with the length of the compiler to find your score.

Just Count. (No inputs - The generated program will count 1 to n without replacements.)

Just Golf. (1:Golf - The generated program will output "Golf" n times.)

Classic FizzBuzz. (3:Fizz, 5:Buzz)

(Note that your compiler is required to generate code for any valid input, not just these listed.)

答:
Ruby 99 + (86 + 94 + 103) = 382

```<code>puts"(1..ARGV[0].to_i).each{|i|x=[];#{ARGV[0]}.each{|k,v|x<<v if i%k==0};puts x.size>0?x.join():i}"
</code>```

Usage:

```<code>wc -c main.rb # 99 chars
ruby main.rb "{}" | ruby - 100 # 1..2..3..
ruby main.rb "{}" | wc -c # 86 chars
ruby main.rb "{1=>:Golf}" | ruby - 100 # Golf..Golf..Golf..
ruby main.rb "{1=>:Golf}" | wc -c # 94 chars
ruby main.rb "{3=>:Fizz,5=>:Buzz}" | ruby - 100 # 1..2..Fizz..4..Buzz..
ruby main.rb "{3=>:Fizz,5=>:Buzz}" | wc -c # 103 chars
</code>```

Title: Create a FizzBuzz compiler

Body:
Ruby 99 + (86 + 94 + 103) = 382

puts"(1..ARGV[0].to_i).each{|i|x=[];#{ARGV[0]}.each{|k,v|x<<v if i%k==0};puts x.size>0?x.join():i}"

Usage:

wc -c main.rb # 99 chars
ruby main.rb "{}" | ruby - 100 # 1..2..3..
ruby main.rb "{}" | wc -c # 86 chars
ruby main.rb "{1=>:Golf}" | ruby - 100 # Golf..Golf..Golf..
ruby main.rb "{1=>:Golf}" | wc -c # 94 chars
ruby main.rb "{3=>:Fizz,5=>:Buzz}" | ruby - 100 # 1..2..Fizz..4..Buzz..
ruby main.rb "{3=>:Fizz,5=>:Buzz}" | wc -c # 103 chars


问:
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>```

答:
Python, 58 bytes

Based on Tony S.'s Ruby answer. This answer works in Python 2 and 3. Golfing suggestions welcome.

lambda n:max([n[i+v]for i,v in enumerate(n)if i+v<len(n)])
```

<p><strong>Ungolfing</strong></p>

<pre class="lang-python prettyprint-override"><code>def f(array):
    result = []
    for index, value in enumerate(array):
        if index + value < len(array):
            result.append(array[index + value])
    return max(result)
</code>```

Body:
Python, 58 bytes

Based on Tony S.'s Ruby answer. This answer works in Python 2 and 3. Golfing suggestions welcome.

lambda n:max([n[i+v]for i,v in enumerate(n)if i+v<len(n)])

Ungolfing

def f(array):
    result = []
    for index, value in enumerate(array):
        if index + value < len(array):
            result.append(array[index + value])
    return max(result)


问:
ASCII Odd/Even Cipher
We'll define the ASCII Odd/Even Cipher via the below pseudocode:

```<code>Define 'neighbor' as the characters adjacent to the current letter in the string

If the one of the neighbors is out of bounds of the string, treat it as \0 or null

Take an input string

For each letter in the string, do
  If the 0-based index of the current letter is even, then
    Use the binary-or of the ASCII codes of both its neighbors
  Else
    If the ASCII code of the current letter is odd, then
      Use the binary-or of itself plus the left neighbor
    Else
      Use the binary-or of itself plus the right neighbor
  In all cases,
    Convert the result back to ASCII and return it
  If this would result in a code point 127 or greater to be converted, then
    Instead return a space

Join the results of the For loop back into one string and output it
</code>```

For example, for input Hello, the output is emmol, since

The H turns to \0 | 'e' which is e

The e turns to 'e' | 'l', or 101 | 108, which is 109 or m

The first l also turns to 101 | 108 or m

The second l turns to 108 | 111, which is 111 or o

The o turns to 108 | \0, or l

Input

A sentence composed solely of printable ASCII characters, in any suitable format.

The sentence may have periods, spaces, and other punctuation, but will only ever be one line.

The sentence will be at least three characters in length.

Output

The resulting cipher, based on the rules described above, returned as a string or output.

The Rules

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 (in bytes) wins.

Examples

Input on one line, output on the following. Blank lines separate examples.

```<code>Hello
emmol

Hello, World!
emmol, ww~ved

PPCG
PSWG

Programming Puzzles and Code Golf
r wogsmmoonpuu ~ meannncoooeggonl

abcdefghijklmnopqrstuvwxyz
bcfefgnijknmno~qrsvuvw~yzz

!abcdefghijklmnopqrstuvwxyz
aaccgeggoikkomoo qsswuww yy

Test 123 with odd characters. R@*SKA0z8d862
euutu133www|todddchizsscguwssr`jS{SK{z~|v66
</code>```

答:
J, 42 bytes

```<code>4:u:3({.OR{:)`((2|1&{){2:OR/\|.)\0,~0,3&u:
</code>```

Uses the property that verbs in J can be applied in an alternating fashion using a gerund ` for certain adverbs such as infix \.

Usage

```<code>   f =: 4:u:3({.OR{:)`((2|1&{){2:OR/\|.)\0,~0,3&u:
   f 'Hello'
emmol
   f 'Hello, World!'
emmol,ww~ved
   f 'PPCG'
PSWG
   f 'Programming Puzzles and Code Golf'
rwogsmmoonpuu~meannncoooeggonl
   f 'abcdefghijklmnopqrstuvwxyz'
bcfefgnijknmno~qrsvuvw~yzz
   f '!abcdefghijklmnopqrstuvwxyz'
aaccgeggoikkomooqsswuwwyy
   f 'Test 123 with odd characters. R@*SKA0z8d862'
euutu133www|todddchizsscguwssr`jS{SK{z~|v66
</code>```

Explanation

```<code>4:u:3({.OR{:)`((2|1&{){2:OR/\|.)\0,~0,3&u:  Input: string S
                                      3&u:  Convert each char to an ordinal
                                    0,      Prepend 0
                                 0,~        Append 0
    3                           \           For each slice of size 3
     (      )`                                For the first slice (even-index)
          {:                                    Get the tail
      {.                                        Get the head
        OR                                      Bitwise OR the head and tail
             `(                )              For the second slice (odd-index)
                             |.                 Reverse the slice
                       2:   \                   For each pair
                         OR/                      Reduce using bitwise OR
                  1&{                           Get the middle value of the slice
                2|                              Take it modulo 2
                      {                         Index into the bitwise OR pairs and select
                                              Repeat cyclically for the remaining slices
4:u:                                        Convert each ordinal back to a char and return
</code>```

Title: ASCII Odd/Even Cipher

Body:
J, 42 bytes

4:u:3({.OR{:)`((2|1&{){2:OR/\|.)\0,~0,3&u:

Uses the property that verbs in J can be applied in an alternating fashion using a gerund ` for certain adverbs such as infix \.

Usage

   f =: 4:u:3({.OR{:)`((2|1&{){2:OR/\|.)\0,~0,3&u:
   f 'Hello'
emmol
   f 'Hello, World!'
emmol,ww~ved
   f 'PPCG'
PSWG
   f 'Programming Puzzles and Code Golf'
rwogsmmoonpuu~meannncoooeggonl
   f 'abcdefghijklmnopqrstuvwxyz'
bcfefgnijknmno~qrsvuvw~yzz
   f '!abcdefghijklmnopqrstuvwxyz'
aaccgeggoikkomooqsswuwwyy
   f 'Test 123 with odd characters. R@*SKA0z8d862'
euutu133www|todddchizsscguwssr`jS{SK{z~|v66

Explanation

4:u:3({.OR{:)`((2|1&{){2:OR/\|.)\0,~0,3&u:  Input: string S
                                      3&u:  Convert each char to an ordinal
                                    0,      Prepend 0
                                 0,~        Append 0
    3                           \           For each slice of size 3
     (      )`                                For the first slice (even-index)
          {:                                    Get the tail
      {.                                        Get the head
        OR                                      Bitwise OR the head and tail
             `(                )              For the second slice (odd-index)
                             |.                 Reverse the slice
                       2:   \                   For each pair
                         OR/                      Reduce using bitwise OR
                  1&{                           Get the middle value of the slice
                2|                              Take it modulo 2
                      {                         Index into the bitwise OR pairs and select
                                              Repeat cyclically for the remaining slices
4:u:                                        Convert each ordinal back to a char and return


答:
Jelly, <s>33</s> 31 bytes

```<code>2ịḂị|2\
|ṚḢ,Ç
O0,0jṡ3µÇ€⁸JḂ¤ị"Ọ
</code>```

A straight-forward approach that can surely be made shorter.

Try it online!

Title: ASCII Odd/Even Cipher

Body:
We'll define the ASCII Odd/Even Cipher via the below pseudocode:

```<code>Define 'neighbor' as the characters adjacent to the current letter in the string

If the one of the neighbors is out of bounds of the string, treat it as \0 or null

Take an input string

For each letter in the string, do
  If the 0-based index of the current letter is even, then
    Use the binary-or of the ASCII codes of both its neighbors
  Else
    If the ASCII code of the current letter is odd, then
      Use the binary-or of itself plus the left neighbor
    Else
      Use the binary-or of itself plus the right neighbor
  In all cases,
    Convert the result back to ASCII and return it
  If this would result in a code point 127 or greater to be converted, then
    Instead return a space

Join the results of the For loop back into one string and output it
</code>```

For example, for input Hello, the output is emmol, since

The H turns to \0 | 'e' which is e

The e turns to 'e' | 'l', or 101 | 108, which is 109 or m

The first l also turns to 101 | 108 or m

The second l turns to 108 | 111, which is 111 or o

The o turns to 108 | \0, or l

Input

A sentence composed solely of printable ASCII characters, in any suitable format.

The sentence may have periods, spaces, and other punctuation, but will only ever be one line.

The sentence will be at least three characters in length.

Output

The resulting cipher, based on the rules described above, returned as a string or output.

The Rules

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 (in bytes) wins.

Examples

Input on one line, output on the following. Blank lines separate examples.

```<code>Hello
emmol

Hello, World!
emmol, ww~ved

PPCG
PSWG

Programming Puzzles and Code Golf
r wogsmmoonpuu ~ meannncoooeggonl

abcdefghijklmnopqrstuvwxyz
bcfefgnijknmno~qrsvuvw~yzz

!abcdefghijklmnopqrstuvwxyz
aaccgeggoikkomoo qsswuww yy

Test 123 with odd characters. R@*SKA0z8d862
euutu133www|todddchizsscguwssr`jS{SK{z~|v66
</code>```

Body:
Jelly, <s>33</s> 31 bytes

2ịḂị|2\
|ṚḢ,Ç
O0,0jṡ3µÇ€⁸JḂ¤ị"Ọ

A straight-forward approach that can surely be made shorter.

Try it online!


答:
Haskell, 457 413 characters

```<code>import IO
import System
z=return
'>'#(c,(l,d:r))=z(d,(c:l,r))
'<'#(d,(c:l,r))=z(c,(l,d:r))
'+'#(c,m)=z(succ c,m)
'-'#(c,m)=z(pred c,m)
'.'#t@(c,_)=putChar c>>hFlush stdout>>z t
','#(_,m)=getChar>>=(\c->z(c,m))
_#t=z t
_%t@('\0',_)=z t
i%t=i t>>=(i%)
b('[':r)=k$b r
b(']':r)=(z,r)
b(c:r)=f(c#)$b r
b[]=(z,[])
f j(i,r)=(\t->j t>>=i,r)
k(i,r)=f(i%)$b r
main=getArgs>>=readFile.head>>=($('\0',("",repeat '\0'))).fst.b
</code>```

This code "compiles" the BF program into an IO action of the form State -> IO State the state is a zipper on an infinite string.

Sad that I had to expend 29 characters to turn buffering off. Without those, it works, but you don't see the prompts before you have to type input. The compiler itself (b, f, and k) is just 99 characters, the runtime (# and %) is 216. The driver w/initial state another 32.

```<code>>ghc -O3 --make BF.hs
[1 of 1] Compiling Main             ( BF.hs, BF.o )
Linking BF ...

>./BF HELLO.BF
Hello World!

>./BF PRIME.BF
Primes up to: 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
</code>```

update 2011-02-15: Incorporated J B's suggestions, did a little renaming, and tightened up main

Title: Interpret brainfuck

Body:
Write the shortest program in your favourite language to interpret a brainfuck program. The program is read from a file. Input and output are standard input and standard output.

Cell size: 8bit unsigned. Overflow is undefined.

Array size: 30000 bytes (not circled)

Bad commands are not part of the input

Comments begin with # and extend to the end of line Comments are everything not in +-.,[]<>

no EOF symbol

A very good test can be found here. It reads a number and then prints the prime numbers up to that number. To prevent link rot, here is a copy of the code:

```<code>compute prime numbers
to use type the max number then push Alt 1 0
===================================================================
======================== OUTPUT STRING ============================
===================================================================
>++++++++[<++++++++>-]<++++++++++++++++.[-]
>++++++++++[<++++++++++>-]<++++++++++++++.[-]
>++++++++++[<++++++++++>-]<+++++.[-]
>++++++++++[<++++++++++>-]<+++++++++.[-]
>++++++++++[<++++++++++>-]<+.[-]
>++++++++++[<++++++++++>-]<+++++++++++++++.[-]
>+++++[<+++++>-]<+++++++.[-]
>++++++++++[<++++++++++>-]<+++++++++++++++++.[-]
>++++++++++[<++++++++++>-]<++++++++++++.[-]
>+++++[<+++++>-]<+++++++.[-]
>++++++++++[<++++++++++>-]<++++++++++++++++.[-]
>++++++++++[<++++++++++>-]<+++++++++++.[-]
>+++++++[<+++++++>-]<+++++++++.[-]
>+++++[<+++++>-]<+++++++.[-]

===================================================================
======================== INPUT NUMBER  ============================
===================================================================
+                          cont=1
[
 -                         cont=0
 >,
 ======SUB10======
 ----------

 [                         not 10
  <+>                      cont=1
  =====SUB38======
  ----------
  ----------
  ----------
  --------

  >
  =====MUL10=======
  [>+>+<<-]>>[<<+>>-]<     dup

  >>>+++++++++
  [
   <<<
   [>+>+<<-]>>[<<+>>-]<    dup
   [<<+>>-]
   >>-
  ]
  <<<[-]<
  ======RMOVE1======
  <
  [>+<-]
 ]
 <
]
>>[<<+>>-]<<

===================================================================
======================= PROCESS NUMBER  ===========================
===================================================================

==== ==== ==== ====
numd numu teid teiu
==== ==== ==== ====

>+<-
[
 >+
 ======DUP======
 [>+>+<<-]>>[<<+>>-]<

 >+<--

 >>>>>>>>+<<<<<<<<   isprime=1

 [
  >+

  <-

  =====DUP3=====
  <[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<<<

  =====DUP2=====
  >[>>+>+<<<-]>>>[<<<+>>>-]<<< <

  >>>

  ====DIVIDES=======
  [>+>+<<-]>>[<<+>>-]<   DUP i=div

  <<
  [
    >>>>>+               bool=1
    <<<
    [>+>+<<-]>>[<<+>>-]< DUP
    [>>[-]<<-]           IF i THEN bool=0
    >>
    [                    IF i=0
      <<<<
      [>+>+<<-]>>[<<+>>-]< i=div
      >>>
      -                  bool=0
    ]
    <<<
    -                    DEC i
    <<
    -
  ]

  +>>[<<[-]>>-]<<
  >[-]<                  CLR div
  =====END DIVIDES====

  [>>>>>>[-]<<<<<<-]     if divides then isprime=0

  <<

  >>[-]>[-]<<<
 ]

 >>>>>>>>
 [
  -
  <<<<<<<[-]<<

  [>>+>+<<<-]>>>[<<<+>>>-]<<<

  >>

  ===================================================================
  ======================== OUTPUT NUMBER  ===========================
  ===================================================================
  [>+<-]>

  [
   ======DUP======
   [>+>+<<-]>>[<<+>>-]<

   ======MOD10====
   >+++++++++<
   [
    >>>+<<              bool= 1
    [>+>[-]<<-]         bool= ten==0
    >[<+>-]             ten = tmp
    >[<<++++++++++>>-]  if ten=0 ten=10
    <<-                 dec ten
    <-                  dec num
   ]
   +++++++++            num=9
   >[<->-]<             dec num by ten

   =======RROT======
      [>+<-]
   <  [>+<-]
   <  [>+<-]
   >>>[<<<+>>>-]
   <

   =======DIV10========
   >+++++++++<
   [
    >>>+<<                bool= 1
    [>+>[-]<<-]           bool= ten==0
    >[<+>-]               ten = tmp
    >[<<++++++++++>>>+<-] if ten=0 ten=10  inc div
    <<-                   dec ten
    <-                    dec num
   ]
   >>>>[<<<<+>>>>-]<<<<   copy div to num
   >[-]<                  clear ten

   =======INC1=========
   <+>
  ]

  <
  [
   =======MOVER=========
   [>+<-]

   =======ADD48========
   +++++++[<+++++++>-]<->

   =======PUTC=======
   <.[-]>

   ======MOVEL2========
   >[<<+>>-]<

   <-
  ]

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

  ===================================================================
  =========================== END FOR ===============================
  ===================================================================

  >>>>>>>
 ]
 <<<<<<<<

 >[-]<
  [-]
 <<-
]

======LF========

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

Example run:

```<code>$ python2 bf.py PRIME.BF
Primes up to: 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
</code>```

Body:
Haskell, 457 413 characters

import IO
import System
z=return
'>'#(c,(l,d:r))=z(d,(c:l,r))
'<'#(d,(c:l,r))=z(c,(l,d:r))
'+'#(c,m)=z(succ c,m)
'-'#(c,m)=z(pred c,m)
'.'#t@(c,_)=putChar c>>hFlush stdout>>z t
','#(_,m)=getChar>>=(\c->z(c,m))
_#t=z t
_%t@('\0',_)=z t
i%t=i t>>=(i%)
b('[':r)=k$b r
b(']':r)=(z,r)
b(c:r)=f(c#)$b r
b[]=(z,[])
f j(i,r)=(\t->j t>>=i,r)
k(i,r)=f(i%)$b r
main=getArgs>>=readFile.head>>=($('\0',("",repeat '\0'))).fst.b

This code "compiles" the BF program into an IO action of the form State -> IO State the state is a zipper on an infinite string.

Sad that I had to expend 29 characters to turn buffering off. Without those, it works, but you don't see the prompts before you have to type input. The compiler itself (b, f, and k) is just 99 characters, the runtime (# and %) is 216. The driver w/initial state another 32.

>ghc -O3 --make BF.hs
[1 of 1] Compiling Main             ( BF.hs, BF.o )
Linking BF ...

>./BF HELLO.BF
Hello World!

>./BF PRIME.BF
Primes up to: 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

update 2011-02-15: Incorporated J B's suggestions, did a little renaming, and tightened up main

ContentLicense: CC BY-SA 2.5


问:
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.

答:
Factor

With includes: 388

Without: 300

```<code>USING: arrays formatting io kernel math math.parser prettyprint random sequences ;
IN: N
CONSTANT: d { { 3 3 3 3 3 6 } { 2 2 2 5 5 5 } { 1 4 4 4 4 4 } }
: p ( -- ) 1 read string>number [ 3 mod 1 + ] keep [ 1 - d nth ] bi@ 2array 21 iota [ drop first2 [ random ] bi@ [ 2array . ] 2keep < ] with map [ ] count [ 11 > "Comput" "Play" ? ] [ "er wins with %d points" sprintf ] bi append print ;
</code>```

Yeah, Factor's not really the language to use when golfing, but it's nice.

Title: Non-transitive dice game

Body:
Factor

With includes: 388

Without: 300

USING: arrays formatting io kernel math math.parser prettyprint random sequences ;
IN: N
CONSTANT: d { { 3 3 3 3 3 6 } { 2 2 2 5 5 5 } { 1 4 4 4 4 4 } }
: p ( -- ) 1 read string>number [ 3 mod 1 + ] keep [ 1 - d nth ] bi@ 2array 21 iota [ drop first2 [ random ] bi@ [ 2array . ] 2keep < ] with map [ ] count [ 11 > "Comput" "Play" ? ] [ "er wins with %d points" sprintf ] bi append print ;

Yeah, Factor's not really the language to use when golfing, but it's nice.


问:
Binary representation of a number is palindrome or not?
Write a full program  to find whether the binary representation of a number is palindrome or not?

```<code>Sample Input
5

Sample Output
YES
</code>```

Print YES if binary representation is palindrome and NO otherwise.

答:
Pyth, 18 bytes

```<code>%2>"YNEOS"!qJ.BQ_J
</code>```

Also 18 bytes:

```<code>@,"NO""YES"qJ.BQ_J
</code>```

Body:
Pyth, 18 bytes

%2>"YNEOS"!qJ.BQ_J

Also 18 bytes:

@,"NO""YES"qJ.BQ_J


答:
C, 1080 bytes total

Compiler [369 bytes]

```<code>#include<stdlib.h>
r,t,f=3,b=5,n;char*F="FIzz",*B="buZZ";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);}
</code>```

Fizz Buzz [241]

```<code>#include<stdlib.h>
r,t,f=3,b=5,n;char*F="FIzz",*B="buZZ";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);}
</code>```

Golf [237]

```<code>#include<stdlib.h>
r,t,f=1,b=0,n;char*F="golf",*B="";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);}
</code>```

Count [233 bytes]

```<code>#include<stdlib.h>
r,t,f=0,b=1,n;char*F="",*B="";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);}
</code>```

Title: Create a FizzBuzz compiler

Body:
Welcome to the world of compiler golf. Your task is to write a program that generates another program to play a variant of FizzBuzz on spec.

Your compiler

Write a compiler that generates variants of the FizzBuzz program to spec. The spec of this variant is expressed in the form of an array of integer/string pairs.

The input may be in any form that is convenient to your language. (My examples use n:xxxx, but this is just for illustrative purposes.)

Each integer input may only be used once per invocation of your compiler.

The integer of each pair will have a value of at least one.

The string of each pair will be made of only exactly four ASCII letters.

The output must be a single complete program that conforms to the rules below.

The output may be in any convenient form, as long as it is a textual program. (So no returning lambda expressions.)

Behavior is undefined for inputs not conforming to the above rules.

Your generated FizzBuzz program

The program generated by your compiler will take a single integer, n, as input. It will output a sequence of numbers starting from one up to and including n, replacing numbers with FizzBuzz strings when required.

The generated program must be in the same language as the compiler.

The input n may be in any form convenient to your language.

n will have a value of at least one.

A number that is a multiple of at least one of the integers input to the compiler must be replaced by all of the strings paired with those integers joined together.

A number that is not to be replaced by a FizzBuzz string must be output in decimal ASCII.

For example;

```<code>> GenFizzBuzz 3:Fizz 5:Buzz
> a.out 5
1
2
Fizz
4
Buzz
</code>```

Scoring

Your entry will be scored by the length of the programs your compiler generates added to the length of your compiler. Run your compiler many times with each the following parameters and add the lengths of the generated programs together with the length of the compiler to find your score.

Just Count. (No inputs - The generated program will count 1 to n without replacements.)

Just Golf. (1:Golf - The generated program will output "Golf" n times.)

Classic FizzBuzz. (3:Fizz, 5:Buzz)

(Note that your compiler is required to generate code for any valid input, not just these listed.)

Body:
C, 1080 bytes total

Compiler [369 bytes]

#include<stdlib.h>
r,t,f=3,b=5,n;char*F="FIzz",*B="buZZ";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);}

Fizz Buzz [241]

#include<stdlib.h>
r,t,f=3,b=5,n;char*F="FIzz",*B="buZZ";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);}

Golf [237]

#include<stdlib.h>
r,t,f=1,b=0,n;char*F="golf",*B="";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);}

Count [233 bytes]

#include<stdlib.h>
r,t,f=0,b=1,n;char*F="",*B="";main(int c,char **v){if(f)for(c=atoi(v[1]),n=1;c>=n;)r=f?n%f:0,r?(t=b?n%b:0)?printf("%i\n",n):puts(B):r?printf("%s%s\n",F,B):puts(F),++n;else for(c=0;c<atoi(v[1]);)printf("%i\n",++c);}


问:
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!

答:
Scala, 119 bytes

```<code>def f(s:String,a:Seq[Char]*)=a filter(_ startsWith s)reduceOption(_ zip _ takeWhile(t=>t._1==t._2)map(_._1))getOrElse s
</code>```

Ungolfed:

```<code>def tabComplete(input: String, options: Seq[Char]*) = {
  options.
  filter((x: String) => x.startsWith(input)).
  reduceOption((x: Seq[Char], y: Seq[Char]) =>
    x.zip(y).
    takeWhile((t: (Char, Char)) => t._1 == t._2).
    map((t: (Char, Char)) => t._1)
  ).getOrElse(input)
}
</code>```

Explanation:

```<code>def g(s:String,a:Seq[Char]*)= //define a method g with a string and a vararg array of strings as parameter
  a filter(_ startsWith s)    //filter the options to contains only elements starting with the input
  reduceOption(               //if the filtered array is nonempty, reduce it:
    _ zip _                     //zip two elements together
    takeWhile(t=>t._1==t._2)    //take the tuples while they contain the same char
    map(_._1)                   //take the first element from each tuple
  )getOrElse s                //else return the input
</code>```

Title: Implement tab completion

Body:
Scala, 119 bytes

def f(s:String,a:Seq[Char]*)=a filter(_ startsWith s)reduceOption(_ zip _ takeWhile(t=>t._1==t._2)map(_._1))getOrElse s

Ungolfed:

def tabComplete(input: String, options: Seq[Char]*) = {
  options.
  filter((x: String) => x.startsWith(input)).
  reduceOption((x: Seq[Char], y: Seq[Char]) =>
    x.zip(y).
    takeWhile((t: (Char, Char)) => t._1 == t._2).
    map((t: (Char, Char)) => t._1)
  ).getOrElse(input)
}

Explanation:

def g(s:String,a:Seq[Char]*)= //define a method g with a string and a vararg array of strings as parameter
  a filter(_ startsWith s)    //filter the options to contains only elements starting with the input
  reduceOption(               //if the filtered array is nonempty, reduce it:
    _ zip _                     //zip two elements together
    takeWhile(t=>t._1==t._2)    //take the tuples while they contain the same char
    map(_._1)                   //take the first element from each tuple
  )getOrElse s                //else return the input


问:
Is it a balanced number?
A number is balanced if the sum of the digits on each half of the number is equal, so: 1423 is balanced because 1+4 = 2+3, so is: 42615 because 4+2=1+5. Note that the middle digit is not included on either side (or it's included on both sides) if there's an odd number of digits.

Challenge:

Take a positive integer as input, and output a truthy value if it's balanced and a falsy value if it's unbalanced.

Test cases (true)

```<code>1
6
11
141
1221
23281453796004414
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088
</code>```

Test cases (false)

```<code>10
12
110
15421
5234095123508321
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454
</code>```

There will not be numbers starting with zero, for instance 00032 instead of 32. You must support numbers up to at least 100 digits (so larger than 2^64-1). As always, optional input format, so you may surround the number with apostrophes if desired.

答:
Actually, <s>17</s> 16 bytes

This answer is inspired by ElPedro's Python 2 answer and their idea to use [-b:]. Golfing suggestions welcome. Try it online!

```<code>$♂≈;l½L│±aHΣ)tΣ=
</code>```

Ungolfing

```<code>      Implicit input n.
$♂≈   list(str(n)). This converts n to a list of n's digits.
;l    Duplicate the list of digits and get its length. Call it len.
½L    Push len//2.
│     This duplicates the stack.
        Stack: len//2, digit_list, len//2, digit_list
±     Negate the len//2 at TOS for later.
a     Invert the stack.
        Stack: digit_list, len//2, digit_list, -(len//2)
HΣ    Push digit_list[:len//2], then push its sum.
)     Rotate this first sum to BOS.
tΣ    Push digit_list[-(len//2):], then push its sum.
=     Check if those sums are equal.
      Implicit return.
</code>```

Title: Is it a balanced number?

Body:
Actually, <s>17</s> 16 bytes

This answer is inspired by ElPedro's Python 2 answer and their idea to use [-b:]. Golfing suggestions welcome. Try it online!

$♂≈;l½L│±aHΣ)tΣ=

Ungolfing

      Implicit input n.
$♂≈   list(str(n)). This converts n to a list of n's digits.
;l    Duplicate the list of digits and get its length. Call it len.
½L    Push len//2.
│     This duplicates the stack.
        Stack: len//2, digit_list, len//2, digit_list
±     Negate the len//2 at TOS for later.
a     Invert the stack.
        Stack: digit_list, len//2, digit_list, -(len//2)
HΣ    Push digit_list[:len//2], then push its sum.
)     Rotate this first sum to BOS.
tΣ    Push digit_list[-(len//2):], then push its sum.
=     Check if those sums are equal.
      Implicit return.


问:
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

```

答:
Scala, <s>90</s> 53 bytes

```<code>def h(g:Int,a:BigInt*)=a.max>g&&a.reduce(_ gcd _)%g<1
</code>```

Works basically the same as the other answers, <s>but scala doesn't have a built-in gcd function.</s> Scala has a built.in gcd function, but only for BigInt.

Title: The Decanting Problem

Body:
Scala, <s>90</s> 53 bytes

def h(g:Int,a:BigInt*)=a.max>g&&a.reduce(_ gcd _)%g<1

Works basically the same as the other answers, <s>but scala doesn't have a built-in gcd function.</s> Scala has a built.in gcd function, but only for BigInt.


答:
Actually, 17 bytes

This answer is an Actually port of my Python answer. Golfing suggestions welcome. Try it online!

```<code>;╗ñ♂Σ⌠╜l>⌡░⌠╜E⌡MM
</code>```

Ungolfing

```<code>         Implicit input L.
;╗       Duplicate L and save a copy of L to register 0.
ñ        enumerate() the other copy of L.
♂Σ       sum() all the pairs of [index, value of n]. Call this list Z.
⌠...⌡░   Push values of Z where the following function returns a truthy value. Variable v_i.
  ╜        Push L from register 0.
  l        Push len(L).
  >        Check if len(L) > v_i.
⌠...⌡M   Map the following function over Z_filtered. Variable i.
  ╜        Push L from register 0.
  E        Take the ith index of L.
M        max() the result of the map.
         Implicit return.
</code>```

Title: Find the largest number n positions away from n

Body:
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>```

Body:
Actually, 17 bytes

This answer is an Actually port of my Python answer. Golfing suggestions welcome. Try it online!

;╗ñ♂Σ⌠╜l>⌡░⌠╜E⌡MM

Ungolfing

         Implicit input L.
;╗       Duplicate L and save a copy of L to register 0.
ñ        enumerate() the other copy of L.
♂Σ       sum() all the pairs of [index, value of n]. Call this list Z.
⌠...⌡░   Push values of Z where the following function returns a truthy value. Variable v_i.
  ╜        Push L from register 0.
  l        Push len(L).
  >        Check if len(L) > v_i.
⌠...⌡M   Map the following function over Z_filtered. Variable i.
  ╜        Push L from register 0.
  E        Take the ith index of L.
M        max() the result of the map.
         Implicit return.


答:
Haskell, 55 bytes

g(h:t)=read[h]-g(reverse t)
g _=0
(==0).g.(<*"xx").show
```
<p>The recursive function <code>g</code> unwraps a number string from both ends by repeatedly taking the head, then reversing. It subtracts the recursive result from the head, which causes it alternate coefficients of +1 and -1, with +1 applied to the first half and -1 to the second half.</p>
<pre class="lang-haskell prettyprint-override"><code>   g "12345"
== 1 - g "5432"
== 1 - (5 - g "432")
== 1 - (5 - (4 - g "32"))
== 1 - (5 - (4 - (3 - g "2"))
== 1 - (5 - (4 - (3 - 2))
== 1 + 2 + 3 - 4 - 5
</code>```

So, it takes the sum of the first half minus the sum of the second half. This has the issue that with an odd number of digits, the center tiebreaks to the left, but the main function fixes that by (<*"xx"), which doubles every character, i.e. "12345" becomes "1122334455". That way the middle digit splits evenly on both sides and cancels out.

Title: Is it a balanced number?

Body:
A number is balanced if the sum of the digits on each half of the number is equal, so: 1423 is balanced because 1+4 = 2+3, so is: 42615 because 4+2=1+5. Note that the middle digit is not included on either side (or it's included on both sides) if there's an odd number of digits.

Challenge:

Take a positive integer as input, and output a truthy value if it's balanced and a falsy value if it's unbalanced.

Test cases (true)

```<code>1
6
11
141
1221
23281453796004414
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088
</code>```

Test cases (false)

```<code>10
12
110
15421
5234095123508321
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454
</code>```

There will not be numbers starting with zero, for instance 00032 instead of 32. You must support numbers up to at least 100 digits (so larger than 2^64-1). As always, optional input format, so you may surround the number with apostrophes if desired.

Body:
Haskell, 55 bytes

g(h:t)=read[h]-g(reverse t)
g _=0
(==0).g.(<*"xx").show

The recursive function g unwraps a number string from both ends by repeatedly taking the head, then reversing. It subtracts the recursive result from the head, which causes it alternate coefficients of +1 and -1, with +1 applied to the first half and -1 to the second half.

   g "12345"
== 1 - g "5432"
== 1 - (5 - g "432")
== 1 - (5 - (4 - g "32"))
== 1 - (5 - (4 - (3 - g "2"))
== 1 - (5 - (4 - (3 - 2))
== 1 + 2 + 3 - 4 - 5

So, it takes the sum of the first half minus the sum of the second half. This has the issue that with an odd number of digits, the center tiebreaks to the left, but the main function fixes that by (<*"xx"), which doubles every character, i.e. "12345" becomes "1122334455". That way the middle digit splits evenly on both sides and cancels out.


答:
JavaScript (ES6), <s>125</s> <s>118</s> 114 bytes

Embarrassingly long, but charCodeAt and String.fromCharCode alone are 29 bytes. :-/

s=>[...s].map((_,i)=>String.fromCharCode((x=(C=i=>s.charCodeAt(i))((i-1)|1)|C(i+1-2*(C(i)&i&1)))>126?32:x)).join``
```

<h3>How it works</h3>

<p>Each character at position <code>i</code> is translated with the following formula, which covers all rules at once:</p>

```C((i - 1) | 1) | C(i + 1 - 2 * (C(i) & i & 1))
```

<p>where <code>C(n)</code> returns the ASCII code of the n-th character of the input string.</p>

<h3>Demo</h3>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let f =

s=>[...s].map((_,i)=>String.fromCharCode((x=(C=i=>s.charCodeAt(i))((i-1)|1)|C(i+1-2*(C(i)&i&1)))>126?32:x)).join``

console.log(f("Hello"));
console.log(f("Hello, World!"));
console.log(f("PPCG"));
console.log(f("Programming Puzzles and Code Golf"));
console.log(f("abcdefghijklmnopqrstuvwxyz"));
console.log(f("!abcdefghijklmnopqrstuvwxyz"));
console.log(f("Test 123 with odd characters. R@*SKA0z8d862"));</code>```

Title: ASCII Odd/Even Cipher

Body:
JavaScript (ES6), <s>125</s> <s>118</s> 114 bytes

Embarrassingly long, but charCodeAt and String.fromCharCode alone are 29 bytes. :-/

s=>[...s].map((_,i)=>String.fromCharCode((x=(C=i=>s.charCodeAt(i))((i-1)|1)|C(i+1-2*(C(i)&i&1)))>126?32:x)).join``

How it works

Each character at position i is translated with the following formula, which covers all rules at once:

C((i - 1) | 1) | C(i + 1 - 2 * (C(i) & i & 1))

where C(n) returns the ASCII code of the n-th character of the input string.

Demo

let f =

s=>[...s].map((_,i)=>String.fromCharCode((x=(C=i=>s.charCodeAt(i))((i-1)|1)|C(i+1-2*(C(i)&i&1)))>126?32:x)).join``

console.log(f("Hello"));
console.log(f("Hello, World!"));
console.log(f("PPCG"));
console.log(f("Programming Puzzles and Code Golf"));
console.log(f("abcdefghijklmnopqrstuvwxyz"));
console.log(f("!abcdefghijklmnopqrstuvwxyz"));
console.log(f("Test 123 with odd characters. R@*SKA0z8d862"));


答:
Actually, 10 bytes

This was the shortest solution I found that didn't run into interpreter bugs on TIO. Golfing suggestions welcome. Try it online!

```<code>;╗r`P╜>`░l
</code>```

Ungolfing

```<code>         Implicit input n.
;╗       Duplicate n and save a copy of n to register 0.
r        Push range [0..(n-1)].
`...`░   Push values of the range where the following function returns a truthy value.
  P        Push the a-th prime
  ╜        Push n from register 0.
  >        Check if n > the a-th prime.
l        Push len(the_resulting_list).
         Implicit return.
</code>```

Title: Prime counting function

Body:
Introduction

The Prime Counting Function, also known as the Pi function \$\pi(x)\$, returns the amount of primes less than or equal to x.

Challenge

Your program will take an integer x which you can assume to be positive, and output a single integer equal to the amount of primes less than or equal to x. This is a code-golf challenge, so the winner will be the program with the fewest bytes.

You may use any language of your choosing provided that it existed before this challenge went up, but if the language has a built-in prime-counting function or a primality checking function (such as Mathematica), that function cannot be used in your code.

Example Inputs

Input:

1

Output:

0

Input:

2

Output:

1

Input:

5

Output:

3

A000720 - OEIS

Body:
Actually, 10 bytes

This was the shortest solution I found that didn't run into interpreter bugs on TIO. Golfing suggestions welcome. Try it online!

;╗r`P╜>`░l

Ungolfing

         Implicit input n.
;╗       Duplicate n and save a copy of n to register 0.
r        Push range [0..(n-1)].
`...`░   Push values of the range where the following function returns a truthy value.
  P        Push the a-th prime
  ╜        Push n from register 0.
  >        Check if n > the a-th prime.
l        Push len(the_resulting_list).
         Implicit return.


答:
PHP, not competing

I wanted to do it without using strings at all.

iterative solution, 78 bytes

```<code>for($x=log($n=$argv[1],2);$i<$x&($n>>$i^$n>>$x-$i^1);$i++);echo$i<$x/2?NO:YES;
</code>```

recursive solution, 113 bytes

```<code>function p($n,$x=0){return$n<2?$n:is_pal(($n&(1<<$x=log($n,2)/2)-1)^$n>>$x+!is_int($x));}echo p($argv[1])?YES:NO;
</code>```

If n is a binary palindrome, the upper half xor the lower half is also a binary palindrome and vice versa.

a port of the excellent C answer from fR0DDY, 58 bytes

```<code>for($x=2*$v=$argv[1];$x/=2;$r=$r*2|$x&1);echo$r-$v?NO:YES;
</code>```

a binary reverse. Columbus´ egg.

Title: Binary representation of a number is palindrome or not?

Body:
Write a full program  to find whether the binary representation of a number is palindrome or not?

```<code>Sample Input
5

Sample Output
YES
</code>```

Print YES if binary representation is palindrome and NO otherwise.

Body:
PHP, not competing

I wanted to do it without using strings at all.

iterative solution, 78 bytes

for($x=log($n=$argv[1],2);$i<$x&($n>>$i^$n>>$x-$i^1);$i++);echo$i<$x/2?NO:YES;

recursive solution, 113 bytes

function p($n,$x=0){return$n<2?$n:is_pal(($n&(1<<$x=log($n,2)/2)-1)^$n>>$x+!is_int($x));}echo p($argv[1])?YES:NO;

If n is a binary palindrome, the upper half xor the lower half is also a binary palindrome and vice versa.

a port of the excellent C answer from fR0DDY, 58 bytes

for($x=2*$v=$argv[1];$x/=2;$r=$r*2|$x&1);echo$r-$v?NO:YES;

a binary reverse. Columbus´ egg.


问:
Emulate a 7-segment display

Task

The task is to display any of the 128 possible states of a
7-segment display.

Your program should accept a string of 7 characters ("bits") that are either 0 or 1.
First bit of input corresponds to segment A of the following illustration, the
second to B, etc (ignore dp):

How you represent the display is up to you -- a single Unicode or ASCII symbol,
ASCII art, grafically, or whatever you can come up with. However, each
input must have it's own distinct output. If you come up with something fancy I'm sure you can harvest upvotes by showing off some examples.

All 128 possible states of the display are:

Rules

Codegolf

As I said, any kind of output is allowed, but it would be nice if you specified it.

Input can be stdin or command line argument.

Examples

Input

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

Output

As ASCII/Unicode:

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

Different kinds of ASCII art (I'm not too good at this)

```<code> _   ╺┓  ╒╗   ---
 _|  ┏┛  ╔╝     |
|_   ┗╸  ╚╛   ---
              |
              ---
</code>```

答:
I thought we needed a lispy answer...

Clojure, 159 chars

```<code>(print(apply str(flatten(interpose\newline(partition 3(map(fn[x](if(= x\1)\o" "))(str" "(apply str(interpose" "(map(vec(read-line))[0 5 1 6 4 2 3])))" ")))))))
</code>```

The above will run in the REPL and provide the correct answer. For example:

```<code>1111111
 o
o o
 o
o o
 o
</code>```

Throwing numbers at it with small modifications:

```<code>(doseq [i ["1111110" "0110000" "1101101" "1111001" "0110011" "1011011" "1011111" "1110000" "1111111" "1111011"]]
(println (apply str(flatten(interpose\newline(partition 3(map(fn[x](if(= x\1)\o" "))(str" "(apply str(interpose" "(map(vec i)[0 5 1 6 4 2 3])))" ")))))))
(println))
</code>```

yields:

```<code> o
o o

o o
 o

  o

  o

 o
  o
 o
o
 o

 o
  o
 o
  o
 o

o o
 o
  o

 o
o
 o
  o
 o

 o
o
 o
o o
 o

 o
  o

  o

 o
o o
 o
o o
 o

 o
o o
 o
  o
 o

nil
</code>```

Not easy to read, but they're there!

Title: Emulate a 7-segment display

Body:
I thought we needed a lispy answer...

Clojure, 159 chars

(print(apply str(flatten(interpose\newline(partition 3(map(fn[x](if(= x\1)\o" "))(str" "(apply str(interpose" "(map(vec(read-line))[0 5 1 6 4 2 3])))" ")))))))

The above will run in the REPL and provide the correct answer. For example:

1111111
 o
o o
 o
o o
 o

Throwing numbers at it with small modifications:

(doseq [i ["1111110" "0110000" "1101101" "1111001" "0110011" "1011011" "1011111" "1110000" "1111111" "1111011"]]
(println (apply str(flatten(interpose\newline(partition 3(map(fn[x](if(= x\1)\o" "))(str" "(apply str(interpose" "(map(vec i)[0 5 1 6 4 2 3])))" ")))))))
(println))

yields:

 o
o o

o o
 o

  o

  o

 o
  o
 o
o
 o

 o
  o
 o
  o
 o

o o
 o
  o

 o
o
 o
  o
 o

 o
o
 o
o o
 o

 o
  o

  o

 o
o o
 o
o o
 o

 o
o o
 o
  o
 o

nil

Not easy to read, but they're there!


Title: Simulate the Universe!

Body:
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>```

Body:
Mathematica, 950bytes-10% = 855 bytes

Using expression compressing:

ToExpression[Uncompress["1:eJxdVG1v2jAQ7of9kMyVpna9pkkKLV0aROlW2AQVb1MqPGsKYCBaYtPEjFLgf+zn7vKGaD/kse/J+fz4zuePI9nr//twdOQ5ZTt0DHvkDLxRwGkTPGZHTs8TExnez6U/5nYvN3vcC+zAaXExU3P7l2Faz7T7m31xiEZuqwPZV5EvZrRLqcUYu62mdH/lq/E8IU3GoAmk6c9msVaXsRQEXoHUpVIy1LpLL/pDYLgn7oTynzPSBeIWKxpAGsEymQ1aQAbeUmvxhUrs3EzWBTk1BXI/96J99IfCPgiOOw6L4AsgnbnEpTGBNpB2us8aSOIepsYLbiIXRbynzDqI1sEIMvZVlDgLII98mWRFEhhnYcSe4EC+BXycua6AYPo8MePvDl6w+Y6o6qtciUMnmVO5xx2Qn28k1VMi+8uSqrlzTBBt83DEoy4dQXPrbofbl+0Tg/DsDK/CQ+ApxQU9yYt3jHX7PqU9ym4N3YSIbvSrUgV0s2SCXqlYoBvXRgnx0rpGNMs3iIZlXSaDaZrJYFilUjaaV7vz6mbzCsMdbFxwERvQQMSCtnCYwgPiMP29gEU67yC2YY34Ak+7HV4khsnZayonmjYdEOiwTrGFiG4uw/q+dTN0y7gCA8WW3qFZtt6jWckwVSxgjJH5gZhcsYQ24gpWiNmx6nCXnwRFDBmcYHZPD3Jo3WSSXZBpElYpvqI3g99wnJbp9NNFbcTs2Hm+qJ08yij0gtq9XAoV0xG70HvLgJ9XW36sTu0O3ihFyWDOtaXw//Io5tpYCuX5eJOxB9PG/CF9QYvSDvBWxQsZc7rJGh+1BbXYcXwoZiYQAkTD1icsIf2CAoIqNz6YgH54PvzSdtcJs1PluZw+9gxu50uhcTHhE82bKh69eSswFZ/D9KlYy7FCOah6EmOg/5kZdRM="]]

Uncompressed Code (1168 bytes-10% = 1051.2bytes):

a=5;m=0;b=Table[H,a];r=RandomChoice;R=RandomReal;l=Length;
q[Q_]:=" "<>ToString[Q[[2]]]<>" "<>Switch[Q[[1]],H,"Higgs Boson",z,"Bottom Quark",Z,"Bottom Antiquark",W,"W Boson",G,"Gluon",TL,"Tau Lepton",L,"Tau Antilepton",f,"Charm Quark",F,"Charm Antiquark",Z,"Z Boson",p,"Photons",M,"Muon",y,"Antimuon",x,"Top Quark",X,"Top Antiquark",P,"Positron",n,"Neutrino",c,"Antineutrino",e,"Electron",w,"Strange Antiquark",W,"Strange Quark",M,"Down Antiquark",o,"Down Quark",A,"Up Antiquark",B,"Up Quark"]
While[MemberQ[b,H|W|Z|x|X],m++;b=Flatten[(Switch[#,H,If[R[]<0.1,r[{.648,.141,.882,.0704,.0327,.0159,.00223,.00111,.000244,.000216}->{{z,Z},{W,W},{G,G},{TL,L},{f,F},{Z,Z},{p,p},{Z,P},{M,y},{x,X}}],H],W,If[R[]<0.5,r[{{P,n},{y,n},{L,n}}],W],Z,If[R[]<0.5,r[{0.206,0.034,0.034,0.034,0.152,0.152,0.152,0.118,0.118}->{{n,c},{e,P},{M,y},{TL,L},{o,M},{w,w},{z,Z},{B,A},{f,F}}],Z],(x|X),If[R[]<0.1295,r[{{W,o},{W,w},{W,z}}]],_,#]
)&/@b];s=q/@(Normal@Counts[b]/.Rule->List);Print["The universe contains"<>StringJoin[Flatten[Transpose[{Table[If[l@s==i,If[l@s==1,""," and"],If[i==1,"",","]],{i,1,l@s}],s}]]]<>"."];]
Print["Simulation ended after "<>ToString[0.1*m]<>" yoctoseconds."]

The startparameter can by choosen by altering the value for a.

I noticed i've used the wrong probability for the Higgs boson but cant currently change it (in some hours or so). So add 3 oder 4 bytes to the current solution. (It was a test-value)


问:
String Distance

Challenge

Given an input of an all-lowercase string [a-z], output the total distance between the letters.

Example

```<code>Input: golf

Distance from g to o : 8
Distance from o to l : 3
Distance from l to f : 6

Output: 17
</code>```

Rules

Standard loopholes forbidden

This is code-golf - shortest answer in bytes wins.

The alphabet can be traversed from either direction. You must always use the shortest path. (i.e the distance between x and c is 5).

Test cases

```<code>Input: aa
Output: 0

Input: stack
Output: 18

Input: zaza
Output: 3

Input: valleys
Output: 35
</code>```

答:
Java, 109 bytes

```<code>int f(String s){int x=0,t,a=0;for(byte b:s.getBytes()){t=a>0?(a-b+26)%26:0;t=t>13?26-t:t;x+=t;a=b;}return x;
</code>```

Title: String Distance

Body:
Java, 109 bytes

int f(String s){int x=0,t,a=0;for(byte b:s.getBytes()){t=a>0?(a-b+26)%26:0;t=t>13?26-t:t;x+=t;a=b;}return x;


问:
Minecraft castle fractal
Inpsired by a youtube video from a fellow PPCG user...

You challenge is to use ASCII-art draw a Minecraft castle wall of Andesite and Diorite. The shape of the wall is the Cantor Set. For reference, the Cantor Set is made by repeating the following N times:

Triple the current step

Replace the middle one with blank space

Add a full line below it

This creates the following for the first four steps:

```<code>*

* *
***

* *   * *
***   ***
*********

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

However, your challenge is not quite that simple. You see, after the cantor set gets really big, it becomes boring to look at the same character repeated over and over and over. So we're going to change that by overlaying an alternating series of asterisks * and pound signs #. You should alternate on every three characters horizontally, and on every row vertically. (Of course leaving the spaces the same) For example, the second example will become:

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

and the third example will become:

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

For completeness, here are examples four and five:

```<code>#4
* *   * *         * *   * *
###   ###         ###   ###
***###***         ***###***
###***###***###***###***###

#5
* *   * *         * *   * *                           * *   * *         * *   * *
###   ###         ###   ###                           ###   ###         ###   ###
***###***         ***###***                           ***###***         ***###***
###***###***###***###***###                           ###***###***###***###***###
***###***###***###***###***###***###***###***###***###***###***###***###***###***
</code>```

And one mega example, the 6th iteration:

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

The challenge

You must write a full program or function that accepts a positive integer for input, and outputs the N'th generation of this minecraft castle fractal. You can take Input and output by any reasonable method, and you do not have to worry about invalid inputs (such as numbers less than 1, floating point numbers, non-numbers, etc.).

The shortest answer, measured in bytes wins!

答:
PHP, 159 bytes

```<code>for($r=($n=--$argv[1])?["* *","###"]:["*"];++$i<$n;$r[]=$a.$b.$a){$a=strtr($b=end($r),"#*","*#");foreach($r as&$s)$s.=str_pad("",3**$i).$s;}echo join("\n",$r);
</code>```

breakdown

```<code>for(
    $r=($n=--$argv[1])  // pre-decrease argument, initialize result
    ?["* *","###"]      // shorter than handling the special iteration 2 in the loop
    :["*"]              // iteration 1
    ;
    ++$i<$n             // further iterations:
    ;
    $r[]=$a.$b.$a       // 3. concatenate $a, $b, $a and add to result
)
{
                        // 1. save previous last line to $b, swap `*` with `#` to $a
    $a=strtr($b=end($r),"#*","*#");
                        // 2. duplicate all lines with spaces of the same length inbetween
    foreach($r as&$s)$s.=str_pad("",3**$i).$s;  # strlen($s)==3**$i
}
// output
echo join("\n",$r);
</code>```

Title: Minecraft castle fractal

Body:
PHP, 159 bytes

for($r=($n=--$argv[1])?["* *","###"]:["*"];++$i<$n;$r[]=$a.$b.$a){$a=strtr($b=end($r),"#*","*#");foreach($r as&$s)$s.=str_pad("",3**$i).$s;}echo join("\n",$r);

breakdown

for(
    $r=($n=--$argv[1])  // pre-decrease argument, initialize result
    ?["* *","###"]      // shorter than handling the special iteration 2 in the loop
    :["*"]              // iteration 1
    ;
    ++$i<$n             // further iterations:
    ;
    $r[]=$a.$b.$a       // 3. concatenate $a, $b, $a and add to result
)
{
                        // 1. save previous last line to $b, swap `*` with `#` to $a
    $a=strtr($b=end($r),"#*","*#");
                        // 2. duplicate all lines with spaces of the same length inbetween
    foreach($r as&$s)$s.=str_pad("",3**$i).$s;  # strlen($s)==3**$i
}
// output
echo join("\n",$r);


答:
Haxe, 164 bytes

Works only with system platforms (php, neko, cpp, etc.). Takes input through command line arguments.

```<code>class T{static function main(){var r:Dynamic=Std.parseInt(Sys.args()[0]);var s=r.toString(2);trace(s==[for(i in-s.length+1...1)s.charAt(-i)].join('')?"YES":"NO");}}
</code>```

Body:
Haxe, 164 bytes

Works only with system platforms (php, neko, cpp, etc.). Takes input through command line arguments.

class T{static function main(){var r:Dynamic=Std.parseInt(Sys.args()[0]);var s=r.toString(2);trace(s==[for(i in-s.length+1...1)s.charAt(-i)].join('')?"YES":"NO");}}


问:
Open the browser to http://codegolf.stackexchange.com
Your job is to open a browser window of the default browser to http://codegolf.stackexchange.com.

Your code must open the browser itself, and cannot rely on an open one.

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

Moderator note: A large number of answers to this challenge use the URLs http://ppcg.lol or http://ppcg.ga. These URLs did direct to https://codegolf.stackexchange.com at the time, but have since expired. By this meta discussion, they have been allowed to stay, with the note that they are currently invalid.

答:
Nim, 47 bytes

```<code>import browsers
openDefaultBrowser"www.ppcg.ga"
</code>```

Body:
Nim, 47 bytes

import browsers
openDefaultBrowser"www.ppcg.ga"


答:
05AB1E, <s>17</s> 12 bytes

```<code>‘NO…Ü‘#EbÂQè
</code>```

-5 bytes thanks to Adnan.

Try it online!

Body:
05AB1E, <s>17</s> 12 bytes

‘NO…Ü‘#EbÂQè

-5 bytes thanks to Adnan.

Try it online!


答:
JavaScript (ES6), 46 bytes

I wanted to try an answer without sorting:

```<code>a=>a.map(i=>i<n?n=i:i>x?x=i:0,n=x=a[0])&&[n,x]
</code>```

Bonus recursive version, 53 bytes:

```<code>f=([i,...a],n=i,x=i)=>i+.5?f(a,i<n?i:n,i>x?i:x):[n,x]
</code>```

Title: Find the minimum and maximum integers in an array, without using builtins

Body:
Challenge

Given an array of integers, received from stdin, function arguments, program arguments, or some other method:

Output only the minimum and maximum numbers in the array, through a return value, stdout, or other fitting methods.

Example session

```<code>> minmax( {0, 15, 2, 3, 7, 18, -2, 9, 6, -5, 3, 8, 9, -14} )
-14 18
</code>```

Reference implementation

```<code>// C++14

void minmax(std::vector<int> v) {
    int min = v[0]; int max = v[0];
    for(auto it : v) {
        if (*it < min)
            min = *it;
        if (*it > max)
            max = *it;
    }
    std::cout << min << ' ' << max << std::endl;
}
</code>```

Rules

You may not use a built-in function to calculate the values.

Standard loopholes disallowed.

Creative implementations encouraged.

This is code-golf, shortest answer wins but will not be selected.

Clarifications

If the array contains 1 element you need to output it twice.

If the minimum and maximum values are the same, you need to output them both.

Body:
JavaScript (ES6), 46 bytes

I wanted to try an answer without sorting:

a=>a.map(i=>i<n?n=i:i>x?x=i:0,n=x=a[0])&&[n,x]

Bonus recursive version, 53 bytes:

f=([i,...a],n=i,x=i)=>i+.5?f(a,i<n?i:n,i>x?i:x):[n,x]


答:
Matlab, 71 bytes

```<code>function paly(n)
v=de2bi(n);
if v==v(numel(v):-1:1)
'YES'
else
'NO'
end
</code>```

Body:
Matlab, 71 bytes

function paly(n)
v=de2bi(n);
if v==v(numel(v):-1:1)
'YES'
else
'NO'
end


Title: Prime counting function

Body:
MediaWiki templates with ParserFunctions, 220 + 19 = 239 bytes

{{#ifexpr:{{{2}}}+1={{{1}}}|0|{{#ifexpr:{{{3}}}={{{2}}}|{{P|{{{1}}}|{{#expr:{{{2}}}+1}}|2}}|{{#ifexpr:{{{2}}} mod {{{3}}}=0|{{#expr:1+{{P|{{{1}}}|{{#expr:{{{2}}}+1}}|2}}|{{P|{{{1}}}|{{{2}}}|{{#expr:{{{2}}}+1}}}}}}}}}}}}

To call the template:

{{{P|{{{n}}}|2|2}}}

Arranged in Lisp style:

{{#ifexpr:{{{2}}} + 1 = {{{1}}}|0|
    {{#ifexpr:{{{3}}} = {{{2}}} |
        {{P|{{{1}}}|{{#expr:{{{2}}} + 1}}|2}} |
            {{#ifexpr:{{{2}}} mod {{{3}}} = 0 |
                {{#expr:1 + {{P|{{{1}}}|{{#expr:{{{2}}} + 1}}|2}} |
                {{P|{{{1}}}|{{{2}}}|{{#expr:{{{2}}} + 1}}}}}}}}}}}}

Just a basic primality test from 2 to n. The numbers with three braces around them are the variables, where {{{1}}} is n, {{{2}}} is the number being tested, {{{3}}} is the factor to check.


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

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

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

If that number is 1, print out 1 forever.

Challenge

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

take input from STDIN or an acceptable alternative

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

must output to STDOUT or an acceptable alternative

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

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

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

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

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
braingasm, 5 bytes

```<code>;:[:]
</code>```

The braingasm instruction ; and : are very similar to the brainfuck instructions , and ..

; gets some input from stdin, reads it as an integer, and stores the integer value in the current cell. : prints the value of the current formatted as an integer. Like in brainfuck, [] loops while the current cell is non-zero.

Title: Implement a Truth-Machine

Body:
braingasm, 5 bytes

;:[:]

The braingasm instruction ; and : are very similar to the brainfuck instructions , and ..

; gets some input from stdin, reads it as an integer, and stores the integer value in the current cell. : prints the value of the current formatted as an integer. Like in brainfuck, [] loops while the current cell is non-zero.


问:
Write the longest sentence using keywords of a programming language
As the title said, the challenge is to write the longest sentence by only using the keywords of 1 programming language.

For instance, using the keywords of C++, it is possible to write this sentence:

do not try this float

What can you come up with?

答:
Factor - 109

"Take my-world and with happy? make items to-do. Pause. Self
  not happy?"

"Yes<<."

"From oldies?"

"Yes>>. Self sad."

"Haversin, listen, each and every formula become oldies. Become not
  sad, do-something greater-from-last. Or .
  My-arch self is_gold<<. Change-is_gold. Go-back where
  your_event_mask<< make happy? future. Fulfill promise of
  self. Remember-definition, light are-copies-of happy?"

"Sweetest-day near>> me?. Handle-me, handle-me. Sad self.
  Home not near>>. Home not near>> at all. Out-of-memory.
  Sad self, old<< self. Most near>> ones left self long
  ago."

"Haversin, change-known self. No sad, Haversin.
  Become happy? Forget what<< keep self from happy?
  My-arch self want>> self be> not sad. Before leave,
  remember-error."

"Not remember-error! Error not! My-array
  has-entry? not of error! Leave error!"

"Smart-if remember-error."

A lot of these are stretches, but it somewhat tells a story, so it makes up for that.