答:
Python, 14 bytes, depth 3, A010872 from A000030

```<code>x=lambda x:x%3
</code>```

The next sequence should start with the following terms:

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

Title: Evolution of OEIS

Body:
Python, 14 bytes, depth 3, A010872 from A000030

x=lambda x:x%3

The next sequence should start with the following terms:

0, 1, 2


问:
hackertyper.net

Introduction

hackertyper.net is a website that simulates "hacking" (as the media portrays it) by outputting complicated code from the crypto section of the Linux kernel onto the screen as you type at a rate of 3 characters per one inputted.

Challenge

Your program/function should either accept a file as a command-line argument, have the file path hard-coded, or accept the text [that would be in the file] as a command-line or function argument, and mimic hackertyper.net by outputting 3 characters onto the screen (STDOUT or equivalent) from the file for each one received through STDIN or equivalent.

Once EOF is reached, the program should start outputting characters from the beginning of the file again (wrap).

Specs

For the purposes of simplicity, you can assume that STDIN has already been set to no buffer and no echo mode, that is not waiting until the user presses enter before passing input to your program and not displaying the characters you type.

The file can contain newlines, while the input will not contain newlines.

For a small example written in C (not golfed) that demonstrates how this works, see this.

Green text and a black background are not required.

Example input and output

The file:

```<code>#include <stdio.h>
int main() { }

</code>```

Input:

```<code>hello world
</code>```

Output:

```<code>#include <stdio.h>
int main() { }
</code>```

The file:

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

Input:

```<code>hello world
</code>```

Output:

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

答:
Haskell, 25 bytes

First argument is what's "typed", the second the source to display

```<code>(.cycle).take.(3*).length
</code>```

Or non-pointfree, for (possibly) better readability:

```<code>h a=take(3*length a).cycle
</code>```

ContentLicense: CC BY-SA 3.0

Title: hackertyper.net

Body:
Haskell, 25 bytes

First argument is what's "typed", the second the source to display

(.cycle).take.(3*).length

Or non-pointfree, for (possibly) better readability:

h a=take(3*length a).cycle


问:
Compute the Adler-32 checksum

Background

Adler-32 is a 32-bit checksum invented by Mark Adler in 1995 which is part of the widely used zlib library (also developed by Adler). Adler-32 is not as reliable as a 32-bit cyclic redundancy check, but – at least in software  – it is much faster and easier to implement.

Definition

Let B = [b1, ⋯, bn] be a byte array.

The Adler-32 checksum of B is defined as the result of low + 65536 × high, where:

low := ((1 + b1 + ⋯ + bn) mod 65521)

high := (((1 + b1) + (1 + b1 + b2) + ⋯ (1 + b1 + ⋯ + bn)) mod 65521)

Task

Given a byte array as input, compute and return its Adler-32 checksum, abiding to the following.

You can take the input as an array of bytes or integers, or as a string.

In both cases, only bytes corresponding to printable ASCII characters will occur in the input.

You may assume that the length of the input will satisfy 0 < length ≤ 4096.

If you choose to print the output, you may use any positive base up to and including 256.

If you choose unary, make sure interpreter can handle up to 232 - 983056 bytes of output on a machine with 16 GiB of RAM.

Built-ins that compute the Adler-32 checksum are forbidden.

Standard code-golf rules apply.

Test cases

```<code>String:     "Eagles are great!"
Byte array: [69, 97, 103, 108, 101, 115, 32, 97, 114, 101, 32, 103, 114, 101, 97, 116, 33]
Checksum:   918816254

String:     "Programming Puzzles & Code Golf"
Byte array: [80, 114, 111, 103, 114, 97, 109, 109, 105, 110, 103, 32, 80, 117, 122, 122, 108, 101, 115, 32, 38, 32, 67, 111, 100, 101, 32, 71, 111, 108, 102]
Checksum:   3133147946

String:     "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
Byte array: [126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126]
Checksum:   68095937

String:     <1040 question marks>
Byte array: <1040 copies of 63>
Checksum:   2181038080
</code>```

答:
Labyrinth, <s>37</s> <s>36</s> <s>32</s> 31 bytes

```<code>}?"{655:}21:}%=}){%{{36*+!
:++)
</code>```

Try it online!

Input as a list of integers. The program terminates with an error (whose error message goes to STDERR).

Explanation

Labyrinth primer:

Labyrinth has two stacks of arbitrary-precision integers, main and aux(iliary), which are initially filled with an (implicit) infinite amount of zeros.

The source code resembles a maze, where the instruction pointer (IP) follows corridors when it can (even around corners). The code starts at the first valid character in reading order, i.e. in the top left corner in this case. When the IP comes to any form of junction (i.e. several adjacent cells in addition to the one it came from), it will pick a direction based on the top of the main stack. The basic rules are: turn left when negative, keep going ahead when zero, turn right when positive. And when one of these is not possible because there's a wall, then the IP will take the opposite direction. The IP also turns around when hitting dead ends.

Digits are processed by multiplying the top of the main stack by 10 and then adding the digit. To start a new number, you can push a zero with _.

Although the code starts with a 4x2 "room", that is actually two separate two-by-two loops squeezed together. The IP just happens to stick to one loop at a time due to the stack values.

So the code starts with a 2x2 (clockwise) loop which reads input while computing prefix sums:

```<code>}   Move last prefix sum over to aux.
?   Read an integer from STDIN or push 0 on EOF, which exits the loop.
+   Add current value to prefix sum.
:   Duplicate this prefix sum.
</code>```

Now we've got all the prefix sums on the aux stack, as well as a copy of the sum over all values and the 0 from EOF on main. With that, we enter another 2x2 (clockwise) loop which sums all the prefix sums to compute HIGH.

```<code>"   No-op. Does nothing.
{   Pull one prefix sum over from aux. When we're done, this fetches a 0,
    which exits the loop.
)   Increment prefix sum.
+   Add it to HIGH.
</code>```

The main stack now has LOW - 1 and HIGH and zero, except we haven't taken the modulo yet. The remainder of the code is completely linear:

```<code>655      Turn the zero into 655.
:}       Make a copy and shift it over to aux.
21       Turn the copy on main into 65521.
:}       Make a copy and shift it over to aux.
%        Take HIGH mod 65521.
=        Swap HIGH with the other copy of 65521 on aux.
}){      Move 65521 back to aux, increment LOW-1 to LOW,
         move 65521 back to main.
%        Take LOW mod 65521.
{        Move HIGH back to main.
{        Move the other copy of 655 back to main.
36       Turn it into 65536.
*        Multiply HIGH by that.
+        Add it to LOW.
!        Print it.
</code>```

The IP now hits a dead end and turns around. The + and * are essentially no-ops, due to the zeros at the stack bottom. The 36 now turns the top of main into 63, but the two {{ pull two zeros from aux on top of it. Then % tries to divide by zero which terminates the program.

Note that Labyrinth uses arbitrary-precision integers so deferring the modulo until the end of the sum won't cause problems with integer overflow.

Title: Compute the Adler-32 checksum

Body:
Labyrinth, <s>37</s> <s>36</s> <s>32</s> 31 bytes

}?"{655:}21:}%=}){%{{36*+!
:++)

Try it online!

Input as a list of integers. The program terminates with an error (whose error message goes to STDERR).

Explanation

Labyrinth primer:

Labyrinth has two stacks of arbitrary-precision integers, main and aux(iliary), which are initially filled with an (implicit) infinite amount of zeros.

The source code resembles a maze, where the instruction pointer (IP) follows corridors when it can (even around corners). The code starts at the first valid character in reading order, i.e. in the top left corner in this case. When the IP comes to any form of junction (i.e. several adjacent cells in addition to the one it came from), it will pick a direction based on the top of the main stack. The basic rules are: turn left when negative, keep going ahead when zero, turn right when positive. And when one of these is not possible because there's a wall, then the IP will take the opposite direction. The IP also turns around when hitting dead ends.

Digits are processed by multiplying the top of the main stack by 10 and then adding the digit. To start a new number, you can push a zero with _.

Although the code starts with a 4x2 "room", that is actually two separate two-by-two loops squeezed together. The IP just happens to stick to one loop at a time due to the stack values.

So the code starts with a 2x2 (clockwise) loop which reads input while computing prefix sums:

}   Move last prefix sum over to aux.
?   Read an integer from STDIN or push 0 on EOF, which exits the loop.
+   Add current value to prefix sum.
:   Duplicate this prefix sum.

Now we've got all the prefix sums on the aux stack, as well as a copy of the sum over all values and the 0 from EOF on main. With that, we enter another 2x2 (clockwise) loop which sums all the prefix sums to compute HIGH.

"   No-op. Does nothing.
{   Pull one prefix sum over from aux. When we're done, this fetches a 0,
    which exits the loop.
)   Increment prefix sum.
+   Add it to HIGH.

The main stack now has LOW - 1 and HIGH and zero, except we haven't taken the modulo yet. The remainder of the code is completely linear:

655      Turn the zero into 655.
:}       Make a copy and shift it over to aux.
21       Turn the copy on main into 65521.
:}       Make a copy and shift it over to aux.
%        Take HIGH mod 65521.
=        Swap HIGH with the other copy of 65521 on aux.
}){      Move 65521 back to aux, increment LOW-1 to LOW,
         move 65521 back to main.
%        Take LOW mod 65521.
{        Move HIGH back to main.
{        Move the other copy of 655 back to main.
36       Turn it into 65536.
*        Multiply HIGH by that.
+        Add it to LOW.
!        Print it.

The IP now hits a dead end and turns around. The + and * are essentially no-ops, due to the zeros at the stack bottom. The 36 now turns the top of main into 63, but the two {{ pull two zeros from aux on top of it. Then % tries to divide by zero which terminates the program.

Note that Labyrinth uses arbitrary-precision integers so deferring the modulo until the end of the sum won't cause problems with integer overflow.


问:
Tips for golfing in PARI/GP
PARI/GP is a free computer algebra system. It is designed for (algebraic) number theory, not golfing, but that's part of the attraction. Unsurprisingly, it fares best at mathematical tasks; its support for string manipulation is primitive. (Having said that, advice for golfing non-mathematical tasks is also welcome.)

As usual, please post one tip per answer.

These tips should be at least somewhat specific to PARI/GP; advice which applies to 'most' languages belongs at Tips for golfing in <all languages>. Some general tips which don't need to be included:

Compress whitespace. (In GP all whitespace outside of strings is optional.)

Use single-character variables. (There are 50 choices, a-z and A-Z except I and O.)

Use < and > rather than <= and >= when possible.

Chain assignments. (a=b=c or a+=b*=c)

答:
Avoid return when possible.

The final value in the function is returned, so don't write ...;return(x) but just ...;x.

If you must use return, note that the bare for return yields the PARI value gnil, which is falsy (coerced into a GP 0 or PARI gen_0 as needed), so you can usually write return rather than return(0).

And (almost?) needless to say, but if you have two values to choose from, much better to return if(condition,x,y) than if(condition,return(x));y.

Title: Tips for golfing in PARI/GP


问:
The alphabet in programming languages
Our task is to, for each letter of the (English) alphabet, write a program that prints the alphabet, in a language whose name starts with that letter.

Input: none

Output:

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

uppercase and trailing newline optional

Rules:

The scoring metric is the length of the programming language name, plus the length of the code.  Hence, C will be assessed a "penalty" of 1, while GolfScript will be assessed a penalty of 10.

One language/implementation per answer.  Multiple answers are encouraged.

If a programming language name's first letter is not an English letter, it should not be coerced into one.  It will be treated as a separate letter (meaning less competition).

No answer will be accepted until every English letter has a solution.

Current rankings:

APL: 5

Brachylog: 11

Canvas: 7

DOS: 13

Eso2D: 20

Fish: 20

Gaia: 6

Husk: 8

IPEL: 23

Japt: 6

Keg: 6

Ly: 13

MathGolf: 9

Ni: 15

Owl: 14

Pip: 4

QuadR: 31

Ruby: 17

Stax: 6

Thunno: 8

Unix Shell: 31

V: 4

W: 4

XJam: 10

Yorick: 36

Z80Golf: 16

Tell me if I'm missing anybody.

Automatic leaderboard (experimental)

var QUESTION_ID=2078;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){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&&r.indexOf('non-competing')===-1&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],lang:/a)-(d<a)||e.size-s.size});var s={},a=null,n="A";e.forEach(function(e){n=e.lang[0].toUpperCase(),a=e.size;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+" is for").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.lang,p=o[0].toUpperCase();s[p]=s[p]||{language:e.language,lang:e.lang,letter:p,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return(e.letter>s.letter)-(e.letter<s.letter)});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.language).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),jQuery("#languages").append(jQuery(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*(?:<[^>]+>)?(?:[^]+?for )?((?:]*?>)?(?:(?! [(=→-])[^\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} /* font fix */ body {font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;} /* #language-list x-pos fix */ #answer-list {margin-right: 200px;}</code>```

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

Winners by Letter

Language	User	Score

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

Everything

	Language	Author	Size

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

```

答:
Mouse, 26 + 5 = 31

```<code>97a:(a.123<^a.&DUP !'1+a:)
</code>```

Which outputs:

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

Note the lame way would be:

```<code>"abcdefghijklmnopqrstuvwxyz"
</code>```

Which gets printed implicitly immediately (as string literals do, unfortunately), but it's 28 bytes.

ContentLicense: CC BY-SA 4.0

Title: The alphabet in programming languages

Body:
Mouse, 26 + 5 = 31

97a:(a.123<^a.&DUP !'1+a:)

Which outputs:

abcdefghijklmnopqrstuvwxyz

Note the lame way would be:

"abcdefghijklmnopqrstuvwxyz"

Which gets printed implicitly immediately (as string literals do, unfortunately), but it's 28 bytes.


问:
Run through an array
We all often hear the idiom "walk through the array" to mean "map the function over the following array". However, I need it done (now!), so I want you to run through the array.

How do I run?

Imagine there's a wild pack of wolves behind you

Running through an array is like walking through one, except you  can skip over elements. Yes, it's sometimes messy, but it (generally) works. "Which elements are skipped?", you may ask. Well, this is done at random. Let's walk through running through the array!

Let e be the current element.

Let random generate a random float in [0,1). If random() < 0.5, then you go the next element and then to step 1. (You may generate a number by other means, so long as their is an (ideally) equal chance of skipping and remaining. E.g., you can use choose an element from a two-member set and perform the action based on the result.)

Otherwise, you perform function f on e.

Objective

Given an array/list/string like either A and a number K, run through the array, adding K to each member accessed. Output/return this array. A will only contain non-negative integers, and K will only ever be a non-negative integers. This is a code-golf, so the shortest program in bytes wins.

Test cases (examples)

```<code>K, A => possible K'
[1, 2, 3, 4], 0 => [1, 2, 3, 4]
[1, 2, 3, 4], 1 => [1, 3, 3, 5]
[0, 0, 0, 0], 2 => [2, 0, 0, 2]
</code>```

答:
Mathcad,  bytes

No formal byte count as Mathcad counting protocol yet to be decided.

Title: Run through an array


答:
Perl 6, 60 bytes

{(.sum+1)%65521+65536*((sum(1,*+.shift...->{!$_})-1)%65521)}
```

<h3>Explanation:</h3>

<pre class="lang-perl6 prettyprint-override"><code>{
  # $_ is the implicit parameter for this lambda because this block doesn't have
  # an explicit parameter, and @_ isn't seen inside of it.
  # ( @_ takes precedence over $_ when it is seen by the compiler )

  # .sum is short for $_.sum
  ( .sum + 1 ) % 65521 + 65536
  *
  (
    (
      sum(

        # generate a sequence:

        1,         # starting with 1
        * + .shift # lambda that adds previous result (*) with $_.shift
        ...        # generate until:
        -> { !$_ } # $_ is empty

        # ^ I used a pointy block with zero parameters
        # so that the block doesn't have an implicit parameter
        # like the surrounding block

        # this is so that $_ refers to the outer $_

      ) - 1        # remove starting value
    ) % 65521
  )
}
</code>```

Test:

#! /usr/bin/env perl6
use v6.c;
use Test;

# give the lambda a name
my &Adler32 = {(.sum+1)%65521+65536*((sum(1,*+.shift...->{!$_})-1)%65521)}

my @tests = (
  (  918816254,  'Eagles are great!'),
  ( 3133147946,  'Programming Puzzles & Code Golf'),
  (   68095937,  '~' x 32,     "'~' x 32"),
  ( 2181038080,  63 xx 1040,   "'?' x 1040"),
);

plan +@tests;

for @tests -> ($checksum, $input, $gist? ) {
  my @array := do given $input {
    when Str { .encode.Array }
    default { .Array }
  }

  is Adler32(@array), $checksum, $gist // $input.perl
}
```

<pre class="lang-none prettyprint-override"><code>1..4
ok 1 - "Eagles are great!"
ok 2 - "Programming Puzzles \& Code Golf"
ok 3 - '~' x 32
ok 4 - '?' x 1040
</code>```

Title: Compute the Adler-32 checksum

Body:
Background

Adler-32 is a 32-bit checksum invented by Mark Adler in 1995 which is part of the widely used zlib library (also developed by Adler). Adler-32 is not as reliable as a 32-bit cyclic redundancy check, but – at least in software  – it is much faster and easier to implement.

Definition

Let B = [b1, ⋯, bn] be a byte array.

The Adler-32 checksum of B is defined as the result of low + 65536 × high, where:

low := ((1 + b1 + ⋯ + bn) mod 65521)

high := (((1 + b1) + (1 + b1 + b2) + ⋯ (1 + b1 + ⋯ + bn)) mod 65521)

Task

Given a byte array as input, compute and return its Adler-32 checksum, abiding to the following.

You can take the input as an array of bytes or integers, or as a string.

In both cases, only bytes corresponding to printable ASCII characters will occur in the input.

You may assume that the length of the input will satisfy 0 < length ≤ 4096.

If you choose to print the output, you may use any positive base up to and including 256.

If you choose unary, make sure interpreter can handle up to 232 - 983056 bytes of output on a machine with 16 GiB of RAM.

Built-ins that compute the Adler-32 checksum are forbidden.

Standard code-golf rules apply.

Test cases

```<code>String:     "Eagles are great!"
Byte array: [69, 97, 103, 108, 101, 115, 32, 97, 114, 101, 32, 103, 114, 101, 97, 116, 33]
Checksum:   918816254

String:     "Programming Puzzles & Code Golf"
Byte array: [80, 114, 111, 103, 114, 97, 109, 109, 105, 110, 103, 32, 80, 117, 122, 122, 108, 101, 115, 32, 38, 32, 67, 111, 100, 101, 32, 71, 111, 108, 102]
Checksum:   3133147946

String:     "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
Byte array: [126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126]
Checksum:   68095937

String:     <1040 question marks>
Byte array: <1040 copies of 63>
Checksum:   2181038080
</code>```

Body:
Perl 6, 60 bytes

{(.sum+1)%65521+65536*((sum(1,*+.shift...->{!$_})-1)%65521)}

Explanation:

{
  # $_ is the implicit parameter for this lambda because this block doesn't have
  # an explicit parameter, and @_ isn't seen inside of it.
  # ( @_ takes precedence over $_ when it is seen by the compiler )

  # .sum is short for $_.sum
  ( .sum + 1 ) % 65521 + 65536
  *
  (
    (
      sum(

        # generate a sequence:

        1,         # starting with 1
        * + .shift # lambda that adds previous result (*) with $_.shift
        ...        # generate until:
        -> { !$_ } # $_ is empty

        # ^ I used a pointy block with zero parameters
        # so that the block doesn't have an implicit parameter
        # like the surrounding block

        # this is so that $_ refers to the outer $_

      ) - 1        # remove starting value
    ) % 65521
  )
}

Test:

#! /usr/bin/env perl6
use v6.c;
use Test;

# give the lambda a name
my &Adler32 = {(.sum+1)%65521+65536*((sum(1,*+.shift...->{!$_})-1)%65521)}

my @tests = (
  (  918816254,  'Eagles are great!'),
  ( 3133147946,  'Programming Puzzles & Code Golf'),
  (   68095937,  '~' x 32,     "'~' x 32"),
  ( 2181038080,  63 xx 1040,   "'?' x 1040"),
);

plan +@tests;

for @tests -> ($checksum, $input, $gist? ) {
  my @array := do given $input {
    when Str { .encode.Array }
    default { .Array }
  }

  is Adler32(@array), $checksum, $gist // $input.perl
}

1..4
ok 1 - "Eagles are great!"
ok 2 - "Programming Puzzles \& Code Golf"
ok 3 - '~' x 32
ok 4 - '?' x 1040


问:
Find the repetend of the decimal representation!
In this challenge 2 years ago, we found the period of a unit fraction (1/n where n is a natural number).

Now, your task is to write a program/function to find the repetend of a unit fraction.

The repetend is the part of the decimal expansion which repeats infinitely, like:

The decimal representation of 1/6 is 0.16666..., then the repetend is 6.

The decimal representation of 1/11 is 0.090909..., then the repetend is 09.

The decimal representation of 1/28 is 0.0357142857142857142857..., then the repetend is 571428.

Specs

Input in any reasonable format.

Output the repetend in decimal, string or list.

For 1/7 (0.142857142857...), you must output 142857 instead of 428571.

For 1/13 (0.076923076923076923...), you must output 076923 instead of 76923.

No brute force, please.

Testcases

```<code>Input    Output
1        0
2        0
3        3
7        142857
13       076923
17       0588235294117647
28       571428
70       142857
98       102040816326530612244897959183673469387755
9899     000101020305081321345590463683200323264976260228305889483786241034447924032730578846348115971310233356904737852308313971108192746742095161127386604707546216789574704515607637135064147893726639054449944438832205273259925244974239822204263056874431760783917567431053641781998181634508536215779371653702394181230427315890493989291847661379937367410849580765733912516415799575714718658450348520052530558642287099707041115264168097787655318719062531568845337912920497019901
</code>```

Scoring

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

No answer would be accepted, because the goal is not to find the language capable of producing the shortest solution, but the shortest solution in each language.

Leaderboard

var QUESTION_ID=78850,OVERRIDE_USER=42854;function answersUrl(e){return"http://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"http://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

```

答:
Python 3.5, <s>79</s> <s>74</s> <s>73</s> 70 bytes

f=lambda n,t=1,q=[],*d:q[(*d,t).index(t):]or f(n,t%n*10,q+[t//n],*d,t)
```

Saved 3 bytes by keeping track of dividends, an idea I took from @aditsu's CJam answer.

Test it on repl.it.

Body:
Python 3.5, <s>79</s> <s>74</s> <s>73</s> 70 bytes

f=lambda n,t=1,q=[],*d:q[(*d,t).index(t):]or f(n,t%n*10,q+[t//n],*d,t)

Saved 3 bytes by keeping track of dividends, an idea I took from @aditsu's CJam answer.

Test it on repl.it.


答:
php 71 bytes

```<code>function f($s,$k){foreach($s as $v){$v+=rand(0,2)==0?k:0;echo $v.",";}}
</code>```

Title: Run through an array

Body:
We all often hear the idiom "walk through the array" to mean "map the function over the following array". However, I need it done (now!), so I want you to run through the array.

How do I run?

Imagine there's a wild pack of wolves behind you

Running through an array is like walking through one, except you  can skip over elements. Yes, it's sometimes messy, but it (generally) works. "Which elements are skipped?", you may ask. Well, this is done at random. Let's walk through running through the array!

Let e be the current element.

Let random generate a random float in [0,1). If random() < 0.5, then you go the next element and then to step 1. (You may generate a number by other means, so long as their is an (ideally) equal chance of skipping and remaining. E.g., you can use choose an element from a two-member set and perform the action based on the result.)

Otherwise, you perform function f on e.

Objective

Given an array/list/string like either A and a number K, run through the array, adding K to each member accessed. Output/return this array. A will only contain non-negative integers, and K will only ever be a non-negative integers. This is a code-golf, so the shortest program in bytes wins.

Test cases (examples)

```<code>K, A => possible K'
[1, 2, 3, 4], 0 => [1, 2, 3, 4]
[1, 2, 3, 4], 1 => [1, 3, 3, 5]
[0, 0, 0, 0], 2 => [2, 0, 0, 2]
</code>```

Body:
php 71 bytes

function f($s,$k){foreach($s as $v){$v+=rand(0,2)==0?k:0;echo $v.",";}}


问:
Compute the histogram entropy estimation of a string
Write a program or function that estimates the Shannon entropy of a given string.

If a string has n characters, d distinct characters, xi is the i th distinct character, and P(xi) is the probability of that character occuring in the string, then our Shannon entropy estimate for that string is given by:

For the estimation in this challenge we assume that the probability of a character occurring in a string is simply the number of times it occurs divided by the total number of characters.

Your answer must be accurate to at least 3 digits after the period.

Test cases:

```<code>"This is a test.", 45.094
"00001111", 8.000
"cwmfjordbankglyphsvextquiz", 122.211
"             ", 0.0
</code>```

答:
k (32 bytes)

```<code>{-+/c*(log c%n:+/c:#:'=x)%log 2}
</code>```

Or in q, the translation is not all that short but clearer:

```<code>{neg sum c*2 xlog c%n:sum c:count each group x}
</code>```

Body:
k (32 bytes)

{-+/c*(log c%n:+/c:#:'=x)%log 2}

Or in q, the translation is not all that short but clearer:

{neg sum c*2 xlog c%n:sum c:count each group x}


答:
Jolf, 10 bytes

```<code>]*iγl*I30γ
</code>```

Try it here!

Explanation

```<code>]*iγl*I30γ
 *i        repeat string 1
    l*I3    the length of the other string * 3
   γ        γ = (^)
]       0γ  (^).slice(0, γ)
</code>```

Title: hackertyper.net

Body:
Introduction

hackertyper.net is a website that simulates "hacking" (as the media portrays it) by outputting complicated code from the crypto section of the Linux kernel onto the screen as you type at a rate of 3 characters per one inputted.

Challenge

Your program/function should either accept a file as a command-line argument, have the file path hard-coded, or accept the text [that would be in the file] as a command-line or function argument, and mimic hackertyper.net by outputting 3 characters onto the screen (STDOUT or equivalent) from the file for each one received through STDIN or equivalent.

Once EOF is reached, the program should start outputting characters from the beginning of the file again (wrap).

Specs

For the purposes of simplicity, you can assume that STDIN has already been set to no buffer and no echo mode, that is not waiting until the user presses enter before passing input to your program and not displaying the characters you type.

The file can contain newlines, while the input will not contain newlines.

For a small example written in C (not golfed) that demonstrates how this works, see this.

Green text and a black background are not required.

Example input and output

The file:

```<code>#include <stdio.h>
int main() { }

</code>```

Input:

```<code>hello world
</code>```

Output:

```<code>#include <stdio.h>
int main() { }
</code>```

The file:

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

Input:

```<code>hello world
</code>```

Output:

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

Body:
Jolf, 10 bytes

]*iγl*I30γ

Try it here!

Explanation

]*iγl*I30γ
 *i        repeat string 1
    l*I3    the length of the other string * 3
   γ        γ = (^)
]       0γ  (^).slice(0, γ)


问:
Calculate the a ^ b WITHOUT using *, / and ^

Challenge

Your goal is, given two positive integer numbers a and b, to calculate (and output) a ^ b without using either multiplication, division and the power itself (not directly, at least).
And, of course, built-in exponentiation functions.

Scoring

This is code-golf, so the shorter, the better.

Test cases

```<code>Input => Output
2, 3 => 8
5, 5 => 3125
100, 4 => 100000000
17, 9 => 118587876497
0, 1 => 0
3921, 0 => 1
</code>```

答:
k (19 bytes)

This is slow and uses lots of memory:

```<code>{#,//(x#,:)/[y;0b]}
</code>```

The /s are not division, it's the converge operator.

Body:
k (19 bytes)

This is slow and uses lots of memory:

{#,//(x#,:)/[y;0b]}

The /s are not division, it's the converge operator.


Title: Compute the Adler-32 checksum

Body:
Ruby, 91 bytes

->s{b=s.bytes;z=i=b.size
b.inject(1,:+)%65521+b.map{|e|e*(1+i-=1)}.inject(z,:+)%65521*4**8}


Title: Run through an array

Body:
k (12 bytes)

{x+y*(#x)?2}

e.g.

k){x+y*(#x)?2}[0 0 0 0;2]
2 2 2 0

More generally, where f can be passed as an argument for 16 characters

{@[x;&(#x)?2;y]}

e.g.

k){@[x;&(#x)?2;y]}[0 0 0 0;2+]
0 0 2 0


Title: Compute the Adler-32 checksum

Body:
Clojure, 109 bytes

Based on @Mark Adler's solution.

(fn f[s](->> s(reduce #(mapv + %(repeat %2)[0(first %)])[1 0])(map #(rem % 65521))(map *[1 65536])(apply +)))

Ungolfed

(fn f [s]
  (->> s
       (reduce #(mapv + % (repeat %2) [0 (first %)]) [1 0])
       (map #(rem % 65521))
       (map * [1 65536])
       (apply +)))

Usage

=> (def f (fn f[s](->> s(reduce #(mapv + %(repeat %2)[0(first %)])[1 0])(map #(rem % 65521))(map *[1 65536])(apply +))))
=> (f [69 97 103 108 101 115 32 97 114 101 32 103 114 101 97 116 33])
918816254
=> (f [80 114 111 103 114 97 109 109 105 110 103 32 80 117 122 122 108 101 115 32 38 32 67 111 100 101 32 71 111 108 102])
3133147946
=> (f (repeat 32 126))
68095937
=> (f (repeat 1040 63))
2181038080
=> (f (repeat 4096 255))
2170679522


问:
Generate n digits of Gijswijt's sequence

Introduction

Gijswijt's sequence (A090822) is famously really, REALLY slow. To illustrate:

The first 3 appears in the 9th term (alright).

The first 4 appears in the 220th term (a long way away, but feasible).

The first 5 appears at (approximately) the 10^(10^23)th term (just no).

No one really even knows where the first 6 is... it's suspected it's at the...

2^(2^(3^(4^5)))th term.

You can assume that you won't have to deal with a two-digit number.

The sequence is generated like so:

The first term is 1.

Each term after that is the amount of repeating "blocks" previous to it (if there are multiple repeating "blocks", the largest amount of repeating blocks is used).

To clarify, here are the first few terms.

1 -> 1, 1 (one repeating block (1), so the digit recorded is 1)

1, 1 -> 1, 1, 2 (two repeating blocks (1), so the digit recorded is 2)

1, 1, 2 -> 1, 1, 2, 1 (one repeating block (2 or 1, 1, 2), so the digit recorded is 1)

1, 1, 2, 1 -> 1, 1, 2, 1, 1 (you get the idea)

1, 1, 2, 1, 1 -> 1, 1, 2, 1, 1, 2

1, 1, 2, 1, 1, 2 -> 1, 1, 2, 1, 1, 2, 2 (two repeating blocks (1, 1, 2), so the digit recorded is 2)

Task

Your task is, as stated in the question, to generate n digits of the Gijswijt sequence.

Instructions

The input will be an integer n.

Your code can output the digits in any form (a list, multiple outputs, etc.).

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

答:
Ruby, 84 bytes

The Retina answer inspired me to do a regex-based solution to find the best sequence instead of somehow counting sequences in an array, but with less of the genius (negative lookbehinds with quantifiers don't seem to be allowed in Ruby, so I doubt I could directly port Retina's answer over anyways)

```<code>->n{s='';n.times{s+=(1..n).map{|i|s=~/(\d{#{i}})\1+$/?$&.size/i: 1}.max.to_s};s[-1]}
</code>```

Given an already-generated sequence s, it maps over all i from 1 to s.length (n was used in this case to save bytes since n>=s.length) and then uses this regex to help calculate the number of repetitions of a subsequence with length i:

```<code>/(.{#{i}})\1+$/
/(                 # Assign the following to group 1
  .{#{i}}          # Match `i` number of characters
         )         # End group 1
          \1+      # Match 1 or more repetitions of group 1
             $/    # Match the end of string
</code>```

If a match is found of that length, it calculates the number of repetitions by dividing the length of the given match $& by i, the length of the subsequence; if no match was found, it is treated as 1. The function then finds the maximum number of repetitions from this mapping and adds that number to the end of the string.

Body:
Ruby, 84 bytes

The Retina answer inspired me to do a regex-based solution to find the best sequence instead of somehow counting sequences in an array, but with less of the genius (negative lookbehinds with quantifiers don't seem to be allowed in Ruby, so I doubt I could directly port Retina's answer over anyways)

->n{s='';n.times{s+=(1..n).map{|i|s=~/(\d{#{i}})\1+$/?$&.size/i: 1}.max.to_s};s[-1]}

Given an already-generated sequence s, it maps over all i from 1 to s.length (n was used in this case to save bytes since n>=s.length) and then uses this regex to help calculate the number of repetitions of a subsequence with length i:

/(.{#{i}})\1+$/
/(                 # Assign the following to group 1
  .{#{i}}          # Match `i` number of characters
         )         # End group 1
          \1+      # Match 1 or more repetitions of group 1
             $/    # Match the end of string

If a match is found of that length, it calculates the number of repetitions by dividing the length of the given match $& by i, the length of the subsequence; if no match was found, it is treated as 1. The function then finds the maximum number of repetitions from this mapping and adds that number to the end of the string.


答:
Mathematica, 45 bytes

```<code>Tr[Log[2,Tr@#/#]#]&@Values@CharacterCounts@#&
</code>```

Usage

This returns exact results so we approximate them with N.

```<code>  f = Tr[Log[2,Tr@#/#]#]&@Values@CharacterCounts@#&
  f["This is a test."]//N
45.0936
  f["00001111"]//N
8.
  f["cwmfjordbankglyphsvextquiz"]//N
122.211
  f["             "]//N
0.
</code>```

Title: Compute the histogram entropy estimation of a string

Body:
Write a program or function that estimates the Shannon entropy of a given string.

If a string has n characters, d distinct characters, xi is the i th distinct character, and P(xi) is the probability of that character occuring in the string, then our Shannon entropy estimate for that string is given by:

For the estimation in this challenge we assume that the probability of a character occurring in a string is simply the number of times it occurs divided by the total number of characters.

Your answer must be accurate to at least 3 digits after the period.

Test cases:

```<code>"This is a test.", 45.094
"00001111", 8.000
"cwmfjordbankglyphsvextquiz", 122.211
"             ", 0.0
</code>```

Body:
Mathematica, 45 bytes

Tr[Log[2,Tr@#/#]#]&@Values@CharacterCounts@#&

Usage

This returns exact results so we approximate them with N.

  f = Tr[Log[2,Tr@#/#]#]&@Values@CharacterCounts@#&
  f["This is a test."]//N
45.0936
  f["00001111"]//N
8.
  f["cwmfjordbankglyphsvextquiz"]//N
122.211
  f["             "]//N
0.


问:
Will it float?

The challenge

Given a 2d string representing the bottom of a boat as an input, you must determine whether or not the boat will float. This 2D string can be in whatever format is most convenient. (String with newlines, list of string, list of list of chars, etc.) Print a truthy value if it will float, and a falsey value if it will sink.

A boat will tip over if the bottom has an inconsistent density, so every character of must be the same. Also, if a boat has large holes in it, represented by spaces, it will sink, so your boat must have no holes with an area greater than 4. Here is an example:

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

This boat is valid because the largest hole in it has an area of 4. This boat:

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

is invalid because it has a hole with an area of 7. You can safely assume that the outside of every input will be a solid rectangle with no holes. Here are some more tests:

```<code>$$$$$$$$
***$$$$$
***$$$$$
***$$$$$
$$$$$$$$
Invalid density. Sink.

%%%%%%%%
%    % %
%%%%%  %
%    % %
%%%%%%%%
None of the holes are larger than 4. Float.

OOOOOOOO
OOOOOOO
OOOOOOOO
OOOOOOOO
OOOOOOOO
The outside border is not solid. Undefined.

&&&&&&&&&&&&&
& & & & & & &
&& & & & & &&
& & & & & & &
&& & & & & &&
& & & & & & &
&&&&&&&&&&&&&
Although I would not be comfortable riding in this boat myself,
none of the holes are larger than 4. It floats.

@@@@@
@   @
@   @
@   @
@@@@@
It sinks.
</code>```

Rules

IO can be in any reasonable format.

Standard loopholes apply.

Shortest answer in bytes wins.

The given string will entirely consist of printable ASCII.

答:
Matlab, 106 bytes

```<code>s=input('');im=~(s-32);c=bwconncomp(im,4);disp(~nnz(cellfun(@nnz,c.PixelIdxList)>3)&nnz(unique(s(~im)))<2)
</code>```

The input is a matrix of characters, e.g. for the first test case:

```<code>`['$$$$$$$$';'***$$$$$';'***$$$$$';'***$$$$$';'$$$$$$$$']`
</code>```

Explanation:

```<code>s=input('');           %read input
im=~(s-32);            %convert input to bw image (space = black)
c=bwconncomp(im,4);    %calculate the connected components (4 connectivity)

disp(
     ~nnz(cellfun(@nnz,c.PixelIdxList)>3) %find out whether we have components that have more at least 4 pixels
     &nnz(unique(s(~im)))<2)              %find out if we have more than 1 non-space character
</code>```

Title: Will it float?

Body:
Matlab, 106 bytes

s=input('');im=~(s-32);c=bwconncomp(im,4);disp(~nnz(cellfun(@nnz,c.PixelIdxList)>3)&nnz(unique(s(~im)))<2)

The input is a matrix of characters, e.g. for the first test case:

`['$$$$$$$$';'***$$$$$';'***$$$$$';'***$$$$$';'$$$$$$$$']`

Explanation:

s=input('');           %read input
im=~(s-32);            %convert input to bw image (space = black)
c=bwconncomp(im,4);    %calculate the connected components (4 connectivity)

disp(
     ~nnz(cellfun(@nnz,c.PixelIdxList)>3) %find out whether we have components that have more at least 4 pixels
     &nnz(unique(s(~im)))<2)              %find out if we have more than 1 non-space character


答:
Python 3 (79 bytes)

Based on R. Kap's solution.

```<code>lambda w,E=65521:(1+sum(w))%E+(sum(1+sum(w[:i+1])for i in range(len(w)))%E<<16)
</code>```

I replaced the multiplication by a shift and removed a pair of brackets.

Because I can't post comments I made a new answer.

Title: Compute the Adler-32 checksum

Body:
Python 3 (79 bytes)

Based on R. Kap's solution.

lambda w,E=65521:(1+sum(w))%E+(sum(1+sum(w[:i+1])for i in range(len(w)))%E<<16)

I replaced the multiplication by a shift and removed a pair of brackets.

Because I can't post comments I made a new answer.


答:
Octave, <s>52</s> 50 bytes

Saved 2 bytes thanks to @LuisMendo

```<code>@(B)mod([sum(S=cumsum(B)+1),S(end)],65521)*[4^8;1]
</code>```

Takes an array of integers as input.

low is taken from the last element of high (before summing) rather than calculating the sum explicitly, saving a grand total of... 1 byte!

Sample run on ideone.

Title: Compute the Adler-32 checksum

Body:
Background

Adler-32 is a 32-bit checksum invented by Mark Adler in 1995 which is part of the widely used zlib library (also developed by Adler). Adler-32 is not as reliable as a 32-bit cyclic redundancy check, but – at least in software  – it is much faster and easier to implement.

Definition

Let B = [b1, ⋯, bn] be a byte array.

The Adler-32 checksum of B is defined as the result of low + 65536 × high, where:

low := ((1 + b1 + ⋯ + bn) mod 65521)

high := (((1 + b1) + (1 + b1 + b2) + ⋯ (1 + b1 + ⋯ + bn)) mod 65521)

Task

Given a byte array as input, compute and return its Adler-32 checksum, abiding to the following.

You can take the input as an array of bytes or integers, or as a string.

In both cases, only bytes corresponding to printable ASCII characters will occur in the input.

You may assume that the length of the input will satisfy 0 < length ≤ 4096.

If you choose to print the output, you may use any positive base up to and including 256.

If you choose unary, make sure interpreter can handle up to 232 - 983056 bytes of output on a machine with 16 GiB of RAM.

Built-ins that compute the Adler-32 checksum are forbidden.

Standard code-golf rules apply.

Test cases

```<code>String:     "Eagles are great!"
Byte array: [69, 97, 103, 108, 101, 115, 32, 97, 114, 101, 32, 103, 114, 101, 97, 116, 33]
Checksum:   918816254

String:     "Programming Puzzles & Code Golf"
Byte array: [80, 114, 111, 103, 114, 97, 109, 109, 105, 110, 103, 32, 80, 117, 122, 122, 108, 101, 115, 32, 38, 32, 67, 111, 100, 101, 32, 71, 111, 108, 102]
Checksum:   3133147946

String:     "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
Byte array: [126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126]
Checksum:   68095937

String:     <1040 question marks>
Byte array: <1040 copies of 63>
Checksum:   2181038080
</code>```

Body:
Octave, <s>52</s> 50 bytes

Saved 2 bytes thanks to @LuisMendo

@(B)mod([sum(S=cumsum(B)+1),S(end)],65521)*[4^8;1]

Takes an array of integers as input.

low is taken from the last element of high (before summing) rather than calculating the sum explicitly, saving a grand total of... 1 byte!

Sample run on ideone.


答:
Ruby, 39 bytes

In Ruby, $< reads from the supplied file in the command line arguments instead of $stdin if one is given. (If you forget to supply a file, you get a blank output because it reads everything out of $stdin in $<.read and thus STDIN.read.size will be 0.)

```<code>$><<($<.read*s=3*STDIN.read.size)[0,s]
</code>```

Title: hackertyper.net

Body:
Ruby, 39 bytes

In Ruby, $< reads from the supplied file in the command line arguments instead of $stdin if one is given. (If you forget to supply a file, you get a blank output because it reads everything out of $stdin in $<.read and thus STDIN.read.size will be 0.)

$><<($<.read*s=3*STDIN.read.size)[0,s]


Title: Compute the Adler-32 checksum

Body:
Javascript (130 Characters Golfed)

Ungolfed

function a(b)
{
    c=1
    for(i=0;i<b.length;i++)
    {
        c+=b[i]
    }
    d=c%65521
    f=""
    e=0
    k=""
    for(j=0;j<b.length;j++)
    {
        k+= "+"+b[j]
        f+= "(1"+k+")"
        e= ((eval(f)))
        if(j!=b.length-1){f+="+"}
    }
    g=e%65521
    h=d+65536*g
    console.log(h)
}

Golfed

a=b=>{for(c=1,k=f="",y=b.length,i=0;i<y;i++)c+=x=b[i],f+="(1"+(k+="+"+x)+")",i<y-1&&(f+="+");return z=65521,c%z+65536*(eval(f)%z)}

Paste into Developers Console and then give it an Array of Bytes
EG:

[69, 97, 103, 108, 101, 115, 32, 97, 114, 101, 32, 103, 114, 101, 97, 116, 33]

And it will return the checksum to the console


答:
Scheme, 195 bytes

```<code>(define(a b)(+(let L((b b)(s 1))(if(=(length b)0)s(L(cdr b)(modulo(+ s(car b))65521))))(* 65536(let H((b b)(s 1)(t 0))(if(=(length b)0)t(let((S(+ s(car b))))(H(cdr b)S(modulo(+ t S)65521))))))))
</code>```

If it weren't for all those parentheses...

Title: Compute the Adler-32 checksum

Body:
Scheme, 195 bytes

(define(a b)(+(let L((b b)(s 1))(if(=(length b)0)s(L(cdr b)(modulo(+ s(car b))65521))))(* 65536(let H((b b)(s 1)(t 0))(if(=(length b)0)t(let((S(+ s(car b))))(H(cdr b)S(modulo(+ t S)65521))))))))

If it weren't for all those parentheses...


问:
Compute CRC32 Hash

Credits

This challenge originated from @miles.

Create a function that computes the CRC32 hash of an input string. The input will be an ASCII string of any length. The output will be the CRC32 hash of that input string.

Explanation

The algorithm of CRC32 and other CRC are essentially the same, so only CRC3 will be demonstrated here.

Firstly, you have the generator polynomial, which is actually a 4-bit [n+1] integer (would be 33-bit in CRC32).

In this example, the generator polynomial is 1101.

Then, you will have the string to be hashed, which in this example would be 00010010111100101011001101.

```<code>00010010111100101011001101|000 (1)    append three [n] "0"s
   1101                        (2)    align with highest bit
00001000111100101011001101|000 (3)    XOR (1) and (2)
    1101                       (4)    align with highest bit
00000101111100101011001101|000 (5)    XOR (3) and (4)
     1101                      (6)    align with highest bit
00000011011100101011001101|000 (7)    XOR (5) and (6)
      1101                     (8)    align with highest bit
00000000001100101011001101|000 (9)    XOR (7) and (8)
          1101                 (10)   align with highest bit
00000000000001101011001101|000 (11)   XOR (9) and (10)
             1101              (12)   align with highest bit
00000000000000000011001101|000 (13)   XOR (11) and (12)
                  1101         (14)   align with highest bit
00000000000000000000011101|000 (15)   XOR (13) and (14)
                     1101      (16)   align with highest bit
00000000000000000000000111|000 (17)   XOR (15) and (16)
                       110 1   (18)   align with highest bit
00000000000000000000000001|100 (19)   XOR (17) and (18)
                         1 101 (20)   align with highest bit
00000000000000000000000000|001 (21)   XOR (19) and (20)
^--------REGION 1--------^ ^2^
</code>```

The remainder obtained at (21), when region 1 is zero, which is 001, would be the result of the CRC3 hash.

Specs

The generator polynomial is 0x104C11DB7, or 0b100000100110000010001110110110111, or 4374732215.

Input can be a string or a list of integers, or any other reasonable format.

Output be a hex string or just an integer, or any other reasonable format.

Built-ins that compute the CRC32 hash are not allowed.

Goal

Standard rules for code-golf apply.

The shortest code wins.

Test cases

```<code>input         output      (hex)
"code-golf"   147743960   08CE64D8
"jelly"       1699969158  65537886
""            0           00000000
</code>```

答:
Jelly, 34 bytes

```<code>l2_32Ḟ4374732215æ«^
Oḅ⁹æ«32Çæ»32$¿
</code>```

Try it online!

Title: Compute CRC32 Hash

Body:
Jelly, 34 bytes

l2_32Ḟ4374732215æ«^
Oḅ⁹æ«32Çæ»32$¿

Try it online!


Title: Compute CRC32 Hash

Body:
Credits

This challenge originated from @miles.

Create a function that computes the CRC32 hash of an input string. The input will be an ASCII string of any length. The output will be the CRC32 hash of that input string.

Explanation

The algorithm of CRC32 and other CRC are essentially the same, so only CRC3 will be demonstrated here.

Firstly, you have the generator polynomial, which is actually a 4-bit [n+1] integer (would be 33-bit in CRC32).

In this example, the generator polynomial is 1101.

Then, you will have the string to be hashed, which in this example would be 00010010111100101011001101.

```<code>00010010111100101011001101|000 (1)    append three [n] "0"s
   1101                        (2)    align with highest bit
00001000111100101011001101|000 (3)    XOR (1) and (2)
    1101                       (4)    align with highest bit
00000101111100101011001101|000 (5)    XOR (3) and (4)
     1101                      (6)    align with highest bit
00000011011100101011001101|000 (7)    XOR (5) and (6)
      1101                     (8)    align with highest bit
00000000001100101011001101|000 (9)    XOR (7) and (8)
          1101                 (10)   align with highest bit
00000000000001101011001101|000 (11)   XOR (9) and (10)
             1101              (12)   align with highest bit
00000000000000000011001101|000 (13)   XOR (11) and (12)
                  1101         (14)   align with highest bit
00000000000000000000011101|000 (15)   XOR (13) and (14)
                     1101      (16)   align with highest bit
00000000000000000000000111|000 (17)   XOR (15) and (16)
                       110 1   (18)   align with highest bit
00000000000000000000000001|100 (19)   XOR (17) and (18)
                         1 101 (20)   align with highest bit
00000000000000000000000000|001 (21)   XOR (19) and (20)
^--------REGION 1--------^ ^2^
</code>```

The remainder obtained at (21), when region 1 is zero, which is 001, would be the result of the CRC3 hash.

Specs

The generator polynomial is 0x104C11DB7, or 0b100000100110000010001110110110111, or 4374732215.

Input can be a string or a list of integers, or any other reasonable format.

Output be a hex string or just an integer, or any other reasonable format.

Built-ins that compute the CRC32 hash are not allowed.

Goal

Standard rules for code-golf apply.

The shortest code wins.

Test cases

```<code>input         output      (hex)
"code-golf"   147743960   08CE64D8
"jelly"       1699969158  65537886
""            0           00000000
</code>```

Body:
Pyth, 42 bytes

?!Q0h<#^2 32.uxN.<4374732215.as-lN32.<CQ32

Test suite.


问:
XOR multiplication
You goal is to implement the operation of XOR (carryless) multiplication, defined below, in as few bytes as possible.

If we think of bitwise XOR (^) as binary addition without carrying

```<code>   101   5
^ 1001   9
  ----
  1100  12

  5^9=12
</code>```

we can perform XOR multiplication @ by doing binary long-multiplication but doing the adding step without carrying as bitwise XOR ^.

```<code>     1110  14
   @ 1101  13
    -----
     1110
       0
   1110
^ 1110
  ------
  1000110  70

  14@13=70
</code>```

(For mathematicians, this is multiplication in the polynomial ring \$F_2[x]\$, identifying polynomials with natural numbers by evaluating at \$x=2\$ as a polynomial over \$\mathbb Z\$.)

XOR multiplication commutes a@b=b@a, associates (a@b)@c=a@(b@c), and distributes over bitwise XOR a@(b^c)=(a@b)^(a@c). In fact, it is the unique such operation that matches multiplication a@b=a*b whenever a and b are powers of 2 like 1,2,4,8....

Requirements

Take two non-negative integers as input and output or print their XOR-product. This should be as numbers or their decimal string representations, not their binary expansions. Fewest bytes wins.

Don't worry about integer overflows.

Here are some test cases formatted as a b a@b.

```<code>0 1 0
1 2 2
9 0 0
6 1 6
3 3 5
2 5 10
7 9 63
13 11 127
5 17 85
14 13 70
19 1 19
63 63 1365
</code>```

答:
Jelly, 16 bytes

```<code>Ḥ⁴BL’¤Ð¡U×"⁴B¤^/
</code>```

Try it online!

Title: XOR multiplication

Body:
Jelly, 16 bytes

Ḥ⁴BL’¤Ð¡U×"⁴B¤^/

Try it online!


答:
Ruby, 142 bytes

Anonymous function; takes a string as input, returns an integer.

->s{z=8*i=s.size;r=0;h=4374732215<<z
l=->n{j=0;j+=1 while 0<n/=2;j}
s.bytes.map{|e|r+=e*256**(i-=1)};r<<=32
z.times{h/=2;r^=l[h]==l[r]?h:0}
r}
```

Title: Compute CRC32 Hash


问:
Decompose a number!
Your task is to decompose a number using the format below.

This is similar to base conversion, except that instead of listing the digits in the base, you list the values, such that the list adds up to the input.

If the given base is \$n\$, then each number in the list must be in the form of \$k\times n^m\$, where \$0\le k<n\$ and \$m\$ is unique throughout the list.

Specs

Any reasonable input/output format. Your program/function takes 2 inputs and outputs a list.

Output list can be in any order.

0 can be excluded or included.

Leading 0s are allowed.

Built-ins are allowed.

Testcases

```<code>number base   converted list
input1 input2 output
123456 10     [100000,20000,3000,400,50,6] or [6,50,400,3000,20000,100000]
11     2      [8,2,1] or [0,0,0,0,8,0,2,1]
727    20     [400,320,7]
101    10     [100,1] or [100,0,1]
</code>```

Scoring

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

答:
Pyth - <s>12</s> 11 bytes

Just a FGITW, can be shorter.

```<code>.e*b^Qk_jEQ
</code>```

Test Suite.

Title: Decompose a number!

Body:
Pyth - <s>12</s> 11 bytes

Just a FGITW, can be shorter.

.e*b^Qk_jEQ

Test Suite.


答:
Jelly, 12 bytes

```<code>bLR’*@€U
b×ç
</code>```

Can be waaaay shorter...

Try it online!

Title: Decompose a number!

Body:
Your task is to decompose a number using the format below.

This is similar to base conversion, except that instead of listing the digits in the base, you list the values, such that the list adds up to the input.

If the given base is \$n\$, then each number in the list must be in the form of \$k\times n^m\$, where \$0\le k<n\$ and \$m\$ is unique throughout the list.

Specs

Any reasonable input/output format. Your program/function takes 2 inputs and outputs a list.

Output list can be in any order.

0 can be excluded or included.

Leading 0s are allowed.

Built-ins are allowed.

Testcases

```<code>number base   converted list
input1 input2 output
123456 10     [100000,20000,3000,400,50,6] or [6,50,400,3000,20000,100000]
11     2      [8,2,1] or [0,0,0,0,8,0,2,1]
727    20     [400,320,7]
101    10     [100,1] or [100,0,1]
</code>```

Scoring

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

Body:
Jelly, 12 bytes

bLR’*@€U
b×ç

Can be waaaay shorter...

Try it online!


答:
TMP, 55 bytes

3a1.3b0.1;4+a>T8%a>xFFF14+b>a8%b>xFFF11~5164|b>a2$b$

Implementation in Lua can be found here: http://preview.ccode.gq/projects/TMP.lua

Title: Compute the Adler-32 checksum

Body:
TMP, 55 bytes

3a1.3b0.1;4+a>T8%a>xFFF14+b>a8%b>xFFF11~5<b>164|b>a2$b$

Implementation in Lua can be found here: http://preview.ccode.gq/projects/TMP.lua


问:
Build a word generator!
Your task is to create a program/function to replicate this word generator.

Details

Your program/function take two input. One input is the categories. The other input is the syllable types.

Categories

categories will consist of classes of letters.

For example, V=aeiou means that the letters a, e, i, o, and u will be classified under the category V.

Each category will have a 1-letter name in UPPERCASE.

The letters it contains will all be in lowercase.

Syllable types

For example CV would mean that the syllable will consist of a letter in category C and then a letter in category V.

For example, if C=bcd and V=ae, then the syllable can be ba, be, ca, ce, da, or de.

Your task

Your task is to generate 100 random words, each with a random length of 1-5 syllables, each chosen randomly in the syllable types, with the letter in each category chosen also randomly.

Specs

Any reasonable input/output format. I don't care how you input the list.

All inputs will be valid.

Scoring

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

Testcase

```<code>input1          input2    output
"C=st;V=aeiou"  "CV/CVC"  tasiti tese tossi tesis titi sese saset su sosastesisat sisosis sissa sata to sisas sese satetot sisuta tatote sa tetsesuti sossut ti seso tese tostutsasussi tutiset sasates tasa ta sa satso tastitta tetti sesita setetat tatsi tisetot sassu sessiso satessase sas ses totasta si tetsit titse sase totas sa ta sasesa tasa sostat sesi sissa tato tos tate sustosussatta sustas sassatote tesas sutat tatetatossos testisot tatta tissisisa sasese sesatus tito sisa satas sasisi so sasatustu sosses tetsa tese sestit sestu tisot sutastot sesu tet sotte sisute setotitsesi tita
</code>```

答:
Ruby, 80 bytes

gotta go fast

Input is a dictionary hash (for example, {'C' => ['b', 'c'], 'V' => ['a', 'e']}) and a list of syllable structures (for example, ['CV', 'VC'] or %w{CV VC}.

```<code>->c,s{100.times{puts (0..rand(5)).map{s.sample}.join.gsub(/./){|e|c[e].sample}}}
</code>```

For sample input:

```<code>c = {
    'C' => %w{r s t l n},
    'V' => %w{a e i o u}
}
s = %w{CV CVC}
</code>```

This produces a sample output:

```<code>salsun
lonlutunonnus
solitlaton
rusitar
lotol
ris
relussetsa
tanotte
nasun
sur
lusin
tuslu
nerunol
sorrelussenu
ni
nanro
nulila
ritlalatiso
nururlontensa
lilas
tatsisuto
lel
rerlisletnut
ler
netlo
sorora
surot
tilsasotisi
rilnolrati
lasrare
totni
surreratlaral
li
tullatilro
rusenoreto
lulnunen
nortille
tut
sanitare
soniserloras
tiritrattitsis
ratretrate
tesne
lastinsolta
sinirsitur
lulesuleno
li
sirurata
nutesnisitur
rulunna
natneretasi
lonre
les
laruletan
nitis
tarletu
tonrora
la
senru
seltotoniles
teransotutel
re
lulsirnilletus
nunanurlon
nunlortotsonna
nolun
tolso
nas
leltirninara
neltinlesla
lulutsisot
lesulusutnis
nolu
nun
tituntillini
ralteres
sasnirosse
tutorlari
nonlelletottan
lirsetutit
so
le
setse
susritterlilu
lorrirotri
linuritlilrat
rernilnelnutel
sulolletrolo
nisatellilru
tulene
tetnan
lisotoslersor
nerlani
ne
tunoletso
nonlontaroltun
rirrostarset
sotlonsiro
net
sutona
</code>```

Title: Build a word generator!

Body:
Ruby, 80 bytes

gotta go fast

Input is a dictionary hash (for example, {'C' => ['b', 'c'], 'V' => ['a', 'e']}) and a list of syllable structures (for example, ['CV', 'VC'] or %w{CV VC}.

->c,s{100.times{puts (0..rand(5)).map{s.sample}.join.gsub(/./){|e|c[e].sample}}}

For sample input:

c = {
    'C' => %w{r s t l n},
    'V' => %w{a e i o u}
}
s = %w{CV CVC}

This produces a sample output:

salsun
lonlutunonnus
solitlaton
rusitar
lotol
ris
relussetsa
tanotte
nasun
sur
lusin
tuslu
nerunol
sorrelussenu
ni
nanro
nulila
ritlalatiso
nururlontensa
lilas
tatsisuto
lel
rerlisletnut
ler
netlo
sorora
surot
tilsasotisi
rilnolrati
lasrare
totni
surreratlaral
li
tullatilro
rusenoreto
lulnunen
nortille
tut
sanitare
soniserloras
tiritrattitsis
ratretrate
tesne
lastinsolta
sinirsitur
lulesuleno
li
sirurata
nutesnisitur
rulunna
natneretasi
lonre
les
laruletan
nitis
tarletu
tonrora
la
senru
seltotoniles
teransotutel
re
lulsirnilletus
nunanurlon
nunlortotsonna
nolun
tolso
nas
leltirninara
neltinlesla
lulutsisot
lesulusutnis
nolu
nun
tituntillini
ralteres
sasnirosse
tutorlari
nonlelletottan
lirsetutit
so
le
setse
susritterlilu
lorrirotri
linuritlilrat
rernilnelnutel
sulolletrolo
nisatellilru
tulene
tetnan
lisotoslersor
nerlani
ne
tunoletso
nonlontaroltun
rirrostarset
sotlonsiro
net
sutona


问:
Watson-Crick palindromes

Problem

Create a function that can determine whether or not an arbitrary DNA string is a Watson-Crick palindrome. The function will take a DNA string and output a true  value if the string is a Watson-Crick palindrome and a false value if it is not. (True and False can also be represented as 1 and 0, respectively.)

The DNA string may either be in all uppercase or all lowercase depending on your preference.

Also, the DNA string will not be empty.

Explanation

A DNA string is a Watson-Crick palindrome when the complement of its reverse is equal to itself.

Given a DNA string, first reverse it, and then complement each character according to the DNA bases (A ↔ T and C ↔ G). If the original string is equal to the complemented-reverse string, it is a Watson-Crick palindrome.

For more, see this question. It is a different challenge where you must find the longest substring of a DNA string where that substring is a Watson-Crick palindrome.

Goal

This is code-golf and the shortest code wins.

Test Cases

The format is <input> = <output>.

```<code>ATCGCGAT = true
AGT = false
GTGACGTCAC = true
GCAGTGA = false
GCGC = true
AACTGCGTTTAC = false
ACTG = false
</code>```

答:
, 13 chars / 17 bytes

```<code>⟮ïĪ`ACGT”⟯ᴙ≔Ⅰ
</code>```

Try it here (Firefox only).

Explanation

Transliterate input from ACGT to TGCA and check if the resulting string is a palindrome.

Title: Watson-Crick palindromes

Body:
, 13 chars / 17 bytes

⟮ïĪ`ACGT”⟯ᴙ≔Ⅰ

Try it here (Firefox only).

Explanation

Transliterate input from ACGT to TGCA and check if the resulting string is a palindrome.


答:
Racket, 82 bytes

(define(d n b[a'()])(if(< n 1)a(d(/ n b)b(cons(*(modulo(floor n)b)(length a))a))))
```

I'm a winner (!)

Title: Decompose a number!

Body:
Racket, 82 bytes

(define(d n b[a'()])(if(< n 1)a(d(/ n b)b(cons(*(modulo(floor n)b)(length a))a))))

I'm a winner (!)


答:
Pyth - 18 bytes

Takes input as a dict and then one structure per line.

```<code>V100ssmmO@QkO.zhO5
</code>```

Try it online here.

Title: Build a word generator!

Body:
Your task is to create a program/function to replicate this word generator.

Details

Your program/function take two input. One input is the categories. The other input is the syllable types.

Categories

categories will consist of classes of letters.

For example, V=aeiou means that the letters a, e, i, o, and u will be classified under the category V.

Each category will have a 1-letter name in UPPERCASE.

The letters it contains will all be in lowercase.

Syllable types

For example CV would mean that the syllable will consist of a letter in category C and then a letter in category V.

For example, if C=bcd and V=ae, then the syllable can be ba, be, ca, ce, da, or de.

Your task

Your task is to generate 100 random words, each with a random length of 1-5 syllables, each chosen randomly in the syllable types, with the letter in each category chosen also randomly.

Specs

Any reasonable input/output format. I don't care how you input the list.

All inputs will be valid.

Scoring

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

Testcase

```<code>input1          input2    output
"C=st;V=aeiou"  "CV/CVC"  tasiti tese tossi tesis titi sese saset su sosastesisat sisosis sissa sata to sisas sese satetot sisuta tatote sa tetsesuti sossut ti seso tese tostutsasussi tutiset sasates tasa ta sa satso tastitta tetti sesita setetat tatsi tisetot sassu sessiso satessase sas ses totasta si tetsit titse sase totas sa ta sasesa tasa sostat sesi sissa tato tos tate sustosussatta sustas sassatote tesas sutat tatetatossos testisot tatta tissisisa sasese sesatus tito sisa satas sasisi so sasatustu sosses tetsa tese sestit sestu tisot sutastot sesu tet sotte sisute setotitsesi tita
</code>```

Body:
Pyth - 18 bytes

Takes input as a dict and then one structure per line.

V100ssmmO@QkO.zhO5

Try it online here.


答:
J, <s>20</s> 19 bytes

```<code>[(]*(^<:@#\.))#.inv
</code>```

Usage

```<code>   f =: [(]*(^<:@#\.))#.inv
   10 f 123456
100000 20000 3000 400 50 6
   2 f 11
8 0 2 1
   20 f 727
400 320 7
   10 f 101
100 0 1
</code>```

Explanation

```<code>[(]*(^<:@#\.))#.inv
              #.      Given a base and list of digits in that base,
                      converts it to an integer in base 10
                inv   Power conjunction by -1, creates an inverse
                      Now, this becomes a verb that given a base and an integer in base 10,
                      creates a list of digits in that base representing it
[                     Select the base and pass it along
         #\.          Tally each suffix of the list of base digits,
                      Counts down from n to 1
      <:              Decrements each value
        @             More specifically, decrement is composed with the tally and applied
                      together on each suffix
     ^                Raises each value x using base^x
  ]                   Selects the list of base digits
   *                  Multiply elementwise between each base power and base digit
</code>```

Title: Decompose a number!

Body:
J, <s>20</s> 19 bytes

[(]*(^<:@#\.))#.inv

Usage

   f =: [(]*(^<:@#\.))#.inv
   10 f 123456
100000 20000 3000 400 50 6
   2 f 11
8 0 2 1
   20 f 727
400 320 7
   10 f 101
100 0 1

Explanation

[(]*(^<:@#\.))#.inv
              #.      Given a base and list of digits in that base,
                      converts it to an integer in base 10
                inv   Power conjunction by -1, creates an inverse
                      Now, this becomes a verb that given a base and an integer in base 10,
                      creates a list of digits in that base representing it
[                     Select the base and pass it along
         #\.          Tally each suffix of the list of base digits,
                      Counts down from n to 1
      <:              Decrements each value
        @             More specifically, decrement is composed with the tally and applied
                      together on each suffix
     ^                Raises each value x using base^x
  ]                   Selects the list of base digits
   *                  Multiply elementwise between each base power and base digit


答:
x86-64 machine code function: <s>33</s> 32 bytes  (or <s>31</s> 30 bytes with an int[] input instead of char[])

x86-32 machine code function: 31 bytes

As a GNU C inline-asm code fragment: saves <s>2B</s> 1B (just the ret insn).

Commented source and test driver on github

The 64bit version is callable directly from C with the standard System V x86-64 ABI (using 2 dummy args to get args in the regs I want).  Custom calling conventions are not uncommon for asm code, so this is a bonus feature.

32bit machine code saves 1B, because merging the high and low halves with push16/push16 => pop32 only works in 32bit mode.  A 32bit function would need a custom calling convention.  We shouldn't hold that against it, but calling from C needs a wrapper function.

After processing 4096 ~ (ASCII 126) bytes, high = 0x3f040000, low = 0x7e001.  So high's most-significant bit isn't set yet.  My code takes advantage of this, sign-extending eax into edx:eax with cdq as a way of zeroing edx.

```<code># See the NASM source below
0000000000401120 <golfed_adler32_amd64>:
  401120:       31 c0                   xor    eax,eax
  401122:       99                      cdq
  401123:       8d 7a 01                lea    edi,[rdx+0x1]
0000000000401126 <golfed_adler32_amd64.byteloop>:
  401126:       ac                      lods   al,BYTE PTR ds:[rsi]
  401127:       01 c7                   add    edi,eax
  401129:       01 fa                   add    edx,edi
  40112b:       e2 f9                   loop   401126 <golfed_adler32_amd64.byteloop>
000000000040112d <golfed_adler32_amd64.end>:
  40112d:       66 b9 f1 ff             mov    cx,0xfff1
  401131:       92                      xchg   edx,eax
  401132:       99                      cdq
  401133:       f7 f1                   div    ecx
  401135:       52                      push   rdx
  401136:       97                      xchg   edi,eax
  401137:       99                      cdq
  401138:       f7 f1                   div    ecx
  40113a:       66 52                   push   dx      # this is the diff from last version: evil push/pop instead of shift/add
  40113c:       58                      pop    rax
  40113d:       66 5a                   pop    dx
  40113f:       c3                      ret
0000000000401140 <golfed_adler32_amd64_end>:
</code>```

0x40 - 0x20 = 32 bytes.

Commented NASM source:

tricks:

xchg eax, r32 is one byte; cheaper than mov.  8086 needed data in ax for a lot more stuff than >= 386, so they decided to spend a lot of opcode-space on the now-rarely-used xchg ax, r16.

Mixing push64 and push16 for merging high and low into a single register saves reg-reg data movement instructions around two divs.  The 32bit version of this trick works even better: push16 / push16 / pop32 is only 5B total, not 6.

Since we push/pop, this isn't safe for inline asm in the SysV amd64 ABI (with a red zone).

```<code>golfed_adler32_amd64_v3:   ; (int dummy, const char *buf, int dummy, uint64_t len)

    ;; args: len in rcx,  const char *buf in rsi
    ;; Without dummy args, (unsigned len, const char *buf),  mov ecx, edi is the obvious solution, costing 2 bytes

    xor     eax,eax         ; scratch reg for loading bytes
    cdq                     ; edx: high=0
    lea     edi, [rdx+1]    ; edi: low=1
    ;jrcxz  .end            ; We don't handle len=0.  unlike rep, loop only checks rcx after decrementing
.byteloop:
    lodsb                   ; upper 24b of eax stays zeroed (no partial-register stall on Intel P6/SnB-family CPUs, thanks to the xor-zeroing)
    add     edi, eax        ; low += zero_extend(buf[i])
    add     edx, edi        ; high += low
    loop   .byteloop
.end:
    ;; exit when ecx = 0, eax = last byte of buf
    ;; lodsb at this point would load the terminating 0 byte, conveniently leaving eax=0

    mov     cx, 65521       ; ecx = m = adler32 magic constant.  (upper 16b of ecx is zero from the loop exit condition.  This saves 1B over mov r32,imm32)
    ;sub    cx, (65536 - 65521) ; the immediate is small enough to use the imm8 encoding.  No saving over mov, though, since this needs a mod/rm byte

    xchg    eax, edx        ; eax = high,  edx = buf[last_byte]
    cdq                     ; could be removed if we could arrange things so the loop ended with a load of the 0 byte

    div     ecx             ; div instead of idiv to fault instead of returning wrong answers if high has overflowed to negative.  (-1234 % m is negative)
    push    rdx             ; push high%m and 6B of zero padding

    xchg    eax, edi        ; eax=low
    cdq
    div     ecx             ; edx = low%m

    ;; concatenate the two 16bit halves of the result by putting them in contiguous memory
    push    dx              ; push low%m with no padding
    pop     rax             ; pop  high%m << 16 | low%m   (x86 is little-endian)

    pop     dx              ; add rsp, 2 to restore the stack pointer

    ;; outside of 16bit code, we can't justify returning the result in the dx:ax register pair
    ret
golfed_adler32_amd64_end_v3:
</code>```

I also considered using rcx as an array index, instead of having two loop counters, but adler32(s) != adler32(reverse(s)).  So we couldn't use loop.  Counting from -len up towards zero and using movzx r32, [rsi+rcx] just uses way too many bytes.

If we want to consider incrementing the pointer ourself, 32bit code is probably the way to go.  Even the x32 ABI (32bit pointers) isn't sufficient, because inc esi is 2B on amd64, but 1B on i386.  It appears hard to beat xor eax,eax / lodsb / loop: 4B total to get each element in turn zero-extended into eax.  inc esi / movzx r32, byte [esi] / loop is 5B.

scas is another option for incrementing a pointer with a 1B instruction in 64bit mode.  (rdi/edi instead of rsi, so we'd take the pointer arg in rdi).  We can't use the flag result from scas as a loop condition, though, because we don't want to keep eax zeroed.  Different register allocation could maybe save a byte after the loop.

int[] input

The full function taking uint8_t[] is the "main" answer, because it's a more interesting challenge.  Unpacking to int[] is an unreasonable thing to ask our caller to do in this language, but it does save 2B.

If we take our input as an unpacked array of 32bit integers, we can save one byte easily (use lodsd and replace xor eax,eax / cdq with just xor edx,edx).

We can save another byte by zeroing edx with lodsd/cdq, and re-arranging the loop so it loads the terminating 0 element before exiting.  (We're still assuming it exists, even though this is an array of int, not a string).

```<code>; untested: I didn't modify the test driver to unpack strings for this
golfed_adler32_int_array:
    ; xor   edx,edx
    lodsd                   ; first element. only the low byte non-zero
    cdq                     ; edx: high=0
    lea     edi, [rdx+1]    ; edi: low=1
    ;jrcxz  .end            ; handle len=0?  unlike rep, loop only checks rcx after decrementing
.intloop:
    add     edi, eax        ; low += buf[i]
    add     edx, edi        ; high += low
    lodsd                   ; load buf[i+1] for next iteration
    loop   .intloop
.end:
    ;; exit when ecx = 0, eax = terminating 0

    xchg    eax, edx
    ;cdq               ; edx=0 already, ready for div
    ; same as the char version
</code>```

I also made an untested version that uses scasd (1B version of add edi,4) and add eax, [rdi] instead of lodsd, but it's also 30 bytes.  The savings from having high in eax at the end of the loop are balanced out by larger code elsewhere.  It has the advantage of not depending on a terminating 0 element in the input, though, which is maybe unreasonable for an unpacked array where we're also given the length explicitly.

C++11 test driver

See the github link.  This answer was getting too big, and the test driver got more features with bigger code.

Title: Compute the Adler-32 checksum

Body:
Background

Adler-32 is a 32-bit checksum invented by Mark Adler in 1995 which is part of the widely used zlib library (also developed by Adler). Adler-32 is not as reliable as a 32-bit cyclic redundancy check, but – at least in software  – it is much faster and easier to implement.

Definition

Let B = [b1, ⋯, bn] be a byte array.

The Adler-32 checksum of B is defined as the result of low + 65536 × high, where:

low := ((1 + b1 + ⋯ + bn) mod 65521)

high := (((1 + b1) + (1 + b1 + b2) + ⋯ (1 + b1 + ⋯ + bn)) mod 65521)

Task

Given a byte array as input, compute and return its Adler-32 checksum, abiding to the following.

You can take the input as an array of bytes or integers, or as a string.

In both cases, only bytes corresponding to printable ASCII characters will occur in the input.

You may assume that the length of the input will satisfy 0 < length ≤ 4096.

If you choose to print the output, you may use any positive base up to and including 256.

If you choose unary, make sure interpreter can handle up to 232 - 983056 bytes of output on a machine with 16 GiB of RAM.

Built-ins that compute the Adler-32 checksum are forbidden.

Standard code-golf rules apply.

Test cases

```<code>String:     "Eagles are great!"
Byte array: [69, 97, 103, 108, 101, 115, 32, 97, 114, 101, 32, 103, 114, 101, 97, 116, 33]
Checksum:   918816254

String:     "Programming Puzzles & Code Golf"
Byte array: [80, 114, 111, 103, 114, 97, 109, 109, 105, 110, 103, 32, 80, 117, 122, 122, 108, 101, 115, 32, 38, 32, 67, 111, 100, 101, 32, 71, 111, 108, 102]
Checksum:   3133147946

String:     "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
Byte array: [126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126]
Checksum:   68095937

String:     <1040 question marks>
Byte array: <1040 copies of 63>
Checksum:   2181038080
</code>```

Body:
x86-64 machine code function: <s>33</s> 32 bytes  (or <s>31</s> 30 bytes with an int[] input instead of char[])

x86-32 machine code function: 31 bytes

As a GNU C inline-asm code fragment: saves <s>2B</s> 1B (just the ret insn).

Commented source and test driver on github

The 64bit version is callable directly from C with the standard System V x86-64 ABI (using 2 dummy args to get args in the regs I want).  Custom calling conventions are not uncommon for asm code, so this is a bonus feature.

32bit machine code saves 1B, because merging the high and low halves with push16/push16 => pop32 only works in 32bit mode.  A 32bit function would need a custom calling convention.  We shouldn't hold that against it, but calling from C needs a wrapper function.

After processing 4096 ~ (ASCII 126) bytes, high = 0x3f040000, low = 0x7e001.  So high's most-significant bit isn't set yet.  My code takes advantage of this, sign-extending eax into edx:eax with cdq as a way of zeroing edx.

# See the NASM source below
0000000000401120 <golfed_adler32_amd64>:
  401120:       31 c0                   xor    eax,eax
  401122:       99                      cdq
  401123:       8d 7a 01                lea    edi,[rdx+0x1]
0000000000401126 <golfed_adler32_amd64.byteloop>:
  401126:       ac                      lods   al,BYTE PTR ds:[rsi]
  401127:       01 c7                   add    edi,eax
  401129:       01 fa                   add    edx,edi
  40112b:       e2 f9                   loop   401126 <golfed_adler32_amd64.byteloop>
000000000040112d <golfed_adler32_amd64.end>:
  40112d:       66 b9 f1 ff             mov    cx,0xfff1
  401131:       92                      xchg   edx,eax
  401132:       99                      cdq
  401133:       f7 f1                   div    ecx
  401135:       52                      push   rdx
  401136:       97                      xchg   edi,eax
  401137:       99                      cdq
  401138:       f7 f1                   div    ecx
  40113a:       66 52                   push   dx      # this is the diff from last version: evil push/pop instead of shift/add
  40113c:       58                      pop    rax
  40113d:       66 5a                   pop    dx
  40113f:       c3                      ret
0000000000401140 <golfed_adler32_amd64_end>:

0x40 - 0x20 = 32 bytes.

Commented NASM source:

tricks:

xchg eax, r32 is one byte; cheaper than mov.  8086 needed data in ax for a lot more stuff than >= 386, so they decided to spend a lot of opcode-space on the now-rarely-used xchg ax, r16.

Mixing push64 and push16 for merging high and low into a single register saves reg-reg data movement instructions around two divs.  The 32bit version of this trick works even better: push16 / push16 / pop32 is only 5B total, not 6.

Since we push/pop, this isn't safe for inline asm in the SysV amd64 ABI (with a red zone).

golfed_adler32_amd64_v3:   ; (int dummy, const char *buf, int dummy, uint64_t len)

    ;; args: len in rcx,  const char *buf in rsi
    ;; Without dummy args, (unsigned len, const char *buf),  mov ecx, edi is the obvious solution, costing 2 bytes

    xor     eax,eax         ; scratch reg for loading bytes
    cdq                     ; edx: high=0
    lea     edi, [rdx+1]    ; edi: low=1
    ;jrcxz  .end            ; We don't handle len=0.  unlike rep, loop only checks rcx after decrementing
.byteloop:
    lodsb                   ; upper 24b of eax stays zeroed (no partial-register stall on Intel P6/SnB-family CPUs, thanks to the xor-zeroing)
    add     edi, eax        ; low += zero_extend(buf[i])
    add     edx, edi        ; high += low
    loop   .byteloop
.end:
    ;; exit when ecx = 0, eax = last byte of buf
    ;; lodsb at this point would load the terminating 0 byte, conveniently leaving eax=0

    mov     cx, 65521       ; ecx = m = adler32 magic constant.  (upper 16b of ecx is zero from the loop exit condition.  This saves 1B over mov r32,imm32)
    ;sub    cx, (65536 - 65521) ; the immediate is small enough to use the imm8 encoding.  No saving over mov, though, since this needs a mod/rm byte

    xchg    eax, edx        ; eax = high,  edx = buf[last_byte]
    cdq                     ; could be removed if we could arrange things so the loop ended with a load of the 0 byte

    div     ecx             ; div instead of idiv to fault instead of returning wrong answers if high has overflowed to negative.  (-1234 % m is negative)
    push    rdx             ; push high%m and 6B of zero padding

    xchg    eax, edi        ; eax=low
    cdq
    div     ecx             ; edx = low%m

    ;; concatenate the two 16bit halves of the result by putting them in contiguous memory
    push    dx              ; push low%m with no padding
    pop     rax             ; pop  high%m << 16 | low%m   (x86 is little-endian)

    pop     dx              ; add rsp, 2 to restore the stack pointer

    ;; outside of 16bit code, we can't justify returning the result in the dx:ax register pair
    ret
golfed_adler32_amd64_end_v3:

I also considered using rcx as an array index, instead of having two loop counters, but adler32(s) != adler32(reverse(s)).  So we couldn't use loop.  Counting from -len up towards zero and using movzx r32, [rsi+rcx] just uses way too many bytes.

If we want to consider incrementing the pointer ourself, 32bit code is probably the way to go.  Even the x32 ABI (32bit pointers) isn't sufficient, because inc esi is 2B on amd64, but 1B on i386.  It appears hard to beat xor eax,eax / lodsb / loop: 4B total to get each element in turn zero-extended into eax.  inc esi / movzx r32, byte [esi] / loop is 5B.

scas is another option for incrementing a pointer with a 1B instruction in 64bit mode.  (rdi/edi instead of rsi, so we'd take the pointer arg in rdi).  We can't use the flag result from scas as a loop condition, though, because we don't want to keep eax zeroed.  Different register allocation could maybe save a byte after the loop.

int[] input

The full function taking uint8_t[] is the "main" answer, because it's a more interesting challenge.  Unpacking to int[] is an unreasonable thing to ask our caller to do in this language, but it does save 2B.

If we take our input as an unpacked array of 32bit integers, we can save one byte easily (use lodsd and replace xor eax,eax / cdq with just xor edx,edx).

We can save another byte by zeroing edx with lodsd/cdq, and re-arranging the loop so it loads the terminating 0 element before exiting.  (We're still assuming it exists, even though this is an array of int, not a string).

; untested: I didn't modify the test driver to unpack strings for this
golfed_adler32_int_array:
    ; xor   edx,edx
    lodsd                   ; first element. only the low byte non-zero
    cdq                     ; edx: high=0
    lea     edi, [rdx+1]    ; edi: low=1
    ;jrcxz  .end            ; handle len=0?  unlike rep, loop only checks rcx after decrementing
.intloop:
    add     edi, eax        ; low += buf[i]
    add     edx, edi        ; high += low
    lodsd                   ; load buf[i+1] for next iteration
    loop   .intloop
.end:
    ;; exit when ecx = 0, eax = terminating 0

    xchg    eax, edx
    ;cdq               ; edx=0 already, ready for div
    ; same as the char version

I also made an untested version that uses scasd (1B version of add edi,4) and add eax, [rdi] instead of lodsd, but it's also 30 bytes.  The savings from having high in eax at the end of the loop are balanced out by larger code elsewhere.  It has the advantage of not depending on a terminating 0 element in the input, though, which is maybe unreasonable for an unpacked array where we're also given the length explicitly.

C++11 test driver

See the github link.  This answer was getting too big, and the test driver got more features with bigger code.


问:
Express a number with only 0-9 and the four operations

Explanation

Befunge is a two-dimensional program that uses stacks.

That means, to do 5 + 6, you write 56+, meaning:

```<code>56+
5    push 5 into stack
 6   push 6 into stack
  +  pop the first two items in the stack and add them up, and push the result into stack

(to those of you who do not know stacks, "push" just means add and "pop" just means take off)
</code>```

However, as the intelligent of you have observed, we cannot push the number 56 directly into the stack.

To do so, we must write 78* instead, which multiplies 7 and 8 and pushes the product into the stack.

Details

Input can be taken in any format, meaning it can be STDIN or not, at the programmer's discretion.

The input will be a positive integer (no bonus for including 0 or negative integers).

The output will be a string consisting of only these characters: 0123456789+-*/ (I would not use % modulo.)

The goal is to find the shortest string that can represent the input, using the format described above.

For example, if the input is 123, then the output would be 67*99*+. The output should be evaluated from left to right.

If there are more than one acceptable outputs (e.g. 99*67*+ is also acceptable), any one can be printed (no bonus for printing all of them).

Further Explanation

If you still do not understand how 67*99*+ evaluates to 123, here is a detailed explanation.

```<code>stack    |operation|explanation
          67*99*+
[6]       6         push 6 to stack
[6,7]      7        push 7 to stack
[42]        *       pop two from stack and multiply, then put result to stack
[42,9]       9      push 9 to stack
[42,9,9]      9     push 9 to stack
[42,81]        *    pop two from stack and multiply, then put result to stack
[123]           +   pop two from stack and add, then put result to stack
</code>```

TL;DR

The program needs to find the shortest string that can represent the input (number), using the format specified above.

Notes

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

Disambiguation

The - can either be x-y or y-x, at the programmer's discretion. However, the choice must be consistent within the solution. Likewise for the /.

Sample program

Lua, 1862 bytes (try it online)

Since I am the author, I will not golf it at all.

Explanation:

```<code>This uses the depth-first search method.
</code>```

More about depth-first search: here.

The program:

```<code>local input = (...) or 81

local function div(a,b)
    if b == 0 then
        return "error"
    end
    local result = a/b
    if result > 0 then
        return math.floor(result)
    else
        return math.ceil(result)
    end
end

local function eval(expr)
    local stack = {}
    for i=1,#expr do
        local c = expr:sub(i,i)
        if c:match('[0-9]') then
            table.insert(stack, tonumber(c))
        else
            local a = table.remove(stack)
            local b = table.remove(stack)
            if a and b then
                if c == '+' then
                    table.insert(stack, a+b)
                elseif c == '-' then
                    table.insert(stack, b-a)
                elseif c == '*' then
                    table.insert(stack, a*b)
                elseif c == '/' then
                    local test = div(b,a)
                    if test == "error" then
                        return -1
                    else
                        table.insert(stack, a+b)
                    end
                end
            else
                return -1
            end
        end
    end
    return table.remove(stack) or -1
end

local samples, temp = {""}, {}

while true do
    temp = {}
    for i=1,#samples do
        local s = samples[i]
        table.insert(temp, s..'0')
        table.insert(temp, s..'1')
        table.insert(temp, s..'2')
        table.insert(temp, s..'3')
        table.insert(temp, s..'4')
        table.insert(temp, s..'5')
        table.insert(temp, s..'6')
        table.insert(temp, s..'7')
        table.insert(temp, s..'8')
        table.insert(temp, s..'9')
        table.insert(temp, s..'+')
        table.insert(temp, s..'-')
        table.insert(temp, s..'*')
        table.insert(temp, s..'/')
    end
    for i=1,#temp do
        if input == eval(temp[i]) then
            print(temp[i])
            return
        end
    end
    samples = temp
end
</code>```

Bonus

A cake for you if you use Befunge (or any variant of it) to write the code.

答:
Python 3, 183 bytes

```<code>e,n=enumerate,input()
v=list('0123456789')+[' '*n]*n*2
for i,s in e(v):
 for j,t in e(v):
  for o,k in zip('+*-',(i+j,i*j,i-j)):
   if 9<k<2*n:v[k]=min(v[k],s+t+o,key=len)
print(v[n])
</code>```

Speed isn't totally unreasonable (123, 221, 1237, 6551 finish on the order of seconds or minutes). Changing the if statement to if j<=i and <k<2*n speeds it up more, at the cost of 9 more bytes. I left out division (/), because I can't see how it would be needed.

Body:
Python 3, 183 bytes

e,n=enumerate,input()
v=list('0123456789')+[' '*n]*n*2
for i,s in e(v):
 for j,t in e(v):
  for o,k in zip('+*-',(i+j,i*j,i-j)):
   if 9<k<2*n:v[k]=min(v[k],s+t+o,key=len)
print(v[n])

Speed isn't totally unreasonable (123, 221, 1237, 6551 finish on the order of seconds or minutes). Changing the if statement to if j<=i and <k<2*n speeds it up more, at the cost of 9 more bytes. I left out division (/), because I can't see how it would be needed.


问:
Make a search engine
You need to make a program, that when giving a list and a string, searches on the list for items that contains the string.

Examples:

```<code>Input: th [thing, awesome, potato, example]
Output: thing (Because it starts with "th")

Input: ing [thing, potato]
Output: thing (Because it ends with "ing")

Input: tat [thing, potato]
Output: potato (Because it contains "tat")

Input: tat [tato, potato]
Output: tato, potato (If there are 2 or more results matching, print all of them)
</code>```

Remember, this is code golf, so the shortest code wins.

Leaderboard

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

/* Configuration */

var QUESTION_ID = 72079; // 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 = 48934; // 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

```

答:
Racket, 49 bytes

(λ(l s)(filter-map(curryr string-contains? s)l))
```

Title: Make a search engine