答:
bash + GNU coreutils, 109 Bytes

```<code>l=${#1}
for i in `seq 0 $l`;{
for j in `seq $((l-i))`;{
for k in `seq $i`;{ printf ' ';}
echo ${1:i:j}
}; }
</code>```

Maybe there is a shorter solution, but this is the best that came into my mind. Uniqueness of chracters does not matter here.

Title: Exploded substrings

Body:
Introduction

Let's observe the string abc. The substrings that can be made from this are:

```<code>a, ab, abc, b, bc, c
</code>```

We now need to align them under the initial string, like this:

```<code>abc
a
 b
  c
ab
 bc
abc
</code>```

The order of the string doesn't matter, so this is also perfectly valid:

```<code>abc
a
ab
abc
 b
 bc
  c
</code>```

So, the substring is positioned under the location of the substring in the initial string. So for abcdef and the substring cde, it would look like this:

```<code>abcdef
  cde
</code>```

The Task

The task is to align all substrings with a length greater than 0, like shown above. You can assume that the string itself will only contain alphabetic characters and has at least 1 character. For the padding, you can use a space or some other non-alphabetic printable ASCII character (32 - 127). Maybe not necessary to mention, but the string itself will only contain unique characters, so not like aba, since the a occurs twice.

Test cases

Input: abcde

Possible output:

```<code>a
ab
abc
abcd
abcde
 b
 bc
 bcd
 bcde
  c
  cd
  cde
   d
   de
    e
</code>```

Input: abcdefghij

Possible output:

```<code>a
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
abcdefghij
 b
 bc
 bcd
 bcde
 bcdef
 bcdefg
 bcdefgh
 bcdefghi
 bcdefghij
  c
  cd
  cde
  cdef
  cdefg
  cdefgh
  cdefghi
  cdefghij
   d
   de
   def
   defg
   defgh
   defghi
   defghij
    e
    ef
    efg
    efgh
    efghi
    efghij
     f
     fg
     fgh
     fghi
     fghij
      g
      gh
      ghi
      ghij
       h
       hi
       hij
        i
        ij
         j
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

Body:
bash + GNU coreutils, 109 Bytes

l=${#1}
for i in `seq 0 $l`;{
for j in `seq $((l-i))`;{
for k in `seq $i`;{ printf ' ';}
echo ${1:i:j}
}; }

Maybe there is a shorter solution, but this is the best that came into my mind. Uniqueness of chracters does not matter here.


问:
The Back-and-Forth Sequence
Imagine a path made up of < and > and ending in a @, e.g.

```<code>><>@
</code>```

A walker starts on the left-most cell. He will traverse the path as follows:

If the walker is on a @ cell, he's reached the goal and is done.

If the walker is on a > cell, the entire path shifts one step to the right, cyclically, taking the walker with it.

If the walker is on a < cell, the entire path shifts one step to the left, cyclically, taking the walker with it.

Afterwards, the walker takes a single step. If he's at either end of the path, he moves away from the end. Otherwise he keeps moving in the direction he moved on the last step (ignoring the rotation), walking right initially.

Let's work through the above example. The walker's position is marked with ^:

```<code>><>@   --rotate-->  @><>
^                    ^
step right (first step):
@><>   --rotate-->  ><>@
  ^                  ^
step right:
><>@   --rotate-->  @><>
  ^                    ^
step left (dead end):
@><>   --rotate-->  ><>@
  ^                  ^
step left:
><>@   --rotate-->  @><>
^                    ^
step left:
@><>   Goal reached!
^
</code>```

The walker visited 6 cells in the process (including the starting cell as well as the @, and counting each cell as often as it's visited).

Here is a small example, where the walker is transported across the edges by a rotation:

```<code>>>@   --rotate-->  @>>
^                   ^
step right (first step):
@>>   --rotate-->  >@>
  ^                ^
step right (dead end):
>@>   Goal reached!
 ^
</code>```

This time the walker visited 3 cells.

We can easily turn this into an integer sequence:

You're given a positive integer N, e.g. 9.

You compute the the binary representation of this integer, e.g. 1001.

Then turn 1 into > and 0 into < and append a @: ><<>@.

We associate with N the number of cells visited by the walker in the number constructed this way.

The first few elements of the resulting sequence are:

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

This may seem quite arbitrary, but the resulting sequence actually turns out to have a lot of structure:

For reference, you can find the first 2048 numbers of the sequence in this pastebin.

The Challenge

You guessed it: you're to compute the above sequence. You can do that one of three ways:

You can produce an infinite sequence (while memory permits), either by continuously outputting (separated by non-numeric characters) values or by using some form of infinite generator in languages that support them. If you print an infinite stream to STDOUT, you don't have to print the numbers one by one, but make sure that every number would be printed after a finite amount of time (and in order). If you use this option, you should not take any input.

You can take an integer N as input and produce the Nth term of the sequence.

You can take an integer N as input and produce everything up to the Nth term of the sequence, either as a list or string using an unambiguous separator.

Since I don't want to penalise languages which can't easily convert between bases, instead of the integer N you may instead take the binary representation of N, using 0s and 1s as usual (as a list or string), with the most-significant bit first.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

Standard code-golf rules apply.

Background

This actually computes the number of "ticks" a straight-forward interpreter of my esoteric programming language Labyrinth would need to interpret the "path" as source code. In that case, the "walker" is simply the instruction pointer (which has a position and a direction), the @ command terminates the program and < and > are source-code modification commands.

答:
JavaScript (ES6), 65 bytes

```<code>s=>(l=s.length+1)%2|!(m=s.match(`(0*1){$l/2}}`))?l:m[0].length*2
</code>```

Accepts a binary string. Uses the bounce check from the various other answers.

ContentLicense: CC BY-SA 3.0

Title: The Back-and-Forth Sequence

Body:
JavaScript (ES6), 65 bytes

s=>(l=s.length+1)%2|!(m=s.match(`(0*1){$l/2}}`))?l:m[0].length*2

Accepts a binary string. Uses the bounce check from the various other answers.


问:
Calculate the Kronecker Product
Related, but very different.

In the examples below, \$A\$ and \$B\$ will be \$2\times2\$ matrices, and the matrices are one-indexed.

A Kronecker product has the following properties:

```<code>A⊗B =  A(1,1)*B   A(1,2)*B
        A(2,1)*B   A(2,2)*B

     =  A(1,1)*B(1,1)   A(1,1)*B(1,2)   A(1,2)*B(1,1)   A(1,2)*B(1,2)
        A(1,1)*B(2,1)   A(1,1)*B(2,2)   A(1,2)*B(2,1)   A(1,2)*B(2,2)
        A(2,1)*B(1,1)   A(2,1)*B(1,2)   A(2,2)*B(1,1)   A(2,2)*B(1,2)
        A(2,2)*B(2,1)   A(2,2)*B(1,2)   A(2,2)*B(2,1)   A(2,2)*B(2,2)
</code>```

Challenge: Given two matrices, \$A\$ and \$B\$, return \$A\otimes B\$.

The size of the matrices will be at least \$1\times1\$. The maximum size will be whatever your computer / language can handle by default, but minimum \$5\times5\$ input.

All input values will be non-negative integers

Builtin functions that calculate Kronecker products or Tensor/Outer products are not allowed

In general: Standard rules regarding I/O format, program & functions, loopholes etc.

Test cases:

```<code>A =
     1     2
     3     4
B =
     5     6
     7     8
A⊗B =
     5     6    10    12
     7     8    14    16
    15    18    20    24
    21    24    28    32

B⊗A =
     5    10     6    12
    15    20    18    24
     7    14     8    16
    21    28    24    32
------------------------
A =
     1
     2
B =
     1     2

A⊗B =
     1     2
     2     4
------------------------
A =
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

B =
     1     1
     0     1

A⊗B  =
    16    16     2     2     3     3    13    13
     0    16     0     2     0     3     0    13
     5     5    11    11    10    10     8     8
     0     5     0    11     0    10     0     8
     9     9     7     7     6     6    12    12
     0     9     0     7     0     6     0    12
     4     4    14    14    15    15     1     1
     0     4     0    14     0    15     0     1

B⊗A =
    16     2     3    13    16     2     3    13
     5    11    10     8     5    11    10     8
     9     7     6    12     9     7     6    12
     4    14    15     1     4    14    15     1
     0     0     0     0    16     2     3    13
     0     0     0     0     5    11    10     8
     0     0     0     0     9     7     6    12
     0     0     0     0     4    14    15     1
------------------------

A = 2
B = 5
A⊗B = 10
</code>```

答:
Julia, <s>40</s> <s>39</s> 37 bytes

```<code>A%B=hvcat(sum(A^0),map(a->a*B,A')...)
</code>```

Try it online!

How it works

For matrices A and B, map(a->a*B,A') computes the Kronecker product A⊗B.

The result is a vector of matrix blocks with the dimensions of B.

We have to transpose A (with ') since matrices are stored in column-major order.

sum(A^0) computes the sum of all entries of the identity matrix of A's dimensions. For an n×n matrix A, this yields n.

With first argument n, hvcat concatenates n matrix blocks horizontally, and the resulting (larger) blocks vertically.

ContentLicense: CC BY-SA 4.0

Title: Calculate the Kronecker Product

Body:
Julia, <s>40</s> <s>39</s> 37 bytes

A%B=hvcat(sum(A^0),map(a->a*B,A')...)

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

How it works

For matrices A and B, map(a->a*B,A') computes the Kronecker product A⊗B.

The result is a vector of matrix blocks with the dimensions of B.

We have to transpose A (with ') since matrices are stored in column-major order.

sum(A^0) computes the sum of all entries of the identity matrix of A's dimensions. For an n×n matrix A, this yields n.

With first argument n, hvcat concatenates n matrix blocks horizontally, and the resulting (larger) blocks vertically.


问:
Inverse function
Wouldn't it be neat if programming functions could be inverted, just like the mathematical function they implement?

Write a function (or program) that takes one input x in any form, that outputs ln(x).

When the bytes of the program are reordered/reversed so that the first byte now is the last byte, it should take one input x in any form and output e^x instead.

Your answer must have at least 3 correct significant figures.

Approximations are fine, as long as they have at least 3 correct significant figures.

Your code must be in the same programming language both forwards and backwards.

Let's say this program implements ln(x):

```<code>abc你好
</code>```

Then this program has to implement e^x:

```<code>\xBD\xA5\xE5\xA0\xBD\xE4cba
</code>```

Gold star if you use a language without float support.

This is a weird form of code-golf, so the shortest program wins.

答:
Fuzzy Octo Guacamole, 7 bytes

non-competing, FOG is newer than the challenge

```<code>EZO@pZE
</code>```

This is the equivalent of a function in FOG.  It assumes the input is on the stack. This can be assigned to a function by the code "EZO@pZE""f"o, where f is any single-char name you want to assign.  Then use it like any other command. Example: "EZO@pZE"'f'o^f.

Explanation:

```<code>EZO@pZE
E       # Push E (2.718....)
 Z      # Reverse stack (it is now [e, input])
  O     # log(x, y) which is ln(input)
   @    # Exit. (implicit output) Nothing after this gets run.
    p   # x^y (power function)
     Z  # Reverse stack
      E # Push E.
</code>```

Reversed:

```<code>EZp@OZE
E       # Push E (2.718....)
 Z      # Reverse stack (it is now [e, input])
  O     # x^y (power function)
   @    # Exit. (implicit output) Nothing after this gets run.
    p   # log(x, y) which is ln(input)
     Z  # Reverse stack
      E # Push E.
</code>```

Title: Inverse function

Body:
Fuzzy Octo Guacamole, 7 bytes

non-competing, FOG is newer than the challenge

EZO@pZE

This is the equivalent of a function in FOG.  It assumes the input is on the stack. This can be assigned to a function by the code "EZO@pZE""f"o, where f is any single-char name you want to assign.  Then use it like any other command. Example: "EZO@pZE"'f'o^f.

Explanation:

EZO@pZE
E       # Push E (2.718....)
 Z      # Reverse stack (it is now [e, input])
  O     # log(x, y) which is ln(input)
   @    # Exit. (implicit output) Nothing after this gets run.
    p   # x^y (power function)
     Z  # Reverse stack
      E # Push E.

Reversed:

EZp@OZE
E       # Push E (2.718....)
 Z      # Reverse stack (it is now [e, input])
  O     # x^y (power function)
   @    # Exit. (implicit output) Nothing after this gets run.
    p   # log(x, y) which is ln(input)
     Z  # Reverse stack
      E # Push E.


问:
Calculating (3 + sqrt(5))^n exactly
Today your goal is to find integers a and b given non-negative integer n such that:

You should write a program or a function that takes parameter n and outputs a and b in a format of your choice.

Standard loopholes apply. Additionally, it's intended that you implement the above problem using basic arithmetic yourself. So you may not use built-in exact algebra functionality, rationals, or functions implementing non-trivial mathematical constructs (for example the Lucas sequence).

Shortest code in bytes wins.

Example input/output:

0 → 1, 0

  1 → 3, 1

  2 → 14, 6

  3 → 72, 32

  4 → 376, 168

  5 → 1968, 880

  6 → 10304, 4608

  7 → 53952, 24128

  8 → 282496, 126336

  9 → 1479168, 661504

Title: Calculating (3 + sqrt(5))^n exactly

Body:
C/C++ 89 bytes

void g(int n,long&a,long&b){if(n){long j,k;g(n-1,j,k);a=3*j+5*k;b=j+3*k;}else{a=1;b=0;}}

Formatted:

    void g(int n, long&a, long&b) {
if (n) {
    long j, k;
    g(n - 1, j, k);
    a = 3 * j + 5 * k;
    b = j + 3 * k;
} else {
    a = 1;
    b = 0;
}}

Same concept:

void get(int n, long &a, long& b) {
    if (n == 0) {
        a = 1;
        b = 0;
        return;
    }
    long j, k;
    get(n - 1, j, k);
    a = 3 * j + 5 * k;
    b = j + 3 * k;
}

The test bench:

#include <iostream>
using namespace std;
int main() {
    long a, b;
    for (int i = 0; i < 55; i++) {
        g(i, a, b);
        cout << i << "-> " << a << ' ' << b << endl;
    }
    return 0;
}

The output:

0-> 1 0
1-> 3 1
2-> 14 6
3-> 72 32
4-> 376 168
5-> 1968 880
6-> 10304 4608
7-> 53952 24128
8-> 282496 126336
9-> 1479168 661504
10-> 7745024 3463680
11-> 40553472 18136064
12-> 212340736 94961664
13-> 1111830528 497225728
14-> 5821620224 2603507712
15-> 30482399232 13632143360
16-> 159607914496 71378829312
17-> 835717890048 373744402432
18-> 4375875682304 1956951097344
19-> 22912382533632 10246728974336
20-> 119970792472576 53652569456640
21-> 628175224700928 280928500842496
22-> 3289168178315264 1470960727228416
23-> 17222308171087872 7702050360000512
24-> 90177176313266176 40328459251089408
25-> 472173825195245568 211162554066534400
26-> 2472334245918408704 1105661487394848768


答:
J, 8 bytes

The natural logarithm is ^., and exponential ^. The problem is, . can only modify a valid verb, otherwise, a spelling error will occur. Thus, we can't use the left argument trick in the APL answer, becuase ^.[^ would cause an error when reversed, as ^[.^ creates an invalid verb. So, we must use comments; but NB. is so long :( Fortunately, they both end with ., so&ldots; there's that.

Logarithm:

```<code>^.NB.BN^
</code>```

Exponential:

```<code>^NB.BN.^
</code>```

You can enter them for yourself online!

Title: Inverse function

Body:
Wouldn't it be neat if programming functions could be inverted, just like the mathematical function they implement?

Write a function (or program) that takes one input x in any form, that outputs ln(x).

When the bytes of the program are reordered/reversed so that the first byte now is the last byte, it should take one input x in any form and output e^x instead.

Your answer must have at least 3 correct significant figures.

Approximations are fine, as long as they have at least 3 correct significant figures.

Your code must be in the same programming language both forwards and backwards.

Let's say this program implements ln(x):

```<code>abc你好
</code>```

Then this program has to implement e^x:

```<code>\xBD\xA5\xE5\xA0\xBD\xE4cba
</code>```

Gold star if you use a language without float support.

This is a weird form of code-golf, so the shortest program wins.

Body:
J, 8 bytes

The natural logarithm is ^., and exponential ^. The problem is, . can only modify a valid verb, otherwise, a spelling error will occur. Thus, we can't use the left argument trick in the APL answer, becuase ^.[^ would cause an error when reversed, as ^[.^ creates an invalid verb. So, we must use comments; but NB. is so long :( Fortunately, they both end with ., so&ldots; there's that.

Logarithm:

^.NB.BN^

Exponential:

^NB.BN.^

You can enter them for yourself online!


问:
How compatible are my strings?

Introduction

Consider two strings A and B of the same length L, and an integer K ≥ 0.
For the purposes of this challenge, we say that the strings are K-compatible, if there exists a string C of length K such that A is a contiguous substring of the concatenation BCB.
Note that A is a substring of BAB, so A and B are always L-compatible (but may also be K-compatible for some other K < L).

Input

Your inputs are two strings of the same positive length, consisting of upper- and lowercase ASCII letters.

Output

Your output shall be the lowest non-negative integer K such that the inputs are K-compatible.

Example

Consider the inputs

```<code>A = HHHHHH
B = HHttHH
</code>```

They are not 0-compatible, because A is not a substring of HHttHHHHttHH.
They are also not 1-compatible, because A is not a substring of HHttHH#HHttHH no matter which letter is placed on the #.
However, A is a substring of HHttHHHHHHttHH, where C is the two-letter string HH.
Thus the inputs are 2-compatible, and the correct output is 2.

Rules and scoring

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

Test cases

The compatibility condition is symmetric, so swapping the two inputs should not change the output.

```<code>E G -> 1
E E -> 0
aB Bc -> 1
YY tY -> 1
abcd bcda -> 0
abcXd bxcda -> 4
Hello Hello -> 0
Hello olHel -> 1
aBaXYa aXYaBa -> 1
aXYaBa aBaXYa -> 1
HHHHHH HHttHH -> 2
abcdab cdabcd -> 2
XRRXXXXR XRXXRXXR -> 4
evveeetev tetevevev -> 7
vzzvzJvJJz vJJvzJJvJz -> 10
JJfcfJJcfJfb JcfJfbbJJJfJ -> 5
GhhaaHHbbhGGH HHaaHHbbGGGhh -> 9
OyDGqyDGDOGOGyG yDGqOGqDyyyyOyD -> 12
ffKKBBpGfGKpfGpbKb fGpbKbpBBBffbbbffK -> 9
UZuPPZuPdVdtuDdDiuddUPtUidtVVV dtUPtUidtVVVtDZbZZPuiUZuPPZuPd -> 21
</code>```

Leaderboard

Here's a Stack Snippet to generate a leaderboard and list of winners by language.
To make sure your answer shows up, start it with a header of the form

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

You can keep old scores in the header by using the strikethrough tags: <s>57</s> will appear as <s>57</s>.

/* Configuration */

var QUESTION_ID = 78736; // 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 = 32014; // 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 (! /<a/.test(lang)) lang = '' + lang + '';
    lang = jQuery(lang).text().toLowerCase();

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

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

  langs.sort(function (a, b) {
    if (a.uniq > b.uniq) return 1;
    if (a.uniq < b.uniq) 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/Sites/codegolf/all.css?v=617d0685f6f3">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Jolf, 40 Bytes

```<code>Wά)Ζ0W<ζli)? h++i]Iζ+ζniIoά0nΖhζ}onhn}wn
</code>```

Try it!

I'm quite new to Jolf, learned a lot while figuring this out. Seems a bit awkward, still could probably could be golfed down further. Even knocked off 2 bytes while writing this explanation.

Explanation:

```<code>  Wά)                                      While ά (initialized to 16)
     Ζ0                                    Set ζ to 0
       W<ζli)                              While ζ < length(A)
             ? h++i]Iζ+ζniIoά0n            Set ά to 0 if (A + a substring from B of length n + A) contains B
                               Ζhζ         Increment ζ
                                  }onhn    Increment n (initialize to 0
                                       }wn Decrement n and print
</code>```

Title: How compatible are my strings?

Body:
Jolf, 40 Bytes

Wά)Ζ0W<ζli)? h++i]Iζ+ζniIoά0nΖhζ}onhn}wn

Try it!

I'm quite new to Jolf, learned a lot while figuring this out. Seems a bit awkward, still could probably could be golfed down further. Even knocked off 2 bytes while writing this explanation.

Explanation:

  Wά)                                      While ά (initialized to 16)
     Ζ0                                    Set ζ to 0
       W<ζli)                              While ζ < length(A)
             ? h++i]Iζ+ζniIoά0n            Set ά to 0 if (A + a substring from B of length n + A) contains B
                               Ζhζ         Increment ζ
                                  }onhn    Increment n (initialize to 0
                                       }wn Decrement n and print


答:
J, 10 bytes

This is one possible implementation.

```<code>[:,./^:2*/
</code>```

J, 13 bytes

This is a similar implementation, but instead uses J's ability to define ranks. It applies * between each element on the LHS with the entire RHS.

```<code>[:,./^:2*"0 _
</code>```

Usage

```<code>   f =: <either definition>
    (2 2 $ 1 2 3 4) f (2 2 $ 5 6 7 8)
 5  6 10 12
 7  8 14 16
15 18 20 24
21 24 28 32
   (2 1 $ 1 2) f (1 2 $ 1 2)
1 2
2 4
   2 f 5
10
</code>```

Title: Calculate the Kronecker Product

Body:
Related, but very different.

In the examples below, \$A\$ and \$B\$ will be \$2\times2\$ matrices, and the matrices are one-indexed.

A Kronecker product has the following properties:

```<code>A⊗B =  A(1,1)*B   A(1,2)*B
        A(2,1)*B   A(2,2)*B

     =  A(1,1)*B(1,1)   A(1,1)*B(1,2)   A(1,2)*B(1,1)   A(1,2)*B(1,2)
        A(1,1)*B(2,1)   A(1,1)*B(2,2)   A(1,2)*B(2,1)   A(1,2)*B(2,2)
        A(2,1)*B(1,1)   A(2,1)*B(1,2)   A(2,2)*B(1,1)   A(2,2)*B(1,2)
        A(2,2)*B(2,1)   A(2,2)*B(1,2)   A(2,2)*B(2,1)   A(2,2)*B(2,2)
</code>```

Challenge: Given two matrices, \$A\$ and \$B\$, return \$A\otimes B\$.

The size of the matrices will be at least \$1\times1\$. The maximum size will be whatever your computer / language can handle by default, but minimum \$5\times5\$ input.

All input values will be non-negative integers

Builtin functions that calculate Kronecker products or Tensor/Outer products are not allowed

In general: Standard rules regarding I/O format, program & functions, loopholes etc.

Test cases:

```<code>A =
     1     2
     3     4
B =
     5     6
     7     8
A⊗B =
     5     6    10    12
     7     8    14    16
    15    18    20    24
    21    24    28    32

B⊗A =
     5    10     6    12
    15    20    18    24
     7    14     8    16
    21    28    24    32
------------------------
A =
     1
     2
B =
     1     2

A⊗B =
     1     2
     2     4
------------------------
A =
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

B =
     1     1
     0     1

A⊗B  =
    16    16     2     2     3     3    13    13
     0    16     0     2     0     3     0    13
     5     5    11    11    10    10     8     8
     0     5     0    11     0    10     0     8
     9     9     7     7     6     6    12    12
     0     9     0     7     0     6     0    12
     4     4    14    14    15    15     1     1
     0     4     0    14     0    15     0     1

B⊗A =
    16     2     3    13    16     2     3    13
     5    11    10     8     5    11    10     8
     9     7     6    12     9     7     6    12
     4    14    15     1     4    14    15     1
     0     0     0     0    16     2     3    13
     0     0     0     0     5    11    10     8
     0     0     0     0     9     7     6    12
     0     0     0     0     4    14    15     1
------------------------

A = 2
B = 5
A⊗B = 10
</code>```

Body:
J, 10 bytes

This is one possible implementation.

[:,./^:2*/

J, 13 bytes

This is a similar implementation, but instead uses J's ability to define ranks. It applies * between each element on the LHS with the entire RHS.

[:,./^:2*"0 _

Usage

   f =: <either definition>
    (2 2 $ 1 2 3 4) f (2 2 $ 5 6 7 8)
 5  6 10 12
 7  8 14 16
15 18 20 24
21 24 28 32
   (2 1 $ 1 2) f (1 2 $ 1 2)
1 2
2 4
   2 f 5
10


问:
Survival Game - Create Your Wolf

The Board

The Board is a two dimensional array of cells. Cells are populated by Animals. Every day, all Animals on the Board simultaneously make one move. If two or more Animals move to the same cell, they fight until one remains. The possible moves and attacks are as follows:

Moves - { Move.UP, Move.RIGHT, Move.DOWN, Move.LEFT, Move.HOLD }

Attacks - { Attack.ROCK, Attack.PAPER, Attack.SCISSORS, Attack.SUICIDE }

Animals fight by playing Rock-Paper-Scissors. Standard rules apply but with two modifications. First, you may commit suicide at any time. Second, a tie is broken pseudorandomly. If more than two Animals collide, two are pseudorandomly selected to fight until one remains.

The Players

Animal behavior and appearance is as follows.

Lion

Represented by the character L. Moves DOWN, RIGHT, then repeats. Pseudorandomly attacks with PAPER or SCISSORS.

Bear

Represented by the character B. Moves DOWN x 4, RIGHT x 4, UP x 4, LEFT x 4, then repeats. Attacks with PAPER.

Stone

Represented by the character S. Moves HOLD. Attacks with ROCK.

Wolf

Only wolves that are submitted as an answer will be included. Represented by 'W'. Moves with any Move. Attacks with any Attack

You will implement the Wolf by filling in the blanks in the following template. All submissions must be in Java and must be contained in a single file. Alternatively, @ProgrammerDan has written a wrapper class that extends the competition to non-java submissions.

// Optional code here
public class Wolf extends Animal {
    // Optional code here
    public Wolf() { super('W'); /* Optional code here */ }
    public Attack fight(char opponent) { /* Required code here. Must return an Attack. */ }
    public Move move() { /* Required code here. Must return a Move. */ }
    // Optional code here
}
```

The submission with the highest average number of living wolves after five trials with 1,000 iterations wins. I will update the winner each time a new answer is posted (but not within the first 24 hours).

Tools

You are provided with a small map of your immediate surroundings in the following form.

char[][] surroundings A zero indexed, 3 by 3 matrix of characters that represent nearby animals. Empty tiles are represented by a space character (' '). You are at surroundings[1][1]. For example, to your right would be surroundings[1][2], and above you is surroundings[0][1]. Your surroundings are updated just before being asked to move, but may be out of date when asked to fight.

You may persist data between invocations of your Wolf, Move requests, and Attack requests. You may neither read from nor modify files created by another Wolf class.

You are provided with the size of the map in the following form

int MAP_SIZE

Assumptions

All submission will compete on the same board against all other submissions as well as Lions, Bears, and Stones

The board is a square with sides of length sqrt(n+3)*20 where n is the number of submissions. All sides wrap, so you can safely move in any direction infinitely.

Simulation begins at ~25% board capacity with 100 of each Animal pseudorandomly distributed across the board.

If an Animal throws an exception when asked to move, that Animal will HOLD

If an Animal throws an exception when asked to fight, that Animal will SUICIDE

If an Animal has no letter when the controller checks, that Animal will immediately die

Getting Started and Testing Instructions

The tools you need to test your submission can be found here. The following files should be available at that link.

ExampleRun.gif - A 5-10 second gif of the program running.

Scoreboard - The latest results of the competition.

Wild.jar - An executable that you can run to watch the premade Animals run around.

Wild.zip - The NetBeans project that houses the controller program with a few premade Animals added. Use this to develop your submission.

WildPopulated.zip - Same as above, but with and about 40 submissions added for you to test against. The GUI has also been removed because of performance issues. The results will simply appear a few moments after you run. The non-Java submissions are commented out because they require extra downloads and effort. Use this to test your submission against the field.

Wolf.txt -  A naive implementation of the Wolf class in Java. You may use and expand that implementation without crediting me.

To test your class:

Download Wild.zip

Rename your Wolf.java and Wolf class to something unique

Add your UniquelyNamedWolf.java file to Wild\src\animals\

In the Wild class, add your class to classes array, like this.

Class[] classes = { UniquelyNamedWolf.class, Bear.class, Lion.class, Stone.class, Wolf.class };

Rebuild and run

I also included another project containing all of the submissions, for testing purposes. I creatively named it "WildPopulated". The three or four non-Java wolves were commented out, because getting them to run requires a lot of extra work and downloads. The one I posted should run with zero extra work. The GUI was also commented out for the sake of speed.

Scoreboard April 22, 2014

The Scoreboard has been moved to Google Drive. View it here. It will be updated on a casual basis (i.e., when I get to it) as new submissions come in.

Side Challenge - NoHOLD

Removed because no (as in zero) participation. It wasn't part of the original challenge anyway.

答:
WanderingWolf

```<code>package animals;

public class WanderingWolf extends Animal {
    public WanderingWolf() {
        super('W');
    }
    public Attack fight(char enemy) {
        switch (enemy) {
            case 'B': // Bear: paper
            case 'L': // Lion: paper or scissors
                return Attack.SCISSORS;
            case 'S': // Stone: rock
                return Attack.PAPER;
            default:
                return Attack.values()[(int)(Math.random() * 3)];
        }
    }
    public Move move() {
        return Move.values()[(int)(Math.random() * 5)];
    }
}
</code>```

To move, it wanders. To attack, it uses the move that always wins (or ties), except for other wolves, which it attacks randomly for.

Title: Survival Game - Create Your Wolf

Body:
WanderingWolf

package animals;

public class WanderingWolf extends Animal {
    public WanderingWolf() {
        super('W');
    }
    public Attack fight(char enemy) {
        switch (enemy) {
            case 'B': // Bear: paper
            case 'L': // Lion: paper or scissors
                return Attack.SCISSORS;
            case 'S': // Stone: rock
                return Attack.PAPER;
            default:
                return Attack.values()[(int)(Math.random() * 3)];
        }
    }
    public Move move() {
        return Move.values()[(int)(Math.random() * 5)];
    }
}

To move, it wanders. To attack, it uses the move that always wins (or ties), except for other wolves, which it attacks randomly for.


答:
RandomWolf

```<code>package animals;

public class RandomWolf extends Animal {
    public RandomWolf() {
        super('W');
    }
    public Attack fight(char enemy) {
        return Attack.values()[(int)(Math.random() * 4)];
    }
    public Move move() {
        return Move.values()[(int)(Math.random() * 5)];
    }
}
</code>```

Does everything randomly. Commits suicide a quarter of the time it attacks :-)

Title: Survival Game - Create Your Wolf

Body:
The Board

The Board is a two dimensional array of cells. Cells are populated by Animals. Every day, all Animals on the Board simultaneously make one move. If two or more Animals move to the same cell, they fight until one remains. The possible moves and attacks are as follows:

Moves - { Move.UP, Move.RIGHT, Move.DOWN, Move.LEFT, Move.HOLD }

Attacks - { Attack.ROCK, Attack.PAPER, Attack.SCISSORS, Attack.SUICIDE }

Animals fight by playing Rock-Paper-Scissors. Standard rules apply but with two modifications. First, you may commit suicide at any time. Second, a tie is broken pseudorandomly. If more than two Animals collide, two are pseudorandomly selected to fight until one remains.

The Players

Animal behavior and appearance is as follows.

Lion

Represented by the character L. Moves DOWN, RIGHT, then repeats. Pseudorandomly attacks with PAPER or SCISSORS.

Bear

Represented by the character B. Moves DOWN x 4, RIGHT x 4, UP x 4, LEFT x 4, then repeats. Attacks with PAPER.

Stone

Represented by the character S. Moves HOLD. Attacks with ROCK.

Wolf

Only wolves that are submitted as an answer will be included. Represented by 'W'. Moves with any Move. Attacks with any Attack

You will implement the Wolf by filling in the blanks in the following template. All submissions must be in Java and must be contained in a single file. Alternatively, @ProgrammerDan has written a wrapper class that extends the competition to non-java submissions.

// Optional code here
public class Wolf extends Animal {
    // Optional code here
    public Wolf() { super('W'); /* Optional code here */ }
    public Attack fight(char opponent) { /* Required code here. Must return an Attack. */ }
    public Move move() { /* Required code here. Must return a Move. */ }
    // Optional code here
}
```

The submission with the highest average number of living wolves after five trials with 1,000 iterations wins. I will update the winner each time a new answer is posted (but not within the first 24 hours).

Tools

You are provided with a small map of your immediate surroundings in the following form.

char[][] surroundings A zero indexed, 3 by 3 matrix of characters that represent nearby animals. Empty tiles are represented by a space character (' '). You are at surroundings[1][1]. For example, to your right would be surroundings[1][2], and above you is surroundings[0][1]. Your surroundings are updated just before being asked to move, but may be out of date when asked to fight.

You may persist data between invocations of your Wolf, Move requests, and Attack requests. You may neither read from nor modify files created by another Wolf class.

You are provided with the size of the map in the following form

int MAP_SIZE

Assumptions

All submission will compete on the same board against all other submissions as well as Lions, Bears, and Stones

The board is a square with sides of length sqrt(n+3)*20 where n is the number of submissions. All sides wrap, so you can safely move in any direction infinitely.

Simulation begins at ~25% board capacity with 100 of each Animal pseudorandomly distributed across the board.

If an Animal throws an exception when asked to move, that Animal will HOLD

If an Animal throws an exception when asked to fight, that Animal will SUICIDE

If an Animal has no letter when the controller checks, that Animal will immediately die

Getting Started and Testing Instructions

The tools you need to test your submission can be found here. The following files should be available at that link.

ExampleRun.gif - A 5-10 second gif of the program running.

Scoreboard - The latest results of the competition.

Wild.jar - An executable that you can run to watch the premade Animals run around.

Wild.zip - The NetBeans project that houses the controller program with a few premade Animals added. Use this to develop your submission.

WildPopulated.zip - Same as above, but with and about 40 submissions added for you to test against. The GUI has also been removed because of performance issues. The results will simply appear a few moments after you run. The non-Java submissions are commented out because they require extra downloads and effort. Use this to test your submission against the field.

Wolf.txt -  A naive implementation of the Wolf class in Java. You may use and expand that implementation without crediting me.

To test your class:

Download Wild.zip

Rename your Wolf.java and Wolf class to something unique

Add your UniquelyNamedWolf.java file to Wild\src\animals\

In the Wild class, add your class to classes array, like this.

Class[] classes = { UniquelyNamedWolf.class, Bear.class, Lion.class, Stone.class, Wolf.class };

Rebuild and run

I also included another project containing all of the submissions, for testing purposes. I creatively named it "WildPopulated". The three or four non-Java wolves were commented out, because getting them to run requires a lot of extra work and downloads. The one I posted should run with zero extra work. The GUI was also commented out for the sake of speed.

Scoreboard April 22, 2014

The Scoreboard has been moved to Google Drive. View it here. It will be updated on a casual basis (i.e., when I get to it) as new submissions come in.

Side Challenge - NoHOLD

Removed because no (as in zero) participation. It wasn't part of the original challenge anyway.

Body:
RandomWolf

package animals;

public class RandomWolf extends Animal {
    public RandomWolf() {
        super('W');
    }
    public Attack fight(char enemy) {
        return Attack.values()[(int)(Math.random() * 4)];
    }
    public Move move() {
        return Move.values()[(int)(Math.random() * 5)];
    }
}

Does everything randomly. Commits suicide a quarter of the time it attacks :-)


问:
Find the program that prints this integer sequence (Robbers' thread)
This is the robbers' thread. The cops' thread goes here.

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

No-ops can be used in robber's solution.

The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

Language, nn characters (including link to answer), Cop's username

Code:

```<code>function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Output

```<code>a(0) returns 0
a(3) returns 2
</code>```

Optional explanation and comments.

答:
05AB1E, 3 bytes, Emigna, A002994

Code:

```<code>3m¬
</code>```

Explanation:

```<code>3m   # Compute input ** 3
  ¬  # Take the first digit
</code>```

This gives us the initial digits of the cubes, which is A002994.

Uses CP-1252 encoding. Try it online!.

Body:
05AB1E, 3 bytes, Emigna, A002994

Code:

3m¬

Explanation:

3m   # Compute input ** 3
  ¬  # Take the first digit

This gives us the initial digits of the cubes, which is A002994.

Uses CP-1252 encoding. Try it online!.


问:
Transform a matrix
Write a program or function where a matrix A (maximum value of dimensions of the matrix is 100) is transformed to a new matrix B. Each element of the new matrix B is the sum of the positive neighbors of the corresponding element of the matrix A.

Only neighbors in the four orthogonal directions are considered, and the edges do not wrap around.

Example input:

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

Output:

```<code> 6  4  2
 1  6 13
 5 12 10
 2 11 12
</code>```

Rules:

As input use integers.

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

答:
Jelly, <s>23</s> <s>20</s> 18 bytes

```<code>0;+ḊṖ
ZÇ€Z+Ç€
+AHÇ
</code>```

Try it online!

Algorithm

Let's say there is only one row: [1,2,3,4].

Let's say A is the result of prepending a zero, i.e. [0,1,2,3,4].

B is the result of removing the first item, i.e. [2,3,4].

Then the final result is simply A+B vectorized, then removing the last item.

Now, the algorithm is to apply this to every row as well as every column, then find their vectorized sum.

To each column?! I thought Jelly does not support this...

You're right. Therefore, I transposed it, applied to each row, then transposed it again.

Algorithm for removing negative numbers

Here, you just add to each number their absolute. It effectively eliminates negative numbers while doubling each positive number. Then, just halve the whole matrix.

Title: Transform a matrix

Body:
Jelly, <s>23</s> <s>20</s> 18 bytes

0;+ḊṖ
ZÇ€Z+Ç€
+AHÇ

Try it online!

Algorithm

Let's say there is only one row: [1,2,3,4].

Let's say A is the result of prepending a zero, i.e. [0,1,2,3,4].

B is the result of removing the first item, i.e. [2,3,4].

Then the final result is simply A+B vectorized, then removing the last item.

Now, the algorithm is to apply this to every row as well as every column, then find their vectorized sum.

To each column?! I thought Jelly does not support this...

You're right. Therefore, I transposed it, applied to each row, then transposed it again.

Algorithm for removing negative numbers

Here, you just add to each number their absolute. It effectively eliminates negative numbers while doubling each positive number. Then, just halve the whole matrix.


答:
05AB1E, 8 bytes, Emigna, A088666

Code (with obfuscated version below):

```<code>4m1s+rT%
___s_r__
</code>```

Explanation:

```<code>4m         # Compute input ** 4
  1        # Add one to the stack
   s       # Swap the top two elements
    +      # Add the two numbers (result = input ** 4 + 1)
     r     # Reverse the stack
      T    # Add 10
       %   # Modulo
</code>```

This comes down to the formula a(n) = (n4 + 1) % 10, which is A088666. I'm excited to see what the original code was.

Try it online!.

Title: Find the program that prints this integer sequence (Robbers' thread)

Body:
This is the robbers' thread. The cops' thread goes here.

In the cops thread, the task was to write a program/function that takes a positive (or non-negative) integer and outputs/returns another number (not necessarily integer). The robbers task is to unscramble the code the cops used to produce this output.

The cracked code doesn't have to be identical, as long as it has the same length and any revealed characters are in the correct positions. The language must also be the same (version numbers can be different). The output must of course be identical.

No-ops can be used in robber's solution.

The winner of the robbers thread will be the user who has cracked the
most submissions by May 7th 2016. If there's a tie, the user who has cracked submissions with the longest combined code will win.

The submission should be formatted like this:

Language, nn characters (including link to answer), Cop's username

Code:

```<code>function a(n)
    if n<2 then
        return n
    else
        return a(n-1) + a(n-2)
    end
end
</code>```

Output

```<code>a(0) returns 0
a(3) returns 2
</code>```

Optional explanation and comments.

Body:
05AB1E, 8 bytes, Emigna, A088666

Code (with obfuscated version below):

4m1s+rT%
___s_r__

Explanation:

4m         # Compute input ** 4
  1        # Add one to the stack
   s       # Swap the top two elements
    +      # Add the two numbers (result = input ** 4 + 1)
     r     # Reverse the stack
      T    # Add 10
       %   # Modulo

This comes down to the formula a(n) = (n4 + 1) % 10, which is A088666. I'm excited to see what the original code was.

Try it online!.


答:
Python 2.7, <s>158</s> 145 bytes

The worst answer here, but my best golf in Python yet. At least it was fun learning how to do matrix multiplication.

Golfed:

```<code>def q(m,p):
 r=range(len(m))
 if p<1:return[[x==y for x in r]for y in r]
 o=q(m,p-1)
 return[[sum([m[c][y]*o[x][c]for c in r])for y in r]for x in r]
</code>```

Explanation:

```<code>#accepts 2 arguments, matrix, and power to raise to
def power(matrix,exponent):
 #get the range object beforehand
 length=range(len(matrix))
 #if we are at 0, return the identity
 if exponent<1:
  #the Boolean statement works because Python supports multiplying ints by bools
  return [[x==y for x in length] for y in length]
 #otherwise, recur
 lower=power(matrix,exponent-1)
 #and return the product
 return [[sum([matrix[c][y]*lower[x][c] for c in length]) for y in length] for x in length]
</code>```

Title: Find the Matrix Power

Body:
Problem

Create a program or function that can calculate the result of a matrix raised to the nth power. Your code will take an arbitrary square matrix A and a non-negative integer n, and return a matrix with the value An.

Restrictions

Built-in functions that compute the matrix power and matrix product are not allowed.

The rest of the standard rules for code-golf apply.

Explanation

Given a square matrix A, the value of An = A A ⋯ A (repeated matrix product of A with itself, n times). If n is positive, the standard just mentioned is used. When n is zero, the identity matrix with the same order of A is the result.

Goal

This is code-golf and the shortest code wins.

Test Cases

Here, A is the input matrix, n is the input integer, and r is the output matrix where r = An.

```<code>n = 0
A = 62 72
    10 34
r =  1  0
     0  1

n = 1
A = 23 61 47
    81 11 60
    42  9  0
r = 23 61 47
    81 11 60
    42  9  0

n = 2
A =  12  28 -26  3
     -3 -10 -13  0
     25  41   3 -4
    -20 -14  -4 29
r = -650 -1052  -766 227
    -331  -517   169  43
     332   469 -1158 -53
    -878  -990   574 797

n = 4
A = -42 -19  18 -38
    -33  26 -13  31
    -43  25 -48  28
     34 -26  19 -48
r = -14606833  3168904 -6745178  4491946
      1559282  3713073 -4130758  7251116
      8097114  5970846 -5242241 12543582
     -5844034 -4491274  4274336 -9196467

n = 5
A =  7  0 -3  8 -5  6 -6
     6  7  1  2  6 -3  2
     7  8  0  0 -8  5  2
     3  0  1  2  4 -3  4
     2  4 -1 -7 -4 -1 -8
    -3  8 -9 -2  7 -4 -8
    -4 -5 -1  0  5  5 -1
r =  39557  24398 -75256 131769  50575   14153  -7324
    182127  19109   3586 115176 -23305    9493 -44754
    146840  31906 -23476 190418 -38946   65494  26468
     42010 -21876  41060 -13950 -55148   19290   -406
     44130  34244 -35944  34272  22917  -39987 -54864
      1111  40810 -92324  35831 215711 -117849 -75038
    -70219   8803 -61496   6116  45247   50166   2109
</code>```

Body:
Python 2.7, <s>158</s> 145 bytes

The worst answer here, but my best golf in Python yet. At least it was fun learning how to do matrix multiplication.

Golfed:

def q(m,p):
 r=range(len(m))
 if p<1:return[[x==y for x in r]for y in r]
 o=q(m,p-1)
 return[[sum([m[c][y]*o[x][c]for c in r])for y in r]for x in r]

Explanation:

#accepts 2 arguments, matrix, and power to raise to
def power(matrix,exponent):
 #get the range object beforehand
 length=range(len(matrix))
 #if we are at 0, return the identity
 if exponent<1:
  #the Boolean statement works because Python supports multiplying ints by bools
  return [[x==y for x in length] for y in length]
 #otherwise, recur
 lower=power(matrix,exponent-1)
 #and return the product
 return [[sum([matrix[c][y]*lower[x][c] for c in length]) for y in length] for x in length]


问:
ASCII Art Mayan Numerals
This challenge is simple.  Given a number, output a ascii-art representation of the number, using the Mayan Base-20 numeral system.

What is the Mayan system?

The Mayans used base 20 to store numbers, so the first position was the 1s place, the next the 20s place, then the 400s, etc.

So Mayan number 1 is 1 in base 10, but 10 is actually 20 in base 10, 207 is 807 in base 10, etc..

And they represented their numbers as pictographs, with a special symbol for 0.

```<code> -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------
</code>```

That was their zero.  (at least the half picascii half my artisticness ascii art version)

That is a <s>real</s> picture of the mayan zero symbol.1

This was their five:

```<code>--------------------------------
|                              |
--------------------------------
</code>```

And a 4:

```<code> ----   ----   ----   ----
|    | |    | |    | |    |
|    | |    | |    | |    |
 ----   ----   ----   ----
</code>```

Finally, to put it together:

```<code> ----   ----   ----
|    | |    | |    |
|    | |    | |    |
 ----   ----   ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------
</code>```

So they have x//5 bars, and x%5 dots on top of the bars.  And if x=0, they use the shell/loaf instead of a blank space.

For more images, try the Wikimedia Commons page of Maya number images.

But this is only for numbers up to 19. We aren't allowed to have more than 4 bars and 4 dots in a single 'story'... So we go up!

The output for 20 is:

```<code> ----
|    |
|    |
 ----

 -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------
</code>```

Note this would normally be invalid, because is has a 1 and a 0 at the same time.  But the 3 (note that, your answer needs at least 3) newlines before the 0 mean a new place value.

The bottom story has dots, meaning 1, and bars meaning 5.  But it actually has dots meaning 20^0 and bars meaning 20^0 * 5.

Each story goes up a power.  The second story dots mean 20 (20^1) and 100 (20^1 * 5).

So the number 506 can be represented as:

```<code> ----
|    |
|    |
 ----

--------------------------------
|                              |
--------------------------------

 ----
|    |
|    |
 ----
--------------------------------
|                              |
--------------------------------
</code>```

This is (20^0) * 1 + (20^0 * 5) * 1 + (20^1 * 5) * 1 + (20^2) * 1 = 1 + 5 + 100 + 400 = 506.

Your mission, should you choose not or choose to (it doesn't matter), is to output a ascii art representation of the base-10 number.

Other Rules:

Leading/trailing space is okay, as long as the dots, bars, and shells are intact.

The bars, dots, and shells must be exactly what the test cases have.  No resizing.

Leading '0's are okay. (leading shells on the output)

You don't have to have exactly 3 newlines between each place value or story, just at least 3.

Test Cases:

```<code>15

--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

12

 ----   ----
|    | |    |
|    | |    |
 ----   ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

4

 ----   ----   ----   ----
|    | |    | |    | |    |
|    | |    | |    | |    |
 ----   ----   ----   ----

0

 -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------

24

 ----
|    |
|    |
 ----

 ----   ----   ----   ----
|    | |    | |    | |    |
|    | |    | |    | |    |
 ----   ----   ----   ----

33

 ----
|    |
|    |
 ----

 ----   ----   ----
|    | |    | |    |
|    | |    | |    |
 ----   ----   ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

20

 ----
|    |
|    |
 ----

 -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------
</code>```

1: They also used the heads of gods for the symbols, but for this challenge the shell/bread/zelda chest will be used.

Title: ASCII Art Mayan Numerals

Body:
Python, 411 bytes

w,m=input(),[]
for i in[20**i for i in range(int(w**0.25))][::-1]:m.append(w/i);w=w%i
for i in m or[0]:print(lambda x,y='\n',w=' ----  ',z='|    | ':w*(x%5)+y+z*(x%5)+y+z*(x%5)+y+w*(x%5)+y+('-'*32+'\n|'+' '*30+'|\n'+'-'*32+y)*(x/5)if x else''' -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 ------------------- ''')(i),'\n\n\n'

I created this to generate test cases, you can use it as a benchmark. Sorta golfed.


答:
Ruby, <s>223</s> <s>180</s> <s>177</s> 179 bytes

Anonymous function, returns a multiline string.

Forgot to add some extra spacing that was needed, and also the recursion. Also golfed a bit more by shifting things around.

```<code>f=->n{s=?|;e=' ';n<20?(n<1?[t=e+d=?-*19,a=s+(e*4+s)*4,a,s+d+s,b=s+e*19+s,b,t]:((r=n%5)>0?[t=" ----  "*r,m="|    | "*r,m,t]:[])+[a=?-*32,s+e*30+s,a]*(n/5))*$/:f[n/20]+$/*5+f[n%20]}
</code>```

Title: ASCII Art Mayan Numerals

Body:
This challenge is simple.  Given a number, output a ascii-art representation of the number, using the Mayan Base-20 numeral system.

What is the Mayan system?

The Mayans used base 20 to store numbers, so the first position was the 1s place, the next the 20s place, then the 400s, etc.

So Mayan number 1 is 1 in base 10, but 10 is actually 20 in base 10, 207 is 807 in base 10, etc..

And they represented their numbers as pictographs, with a special symbol for 0.

```<code> -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------
</code>```

That was their zero.  (at least the half picascii half my artisticness ascii art version)

That is a <s>real</s> picture of the mayan zero symbol.1

This was their five:

```<code>--------------------------------
|                              |
--------------------------------
</code>```

And a 4:

```<code> ----   ----   ----   ----
|    | |    | |    | |    |
|    | |    | |    | |    |
 ----   ----   ----   ----
</code>```

Finally, to put it together:

```<code> ----   ----   ----
|    | |    | |    |
|    | |    | |    |
 ----   ----   ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------
</code>```

So they have x//5 bars, and x%5 dots on top of the bars.  And if x=0, they use the shell/loaf instead of a blank space.

For more images, try the Wikimedia Commons page of Maya number images.

But this is only for numbers up to 19. We aren't allowed to have more than 4 bars and 4 dots in a single 'story'... So we go up!

The output for 20 is:

```<code> ----
|    |
|    |
 ----

 -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------
</code>```

Note this would normally be invalid, because is has a 1 and a 0 at the same time.  But the 3 (note that, your answer needs at least 3) newlines before the 0 mean a new place value.

The bottom story has dots, meaning 1, and bars meaning 5.  But it actually has dots meaning 20^0 and bars meaning 20^0 * 5.

Each story goes up a power.  The second story dots mean 20 (20^1) and 100 (20^1 * 5).

So the number 506 can be represented as:

```<code> ----
|    |
|    |
 ----

--------------------------------
|                              |
--------------------------------

 ----
|    |
|    |
 ----
--------------------------------
|                              |
--------------------------------
</code>```

This is (20^0) * 1 + (20^0 * 5) * 1 + (20^1 * 5) * 1 + (20^2) * 1 = 1 + 5 + 100 + 400 = 506.

Your mission, should you choose not or choose to (it doesn't matter), is to output a ascii art representation of the base-10 number.

Other Rules:

Leading/trailing space is okay, as long as the dots, bars, and shells are intact.

The bars, dots, and shells must be exactly what the test cases have.  No resizing.

Leading '0's are okay. (leading shells on the output)

You don't have to have exactly 3 newlines between each place value or story, just at least 3.

Test Cases:

```<code>15

--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

12

 ----   ----
|    | |    |
|    | |    |
 ----   ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

4

 ----   ----   ----   ----
|    | |    | |    | |    |
|    | |    | |    | |    |
 ----   ----   ----   ----

0

 -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------

24

 ----
|    |
|    |
 ----

 ----   ----   ----   ----
|    | |    | |    | |    |
|    | |    | |    | |    |
 ----   ----   ----   ----

33

 ----
|    |
|    |
 ----

 ----   ----   ----
|    | |    | |    |
|    | |    | |    |
 ----   ----   ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

20

 ----
|    |
|    |
 ----

 -------------------
|    |    |    |    |
|    |    |    |    |
|-------------------|
|                   |
|                   |
 -------------------
</code>```

1: They also used the heads of gods for the symbols, but for this challenge the shell/bread/zelda chest will be used.

Body:
Ruby, <s>223</s> <s>180</s> <s>177</s> 179 bytes

Anonymous function, returns a multiline string.

Forgot to add some extra spacing that was needed, and also the recursion. Also golfed a bit more by shifting things around.

f=->n{s=?|;e=' ';n<20?(n<1?[t=e+d=?-*19,a=s+(e*4+s)*4,a,s+d+s,b=s+e*19+s,b,t]:((r=n%5)>0?[t=" ----  "*r,m="|    | "*r,m,t]:[])+[a=?-*32,s+e*30+s,a]*(n/5))*$/:f[n/20]+$/*5+f[n%20]}


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

答:
Racket, 130 bytes

:c

```<code>#lang racket
(require math)(λ(S)(let([s(string->list S)])(sum(map(λ(c)(/(log(/(length s)(count(λ(x)(char=? c x))s)))(log 2)))s))))
</code>```

Translation of my Factor answer, so it's an indirect translation of Kenny Lau's Python answer.

Body:
Racket, 130 bytes

:c

#lang racket
(require math)(λ(S)(let([s(string->list S)])(sum(map(λ(c)(/(log(/(length s)(count(λ(x)(char=? c x))s)))(log 2)))s))))

Translation of my Factor answer, so it's an indirect translation of Kenny Lau's Python answer.


问:
Exploded substrings

Introduction

Let's observe the string abc. The substrings that can be made from this are:

```<code>a, ab, abc, b, bc, c
</code>```

We now need to align them under the initial string, like this:

```<code>abc
a
 b
  c
ab
 bc
abc
</code>```

The order of the string doesn't matter, so this is also perfectly valid:

```<code>abc
a
ab
abc
 b
 bc
  c
</code>```

So, the substring is positioned under the location of the substring in the initial string. So for abcdef and the substring cde, it would look like this:

```<code>abcdef
  cde
</code>```

The Task

The task is to align all substrings with a length greater than 0, like shown above. You can assume that the string itself will only contain alphabetic characters and has at least 1 character. For the padding, you can use a space or some other non-alphabetic printable ASCII character (32 - 127). Maybe not necessary to mention, but the string itself will only contain unique characters, so not like aba, since the a occurs twice.

Test cases

Input: abcde

Possible output:

```<code>a
ab
abc
abcd
abcde
 b
 bc
 bcd
 bcde
  c
  cd
  cde
   d
   de
    e
</code>```

Input: abcdefghij

Possible output:

```<code>a
ab
abc
abcd
abcde
abcdef
abcdefg
abcdefgh
abcdefghi
abcdefghij
 b
 bc
 bcd
 bcde
 bcdef
 bcdefg
 bcdefgh
 bcdefghi
 bcdefghij
  c
  cd
  cde
  cdef
  cdefg
  cdefgh
  cdefghi
  cdefghij
   d
   de
   def
   defg
   defgh
   defghi
   defghij
    e
    ef
    efg
    efgh
    efghi
    efghij
     f
     fg
     fgh
     fghi
     fghij
      g
      gh
      ghi
      ghij
       h
       hi
       hij
        i
        ij
         j
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

答:
PHP, 151 chars

Ungolfed

```<code><?php
$input = $argv[1];
foreach(str_split($input) as $p=>$letter)
{
    $spaces = str_repeat(" ", $p);
    echo $spaces.$letter."\n";
    $p++;
    for($i=$p;$i<strlen($input);$i++)
    {
        echo $spaces.$letter.substr($input, $p, $i)."\n";
    }
}
?>
</code>```

Golfed

```<code><?$c=$argv[1];foreach(str_split($c)as$d=>$b){$a=str_repeat(" ",$d);echo$a.$b."\n";$d++;for($e=$d;$e<strlen($c);$e++){echo$a.$b.substr($c,$d,$e)."\n";}}
</code>```

Example

```<code>php explodesub.php 'abc'
a
ab
abc
 b
 bc
  c
</code>```

Title: Exploded substrings

Body:
PHP, 151 chars

Ungolfed

<?php
$input = $argv[1];
foreach(str_split($input) as $p=>$letter)
{
    $spaces = str_repeat(" ", $p);
    echo $spaces.$letter."\n";
    $p++;
    for($i=$p;$i<strlen($input);$i++)
    {
        echo $spaces.$letter.substr($input, $p, $i)."\n";
    }
}
?>

Golfed

<?$c=$argv[1];foreach(str_split($c)as$d=>$b){$a=str_repeat(" ",$d);echo$a.$b."\n";$d++;for($e=$d;$e<strlen($c);$e++){echo$a.$b.substr($c,$d,$e)."\n";}}

Example

php explodesub.php 'abc'
a
ab
abc
 b
 bc
  c


答:
Java 8, <s>198</s> <s>182</s> 30 bytes

```<code>d->Math.log(d)//)d(pxe.htaM<-d
</code>```

Try it online.

and reversed:

```<code>d->Math.exp(d)//)d(gol.htaM<-d
</code>```

Try it online.

Uses the comment trick (//) with built-ins for Math.log and Math.exp.

Title: Inverse function

Body:
Wouldn't it be neat if programming functions could be inverted, just like the mathematical function they implement?

Write a function (or program) that takes one input x in any form, that outputs ln(x).

When the bytes of the program are reordered/reversed so that the first byte now is the last byte, it should take one input x in any form and output e^x instead.

Your answer must have at least 3 correct significant figures.

Approximations are fine, as long as they have at least 3 correct significant figures.

Your code must be in the same programming language both forwards and backwards.

Let's say this program implements ln(x):

```<code>abc你好
</code>```

Then this program has to implement e^x:

```<code>\xBD\xA5\xE5\xA0\xBD\xE4cba
</code>```

Gold star if you use a language without float support.

This is a weird form of code-golf, so the shortest program wins.

Body:
Java 8, <s>198</s> <s>182</s> 30 bytes

d->Math.log(d)//)d(pxe.htaM<-d

Try it online.

and reversed:

d->Math.exp(d)//)d(gol.htaM<-d

Try it online.

Uses the comment trick (//) with built-ins for Math.log and Math.exp.


问:
Calculate the nth term of Golomb's self-describing sequence
Inspired by the previous question.

Golomb's self-describing sequence g(n) is a sequence where any natural number n is repeated within the sequence g(n) times.

The first few numbers in the sequence are:

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

You can see that g(4)=3, and that "4" is repeated 3 times in the sequence.

Given an input of n, output g(n).

Limitations: n < 100000.

Smallest code wins.

答:
Haskell, 63 bytes

```<code>f n|n<3=n|n<4=2|1>0=foldr1(++)[replicate(f m)m|m<-[1..]]!!(n-1)
</code>```

This is the naive approach, I was not aware of the very short recurison when I wrote this, but I thought I'd post it anyway, even tough it is longer than all other Haskell implementations, as e.g.

Calculate the nth term of Golomb's self-describing sequence

and

https://codegolf.stackexchange.com/a/23979/24877

Body:
Haskell, 63 bytes

f n|n<3=n|n<4=2|1>0=foldr1(++)[replicate(f m)m|m<-[1..]]!!(n-1)

This is the naive approach, I was not aware of the very short recurison when I wrote this, but I thought I'd post it anyway, even tough it is longer than all other Haskell implementations, as e.g.

Calculate the nth term of Golomb's self-describing sequence

and

https://codegolf.stackexchange.com/a/23979/24877


答:
Python 3.5, 404 400 392 312 311 308 290 281 285 281 bytes:

(Thanks to Adnan for a tip on saving 9 bytes(290->281) and Neil for a tip on saving 4 bytes(285->281)!)

```<code>def u(z):
 p=[];P=print;S,N,M,X=' -|\n'
 while not p or z:p+=[z%20];z=z//20
 E=lambda i:(S+N*4+S)*i+X+((M+S*4+M)*i+X)*2+(S+N*4+S)*i+X;F=N*32+X+M+S*30+M+X+N*32+X;[P(S+N*19+S+X+M+((S*4+M)*4+X+M)*2+N*19+M+X+(M+S*19+M+X)*2+S+N*19+S+X*3)if y<1else P(E(y%5)+F*(y//5)+X*3)for y in p[::-1]]
</code>```

Try it online! (Ideone)

Analysis

For the purposes of this analysis, we will use the character set 0123456789ABCDEFGHIJ to represent each digit in base 20.

So, I could have gone and converted base 10 into base 20 using one of two algorithms I have. The first algorithm I thought of using is what I call the powers algorithm. This is not the one that I used in the code though as it would have made it way longer than it should have been, so I'm not going to talk about this one. However, I did create a python script that converts any integer in base 10 into any other base provided using this method, which you can use here on repl.it. The one I used instead for this challenge is what I call the division algorithm, which I think is explained pretty good here. But basically what happens is that it takes the base 10 number provided and divides it by the base it needs to convert the number to, which in this case is 20, until the remainder is either 0 or 1. It then takes the quotiant and remainder, in that order, from the last division operation, and then all the other remainders from the other division operations in the order from last to first. All these digits are then joined together, and that joined sequence reversed is your base 10 number in base 20! To illustrate this, assume you want to convert the base 10 number 431 to base 20. So, what we would do is this:

```<code>[]=list we will put all remainders and the last quotient in
R = Remainder

1. 431/20 = 21 R11 [B (B=11 in base 20)]
2. 21/20 = 1 R1 [Add the remainder and quotient: B11]
</code>```

Then, finally we would take the list we have, which in this case contains B11, and reverse it so that we now have 11B. In doing this, we have finally got our final answer! 431 in base 10 converted to base 20 is 11B, which can be confirmed using my Python script that uses the powers algorithm which I already shared a link to above, but I will do it again here. Here is one that also uses the division algorithm described in this answer and returns the same answer as the powers one.

This entire process is essentially what happens in my script in this while loop: while not p or z:p+=[z%20];z=z//20. The only difference is that numbers >9 are not represented as letters but instead as themselves.

Moving on, after the base 10 number has been converted to base 20, for each digit in the base 20 integer, which we will call g, g mod 5 dots are printed out and then g//5 bars are printed out. Then the program prints 3 blank lines and moves on to the next digit. However, if the digit is 0, then a single "loaf" is printed out followed by 3 new lines, and then the program moves onto the next digit. So, taking the base 20 number 11B, we go to the first digit. The first digit is 1, and therefore it would print 0 bars since 1//5=0, and 1 dot since 1%5=1. So, we would first get this:

```<code> ----
|    |
|    |
 ----
</code>```

and then 3 new lines. Moving onto the the second digit, we also see that it is 1, so it would output the same thing:

```<code> ----
|    |
|    |
 ----
</code>```

and also 3 new lines. Finally, moving onto the last digit, we see that it's a B. Since B=11 in base 20, the program would output 1 dot since 11%5=1 and 2 bars since 11//5=2. So now, we get this:

```<code> ----
|    |
|    |
 ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------
</code>```

Finally, putting all this together, we get this:

```<code> ----
|    |
|    |
 ----

 ----
|    |
|    |
 ----

 ----
|    |
|    |
 ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------
</code>```

And, that's the mayan numeral for 431! You finally have your base 10 number represented in base 20 Mayan numerals.

Note: You may or may not have noticed that lambda function in my code. Regardless, this function is used for the creation of the dots since multiple dots must be output next to each other.

Title: ASCII Art Mayan Numerals

Body:
Python 3.5, 404 400 392 312 311 308 290 281 285 281 bytes:

(Thanks to Adnan for a tip on saving 9 bytes(290->281) and Neil for a tip on saving 4 bytes(285->281)!)

def u(z):
 p=[];P=print;S,N,M,X=' -|\n'
 while not p or z:p+=[z%20];z=z//20
 E=lambda i:(S+N*4+S)*i+X+((M+S*4+M)*i+X)*2+(S+N*4+S)*i+X;F=N*32+X+M+S*30+M+X+N*32+X;[P(S+N*19+S+X+M+((S*4+M)*4+X+M)*2+N*19+M+X+(M+S*19+M+X)*2+S+N*19+S+X*3)if y<1else P(E(y%5)+F*(y//5)+X*3)for y in p[::-1]]

Try it online! (Ideone)

Analysis

For the purposes of this analysis, we will use the character set 0123456789ABCDEFGHIJ to represent each digit in base 20.

So, I could have gone and converted base 10 into base 20 using one of two algorithms I have. The first algorithm I thought of using is what I call the powers algorithm. This is not the one that I used in the code though as it would have made it way longer than it should have been, so I'm not going to talk about this one. However, I did create a python script that converts any integer in base 10 into any other base provided using this method, which you can use here on repl.it. The one I used instead for this challenge is what I call the division algorithm, which I think is explained pretty good here. But basically what happens is that it takes the base 10 number provided and divides it by the base it needs to convert the number to, which in this case is 20, until the remainder is either 0 or 1. It then takes the quotiant and remainder, in that order, from the last division operation, and then all the other remainders from the other division operations in the order from last to first. All these digits are then joined together, and that joined sequence reversed is your base 10 number in base 20! To illustrate this, assume you want to convert the base 10 number 431 to base 20. So, what we would do is this:

[]=list we will put all remainders and the last quotient in
R = Remainder

1. 431/20 = 21 R11 [B (B=11 in base 20)]
2. 21/20 = 1 R1 [Add the remainder and quotient: B11]

Then, finally we would take the list we have, which in this case contains B11, and reverse it so that we now have 11B. In doing this, we have finally got our final answer! 431 in base 10 converted to base 20 is 11B, which can be confirmed using my Python script that uses the powers algorithm which I already shared a link to above, but I will do it again here. Here is one that also uses the division algorithm described in this answer and returns the same answer as the powers one.

This entire process is essentially what happens in my script in this while loop: while not p or z:p+=[z%20];z=z//20. The only difference is that numbers >9 are not represented as letters but instead as themselves.

Moving on, after the base 10 number has been converted to base 20, for each digit in the base 20 integer, which we will call g, g mod 5 dots are printed out and then g//5 bars are printed out. Then the program prints 3 blank lines and moves on to the next digit. However, if the digit is 0, then a single "loaf" is printed out followed by 3 new lines, and then the program moves onto the next digit. So, taking the base 20 number 11B, we go to the first digit. The first digit is 1, and therefore it would print 0 bars since 1//5=0, and 1 dot since 1%5=1. So, we would first get this:

 ----
|    |
|    |
 ----

and then 3 new lines. Moving onto the the second digit, we also see that it is 1, so it would output the same thing:

 ----
|    |
|    |
 ----

and also 3 new lines. Finally, moving onto the last digit, we see that it's a B. Since B=11 in base 20, the program would output 1 dot since 11%5=1 and 2 bars since 11//5=2. So now, we get this:

 ----
|    |
|    |
 ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

Finally, putting all this together, we get this:

 ----
|    |
|    |
 ----

 ----
|    |
|    |
 ----

 ----
|    |
|    |
 ----
--------------------------------
|                              |
--------------------------------
--------------------------------
|                              |
--------------------------------

And, that's the mayan numeral for 431! You finally have your base 10 number represented in base 20 Mayan numerals.

Note: You may or may not have noticed that lambda function in my code. Regardless, this function is used for the creation of the dots since multiple dots must be output next to each other.


答:
Jelly, 10 bytes

```<code>31,53Dæ*³Ḣ
</code>```

Try it online!

Uses matrix. Computes ([[3,1],[5,3]]**input())[0].

Title: Calculating (3 + sqrt(5))^n exactly

Body:
Today your goal is to find integers a and b given non-negative integer n such that:

You should write a program or a function that takes parameter n and outputs a and b in a format of your choice.

Standard loopholes apply. Additionally, it's intended that you implement the above problem using basic arithmetic yourself. So you may not use built-in exact algebra functionality, rationals, or functions implementing non-trivial mathematical constructs (for example the Lucas sequence).

Shortest code in bytes wins.

Example input/output:

0 → 1, 0

  1 → 3, 1

  2 → 14, 6

  3 → 72, 32

  4 → 376, 168

  5 → 1968, 880

  6 → 10304, 4608

  7 → 53952, 24128

  8 → 282496, 126336

  9 → 1479168, 661504

Body:
Jelly, 10 bytes

31,53Dæ*³Ḣ

Try it online!

Uses matrix. Computes ([[3,1],[5,3]]**input())[0].


问:
Shortest infinite loop producing no output
Your task is to create the shortest infinite loop!

The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.

Rules

Each submission must be a full program.

You must create the shortest infinite loop.

Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.

The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.

The program must not write anything to STDERR.

Feel free to use a language (or language version) even if it's newer than this challenge.
-Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. :D

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

This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.

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

There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like #[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes.

Standard loopholes are not allowed.

(I have taken some of these rules from Martin Büttner's "Hello World" challenge)

Please feel free to post in the comments to tell me how this challenge could be  improved.

Catalogue

This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:

```<code># Language name, X bytes
</code>```

Obviously replacing Language name and X bytes with the proper items. If you want to link to the languages' website, use this template, as posted above:

```<code>#[Language name](http://link.to/the/language), X bytes
</code>```

Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)

var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//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"//api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+lang+'').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang,user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase())return 1;if(a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase())return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;width:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;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">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Revaver2pi, 5 bytes

```<code>TEL 0
</code>```

TEL searches (cyclically) for the next TEL with the same first argument and jumps to there.

Body:
Revaver2pi, 5 bytes

TEL 0

TEL searches (cyclically) for the next TEL with the same first argument and jumps to there.


答:
XRF, 5 bytes

```<code>FFFFF
</code>```

Only contains one chunk, which is a NOP. The instruction pointer is the top of the stack, so it never changes and just repeats the code infinitely.

Title: Shortest infinite loop producing no output

Body:
Your task is to create the shortest infinite loop!

The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.

Rules

Each submission must be a full program.

You must create the shortest infinite loop.

Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.

The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.

The program must not write anything to STDERR.

Feel free to use a language (or language version) even if it's newer than this challenge.
-Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. :D

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

This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.

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

There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like #[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes.

Standard loopholes are not allowed.

(I have taken some of these rules from Martin Büttner's "Hello World" challenge)

Please feel free to post in the comments to tell me how this challenge could be  improved.

Catalogue

This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:

```<code># Language name, X bytes
</code>```

Obviously replacing Language name and X bytes with the proper items. If you want to link to the languages' website, use this template, as posted above:

```<code>#[Language name](http://link.to/the/language), X bytes
</code>```

Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)

var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//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"//api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+lang+'').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang,user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase())return 1;if(a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase())return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;width:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;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">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
XRF, 5 bytes

FFFFF

Only contains one chunk, which is a NOP. The instruction pointer is the top of the stack, so it never changes and just repeats the code infinitely.


问:
Addition in base -1+i
Gaussian integers are complex numbers of the form a+bi where a and b are both integers. In base -1+i, all Gaussian integers can be uniquely represented using the digits 0 and 1, without the need for a symbol to denote sign.

For instance, 1100 in base -1+i represents the decimal number 2, since

```<code>1*(-1+i)^3 + 1*(-1+i)^2 + 0*(-1+i)^1 + 0*(-1+i)^0
= (2+2i) + (-2i) + 0 + 0
= 2
</code>```

Input will be two Gaussian integers in base -1+i  represented using the digits 01. This can take one of the following forms:

Two separate digit strings,

Two decimal integers consisting of 01 representing the base -1+i numbers (e.g. 1100 for 2 in base -1+i),

Two binary integers representing the base -1+i numbers (e.g. decimal 12 or 0b1100 for 2 in base -1+i)

A single string separating two digit strings/binary integers by a single non-alphanumeric separator (e.g. 1100 1100 or 12,12 for 2+2)

Output the sum of the two Gaussian integers, also in base -1+i and represented using the digits 01 (in one of the formats allowed as input, not necessarily the same choice). The output is allowed to contain a finite number of leading zeroes.

Your function or program must terminate within 2 seconds for inputs of at most 30 digits each.

Additional clarifications

You may assume that the input contains no extraneous leading zeroes. For the special case of 0, you may choose either 0 or the empty string as the representation.

Test cases

```<code>0, 0 => 0                                      # 0 + 0 = 0
0, 1 => 1                                      # 0 + 1 = 1
1, 1 => 1100                                   # 1 + 1 = 2
1100, 1100 => 111010000                        # 2 + 2 = 4
1101, 1101 => 111011100                        # 3 + 3 = 6
110111001100, 1110011011100 => 0               # 42 + (-42) = 0
11, 111 => 0                                   # i + (-i) = 0
11, 110 => 11101                               # i + (-1-i) = -1
10101, 11011 => 10010                          # (-3-2i) + (-2+3i) = (-5+i)
1010100101, 111101 => 1110100000100            # (-19+2i) + (3-4i) = (-16-2i)
</code>```

Longer test cases:

```<code>11011011010110101110010001001, 111100010100101001001010010101 => 0
111111111111111111111111111111, 111111111111111111111111111111 => 100100100100100100100100100100
101101110111011101110111011101, 101101110111011101110111011101 => 11101001010001000100010001000100011100
100100010101001101010110101010, 100010011101001011111110101000 => 110000110010101100001100111100010
</code>```

答:
Retina, <s>157</s> <s>151</s> <s>134</s> <s>133</s> <s>124</s> 123 bytes

1 byte off thanks to Martin Büttner.

```<code>(.+),(.+)
$.1$*0$2,$.2$*0$1,
1
0x
+`(0x*)(,.*)0(x*),
$2,$1$3
{`,

(^|0x0xx0xx)
000
(0x*)(0x*)(0x*0)xx
$1x$2x$3
)`^0+
0
0x
1
</code>```

Try it online!

Converts to unary, and then repeat the following replacements (shown here in decimal):

```<code>122 -> 000
0002 -> 1100 (this can also be 0012 -> 1110 and 1112 -> 2210 or even 2222 -> 3320 or even 3333 -> 4431)
</code>```

Basically, when larger than two: take away two, add nothing in the previous digit, add one to the previous digit, then add one to the previous digit.

In pseudocode:

```<code>if(a[n]>2):
    a[n] -= 2;
    a[n-2] += 1;
    a[n-3] += 1;
</code>```

Unary implementation:

Each digit (e.g. 3) is shown as the number of xs (e.g. xxx) and then prefixed with 0.

For example, 1234 would be expressed as 0x0xx0xxx0xxxx.

This leaves 0 unchanged, as 101 would be expressed by 0x00x.

Since initially and finally, there is only 0 and 1, the conversion could be easily done by 1->0x and 0x->1.

Click here to see every step.

Title: Addition in base -1+i

Body:
Retina, <s>157</s> <s>151</s> <s>134</s> <s>133</s> <s>124</s> 123 bytes

1 byte off thanks to Martin Büttner.

(.+),(.+)
$.1$*0$2,$.2$*0$1,
1
0x
+`(0x*)(,.*)0(x*),
$2,$1$3
{`,

(^|0x0xx0xx)
000
(0x*)(0x*)(0x*0)xx
$1x$2x$3
)`^0+
0
0x
1

Try it online!

Converts to unary, and then repeat the following replacements (shown here in decimal):

122 -> 000
0002 -> 1100 (this can also be 0012 -> 1110 and 1112 -> 2210 or even 2222 -> 3320 or even 3333 -> 4431)

Basically, when larger than two: take away two, add nothing in the previous digit, add one to the previous digit, then add one to the previous digit.

In pseudocode:

if(a[n]>2):
    a[n] -= 2;
    a[n-2] += 1;
    a[n-3] += 1;

Unary implementation:

Each digit (e.g. 3) is shown as the number of xs (e.g. xxx) and then prefixed with 0.

For example, 1234 would be expressed as 0x0xx0xxx0xxxx.

This leaves 0 unchanged, as 101 would be expressed by 0x00x.

Since initially and finally, there is only 0 and 1, the conversion could be easily done by 1->0x and 0x->1.

Click here to see every step.