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

Saved one byte due to @LuisMendo's tip here!

```<code>tfWt2/!-RXzB*c
</code>```

So many ways... had to find a new one. Happy bits! :)

Try it online!

Exploded

```<code>t       % duplicate input
f       % get indices of nonzero elements in vector (i.e. 1:n)
W       % 2 raised to array, element-wise: 2^(1:n)
t       % duplicate array
2/      % divide by 2: 2^(0:n-1)
!       % transpose array
-       % element-wise subtraction (w/singleton expansion)
R       % upper triangular part
Xz      % nonzero elements
B       % convert from decimal to binary. Produces a logical array
*       % array product (element-wise, singleton expansion)
c       % convert to character array; 0's automatically converted to spaces
</code>```

Title: Exploded substrings

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

Saved one byte due to @LuisMendo's tip here!

tfWt2/!-RXzB*c

So many ways... had to find a new one. Happy bits! :)

Try it online!

Exploded

t       % duplicate input
f       % get indices of nonzero elements in vector (i.e. 1:n)
W       % 2 raised to array, element-wise: 2^(1:n)
t       % duplicate array
2/      % divide by 2: 2^(0:n-1)
!       % transpose array
-       % element-wise subtraction (w/singleton expansion)
R       % upper triangular part
Xz      % nonzero elements
B       % convert from decimal to binary. Produces a logical array
*       % array product (element-wise, singleton expansion)
c       % convert to character array; 0's automatically converted to spaces


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

答:
Haskell, 65 bytes

```<code>(>>=zipWith((++).(`replicate`' '))[0..].init.tails).reverse.inits
</code>```

It requires inits and tails from Data.List, though. To output it, add mapM_ putStrLn. to the front.

Relatively straightforward; the reverse is to make sure the original string is first.

```<code>GHCi> mapM_ putStrLn.(>>=zipWith((++).(`replicate`' '))[0..].init.tails).reverse.inits$"abcde"
abcde
 bcde
  cde
   de
    e
abcd
 bcd
  cd
   d
abc
 bc
  c
ab
 b
a
it :: ()
(0.02 secs, 0 bytes)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Exploded substrings

Body:
Haskell, 65 bytes

(>>=zipWith((++).(`replicate`' '))[0..].init.tails).reverse.inits

It requires inits and tails from Data.List, though. To output it, add mapM_ putStrLn. to the front.

Relatively straightforward; the reverse is to make sure the original string is first.

GHCi> mapM_ putStrLn.(>>=zipWith((++).(`replicate`' '))[0..].init.tails).reverse.inits$"abcde"
abcde
 bcde
  cde
   de
    e
abcd
 bcd
  cd
   d
abc
 bc
  c
ab
 b
a
it :: ()
(0.02 secs, 0 bytes)


答:
Perl 6, 34 bytes

perl6 -ne 'm/^(.*)(.+)<{+put " "x$0.to,$1}>/'
```

<pre class="lang-perl6 prettyprint-override"><code>m/       # match the input line
  ^      # from the start
  ( .* ) # 0 or more characters ( $0 )
  ( .+ ) # 1 or more characters ( $1 )

  <{ # match against the result of:

    +put # print with a trailing newline:
      " " x $0.to, # add the leading spaces
      $1           # the substring
  }>
/
</code>```

The reason for the + before put is so that it returns 1 instead of True, which is guaranteed not to be in the input so it always has to backtrack.

$ perl6 -ne 'm/^(.*)(.+)<{+put " "x$0.to,$1}>/' <<< abcd
```

<pre class="lang-none prettyprint-override"><code>   d
  cd
  c
 bcd
 bc
 b
abcd
abc
ab
a
</code>```

( If you want it in the opposite order use (.*?)(.+?) instead of (.*)(.+) )

This was inspired by the Perl 5 answer.

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:
Perl 6, 34 bytes

perl6 -ne 'm/^(.*)(.+)<{+put " "x$0.to,$1}>/'

m/       # match the input line
  ^      # from the start
  ( .* ) # 0 or more characters ( $0 )
  ( .+ ) # 1 or more characters ( $1 )

  <{ # match against the result of:

    +put # print with a trailing newline:
      " " x $0.to, # add the leading spaces
      $1           # the substring
  }>
/

The reason for the + before put is so that it returns 1 instead of True, which is guaranteed not to be in the input so it always has to backtrack.

$ perl6 -ne 'm/^(.*)(.+)<{+put " "x$0.to,$1}>/' <<< abcd

   d
  cd
  c
 bcd
 bc
 b
abcd
abc
ab
a

( If you want it in the opposite order use (.*?)(.+?) instead of (.*)(.+) )

This was inspired by the Perl 5 answer.


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

答:
MATL, <s>31</s>, 25 bytes

```<code>BXHnQtHsy2/<w2\+~?2/Hfw)E
</code>```

This is just a MATL version of Agawa001's algorithm, except it takes an integer input N and returns the N-th term in the sequence. It was tricky keeping up with all the elements in the stack! I had to resort to using a clipboard to avoid going insane. You can Try it online!

Can be made into a loop printing the first N terms by adding :"@ before the code, and ]D after.

Thanks to Luis Mendo for saving 6 whole bytes!

Title: The Back-and-Forth Sequence

Body:
MATL, <s>31</s>, 25 bytes

BXHnQtHsy2/<w2\+~?2/Hfw)E

This is just a MATL version of Agawa001's algorithm, except it takes an integer input N and returns the N-th term in the sequence. It was tricky keeping up with all the elements in the stack! I had to resort to using a clipboard to avoid going insane. You can Try it online!

Can be made into a loop printing the first N terms by adding :"@ before the code, and ]D after.

Thanks to Luis Mendo for saving 6 whole bytes!


答:
Ruby, <s>75</s> 67 bytes

Anonymous function. <s>Uses regex substitution to align the substrings.</s> . is the filler character.

```<code>->s{(l=s.size).times{|i|(l-i).times{|j|puts s.tr(?^+s[j,i+1],?.)}}}
</code>```

Title: Exploded substrings

Body:
Ruby, <s>75</s> 67 bytes

Anonymous function. <s>Uses regex substitution to align the substrings.</s> . is the filler character.

->s{(l=s.size).times{|i|(l-i).times{|j|puts s.tr(?^+s[j,i+1],?.)}}}


问:
Construct the Identity Matrix
The challenge is very simple. Given an integer input n, output the n x n identity matrix. The identity matrix is one that has 1s spanning from the top left down to the bottom right. You will write a program or a function that will return or output the identity matrix you constructed. Your output may be a 2D array, or numbers separated by spaces/tabs and newlines.

Example input and output

```<code>1: [[1]]
2: [[1, 0], [0, 1]]
3: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
4: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
5: [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]

1
===
1

2
===
1 0
0 1

3
===
1 0 0
0 1 0
0 0 1

etc.
</code>```

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

答:
Javascript, 40

f=
n=>'0'.repeat(n).replace(/./g,"$`1$'\n")

I.oninput=_=>O.innerHTML=f(+I.value)
I.oninput()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id=I value=5>
<pre id=O></code>```

Title: Construct the Identity Matrix

Body:
Javascript, 40

f=
n=>'0'.repeat(n).replace(/./g,"$`1$'\n")

I.oninput=_=>O.innerHTML=f(+I.value)
I.oninput()

<input id=I value=5>
<pre id=O>


答:
Sage, 15 bytes

identity_matrix
```

Exactly what it says on the tin

Try it online

Thanks to Lynn for pointing out that I was being a doofus.

Title: Construct the Identity Matrix

Body:
The challenge is very simple. Given an integer input n, output the n x n identity matrix. The identity matrix is one that has 1s spanning from the top left down to the bottom right. You will write a program or a function that will return or output the identity matrix you constructed. Your output may be a 2D array, or numbers separated by spaces/tabs and newlines.

Example input and output

```<code>1: [[1]]
2: [[1, 0], [0, 1]]
3: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
4: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
5: [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]

1
===
1

2
===
1 0
0 1

3
===
1 0 0
0 1 0
0 0 1

etc.
</code>```

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

Body:
Sage, 15 bytes

identity_matrix

Exactly what it says on the tin

Try it online

Thanks to Lynn for pointing out that I was being a doofus.


问:
Generate a Kolakoski sequence

Definition1

A Kolakoski sequence is a self-describing infinite sequence {kn} of alternating blocks of 1's and 2's, given by the following rules:

k0 = 1

kn = the length of the (n+1)'th block

The Task

Given a positive integer n, generate the first n elements of the Kolakoski sequence.

Details

Input will be provided as a single command line argument n. Please write a full program that will print the first n elements of the Kolakoski sequence (in order) to STDOUT, with each element separated by your favorite whitespace.

Scoring

Lets count source code bytes this time with all whitespace included. Fewest number of bytes wins. In the event of a tie, the solution with the earliest submission time wins.

The Sequence2

1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, ...

References

John Smith, Ariel Scolnicov, yark. "Kolakoski sequence" (version 3). PlanetMath.org. Freely available at http://planetmath.org/KolakoskiSequence.html.

The Online Encyclopedia of Integer Sequences http://oeis.org/A000002

Other resources

Kolakoski Sequence at Wikipedia http://en.wikipedia.org/wiki/Kolakoski_sequence

Kolakoski Sequence at Wolfram MathWorld http://mathworld.wolfram.com/KolakoskiSequence.html

答:
Javascript (414 Characters)

```<code>function range(n,e,t){if("undefined"==typeof e&&(e=n,n=0),"undefined"==typeof t&&(t=1),t>0&&n>=e||0>t&&e>=n)return[];for(var i=[],r=n;t>0?e>r:r>e;r+=t)i.push(r);return i}function kolakoskiGen(n){var e=[1,2,2],t=parseInt(n),r=range(2,t);for(i in r)if(-1!=r.indexOf(parseInt(i))){var f=[1+i%2];f.length=f.length*e[i],f[f.length-1]=f[0],2==f.length?(e[e.length]=f[0],e[e.length]=f[1]):e[e.length]=f[0]}console.log(e)}
</code>```

Could probably be more Efficient

Title: Generate a Kolakoski sequence

Body:
Javascript (414 Characters)

function range(n,e,t){if("undefined"==typeof e&&(e=n,n=0),"undefined"==typeof t&&(t=1),t>0&&n>=e||0>t&&e>=n)return[];for(var i=[],r=n;t>0?e>r:r>e;r+=t)i.push(r);return i}function kolakoskiGen(n){var e=[1,2,2],t=parseInt(n),r=range(2,t);for(i in r)if(-1!=r.indexOf(parseInt(i))){var f=[1+i%2];f.length=f.length*e[i],f[f.length-1]=f[0],2==f.length?(e[e.length]=f[0],e[e.length]=f[1]):e[e.length]=f[0]}console.log(e)}

Could probably be more Efficient


答:
Sage, 112 bytes

lambda A,n:reduce(lambda A,B:[[sum(map(mul,zip(a,b)))for b in zip(*B)]for a in A],[A]*n,identity_matrix(len(A)))
```

Try it online

Explanation:

The inner lambda (lambda A,B:[[sum(map(mul,zip(a,b)))for b in zip(*B)]for a in A]) is a straightforward implementation of matrix multiplication. The outer lambda (lambda A,n:reduce(...,[A]*n,identity_matrix(len(A)))) uses reduce to compute the matrix power by iterated matrix multiplication (using the aforementioned homemade matrix multiplication function), with the identity matrix as the initial value to support n=0.

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:
Sage, 112 bytes

lambda A,n:reduce(lambda A,B:[[sum(map(mul,zip(a,b)))for b in zip(*B)]for a in A],[A]*n,identity_matrix(len(A)))

Try it online

Explanation:

The inner lambda (lambda A,B:[[sum(map(mul,zip(a,b)))for b in zip(*B)]for a in A]) is a straightforward implementation of matrix multiplication. The outer lambda (lambda A,n:reduce(...,[A]*n,identity_matrix(len(A)))) uses reduce to compute the matrix power by iterated matrix multiplication (using the aforementioned homemade matrix multiplication function), with the identity matrix as the initial value to support n=0.


答:
Python 2, 74 bytes

```<code>def f(x):k=len(x)+1;print next((i*2for i in range(k)if k==2*sum(x[:i])),k)
</code>```

This function accepts a single integer in form of the list of its binary digits as input.

The algorithm is equivalent to the one from @Agawa001's answer and my Jelly answer.

Test it on Ideone.

How it works

next attempts to find the first integer 2i for which k==2*sum(x[:i]) returns true. Since x[:i] contains i elements, this gives the 1-based index of the (k / 2)th 1.

next will fail if k/2 is non-integral or if x contains less than k / 2 ones. In this case, the default value k is returned.

Title: The Back-and-Forth Sequence

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

Body:
Python 2, 74 bytes

def f(x):k=len(x)+1;print next((i*2for i in range(k)if k==2*sum(x[:i])),k)

This function accepts a single integer in form of the list of its binary digits as input.

The algorithm is equivalent to the one from @Agawa001's answer and my Jelly answer.

Test it on Ideone.

How it works

next attempts to find the first integer 2i for which k==2*sum(x[:i]) returns true. Since x[:i] contains i elements, this gives the 1-based index of the (k / 2)th 1.

next will fail if k/2 is non-integral or if x contains less than k / 2 ones. In this case, the default value k is returned.


答:
Julia, <s>90</s> <s>86</s> 68 bytes

f(A,n)=n<1?eye(A):[A[i,:][:]⋅f(A,n-1)[:,j]for i=m=1:size(A,1),j=m]
```

<p>This is a recursive function that accepts a matrix (<code>Array{Int,2}</code>) and an integer and returns a matrix.</p>

<p>Ungolfed:</p>

<pre class="lang-default prettyprint-override"><code>function f(A, n)
    if n < 1
        # Identity matrix with the same type and dimensions as the input
        eye(A)
    else
        # Compute the dot product of the ith row of A and the jth column
        # of f called on A with n decremented
        [dot(A[i,:][:], f(A, n-1)[:,j]) for i = (m = 1:size(A,1)), j = m]
    end
end
</code>```

Try it online! (includes all but the last test case, which is too slow for the site)

Saved 18 bytes thanks to Dennis!

Title: Find the Matrix Power

Body:
Julia, <s>90</s> <s>86</s> 68 bytes

f(A,n)=n<1?eye(A):[A[i,:][:]⋅f(A,n-1)[:,j]for i=m=1:size(A,1),j=m]

This is a recursive function that accepts a matrix (Array{Int,2}) and an integer and returns a matrix.

Ungolfed:

function f(A, n)
    if n < 1
        # Identity matrix with the same type and dimensions as the input
        eye(A)
    else
        # Compute the dot product of the ith row of A and the jth column
        # of f called on A with n decremented
        [dot(A[i,:][:], f(A, n-1)[:,j]) for i = (m = 1:size(A,1)), j = m]
    end
end

<a href="http://julia.tryitonline.net/#code=ZihBLG4pPW48MT9leWUoQSk6W0FbaSw6XVs6XeKLhWYoQSxuLTEpWzosal1mb3IgaT1tPTE6c2l6ZShBLDEpLGo9bV0KCmZvciBjYXNlIGluIFsoWzYyIDcyOyAxMCAzNF0sIDApLAogICAgICAgICAgICAgKFsyMyA2MSA0NzsgODEgMTEgNjA7IDQyICA5ICAwXSwgMSksCiAgICAgICAgICAgICAoWzEyICAyOCAtMjYgIDM7IC0zIC0xMCAtMTMgIDA7IDI1ICA0MSAgIDMgLTQ7IC0yMCAtMTQgIC00IDI5XSwgMiksCiAgICAgICAgICAgICAoWy00MiAtMTkgIDE4IC0zODsgLTMzICAyNiAtMTMgIDMxOyAtNDMgIDI1IC00OCAgMjg7IDM0IC0yNiAgMTkgLTQ4XSwgNCldCiAgICBwcmludGxuKGYoY2FzZVsxXSwgY2FzZVsyXSkgPT0gY2FzZVsxXV5jYXNlWzJdKQplbmQ&input=" rel="nofollow">Try it online! (includes all but the last test case, which is too slow for the site)

Saved 18 bytes thanks to Dennis!


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

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

The Rules

Each submission must be a full program.

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

The program must not write anything to STDERR.

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

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

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

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

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

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

For inspiration, check the Hello World Collection.

The Catalogue

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

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

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

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

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

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

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

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

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Y 16 bytes

No, not http://foldoc.org/Y or https://github.com/ConorOBrien-Foxx/Y although we probably need an entry for both of them as well...

Y is a stack-oriented FORTH-type programming language by Thomas Fischbacher derived from Wouter van Oortmerssen's "FALSE". Like FALSE, Y is cryptic to the extreme. According to the readme it is much more powerful because "virtually all of the example programs in 'Kernighan & Ritchie - Programming in C' can be done in Y in a fraction of time and code."

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

ContentLicense: CC BY-SA 4.0

Title: "Hello, World!"

Body:
Y 16 bytes

No, not http://foldoc.org/Y or https://github.com/ConorOBrien-Foxx/Y although we probably need an entry for both of them as well...

Y is a stack-oriented FORTH-type programming language by Thomas Fischbacher derived from Wouter van Oortmerssen's "FALSE". Like FALSE, Y is cryptic to the extreme. According to the readme it is much more powerful because "virtually all of the example programs in 'Kernighan & Ritchie - Programming in C' can be done in Y in a fraction of time and code."

"Hello, World!"`


答:
Jelly, 10 bytes

```<code>ð+\ḤiḤoµL‘
</code>```

This function accepts a single integer in form of the list of its binary digits as input.

The algorithm is equivalent to the one from @Agawa001's answer.

Try it online! or generate the first 2048 numbers.

Background

Enumerate the positions underneath the path from 0 to L, giving a total of L + 1 positions. L coincides the number of binary digits of the number N that encodes the path. With this notation, the walker starts at position 0, the goal at position L.

With each step the walker takes, he gets one step closer to the goal (in the direction he's currently walking). Also, with each shift-step, depending on whether he walks with or against the shifting direction, he either increments or decrements his position by 2 modulo L + 1, or he stays in the current position.

To change direction, he has to land on position L - 1 (facing L) or position 1 (facing 0), then get shifted in his direction. The next step he takes will bring him back to his previous position, facing the opposite direction.

If L is even, L - 1 is odd, so he cannot advance from his initial position to L - 1 directly. The only way to reach it is to pass through L, getting carried to 0 and taking the next step to land on 1, then advancing to the right. This requires advancing 2L positions, which can be done in no less than L steps.

However, after taking L steps without changing direction, he will have reached the goal. Adding one for the starting cell, we get a total of L + 1 visited cells in this case.

If L is odd, L - 1 is even, so he can reach that position by getting shifted (L - 1) / 2 times to the right. If position L - 1 is underneath a 1 at that time, he will get shifted to position L, turn around, and step on position L - 1 (facing leftwards).

This may or may not happen before he reaches his goal, so there are two cases to analyze:

If there are less than (L + 1) / 2 occurrences of 1 in the binary expansion of N, taking L steps will not suffice to turn direction. Since these L steps bring the walker to his goal, adding one for the starting cell, we get a total of L + 1 visited cells in this case.

If there are at least (L + 1) / 2 occurrences of 1 in the binary expansion of N, advancing to the ((L + 1) / 2)th occurrence will require I steps, where I is the initial position of that occurrence of 1.

Thus, after taking I steps, the walker is in position L - 1, facing leftwards. To turn directions again, he would have to walk advance leftwards to position 1. However, as in the even case, since (L - 1) - 1 is odd, this will require going through 0 and taking no less tha L steps.

Since the initial distance to the goal in the left direction is 1, after taking I steps, the walker finds himself at distance of I + 1 from the goal after changing directions. Since I < L, we have that I + 1 ≤ L, so the next I + 1 steps will bring him to the goal.

This gives a total of I + I + 1 = 2I + 1 taken steps. Adding one for the starting cell, we get a total of 2I + 1 + 1 = 2(I + 1) visited cells in this case.

How it works

```<code>ð+\ḤiḤoµL‘  Main link. Argument: x (list of binary digits of N)

       µ    Monadic chain. Argument: x
        L   Compute L, the length of x.
         ‘  Increment to yield L + 1.

ð           Dyadic chain. Left argument: x. Right argument: L + 1
 +\         Compute the cumulative sum of x.
            This replaces the k-th one (and all zeroes to its right) with k.
   Ḥ        Unhalve; multiply all partial sums by 2.
    i       Find the first index of L + 1.
            This either gives I + 1, the 1-based index of the ((L + 1) / 2)-th one
            or 0 if the list doesn't contain L + 1.
            The result will be 0 if x contains less than (L + 1) / 2 ones
            or if L + 1 is an odd integer.
     Ḥ      Unhalve; yield either 2(I + 1) or 0.
      o     Logical OR with L + 1; if the previous operation returned a falsy
            value (i.e., if it yielded 0), replace that value with L + 1.
</code>```

Title: The Back-and-Forth Sequence

Body:
Jelly, 10 bytes

ð+\ḤiḤoµL‘

This function accepts a single integer in form of the list of its binary digits as input.

The algorithm is equivalent to the one from @Agawa001's answer.

Try it online! or generate the first 2048 numbers.

Background

Enumerate the positions underneath the path from 0 to L, giving a total of L + 1 positions. L coincides the number of binary digits of the number N that encodes the path. With this notation, the walker starts at position 0, the goal at position L.

With each step the walker takes, he gets one step closer to the goal (in the direction he's currently walking). Also, with each shift-step, depending on whether he walks with or against the shifting direction, he either increments or decrements his position by 2 modulo L + 1, or he stays in the current position.

To change direction, he has to land on position L - 1 (facing L) or position 1 (facing 0), then get shifted in his direction. The next step he takes will bring him back to his previous position, facing the opposite direction.

If L is even, L - 1 is odd, so he cannot advance from his initial position to L - 1 directly. The only way to reach it is to pass through L, getting carried to 0 and taking the next step to land on 1, then advancing to the right. This requires advancing 2L positions, which can be done in no less than L steps.

However, after taking L steps without changing direction, he will have reached the goal. Adding one for the starting cell, we get a total of L + 1 visited cells in this case.

If L is odd, L - 1 is even, so he can reach that position by getting shifted (L - 1) / 2 times to the right. If position L - 1 is underneath a 1 at that time, he will get shifted to position L, turn around, and step on position L - 1 (facing leftwards).

This may or may not happen before he reaches his goal, so there are two cases to analyze:

If there are less than (L + 1) / 2 occurrences of 1 in the binary expansion of N, taking L steps will not suffice to turn direction. Since these L steps bring the walker to his goal, adding one for the starting cell, we get a total of L + 1 visited cells in this case.

If there are at least (L + 1) / 2 occurrences of 1 in the binary expansion of N, advancing to the ((L + 1) / 2)th occurrence will require I steps, where I is the initial position of that occurrence of 1.

Thus, after taking I steps, the walker is in position L - 1, facing leftwards. To turn directions again, he would have to walk advance leftwards to position 1. However, as in the even case, since (L - 1) - 1 is odd, this will require going through 0 and taking no less tha L steps.

Since the initial distance to the goal in the left direction is 1, after taking I steps, the walker finds himself at distance of I + 1 from the goal after changing directions. Since I < L, we have that I + 1 ≤ L, so the next I + 1 steps will bring him to the goal.

This gives a total of I + I + 1 = 2I + 1 taken steps. Adding one for the starting cell, we get a total of 2I + 1 + 1 = 2(I + 1) visited cells in this case.

How it works

ð+\ḤiḤoµL‘  Main link. Argument: x (list of binary digits of N)

       µ    Monadic chain. Argument: x
        L   Compute L, the length of x.
         ‘  Increment to yield L + 1.

ð           Dyadic chain. Left argument: x. Right argument: L + 1
 +\         Compute the cumulative sum of x.
            This replaces the k-th one (and all zeroes to its right) with k.
   Ḥ        Unhalve; multiply all partial sums by 2.
    i       Find the first index of L + 1.
            This either gives I + 1, the 1-based index of the ((L + 1) / 2)-th one
            or 0 if the list doesn't contain L + 1.
            The result will be 0 if x contains less than (L + 1) / 2 ones
            or if L + 1 is an odd integer.
     Ḥ      Unhalve; yield either 2(I + 1) or 0.
      o     Logical OR with L + 1; if the previous operation returned a falsy
            value (i.e., if it yielded 0), replace that value with L + 1.


问:
Write the shortest program that generates the most compiler warnings and errors

The challenge:

Write a very short program that, when compiled, creates the most amount of compiler warnings and errors. It can be written in any programming language.

Scoring:

The score is determined by this equation: errors_and_warnings_length/code_length. Highest score wins.

Example:

The C# program class is 5 chars long and generates 3 warnings, which is a score of (1/5)*3 = 0.6.

EDIT:

Because of some confusion, programs have to be at least 1 char long. Otherwise it would get a score of infinity.

答:
C++98 (211 bytes) g++-5 (Ubuntu 5.2.1-23ubuntu1~12.04) 5.2.1 0151031

I wanted to see how well I could do in C++ without using the preprocessor at all. This program produces 2,139,390,572 bytes of output, most of which is a single error message.

```<code>template<int i,class S,class T>struct R{typedef R<i,typename R<i-1,S,S>::D,typename R<i-1,S,S>::D>D;};template<class S,class T>struct R<0,S,T>{typedef S D;};void f(){R<27,float,R<24,int*const*,int>::D>::D&E=4;}

me@Basement:~/src/junk$ ls -l a.C
-rw-rw-r-- 1 me me 211 Apr 27 21:44 a.C
me@Basement:~/src/junk$ g++-5 a.C -fmax-errors=1 2>a.C.errors.txt
me@Basement:~/src/junk$ ls -l a.C.errors.txt
-rw-rw-r-- 1 me me 2139390572 Apr 27 22:01 a.C.errors.txt
</code>```

Ungolfed:

```<code>template <int i, class S, class T>
struct R {
    typedef R<i, typename R<i-1,S,S>::D, typename R<i-1,S,S>::D> D;
};
template <class S, class T>
struct R<0, S, T> {
    typedef S D;
};
void f() {
    R<27, float, R<24, int*const*, int>::D>::D &E = 4;
}
</code>```

This program works by defining a recursive struct template R which holds a typedef D containing two copies of R. This results in an type name which grows exponentially, which is printed out in full in the error message. Unfortunately, g++ seems to choke while attempting to print an error message longer than (1<<31) bytes. 2,139,390,572 bytes was the closest I could get to the limit without going over. I'm curious if anyone can adjust the recursion limits and parameter types 27, float, 24, int*const* to get closer to the limit (or find a compiler which can print an even longer error message).

Excerpts from the error message:

```<code>a.C: In function ‘void f()’:
a.C:1:208:  error:  invalid  initialization  of non-const reference of type
‘R<27, float, R<24, R<23, R<22, R<21, R<20, R<19, R<18, R<17, R<16, R<15,
R<14,  R<13, R<12, R<11, R<10, R<9, R<8, R<7, R<6, R<5, R<4, R<3, R<2, R<1,
int* const*, int* const*>, R<1, int* const*, int* const*> >, R<2, R<1, int*
const*,  int*  const*>,  R<1, int* const*, int* const*> > >, R<3, R<2, R<1,
int* const*, int* const*>, R<1, int* const*, int* const*> >, R<2, R<1, int*
const*,  int* const*>, R<1, int* const*, int* const*> > > >, R<4, R<3, R<2,
R<1, int* const*, int* const*>, R<1,
...
int*  const*,  int*  const*>  > > > > > > > > > > > > > > > > > > > > > > >
>::D& {aka R<27, R<26, R<25, R<24, R<23,  R<22,  R<21,  R<20,  R<19,  R<18,
R<17,  R<16,  R<15,  R<14, R<13, R<12, R<11, R<10, R<9, R<8, R<7, R<6, R<5,
R<4, R<3, R<2, R<1, float, float>, R<1, float, float> >, R<2,  R<1,  float,
float>,  R<1,  float, float> > >, R<3, R<2, R<1, float, float>, R<1, float,
float> >, R<2, R<1, float, float>, R<1, float, float> > > >, R<4,
...
, R<1, float, float>, R<1, float, float> > >, R<3, R<2, R<1, float, float>,
R<1, float, float> >, R<2, R<1, float, float>, R<1, float, float> > > > > >
>  >  >  >  >  >  > > > > > > > > > > > > > > >&}’ from an rvalue of type
‘int’
    template<int    i,class   S,class   T>struct   R{typedef   R<i,typename
R<i-1,S,S>::D,typename  R<i-1,S,S>::D>D;};template<class  S,class  T>struct
R<0,S,T>{typedef                         S                         D;};void
f(){R<27,float,R<24,int*const*,int>::D>::D&E=4;}

                                                        ^
compilation terminated due to -fmax-errors=1.
</code>```

2,139,390,572 bytes / 211 bytes = 10,139,291.8

Body:
C++98 (211 bytes) g++-5 (Ubuntu 5.2.1-23ubuntu1~12.04) 5.2.1 0151031

I wanted to see how well I could do in C++ without using the preprocessor at all. This program produces 2,139,390,572 bytes of output, most of which is a single error message.

template<int i,class S,class T>struct R{typedef R<i,typename R<i-1,S,S>::D,typename R<i-1,S,S>::D>D;};template<class S,class T>struct R<0,S,T>{typedef S D;};void f(){R<27,float,R<24,int*const*,int>::D>::D&E=4;}

me@Basement:~/src/junk$ ls -l a.C
-rw-rw-r-- 1 me me 211 Apr 27 21:44 a.C
me@Basement:~/src/junk$ g++-5 a.C -fmax-errors=1 2>a.C.errors.txt
me@Basement:~/src/junk$ ls -l a.C.errors.txt
-rw-rw-r-- 1 me me 2139390572 Apr 27 22:01 a.C.errors.txt

Ungolfed:

template <int i, class S, class T>
struct R {
    typedef R<i, typename R<i-1,S,S>::D, typename R<i-1,S,S>::D> D;
};
template <class S, class T>
struct R<0, S, T> {
    typedef S D;
};
void f() {
    R<27, float, R<24, int*const*, int>::D>::D &E = 4;
}

This program works by defining a recursive struct template R which holds a typedef D containing two copies of R. This results in an type name which grows exponentially, which is printed out in full in the error message. Unfortunately, g++ seems to choke while attempting to print an error message longer than (1<<31) bytes. 2,139,390,572 bytes was the closest I could get to the limit without going over. I'm curious if anyone can adjust the recursion limits and parameter types 27, float, 24, int*const* to get closer to the limit (or find a compiler which can print an even longer error message).

Excerpts from the error message:

a.C: In function ‘void f()’:
a.C:1:208:  error:  invalid  initialization  of non-const reference of type
‘R<27, float, R<24, R<23, R<22, R<21, R<20, R<19, R<18, R<17, R<16, R<15,
R<14,  R<13, R<12, R<11, R<10, R<9, R<8, R<7, R<6, R<5, R<4, R<3, R<2, R<1,
int* const*, int* const*>, R<1, int* const*, int* const*> >, R<2, R<1, int*
const*,  int*  const*>,  R<1, int* const*, int* const*> > >, R<3, R<2, R<1,
int* const*, int* const*>, R<1, int* const*, int* const*> >, R<2, R<1, int*
const*,  int* const*>, R<1, int* const*, int* const*> > > >, R<4, R<3, R<2,
R<1, int* const*, int* const*>, R<1,
...
int*  const*,  int*  const*>  > > > > > > > > > > > > > > > > > > > > > > >
>::D& {aka R<27, R<26, R<25, R<24, R<23,  R<22,  R<21,  R<20,  R<19,  R<18,
R<17,  R<16,  R<15,  R<14, R<13, R<12, R<11, R<10, R<9, R<8, R<7, R<6, R<5,
R<4, R<3, R<2, R<1, float, float>, R<1, float, float> >, R<2,  R<1,  float,
float>,  R<1,  float, float> > >, R<3, R<2, R<1, float, float>, R<1, float,
float> >, R<2, R<1, float, float>, R<1, float, float> > > >, R<4,
...
, R<1, float, float>, R<1, float, float> > >, R<3, R<2, R<1, float, float>,
R<1, float, float> >, R<2, R<1, float, float>, R<1, float, float> > > > > >
>  >  >  >  >  >  > > > > > > > > > > > > > > >&}’ from an rvalue of type
‘int’
    template<int    i,class   S,class   T>struct   R{typedef   R<i,typename
R<i-1,S,S>::D,typename  R<i-1,S,S>::D>D;};template<class  S,class  T>struct
R<0,S,T>{typedef                         S                         D;};void
f(){R<27,float,R<24,int*const*,int>::D>::D&E=4;}

                                                        ^
compilation terminated due to -fmax-errors=1.

2,139,390,572 bytes / 211 bytes = 10,139,291.8


答:
Julia 0.4, 4̷4̷  42 bytes

```<code>x->(k=endof(x)+1;try k=2find(x)[k/2]end;k)
</code>```

This function accepts a single integer in form of the list of its binary digits as input.

The algorithm is equivalent to the one from @Agawa001's answer and my Jelly answer.

Try it online!

How it works

find(x) returns the 1-based indices of all non-zero elements of x. We attempt to access the resulting array at index k / 2 and, if successful, overwrite k with twice the selected index.

This will fail if and only if one of the following is true:

k / 2 is a non-integral float, so and InexactError is raised.

The index array has less than k / 2 elements, so a BoundsError is raised.

In either case, overwriting k will fail, so its original value will be returned.

Title: The Back-and-Forth Sequence

Body:
Julia 0.4, 4̷4̷  42 bytes

x->(k=endof(x)+1;try k=2find(x)[k/2]end;k)

This function accepts a single integer in form of the list of its binary digits as input.

The algorithm is equivalent to the one from @Agawa001's answer and my Jelly answer.

Try it online!

How it works

find(x) returns the 1-based indices of all non-zero elements of x. We attempt to access the resulting array at index k / 2 and, if successful, overwrite k with twice the selected index.

This will fail if and only if one of the following is true:

k / 2 is a non-integral float, so and InexactError is raised.

The index array has less than k / 2 elements, so a BoundsError is raised.

In either case, overwriting k will fail, so its original value will be returned.


问:
Generate n digits of Gijswijt's sequence

Introduction

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

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

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

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

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

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

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

The sequence is generated like so:

The first term is 1.

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

To clarify, here are the first few terms.

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

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

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

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

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

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

Task

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

Instructions

The input will be an integer n.

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

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

答:
CJam, <s>33</s> <s>31</s> <s>30</s> 27 bytes

Thanks to Peter Taylor for saving 1 byte.

```<code>1sri({),:)1$W%f/:e`$W=sc+}
</code>```

Test it here.

Explanation

```<code>1s      e# Initialise the sequence as "1".
ri(     e# Read input N and decrement.
{       e# For each I from 0 to N-1...
  )     e#   Increment to get I from 1 to N.
  ,     e#   Turn into a range [0 1 ... I-1].
  :)    e#   Increment each element to get [1 2 ... I].
  1$    e#   Copy sequence so far.
  W%    e#   Reverse the copy.
  f/    e#   For each element x in [1 2 ... I], split the (reversed) sequence
        e#   into (non-overlapping) chunks of length x. These are the potentially
        e#   repeated blocks we're looking for. We now want to find the splitting
        e#   which starts with the largest number of equal blocks.
  :e`   e#   To do that, we run-length encode each list blocks.
  $     e#   Then we sort the list of run-length encoded splittings, which primarily
        e#   sorts them by the length of the first run.
  W=    e#   We extract the last splitting which starts with the longest run.
  sc    e#   And then we extract the length of the first run by flattening
        e#   the list into a string and retrieving the first character.
  +     e#   This is the new element of the sequence, so we append it.
}/
</code>```

Body:
CJam, <s>33</s> <s>31</s> <s>30</s> 27 bytes

Thanks to Peter Taylor for saving 1 byte.

1sri({),:)1$W%f/:e`$W=sc+}

Test it here.

Explanation

1s      e# Initialise the sequence as "1".
ri(     e# Read input N and decrement.
{       e# For each I from 0 to N-1...
  )     e#   Increment to get I from 1 to N.
  ,     e#   Turn into a range [0 1 ... I-1].
  :)    e#   Increment each element to get [1 2 ... I].
  1$    e#   Copy sequence so far.
  W%    e#   Reverse the copy.
  f/    e#   For each element x in [1 2 ... I], split the (reversed) sequence
        e#   into (non-overlapping) chunks of length x. These are the potentially
        e#   repeated blocks we're looking for. We now want to find the splitting
        e#   which starts with the largest number of equal blocks.
  :e`   e#   To do that, we run-length encode each list blocks.
  $     e#   Then we sort the list of run-length encoded splittings, which primarily
        e#   sorts them by the length of the first run.
  W=    e#   We extract the last splitting which starts with the longest run.
  sc    e#   And then we extract the length of the first run by flattening
        e#   the list into a string and retrieving the first character.
  +     e#   This is the new element of the sequence, so we append it.
}/


答:
J, <s>35</s> <s>23</s> 22 bytes

```<code>[:;#\.<@{."_1|.\."1^:2
</code>```

It took me a while but I finally optimized it.

Usage

```<code>   f =: [:;#\.<@{."_1|.\."1^:2
   f 'abcde'
abcde
abcd
abc
ab
a
 bcde
 bcd
 bc
 b
  cde
  cd
  c
   de
   d
    e
</code>```

Explanation

```<code>[:;#\.<@{."_1|.\."1^:2  Input: s
             |.\."1     For each suffix of s, reverse it
                   ^:2  Repeat that twice to create all exploded substrings
   #\.                  Get the length of each suffix. This is
                        used to make the range [len(s), len(s)-1, ..., 1]
        {."_1           For each value in the range, take that many strings from
                        the list of exploded substrings. This avoids blank substrings
      <@                Box each set of strings
[:;                     Unbox and join the strings together and return
</code>```

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:
J, <s>35</s> <s>23</s> 22 bytes

[:;#\.<@{."_1|.\."1^:2

It took me a while but I finally optimized it.

Usage

   f =: [:;#\.<@{."_1|.\."1^:2
   f 'abcde'
abcde
abcd
abc
ab
a
 bcde
 bcd
 bc
 b
  cde
  cd
  c
   de
   d
    e

Explanation

[:;#\.<@{."_1|.\."1^:2  Input: s
             |.\."1     For each suffix of s, reverse it
                   ^:2  Repeat that twice to create all exploded substrings
   #\.                  Get the length of each suffix. This is
                        used to make the range [len(s), len(s)-1, ..., 1]
        {."_1           For each value in the range, take that many strings from
                        the list of exploded substrings. This avoids blank substrings
      <@                Box each set of strings
[:;                     Unbox and join the strings together and return


答:
Pyth, <s>41</s> 38 bytes

```<code>J]1VSQ=J+h.MZmh+fn@c+J0dT<JdSNZSNJ;P_J
</code>```

Try it online!

Title: Generate n digits of Gijswijt's sequence

Body:
Introduction

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

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

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

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

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

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

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

The sequence is generated like so:

The first term is 1.

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

To clarify, here are the first few terms.

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

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

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

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

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

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

Task

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

Instructions

The input will be an integer n.

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

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

Body:
Pyth, <s>41</s> 38 bytes

J]1VSQ=J+h.MZmh+fn@c+J0dT<JdSNZSNJ;P_J

Try it online!


答:
Pyth, <s>25</s> <s>22</s> 21 bytes

```<code>t_u+eSmtfxG*Td1._GGQN
</code>```

OP confirmed that we only need to handle single-digit numbers. This allowed to store the list as a string of digits. -> Saved 3 bytes

Try it online: Demonstration

Explanation:

```<code>t_u+...GQN      implicit: Q = input number
         N      start with the string G = '"'
  u     Q       do the following Q times:
    ...            generate the next number
   +   G           and prepend it to G
 _              print reversed string at the end
t               remove the first char (the '"')
</code>```

And here's how I generate the next number:

```<code>eSmtfxG*Td1._G
           ._G    generate all prefixes of G
  m               map each prefix d to:
    f     1          find the first number T >= 1, so that:
       *Td              d repeated T times
     xG                 occurs at the beginning of G
 S                  sort all numbers
e                   take the last one (maximum)
</code>```

21 bytes with lists

```<code>_u+eSmhhrcGd8SlGGtQ]1
</code>```

Try it online: Demonstration

Uses the same ideas of Martin and Peter. At each step I split the string into pieces of length 1, pieces of length 2, ... Then I range-length-encode them and use the maximal first run as next number.

20 bytes with strings

```<code>t_u+eSmhhrcGd8SlGGQN
</code>```

Try it online: Demonstration

Combines the ideas of the two codes above.

Body:
Pyth, <s>25</s> <s>22</s> 21 bytes

t_u+eSmtfxG*Td1._GGQN

OP confirmed that we only need to handle single-digit numbers. This allowed to store the list as a string of digits. -> Saved 3 bytes

Try it online: Demonstration

Explanation:

t_u+...GQN      implicit: Q = input number
         N      start with the string G = '"'
  u     Q       do the following Q times:
    ...            generate the next number
   +   G           and prepend it to G
 _              print reversed string at the end
t               remove the first char (the '"')

And here's how I generate the next number:

eSmtfxG*Td1._G
           ._G    generate all prefixes of G
  m               map each prefix d to:
    f     1          find the first number T >= 1, so that:
       *Td              d repeated T times
     xG                 occurs at the beginning of G
 S                  sort all numbers
e                   take the last one (maximum)

21 bytes with lists

_u+eSmhhrcGd8SlGGtQ]1

Try it online: Demonstration

Uses the same ideas of Martin and Peter. At each step I split the string into pieces of length 1, pieces of length 2, ... Then I range-length-encode them and use the maximal first run as next number.

20 bytes with strings

t_u+eSmhhrcGd8SlGGQN

Try it online: Demonstration

Combines the ideas of the two codes above.


答:
JavaScript (ES6), 123 bytes

```<code>(n,a)=>[...Array(n)].map(_=>r=m(i=>m(j=>m(k=>s+=a[i][k]*r[k][j],s=0)&&s)),m=g=>a.map((_,n)=>g(n)),r=m(i=>m(j=>+!(i^j))))&&r
</code>```

I had a 132 byte version using reduce but I was just mapping over a so often that it turned out to be 9 bytes shorter to write a helper function to do it for me. Works by creating the identity matrix and multiplying it by a longhand n times. There are a number of expressions that return 0 or 1 for i == j but they all seem to be 7 bytes long.

Title: Find the Matrix Power

Body:
JavaScript (ES6), 123 bytes

(n,a)=>[...Array(n)].map(_=>r=m(i=>m(j=>m(k=>s+=a[i][k]*r[k][j],s=0)&&s)),m=g=>a.map((_,n)=>g(n)),r=m(i=>m(j=>+!(i^j))))&&r

I had a 132 byte version using reduce but I was just mapping over a so often that it turned out to be 9 bytes shorter to write a helper function to do it for me. Works by creating the identity matrix and multiplying it by a longhand n times. There are a number of expressions that return 0 or 1 for i == j but they all seem to be 7 bytes long.


问:
Swap Pairs or Remove

Specification

For this challenge you will:

Take an array of positive integers.

For each overlapping pair in the array, calculate the difference of it's integers. If the difference is a common divisor of the integers (they are both divisible by their difference), swap their positions in the array. The values of the next pair are affected by this swap. No integer is divisible by 0.

If an integer was not divisible by the difference of any of it's pairs, remove it from the array.

Repeat the previous two steps until the length of the array will not decrease any further.

Output the length of the resulting array.

Example

Input = [ 4, 5, 2, 4 ].

Difference of first pair [ ( 4, 5, ) 2, 4 ] = 1, (common divisor of 4 and 5)

Swap the pair and the array becomes [ 5, 4, 2, 4 ].

Difference of second pair [ 5, ( 4, 2, ) 4 ] = 2 (common divisor of 4 and 2)

Swap the pair so the array becomes [ 5, 2, 4, 4 ].

Difference of third pair [ 5, 2, ( 4, 4 ) ] = 0 (not a divisor of any integer)

Do not swap the pair so the array remains the same.

The final 4 was never swapped, remove it so the array becomes [ 5, 2, 4 ].

Repeat.

Difference of first pair [ ( 5, 2, ) 4 ] = 3

Do not swap the pair so the array remains the same.

Difference of second pair [ 5, ( 2, 4 ) ] = 2

Swap the pair so the array becomes [ 5, 4, 2 ].

The 5 was never swapped, remove it so the array becomes [ 4, 2 ]

Repeat.

From here the array will endlessly switch between [ 4, 2 ] and [ 2, 4 ], so output the resulting length of 2.

Rules

Input array will always have a length between 2 and 9 inclusive.

Integers will always be between 1 and 999 inclusive.

Input can optionally be in the form of a string delimited by a specific character.

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

Test Cases

Format: [ input array ] = result (steps to get result, do not output this)

```<code>[ 1, 1 ] = 0                        ([])
[ 1, 2 ] = 2                        ([ 2, 1 ] -> [ 1, 2 ] -> ...)
[ 1, 2, 3 ] = 2                     ([ 2, 1 ] -> [ 1, 2 ] -> ...)
[ 4, 6, 8 ] = 3                     ([ 6, 8, 4 ] -> [ 8, 4, 6 ] -> [ 4, 6, 8 ] -> ...)
[ 99, 1, 3 ] = 0                    ([])
[ 4, 5, 2, 4 ] = 2                  ([ 5, 2, 4 ] -> [ 4, 2 ] -> [ 2, 4 ] -> ...)
[ 12, 4, 6, 3 ] = 3                 ([ 6, 4, 3 ] -> [ 4, 3, 6 ] -> [ 3, 6, 4 ] -> ...)
[ 9, 6, 10, 18 ] = 2                ([ 6, 10, 18, 9 ] -> [ 9, 18 ] -> [ 18, 9 ] -> ...)
[ 55, 218, 654, 703, 948, 960 ] = 2
[ 954, 973, 925, 913, 924, 996, 927, 981, 905 ] = 2
</code>```

答:
JavaScript (ES6), 133

Recursive function.

F=(m,k=[])=>(k[m]=m,f=m.map((x,i)=>x%(w=x-(y=m[i+1]))==0&y%w==0?m[m[i]=y,i+1]=x:0),k[m=m.filter((x,i)=>f[i-1]|f[i])]?m.length:F(m,k))
```

<p><em>Less golfed and not recursive</em></p>

<pre class="lang-js prettyprint-override"><code>F=m=>{
  for(k=[];!k[m];) // use k to find a repeated state and exit the loop
  {
    k[m]=1
    console.log(m)
    // loop for swap and mark swap position in array f
    f=m.map((x,i)=>(
      y=m[i+1], // next element
      w=x-y,    // difference
      x%w==0&y%w==0 // if common divisor ...
        ?m[m[i+1]=x,i]=y // swap elements,mark with nonzero
        :0 // no swap, mark with 0
    ))
    m=m.filter((x,i)=>f[i-1]|f[i]) // remove elements not swapped
  }
  return m.length
}
</code>```

Test

F=(m,k=[])=>(k[m]=m,f=m.map((x,i)=>x%(w=x-(y=m[i+1]))==0&y%w==0?m[m[i]=y,i+1]=x:0),k[m=m.filter((x,i)=>f[i-1]|f[i])]?m.length:F(m,k))

console.log=x=>O.textContent+=x+'\n'

;[[1,1],[1,2],[1,2,3],[4,6,8],[99,1,3],[4,5,2,4],[12,4,6,3],[9,6,10,18]
,[ 55, 218, 654, 703, 948, 960 ],[ 954, 973, 925, 913, 924, 996, 927, 981, 905 ]]
.forEach(t=>console.log(t+' -> '+F(t)))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id=O>``````

Title: Swap Pairs or Remove

Body:
JavaScript (ES6), 133

Recursive function.

F=(m,k=[])=>(k[m]=m,f=m.map((x,i)=>x%(w=x-(y=m[i+1]))==0&y%w==0?m[m[i]=y,i+1]=x:0),k[m=m.filter((x,i)=>f[i-1]|f[i])]?m.length:F(m,k))

Less golfed and not recursive

F=m=>{
  for(k=[];!k[m];) // use k to find a repeated state and exit the loop
  {
    k[m]=1
    console.log(m)
    // loop for swap and mark swap position in array f
    f=m.map((x,i)=>(
      y=m[i+1], // next element
      w=x-y,    // difference
      x%w==0&y%w==0 // if common divisor ...
        ?m[m[i+1]=x,i]=y // swap elements,mark with nonzero
        :0 // no swap, mark with 0
    ))
    m=m.filter((x,i)=>f[i-1]|f[i]) // remove elements not swapped
  }
  return m.length
}

Test

F=(m,k=[])=>(k[m]=m,f=m.map((x,i)=>x%(w=x-(y=m[i+1]))==0&y%w==0?m[m[i]=y,i+1]=x:0),k[m=m.filter((x,i)=>f[i-1]|f[i])]?m.length:F(m,k))

console.log=x=>O.textContent+=x+'\n'

;[[1,1],[1,2],[1,2,3],[4,6,8],[99,1,3],[4,5,2,4],[12,4,6,3],[9,6,10,18]
,[ 55, 218, 654, 703, 948, 960 ],[ 954, 973, 925, 913, 924, 996, 927, 981, 905 ]]
.forEach(t=>console.log(t+' -> '+F(t)))

<pre id=O></pre>


问:
Count up folks!

Introduction

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

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

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

Challenge

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

Rules

You can get n any way.

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

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

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

Standard loopholes are denied.

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

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

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

Bonuses

20%

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

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

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

答:
QBASIC, 43 bytes

1 INPUT a
2 FOR b=1 TO a
3 PRINT b
4 NEXT b
```

Title: Count up folks!


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

答:
CJam, 13 bytes

```<code>{ffff*::.+:~}
</code>```

This is an unnamed block that expects two matrices on top of the stack and leaves their Kronecker product in their place.

Test suite.

Explanation

This is just the Kronecker product part from the previous answer, therefore I'm here just reproducing the relevant parts of the previous explanation:

Here is a quick overview of CJam's infix operators for list manipulation:

f expects a list and something else on the stack and maps the following binary operator over the list, passing in the other element as the second argument. E.g. [1 2 3] 2 f* and 2 [1 2 3] f* both give [2 4 6]. If both elements are lists, the first one is mapped over and the second one is used to curry the binary operator.

: has two uses: if the operator following it is unary, this is a simple map. E.g. [1 0 -1 4 -3] :z is [1 0 1 4 3], where z gets the modulus of a number. If the operator following it is binary, this will fold the operator instead. E.g. [1 2 3 4] :+ is 10.

. vectorises a binary operator. It expects two lists as arguments and applies the operator to corresponding pairs. E.g. [1 2 3] [5 7 11] .* gives [5 14 33].

```<code>ffff*  e# This is the important step for the Kronecker product (but
       e# not the whole story). It's an operator which takes two matrices
       e# and replaces each cell of the first matrix with the second matrix
       e# multiplied by that cell (so yeah, we'll end up with a 4D list of
       e# matrices nested inside a matrix).
       e# Now the ffff* is essentially a 4D version of the standard ff* idiom
       e# for outer products. For an explanation of ff*, see the answer to
       e# to the Kronecker sum challenge.
       e# The first ff maps over the cells of the first matrix, passing in the
       e# second matrix as an additional argument. The second ff then maps over
       e# the second matrix, passing in the cell from the outer map. We
       e# multiply them with *.
       e# Just to recap, we've essentially got the Kronecker product on the
       e# stack now, but it's still a 4D list not a 2D list.
       e# The four dimensions are:
       e#   1. Columns of the outer matrix.
       e#   2. Rows of the outer matrix.
       e#   3. Columns of the submatrices.
       e#   4. Rows of the submatrices.
       e# We need to unravel that into a plain 2D matrix.
::.+   e# This joins the rows of submatrices across columns of the outer matrix.
       e# It might be easiest to read this from the right:
       e#   +    Takes two rows and concatenates them.
       e#   .+   Takes two matrices and concatenates corresponding rows.
       e#   :.+  Takes a list of matrices and folds .+ over them, thereby
       e#        concatenating the corresponding rows of all matrices.
       e#   ::.+ Maps this fold operation over the rows of the outer matrix.
       e# We're almost done now, we just need to flatten the outer-most level
       e# in order to get rid of the distinction of rows of the outer matrix.
:~     e# We do this by mapping ~ over those rows, which simply unwraps them.
</code>```

Title: Calculate the Kronecker Product

Body:
CJam, 13 bytes

{ffff*::.+:~}

This is an unnamed block that expects two matrices on top of the stack and leaves their Kronecker product in their place.

<a href="http://cjam.aditsu.net/#code=qN%2F%7B%3AQ%3B%0A%0AQ~ffff*%3A%3A.%2B%3A~%0A%0A%7Bs4Se%5B%7Df%25Sf*N*oNoNo%7D%2F&input=%5B%5B1%202%5D%20%5B3%204%5D%5D%20%5B%5B5%206%5D%20%5B7%208%5D%5D%0A%5B%5B5%206%5D%20%5B7%208%5D%5D%20%5B%5B1%202%5D%20%5B3%204%5D%5D%0A%5B%5B1%5D%20%5B2%5D%5D%20%5B%5B1%202%5D%5D%0A%5B%5B1%202%5D%5D%20%5B%5B1%5D%20%5B2%5D%5D%0A%5B%5B16%202%203%2013%5D%20%5B5%2011%2010%208%5D%20%5B9%207%206%2012%5D%20%5B4%2014%2015%201%5D%5D%20%5B%5B1%201%5D%20%5B0%201%5D%5D%0A%5B%5B1%201%5D%20%5B0%201%5D%5D%20%5B%5B16%202%203%2013%5D%20%5B5%2011%2010%208%5D%20%5B9%207%206%2012%5D%20%5B4%2014%2015%201%5D%5D" rel="nofollow noreferrer">Test suite.

Explanation

This is just the Kronecker product part from the previous answer, therefore I'm here just reproducing the relevant parts of the previous explanation:

Here is a quick overview of CJam's infix operators for list manipulation:

f expects a list and something else on the stack and maps the following binary operator over the list, passing in the other element as the second argument. E.g. [1 2 3] 2 f* and 2 [1 2 3] f* both give [2 4 6]. If both elements are lists, the first one is mapped over and the second one is used to curry the binary operator.

: has two uses: if the operator following it is unary, this is a simple map. E.g. [1 0 -1 4 -3] :z is [1 0 1 4 3], where z gets the modulus of a number. If the operator following it is binary, this will fold the operator instead. E.g. [1 2 3 4] :+ is 10.

. vectorises a binary operator. It expects two lists as arguments and applies the operator to corresponding pairs. E.g. [1 2 3] [5 7 11] .* gives [5 14 33].

ffff*  e# This is the important step for the Kronecker product (but
       e# not the whole story). It's an operator which takes two matrices
       e# and replaces each cell of the first matrix with the second matrix
       e# multiplied by that cell (so yeah, we'll end up with a 4D list of
       e# matrices nested inside a matrix).
       e# Now the ffff* is essentially a 4D version of the standard ff* idiom
       e# for outer products. For an explanation of ff*, see the answer to
       e# to the Kronecker sum challenge.
       e# The first ff maps over the cells of the first matrix, passing in the
       e# second matrix as an additional argument. The second ff then maps over
       e# the second matrix, passing in the cell from the outer map. We
       e# multiply them with *.
       e# Just to recap, we've essentially got the Kronecker product on the
       e# stack now, but it's still a 4D list not a 2D list.
       e# The four dimensions are:
       e#   1. Columns of the outer matrix.
       e#   2. Rows of the outer matrix.
       e#   3. Columns of the submatrices.
       e#   4. Rows of the submatrices.
       e# We need to unravel that into a plain 2D matrix.
::.+   e# This joins the rows of submatrices across columns of the outer matrix.
       e# It might be easiest to read this from the right:
       e#   +    Takes two rows and concatenates them.
       e#   .+   Takes two matrices and concatenates corresponding rows.
       e#   :.+  Takes a list of matrices and folds .+ over them, thereby
       e#        concatenating the corresponding rows of all matrices.
       e#   ::.+ Maps this fold operation over the rows of the outer matrix.
       e# We're almost done now, we just need to flatten the outer-most level
       e# in order to get rid of the distinction of rows of the outer matrix.
:~     e# We do this by mapping ~ over those rows, which simply unwraps them.


答:
Jelly, <s>10</s> 9 bytes

```<code>×€€;"/€;/
</code>```

Uses Büttner's Algorithm (ü pronounced when trying to make an ee sound [as in meet] in the mouth-shape of an oo sound [as in boot]).

The ;"/€;/ is inspired by Dennis Mitchell. It was originally Z€F€€;/ (which costs one more byte).

Test case 1

Test case 2

Test case 3

Test case 4

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:
Jelly, <s>10</s> 9 bytes

×€€;"/€;/

Uses Büttner's Algorithm (ü pronounced when trying to make an ee sound [as in meet] in the mouth-shape of an oo sound [as in boot]).

The ;"/€;/ is inspired by Dennis Mitchell. It was originally Z€F€€;/ (which costs one more byte).

Test case 1

Test case 2

Test case 3

Test case 4


答:
Dyalog APL, 1 byte

```<code>⍳
</code>```

This has worked since the very first APL, back in the seventies:

```<code>⍳⎕
</code>```

No built-in (also always worked):

```<code>+\⎕⍴1
</code>```

Cumulative sum +\ of input ⎕ number of ⍴ 1s.

Obviously you will need enough memory to contain the result. Here is a print loop to avoid memory full:

```<code>{⎕←1+⍵}⍣⎕⊢0
</code>```

{return and print ⎕← 1+ argument ⍵ } applied ⍣ input ⎕ times to ⊢ 0.

Title: Count up folks!

Body:
Introduction

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

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

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

Challenge

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

Rules

You can get n any way.

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

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

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

Standard loopholes are denied.

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

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

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

Bonuses

20%

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

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

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

Body:
Dyalog APL, 1 byte

⍳

This has worked since the very first APL, back in the seventies:

⍳⎕

No built-in (also always worked):

+\⎕⍴1

Cumulative sum +\ of input ⎕ number of ⍴ 1s.

Obviously you will need enough memory to contain the result. Here is a print loop to avoid memory full:

{⎕←1+⍵}⍣⎕⊢0

{return and print ⎕← 1+ argument ⍵ } applied ⍣ input ⎕ times to ⊢ 0.


答:
Pyth, <s>14</s> <s>12</s> 11 bytes

```<code>JEsMs*RRRRJ
</code>```

Translation of Jelly answer, which is based on Büttner's Algorithm (ü pronounced when trying to make an ee sound [as in meet] in the mouth-shape of an oo sound [as in boot]).

Try it online (test case 1)!

Bonus: calculate B⊗A in the same number of bytes

```<code>JEsMs*LRLRJ
</code>```

Try it online (test case 1)!

Title: Calculate the Kronecker Product

Body:
Pyth, <s>14</s> <s>12</s> 11 bytes

JEsMs*RRRRJ

Translation of Jelly answer, which is based on Büttner's Algorithm (ü pronounced when trying to make an ee sound [as in meet] in the mouth-shape of an oo sound [as in boot]).

Try it online (test case 1)!

Bonus: calculate B⊗A in the same number of bytes

JEsMs*LRLRJ

Try it online (test case 1)!


答:
JavaScript (ES6), 79

Straightforward implementation with nested looping

(a,b)=>a.map(a=>b.map(b=>a.map(y=>b.map(x=>r.push(y*x)),t.push(r=[]))),t=[])&&t
```

<p><strong>Test</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f=(a,b)=>a.map(a=>b.map(b=>a.map(y=>b.map(x=>r.push(y*x)),t.push(r=[]))),t=[])&&t

console.log=x=>O.textContent+=x+'\n'

function show(label, mat)
{
  console.log(label)
  console.log(mat.join`\n`)
}

;[
  {a:[[1,2],[3,4]],b:[[5,6],[7,8]] },
  {a:[[1],[2]],b:[[1,2]]},
  {a:[[16,2,3,13],[5,11,10,8],[9,7,6,12],[4,14,15,1]],b:[[1,1],[0,1]]},
  {a:[[2]],b:[[5]]}
].forEach(t=>{
  show('A',t.a)
  show('B',t.b)
  show('A⊗B',f(t.a,t.b))
  show('B⊗A',f(t.b,t.a))
  console.log('-----------------')
})</code>```

```</code>```

Title: Calculate the Kronecker Product

Body:
JavaScript (ES6), 79

Straightforward implementation with nested looping

(a,b)=>a.map(a=>b.map(b=>a.map(y=>b.map(x=>r.push(y*x)),t.push(r=[]))),t=[])&&t

Test

f=(a,b)=>a.map(a=>b.map(b=>a.map(y=>b.map(x=>r.push(y*x)),t.push(r=[]))),t=[])&&t

console.log=x=>O.textContent+=x+'\n'

function show(label, mat)
{
  console.log(label)
  console.log(mat.join`\n`)
}

;[
  {a:[[1,2],[3,4]],b:[[5,6],[7,8]] },
  {a:[[1],[2]],b:[[1,2]]},
  {a:[[16,2,3,13],[5,11,10,8],[9,7,6,12],[4,14,15,1]],b:[[1,1],[0,1]]},
  {a:[[2]],b:[[5]]}
].forEach(t=>{
  show('A',t.a)
  show('B',t.b)
  show('A⊗B',f(t.a,t.b))
  show('B⊗A',f(t.b,t.a))
  console.log('-----------------')
})

<pre id=O></pre>


问:
Calculate the Kronecker sum of two matrices
In the examples below, A and B will be 2-by-2 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>```

A Kronecker sum has the following properties:

```<code>A⊕B = A⊗Ib + Ia⊗B
</code>```

Ia and Ib are the identity matrices with the dimensions of A and B respectively. A and B are square matrices. Note that A and B can be of different sizes.

```<code>A⊕B =  A(1,1)+B(1,1)  B(1,2)         A(1,2)         0
        B(2,1)         A(1,1)+B(2,2)  0              A(1,2)
        A(2,1)         0              A(2,2)+B(1,1)  B(1,2)
        0              A(2,1)         B(2,1)         A(2,2)+B(2,2)
</code>```

Given two square matrices, A and B, calculate the Kronecker sum of the two matrices.

The size of the matrices will be at least 2-by-2. The maximum size will be whatever your computer / language can handle by default, but minimum 5-by-5 input (5 MB output).

All input values will be non-negative integers

Builtin functions that calculate the Kronecker sum or Kronecker 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    10
     7     9

A⊕B =
     6    10     2     0
     7    10     0     2
     3     0     9    10
     0     3     7    13

----

A =
    28    83    96
     5    70     4
    10    32    44
B =
    39    19    65
    77    49    71
    80    45    76

A⊕B =
    67    19    65    83     0     0    96     0     0
    77    77    71     0    83     0     0    96     0
    80    45   104     0     0    83     0     0    96
     5     0     0   109    19    65     4     0     0
     0     5     0    77   119    71     0     4     0
     0     0     5    80    45   146     0     0     4
    10     0     0    32     0     0    83    19    65
     0    10     0     0    32     0    77    93    71
     0     0    10     0     0    32    80    45   120

----

A =
    76    57    54
    76     8    78
    39     6    94
B =
    59    92
    55    29

A⊕B =
   135    92    57     0    54     0
    55   105     0    57     0    54
    76     0    67    92    78     0
     0    76    55    37     0    78
    39     0     6     0   153    92
     0    39     0     6    55   123
</code>```

Body:
JavaScript (ES6), 109

Built upon the answer to the other challenge

(a,b)=>a.map((a,k)=>b.map((b,i)=>a.map((y,l)=>b.map((x,j)=>r.push(y*(i==j)+x*(k==l))),t.push(r=[]))),t=[])&&t

Test

f=(a,b)=>a.map((a,k)=>b.map((b,i)=>a.map((y,l)=>b.map((x,j)=>r.push(y*(i==j)+x*(k==l))),t.push(r=[]))),t=[])&&t

console.log=x=>O.textContent+=x+'\n'

function show(label, mat)
{
  console.log(label)
  console.log(mat.join`\n`)
}

;[
  {a:[[1,2],[3,4]], b:[[5,10],[7,9]]},
  {a:[[28,83,96],[5,70,4],[10,32,44]], b:[[39,19,65],[77,49,71],[80,45,76]]},
  {a:[[76,57,54],[76,8,78],[39,6,94]], b:[[59,92],[55,29]]}
].forEach(t=>{
  show('A',t.a)
  show('B',t.b)
  show('A⊕B',f(t.a,t.b))
  show('B⊕A',f(t.b,t.a))
  console.log('-----------------')
})

<pre id=O></pre>


答:
MATLAB / Octave, <s>83</s> 42 Bytes

Saved 41 bytes, thanks to  FryAmTheEggman!

```<code>@(A,B)cell2mat(arrayfun(@(n)n*B,A,'un',0))
</code>```

Test it here!

Breakdown

arrayfun is a disguised for-loop that multiplies n*B, for a variable n defined by the second argument. This works because looping through a 2D matrix is the same as looping through a vector. I.e. for x = A is the same as for x = A(:).

'un',0 is equivalent to the more verbose 'UniformOutput', False, and specifies that the output contains cells instead of scalars.

cell2mat is used to convert the cells back to a numeric matrix, which is then outputted.

Title: Calculate the Kronecker Product

Body:
MATLAB / Octave, <s>83</s> 42 Bytes

Saved 41 bytes, thanks to  FryAmTheEggman!

@(A,B)cell2mat(arrayfun(@(n)n*B,A,'un',0))

Test it here!

Breakdown

arrayfun is a disguised for-loop that multiplies n*B, for a variable n defined by the second argument. This works because looping through a 2D matrix is the same as looping through a vector. I.e. for x = A is the same as for x = A(:).

'un',0 is equivalent to the more verbose 'UniformOutput', False, and specifies that the output contains cells instead of scalars.

cell2mat is used to convert the cells back to a numeric matrix, which is then outputted.


答:
CJam (30 29 27 24 bytes)

```<code>'1ri{{)W$W%/e`sc}%$W>+}/
</code>```

Online demo

This is very much a joint effort with Martin.

The clever use of run-length encoding (e`) to identify repetitions is Martin's

So is the use of W$ to simplify the stack management

I eliminated a couple of increment/decrement operations by using $W>+ special-casing, as explained in the dissection below

My first 30-byte approach:

```<code>1ari{,1$f{W%0+_@)</{}#}$W>+}/`
</code>```

Online demo

Dissection

```<code>1a        e# Special-case the first term
ri{       e# Read int n and iterate for i=0 to n-1
  ,1$f{   e#   Iterate for j=0 to i-1 a map with extra parameter of the sequence so far
    W%0+  e#     Reverse and append 0 to ensure a non-trivial non-repeating tail
    _@)</ e#     Take the first j+1 elements and split around them
    {}#   e#     Find the index of the first non-empty part from the split
          e#     That's equivalent to the number of times the initial word repeats
  }
  $W>+    e#   Add the maximal value to the sequence
          e#   NB Special case: if i=0 then we're taking the last term of an empty array
          e#   and nothing is appended - hence the 1a at the start of the program
}/
`         e# Format for pretty printing
</code>```

Body:
CJam (30 29 27 24 bytes)

'1ri{{)W$W%/e`sc}%$W>+}/

Online demo

This is very much a joint effort with Martin.

The clever use of run-length encoding (e`) to identify repetitions is Martin's

So is the use of W$ to simplify the stack management

I eliminated a couple of increment/decrement operations by using $W>+ special-casing, as explained in the dissection below

My first 30-byte approach:

1ari{,1$f{W%0+_@)</{}#}$W>+}/`

Online demo

Dissection

1a        e# Special-case the first term
ri{       e# Read int n and iterate for i=0 to n-1
  ,1$f{   e#   Iterate for j=0 to i-1 a map with extra parameter of the sequence so far
    W%0+  e#     Reverse and append 0 to ensure a non-trivial non-repeating tail
    _@)</ e#     Take the first j+1 elements and split around them
    {}#   e#     Find the index of the first non-empty part from the split
          e#     That's equivalent to the number of times the initial word repeats
  }
  $W>+    e#   Add the maximal value to the sequence
          e#   NB Special case: if i=0 then we're taking the last term of an empty array
          e#   and nothing is appended - hence the 1a at the start of the program
}/
`         e# Format for pretty printing