问:
King of the Hill - Spacewar!

If you've ever played Spacewar!, you know it was a fun game. If you haven't, know this: it was (and is) one of the very first and most important computer games. And it's still fun! The clone I grew up on is this one, which is, apparently and unfortunately, Windows only. So I recreated it!

The KotH is hosted here: PPCG - Spacewar! King of the Hill. I encourage you to play as a human against at least one other bot to get a feel for how the game works.

The Game

One frame is 30 milliseconds (thus, about 33 frames per second).

The field is 800 pixels wide and 600 pixels tall.

The field is toroidal, meaning that spaceships and missiles that move outside of the field reappear on the opposite side.

There are two spaceships, red and blue.

Red is positioned at x=50 and random y between 50, (field height - 50) pixels.

Blue is positioned at x=(field width - 50) and random y between 50, (field height - 50) pixels.

Both face x = (field width)/2.

The available controls are:

Turn left - 5 degrees per frame counterclockwise.

Turn right - 5 degrees per frame clockwise.

Fire missile - travels at an extra 10 pixels per frame in addition to the velocity of the ship, in the direction the ship was pointing.

Fire engine - accelerates the spaceship at 0.30 pixels per frame in the direction the spaceship is pointing.

Hyperspace jump - teleports to some random coordinates in the field, with a 25% chance of exploding. These random coordinates may be on top of the sun.

The maximum speed for ships is 15 pixels per frame under engine power and 40 pixels per frame when gravity-boosted.

When traveling faster than 15 pixels per frame, engine thrust may only change direction or slow down.

Regarding missiles:

Missiles travel in a straight line.

Missiles may be fired at a maximum rate of 1 per 0.1 seconds.

Missiles have a lifetime of 2.25 seconds.

Ships have a maximum of 20 missiles each.

Missiles are point particles internally.

There is a sun in the very center that is extremely hazardous to your ship. The slightest contact is fatal. This sun also destroys missiles.

The sun has gravity. The resultant acceleration is 5000/(distance^2) pixels/frame^2, where distance is in pixels. Spaceships and missiles are affected.

Both ships have three strike zones: the nose, the left wing, and the right wing.

A hit on the nose is instant death.

A hit on either wing reduces the spaceship's turn rate and engine acceleration by half.

If both wings are destroyed, the spaceship cannot be maneuvered and can only fire missiles.

Ships may collide with each other.

A nose-nose impact is fatal for both ships.

A nose-wing impact destroys the wing.

A wing-wing impact destroys both wings.

Dead ships are solid and frozen until they explode 1 second later.

After at least one ship has died, the field is reset 3 seconds later. Until then, the sun and any remaining missiles are still hazardous.

The original game also has deadly and indestructible asteroids, but I won't include those.

The Rules

Your bot must be written in JavaScript.

Your bot should limit its decision to about 10 milliseconds. If I notice consistent lag because of your bot, I'll disqualify it and let you know so you can fix it.

Bots will have access to the following:

Field width and field height

Sun position and radius

The position, rotation, velocity, shape, missile stock, and in-hyperspace status of both ships

The position and velocity of all missiles

When prompted, your bot should return a list of strings.

These strings should be one of the following: turn left, turn right, fire engine, fire missile, hyperspace. Any other string will be ignored.

If there are any duplicates, only the first will be noted.

hyperspace takes precedence over all others.

turn left and turn right at the same time will have no effect.

fire engine will have no effect if the ship only has the nose or is dead.

fire missile will have no effect if a missile was fired too recently.

In a change from the usual, your bot is allowed to exploit the behavior of other bots. I want to encourage a metagame.

Bots may not emulate other bots. (I.e., no mind-reading.)

Bots may not set any variables used by the game and physics code. (I.e., no cheating.)

Bot Implementation Details

I will be storing your bot in its own JavaScript file that is automatically included, with the filename bot_<name>.js. So don't put any spaces or characters that would interfere with this or with naming a function in JavaScript. That's because you should define the following functions: <name>_setup(team) and <name>_getActions(gameInfo, botVars). Further down the page, there exist textareas for the userbot, which you can edit to test your code.

<name>_setup(team)

This function is for you to define any variables that you want to persist. team will be either "red" or "blue". This function must return an object. Define variables like so:

var vars = {};
vars['example'] = "example";
return vars;
```

<p>This <code>vars</code> object will be passed in to the other function:</p>

<h3><code><name>_getActions(gameInfo, botVars)</code></h3>

<p><code>botVars</code> is the object returned by <code><name>_setup(team)</code>. <code>gameInfo</code> is an object containing the following variables:</p>

<pre class="lang-js prettyprint-override"><code>redScore
blueScore
timeLeft

fieldWidth
fieldHeight

sun_x
sun_y
sun_r //sun's radius

gravityStrength //acceleration in pixels/frame^2 at 1 pixel away from the sun's center
engineThrust    //acceleration in pixels/frame^2

speedLimit //maximum speed under engine power
maxSpeed   //maximum speed from gravity boosts

red_x
red_y
red_rot          //rotation in degrees
red_xv           //x velocity
red_yv           //y velocity
red_shape        //one of "full ship", "left wing", "right wing", "nose only"
red_missileStock //the number of missiles red has left
red_inHyperspace //true if red is in hyperspace
red_exploded     //until red explodes, it is still solid and hazardous
red_alive
// likewise for blue //

numMissiles
missiles //this is a list of objects, each with the following variables
  x
  y
  xv
  yv
</code>```

Your bot has full access to these. I'm pretty sure that you can write to them and not affect the original variables, but don't do it anyway. A note on rotations: ships point in the +y direction, downwards, so anything that you want to align with the ship needs to be offset by 90 degrees. Also, positive rotation is clockwise.

This function must return a list of strings, representing your bot's actions. For example, ["turn right","thrust"]. More details on this are in the Rules section.

Additional Details

You may also make use of the following:

LineIntersection(L1, L2)

L1 and L2 are two-element arrays of two-element arrays. That is, L1 := [[x1,y1],[x2,y2]] and L2 := [[u1,v1],[u2,v2]]. This function computes the intersection of two lines and returns this: [[x,y], [a,b]]. [x,y] are the coordinates of the intersection point and [a,b] is a pair of ratios that express how far along each line the intersection point is. As in, a = 0.25 would mean that the intersection point is a quarter of the way from [x1,y1] to [x2,y2], and likewise for b. If there is no intersection, an empty array is returned.

window["shipShapes"]

var shipShapes = {
    'full ship': [[-8,16],[0,-8],[8,16]],
    'left wing': [[-8,16],[0,-8],[4,4],[0,8],[0,16]],
    'right wing':[[-4,4],[0,-8],[8,16],[0,16],[0,8]],
    'nose only': [[-4,4],[0,-8],[4,4],[0,8]]
};
```

<p>These are the coordinates of the ships' polygons. To make getting the current coordinates easier, you may also use...</p>

<h3><code>getShipCoords(<color>)</code></h3>

<p><code>getShipCoords("red")</code> will return the current coordinates of the vertices of Red's ship, and likewise for <code>getShipCoords("blue")</code> and Blue. These coordinates are in a list like so: <code>[[x1,y1],[x2,y2],[x3,y3],...]</code>. Polygons are implicitly closed, so there is a line between the first and last coordinate pairs.</p>

<p><strong>You may not access or alter any other variables or functions in use by the game/website.</strong> And definitely don't name your functions the same. I don't foresee that this will be a problem, but if your bot breaks the game code, that's one possibility. There is no logging or catching of exceptions.</p>

<h2>Winning</h2>

<ul>
<li>Every pairing of bots shall be played at least 10 times, both ways. (So, at least 20 games total.)</li>
<li>Aim to have the highest win/loss ratios <em>overall</em>. If your bot does super well against one other bot, but loses against the other three, that's not as good as winning against two and losing against two (as a general rule of thumb).</li>
<li>For every bot, the ratios (wins+1)/(losses+1) will be calculated, then the mean and standard deviation of these ratios will be calculated. A higher mean will have priority, and in case means are within 1 unit of each other, the lower variance will have priority.</li>
<li>Scoring will begin either in a week from today or after three days of no new submissions. This is so I don't have to repeat any pairing of bots.</li>
</ul>

<p><strong>Above all, have fun!</strong></p>

<hr>

<h2>Leaderboard (2016-01-08 05:15):</h2>

<pre class="lang-js prettyprint-override"><code>#   Name                       Mean      StdDev
1.  Helios                     13.625    6.852
2.  EdgeCase                    8.335    8.155
3.  OpponentDodger              8.415    8.186
4.  OrbitBot                    5.110    6.294
5.  SunAvoider                  5.276    6.772
6.  DangitBobby                 3.320    4.423
7.  SprayAndPray                3.118    4.642
8.  Engineer                    3.903    6.315
9.  RighthandedSpasms           1.805    2.477
10. AttackAndComeBack           2.521    2.921
11. PanicAttack                 2.622    3.102
12. FullSpeedAhead              2.058    3.295
13. UhhIDKWhatToCallThisBot     2.555    3.406
14. MissilesPlusScore           0.159    0.228
15. Hyper                       0.236    0.332
16. RandUmmm                    0.988    1.329
17. Kamikaze                    0.781    1.793
</code>```

Note: This is subject to change as I run more games. Plus, the ordering of ranks 9-13 bothers me, so I may tweak the scoring method to better match one's intuition of how they should be ranked.

(Means and standard deviations were rounded to three decimal digits. Also, Hyper should be HYPER but that messes up the highlighting. :P)

答:
Arrow

Simply chase his enemy, hyperspace when he is in danger and idle when his enemy is dead.

```<code>function Arrow_setup(team) {
    var botVars = {};
    botVars['mpref'] = team + '_';
    botVars['epref'] = team == 'red' ? 'blue_' : 'red_';
    return botVars;
}

function Arrow_getActions(gameInfo, botVars) {
    var actions = [];
    var x = gameInfo[botVars['mpref'] + 'x'],
        y = gameInfo[botVars['mpref'] + 'y'],
        rot = gameInfo[botVars['mpref'] + 'rot']; // My position and rotation
    var ex = gameInfo[botVars['epref'] + 'x'],
        ey = gameInfo[botVars['epref'] + 'y']; // Enemy position
    var Dsunx = Math.abs(x - gameInfo.sun_x);
    var Dsuny = Math.abs(y - gameInfo.sun_y);
    if (Dsunx < 30 && Dsuny < 30) // If Arrow is too close from sun, hyperspace !
        return ['hyperspace'];
    var missiles = gameInfo.missiles;
    for (var i = 0; i < missiles.length; i++) {
        var dx = Math.abs(x - missiles[i].x);
        var dy = Math.abs(y - missiles[i].y);
        if (dx < 10 && dy < 10)
            return ['hyperspace'];
    }
    if (gameInfo[botVars['epref'] + 'alive']) {
        var angle = Math.degrees(Math.atan2(ey - y, ex - x)),
            nrot = (rot - angle + 360) % 360;
        if (nrot > 90 && nrot < 270)
            actions.push('turn left');
        else
            actions.push('turn right');
        if (Math.random() > 0.5) actions.push('fire missile');
    }
    if (Math.random() > 0.5) actions.push('fire engine');
    return actions;
}
</code>```

Title: King of the Hill - Spacewar!

Body:
Arrow

Simply chase his enemy, hyperspace when he is in danger and idle when his enemy is dead.

function Arrow_setup(team) {
    var botVars = {};
    botVars['mpref'] = team + '_';
    botVars['epref'] = team == 'red' ? 'blue_' : 'red_';
    return botVars;
}

function Arrow_getActions(gameInfo, botVars) {
    var actions = [];
    var x = gameInfo[botVars['mpref'] + 'x'],
        y = gameInfo[botVars['mpref'] + 'y'],
        rot = gameInfo[botVars['mpref'] + 'rot']; // My position and rotation
    var ex = gameInfo[botVars['epref'] + 'x'],
        ey = gameInfo[botVars['epref'] + 'y']; // Enemy position
    var Dsunx = Math.abs(x - gameInfo.sun_x);
    var Dsuny = Math.abs(y - gameInfo.sun_y);
    if (Dsunx < 30 && Dsuny < 30) // If Arrow is too close from sun, hyperspace !
        return ['hyperspace'];
    var missiles = gameInfo.missiles;
    for (var i = 0; i < missiles.length; i++) {
        var dx = Math.abs(x - missiles[i].x);
        var dy = Math.abs(y - missiles[i].y);
        if (dx < 10 && dy < 10)
            return ['hyperspace'];
    }
    if (gameInfo[botVars['epref'] + 'alive']) {
        var angle = Math.degrees(Math.atan2(ey - y, ex - x)),
            nrot = (rot - angle + 360) % 360;
        if (nrot > 90 && nrot < 270)
            actions.push('turn left');
        else
            actions.push('turn right');
        if (Math.random() > 0.5) actions.push('fire missile');
    }
    if (Math.random() > 0.5) actions.push('fire engine');
    return actions;
}


问:
Wait a minute – in less than ten seconds

Task

Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half).

The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 seconds.

This is similar to the concept of man-hours: a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed.

Example

The program MyProgram creates 14 threads, each thread sleeps for 5 seconds:

MyProgram → [5.016,70.105]

The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead.

答:
JavaScript (ES6), 148 bytes

with(performance)Promise.all([...Array(9)].map(_=>new Promise(r=>setTimeout(_=>r(t+=now()),7e3,t-=now())),t=0,n=now())).then(_=>alert([now()-n,t]));```

Promises to wait 9 times for 7 seconds for a total of 63 seconds (actually 63.43 when I try), but only actually takes 7.05 seconds of real time when I try.

ContentLicense: CC BY-SA 3.0

Body:
JavaScript (ES6), 148 bytes

with(performance)Promise.all([...Array(9)].map(_=>new Promise(r=>setTimeout(_=>r(t+=now()),7e3,t-=now())),t=0,n=now())).then(_=>alert([now()-n,t]));

Promises to wait 9 times for 7 seconds for a total of 63 seconds (actually 63.43 when I try), but only actually takes 7.05 seconds of real time when I try.


问:
The Ever Amplifying Zigzag
Write a program or function that takes in a positive integer N and outputs the first N numbers of this amplifying zigzag pattern, using only the lines needed:

```<code>                                         26
                                       25  27                                      .
         10                          24      28                                  .
        9  11                      23          29                              .
 2     8     12                  22              30                          44
1 3   7        13              21                  31                      43
   4 6           14          20                      32                  42
    5              15      19                          33              41
                     16  18                              34          40
                       17                                  35      39
                                                             36  38
                                                               37
</code>```

So, if N is 1 the output is

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

If N is 2, the output is

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

If N is 3 the output is

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

If N is 4 the output is

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

If N is 10 the output is

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

If N is 19 the output is

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

and so on.

Notes

Each peak or trough of the zigzag reaches its point one more line away from the line with the 1 on it than the previous peak or trough.

N is not limited to 44. The zigzag grows in the same pattern and larger N should be supported.

Numbers with multiple digits should only "touch" at their corners, as depicted. Make sure this works when N is 100 and above.

There should be no empty (or space only) lines in the output except one optional trailing newline.

Any line may have any amount of trailing spaces.

Scoring

The shortest code in bytes wins. Tiebreaker is earlier answer.

答:
Python 2, 137 bytes

```<code>l={}
i=x=y=n=v=0
exec"v+=1;l[y]=l.get(y,'').ljust(x)+`v`;x+=len(`v`);i=-~i%-~n;y+=n%4-1;n+=2>>i*2;"*input()
for k in sorted(l):print l[k]
</code>```

View the output on ideone.

Title: The Ever Amplifying Zigzag

Body:
Python 2, 137 bytes

l={}
i=x=y=n=v=0
exec"v+=1;l[y]=l.get(y,'').ljust(x)+`v`;x+=len(`v`);i=-~i%-~n;y+=n%4-1;n+=2>>i*2;"*input()
for k in sorted(l):print l[k]

View the output on ideone.


问:
Convert from base 10 to base 2 without built-in base conversions
Background:

You have been given an assignment to convert base 10 numbers to base 2 without using any premade base conversion functions. You can't use any imported libraries either.

Problem:

Convert an input string from base 10 (decimal) to base 2 (binary). You may not use any premade base conversion code/functions/methods, or imported libraries. Since this is code-golf, the shortest answer in bytes will win.

Input will be anything from -32768 to 32767 (include sign byte handling in your code)

答:
Turing Machine Code, 272 bytes

As usual, I'm using the rule table syntax defined here. You can test it on that site or, alternatively, using this java implementation.

A lot of the code is copied from my decimal-to-hex converter here.

```<code>0 * * l B
B * * l C
C * 0 r D
D * * r E
E * * r A
A _ * l 1
A * * r *
1 0 9 l 1
1 1 0 l 2
1 2 1 l 2
1 3 2 l 2
1 4 3 l 2
1 5 4 l 2
1 6 5 l 2
1 7 6 l 2
1 8 7 l 2
1 9 8 l 2
1 _ * r Y
Y * * * X
X * _ r X
X _ _ * halt
2 * * l 2
2 _ _ l 3
3 * 1 r 4
3 1 0 l 3
4 * * r 4
4 _ _ r A
</code>```

Counts down from the input in base 10 while counting up from 0 in base 2. On decrementing zero, it erases the input block and terminates.

Body:
Turing Machine Code, 272 bytes

As usual, I'm using the rule table syntax defined here. You can test it on that site or, alternatively, using this java implementation.

A lot of the code is copied from my decimal-to-hex converter here.

0 * * l B
B * * l C
C * 0 r D
D * * r E
E * * r A
A _ * l 1
A * * r *
1 0 9 l 1
1 1 0 l 2
1 2 1 l 2
1 3 2 l 2
1 4 3 l 2
1 5 4 l 2
1 6 5 l 2
1 7 6 l 2
1 8 7 l 2
1 9 8 l 2
1 _ * r Y
Y * * * X
X * _ r X
X _ _ * halt
2 * * l 2
2 _ _ l 3
3 * 1 r 4
3 1 0 l 3
4 * * r 4
4 _ _ r A

Counts down from the input in base 10 while counting up from 0 in base 2. On decrementing zero, it erases the input block and terminates.


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

There are exactly 16 of them, because:

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

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

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

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

Your functions/programs must be independent.

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

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

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

0,0,1,1 (A)

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

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

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

1,1,0,0 (not A)

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

1,1,1,0 (nand)

1,1,1,1 (true)

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

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
NAND logic gates — 31 gates

As the creator of the original series of NAND gate questions, I couldn't pass up the opportunity to use these gates to solve another logic gate problem.

In each of these diagrams, the top input is A while the bottom input is B.


答:
Forth-83, <s>43</s> 37 bytes

These are all complete programs. The inputs begin on the stack, and the result of each program is the top value of the stack afterwards. Not all of these programs are stack-safe. <s>I wish there was a shorter way to NOT</s> (1+ is shorter.)

Note: -1 is TRUE in this language (and many older languages,) because a bitwise NOT of 0 is -1. Any non-zero value is truthy.

```<code>0000    0
0001    *
0010    <
0011    DROP
0100    >
0101
0110    -
0111    +
1000    + 1+
1001    =
1010    1+
1011    > 1+
1100    DROP 1+
1101    < 1+
1110    * 1+
1111    1
</code>```

Test code:

Replace DROP on line 2 with your program of choice. This program runs the above programs for each combination of inputs and prints whether it was interpreted to be true or false (some of the truthy values are different, but this test program shows that they are still interpreted as true.) Any occurrence of NOT must be replaced with INVERT for this interpreter, because this isn't a Forth‑83 interpreter. The new lines here are for readability, and can be replaced with spaces.

Try it online

```<code>: f
DROP
IF -1 . ELSE 0 . THEN ;

0 0 f
0 -1 f
-1 0 f
-1 -1 f
</code>```

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

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

There are exactly 16 of them, because:

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

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

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

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

Your functions/programs must be independent.

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

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

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

0,0,1,1 (A)

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

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

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

1,1,0,0 (not A)

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

1,1,1,0 (nand)

1,1,1,1 (true)

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

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Forth-83, <s>43</s> 37 bytes

These are all complete programs. The inputs begin on the stack, and the result of each program is the top value of the stack afterwards. Not all of these programs are stack-safe. <s>I wish there was a shorter way to NOT</s> (1+ is shorter.)

Note: -1 is TRUE in this language (and many older languages,) because a bitwise NOT of 0 is -1. Any non-zero value is truthy.

0000    0
0001    *
0010    <
0011    DROP
0100    >
0101
0110    -
0111    +
1000    + 1+
1001    =
1010    1+
1011    > 1+
1100    DROP 1+
1101    < 1+
1110    * 1+
1111    1

Test code:

Replace DROP on line 2 with your program of choice. This program runs the above programs for each combination of inputs and prints whether it was interpreted to be true or false (some of the truthy values are different, but this test program shows that they are still interpreted as true.) Any occurrence of NOT must be replaced with INVERT for this interpreter, because this isn't a Forth‑83 interpreter. The new lines here are for readability, and can be replaced with spaces.

Try it online

: f
DROP
IF -1 . ELSE 0 . THEN ;

0 0 f
0 -1 f
-1 0 f
-1 -1 f


答:
JavaScript (ES6, using WebWorkers), 233 215 bytes

c=s=0;d=new Date();for(i=14;i-->0;)(new Worker(URL.createObjectURL(new Blob(['a=new Date();setTimeout(()=>postMessage(new Date()-a),5e3)'])))).onmessage=m=>{s+=m.data;if(++c>13)console.log((new Date()-d)/1e3,s/1e3)}```

UPD: replaced the way a worker is executed from a string with a more compact and cross-browser one, in the aspect of cross-origin policies. Won't work in Safari, if it still have webkitURL object instead of URL, and in IE.

Title: Wait a minute – in less than ten seconds

Body:
Task

Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half).

The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 seconds.

This is similar to the concept of man-hours: a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed.

Example

The program MyProgram creates 14 threads, each thread sleeps for 5 seconds:

MyProgram → [5.016,70.105]

The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead.

Body:
JavaScript (ES6, using WebWorkers), 233 215 bytes

c=s=0;d=new Date();for(i=14;i-->0;)(new Worker(URL.createObjectURL(new Blob(['a=new Date();setTimeout(()=>postMessage(new Date()-a),5e3)'])))).onmessage=m=>{s+=m.data;if(++c>13)console.log((new Date()-d)/1e3,s/1e3)}

UPD: replaced the way a worker is executed from a string with a more compact and cross-browser one, in the aspect of cross-origin policies. Won't work in Safari, if it still have webkitURL object instead of URL, and in IE.


答:
Dyalog APL, <s>65</s> <s>27</s> <s>23</s> 21 bytes

```<code>(⌈/,+/)⎕TSYNC⎕DL&¨9/7
</code>```

I.e.:

```<code>      (⌈/,+/)⎕TSYNC⎕DL&¨9/7
7.022 63.162
</code>```

Explanation:

⎕DL&¨9/7: spin off 9 threads, each of which waits for 7 seconds. ⎕DL returns the actual amount of time spent waiting, in seconds, which will be the same as its argument give or take a few milliseconds.

⎕TSYNC: wait for all threads to complete, and get the result for each thread.

(⌈/,+/): return the longest execution time of one single thread (during the execution of which all other threads finished, so this is the actual runtime), followed by the sum of the execution time of all threads.

Try it online!

Body:
Dyalog APL, <s>65</s> <s>27</s> <s>23</s> 21 bytes

(⌈/,+/)⎕TSYNC⎕DL&¨9/7

I.e.:

      (⌈/,+/)⎕TSYNC⎕DL&¨9/7
7.022 63.162

Explanation:

⎕DL&¨9/7: spin off 9 threads, each of which waits for 7 seconds. ⎕DL returns the actual amount of time spent waiting, in seconds, which will be the same as its argument give or take a few milliseconds.

⎕TSYNC: wait for all threads to complete, and get the result for each thread.

(⌈/,+/): return the longest execution time of one single thread (during the execution of which all other threads finished, so this is the actual runtime), followed by the sum of the execution time of all threads.

Try it online!


问:
"Hello, World!"
So... uh... this is a bit embarrassing. But we don't have a plain "Hello, World!" challenge yet (despite having 35 variants tagged with hello-world, and counting). While this is not the most interesting code golf in the common languages, finding the shortest solution in certain esolangs can be a serious challenge. For instance, to my knowledge it is not known whether the shortest possible Brainfuck solution has been found yet.

Furthermore, while all of <s>Wikipedia</s> (the Wikipedia entry has been deleted but there is a copy at archive.org
), esolangs and Rosetta Code have lists of "Hello, World!" programs, none of these are interested in having the shortest for each language (there is also this GitHub repository). If we want to be a significant site in the code golf community, I think we should try and create the ultimate catalogue of shortest "Hello, World!" programs (similar to how our basic quine challenge contains some of the shortest known quines in various languages). So let's do this!

The Rules

Each submission must be a full program.

The program must take no input, and print Hello, World! to STDOUT (this exact byte stream, including capitalization and punctuation) plus an optional trailing newline, and nothing else.

The program must not write anything to STDERR.

If anyone wants to abuse this by creating a language where the empty program prints Hello, World!, then congrats, they just paved the way for a very boring answer.

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

Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.

This is not about finding the language with the shortest "Hello, World!" program. This is about finding the shortest "Hello, World!" program in every language. Therefore, I will not mark any answer as "accepted".

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

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

For inspiration, check the Hello World Collection.

The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue 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>## [><>](https://esolangs.org/wiki/Fish), 121 bytes
</code>```

/* Configuration */

var QUESTION_ID = 55422; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

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

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

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

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery(''+lang+'').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  text-align: left !important;
  display: block !important;
}

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

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

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Fith, 17 bytes

```<code>"Hello, World!" .
</code>```

. is the print word.

ContentLicense: CC BY-SA 4.0

Title: "Hello, World!"

Body:
Fith, 17 bytes

"Hello, World!" .

. is the print word.


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

答:
Watch the stack

When writing your code, pay attention to what happens on the stack at each command. I usually draw it out as I go, like so:

```<code>6       6
7       7 6
* DUP   42 42
</code>```

As you go like this, you may find it easier to recognize when you can make use of stack operations like ROT, -ROT, 2DUP, 2OVER, etc...

Title: Tips for golfing in Forth

Body:
Watch the stack

When writing your code, pay attention to what happens on the stack at each command. I usually draw it out as I go, like so:

6       6
7       7 6
* DUP   42 42

As you go like this, you may find it easier to recognize when you can make use of stack operations like ROT, -ROT, 2DUP, 2OVER, etc...


答:
Leave the junk

Programs aren't required to be stack-safe.

Instead, they can leave extra junk on the stack if it saves you bytes. In Forth, the "return value" is leaving something on top of the stack. It probably doesn't matter what junk you have below that on the stack unless you're using recursion and stack depth matters.

Title: Tips for golfing in Forth

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


问:
Partition of a positive integer N
Find the number of partitions of a positive integer n. Hope someone uses the explicit finite formula for the partition function defined in Jan Hendrik Brunier and Ken Ono paper here.

```<code>Sample Input
8
Sample Output
22
</code>```

N is less than or equal to 1000.
Write the complete program. More than anything I would like to see the different approaches.

答:
Ruby - 95 chars

Based on Hoa Long Tam's solution

```<code>s=0
l=[[n=gets.to_i,n]]
(a,i=l.pop;a>0&&i>0&&l+=[[a-i,i],[a,i-1]];a==0&&s+=1)until l==[]
p s
</code>```

ContentLicense: CC BY-SA 2.5

Title: Partition of a positive integer N

Body:
Ruby - 95 chars

Based on Hoa Long Tam's solution

s=0
l=[[n=gets.to_i,n]]
(a,i=l.pop;a>0&&i>0&&l+=[[a-i,i],[a,i-1]];a==0&&s+=1)until l==[]
p s


答:
Mathematica, 109 bytes

```<code>a=AbsoluteTiming;LaunchKernels@7;Plus@@@a@ParallelTable[#&@@a@Pause@9,{7},Method->"EvaluationsPerKernel"->1]&
</code>```

Anonymous function. Requires a license with 7+ sub-kernels to run. Takes 9 seconds realtime and 63 seconds kernel-time, not accounting for overhead. Make sure to only run the preceding statements once (so it doesn't try to re-launch kernels). Testing:

```<code>In[1]:= a=AbsoluteTiming;LaunchKernels@7;func=Plus@@@a@ParallelTable[#&@@a@Pause
@9,{7},Method->"EvaluationsPerKernel"->1]&;

In[2]:= func[]

Out[2]= {9.01498, 63.0068}

In[3]:= func[]

Out[3]= {9.01167, 63.0047}

In[4]:= func[]

Out[4]= {9.00587, 63.0051}
</code>```

Body:
Mathematica, 109 bytes

a=AbsoluteTiming;LaunchKernels@7;Plus@@@a@ParallelTable[#&@@a@Pause@9,{7},Method->"EvaluationsPerKernel"->1]&

Anonymous function. Requires a license with 7+ sub-kernels to run. Takes 9 seconds realtime and 63 seconds kernel-time, not accounting for overhead. Make sure to only run the preceding statements once (so it doesn't try to re-launch kernels). Testing:

In[1]:= a=AbsoluteTiming;LaunchKernels@7;func=Plus@@@a@ParallelTable[#&@@a@Pause
@9,{7},Method->"EvaluationsPerKernel"->1]&;

In[2]:= func[]

Out[2]= {9.01498, 63.0068}

In[3]:= func[]

Out[3]= {9.01167, 63.0047}

In[4]:= func[]

Out[4]= {9.00587, 63.0051}


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

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

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

Task

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

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

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

Input

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

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

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

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

Output

Output has to be written to STDOUT or closest alternative.

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

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

Additional rules

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

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

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

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

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

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

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

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

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

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Fith, 30 bytes

```<code>*math* load line >int prime? .
</code>```

This language isn't great for golfing...

This uses the prime? function in the *math* library. Here's a version using only builtins, which is pretty much what the library function does:

```<code>line >int -> x 2 x range { x swap mod } map all .
</code>```

Explanation:

```<code>line           \ line of input
>int           \ cast to int
-> x           \ set x to the top of the stack
2 x            \ push 2, then x
range          \ range from [2, x)
{ x swap mod } \ anonymous function which calculates x mod its argument
map            \ map that function onto the generated range
all            \ return 1 if everything in the list is Boolean true, else 0
.              \ print the top of the stack
</code>```

You may be able to tell that this language is just a little bit inspired by Forth. It also takes cues from PostScript, Python, and functional programming.

Title: Is this number a prime?

Body:
Fith, 30 bytes

*math* load line >int prime? .

This language isn't great for golfing...

This uses the prime? function in the *math* library. Here's a version using only builtins, which is pretty much what the library function does:

line >int -> x 2 x range { x swap mod } map all .

Explanation:

line           \ line of input
>int           \ cast to int
-> x           \ set x to the top of the stack
2 x            \ push 2, then x
range          \ range from [2, x)
{ x swap mod } \ anonymous function which calculates x mod its argument
map            \ map that function onto the generated range
all            \ return 1 if everything in the list is Boolean true, else 0
.              \ print the top of the stack

You may be able to tell that this language is just a little bit inspired by Forth. It also takes cues from PostScript, Python, and functional programming.


问:
Tips for golfing in Haskell
What general tips do you have for golfing in Haskell? I am looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Haskell. Please post only one tip per answer.

If you are new to golfing in Haskell, please have a look at the Guide to Golfing Rules in Haskell. There is also a dedicated Haskell chat room: Of Monads and Men.

答:
Match a constant value

A list comprehension can pattern match on a constant.

[0|0<-l]
```
<p>This extracts the 0's of a list <code>l</code>, i.e. makes a list of as many 0's as are in <code>l</code>.</p>
<hr />
<pre class="lang-haskell prettyprint-override"><code>[1|[]<-f<$>l]
</code>```

This makes a list of as many 1's as there are elements of l that f takes to the empty list (using <$> as infix map). Apply sum to count these elements.

Compare:

[1|[]<-f<$>l]
[1|x<-l,f x==[]]
```
<hr />
<pre class="lang-haskell prettyprint-override"><code>[x|(0,x)<-l]
</code>```

A constant can be used as part of a pattern match. This extracts the second entries of all tuples whose first entry is 0.

Note that all of these require an actual constant literal, not a the value of a variable. For example, let x=1 in [1|x<-[1,2,3]] will output [1,1,1], not [1], because the outer x binding is overwritten.

Title: Tips for golfing in Haskell

Body:
Match a constant value

A list comprehension can pattern match on a constant.

[0|0<-l]

This extracts the 0's of a list l, i.e. makes a list of as many 0's as are in l.

[1|[]<-f<$>l]

This makes a list of as many 1's as there are elements of l that f takes to the empty list (using <$> as infix map). Apply sum to count these elements.

Compare:

[1|[]<-f<$>l]
[1|x<-l,f x==[]]

[x|(0,x)<-l]

A constant can be used as part of a pattern match. This extracts the second entries of all tuples whose first entry is 0.

Note that all of these require an actual constant literal, not a the value of a variable. For example, let x=1 in [1|x<-[1,2,3]] will output [1,1,1], not [1], because the outer x binding is overwritten.


答:
C, 54 bytes

```<code>i;main(j){for(scanf("%d",&i);i%++j;);putchar(49^j<i);}
</code>```

Must be run without parameters, so j is initialized to 1.

Reads from standard input.

Prints 1 for primes, 0 for composites (no newline).

Could save 2 bytes with unprintable output - I'm not sure if \x00 and \x01 qualify as falsy/truthy.

Title: Is this number a prime?

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

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

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

Task

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

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

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

Input

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

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

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

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

Output

Output has to be written to STDOUT or closest alternative.

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

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

Additional rules

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

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

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

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

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

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

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

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

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

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
C, 54 bytes

i;main(j){for(scanf("%d",&i);i%++j;);putchar(49^j<i);}

Must be run without parameters, so j is initialized to 1.

Reads from standard input.

Prints 1 for primes, 0 for composites (no newline).

Could save 2 bytes with unprintable output - I'm not sure if \x00 and \x01 qualify as falsy/truthy.


答:
C (with pthreads), 339 336 335 bytes

#include<stdio.h>
#include<sys/time.h>
#include<pthread.h>
#define d double
d s=0;int i;pthread_t p[14];d t(){struct timeval a;gettimeofday(&a,NULL);return a.tv_sec+a.tv_usec/1e6;}
h(){d b=t();sleep(5);s+=t()-b;}
main(){d g=t();for(i=14;i-->0;)pthread_create(&p[i],0,&h,0);for(i=14;i-->0;)pthread_join(p[i],0);printf("%f %f",t()-g,s);}
```


问:
Lossy ASCII art compression

Background

PICASCII is a neat tool that converts images into ASCII art.

It achieves different degrees of brightness by using the following ten ASCII characters:

```<code>@#+';:,.`
</code>```

We'll say that these charxels (character elements) have brightnesses from 1 (at-sign) to 10 (space).

Below, you can see the results of converting a little code, the Welsh flag, an overhanded fractal, a large trout and a little golf, displayed with the correct font:

Your can see the images in this fiddle and download them from Google Drive.

Task

While the end results of PICASCII are visually pleasing, all five images combined weigh 153,559 bytes. How much could these images be compressed if we are willing to sacrifice part of their quality?

Your task is to write a program that accepts an ASCII art image such as the above ones and a minimum quality as input and prints a lossy compression of the image – in form of a full program or a function returning a single string – that satisfies the quality requirement.

This means that you do not get to write a separate decompressor; it must be built-in into each of the compressed images.

The original image will consist of charxels with brightnesses between 1 and 10, separated by linefeeds into lines of the same length. The compressed image must have the same dimensions and use the same set of characters.

For an uncompressed image consisting of n charxels, the quality of a compressed version of the image is defined as

where ci is the brightness of the ith charxel of the compressed image's output and ui the brightness of the ith charxel of the uncompressed image.

Scoring

Your code will be run with the five images from above as input and minimum quality settings of 0.50, 0.60, 0.70, 0.80 and 0.90 for each of the images.

Your score is the geometric mean of the sizes of all compressed images, i.e., the twenty-fifth root of the product of the lengths of all twenty-five compressed images.

The lowest score wins!

Additional rules

Your code has to work for arbitrary images, not just the ones used for scoring.

It is expected that you optimize your code towards the test cases, but a program that does not even attempt to compress arbitrary images won't get an upvote from me.

Your compressor may use built-in byte stream compressors (e.g., gzip), but you have to implement them yourself for the compressed images.

Bulit-ins normally used in byte stream decompressors (e.g., base conversion, run-length decoding) are allowed.

Compressor and compressed images do not have to be in the same language.

However, you must pick a single language for all compressed images.

For each compressed image, standard code golf rules apply.

Verification

I've made a CJam script to easily verify all quality requirements and calculate a submission's score.

You can download the Java interpreter from here or here.

```<code>e# URLs of the uncompressed images.
e# "%s" will get replaced by 1, 2, 3, 4, 5.

"file:///home/dennis/codegolf/53199/original/image%s.txt"

e# URLs of the compressed images (source code).
e# "%s-%s" will get replaced by "1-50", "1-60", ... "5-90".

"file:///home/dennis/codegolf/53199/code/image%s-%s.php"

e# URLs of the compressed images (output).

"file:///home/dennis/codegolf/53199/output/image%s-%s.txt"

e# Code

:O;:C;:U;5,:)
{
    5,5f+Af*
    {
        C[IQ]e%g,X*:X;
        ISQS
        [U[I]e%O[IQ]e%]
        {g_W=N&{W<}&}%
        _Nf/::,:=
        {
            {N-"@#+';:,.` "f#}%z
            _::m2f#:+\,81d*/mq1m8#
            _"%04.4f"e%S
            @100*iQ<"(too low)"*
        }{
            ;"Dimension mismatch."
        }?
        N]o
    }fQ
}fI
N"SCORE: %04.4f"X1d25/#e%N
</code>```

Example

Bash → PHP, score 30344.0474

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

Achieves 100% quality for all inputs.

```<code>$ java -jar cjam-0.6.5.jar vrfy.cjam
1 50 1.0000
1 60 1.0000
1 70 1.0000
1 80 1.0000
1 90 1.0000
2 50 1.0000
2 60 1.0000
2 70 1.0000
2 80 1.0000
2 90 1.0000
3 50 1.0000
3 60 1.0000
3 70 1.0000
3 80 1.0000
3 90 1.0000
4 50 1.0000
4 60 1.0000
4 70 1.0000
4 80 1.0000
4 90 1.0000
5 50 1.0000
5 60 1.0000
5 70 1.0000
5 80 1.0000
5 90 1.0000

SCORE: 30344.0474
</code>```

答:
Python 3.5 (main and output) (currently noncompeting)

Happy Birthday, Challenge! Here's your present: an answer!

EDIT: Converted output to python code, improved compression rate (slightly)
EDIT2: Made it print raw when size is 1. Improved score, but score needs to be calculated again.
EDIT3: @Dennis pointed out that I still haev bugs to fix, so I marked the answer as noncompeting

Code:

```<code>import sys
LIST = [' ','`','.',',',':',';',"'",'+','#','@']

def charxel_to_brightness(charxel):
    return LIST.index(charxel)

def brightness_to_charxel(bright):
    return LIST[bright]

def image_to_brightness(imagetext):
    return [list(map(charxel_to_brightness,line)) for line in imagetext.split("\n")]

def brightness_to_image(brightarray):
    return '\n'.join([''.join(map(brightness_to_charxel,line)) for line in brightarray])

def split_into_parts(lst,size):
    return [lst[x:x+size] for x in range(0, len(lst), size)]

def gen_updown(startxel,endxel,size):
    return [[int((size-r)*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_leftright(startxel,endxel,size):
    return [[int((size-c)*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_tlbr(startxel,endxel,size):
    return [[int((2*size-r-c)/2*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_bltr(startxel,endxel,size):
    return [[int((size-r+c)/2*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_block(code,startxel,endxel,size):
    if code==0:return gen_updown(startxel,endxel,size)
    if code==1:return gen_leftright(startxel,endxel,size)
    if code==2:return gen_bltr(startxel,endxel,size)
    if code==3:return gen_tlbr(startxel,endxel,size)

def vars_to_data(code,startxel,endxel):
    acc=endxel
    acc+=startxel<<4
    acc+=code<<8
    return acc

def data_to_vars(data):
    code=data>>8
    startxel=(data>>4)&15
    endxel=data&15
    return code,startxel,endxel

def split_into_squares(imgarray,size):
    rows = split_into_parts(imgarray,size)
    allsquares = []
    for rowblock in rows:
        splitrows = []
        for row in rowblock:
            row = split_into_parts(row,size)
            splitrows.append(row)
        rowdict = []
        for row in splitrows:
            for x in range(len(row)):
                if len(rowdict)<=x:
                    rowdict.append([])
                rowdict[x].append(row[x])
        allsquares.append(rowdict)
    return allsquares

def calc_quality(imgarray,comparray):
    acc=0
    for row in range(len(imgarray)):
        for col in range(len(imgarray[row])):
            acc+=pow(imgarray[row][col]-comparray[row][col],2)
    return (1-(acc/81.0/sum([len(row) for row in imgarray]))**.5)**8

def fuse_squares(squarray):
    output=[]
    counter=0
    scounter=0
    sqrow=0
    while sqrow<len(squarray):
        if scounter<len(squarray[sqrow][0]):
            output.append([])
            for square in squarray[sqrow]:
                output[counter].extend(square[scounter])
            scounter+=1
            counter+=1
        else:
            scounter=0
            sqrow+=1
    return output

def main_calc(imgarray,threshold):
    imgarray = image_to_brightness(imgarray)
    size = 9
    quality = 0
    compimg=[]
    datarray=[]
    testdata = [vars_to_data(c,s,e) for c in range(4) for s in range(10) for e in range(10)]
    while quality<threshold:
        squares = split_into_squares(imgarray,size)
        compimg = []
        datarray = []
        testblock = [gen_block(c,s,e,size) for c in range(4) for s in range(10) for e in range(10)]
        for row in squares:
            comprow = []
            datrow=[]
            for square in row:
                quality_values = [calc_quality(square,block) for block in testblock]
                best_quality = quality_values.index(max(quality_values))
                comprow.append(testblock[best_quality])
                datrow.append(testdata[best_quality])
            compimg.append(comprow)
            datarray.append(datrow)
        compimg = fuse_squares(compimg)
        quality = calc_quality(imgarray,compimg)
        print("Size:{} Quality:{}".format(size,quality))
        size-=1
    return brightness_to_image(compimg),datarray,size+1

template = '''def s(d,s,e,z):
 x=range(z)
 return d<1 and[[int((z-r)*(e-s)/z+s)for c in x]for r in x]or d==1 and[[int((z-c)*(e-s)/z+s)for c in x]for r in x]or d==2 and[[int((2*z-r-c)/2*(e-s)/z+s)for c in x]for r in x]or d>2 and[[int((z-r+c)/2*(e-s)/z+s)for c in x] for r in x]
i=lambda a:'\\n'.join([''.join(map(lambda r:" `.,:;'+#@"[r],l))for l in a])
def f(a):
 o=[];c=0;s=0;r=0
 while r<len(a):
  if s<len(a[r][0]):
   o.append([])
   for q in a[r]:
    o[c].extend(q[s])
   s+=1;c+=1
  else:
   s=0;r+=1
 return o
t={};z={}
print(i(f([[s(D>>8,(D>>4)&15,D&15,z)for D in R]for R in t])))'''

template_size_1 = '''print("""{}""")'''

def main(filename,threshold):
    print(filename+" "+str(threshold))
    file = open(filename,'r')
    compimg,datarray,size = main_calc(file.read(),threshold)
    file.close()
    textoutput = open(filename.split(".")[0]+"-"+str(threshold*100)+".txt",'w')
    textoutput.write(compimg)
    textoutput.close()
    compoutput = open(filename.split(".")[0]+"-"+str(threshold*100)+".py",'w')
    datarray = str(datarray).replace(" ","")
    code = ""
    if size==1:
        code = template_size_1.format(compimg)
    else:
        code= template.format(datarray,str(size))
    compoutput.write(code)
    compoutput.close()
    print("done")

if __name__ == "__main__":
    main(sys.argv[1],float(sys.argv[2]))
</code>```

This answer could use a lot of improvements, so I'll probably be working on it more over the weekend.

How this works:

Divide image into blocks of size size.

Find best matching block

Blocks can have gradient now!

Calculate quality (according to formula) for entire image.

If correct, write zipped image to file.

Otherwise, decrement size and try again.

This algorithm works well for low quality (0.5, 0.6) but doesn't work too well on the higher quality images (actually inflates). It is also really slow.

Here I have all the generated files, so you won't have to re-generate them again.

Title: Lossy ASCII art compression

Body:
Python 3.5 (main and output) (currently noncompeting)

Happy Birthday, Challenge! Here's your present: an answer!

EDIT: Converted output to python code, improved compression rate (slightly)
EDIT2: Made it print raw when size is 1. Improved score, but score needs to be calculated again.
EDIT3: @Dennis pointed out that I still haev bugs to fix, so I marked the answer as noncompeting

Code:

import sys
LIST = [' ','`','.',',',':',';',"'",'+','#','@']

def charxel_to_brightness(charxel):
    return LIST.index(charxel)

def brightness_to_charxel(bright):
    return LIST[bright]

def image_to_brightness(imagetext):
    return [list(map(charxel_to_brightness,line)) for line in imagetext.split("\n")]

def brightness_to_image(brightarray):
    return '\n'.join([''.join(map(brightness_to_charxel,line)) for line in brightarray])

def split_into_parts(lst,size):
    return [lst[x:x+size] for x in range(0, len(lst), size)]

def gen_updown(startxel,endxel,size):
    return [[int((size-r)*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_leftright(startxel,endxel,size):
    return [[int((size-c)*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_tlbr(startxel,endxel,size):
    return [[int((2*size-r-c)/2*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_bltr(startxel,endxel,size):
    return [[int((size-r+c)/2*(endxel-startxel)/size+startxel) for c in range(size)] for r in range(size)]

def gen_block(code,startxel,endxel,size):
    if code==0:return gen_updown(startxel,endxel,size)
    if code==1:return gen_leftright(startxel,endxel,size)
    if code==2:return gen_bltr(startxel,endxel,size)
    if code==3:return gen_tlbr(startxel,endxel,size)

def vars_to_data(code,startxel,endxel):
    acc=endxel
    acc+=startxel<<4
    acc+=code<<8
    return acc

def data_to_vars(data):
    code=data>>8
    startxel=(data>>4)&15
    endxel=data&15
    return code,startxel,endxel

def split_into_squares(imgarray,size):
    rows = split_into_parts(imgarray,size)
    allsquares = []
    for rowblock in rows:
        splitrows = []
        for row in rowblock:
            row = split_into_parts(row,size)
            splitrows.append(row)
        rowdict = []
        for row in splitrows:
            for x in range(len(row)):
                if len(rowdict)<=x:
                    rowdict.append([])
                rowdict[x].append(row[x])
        allsquares.append(rowdict)
    return allsquares

def calc_quality(imgarray,comparray):
    acc=0
    for row in range(len(imgarray)):
        for col in range(len(imgarray[row])):
            acc+=pow(imgarray[row][col]-comparray[row][col],2)
    return (1-(acc/81.0/sum([len(row) for row in imgarray]))**.5)**8

def fuse_squares(squarray):
    output=[]
    counter=0
    scounter=0
    sqrow=0
    while sqrow<len(squarray):
        if scounter<len(squarray[sqrow][0]):
            output.append([])
            for square in squarray[sqrow]:
                output[counter].extend(square[scounter])
            scounter+=1
            counter+=1
        else:
            scounter=0
            sqrow+=1
    return output

def main_calc(imgarray,threshold):
    imgarray = image_to_brightness(imgarray)
    size = 9
    quality = 0
    compimg=[]
    datarray=[]
    testdata = [vars_to_data(c,s,e) for c in range(4) for s in range(10) for e in range(10)]
    while quality<threshold:
        squares = split_into_squares(imgarray,size)
        compimg = []
        datarray = []
        testblock = [gen_block(c,s,e,size) for c in range(4) for s in range(10) for e in range(10)]
        for row in squares:
            comprow = []
            datrow=[]
            for square in row:
                quality_values = [calc_quality(square,block) for block in testblock]
                best_quality = quality_values.index(max(quality_values))
                comprow.append(testblock[best_quality])
                datrow.append(testdata[best_quality])
            compimg.append(comprow)
            datarray.append(datrow)
        compimg = fuse_squares(compimg)
        quality = calc_quality(imgarray,compimg)
        print("Size:{} Quality:{}".format(size,quality))
        size-=1
    return brightness_to_image(compimg),datarray,size+1

template = '''def s(d,s,e,z):
 x=range(z)
 return d<1 and[[int((z-r)*(e-s)/z+s)for c in x]for r in x]or d==1 and[[int((z-c)*(e-s)/z+s)for c in x]for r in x]or d==2 and[[int((2*z-r-c)/2*(e-s)/z+s)for c in x]for r in x]or d>2 and[[int((z-r+c)/2*(e-s)/z+s)for c in x] for r in x]
i=lambda a:'\\n'.join([''.join(map(lambda r:" `.,:;'+#@"[r],l))for l in a])
def f(a):
 o=[];c=0;s=0;r=0
 while r<len(a):
  if s<len(a[r][0]):
   o.append([])
   for q in a[r]:
    o[c].extend(q[s])
   s+=1;c+=1
  else:
   s=0;r+=1
 return o
t={};z={}
print(i(f([[s(D>>8,(D>>4)&15,D&15,z)for D in R]for R in t])))'''

template_size_1 = '''print("""{}""")'''

def main(filename,threshold):
    print(filename+" "+str(threshold))
    file = open(filename,'r')
    compimg,datarray,size = main_calc(file.read(),threshold)
    file.close()
    textoutput = open(filename.split(".")[0]+"-"+str(threshold*100)+".txt",'w')
    textoutput.write(compimg)
    textoutput.close()
    compoutput = open(filename.split(".")[0]+"-"+str(threshold*100)+".py",'w')
    datarray = str(datarray).replace(" ","")
    code = ""
    if size==1:
        code = template_size_1.format(compimg)
    else:
        code= template.format(datarray,str(size))
    compoutput.write(code)
    compoutput.close()
    print("done")

if __name__ == "__main__":
    main(sys.argv[1],float(sys.argv[2]))

This answer could use a lot of improvements, so I'll probably be working on it more over the weekend.

How this works:

Divide image into blocks of size size.

Find best matching block

Blocks can have gradient now!

Calculate quality (according to formula) for entire image.

If correct, write zipped image to file.

Otherwise, decrement size and try again.

This algorithm works well for low quality (0.5, 0.6) but doesn't work too well on the higher quality images (actually inflates). It is also really slow.

Here I have all the generated files, so you won't have to re-generate them again.


答:
Javascript (ES6), 108 92 bytes

I'm making a new answer since this uses a slightly different aproach.

It generates a massive amount of setTimeouts, which are almost all executed with 4ms between them.

Each interval is of 610 milliseconds, over a total of 99 intervals.

M=(N=Date.now)(T=Y=0),eval('setTimeout("T+=N()-M,--i||alert([N()-M,T])",610);'.repeat(i=99))```
</div>
</div>
</p>

<p>It usually runs within 610ms, for a total execution time of around 60.5 seconds.</p>

<p>This was tested on Google Chrome version 51.0.2704.84 m, on windows 8.1 x64.</p>

<hr>

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

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>P=performance,M=P.now(T=Y=0),eval('setTimeout("T+=P.now()-M,--i||alert([P.now()-M,T])",610);'.repeat(i=99))</code>```

Body:
Javascript (ES6), 108 92 bytes

I'm making a new answer since this uses a slightly different aproach.

It generates a massive amount of setTimeouts, which are almost all executed with 4ms between them.

Each interval is of 610 milliseconds, over a total of 99 intervals.

M=(N=Date.now)(T=Y=0),eval('setTimeout("T+=N()-M,--i||alert([N()-M,T])",610);'.repeat(i=99))

It usually runs within 610ms, for a total execution time of around 60.5 seconds.

This was tested on Google Chrome version 51.0.2704.84 m, on windows 8.1 x64.

Old version (108 bytes):

P=performance,M=P.now(T=Y=0),eval('setTimeout("T+=P.now()-M,--i||alert([P.now()-M,T])",610);'.repeat(i=99))


答:
Javascript (ES6), 105 bytes

((t,c,d)=>{i=t();while(c--)setTimeout((c,s)=>{d+=t()-s;if(!c)alert([t()-i,d])},8e3,c,t())})(Date.now,8,0)```
</div>
</div>
</p>

<p><strong>Updated version: 106 bytes</strong>
Borrowed from @Ismael Miguel as he had the great idea to lower sleep time and raise intervals.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>((t,c,d)=>{i=t();while(c--)setTimeout((c,s)=>{d+=t()-s;if(!c)alert([t()-i,d])},610,c,t())})(Date.now,99,0)</code>```

Javascript Ungolfed, 167 bytes

(function(t, c, d){
 i = t();
 while(c--){
  setTimeout(function(c, s){
   d += t() - s;
   if (!c) alert([t() - i, d])
  }, 8e3, c, t())
 }
})(Date.now, 8, 0)```

Body:
Javascript (ES6), 105 bytes

((t,c,d)=>{i=t();while(c--)setTimeout((c,s)=>{d+=t()-s;if(!c)alert([t()-i,d])},8e3,c,t())})(Date.now,8,0)

Updated version: 106 bytes
Borrowed from @Ismael Miguel as he had the great idea to lower sleep time and raise intervals.

((t,c,d)=>{i=t();while(c--)setTimeout((c,s)=>{d+=t()-s;if(!c)alert([t()-i,d])},610,c,t())})(Date.now,99,0)

Javascript Ungolfed, 167 bytes

(function(t, c, d){
 i = t();
 while(c--){
  setTimeout(function(c, s){
   d += t() - s;
   if (!c) alert([t() - i, d])
  }, 8e3, c, t())
 }
})(Date.now, 8, 0)


问:
"Bit-borrow" two numbers
Did you know that a small number can borrow bits from a larger number? Here's an example. Let's say our two numbers 5 and 14. First, write them out in binary:

```<code>5       14
000101  001110
</code>```

First we take the smallest on bit away from the larger number, and we give it to the smallest off bit on the other number. So

```<code>This bit turns off
            |
            v
000101  001110
    ^
    |
This bit turns on
</code>```

Now we have

```<code>000111  001100
</code>```

and our numbers are 7 and 12. The first number is still smaller, so we continue.

```<code>000111  001100
001111  001000
</code>```

Now we have 15 and 8, so we can stop. We'll call this set of operations "bit-borrowing" two numbers. Let's do another example. 20 and 61.

```<code>20        61
010100    111101
010101    111100
010111    111000
111111    100000
63        32
</code>```

So our end result is 32, 63. Let's do one more. 31, and 12. 31 is already bigger than 12, so there's nothing to do! Bit-borrowing 31 and 12 gives 31 and 12, no change.

The challenge

Your challenge is to write a program or function that takes two numbers and bit-borrows them. The two numbers will always positive integers. Your input and output can be in any reasonable format.

Test IO:

```<code>Input: 2, 3
Output: 3, 2

Input: 3, 2
Output: 3, 2

Input: 8, 23
Output: 31, 0

Input: 42, 81
Output: 63, 0

Input: 38, 41
Output: 47, 32

Input: 16, 73
Output: 23, 0

Input: 17, 17
Output: 17, 17
</code>```

Standard loopholes apply, and shortest answer in bytes wins!

答:
Jelly, 11 bytes

```<code>~1¦&N$^µ</¿
</code>```

Try it online! or verify all test cases.

Background

We can extract the last set bit of an integer n as follows.

n + 1 toggles all trailing set bits of n and the adjacent unset bit. For example, 100112 + 1 = 101002.

Since ~n = -(n + 1) = -n - 1, -n = ~n + 1, so -n applies the above to the bitwise NOT of n (which toggles all bits), thus toggling all bits before the last 1.

For example, -101002 = ~101002 + 1 = 010112 + 1 = 011002.

By taking n & -n the bitwise AND of n and -n all bits before the last set bit are nullified (since unequal in n and -n), thus yielding the last set bit of n.

For example, 101002 & -101002 = 101002 & 011002 = 001002.

Thus XORing n with n & -n unsets the last set bit of n.

Conversely, to unset the last set bit of n, it suffices to apply the above to ~n, from where we derive the formula n ^ (~n & -~n).

How it works

```<code>~1¦&N$^µ</¿  Main link. Argument: A (list of pairs)

          ¿  While loop:
        </     Condition: Reduce p by less-than. True iff x < y.
       µ       Body chain:
~1¦              Apply bitwise NOT to the x, first item of the pair.
     $           Convert the two links to the left into a monadic chain.
    N              Negate; multiply [~x, y] by -1, yielding [-~x, -y].
   &               Logical AND. Yields [-~x & ~x, -y & y].
      ^            Vectorized XOR with p. Yields [(-~x & ~x) ^ x, (-y & y) ^ y].
</code>```

Title: "Bit-borrow" two numbers

Body:
Jelly, 11 bytes

~1¦&N$^µ</¿

Try it online! or verify all test cases.

Background

We can extract the last set bit of an integer n as follows.

n + 1 toggles all trailing set bits of n and the adjacent unset bit. For example, 100112 + 1 = 101002.

Since ~n = -(n + 1) = -n - 1, -n = ~n + 1, so -n applies the above to the bitwise NOT of n (which toggles all bits), thus toggling all bits before the last 1.

For example, -101002 = ~101002 + 1 = 010112 + 1 = 011002.

By taking n & -n the bitwise AND of n and -n all bits before the last set bit are nullified (since unequal in n and -n), thus yielding the last set bit of n.

For example, 101002 & -101002 = 101002 & 011002 = 001002.

Thus XORing n with n & -n unsets the last set bit of n.

Conversely, to unset the last set bit of n, it suffices to apply the above to ~n, from where we derive the formula n ^ (~n & -~n).

How it works

~1¦&N$^µ</¿  Main link. Argument: A (list of pairs)

          ¿  While loop:
        </     Condition: Reduce p by less-than. True iff x < y.
       µ       Body chain:
~1¦              Apply bitwise NOT to the x, first item of the pair.
     $           Convert the two links to the left into a monadic chain.
    N              Negate; multiply [~x, y] by -1, yielding [-~x, -y].
   &               Logical AND. Yields [-~x & ~x, -y & y].
      ^            Vectorized XOR with p. Yields [(-~x & ~x) ^ x, (-y & y) ^ y].


答:
Python, 42 bytes

f=lambda x,y:x<y and f(x|x+1,y&y-1)or(x,y)
```

Thanks to @jimmy23013 for golfing off 4 bytes! Thanks to @LeakyNun for golfing off 2 bytes!

Test it on Ideone.

Title: "Bit-borrow" two numbers

Body:
Did you know that a small number can borrow bits from a larger number? Here's an example. Let's say our two numbers 5 and 14. First, write them out in binary:

```<code>5       14
000101  001110
</code>```

First we take the smallest on bit away from the larger number, and we give it to the smallest off bit on the other number. So

```<code>This bit turns off
            |
            v
000101  001110
    ^
    |
This bit turns on
</code>```

Now we have

```<code>000111  001100
</code>```

and our numbers are 7 and 12. The first number is still smaller, so we continue.

```<code>000111  001100
001111  001000
</code>```

Now we have 15 and 8, so we can stop. We'll call this set of operations "bit-borrowing" two numbers. Let's do another example. 20 and 61.

```<code>20        61
010100    111101
010101    111100
010111    111000
111111    100000
63        32
</code>```

So our end result is 32, 63. Let's do one more. 31, and 12. 31 is already bigger than 12, so there's nothing to do! Bit-borrowing 31 and 12 gives 31 and 12, no change.

The challenge

Your challenge is to write a program or function that takes two numbers and bit-borrows them. The two numbers will always positive integers. Your input and output can be in any reasonable format.

Test IO:

```<code>Input: 2, 3
Output: 3, 2

Input: 3, 2
Output: 3, 2

Input: 8, 23
Output: 31, 0

Input: 42, 81
Output: 63, 0

Input: 38, 41
Output: 47, 32

Input: 16, 73
Output: 23, 0

Input: 17, 17
Output: 17, 17
</code>```

Standard loopholes apply, and shortest answer in bytes wins!

Body:
Python, 42 bytes

f=lambda x,y:x<y and f(x|x+1,y&y-1)or(x,y)

Thanks to @jimmy23013 for golfing off 4 bytes! Thanks to @LeakyNun for golfing off 2 bytes!

Test it on Ideone.


答:
Pyth, <s>29</s> <s>27</s> <s>25</s> <s>22</s> <s>21</s> <s>20</s> <s>19</s> <s>18</s> 16 bytes

```
<s>MxG^2x_+\0.BG`HCm.W<FHgVZU2dC</s>
<s>MxG^2x_+0jG2HCm.W<FHgVZU2dC</s>
<s>Cm.W<FH.bxN^2x_+0jN2YZ2dC</s>
<s>m.W<FH.bxN^2x_+0jN2YZ2</s>      <-- changed input/output format
<s>m.W<FH.exb^2x_+0jb2kZ</s>
<s>m.W<FH.U,.|bhb.&ZtZZ</s>
<s>.W<FH.U,.|bhb.&ZtZZ</s>         <-- changed input/output format
<s>.W<FH.U,.|bhb.&ZtZ</s>
.W<FH.U,.|bhb.&t
```

Test suite.

Title: "Bit-borrow" two numbers

Body:
Pyth, <s>29</s> <s>27</s> <s>25</s> <s>22</s> <s>21</s> <s>20</s> <s>19</s> <s>18</s> 16 bytes

<s>MxG^2x_+\0.BG`HCm.W<FHgVZU2dC</s>
<s>MxG^2x_+0jG2HCm.W<FHgVZU2dC</s>
<s>Cm.W<FH.bxN^2x_+0jN2YZ2dC</s>
<s>m.W<FH.bxN^2x_+0jN2YZ2</s>      <-- changed input/output format
<s>m.W<FH.exb^2x_+0jb2kZ</s>
<s>m.W<FH.U,.|bhb.&ZtZZ</s>
<s>.W<FH.U,.|bhb.&ZtZZ</s>         <-- changed input/output format
<s>.W<FH.U,.|bhb.&ZtZ</s>
.W<FH.U,.|bhb.&t

Test suite.


答:
J, <s>31</s> 26 bytes

```<code>,`(($:~(OR>:))~(AND<:))@.<
</code>```

Straight-forward approach using recursion and bitwise tricks. In order to turn off (set to 0) the right-most on (1) bit for a value n, you can perform bitwise-and between n and n-1, and to turn on (set to 1) the right-most off (0) bit for a value n, you can perform bitwise-or between n and n+1.

Usage

The input consists of two integers, one applied on the LHS and the other on the RHS, and the output is a list of the bit-borrowed values.

```<code>   f =: ,`(($:~(OR>:))~(AND<:))@.<
   2 f 3
3 2
   3 f 2
3 2
   8 f 23
31 0
   42 f 81
63 0
   38 f 41
47 32
   16 f 73
23 0
   17 f 17
17 17
</code>```

Explanation

```<code>,`(($:~(OR>:))~(AND<:))@.<  Input: x on LHS, y on RHS
                            If x < y,
,                             Form a 2-element array [x, y] and return
                            Else
                   <:         Decrement y
                AND           Perform bitwise-and on y and y-1, call it y'
          >:                  Increment x
        OR                    Perform bitwise-or on x and x+1, call it x'
    $:                        Call recursively on x' and y' and return
</code>```

Title: "Bit-borrow" two numbers

Body:
J, <s>31</s> 26 bytes

,`(($:~(OR>:))~(AND<:))@.<

Straight-forward approach using recursion and bitwise tricks. In order to turn off (set to 0) the right-most on (1) bit for a value n, you can perform bitwise-and between n and n-1, and to turn on (set to 1) the right-most off (0) bit for a value n, you can perform bitwise-or between n and n+1.

Usage

The input consists of two integers, one applied on the LHS and the other on the RHS, and the output is a list of the bit-borrowed values.

   f =: ,`(($:~(OR>:))~(AND<:))@.<
   2 f 3
3 2
   3 f 2
3 2
   8 f 23
31 0
   42 f 81
63 0
   38 f 41
47 32
   16 f 73
23 0
   17 f 17
17 17

Explanation

,`(($:~(OR>:))~(AND<:))@.<  Input: x on LHS, y on RHS
                            If x < y,
,                             Form a 2-element array [x, y] and return
                            Else
                   <:         Decrement y
                AND           Perform bitwise-and on y and y-1, call it y'
          >:                  Increment x
        OR                    Perform bitwise-or on x and x+1, call it x'
    $:                        Call recursively on x' and y' and return


问:
The handshake problem
The handshake problem is the classic problem that for n people in a room, if they all shake hands, what's the total number of handshakes that occur.

You code should take an input of any number and output the number of handshakes, both in base ten.

Also the code should not let non-integers through. You should output a falsey in this case. The only expected inputs are positive whole integers and positive real numbers - you don't need to worry about complex numbers or strings as inputs.
This should mean that you should expect n >= 0

Test cases

```<code>(N:handshakes)
0:0
10:45
20:190
10.5:0
1337:893116
</code>```

Normal golfing rules apply and shortest code wins.
If your code isn't self explanatory, please explain.

Jelly and 05AB1E are the winners, both at 2 bytes

答:
Java, 363 bytes

I thought I ought to make sure everybody gets a chance to meet everybody else.

Unfortunately some of the party guests do have to ask if they've met someone before, to avoid shaking someone's hand twice. Hopefully the guests are pretty good at recognizing faces.

Golfed:

```<code>import java.util.ArrayList;public class H{static int h = 0;public static void main(String[] a){int b = Integer.parseInt(a[0]);P[] e = new P[b];for(int i=0;i<b;i++){e[i] = new P();}for(P p : e){for(P o : e){p.s(o);}}System.out.print(h);}}class P {ArrayList<P> l = new ArrayList<P>();void s(P o){if(o.equals(this)){return;}if(!o.l.contains(this)){H.h++;l.add(o);}}}
</code>```

Un-golfed:

```<code>import java.util.ArrayList;

public class PartyHost {
    static int shakes = 0;
    public static void main(String[] args){
        int amount = Integer.parseInt(args[0]);
        Person[] people = new Person[amount];
        for(int i=0; i<amount;i++){
            people[i] = new Person();
            // welcome to the party!
        }
        // well, we gotta get this party rockin'. hey, have you met my friend...
        for(Person p : people){
            for(Person other : people){
                p.handshake(other);
            }
        }
        System.out.print(shakes);
    }
}

class Person {
    ArrayList<Person> already_shook = new ArrayList<Person>();
    void handshake(Person other){
        // hmm, have we met already?
        if(other.equals(this)){
            // I mean, I guess I could shake hands with myself... maybe later.
            return;
        }
        if(!other.already_shook.contains(this)){
            // it seems not!
            // *firm grasp. maintain eye contact*
            // uh oh don't hold on too long
            // hope he doesn't grab too early or too late
            PartyHost.shakes++;
            already_shook.add(other);
        }
    }
}
</code>```

Title: The handshake problem

Body:
Java, 363 bytes

I thought I ought to make sure everybody gets a chance to meet everybody else.

Unfortunately some of the party guests do have to ask if they've met someone before, to avoid shaking someone's hand twice. Hopefully the guests are pretty good at recognizing faces.

Golfed:

import java.util.ArrayList;public class H{static int h = 0;public static void main(String[] a){int b = Integer.parseInt(a[0]);P[] e = new P[b];for(int i=0;i<b;i++){e[i] = new P();}for(P p : e){for(P o : e){p.s(o);}}System.out.print(h);}}class P {ArrayList<P> l = new ArrayList<P>();void s(P o){if(o.equals(this)){return;}if(!o.l.contains(this)){H.h++;l.add(o);}}}

Un-golfed:

import java.util.ArrayList;

public class PartyHost {
    static int shakes = 0;
    public static void main(String[] args){
        int amount = Integer.parseInt(args[0]);
        Person[] people = new Person[amount];
        for(int i=0; i<amount;i++){
            people[i] = new Person();
            // welcome to the party!
        }
        // well, we gotta get this party rockin'. hey, have you met my friend...
        for(Person p : people){
            for(Person other : people){
                p.handshake(other);
            }
        }
        System.out.print(shakes);
    }
}

class Person {
    ArrayList<Person> already_shook = new ArrayList<Person>();
    void handshake(Person other){
        // hmm, have we met already?
        if(other.equals(this)){
            // I mean, I guess I could shake hands with myself... maybe later.
            return;
        }
        if(!other.already_shook.contains(this)){
            // it seems not!
            // *firm grasp. maintain eye contact*
            // uh oh don't hold on too long
            // hope he doesn't grab too early or too late
            PartyHost.shakes++;
            already_shook.add(other);
        }
    }
}