答:
Java 7, 36 bytes

```<code>int c(int n){return(n/3+1)*(1-n%3);}
</code>```

Ungolfed & test code:

Try it here.

```<code>class Main{

    static int c(int n){
        return (n / 3 + 1) * (1 - n % 3);
    }

    public static void main(String[] a){
        System.out.println(c(0));
        System.out.println(c(11));
        System.out.println(c(76));
        System.out.println(c(134));
        System.out.println(c(296));
    }
}
</code>```

Zero-indexed output:

```<code>1
-4
0
-45
-99
</code>```

Title: Alternating Sign Sequence

Body:
Java 7, 36 bytes

int c(int n){return(n/3+1)*(1-n%3);}

Ungolfed & test code:

Try it here.

class Main{

    static int c(int n){
        return (n / 3 + 1) * (1 - n % 3);
    }

    public static void main(String[] a){
        System.out.println(c(0));
        System.out.println(c(11));
        System.out.println(c(76));
        System.out.println(c(134));
        System.out.println(c(296));
    }
}

Zero-indexed output:

1
-4
0
-45
-99


问:
Greatest Common Divisor
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

```<code>0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101
</code>```

答:
><>, 12+3 = 15 bytes

```<code>:?!\:}%
;n~/
</code>```

Expects the input numbers to be present on the stack, so +3 bytes for the -v flag. Try it online!

Another implementation of the Euclidean algorithm.

ContentLicense: CC BY-SA 3.0

Title: Greatest Common Divisor

Body:
><>, 12+3 = 15 bytes

:?!\:}%
;n~/

Expects the input numbers to be present on the stack, so +3 bytes for the -v flag. Try it online!

Another implementation of the Euclidean algorithm.


问:
Fairly rank values

Task

Given an input list of integers x1…xn, compute a list of ranks r1…rn (a permutation of {1…n}) so that xr1 ≤ xr2 ≤ … ≤ xrn. Then, for each xi, replace its rank by the arithmetic mean of the ranks of all values in x that are equal to xi. (That is, whenever there is a tie between equal values in x, fairly redistribute the ranks among all of them.) Output the modified list of ranks r’1…r’n.

(For statistics geeks: such a ranking of observations is used in the Mann–Whitney U test (method two, step 1.))

Example

Given an input list [3, -6, 3, 3, 14, 3], the first list of ranks would be [2, 1, 3, 4, 6, 5], which would sort the list into [-6, 3, 3, 3, 3, 14]. Then, the ranks for all 3s in the input list are evened out into (2 + 3 + 4 + 5) ÷ 4 = 3.5. The final output is [3.5, 1, 3.5, 3.5, 6, 3.5].

Test cases

```<code>[4, 1, 4] -> [2.5, 1.0, 2.5]
[5, 14, 14, 14, 14, 5, 14] -> [1.5, 5.0, 5.0, 5.0, 5.0, 1.5, 5.0]
[9, 9, -5, -5, 13, -5, 13, 9, 9, 13] -> [5.5, 5.5, 2.0, 2.0, 9.0, 2.0, 9.0, 5.5, 5.5, 9.0]
[13, 16, 2, -5, -5, -5, 13, 16, -5, -5] -> [7.5, 9.5, 6.0, 3.0, 3.0, 3.0, 7.5, 9.5, 3.0, 3.0]
</code>```

Rules

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

Title: Fairly rank values

Body:
J, 18 bytes

1-:@+1+/"1@:+*@-/~

Based on Dennis' solution using xnor's method.

Using a straight-forward approach requires 24 bytes for me.

(i.~~.){](+/%#)/.1+/:@/:

Usage

   f =: 1-:@+1+/"1@:+*@-/~
   f 3 _6 3 3 14 3
3.5 1 3.5 3.5 6 3.5
   f 4 1 4
2.5 1 2.5
   f 5 14 14 14 14 5 14
1.5 5 5 5 5 1.5 5
   f 9 9 _5 _5 13 _5 13 9 9 13
5.5 5.5 2 2 9 2 9 5.5 5.5 9
   f 13 16 2 _5 _5 _5 13 16 _5 _5
7.5 9.5 6 3 3 3 7.5 9.5 3 3


问:
Oneliner to merge lines with same first field
This is my first codegolf question, so I apologize in advance if it's not appropriate, and I welcome any feedback.

I have a file with this format:

```<code>a | rest of first line
b | rest of second line
b | rest of third line
c | rest of fourth line
d | rest of fifth line
d | rest of sixth line
</code>```

The actual contents vary, as does the delimiter. The contents are just text. The delimiter only appears once per line. For this puzzle, feel free to change the delimiter, e.g. use "%" as the delimiter.

Desired output:

```<code>a | rest of first line
b | rest of second line % rest of third line
c | rest of fourth line
d | rest of fifth line % rest of sixth line
</code>```

I already have both ruby and awk scripts to merge this, but I suspect it's possible to have a short oneliner. i.e. a one-liner that can be used along with pipes and other commands on the command line. I can't figure it out, and my own script is to long to just compress on the command line.

Shortest characters preferred. Input is not necessarily sorted, but we are only interested in merging consecutive lines with matching first fields. There are unlimited lines with matching first fields. Field 1 could be anything, e.g. names of fruits, proper names, etc.

(I run on MacOS, so I am personally most interested in implementations that run on the mac).

Here is a second example/test. Notice "|" is the delimiter. The space before the "|" is irrelevant, and if resent should be considered part of the key. I am using "%" as a delimited in the output, but again, feel free to change the delimiter (but don't used square brackets).

Input:

```<code>why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination
whom|[possessive] whose
whom|[subjective] who
whoever|[objective] whomever
whoever|[possessive] whosever
who|[possessive] whose
who|[objective] whom
</code>```

Desired output:

```<code>why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
whoever|[objective] whomever%[possessive] whosever
who|[possessive] whose%[objective] whom
</code>```

答:
Python 3 - 146 Bytes

Input is the filename or file path of the file, output is to stdout. Could be a lot shorter if I could take input as raw text from command line

Takes input from stdin and outputs to stdin. Setup with separator "|". To test the first example input use the separator " | "

```<code>from itertools import*
for c,b in groupby([x.split("|")for x in input().split("\n")],key=lambda x:x[0]):print(c,"|"," % ".join((a[1]for a in b)))
</code>```

Body:
Python 3 - 146 Bytes

Input is the filename or file path of the file, output is to stdout. Could be a lot shorter if I could take input as raw text from command line

Takes input from stdin and outputs to stdin. Setup with separator "|". To test the first example input use the separator " | "

from itertools import*
for c,b in groupby([x.split("|")for x in input().split("\n")],key=lambda x:x[0]):print(c,"|"," % ".join((a[1]for a in b)))


问:
Collide against walls

Statement

Given an input like this 35 15 0 0 10 that matches the following constrains:

Width in characters of the grid (5-50)

Height in characters of the grid (5-25)

Initial X position of the ball (0-(Width-1)

Initial Y position of the ball (0-(Height-1)

Number of movements to simulate

Generate a grid that shows the trajectory of the ball, knowing it's direction is initially DR (down-right) and that colliding with a wall will reverse the increment being applied to that axis. In other words, if we are going DR and hit the bottom we will now be going UR until we collide again.

The trajectory is not affected by passing twice over the same point since it's not the game snake, it's the trajectory of an object in 2d.

The input will be a string such as the one above and the output should be similar to this, not caring about which characters represent the wall, trajectory or ball, as long as they're consistent.

Points

Your score is the length of your submission, in characters.

Winners by language

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Q, 94 Bytes (kx.com)

{[w;h;i;j;n]./[(1+h,w)#" ";+{z#y_+\0,-1 1@{x=2*_x%2}'&(-_-(z+y)%x)#x}.'(h,j,n;w,i,n);:;"*"]}.

Defines a lambda with parameters w (width), h (height), i (initial x), j (initial y), and n (number of movements).

Lambda is delimited with {}

Final . (after }) allows to use a sequence as argument. Standard function invocation is f[arg;arg;..;arg], but we can also invoque as f . sequence. An integer sequence is v v .. v, so we can invoque as f . w h i j n. If we define f:{..}. we can invoque as f w h i j n (as required by the question)

Solution uses 'K mode' of Q. K is the functional inner core of Q (Q is more readable, verbose and with a lot of additional libraries, but K is compact). To execute in K mode we must use scripts with k extension (vs q extension for q mode). Interactive interpreter starts in Q mode (-> q) prompt). We can load code from k script, and execute test directly on interactive interpreter (even in q mode, as shown in test). There is also a k mode at interactive interpreter level, but it's not worth in this case.

TEST

NOTE.- to avoid display cluttering, we assume f name associated to lambda (f:{..}.)

```<code>q)f 35 15 0 0 49
"*                             *     "
" *                           * *    "
"  *                         *   *   "
"   *                       *     *  "
"    *                     *       * "
"     *                   *         *"
"      *                 *         * "
"       *               *         *  "
"        *             *         *   "
"         *           *         *    "
"          *         *         *     "
"           *       *         *      "
"            *     *   *     *       "
"             *   *     *   *        "
"              * *       * *         "
"               *         *          "
q)f 35 15 4 2 49
"                                *   "
"                               * *  "
"    *                         *   * "
"     *                       *     *"
"      *                     *     * "
"       *                   *     *  "
"        *                 *     *   "
"         *               *     *    "
"          *             *     *     "
"           *           *     *      "
"            *     *   *     *       "
"             *     * *     *        "
"              *     *     *         "
"               *   * *   *          "
"                * *   * *           "
"                 *     *            "
</code>```

EXPLANATION

We define a lambda for 1D movement that accepts args [max;init;n] (legal positions 0..max-1, initial pos init, n movements) and returns a sequence of positions (after computing rebounds). Later apply that lambda to y and x axes (with args [h;j;n] and [w;i;n] respectively).

Initially assume starting at 0 pos. We calculate number of rebounds to accomplish n movements, and generate a sequence with repeated increasing numbers (0 0 ...0; 1 1 .. 1; 2 2  .. 2; ..).

Each subsequence has w items, so there are rebounds just between subsequences. For each number determine if is even, and sustitutes even results by 1 and even results by -1. (1 1 .. 1; -1 -1 .. -1; 1 1 .. 1; ..)

We join subsequences and calculate accumulated sums starting with 0 -> 0 1 2 3 .. 35 34 33 32 .. 0 1 2 ..

finally we drop starting i movements and take exactly n movements

Last, we define a (h x w) char matrix filled with blanks, and for each position (resulting of applying 1D lambda on y and x) we replace character with "*"

Title: Collide against walls

Body:
Q, 94 Bytes (kx.com)

{[w;h;i;j;n]./[(1+h,w)#" ";+{z#y_+\0,-1 1@{x=2*_x%2}'&(-_-(z+y)%x)#x}.'(h,j,n;w,i,n);:;"*"]}.

Defines a lambda with parameters w (width), h (height), i (initial x), j (initial y), and n (number of movements).

Lambda is delimited with {}

Final . (after }) allows to use a sequence as argument. Standard function invocation is f[arg;arg;..;arg], but we can also invoque as f . sequence. An integer sequence is v v .. v, so we can invoque as f . w h i j n. If we define f:{..}. we can invoque as f w h i j n (as required by the question)

Solution uses 'K mode' of Q. K is the functional inner core of Q (Q is more readable, verbose and with a lot of additional libraries, but K is compact). To execute in K mode we must use scripts with k extension (vs q extension for q mode). Interactive interpreter starts in Q mode (-> q) prompt). We can load code from k script, and execute test directly on interactive interpreter (even in q mode, as shown in test). There is also a k mode at interactive interpreter level, but it's not worth in this case.

TEST

NOTE.- to avoid display cluttering, we assume f name associated to lambda (f:{..}.)

q)f 35 15 0 0 49
"*                             *     "
" *                           * *    "
"  *                         *   *   "
"   *                       *     *  "
"    *                     *       * "
"     *                   *         *"
"      *                 *         * "
"       *               *         *  "
"        *             *         *   "
"         *           *         *    "
"          *         *         *     "
"           *       *         *      "
"            *     *   *     *       "
"             *   *     *   *        "
"              * *       * *         "
"               *         *          "
q)f 35 15 4 2 49
"                                *   "
"                               * *  "
"    *                         *   * "
"     *                       *     *"
"      *                     *     * "
"       *                   *     *  "
"        *                 *     *   "
"         *               *     *    "
"          *             *     *     "
"           *           *     *      "
"            *     *   *     *       "
"             *     * *     *        "
"              *     *     *         "
"               *   * *   *          "
"                * *   * *           "
"                 *     *            "

EXPLANATION

We define a lambda for 1D movement that accepts args [max;init;n] (legal positions 0..max-1, initial pos init, n movements) and returns a sequence of positions (after computing rebounds). Later apply that lambda to y and x axes (with args [h;j;n] and [w;i;n] respectively).

Initially assume starting at 0 pos. We calculate number of rebounds to accomplish n movements, and generate a sequence with repeated increasing numbers (0 0 ...0; 1 1 .. 1; 2 2  .. 2; ..).

Each subsequence has w items, so there are rebounds just between subsequences. For each number determine if is even, and sustitutes even results by 1 and even results by -1. (1 1 .. 1; -1 -1 .. -1; 1 1 .. 1; ..)

We join subsequences and calculate accumulated sums starting with 0 -> 0 1 2 3 .. 35 34 33 32 .. 0 1 2 ..

finally we drop starting i movements and take exactly n movements

Last, we define a (h x w) char matrix filled with blanks, and for each position (resulting of applying 1D lambda on y and x) we replace character with "*"


Title: Display "Happy Easter!"

Body:
Your task is to print the following ASCII Art:

```<code> _     _                            _______                           _
| |   | |                          (_______)          _              | |
| |__ | | ____ ____  ____  _   _    _____   ____  ___| |_  ____  ____| |
|  __)| |/ _  |  _ \|  _ \| | | |  |  ___) / _  |/___)  _)/ _  )/ ___)_|
| |   | ( ( | | | | | | | | |_| |  | |____( ( | |___ | |_( (/ /| |    _
|_|   |_|\_||_| ||_/| ||_/ \__  |  |_______)_||_(___/ \___)____)_|   |_|
              |_|   |_|   (____/
</code>```

Remember, this is code-golf, so the code with the smallest amount of bytes wins.
Good luck.

Body:
///, <s>282</s> 279 bytes

Improvement: I noticed that there are too many // in the replacement commands, so I decided to compress them also (to m), which saved me 3 bytes.

/m/\/\///l/ _mk/|amj/b_mi/\\\m/h/|cmg/ddmf/ccme/bbmd/aamc/ |mb/__ma/  /ldlgggdejgggal
hafggga(ej)ga_gdah
hbf e eaea_alde_a eajh_aeaeh
kb)hilak_ \\k_ \\|fcakj) ila|ij)a_)ila)i j)_|
hac ( (ffffc_hahe( (fjf_( (i ihd_
|_kc_|\\_||_h|_ih|_i \\bak|ej)_||_(ji \\j)e)_kc_|
gda|_kc_k (ei

Repeatly compress the most frequent substring.

Thirteenth generation, 282 bytes

/l/ _//k/|a//j/b_//i/\\\///h/|c//g/dd//f/cc//e/bb//d/aa//c/ |//b/__//a/  /ldlgggdejgggal
hafggga(ej)ga_gdah
hbf e eaea_alde_a eajh_aeaeh
kb)hilak_ \\k_ \\|fcakj) ila|ij)a_)ila)i j)_|
hac ( (ffffc_hahe( (fjf_( (i ihd_
|_kc_|\\_||_h|_ih|_i \\bak|ej)_||_(ji \\j)e)_kc_|
gda|_kc_k (ei

Try it online!

First generation, 486 bytes

No compression. Escaped the / and the \.

 _     _                            _______                           _
| |   | |                          (_______)          _              | |
| |__ | | ____ ____  ____  _   _    _____   ____  ___| |_  ____  ____| |
|  __)| |\/ _  |  _ \\|  _ \\| | | |  |  ___) \/ _  |\/___)  _)\/ _  )\/ ___)_|
| |   | ( ( | | | | | | | | |_| |  | |____( ( | |___ | |_( (\/ \/| |    _
|_|   |_|\\_||_| ||_\/| ||_\/ \\__  |  |_______)_||_(___\/ \\___)____)_|   |_|
              |_|   |_|   (____\/

<a href="http://slashes.tryitonline.net/#code=IF8gICAgIF8gICAgICAgICAgICAgICAgICAgICAgICAgICAgX19fX19fXyAgICAgICAgICAgICAgICAgICAgICAgICAgIF8gCnwgfCAgIHwgfCAgICAgICAgICAgICAgICAgICAgICAgICAgKF9fX19fX18pICAgICAgICAgIF8gICAgICAgICAgICAgIHwgfAp8IHxfXyB8IHwgX19fXyBfX19fICBfX19fICBfICAgXyAgICBfX19fXyAgIF9fX18gIF9fX3wgfF8gIF9fX18gIF9fX198IHwKfCAgX18pfCB8XC8gXyAgfCAgXyBcXHwgIF8gXFx8IHwgfCB8ICB8ICBfX18pIFwvIF8gIHxcL19fXykgIF8pXC8gXyAgKVwvIF9fXylffAp8IHwgICB8ICggKCB8IHwgfCB8IHwgfCB8IHwgfF98IHwgIHwgfF9fX18oICggfCB8X19fIHwgfF8oIChcLyBcL3wgfCAgICBfIAp8X3wgICB8X3xcXF98fF98IHx8X1wvfCB8fF9cLyBcXF9fICB8ICB8X19fX19fXylffHxfKF9fX1wvIFxcX19fKV9fX18pX3wgICB8X3wKICAgICAgICAgICAgICB8X3wgICB8X3wgICAoX19fX1wv&input=" rel="nofollow noreferrer">Try it online!

Second generation, 402 bytes

Compressed two spaces to a. The /a/  / means "replace all occurrences of a to two spaces".

/a/  / _aa _aaaaaaaaaaaaaa_______aaaaaaaaaaaaa _
| |a | |aaaaaaaaaaaaa(_______)aaaaa_aaaaaaa| |
| |__ | | ____ ____a____a_a _aa_____a ____a___| |_a____a____| |
|a__)| |\/ _a|a_ \\|a_ \\| | | |a|a___) \/ _a|\/___)a_)\/ _a)\/ ___)_|
| |a | ( ( | | | | | | | | |_| |a| |____( ( | |___ | |_( (\/ \/| |aa_
|_|a |_|\\_||_| ||_\/| ||_\/ \\__a|a|_______)_||_(___\/ \\___)____)_|a |_|
aaaaaaa|_|a |_|a (____\/

<a href="http://slashes.tryitonline.net/#code=L2EvICAvIF9hYSBfYWFhYWFhYWFhYWFhYWFfX19fX19fYWFhYWFhYWFhYWFhYSBfIAp8IHxhIHwgfGFhYWFhYWFhYWFhYWEoX19fX19fXylhYWFhYV9hYWFhYWFhfCB8CnwgfF9fIHwgfCBfX19fIF9fX19hX19fX2FfYSBfYWFfX19fX2EgX19fX2FfX198IHxfYV9fX19hX19fX3wgfAp8YV9fKXwgfFwvIF9hfGFfIFxcfGFfIFxcfCB8IHwgfGF8YV9fXykgXC8gX2F8XC9fX18pYV8pXC8gX2EpXC8gX19fKV98CnwgfGEgfCAoICggfCB8IHwgfCB8IHwgfCB8IHxffCB8YXwgfF9fX18oICggfCB8X19fIHwgfF8oIChcLyBcL3wgfGFhXyAKfF98YSB8X3xcXF98fF98IHx8X1wvfCB8fF9cLyBcXF9fYXxhfF9fX19fX18pX3x8XyhfX19cLyBcXF9fXylfX19fKV98YSB8X3wKYWFhYWFhYXxffGEgfF98YSAoX19fX1wv&input=" rel="nofollow noreferrer">Try it online!

Third generation, 369 bytes

Compressed __ to b. The /b/__/ at the beginning means "replace all occurrences of b to __".

/b/__//a/  / _aa _aaaaaaaaaaaaaabbb_aaaaaaaaaaaaa _
| |a | |aaaaaaaaaaaaa(bbb_)aaaaa_aaaaaaa| |
| |b | | bb bbabba_a _aabb_a bbab_| |_abbabb| |
|ab)| |\/ _a|a_ \\|a_ \\| | | |a|ab_) \/ _a|\/b_)a_)\/ _a)\/ b_)_|
| |a | ( ( | | | | | | | | |_| |a| |bb( ( | |b_ | |_( (\/ \/| |aa_
|_|a |_|\\_||_| ||_\/| ||_\/ \\ba|a|bbb_)_||_(b_\/ \\b_)bb)_|a |_|
aaaaaaa|_|a |_|a (bb\/

<a href="http://slashes.tryitonline.net/#code=L2IvX18vL2EvICAvIF9hYSBfYWFhYWFhYWFhYWFhYWFiYmJfYWFhYWFhYWFhYWFhYSBfIAp8IHxhIHwgfGFhYWFhYWFhYWFhYWEoYmJiXylhYWFhYV9hYWFhYWFhfCB8CnwgfGIgfCB8IGJiIGJiYWJiYV9hIF9hYWJiX2EgYmJhYl98IHxfYWJiYWJifCB8CnxhYil8IHxcLyBfYXxhXyBcXHxhXyBcXHwgfCB8IHxhfGFiXykgXC8gX2F8XC9iXylhXylcLyBfYSlcLyBiXylffAp8IHxhIHwgKCAoIHwgfCB8IHwgfCB8IHwgfCB8X3wgfGF8IHxiYiggKCB8IHxiXyB8IHxfKCAoXC8gXC98IHxhYV8gCnxffGEgfF98XFxffHxffCB8fF9cL3wgfHxfXC8gXFxiYXxhfGJiYl8pX3x8XyhiX1wvIFxcYl8pYmIpX3xhIHxffAphYWFhYWFhfF98YSB8X3xhIChiYlwv&input=" rel="nofollow noreferrer">Try it online!

Fourth generation, 339 bytes

Compressed  | to c. The /c/ |/ at the beginning means "replace all occurrences of c to  |".

/c/ |//b/__//a/  / _aa _aaaaaaaaaaaaaabbb_aaaaaaaaaaaaa _
|caccaaaaaaaaaaaaa(bbb_)aaaaa_aaaaaaa|c
|cbcc bb bbabba_a _aabb_a bbab_|c_abbabb|c
|ab)|c\/ _a|a_ \\|a_ \\|ccca|ab_) \/ _a|\/b_)a_)\/ _a)\/ b_)_|
|cac ( (ccccccccc_|ca|cbb( (ccb_cc_( (\/ \/|caa_
|_|ac_|\\_||_|c|_\/|c|_\/ \\ba|a|bbb_)_||_(b_\/ \\b_)bb)_|ac_|
aaaaaaa|_|ac_|a (bb\/

<a href="http://slashes.tryitonline.net/#code=L2MvIHwvL2IvX18vL2EvICAvIF9hYSBfYWFhYWFhYWFhYWFhYWFiYmJfYWFhYWFhYWFhYWFhYSBfIAp8Y2FjY2FhYWFhYWFhYWFhYWEoYmJiXylhYWFhYV9hYWFhYWFhfGMKfGNiY2MgYmIgYmJhYmJhX2EgX2FhYmJfYSBiYmFiX3xjX2FiYmFiYnxjCnxhYil8Y1wvIF9hfGFfIFxcfGFfIFxcfGNjY2F8YWJfKSBcLyBfYXxcL2JfKWFfKVwvIF9hKVwvIGJfKV98CnxjYWMgKCAoY2NjY2NjY2NjX3xjYXxjYmIoIChjY2JfY2NfKCAoXC8gXC98Y2FhXyAKfF98YWNffFxcX3x8X3xjfF9cL3xjfF9cLyBcXGJhfGF8YmJiXylffHxfKGJfXC8gXFxiXyliYilffGFjX3wKYWFhYWFhYXxffGFjX3xhIChiYlwv&input=" rel="nofollow noreferrer">Try it online!

The rest of the compression rules

So, the list of compression rules:

Compress two spaces to a.

Compress __ to b.

Compress  | to c.

Compress aa to d.

Compress bb to e.

Compress cc to f.

Compress dd to g.

Compress |c to h.

Compress \/ to i. Both the \ and the / in the rules are further escaped.

Compress b_ to j.

Compress |a to k.

Compress  _ to l.

Compress // to m.

As you can see, there are overlapping compression rules. For example, g encodes dd which encodes aaaa which encodes 8 spaces.


答:
Java 7, 167 bytes

It can probably be golfed more by using a different approach..

```<code>import java.util.*;Map c(String[]a){Map m=new HashMap();for(String s:a){String[]x=s.split("=");Object l;m.put(x[0],(l=m.get(x[0]))!=null?l+"%"+x[1]:x[1]);}return m;}
</code>```

NOTE: The method above creates and returns a HashMap with the desired key-value pairs. However, it doesn't print it in the exact output as in OP's question with | as output-delimiter between the keys and new values. Judging by MickeyT's SQL answer where he returned a database table I figured this is allowed; if not more bytes should be added for a print function.

Ungolfed & test code:

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

class Main{

    static Map c(String[] a){
        Map m = new HashMap();
        for(String s : a){
            String[] x = s.split("\\|");
            Object l;
            m.put(x[0], (l = m.get(x[0])) != null
                            ? l + "%" + x[1]
                            : x[1]);
        }
        return m;
    }

    public static void main(String[] a){
        Map m = c(new String[]{
            "why|[may express] surprise, reluctance, impatience, annoyance, indignation",
            "whom|[used in] questions, subordination",
            "whom|[possessive] whose",
            "whom|[subjective] who",
            "whoever|[objective] whomever",
            "whoever|[possessive] whosever",
            "who|[possessive] whose",
            "who|[objective] whom"
        });

        // Object instead of Map.EntrySet because the method returns a generic Map
        for (Object e : m.entrySet()){
            System.out.println(e.toString().replace("=", "|"));
        }
    }
}
</code>```

Output:

```<code>whoever|[objective] whomever%[possessive] whosever
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
why|[may express] surprise, reluctance, impatience, annoyance, indignation
who|[possessive] whose%[objective] whom
</code>```

Title: Oneliner to merge lines with same first field

Body:
This is my first codegolf question, so I apologize in advance if it's not appropriate, and I welcome any feedback.

I have a file with this format:

```<code>a | rest of first line
b | rest of second line
b | rest of third line
c | rest of fourth line
d | rest of fifth line
d | rest of sixth line
</code>```

The actual contents vary, as does the delimiter. The contents are just text. The delimiter only appears once per line. For this puzzle, feel free to change the delimiter, e.g. use "%" as the delimiter.

Desired output:

```<code>a | rest of first line
b | rest of second line % rest of third line
c | rest of fourth line
d | rest of fifth line % rest of sixth line
</code>```

I already have both ruby and awk scripts to merge this, but I suspect it's possible to have a short oneliner. i.e. a one-liner that can be used along with pipes and other commands on the command line. I can't figure it out, and my own script is to long to just compress on the command line.

Shortest characters preferred. Input is not necessarily sorted, but we are only interested in merging consecutive lines with matching first fields. There are unlimited lines with matching first fields. Field 1 could be anything, e.g. names of fruits, proper names, etc.

(I run on MacOS, so I am personally most interested in implementations that run on the mac).

Here is a second example/test. Notice "|" is the delimiter. The space before the "|" is irrelevant, and if resent should be considered part of the key. I am using "%" as a delimited in the output, but again, feel free to change the delimiter (but don't used square brackets).

Input:

```<code>why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination
whom|[possessive] whose
whom|[subjective] who
whoever|[objective] whomever
whoever|[possessive] whosever
who|[possessive] whose
who|[objective] whom
</code>```

Desired output:

```<code>why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
whoever|[objective] whomever%[possessive] whosever
who|[possessive] whose%[objective] whom
</code>```

Body:
Java 7, 167 bytes

It can probably be golfed more by using a different approach..

import java.util.*;Map c(String[]a){Map m=new HashMap();for(String s:a){String[]x=s.split("=");Object l;m.put(x[0],(l=m.get(x[0]))!=null?l+"%"+x[1]:x[1]);}return m;}

NOTE: The method above creates and returns a HashMap with the desired key-value pairs. However, it doesn't print it in the exact output as in OP's question with | as output-delimiter between the keys and new values. Judging by MickeyT's SQL answer where he returned a database table I figured this is allowed; if not more bytes should be added for a print function.

Ungolfed & test code:

import java.util.*;

class Main{

    static Map c(String[] a){
        Map m = new HashMap();
        for(String s : a){
            String[] x = s.split("\\|");
            Object l;
            m.put(x[0], (l = m.get(x[0])) != null
                            ? l + "%" + x[1]
                            : x[1]);
        }
        return m;
    }

    public static void main(String[] a){
        Map m = c(new String[]{
            "why|[may express] surprise, reluctance, impatience, annoyance, indignation",
            "whom|[used in] questions, subordination",
            "whom|[possessive] whose",
            "whom|[subjective] who",
            "whoever|[objective] whomever",
            "whoever|[possessive] whosever",
            "who|[possessive] whose",
            "who|[objective] whom"
        });

        // Object instead of Map.EntrySet because the method returns a generic Map
        for (Object e : m.entrySet()){
            System.out.println(e.toString().replace("=", "|"));
        }
    }
}

Output:

whoever|[objective] whomever%[possessive] whosever
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
why|[may express] surprise, reluctance, impatience, annoyance, indignation
who|[possessive] whose%[objective] whom


问:
24 and 12 Hour Times
Write a program or function with no input that prints or returns this string of 24-hour and 12-hour times:

```<code>00:00 12:00am
01:00  1:00am
02:00  2:00am
03:00  3:00am
04:00  4:00am
05:00  5:00am
06:00  6:00am
07:00  7:00am
08:00  8:00am
09:00  9:00am
10:00 10:00am
11:00 11:00am
12:00 12:00pm
13:00  1:00pm
14:00  2:00pm
15:00  3:00pm
16:00  4:00pm
17:00  5:00pm
18:00  6:00pm
19:00  7:00pm
20:00  8:00pm
21:00  9:00pm
22:00 10:00pm
23:00 11:00pm
</code>```

The string must be output exactly as it appears here. The only exception is that it may optionally have a single trailing newline.

So the MD5 hash of your output should be

```<code>827ae6e2dbb1df494930baedb3ee2653
</code>```

if you do not have a trailing newline and

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

if you do. (Your hash could be different if your system uses another type of newline but that's OK.)

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

Title: 24 and 12 Hour Times

Body:
JavaScript (ES6), <s>119</s> 116 bytes

_=>Array(24).fill().map((_,i)=>`${`0${i}`.slice(-2)}:00 ${` ${(i+11)%12+1}`.slice(-2)}:00${'ap'[+(i>11)]}m`).join`
`


答:
PowerShell, 85 bytes

Strings are merged using hashtable:

%{$h=@{}}{$k,$v=$_-split'\|';$h.$k=($h.$k,$v|?{$_})-join'%'}{$h.Keys|%{$_+'|'+$h.$_}}
```

<h3>Example</h3>

<p>Since PowerShell doesn't support stdin redirection via <code><</code>, I'm assuming that <code>Get-Content .\Filename.txt |</code> will be used as default I/O method.</p>

```Get-Content .\Filename.txt | %{$h=@{}}{$k,$v=$_-split'\|';$h.$k=($h.$k,$v|?{$_})-join'%'}{$h.Keys|%{$_+'|'+$h.$_}}
```

<h3>Output</h3>

```whoever|[objective] whomever%[possessive] whosever
why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
who|[possessive] whose%[objective] whom
```

Body:
PowerShell, 85 bytes

Strings are merged using hashtable:

%{$h=@{}}{$k,$v=$_-split'\|';$h.$k=($h.$k,$v|?{$_})-join'%'}{$h.Keys|%{$_+'|'+$h.$_}}

Example

Since PowerShell doesn't support stdin redirection via <, I'm assuming that Get-Content .\Filename.txt | will be used as default I/O method.

Get-Content .\Filename.txt | %{$h=@{}}{$k,$v=$_-split'\|';$h.$k=($h.$k,$v|?{$_})-join'%'}{$h.Keys|%{$_+'|'+$h.$_}}

Output

whoever|[objective] whomever%[possessive] whosever
why|[may express] surprise, reluctance, impatience, annoyance, indignation
whom|[used in] questions, subordination%[possessive] whose%[subjective] who
who|[possessive] whose%[objective] whom


答:
Racket (Scheme), 44 bytes

Euclid implementation in Racket (Scheme)

```<code>(define(g a b)(if(= 0 b)a(g b(modulo a b))))
</code>```

Edit: Didn't see @Numeri 's solution lol. Somehow we got the exact same code independently

Title: Greatest Common Divisor

Body:
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

```<code>0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101
</code>```

Body:
Racket (Scheme), 44 bytes

Euclid implementation in Racket (Scheme)

(define(g a b)(if(= 0 b)a(g b(modulo a b))))

Edit: Didn't see @Numeri 's solution lol. Somehow we got the exact same code independently


问:
Find the smallest number bigger than the input whose digital sum is the input
"Digital sum" refers to the sum of all the digits in a number.

For example, the digital sum of 1324 is 10, because 1+3+2+4 = 10.

The challenge is to write a program/function to calculate the smallest number bigger than the input whose digital sum is the input.

Example with walkthrough

As an example, take the number 9 as the input:

```<code>9 = 1+8 -> 18
9 = 2+7 -> 27
9 = 3+6 -> 36
...
9 = 8+1 -> 81
9 = 9+0 -> 90
</code>```

The valid output would be the smallest number above, which is 18.

Specs

Note that 9 is not the valid output for this example, because the reversed number must be greater than the original number.

Note that the input will be positive.

Test-Cases:

```<code> 2 => 11      (2 = 1 + 1)
 8 => 17      (8 = 1 + 7)
12 => 39     (12 = 3 + 9)
16 => 79     (16 = 7 + 9)
18 => 99     (18 = 9 + 9)
24 => 699    (24 = 6 + 9 + 9)
32 => 5999   (32 = 5 + 9 + 9 + 9)
</code>```

References:

This is OEIS A161561.

Edit: Added an additional Testcase (18)

Thanks to Martin Ender for the Leaderboard Snippet

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
TSQL(sqlserver 2012), <s>107</s> 99 bytes

```<code>DECLARE @ INT = 32

,@2 char(99)WHILE @>0SELECT
@2=concat(x,@2),@-=x FROM(SELECT IIF(@>9,9,IIF(@2>0,@,@-1))x)y PRINT @2
</code>```

Try it online!

Body:
TSQL(sqlserver 2012), <s>107</s> 99 bytes

DECLARE @ INT = 32

,@2 char(99)WHILE @>0SELECT
@2=concat(x,@2),@-=x FROM(SELECT IIF(@>9,9,IIF(@2>0,@,@-1))x)y PRINT @2

Try it online!


问:
Alternating Sign Sequence

Introduction

The sign of a number is either a +, or a - for every non-zero integer. Zero itself is signless (+0 is the same as -0). In the following sequence, we are going to alternate between the positive sign, the zero and the negative sign. The sequence starts with 1, so we write 1 with a positive sign, with zero (this one is weird, but we just multiply the number by 0) and the negative sign:

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

The next number is 2, and we do the same thing again:

```<code>2, 0, -2
</code>```

The sequence eventually is:

```<code>1, 0, -1, 2, 0, -2, 3, 0, -3, 4, 0, -4, 5, 0, -5, 6, 0, -6, 7, 0, -7, ...
</code>```

Or a more readable form:

```<code>a(0) = 1
a(1) = 0
a(2) = -1
a(3) = 2
a(4) = 0
a(5) = -2
a(6) = 3
a(7) = 0
a(8) = -3
a(9) = 4
...
</code>```

The Task

Given a non-negative integer n, output the nth term of the above sequence. You can choose if you use the zero-indexed or one-indexed version.

Test cases:

Zero-indexed:

```<code>a(0) = 1
a(11) = -4
a(76) = 0
a(134) = -45
a(296) = -99
</code>```

Or if you prefer one-indexed:

```<code>a(1) = 1
a(12) = -4
a(77) = 0
a(135) = -45
a(297) = -99
</code>```

This is code-golf, so the submission with the smallest number of bytes wins!

答:
Erlang, 40 bytes

```<code>F=fun(N)->trunc((N/3+1)*(1-N rem 3))end.
</code>```

Sadly Erlang has no '%' modulo operator and 'rem' requires the spaces, even before the 3.

Title: Alternating Sign Sequence

Body:
Erlang, 40 bytes

F=fun(N)->trunc((N/3+1)*(1-N rem 3))end.

Sadly Erlang has no '%' modulo operator and 'rem' requires the spaces, even before the 3.


答:
05AB1E, <s>51</s> <s>50</s> <s>48</s> <s>44</s> 42 bytes

Saved two bytes thanks to carusocomputing

Code:

```<code>24FNgi0}N…:00©ðN12(%12+Dgiðs}®„paN12‹è'mJ,
</code>```

Try it online!

Explanation

```<code>24F                                         # for N in [0...23]
   Ngi0}                                    # if len(N)=1, push 0
        N                                   # push N
         …:00©                              # push ":00" and store a copy in register
             ð                              # push " "
              N12(%12+D                     # push 2 copies of N%(-12)+12
                       giðs}                # if the length of that number is 1,
                                            # push " " and swap with the number
                            ®               # push ":00" again
                             „pa            # push "pa"
                                N12‹è       # index into that with N<12
                                     'm     # push "m"
                                       J,   # join everything and print with newline
</code>```

Title: 24 and 12 Hour Times

Body:
Write a program or function with no input that prints or returns this string of 24-hour and 12-hour times:

```<code>00:00 12:00am
01:00  1:00am
02:00  2:00am
03:00  3:00am
04:00  4:00am
05:00  5:00am
06:00  6:00am
07:00  7:00am
08:00  8:00am
09:00  9:00am
10:00 10:00am
11:00 11:00am
12:00 12:00pm
13:00  1:00pm
14:00  2:00pm
15:00  3:00pm
16:00  4:00pm
17:00  5:00pm
18:00  6:00pm
19:00  7:00pm
20:00  8:00pm
21:00  9:00pm
22:00 10:00pm
23:00 11:00pm
</code>```

The string must be output exactly as it appears here. The only exception is that it may optionally have a single trailing newline.

So the MD5 hash of your output should be

```<code>827ae6e2dbb1df494930baedb3ee2653
</code>```

if you do not have a trailing newline and

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

if you do. (Your hash could be different if your system uses another type of newline but that's OK.)

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

Body:
05AB1E, <s>51</s> <s>50</s> <s>48</s> <s>44</s> 42 bytes

Saved two bytes thanks to carusocomputing

Code:

24FNgi0}N…:00©ðN12(%12+Dgiðs}®„paN12‹è'mJ,

Try it online!

Explanation

24F                                         # for N in [0...23]
   Ngi0}                                    # if len(N)=1, push 0
        N                                   # push N
         …:00©                              # push ":00" and store a copy in register
             ð                              # push " "
              N12(%12+D                     # push 2 copies of N%(-12)+12
                       giðs}                # if the length of that number is 1,
                                            # push " " and swap with the number
                            ®               # push ":00" again
                             „pa            # push "pa"
                                N12‹è       # index into that with N<12
                                     'm     # push "m"
                                       J,   # join everything and print with newline


答:
Java 7, <s>68</s> 61 bytes

```<code>int f(int n){return n>9?-~(n%9)*(int)Math.pow(10,n/9)-1:n+9;}
</code>```

Does roughly the same thing as many of the other answers here. Wanted to show the Java approach without using string manipulation and loops.

Thanks to FryAmTheEggman for reminding me that I'm dumb ;)

Title: Find the smallest number bigger than the input whose digital sum is the input

Body:
"Digital sum" refers to the sum of all the digits in a number.

For example, the digital sum of 1324 is 10, because 1+3+2+4 = 10.

The challenge is to write a program/function to calculate the smallest number bigger than the input whose digital sum is the input.

Example with walkthrough

As an example, take the number 9 as the input:

```<code>9 = 1+8 -> 18
9 = 2+7 -> 27
9 = 3+6 -> 36
...
9 = 8+1 -> 81
9 = 9+0 -> 90
</code>```

The valid output would be the smallest number above, which is 18.

Specs

Note that 9 is not the valid output for this example, because the reversed number must be greater than the original number.

Note that the input will be positive.

Test-Cases:

```<code> 2 => 11      (2 = 1 + 1)
 8 => 17      (8 = 1 + 7)
12 => 39     (12 = 3 + 9)
16 => 79     (16 = 7 + 9)
18 => 99     (18 = 9 + 9)
24 => 699    (24 = 6 + 9 + 9)
32 => 5999   (32 = 5 + 9 + 9 + 9)
</code>```

References:

This is OEIS A161561.

Edit: Added an additional Testcase (18)

Thanks to Martin Ender for the Leaderboard Snippet

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Java 7, <s>68</s> 61 bytes

int f(int n){return n>9?-~(n%9)*(int)Math.pow(10,n/9)-1:n+9;}

Does roughly the same thing as many of the other answers here. Wanted to show the Java approach without using string manipulation and loops.

Thanks to FryAmTheEggman for reminding me that I'm dumb ;)


答:
JavaScript, <s>97</s> 95 bytes

This is based off of starcorder’s answer. Thanks to George Reith for a 2 byte improvement.

```<code>for(i=0,k=12;i<24;k=i++%12+1)console.log('%s:00 %s:00%sm',i>9?i:'0'+i,k>9?k:' '+k,i>11?'p':'a')
</code>```

Ungolfed:

```<code>for (i=0, k=12; i < 24; k = (i++) % 12 + 1)
    console.log('%s:00 %s:00%sm',
        i > 9 ? i : '0' + i,
        k > 9 ? k : ' ' + k,
        i > 11 ? 'p' : 'a')
</code>```

Title: 24 and 12 Hour Times

Body:
JavaScript, <s>97</s> 95 bytes

This is based off of starcorder’s answer. Thanks to George Reith for a 2 byte improvement.

for(i=0,k=12;i<24;k=i++%12+1)console.log('%s:00 %s:00%sm',i>9?i:'0'+i,k>9?k:' '+k,i>11?'p':'a')

Ungolfed:

for (i=0, k=12; i < 24; k = (i++) % 12 + 1)
    console.log('%s:00 %s:00%sm',
        i > 9 ? i : '0' + i,
        k > 9 ? k : ' ' + k,
        i > 11 ? 'p' : 'a')


答:
Java, 93 bytes

void t(){for(int i=0;i<24;)System.out.printf("'%02d:00',\n'%02d:30'%s",i,i,i++<23?",\n":"");}
```

<p><strong>Ungolfed</strong></p>

<pre class="lang-Java prettyprint-override"><code>void t()
{
    for(int i = 0; i < 24; i++)
    {
        System.out.printf("'%02d:00',\n", i);
        System.out.printf(   "'%02d:30'", i);
        System.out.printf( i < 23 ?",\n":"");
    }
}
</code>```

Title: List all times in the day at a half hour rate

Body:
Shortest answer wins.

It must be sorted, and in 24hr time. The final line does not have a comma.

Output should be as follows:

```<code>'00:00',
'00:30',
'01:00',
'01:30',
'02:00',
'02:30',
'03:00',
'03:30',
'04:00',
'04:30',
'05:00',
'05:30',
'06:00',
'06:30',
'07:00',
'07:30',
'08:00',
'08:30',
'09:00',
'09:30',
'10:00',
'10:30',
'11:00',
'11:30',
'12:00',
'12:30',
'13:00',
'13:30',
'14:00',
'14:30',
'15:00',
'15:30',
'16:00',
'16:30',
'17:00',
'17:30',
'18:00',
'18:30',
'19:00',
'19:30',
'20:00',
'20:30',
'21:00',
'21:30',
'22:00',
'22:30',
'23:00',
'23:30'
</code>```

Body:
Java, 93 bytes

void t(){for(int i=0;i<24;)System.out.printf("'%02d:00',\n'%02d:30'%s",i,i,i++<23?",\n":"");}

Ungolfed

void t()
{
    for(int i = 0; i < 24; i++)
    {
        System.out.printf("'%02d:00',\n", i);
        System.out.printf(   "'%02d:30'", i);
        System.out.printf( i < 23 ?",\n":"");
    }
}


答:
C, 80 bytes

i;s;g(j){s=0;for(;j;j/=10)s+=j%10;return s;}f(n){i=n;while(n-g(i))i++;return i;}
```

<p>Ungolfed try online</p>

<pre class="lang-C prettyprint-override"><code>int g(int j)
{
    int s=0;
    for(;j;j/=10) s += j%10;
    return s;
}

int f(int n)
{
    int i=n;
    for(;n-g(i);i++);
    return i;
}
</code>```

Body:
C, 80 bytes

i;s;g(j){s=0;for(;j;j/=10)s+=j%10;return s;}f(n){i=n;while(n-g(i))i++;return i;}

Ungolfed try online

int g(int j)
{
    int s=0;
    for(;j;j/=10) s += j%10;
    return s;
}

int f(int n)
{
    int i=n;
    for(;n-g(i);i++);
    return i;
}


答:
Lua, 52 bytes

```<code>n=...+0
print(n>9 and(n%9)..string.rep(9,n/9)or n+9)
</code>```

Meant to be saved in a file and run with the Lua interpreter, e.g. lua <file> <input number>

You can also try it here: https://repl.it/CXom/1

(On repl.it the input number is hard-coded for ease of testing)

Body:
Lua, 52 bytes

n=...+0
print(n>9 and(n%9)..string.rep(9,n/9)or n+9)

Meant to be saved in a file and run with the Lua interpreter, e.g. lua <file> <input number>

You can also try it here: https://repl.it/CXom/1

(On repl.it the input number is hard-coded for ease of testing)


答:
Sclipting, 76 bytes

The program assumes that the input is empty (or '0' or anything that converts to the integer 0).

The byte count assumes UTF-16 encoding.

```군上❶겠小꼀虛嗎❷꾣갰글❷결加곀剩增❶겠小글虛嗎댆밁⓷꾣갰⓷⓼곀小掘닐밊終```

Ungolfed:

```<code>군 // 23
上 // for loop (goes from 0 to 23 if input is 0)
    ❶겠小꼀虛嗎 // n < 10 ? "0" : ""
    ❷          // n
    꾣갰글      // ":00 "
    ❷결加곀剩增 // k = (n+11) % 12 + 1
    ❶겠小글虛嗎 // k < 10 ? " " : ""
    댆밁       // "pa"
    ⓷         // Pull n to top of stack
    꾣갰       // ":00"
    ⓷         // Pull "pa" to top of stack
    ⓼         // Pull k to top of stack
    곀小掘     // "pa"[k < 10 ? 1 : 0]
    닐밊       // "m\n"
終 // end of for loop
</code>```

Each iteration of the loop leaves lots of small strings on the stack; at the end they are all automatically concatenated.

Title: 24 and 12 Hour Times

Body:
Sclipting, 76 bytes

The program assumes that the input is empty (or '0' or anything that converts to the integer 0).

The byte count assumes UTF-16 encoding.

군上❶겠小꼀虛嗎❷꾣갰글❷결加곀剩增❶겠小글虛嗎댆밁⓷꾣갰⓷⓼곀小掘닐밊終

Ungolfed:

군 // 23
上 // for loop (goes from 0 to 23 if input is 0)
    ❶겠小꼀虛嗎 // n < 10 ? "0" : ""
    ❷          // n
    꾣갰글      // ":00 "
    ❷결加곀剩增 // k = (n+11) % 12 + 1
    ❶겠小글虛嗎 // k < 10 ? " " : ""
    댆밁       // "pa"
    ⓷         // Pull n to top of stack
    꾣갰       // ":00"
    ⓷         // Pull "pa" to top of stack
    ⓼         // Pull k to top of stack
    곀小掘     // "pa"[k < 10 ? 1 : 0]
    닐밊       // "m\n"
終 // end of for loop

Each iteration of the loop leaves lots of small strings on the stack; at the end they are all automatically concatenated.


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

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

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

Trailing newline can be either \nor \r\n

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

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

Example

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

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Linux ELF/x86, 146 bytes

```<code>00000000  7f 45 4c 46 01 00 00 00  5a 0e 00 00 5a 5e eb 10  |.ELF....Z...Z^..|
00000010  02 00 03 00 0c 50 eb 10  0c 50 eb 10 04 00 00 00  |.....P...P......|
00000020  5e 53 43 53 52 89 e1 b0  66 3d 20 00 01 00 cd 80  |^SCSR...f= .....|
00000030  97 55 6b ed 0a 01 c5 ac  2c 30 79 f6 43 0f cd 01  |.Uk.....,0y.C...|
00000040  dd 55 89 e1 6a 10 51 6a  10 51 57 89 e1 b0 66 cd  |.U..j.Qj.QW...f.|
00000050  80 43 43 b0 66 cd 80 01  64 24 08 89 e1 43 b0 66  |.CC.f...d$...C.f|
00000060  cd 80 89 c1 93 8d 74 24  1b 99 fd ac 01 c2 e2 fb  |......t$........|
00000070  89 f7 b0 0a aa 91 92 f6  f1 86 c4 04 30 aa 42 c1  |............0.B.|
00000080  e8 08 75 f3 42 89 f9 41  b0 04 cd 80 b0 06 cd 80  |..u.B..A........|
00000090  eb c9                                             |..|
00000092
</code>```

Includes a 52-byte ELF header, a 32-byte program header, 111 bytes of program code + 3 bytes of code for skipping around inside the headers.

Information on how to create tiny ELF executables can be found at breadbox's "A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux".

Linux/i386 uses the socketcall(2) multiplex system call, which takes in ebx the specific socket call (the SYS_* macros from /usr/include/linux/net.h), and in ecx a pointer to the argument area of the original library call.

Some things done to keep the executable small:

It assumes registers are zeroed on entry, which Linux does, but is not required by the ELF standard (the only requirement is that on entry EDX points to a finalization funtion (useful for executables loaded by the dynamic linker) or is NULL).

It assumes on launch (typically by a shell) the only open file descriptors are 0, 1, and 2. Which means that the listening socket will be fd 3, and the accepted socket will be fd 4.

It assumes there are exactly 2 arguments (including argv[0]).

The same stack space is reused for the calls to bind(2), listen(2) and accept(2).

To skip over the phentsize and phnum fields, a byte is prepended, turning into a CMP operation which takes the phentsize and phnum fields as an immediate (trick shamelessly stolen from breadbox's solution to 123 in anarchy golf).

x86 string operations LODS (load into accumulator and increment/decrement source index) and STOS (store from accumulator and increment/decrement destination index) are nice for short code.

XCHG EAX, reg is 1-byte, compared to MOV EAX, reg, which takes 2 bytes.

CDQ/CLTD (sign-extend EAX into EDX:EAX) can be used as a 1-byte way to zero the EDX register.

BSWAP is useful for implementing htons().

Nasm source:

```<code>BITS 32                                         ;
                                                ;   ELF HEADER    --   PROGRAM HEADER
; ELF HEADER                                    ; +-------------+
DB 0x7f,'E','L','F'                             ; | magic       |    +--------------------+
                                                ; |             |    |                    |
; PROGRAM HEADERS                               ; |             |    |                    |
DD 1                                            ; |*class   32b | -- | type: PT_LOAD      |
                                                ; |*data   none |    |                    |
                                                ; |*version   0 |    |                    |
                                                ; |*ABI    SysV |    |                    |
DD 0xe5a        ; offset = vaddr & (PAGE_SIZE-1); |*ABI vers    | -- | offset             |
                                                ; |             |    |                    |
entry:  pop     edx     ; edx = 2 (argc)        ; |*PADx7       | -- | vaddr = 0x10eb5e5a |
        pop     esi     ; discard argv[0]       ; |             |    |                    |
        jmp     short skip                      ; |             |    |                    |
DW 2                                            ; | ET_EXEC     | -- |*paddr LO           |
DW 3                                            ; | EM_386      | -- |*paddr HI           |
DD 0x10eb500c                                   ; |*version     | -- | filesz             |
DD 0x10eb500c                                   ; | entry point | -- | memsz              |
DD 4                                            ; | ph offset   | -- | flags: RX          |
                                                ; |             |    |                    |
skip:   pop     esi     ; esi = argv[1]         ; |*sh offset   | -- |*align              |
socket: push    ebx     ; default protocol (0)  ; |             |    |                    |
        inc     ebx                             ; |             |    |                    |
        push    ebx     ; SOCK_STREAM (1)       ; |             |    |                    |
        push    edx     ; AF_INET (2)           ; |*flags       |    +--------------------+
        mov     ecx, esp                        ; |             |
        mov     al, 0x66                        ; |*ehsize      |
DB 0x3d         ; cmp eax,0x10020               ; |             |
DW 32                                           ; | phentsize   |
DW 1                                            ; | phnum       |
                                                ; |             |
        int     0x80    ; socket(2, 1, 0)       ; |*shentsize   |
        xchg    edi, eax; edi = sockfd, eax = 0 ; |*shnum       |
        push    ebp     ; INADDR_ANY            ; |             |
                                                ; |             |
mult:   imul    ebp, 10 ; \_                    ; |*shstrndx    |
        add     ebp, eax; >                     ; |             |
        lodsb           ; >                     ; +-------------+
        sub     al,'0'  ; >
        jns     mult    ; / ebp = atoi(argv[1])                 ;       bind stack frame
                                                                ;    +-----------------------+
endmul: inc     ebx             ; SYS_BIND (2)                  ;    |        INADDR_ANY     |
                                                                ; +->| AF_INET | htons(port) |
        bswap   ebp                                             ; |  +-----------------------+
        add     ebp, ebx        ; AF_INET (2), htons(port)      ; |  |           16          |
        push    ebp                                             ; |  +-----------------------+
                                                                ; |  |         dummy         |
        mov     ecx, esp                                        ; |  +-----------------------+
        push    16              ; addrlen                       ; |  |           16          |
        push    ecx             ; dummy value                   ; |  +-----------------------+
        push    16              ; addrlen                       ; +--|          addr         |
        push    ecx             ; addr                          ;    +-----------------------+
        push    edi             ; sock                          ;    |         sockfd        |
        mov     ecx, esp                                        ;    +-----------------------+
        mov     al, 0x66
        int     0x80            ; bind(sockfd, addr, addrlen)
                                                                ;       accept stack frame
                                                                ;    +-----------------------+
listen: ;mov    byte [esp+8],1                                  ;    |        INADDR_ANY     |
        inc     ebx                                             ; +->| AF_INET | htons(port) |
        inc     ebx             ; SYS_LISTEN (4)                ; |  +-----------------------+
        mov     al, 0x66                                        ; |+>|           16          |
        int     0x80            ; listen(sockfd, backlog)       ; || +-----------------------+
                                                                ; || |         dummy         |
        add     [esp+8], esp                                    ; || +-----------------------+
accept: mov     ecx, esp                                        ; |+-|        &addrlen       |
        inc     ebx             ; SYS_ACCEPT (5)                ; |  +-----------------------+
        mov     al, 0x66                                        ; +--|          addr         |
        int     0x80            ; accept(sockfd, addr, &addrlen);    +-----------------------+
                                                                ;    |         sockfd        |
        mov     ecx, eax        ; ecx = 4                       ;    +-----------------------+
        xchg    ebx, eax        ; ebx = acceptfd, eax = 000000xx

        lea     esi, [esp+27]   ; point to the IP part of struct sockaddr_in
        cdq

        std                     ; reverse direction for string operations
addip:  lodsb                   ; \_
        add     edx, eax        ; > edx = sum of 4 IP bytes
        loop    addip           ; /

        mov     edi, esi        ; reuse struct sockaddr_in as scratch buffer
        mov     al, 10          ; '\n'
        stosb
        xchg    ecx, eax        ; ecx = 10
        xchg    eax, edx        ; edx = 0, eax = sum

divide: div     cl              ; \_
        xchg    al, ah          ; >
        add     al,0x30         ; >
        stosb                   ; > sprintf(scratch, "%d", sum)
        inc     edx             ; >
        shr     eax, 8          ; >
        jnz     divide          ; /

write:  inc     edx             ; ndigits + 1 ('\n')
        mov     ecx, edi
        inc     ecx
        mov     al,4
        int     0x80            ; write(acceptfd, scratch, scratchlen)
close:  mov     al, 6
        int     0x80            ; close(acceptfd)
        jmp     accept
</code>```

Title: A simple TCP server

Body:
Linux ELF/x86, 146 bytes

00000000  7f 45 4c 46 01 00 00 00  5a 0e 00 00 5a 5e eb 10  |.ELF....Z...Z^..|
00000010  02 00 03 00 0c 50 eb 10  0c 50 eb 10 04 00 00 00  |.....P...P......|
00000020  5e 53 43 53 52 89 e1 b0  66 3d 20 00 01 00 cd 80  |^SCSR...f= .....|
00000030  97 55 6b ed 0a 01 c5 ac  2c 30 79 f6 43 0f cd 01  |.Uk.....,0y.C...|
00000040  dd 55 89 e1 6a 10 51 6a  10 51 57 89 e1 b0 66 cd  |.U..j.Qj.QW...f.|
00000050  80 43 43 b0 66 cd 80 01  64 24 08 89 e1 43 b0 66  |.CC.f...d$...C.f|
00000060  cd 80 89 c1 93 8d 74 24  1b 99 fd ac 01 c2 e2 fb  |......t$........|
00000070  89 f7 b0 0a aa 91 92 f6  f1 86 c4 04 30 aa 42 c1  |............0.B.|
00000080  e8 08 75 f3 42 89 f9 41  b0 04 cd 80 b0 06 cd 80  |..u.B..A........|
00000090  eb c9                                             |..|
00000092

Includes a 52-byte ELF header, a 32-byte program header, 111 bytes of program code + 3 bytes of code for skipping around inside the headers.

Information on how to create tiny ELF executables can be found at breadbox's "A Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux".

Linux/i386 uses the socketcall(2) multiplex system call, which takes in ebx the specific socket call (the SYS_* macros from /usr/include/linux/net.h), and in ecx a pointer to the argument area of the original library call.

Some things done to keep the executable small:

It assumes registers are zeroed on entry, which Linux does, but is not required by the ELF standard (the only requirement is that on entry EDX points to a finalization funtion (useful for executables loaded by the dynamic linker) or is NULL).

It assumes on launch (typically by a shell) the only open file descriptors are 0, 1, and 2. Which means that the listening socket will be fd 3, and the accepted socket will be fd 4.

It assumes there are exactly 2 arguments (including argv[0]).

The same stack space is reused for the calls to bind(2), listen(2) and accept(2).

To skip over the phentsize and phnum fields, a byte is prepended, turning into a CMP operation which takes the phentsize and phnum fields as an immediate (trick shamelessly stolen from breadbox's solution to 123 in anarchy golf).

x86 string operations LODS (load into accumulator and increment/decrement source index) and STOS (store from accumulator and increment/decrement destination index) are nice for short code.

XCHG EAX, reg is 1-byte, compared to MOV EAX, reg, which takes 2 bytes.

CDQ/CLTD (sign-extend EAX into EDX:EAX) can be used as a 1-byte way to zero the EDX register.

BSWAP is useful for implementing htons().

Nasm source:

BITS 32                                         ;
                                                ;   ELF HEADER    --   PROGRAM HEADER
; ELF HEADER                                    ; +-------------+
DB 0x7f,'E','L','F'                             ; | magic       |    +--------------------+
                                                ; |             |    |                    |
; PROGRAM HEADERS                               ; |             |    |                    |
DD 1                                            ; |*class   32b | -- | type: PT_LOAD      |
                                                ; |*data   none |    |                    |
                                                ; |*version   0 |    |                    |
                                                ; |*ABI    SysV |    |                    |
DD 0xe5a        ; offset = vaddr & (PAGE_SIZE-1); |*ABI vers    | -- | offset             |
                                                ; |             |    |                    |
entry:  pop     edx     ; edx = 2 (argc)        ; |*PADx7       | -- | vaddr = 0x10eb5e5a |
        pop     esi     ; discard argv[0]       ; |             |    |                    |
        jmp     short skip                      ; |             |    |                    |
DW 2                                            ; | ET_EXEC     | -- |*paddr LO           |
DW 3                                            ; | EM_386      | -- |*paddr HI           |
DD 0x10eb500c                                   ; |*version     | -- | filesz             |
DD 0x10eb500c                                   ; | entry point | -- | memsz              |
DD 4                                            ; | ph offset   | -- | flags: RX          |
                                                ; |             |    |                    |
skip:   pop     esi     ; esi = argv[1]         ; |*sh offset   | -- |*align              |
socket: push    ebx     ; default protocol (0)  ; |             |    |                    |
        inc     ebx                             ; |             |    |                    |
        push    ebx     ; SOCK_STREAM (1)       ; |             |    |                    |
        push    edx     ; AF_INET (2)           ; |*flags       |    +--------------------+
        mov     ecx, esp                        ; |             |
        mov     al, 0x66                        ; |*ehsize      |
DB 0x3d         ; cmp eax,0x10020               ; |             |
DW 32                                           ; | phentsize   |
DW 1                                            ; | phnum       |
                                                ; |             |
        int     0x80    ; socket(2, 1, 0)       ; |*shentsize   |
        xchg    edi, eax; edi = sockfd, eax = 0 ; |*shnum       |
        push    ebp     ; INADDR_ANY            ; |             |
                                                ; |             |
mult:   imul    ebp, 10 ; \_                    ; |*shstrndx    |
        add     ebp, eax; >                     ; |             |
        lodsb           ; >                     ; +-------------+
        sub     al,'0'  ; >
        jns     mult    ; / ebp = atoi(argv[1])                 ;       bind stack frame
                                                                ;    +-----------------------+
endmul: inc     ebx             ; SYS_BIND (2)                  ;    |        INADDR_ANY     |
                                                                ; +->| AF_INET | htons(port) |
        bswap   ebp                                             ; |  +-----------------------+
        add     ebp, ebx        ; AF_INET (2), htons(port)      ; |  |           16          |
        push    ebp                                             ; |  +-----------------------+
                                                                ; |  |         dummy         |
        mov     ecx, esp                                        ; |  +-----------------------+
        push    16              ; addrlen                       ; |  |           16          |
        push    ecx             ; dummy value                   ; |  +-----------------------+
        push    16              ; addrlen                       ; +--|          addr         |
        push    ecx             ; addr                          ;    +-----------------------+
        push    edi             ; sock                          ;    |         sockfd        |
        mov     ecx, esp                                        ;    +-----------------------+
        mov     al, 0x66
        int     0x80            ; bind(sockfd, addr, addrlen)
                                                                ;       accept stack frame
                                                                ;    +-----------------------+
listen: ;mov    byte [esp+8],1                                  ;    |        INADDR_ANY     |
        inc     ebx                                             ; +->| AF_INET | htons(port) |
        inc     ebx             ; SYS_LISTEN (4)                ; |  +-----------------------+
        mov     al, 0x66                                        ; |+>|           16          |
        int     0x80            ; listen(sockfd, backlog)       ; || +-----------------------+
                                                                ; || |         dummy         |
        add     [esp+8], esp                                    ; || +-----------------------+
accept: mov     ecx, esp                                        ; |+-|        &addrlen       |
        inc     ebx             ; SYS_ACCEPT (5)                ; |  +-----------------------+
        mov     al, 0x66                                        ; +--|          addr         |
        int     0x80            ; accept(sockfd, addr, &addrlen);    +-----------------------+
                                                                ;    |         sockfd        |
        mov     ecx, eax        ; ecx = 4                       ;    +-----------------------+
        xchg    ebx, eax        ; ebx = acceptfd, eax = 000000xx

        lea     esi, [esp+27]   ; point to the IP part of struct sockaddr_in
        cdq

        std                     ; reverse direction for string operations
addip:  lodsb                   ; \_
        add     edx, eax        ; > edx = sum of 4 IP bytes
        loop    addip           ; /

        mov     edi, esi        ; reuse struct sockaddr_in as scratch buffer
        mov     al, 10          ; '\n'
        stosb
        xchg    ecx, eax        ; ecx = 10
        xchg    eax, edx        ; edx = 0, eax = sum

divide: div     cl              ; \_
        xchg    al, ah          ; >
        add     al,0x30         ; >
        stosb                   ; > sprintf(scratch, "%d", sum)
        inc     edx             ; >
        shr     eax, 8          ; >
        jnz     divide          ; /

write:  inc     edx             ; ndigits + 1 ('\n')
        mov     ecx, edi
        inc     ecx
        mov     al,4
        int     0x80            ; write(acceptfd, scratch, scratchlen)
close:  mov     al, 6
        int     0x80            ; close(acceptfd)
        jmp     accept


答:
Desmos, <s>125</s> 86 bytes

```<code>b=\operatorname{ceil}\left(\frac{a}{3}\right)
b\operatorname{mod}\left(-a,3\right)-b
a=1
</code>```

Simple fix for \operatorname{ceil}\left(\frac{a}{3}\right)

125 bytes:

```<code>\operatorname{ceil}\left(\frac{a}{3}\right)\operatorname{mod}\left(-a,3\right)-\operatorname{ceil}\left(\frac{a}{3}\right)
a=1
</code>```

This is as close as I could get to divmod.  Might be able to get rid of subtracting -\operatorname{ceil}\left(\frac{a}{3}\right) to shave some bytes off.

Title: Alternating Sign Sequence

Body:
Introduction

The sign of a number is either a +, or a - for every non-zero integer. Zero itself is signless (+0 is the same as -0). In the following sequence, we are going to alternate between the positive sign, the zero and the negative sign. The sequence starts with 1, so we write 1 with a positive sign, with zero (this one is weird, but we just multiply the number by 0) and the negative sign:

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

The next number is 2, and we do the same thing again:

```<code>2, 0, -2
</code>```

The sequence eventually is:

```<code>1, 0, -1, 2, 0, -2, 3, 0, -3, 4, 0, -4, 5, 0, -5, 6, 0, -6, 7, 0, -7, ...
</code>```

Or a more readable form:

```<code>a(0) = 1
a(1) = 0
a(2) = -1
a(3) = 2
a(4) = 0
a(5) = -2
a(6) = 3
a(7) = 0
a(8) = -3
a(9) = 4
...
</code>```

The Task

Given a non-negative integer n, output the nth term of the above sequence. You can choose if you use the zero-indexed or one-indexed version.

Test cases:

Zero-indexed:

```<code>a(0) = 1
a(11) = -4
a(76) = 0
a(134) = -45
a(296) = -99
</code>```

Or if you prefer one-indexed:

```<code>a(1) = 1
a(12) = -4
a(77) = 0
a(135) = -45
a(297) = -99
</code>```

This is code-golf, so the submission with the smallest number of bytes wins!

Body:
Desmos, <s>125</s> 86 bytes

b=\operatorname{ceil}\left(\frac{a}{3}\right)
b\operatorname{mod}\left(-a,3\right)-b
a=1

Simple fix for \operatorname{ceil}\left(\frac{a}{3}\right)

125 bytes:

\operatorname{ceil}\left(\frac{a}{3}\right)\operatorname{mod}\left(-a,3\right)-\operatorname{ceil}\left(\frac{a}{3}\right)
a=1

This is as close as I could get to divmod.  Might be able to get rid of subtracting -\operatorname{ceil}\left(\frac{a}{3}\right) to shave some bytes off.


问:
Recognize a vine

Background

I have a bunch of old and grainy black-and-white images.
Some of them depict vines climbing on a wall, others don't – your task is to classify them for me.

Input and output

Your input is a rectangular 2D array of bits A, given in any convenient format.
It will not be empty, but it's not guaranteed to contain both 0s and 1s.
The array depicts a vine if the following conditions hold:

The bottom row of A contains at least one 1. These are the roots of the vine.

Every 1 in A is connected to the bottom row by a path of 1s that only goes left, right and down (not up, and not diagonally). These paths are the branches of the vine.

Your output is a consistent truthy value if the input depicts a vine, and a consistent falsy value otherwise.

Examples

This array depicts a vine:

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

This input does not depict a vine, since there's a 1 at the middle of the right border that's not connected to the roots by a branch:

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

The all-0 array never depicts a vine, but the all-1 array always does.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

Test cases

Truthy inputs:

```<code>1

0
1
1

01
11

0000
0111
1100
1001

1111
1111
1111
1111

001001
011001
010111
110101
011101
001011

1011011
1001001
1111111
0100000
0111111
1111001
1001111
1111101

0000000
0011100
0010100
0011100
0001000
1111111
0001000
0011100
0010100
0010100
</code>```

Falsy inputs:

```<code>0

1
0

10
01

000
000
000

011
110
000

111111
000000
101011
111001

010010
001000
000010
110001

001100
111111
110101
010011
111011

000110
010111
010101
011110
001101

11000000
10110001
10011111
11110001
01100011
00110110
01101100
01100001
01111111
</code>```

答:
Python + NumPy <s>204</s> <s>202</s> 195 Bytes

from numpy import*
def f(A):
 r,c=A.shape
 z,s=zeros((r,1)),array([0,2,c+3])
 B=hstack((z,A,z)).flat
 for i in range(1,(r-1)*(c+2)):
    if B[i]and not any(B[s]):return 1<0
    s+=1
 return any(B[i:])
```

<p>Expects <code>A</code> to be a 2D numpy array.</p>

<p>Takes the matrix, pads zero columns left and right and flattens the matrix. <code>s</code> is a stencil that points to the left, right and lower element. The loop checks each element except the last line if it is <code>1</code> and at least one of its stencil is <code>1</code>, returns <code>False</code> otherwise. Afterwards, check if the last line contains any <code>1</code>.</p>

<p>Two testcases for you:</p>

<pre class="lang-python prettyprint-override"><code>I1 = '001001\n011001\n010111\n110101\n011101\n001011'
A1 = array([int(c) for c in I1.replace('\n','')]).reshape(6,6)
print f(A1) #True

I2 = '001100\n111111\n110101\n010011\n111011'
A2 = array([int(c) for c in I2.replace('\n','')]).reshape(5,6)
print f(A2) #False
</code>```

Edit1: 1<0 is shorter than False

Edit2: flat is a fine alternative to flatten() and using tabulators for the second intendation in the loop

Title: Recognize a vine

Body:
Python + NumPy <s>204</s> <s>202</s> 195 Bytes

from numpy import*
def f(A):
 r,c=A.shape
 z,s=zeros((r,1)),array([0,2,c+3])
 B=hstack((z,A,z)).flat
 for i in range(1,(r-1)*(c+2)):
    if B[i]and not any(B[s]):return 1<0
    s+=1
 return any(B[i:])

Expects A to be a 2D numpy array.

Takes the matrix, pads zero columns left and right and flattens the matrix. s is a stencil that points to the left, right and lower element. The loop checks each element except the last line if it is 1 and at least one of its stencil is 1, returns False otherwise. Afterwards, check if the last line contains any 1.

Two testcases for you:

I1 = '001001\n011001\n010111\n110101\n011101\n001011'
A1 = array([int(c) for c in I1.replace('\n','')]).reshape(6,6)
print f(A1) #True

I2 = '001100\n111111\n110101\n010011\n111011'
A2 = array([int(c) for c in I2.replace('\n','')]).reshape(5,6)
print f(A2) #False

Edit1: 1<0 is shorter than False

Edit2: flat is a fine alternative to flatten() and using tabulators for the second intendation in the loop


问:
Count up folks!

Introduction

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

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

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

Challenge

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

Rules

You can get n any way.

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

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

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

Standard loopholes are denied.

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

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

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

Bonuses

20%

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

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

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

答:
Desmos, 60+table bytes

```<code>l=\left[1,2,...,\operatorname{floor}\left(a\right)\right]
a=0
</code>```

I have a set to 0 because the table would contain extra spaces if I didn't.  That said, there isn't currently scoring for the table, which I've asked about on meta.

Title: Count up folks!

Body:
Desmos, 60+table bytes

l=\left[1,2,...,\operatorname{floor}\left(a\right)\right]
a=0

I have a set to 0 because the table would contain extra spaces if I didn't.  That said, there isn't currently scoring for the table, which I've asked about on meta.


答:
Hexagony, 25 bytes

```<code>?'+}@/)${':/3$~{3'.%(/'*!
</code>```

Or, in non-minified format:

```<code>    ? ' + }
   @ / ) $ {
  ' : / 3 $ ~
 { 3 ' . % ( /
  ' * ! . . .
   . . . . .
    . . . .
</code>```

Try  it online!

My first foray into Hexagony, so I'm certain I've not done this anywhere near as efficiently as it could be done...

Calculates -(n%3 - 1) on one memory edge, n/3 + 1 on an adjacent one, then multiplies them together.

Title: Alternating Sign Sequence

Body:
Hexagony, 25 bytes

?'+}@/)${':/3$~{3'.%(/'*!

Or, in non-minified format:

    ? ' + }
   @ / ) $ {
  ' : / 3 $ ~
 { 3 ' . % ( /
  ' * ! . . .
   . . . . .
    . . . .

Try  it online!

My first foray into Hexagony, so I'm certain I've not done this anywhere near as efficiently as it could be done...

Calculates -(n%3 - 1) on one memory edge, n/3 + 1 on an adjacent one, then multiplies them together.


答:
J, <s>15</s> 14 bytes

```<code>[`(|$:[)@.(]*)
</code>```

Uses Euclid's algorithm.

Usage

```<code>   f =: [`(|$:[)@.(]*)
   30 f 42
6
   42 f 30
6
   169 f 123
1
</code>```

Explanation

```<code>[`(|$:[)@.(]*)  Input: a, b
           ]*   Get sign(b)
                If sign(n) = 0
[                 Return a
                Else
   |              Get b mod a
      [           Get a
    $:            Call recursively on (b mod a, a)
</code>```

Title: Greatest Common Divisor

Body:
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

```<code>0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101
</code>```

Body:
J, <s>15</s> 14 bytes

[`(|$:[)@.(]*)

Uses Euclid's algorithm.

Usage

   f =: [`(|$:[)@.(]*)
   30 f 42
6
   42 f 30
6
   169 f 123
1

Explanation

[`(|$:[)@.(]*)  Input: a, b
           ]*   Get sign(b)
                If sign(n) = 0
[                 Return a
                Else
   |              Get b mod a
      [           Get a
    $:            Call recursively on (b mod a, a)


答:
R, 28 bytes

```<code>-((n=scan())%%3-1)*(n%/%3+1)
</code>```

Looks like this is a variation of most of the answers here.  Zero based.

```<code>   n=scan()                  # get input from STDIN
  (        )%%3-1            # mod by 3 and shift down (0,1,2) -> (-1,0,1)
-(               )           # negate result (1,0,-1), this handles the alternating signs
                  *(n%/%3+1) # integer division of n by 3, add 1, multiply by previous
</code>```

The nice thing about it is that it handles multiple inputs

```<code>> -((n=scan())%%3-1)*(n%/%3+1)
1: 0 3 6 9 1 4 7 10 2 5 8 11
13:
Read 12 items
 [1]  1  2  3  4  0  0  0  0 -1 -2 -3 -4
>
</code>```

Originally I wanted to do the following, but couldn't trim off the extra bytes.

```<code>rbind(I<-1:(n=scan()),0,-I)[n]
</code>```

Uses rbind to add 0's and negatives to a range of 1 to n then return the n'th term (one based).

```<code># for n = 5
rbind(                    )    # bind rows
            n=scan()           # get input from STDIN and assign to n
      I<-1:(        )          # build range 1 to n and assign to I
                     ,0        # add a row of zeros (expanded automatically)
                       ,-I     # add a row of negatives
                           [n] # return the n'th term
</code>```

Title: Alternating Sign Sequence

Body:
R, 28 bytes

-((n=scan())%%3-1)*(n%/%3+1)

Looks like this is a variation of most of the answers here.  Zero based.

   n=scan()                  # get input from STDIN
  (        )%%3-1            # mod by 3 and shift down (0,1,2) -> (-1,0,1)
-(               )           # negate result (1,0,-1), this handles the alternating signs
                  *(n%/%3+1) # integer division of n by 3, add 1, multiply by previous

The nice thing about it is that it handles multiple inputs

> -((n=scan())%%3-1)*(n%/%3+1)
1: 0 3 6 9 1 4 7 10 2 5 8 11
13:
Read 12 items
 [1]  1  2  3  4  0  0  0  0 -1 -2 -3 -4
>

Originally I wanted to do the following, but couldn't trim off the extra bytes.

rbind(I<-1:(n=scan()),0,-I)[n]

Uses rbind to add 0's and negatives to a range of 1 to n then return the n'th term (one based).

# for n = 5
rbind(                    )    # bind rows
            n=scan()           # get input from STDIN and assign to n
      I<-1:(        )          # build range 1 to n and assign to I
                     ,0        # add a row of zeros (expanded automatically)
                       ,-I     # add a row of negatives
                           [n] # return the n'th term


问:
What's the Binary Time?

What's the Binary Time?

Everybody knows what the normal time is. It's up there in the top-right (or wherever you put it) of your screen. But a question people rarely seem to ask themselves is this: What's the binary time?

Binary Time

Binary Time (True Binary Time) works by first reading the most significant bit (MSB) of the number. If that number is 0, the time expressed is before noon. If that number is 1, the time expressed is after noon. The next bit splits the half of the day the first bit expressed into two more equal halves, this time of 6 hours. The following bit splits into 3 hours, the next 90 minutes, and so on. Times like 12:00:00, where it seems it should be neither, become 1.

I can only understand this strange system of timing, so I need a program to convert to that for me. But as binary numbers are Base-2, and 2 is a small number, your program must be as short as possible.

Requirements

Your program should take a time (as 24-hour-time) as input and output the corresponding binary time number.

The output number should have 16-bit precision (the number should be 16 digits long).

You cannot use a builtin that does all of that conversion for you.

You should floor if it needs to be rounded.

Rules

Standard loopholes are forbidden.

Your program should not write anything to STDERR.

Test Cases

00:00:00 ==> 0000000000000000

12:00:00 ==> 1000000000000000

01:30:00 ==> 0001000000000000

10:33:06 ==> 0111000010001101

09:57:30 ==> 0110101000111000

06:00:00 ==> 0100000000000000

18:00:00 ==> 1100000000000000

Scoring

To win, as I mentioned earlier, you must have the least bytes.

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

var QUESTION_ID = 81057; // 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 = 53406; // 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,]*[^\s,]),.*?(\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,
      });

  });

  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;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) 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}

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

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

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</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

```

答:
Ruby, 75 bytes

```<code>h,m,s=t.split(':').map &:to_i;((h*3600+m*60+s<<9)/675).to_s(2).rjust 16,'0'
</code>```

I feel like there must be a shorter method of converting the time to seconds, but this is all I could think of.

Title: What's the Binary Time?

Body:
Ruby, 75 bytes

h,m,s=t.split(':').map &:to_i;((h*3600+m*60+s<<9)/675).to_s(2).rjust 16,'0'

I feel like there must be a shorter method of converting the time to seconds, but this is all I could think of.