答:
Mathematica, <s>59</s> 56 bytes

Mod[Power~Array~{#2,#-1}.RandomInteger[250,#-1]+#3,251]&
```

Takes three arguments in the order t, n, and s. Constructs a  2d-array with n rows and t-1 columns. Each row vector j, numbered from 1 thru n, contains the powers of j thru jt-1. Then a vector of random integer coefficients in the range 0 thru 250 is created with t-1 values. That is matrix-multiplied with the 2d-array, and then s is added element-wise and taken module 251 to get the value of the polynomial at each of the n points.

Title: Shamir's Secret Sharing

Body:
Given n (the number of players), t (the threshold value), and s (the secret), output the n secrets generated by Shamir's Secret Sharing algorithm.

The Algorithm

For the purposes of this challenge, the computations will be done in GF(251) (the finite field of size 251, otherwise known as the integers mod 251). Ordinarily, the field would be chosen such that its size is a prime much greater than n. To simplify the challenge, the field size will be constant. 251 has been chosen because it is the largest prime representable by an 8-bit unsigned integer.

Generate t-1 random integers in the (inclusive) range [0, 250]. Label these a1 through at-1.

Construct a t-1th degree polynomial using s as the constant value and the random integers from step 1 as the coefficients of the powers of x: f(x) = s + x*a1 + x2*a2 + ... + xt-1*at-1.

Output (f(z) mod 251) for each z in the (inclusive) range [1, n].

Reference Implementation

#!/usr/bin/env python
from __future__ import print_function
import random
import sys

# Shamir's Secret Sharing algorithm
# Input is taken on the command line, in the format "python shamir.py n t s"

n, t, s = [int(x) for x in sys.argv[1:4]]
if t > n:
    print("Error: t must be less than or equal to n")
    exit()
if n not in range(2, 251):
    print("Error: n must be a positive integer less than 251")
    exit()
if t not in range(2, 251):
    print("Error: t must be a positive integer less than 251")
    exit()
if s not in range(251):
    print("Error: s must be a non-negative integer less than 251")
    exit()
p = 251
a = [random.randrange(0, 251) for x in range(t-1)]

def f(x):
    return s + sum(c*x**(i+1) for i,c in enumerate(a))

# Outputting the polynomial is for explanatory purposes only, and should not be included
#  in the output for the challenge
print("f(x) = {0} + {1}".format(s, ' + '.join('{0}*x^{1}'.format(c, i+1) for i,c in enumerate(a))))
for z in range(1, n+1):
    print(f(z) % p)
```

<h2>Verification</h2>

<p>The following Stack Snippet can be used to verify outputs:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var validate = function() {
  $('#nts-error').attr('hidden', parseInt($('#n').val()) >= parseInt($('#t').val()));
  $('#check').prop('disabled', parseInt($('#n').val()) < parseInt($('#t').val()));
};

// the following function is taken from https://rosettacode.org/wiki/Combinations#JavaScript
var combinations = function(arr, k) {
  var i,
    subI,
    ret = [],
    sub,
    next;
  for (i = 0; i < arr.length; i++) {
    if (k === 1) {
      ret.push([arr[i]]);
    } else {
      sub = combinations(arr.slice(i + 1, arr.length), k - 1);
      for (subI = 0; subI < sub.length; subI++) {
        next = sub[subI];
        next.unshift(arr[i]);
        ret.push(next);
      }
    }
  }
  return ret;
};

// The following code is taken from https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing#Javascript_example with the modification that the prime is 251, not 257

var prime = 251;

/* Gives the decomposition of the gcd of a and b.  Returns [x,y,z] such that x = gcd(a,b) and y*a + z*b = x */
function gcdD(a, b) {
  if (b == 0) return [a, 1, 0];
  else {
    var n = Math.floor(a / b),
      c = a % b,
      r = gcdD(b, c);
    return [r[0], r[2], r[1] - r[2] * n];
  }
}

/* Gives the multiplicative inverse of k mod prime.  In other words (k * modInverse(k)) % prime = 1 for all prime > k >= 1  */
function modInverse(k) {
  k = k % prime;
  var r = (k < 0) ? -gcdD(prime, -k)[2] : gcdD(prime, k)[2];
  return (prime + r) % prime;
}

/* Join the shares into a number */
function join(shares) {
  var accum, count, formula, startposition, nextposition, value, numerator, denominator;
  for (formula = accum = 0; formula < shares.length; formula++) {
    /* Multiply the numerator across the top and denominators across the bottom to do Lagrange's interpolation
     * Result is x0(2), x1(4), x2(5) -> -4*-5 and (2-4=-2)(2-5=-3), etc for l0, l1, l2...
     */
    for (count = 0, numerator = denominator = 1; count < shares.length; count++) {
      if (formula == count) continue; // If not the same value
      startposition = shares[formula][0];
      nextposition = shares[count][0];
      numerator = (numerator * -nextposition) % prime;
      denominator = (denominator * (startposition - nextposition)) % prime;
    }
    value = shares[formula][1];
    accum = (prime + accum + (value * numerator * modInverse(denominator))) % prime;
  }
  return accum;
}

$('#check').click(
  function() {
    var good = true;
    var problem = [];
    var n = parseInt($('#n').val());
    var t = parseInt($('#t').val());
    var s = parseInt($('#s').val());
    combinations([...Array(n + 1).keys()].slice(1), t).forEach(
      function(xArr) {
        var xfArr = xArr.map(
          function(x) {
            return [x, parseInt($('#f' + x).val())];
          }
        );
        var L = join(xfArr);
        if (L !== s) {
          good = false;
          problem.push(xArr);
        }
      }
    );
    $('#valid').html(good ? "True" : ("False (problematic secret sets: {" + problem.map(
      function(elem) {
        return "[" + elem.join(', ') + "]";
      }) + "})"));
  }
);

$('#n').change(
  function() {
    var inputHTML = "";
    for (var i = 1; i <= parseInt($('#n').val()); i++) {
      inputHTML += 'f(' + i + '): <input type="number" min="0" max="250" value="0" id="f' + i + '"><br>\r\n';
    }
    $('#inputs').html(inputHTML);
    validate();
  }
);

$('#t').change(
  function() {
    validate();
  }
);</code>```

n:
<input type="number" min="2" max="250" value="6" id="n">t:
<input type="number" min="2" max="250" value="3" id="t">s:
<input type="number" min="0" max="250" value="230" id="s">

t must be less than or equal to n!

  f(1):
  <input type="number" min="0" max="250" value="35" id="f1">

f(2):
  <input type="number" min="0" max="250" value="95" id="f2">

f(3):
  <input type="number" min="0" max="250" value="159" id="f3">

f(4):
  <input type="number" min="0" max="250" value="227" id="f4">

f(5):
  <input type="number" min="0" max="250" value="48" id="f5">

f(6):
  <input type="number" min="0" max="250" value="124" id="f6">

<input type="submit" id="check" value="Verify">

Valid:

```

Rules

s will be a non-negative integer less than 251, and n and t will be positive integers less than 251 and greater than 1. Furthermore, you are guaranteed that the inputs are valid (meaning t <= n).

Input and output can be in any reasonable, unambiguous, and consistent format.

Random numbers are to be sampled from a uniform distribution - each possible value should have equal probability of being chosen.

Body:
Mathematica, <s>59</s> 56 bytes

Mod[Power~Array~{#2,#-1}.RandomInteger[250,#-1]+#3,251]&

Takes three arguments in the order t, n, and s. Constructs a  2d-array with n rows and t-1 columns. Each row vector j, numbered from 1 thru n, contains the powers of j thru jt-1. Then a vector of random integer coefficients in the range 0 thru 250 is created with t-1 values. That is matrix-multiplied with the 2d-array, and then s is added element-wise and taken module 251 to get the value of the polynomial at each of the n points.


问:
Shamir's Secret Sharing
Given n (the number of players), t (the threshold value), and s (the secret), output the n secrets generated by Shamir's Secret Sharing algorithm.

The Algorithm

For the purposes of this challenge, the computations will be done in GF(251) (the finite field of size 251, otherwise known as the integers mod 251). Ordinarily, the field would be chosen such that its size is a prime much greater than n. To simplify the challenge, the field size will be constant. 251 has been chosen because it is the largest prime representable by an 8-bit unsigned integer.

Generate t-1 random integers in the (inclusive) range [0, 250]. Label these a1 through at-1.

Construct a t-1th degree polynomial using s as the constant value and the random integers from step 1 as the coefficients of the powers of x: f(x) = s + x*a1 + x2*a2 + ... + xt-1*at-1.

Output (f(z) mod 251) for each z in the (inclusive) range [1, n].

Reference Implementation

#!/usr/bin/env python
from __future__ import print_function
import random
import sys

# Shamir's Secret Sharing algorithm
# Input is taken on the command line, in the format "python shamir.py n t s"

n, t, s = [int(x) for x in sys.argv[1:4]]
if t > n:
    print("Error: t must be less than or equal to n")
    exit()
if n not in range(2, 251):
    print("Error: n must be a positive integer less than 251")
    exit()
if t not in range(2, 251):
    print("Error: t must be a positive integer less than 251")
    exit()
if s not in range(251):
    print("Error: s must be a non-negative integer less than 251")
    exit()
p = 251
a = [random.randrange(0, 251) for x in range(t-1)]

def f(x):
    return s + sum(c*x**(i+1) for i,c in enumerate(a))

# Outputting the polynomial is for explanatory purposes only, and should not be included
#  in the output for the challenge
print("f(x) = {0} + {1}".format(s, ' + '.join('{0}*x^{1}'.format(c, i+1) for i,c in enumerate(a))))
for z in range(1, n+1):
    print(f(z) % p)
```

<h2>Verification</h2>

<p>The following Stack Snippet can be used to verify outputs:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var validate = function() {
  $('#nts-error').attr('hidden', parseInt($('#n').val()) >= parseInt($('#t').val()));
  $('#check').prop('disabled', parseInt($('#n').val()) < parseInt($('#t').val()));
};

// the following function is taken from https://rosettacode.org/wiki/Combinations#JavaScript
var combinations = function(arr, k) {
  var i,
    subI,
    ret = [],
    sub,
    next;
  for (i = 0; i < arr.length; i++) {
    if (k === 1) {
      ret.push([arr[i]]);
    } else {
      sub = combinations(arr.slice(i + 1, arr.length), k - 1);
      for (subI = 0; subI < sub.length; subI++) {
        next = sub[subI];
        next.unshift(arr[i]);
        ret.push(next);
      }
    }
  }
  return ret;
};

// The following code is taken from https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing#Javascript_example with the modification that the prime is 251, not 257

var prime = 251;

/* Gives the decomposition of the gcd of a and b.  Returns [x,y,z] such that x = gcd(a,b) and y*a + z*b = x */
function gcdD(a, b) {
  if (b == 0) return [a, 1, 0];
  else {
    var n = Math.floor(a / b),
      c = a % b,
      r = gcdD(b, c);
    return [r[0], r[2], r[1] - r[2] * n];
  }
}

/* Gives the multiplicative inverse of k mod prime.  In other words (k * modInverse(k)) % prime = 1 for all prime > k >= 1  */
function modInverse(k) {
  k = k % prime;
  var r = (k < 0) ? -gcdD(prime, -k)[2] : gcdD(prime, k)[2];
  return (prime + r) % prime;
}

/* Join the shares into a number */
function join(shares) {
  var accum, count, formula, startposition, nextposition, value, numerator, denominator;
  for (formula = accum = 0; formula < shares.length; formula++) {
    /* Multiply the numerator across the top and denominators across the bottom to do Lagrange's interpolation
     * Result is x0(2), x1(4), x2(5) -> -4*-5 and (2-4=-2)(2-5=-3), etc for l0, l1, l2...
     */
    for (count = 0, numerator = denominator = 1; count < shares.length; count++) {
      if (formula == count) continue; // If not the same value
      startposition = shares[formula][0];
      nextposition = shares[count][0];
      numerator = (numerator * -nextposition) % prime;
      denominator = (denominator * (startposition - nextposition)) % prime;
    }
    value = shares[formula][1];
    accum = (prime + accum + (value * numerator * modInverse(denominator))) % prime;
  }
  return accum;
}

$('#check').click(
  function() {
    var good = true;
    var problem = [];
    var n = parseInt($('#n').val());
    var t = parseInt($('#t').val());
    var s = parseInt($('#s').val());
    combinations([...Array(n + 1).keys()].slice(1), t).forEach(
      function(xArr) {
        var xfArr = xArr.map(
          function(x) {
            return [x, parseInt($('#f' + x).val())];
          }
        );
        var L = join(xfArr);
        if (L !== s) {
          good = false;
          problem.push(xArr);
        }
      }
    );
    $('#valid').html(good ? "True" : ("False (problematic secret sets: {" + problem.map(
      function(elem) {
        return "[" + elem.join(', ') + "]";
      }) + "})"));
  }
);

$('#n').change(
  function() {
    var inputHTML = "";
    for (var i = 1; i <= parseInt($('#n').val()); i++) {
      inputHTML += 'f(' + i + '): <input type="number" min="0" max="250" value="0" id="f' + i + '"><br>\r\n';
    }
    $('#inputs').html(inputHTML);
    validate();
  }
);

$('#t').change(
  function() {
    validate();
  }
);</code>```

n:
<input type="number" min="2" max="250" value="6" id="n">t:
<input type="number" min="2" max="250" value="3" id="t">s:
<input type="number" min="0" max="250" value="230" id="s">

t must be less than or equal to n!

  f(1):
  <input type="number" min="0" max="250" value="35" id="f1">

f(2):
  <input type="number" min="0" max="250" value="95" id="f2">

f(3):
  <input type="number" min="0" max="250" value="159" id="f3">

f(4):
  <input type="number" min="0" max="250" value="227" id="f4">

f(5):
  <input type="number" min="0" max="250" value="48" id="f5">

f(6):
  <input type="number" min="0" max="250" value="124" id="f6">

<input type="submit" id="check" value="Verify">

Valid:

```

Rules

s will be a non-negative integer less than 251, and n and t will be positive integers less than 251 and greater than 1. Furthermore, you are guaranteed that the inputs are valid (meaning t <= n).

Input and output can be in any reasonable, unambiguous, and consistent format.

Random numbers are to be sampled from a uniform distribution - each possible value should have equal probability of being chosen.

ContentLicense: CC BY-SA 3.0

Title: Shamir's Secret Sharing

Body:
CJam, <s>27</s> 25 bytes

{,:)@({;251mr}%@+fb251f%}

Test it here.


问:
Print a bunch of uninteresting numbers!
An uninteresting number (which I totally didn't make up only for this challenge) is created like this:

Take a positive integer N

Create a new number O by adding the digits of N at the end of N

The final uninteresting number is O*N

For example for N=12:

O = 1212

O*N = 1212 * 12

Final number is 14544

Input

A positive integer N (N > 0) or your language's equivalent. You don't have to catch incorrect input.

Output

The corresponding uninteresting number.

Test cases

```<code>  1 -> 11
  2 -> 44
  3 -> 99
 10 -> 10100
174 -> 30306276
</code>```

Scoring

Shortest Code in Bytes wins.

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

```<code>q;f(char*v){q=atoi(v);return atoi(strcat(v,v))*q;}
</code>```

Usage

```<code>q;f(char*v){q=atoi(v);return atoi(strcat(v,v))*q;}
main(c,v)char**v;{while(*++v)printf("%d\n",f(*v));}
</code>```

Full Program <s>75</s> 69 bytes

```<code>q;main(c,v)char**v;{q=atoi(*++v);printf("%d",atoi(strcat(*v,*v))*q);}
</code>```

-2 & -6 thanks to Toby Speight in this comment

Title: Print a bunch of uninteresting numbers!

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

q;f(char*v){q=atoi(v);return atoi(strcat(v,v))*q;}

Usage

q;f(char*v){q=atoi(v);return atoi(strcat(v,v))*q;}
main(c,v)char**v;{while(*++v)printf("%d\n",f(*v));}

Full Program <s>75</s> 69 bytes

q;main(c,v)char**v;{q=atoi(*++v);printf("%d",atoi(strcat(*v,*v))*q);}

-2 & -6 thanks to Toby Speight in this comment


答:
JavaScript, 181 bytes

(n,t,s)=>{r=Array(t-1).fill(0).map($=>{return Math.random()*251});f=(x=>{p = 0;r.map((k,c)=>p+=k*Math.pow(x, c));return s+p});_=Array(t-1).fill(0);_.map((l,i)=>_[i]=f(i));return _;}
```
<p>Ungolfed:</p>
<pre class="lang-javascript prettyprint-override"><code>(n, t, s) => {
    r = Array(t - 1).fill(0).map($ =>{return Math.random() * 251});
    f = (x => {
        p = 0;
        r.map((k, c) => p += k * Math.pow(x, c));
        return s + p
    });
    _ = Array(t - 1).fill(0);
    _.map((l, i) => _[i] = f(i));
    return _;
}
</code>```

I don't know how to properly check it, but I do know that it was a pain to get JS to map across a new array since apparently .map skips undefined values. If anyone sees any ways to improve, or flaws, don't hesitate to let me know.

Title: Shamir's Secret Sharing

Body:
JavaScript, 181 bytes

(n,t,s)=>{r=Array(t-1).fill(0).map($=>{return Math.random()*251});f=(x=>{p = 0;r.map((k,c)=>p+=k*Math.pow(x, c));return s+p});_=Array(t-1).fill(0);_.map((l,i)=>_[i]=f(i));return _;}

Ungolfed:

(n, t, s) => {
    r = Array(t - 1).fill(0).map($ =>{return Math.random() * 251});
    f = (x => {
        p = 0;
        r.map((k, c) => p += k * Math.pow(x, c));
        return s + p
    });
    _ = Array(t - 1).fill(0);
    _.map((l, i) => _[i] = f(i));
    return _;
}

I don't know how to properly check it, but I do know that it was a pain to get JS to map across a new array since apparently .map skips undefined values. If anyone sees any ways to improve, or flaws, don't hesitate to let me know.


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

```<code>251tliq3$Yrihi:ZQw\
</code>```

Input order is t, s, n.

Try it online!

Explanation

```<code>251t    % Push 251 twice
l       % Push 1
iq      % Take input t. Subtract 1
3$Yr    % Generate t-1 random integers in [1 2 ... 251]
ih      % Take input s. Concatenate with the random integers
i:      % Take input n. Generate range [1 2 ... n]
ZQ      % Evvaluate polynomial at those values
w       % Swap to move copy og 251 to the top of the stack
\       % Modulo. Implicitly display
</code>```

Title: Shamir's Secret Sharing

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

251tliq3$Yrihi:ZQw\

Input order is t, s, n.

Try it online!

Explanation

251t    % Push 251 twice
l       % Push 1
iq      % Take input t. Subtract 1
3$Yr    % Generate t-1 random integers in [1 2 ... 251]
ih      % Take input s. Concatenate with the random integers
i:      % Take input n. Generate range [1 2 ... n]
ZQ      % Evvaluate polynomial at those values
w       % Swap to move copy og 251 to the top of the stack
\       % Modulo. Implicitly display


答:
Jelly, 15 bytes

```<code>251©xX€⁵0¦ḅÐ€%®
</code>```

Expects t, n, and s as command-line arguments. Try it online!

How it works

```<code>251©xX€⁵0¦ḅÐ€%®  Main link. Left argument: t. Right argument: n Third argument: s

251©             Yield 251 and copy it to the register.
    x            Repeat [251] t times.
     X€          Random choice each; pseudo-randomly choose t integers from
                 [1, ..., 251]. Since 251 = 0 (mod 251), this is equivalent to
                 choosing them from [0, ..., 250].
       ⁵0¦       Replace the last generated integer (index 0) with s (⁵).
          ḅÐ€    Interpret the resulting array as a base-k number, for each k in
                 [1, ..., n], and convert to integer.
              ®  Yield 251 from the register.
             %   Take the generated integers modulo 251.
</code>```

Title: Shamir's Secret Sharing

Body:
Jelly, 15 bytes

251©xX€⁵0¦ḅÐ€%®

Expects t, n, and s as command-line arguments. Try it online!

How it works

251©xX€⁵0¦ḅÐ€%®  Main link. Left argument: t. Right argument: n Third argument: s

251©             Yield 251 and copy it to the register.
    x            Repeat [251] t times.
     X€          Random choice each; pseudo-randomly choose t integers from
                 [1, ..., 251]. Since 251 = 0 (mod 251), this is equivalent to
                 choosing them from [0, ..., 250].
       ⁵0¦       Replace the last generated integer (index 0) with s (⁵).
          ḅÐ€    Interpret the resulting array as a base-k number, for each k in
                 [1, ..., n], and convert to integer.
              ®  Yield 251 from the register.
             %   Take the generated integers modulo 251.


答:
C#, <s>138</s> 134 bytes

(n,t,s)=>new int[n+1].Select((_,x)=>(s+new int[t-1].Select(k=>new Random(e).Next(251)).Select((c,i)=>c*Math.Pow(x+1,i+1)).Sum())%251);
```

C# lambda where inputs are int and output is an IEnumerable<double>. You can try my code on .NetFiddle.

I am not 100% sure about the validity of my algorithm, please comment if I misunderstood something.

4 bytes saved with @raggy's trick.

Title: Shamir's Secret Sharing

Body:
C#, <s>138</s> 134 bytes

(n,t,s)=>new int[n+1].Select((_,x)=>(s+new int[t-1].Select(k=>new Random(e).Next(251)).Select((c,i)=>c*Math.Pow(x+1,i+1)).Sum())%251);

C# lambda where inputs are int and output is an IEnumerable<double>. You can try my code on .NetFiddle.

I am not 100% sure about the validity of my algorithm, please comment if I misunderstood something.

4 bytes saved with @raggy's trick.


问:
Quickly find length of n-th term of the look-and-say sequence
The look and say sequence is an example of a run length encoding sequence.  To get the next term of the sequence one groups the sequence into runs of the same number, each group in the next term then becomes two digits, first the number of terms in the group, followed by the value in the group.  The first term is 1.

Here is how we would calculate the first couple of terms by hand:

We start with 1, grouping that gives us [1] a single group of 1 1.  Thus our next term is 11.  We group this and get [11] a single group of 2 1s, so our next term is 21.  Grouping again we get [2],[1], we translate each of these groups into 2 digits each, 12,11 and concatenate, 1211.  Group again [1],[2],[11], then convert each group, 11,12,21 and concatenate, 111221.

The first couple terms of the sequence are:

```<code>1
11
21
1211
111221
312211
13112221
1113213211
</code>```

Write a program that when given n as input returns the length of the nth term of this sequence as output.
Programs should have a runtime of O(n log n).

Answers will be scored in bytes with less bytes being better.

答:
GolfScript, 300 chars

```<code>~8-:m;'!5?HZi " A 9 "$??HLTZ^`eik 5Z`e <^ $k H ,Sds ?LT /5@MUav I " i ? "5i G  !#+.4;>@K]_cdhjy{| *HCRJD@:64122/42.,,*860-40-0.+9?B<862//?D<7=@:420-/5:60.-20.+./384/162.-HCRJD@:64122/42.,,*)! !""$&&('{32-}/]1,/~:&;:L;:T;]:S;0m>{&m=}{L,,{.49=\71=+}%:V{,(,{).V=\T?S={(V=+}/}%0+:V}m*,,0\{.V=\L=8-*+}/}if
</code>```

Here's a slightly shorter entry.  Reads a number m from stdin, writes the length of the m-th term in the look-and-say sequence to stdout.

For example, input 50 produces output 894810, while input 1000 produces (after a few seconds):

```<code>21465050086246039983937316427688400486337379416867195943208935654503780844828013651860410256502890125611856727316762
</code>```

I'll post a more detailed explanation of the code later, but basically this also works by repeatedly multiplying a vector with a sparse matrix, encoded as an ASCII string.  Some clever compression tricks, such as leaving out the all-ones superdiagonal of the matrix, are employed.

Ps. Here's a link to an online demo.  The server has been pretty slow lately, though, so if you see an error message about a timeout, try again (or just download the interpreter and run it yourself).

Addendum:  Here's the promised detailed explanation.  First, let me repost the code with whitespace and comments added:

```<code># Parse input, subtract 8, save in variable m:
~ 8- :m;

# This long string encodes all the constants used by the program (I'll describe it below):
'!5?HZi " A 9 "$??HLTZ^`eik 5Z`e <^ $k H ,Sds ?LT /5@MUav I " i ? "5i G  !#+.4;>@K]_cdhjy{| *HCRJD@:64122/42.,,*860-40-0.+9?B<862//?D<7=@:420-/5:60.-20.+./384/162.-HCRJD@:64122/42.,,*)! !""$&&('

# Parse the data string:
# The data consists of several arrays of positive integers, encoded as printable ASCII
# characters and separated by spaces.  (Note that this means that the range of possible
# data values starts from 1, which requires some adjustment below.  Also, the values in
# L are actually shifted up by 8 to avoid having single quotes in the data string.)

{32-}/   # Subtract 32 (ASCII code of space) from each char and dump result on stack.
]        # Collect numbers from stack into an array.
1,/ ~    # Split array on zeros (formerly spaces) and dump pieces on stack.
:&;      # Save topmost piece (canned responses for inputs 1-7) in var &.
:L;      # Save second piece (element lengths) in var L.
:T;      # Save third piece (nonstandard decay targets) in var T.
]:S;     # Collect remaining pieces (nonstd decay sources) in array and save it in S.

# If m < 0, return a precomputed response from &, else run the indented code below:
0 m > { & m = } {
  # Set V to be the initial element abundance vector (1 Hf + 1 Sn):
  # (Note: both L and V have an extra sentinel 0 at the end to avoid overruns below.)
  L,, { . 49= \ 71= + } % :V
  # Update the element abundances m times:
  {
    # Run the following block for all numbers i from 0 to length(V)-2,
    # collecting the results in an array:
    ,(, {
      # Start with the abundance of element i+1 in V (all elements except H decay
      # downwards; the extra 0 at the end of V is needed to avoid a crash here):
      ).V=\
      # If this element is one of the decay targets listed in T, find the corresponding
      # list of source elements in S and add their abundances from V to the total:
      # (If this element is not in T, we just loop over an empty array at the end of S.)
      T? S= { ( V= + } /
    } %
    # Append a new sentinel 0 to the end of the array and save it as the new V:
    0+:V
  } m *
  # Multiply the element abundances from V with their lengths from L and sum them:
  ,,0\{.V=\L=8-*+}/
} if
</code>```

The key fact that allows this code to work is that, as the look-and-say transformation is repeatedly applied to any string, it eventually splits into substrings which evolve independently, in the sense that we can obtain all the following elements of the look-and-say sequence starting from that string by taking each of the substrings, applying the look-and-say transformation to each of them independently n times and concatenating the results.

Furthermore, in his 1986 article "The Weird and Wonderful Chemistry of Audioactive Decay" (which basically introduced the look-and-say sequence to the world), John Conway proved a remarkable (and, for this challenge, crucial) result which he called the "cosmological theorem":

Cosmological theorem (Conway): There is a set of 92 finite strings of numbers 1–3 (which Conway named after the chemical elements; see table here), and two infinite families of strings each consisting of a fixed prefix followed by some number higher than 3 (these can only appear if the initial string contained number higher than 3 or sequences of more than 3 identical numbers), such that, after at most 24 applications of the look-and-say transformation, any string splits into a chain of such elements, each of which thereafter evolves independently (and splits into further elements).

Thus, to determine the length of a string sufficiently far in the look-and-say sequence, it's sufficient to know how many times each element appears in it.  And, since each element evolves independently, knowing these "elemental abundances" is also sufficient for calculating the corresponding abundances of the next string in the sequence, and so on.

As it happens, the look-and-say sequence starting from the string 1 splits into two Conway elements (Hf72 = 11132 and Sn50 = 13211) after just seven iterations.  Thus, thereafter, we only need to keep track of the abundances of the 92 "common" elements (as the two families of "transuranic" elements cannot arise from common elements).

Mathematically, we can treat the elemental abundances as a vector of length 92.  Calculating the abundances in the next step of the look-and-say sequence is then just equivalent to multiplying this vector with a 92 × 92 matrix, which is what r.e.s.'s solution does literally.

In fact, r.e.s.'s solution actually tracks the abundance of each element multiplied with its length (i.e. the "total mass" of that element in the string), adjusting the matrix accordingly, so that the total length of the string is given simply by adding the numbers in the abundance vector together.  However, I did not find that a particularly convenient representation for code golf.  (It was convenient for Nathaniel Johnston's derivation of Conway's polynomial, since it encodes the lengths into the matrix and thus gives the right eigenvalue for the asymptotic growth rate, but we don't care about that here.)

Instead, I just track the raw abundances of the elements, and only multiply them with the lengths at the end.  This has, combined with the convenient fact that none of the decay products of any element contain more than one copy of any element, means that the entries of the transition matrix are just zeros and ones.  Also, by far most of them are, in fact, zeros (in math jargon, the matrix is sparse), so I can save a lot of space by only storing the indices of those entries which are ones.

Also, in his article, Conway ordered the elements such that (except for H1 = 22, which is a fixed point of the look-and-say transformation), each element decays to the next lower element in the sequence (and possibly some others).
In fact, most elements decay only to the next lower elements.  Thus, by using Conway's ordering of the elements, I can hardcode this "standard decay" as part of the iteration, so that I only need to store the matrix entries corresponding to the other, "nonstandard" decays, saving even more space.

(In fact, what I actually do, for reasons mostly to do with how GolfScript's array operations work, is store one array listing the matrix rows containing non-zero entries (i.e. the elements which are produced in nonstandard decays) and another array of arrays listing, for each of these rows, the columns where the non-zero entries occur (i.e. the elements which produce these elements in such decays).  See the code and comments above for how these arrays are actually used to calculate the updated element abundances.)

The final space-saving trick I used was to encode all these arrays as strings of ASCII characters.  Conveniently, there are 95 printable ASCII characters from space (32) to ~ (126), and the largest value that appears in any of the arrays is 92, so they fit very well.  One extra tweak I made was to shift the values in the element length array (which only go up to 42 anyway) up by 8 so that I could avoid the character ' (39) and thus store my data in a single quoted string without having to add any backslash escape characters.

There are some other minor optimizations too, but those are just standard GolfScript coding tricks.  I should note that the actual code is not all that carefully optimized — it's quite possible that it could be golfed down further.

In any case, despite the inherent slowness of a double-interpreted language like GolfScript, the code runs quite fast and scales well: computing the length of the 10,000th string in the look-and-say sequence takes about 1.5 minutes on my computer.

Conveniently, GolfScript stores all numbers as arbitrary-length integers (bignums), so I didn't have to do anything special to make it produce exact results even for large inputs.
The expected time complexity of this program is O(n log n) (as the element abundances grow linearly with n, and bignum addition takes O(log n) time), and the actual runtime seems to fit that prediction pretty well, as the graph below shows:

(Time is in seconds; for what it's worth, the green curve is given by y = (a x log(b + x) + c) / x, where a = 0.00106462026133545, b = 2720.25843721031 and c = -0.0401630789530016.  The spike on the left mainly comes from the roughly constant runtimes for n < 8, which become relatively large when divided by small n.  I did not include it in the curve fit.)

Body:
GolfScript, 300 chars

~8-:m;'!5?HZi " A 9 "$??HLTZ^`eik 5Z`e <^ $k H ,Sds ?LT /5@MUav I " i ? "5i G  !#+.4;>@K]_cdhjy{| *HCRJD@:64122/42.,,*860-40-0.+9?B<862//?D<7=@:420-/5:60.-20.+./384/162.-HCRJD@:64122/42.,,*)! !""$&&('{32-}/]1,/~:&;:L;:T;]:S;0m>{&m=}{L,,{.49=\71=+}%:V{,(,{).V=\T?S={(V=+}/}%0+:V}m*,,0\{.V=\L=8-*+}/}if

Here's a slightly shorter entry.  Reads a number m from stdin, writes the length of the m-th term in the look-and-say sequence to stdout.

For example, input 50 produces output 894810, while input 1000 produces (after a few seconds):

21465050086246039983937316427688400486337379416867195943208935654503780844828013651860410256502890125611856727316762

I'll post a more detailed explanation of the code later, but basically this also works by repeatedly multiplying a vector with a sparse matrix, encoded as an ASCII string.  Some clever compression tricks, such as leaving out the all-ones superdiagonal of the matrix, are employed.

Ps. <a href="http://golfscript.apphb.com/?c=OyI1MCIgICMgPC0tIHB1dCBpbnB1dCBoZXJlICh0aGUgd2ViIGZvcm0gaGFzIG5vIHNlcGFyYXRlIGZpZWxkIGZvciBpbnB1dCkKCn44LTptOychNT9IWmkgIiBBIDkgIiQ%2FP0hMVFpeYGVpayA1WmBlIDxeICRrIEggLFNkcyA%2FTFQgLzVATVVhdiBJICIgaSA%2FICI1aSBHICAhIysuNDs%2BQEtdX2NkaGp5e3wgKkhDUkpEQDo2NDEyMi80Mi4sLCo4NjAtNDAtMC4rOT9CPDg2Mi8vP0Q8Nz1AOjQyMC0vNTo2MC4tMjAuKy4vMzg0LzE2Mi4tSENSSkRAOjY0MTIyLzQyLiwsKikhICEiIiQmJignezMyLX0vXTEsL346Jjs6TDs6VDtdOlM7MG0%2BeyZtPX17TCwsey40OT1cNzE9K30lOlZ7LCgseykuVj1cVD9TPXsoVj0rfS99JTArOlZ9bSosLDBcey5WPVxMPTgtKit9L31pZg%3D%3D" rel="nofollow noreferrer">Here's a link to an online demo.  The server has been pretty slow lately, though, so if you see an error message about a timeout, try again (or just download the interpreter and run it yourself).

Addendum:  Here's the promised detailed explanation.  First, let me repost the code with whitespace and comments added:

# Parse input, subtract 8, save in variable m:
~ 8- :m;

# This long string encodes all the constants used by the program (I'll describe it below):
'!5?HZi " A 9 "$??HLTZ^`eik 5Z`e <^ $k H ,Sds ?LT /5@MUav I " i ? "5i G  !#+.4;>@K]_cdhjy{| *HCRJD@:64122/42.,,*860-40-0.+9?B<862//?D<7=@:420-/5:60.-20.+./384/162.-HCRJD@:64122/42.,,*)! !""$&&('

# Parse the data string:
# The data consists of several arrays of positive integers, encoded as printable ASCII
# characters and separated by spaces.  (Note that this means that the range of possible
# data values starts from 1, which requires some adjustment below.  Also, the values in
# L are actually shifted up by 8 to avoid having single quotes in the data string.)

{32-}/   # Subtract 32 (ASCII code of space) from each char and dump result on stack.
]        # Collect numbers from stack into an array.
1,/ ~    # Split array on zeros (formerly spaces) and dump pieces on stack.
:&;      # Save topmost piece (canned responses for inputs 1-7) in var &.
:L;      # Save second piece (element lengths) in var L.
:T;      # Save third piece (nonstandard decay targets) in var T.
]:S;     # Collect remaining pieces (nonstd decay sources) in array and save it in S.

# If m < 0, return a precomputed response from &, else run the indented code below:
0 m > { & m = } {
  # Set V to be the initial element abundance vector (1 Hf + 1 Sn):
  # (Note: both L and V have an extra sentinel 0 at the end to avoid overruns below.)
  L,, { . 49= \ 71= + } % :V
  # Update the element abundances m times:
  {
    # Run the following block for all numbers i from 0 to length(V)-2,
    # collecting the results in an array:
    ,(, {
      # Start with the abundance of element i+1 in V (all elements except H decay
      # downwards; the extra 0 at the end of V is needed to avoid a crash here):
      ).V=\
      # If this element is one of the decay targets listed in T, find the corresponding
      # list of source elements in S and add their abundances from V to the total:
      # (If this element is not in T, we just loop over an empty array at the end of S.)
      T? S= { ( V= + } /
    } %
    # Append a new sentinel 0 to the end of the array and save it as the new V:
    0+:V
  } m *
  # Multiply the element abundances from V with their lengths from L and sum them:
  ,,0\{.V=\L=8-*+}/
} if

The key fact that allows this code to work is that, as the look-and-say transformation is repeatedly applied to any string, it eventually splits into substrings which evolve independently, in the sense that we can obtain all the following elements of the look-and-say sequence starting from that string by taking each of the substrings, applying the look-and-say transformation to each of them independently n times and concatenating the results.

Furthermore, in his 1986 article "The Weird and Wonderful Chemistry of Audioactive Decay" (which basically introduced the look-and-say sequence to the world), John Conway proved a remarkable (and, for this challenge, crucial) result which he called the "cosmological theorem":

Cosmological theorem (Conway): There is a set of 92 finite strings of numbers 1–3 (which Conway named after the chemical elements; see table here), and two infinite families of strings each consisting of a fixed prefix followed by some number higher than 3 (these can only appear if the initial string contained number higher than 3 or sequences of more than 3 identical numbers), such that, after at most 24 applications of the look-and-say transformation, any string splits into a chain of such elements, each of which thereafter evolves independently (and splits into further elements).

Thus, to determine the length of a string sufficiently far in the look-and-say sequence, it's sufficient to know how many times each element appears in it.  And, since each element evolves independently, knowing these "elemental abundances" is also sufficient for calculating the corresponding abundances of the next string in the sequence, and so on.

As it happens, the look-and-say sequence starting from the string 1 splits into two Conway elements (Hf72 = 11132 and Sn50 = 13211) after just seven iterations.  Thus, thereafter, we only need to keep track of the abundances of the 92 "common" elements (as the two families of "transuranic" elements cannot arise from common elements).

Mathematically, we can treat the elemental abundances as a vector of length 92.  Calculating the abundances in the next step of the look-and-say sequence is then just equivalent to multiplying this vector with a 92 × 92 matrix, which is what r.e.s.'s solution does literally.

In fact, r.e.s.'s solution actually tracks the abundance of each element multiplied with its length (i.e. the "total mass" of that element in the string), adjusting the matrix accordingly, so that the total length of the string is given simply by adding the numbers in the abundance vector together.  However, I did not find that a particularly convenient representation for code golf.  (It was convenient for Nathaniel Johnston's derivation of Conway's polynomial, since it encodes the lengths into the matrix and thus gives the right eigenvalue for the asymptotic growth rate, but we don't care about that here.)

Instead, I just track the raw abundances of the elements, and only multiply them with the lengths at the end.  This has, combined with the convenient fact that none of the decay products of any element contain more than one copy of any element, means that the entries of the transition matrix are just zeros and ones.  Also, by far most of them are, in fact, zeros (in math jargon, the matrix is sparse), so I can save a lot of space by only storing the indices of those entries which are ones.

Also, in his article, Conway ordered the elements such that (except for H1 = 22, which is a fixed point of the look-and-say transformation), each element decays to the next lower element in the sequence (and possibly some others).
In fact, most elements decay only to the next lower elements.  Thus, by using Conway's ordering of the elements, I can hardcode this "standard decay" as part of the iteration, so that I only need to store the matrix entries corresponding to the other, "nonstandard" decays, saving even more space.

(In fact, what I actually do, for reasons mostly to do with how GolfScript's array operations work, is store one array listing the matrix rows containing non-zero entries (i.e. the elements which are produced in nonstandard decays) and another array of arrays listing, for each of these rows, the columns where the non-zero entries occur (i.e. the elements which produce these elements in such decays).  See the code and comments above for how these arrays are actually used to calculate the updated element abundances.)

The final space-saving trick I used was to encode all these arrays as strings of ASCII characters.  Conveniently, there are 95 printable ASCII characters from space (32) to ~ (126), and the largest value that appears in any of the arrays is 92, so they fit very well.  One extra tweak I made was to shift the values in the element length array (which only go up to 42 anyway) up by 8 so that I could avoid the character ' (39) and thus store my data in a single quoted string without having to add any backslash escape characters.

There are some other minor optimizations too, but those are just standard GolfScript coding tricks.  I should note that the actual code is not all that carefully optimized — it's quite possible that it could be golfed down further.

In any case, despite the inherent slowness of a double-interpreted language like GolfScript, the code runs quite fast and scales well: computing the length of the 10,000th string in the look-and-say sequence takes about 1.5 minutes on my computer.

Conveniently, GolfScript stores all numbers as arbitrary-length integers (bignums), so I didn't have to do anything special to make it produce exact results even for large inputs.
The expected time complexity of this program is O(n log n) (as the element abundances grow linearly with n, and bignum addition takes O(log n) time), and the actual runtime seems to fit that prediction pretty well, as the graph below shows:

(Time is in seconds; for what it's worth, the green curve is given by y = (a x log(b + x) + c) / x, where a = 0.00106462026133545, b = 2720.25843721031 and c = -0.0401630789530016.  The spike on the left mainly comes from the roughly constant runtimes for n < 8, which become relatively large when divided by small n.  I did not include it in the curve fit.)

ContentLicense: CC BY-SA 4.0


Title: Shamir's Secret Sharing

Body:
Julia, 48 bytes

f(n,t,s)=(1:n).^(0:t-1)'*[s;rand(0:250,t-1)]%251

Try it online!


答:
R, <s>28</s> 27 bytes

Edit: -1 byte thanks to @Dominic van Essen.

(10^nchar(z<-scan())*z+z)*z
```

Try it online!

Shorter than bouncyball's solution with different approach.

Explanation

z=scan() gets input

10^nchar(z))*z+z is concatenation of the two copies of the number

*z at the end to get the result.

Title: Print a bunch of uninteresting numbers!

Body:
An uninteresting number (which I totally didn't make up only for this challenge) is created like this:

Take a positive integer N

Create a new number O by adding the digits of N at the end of N

The final uninteresting number is O*N

For example for N=12:

O = 1212

O*N = 1212 * 12

Final number is 14544

Input

A positive integer N (N > 0) or your language's equivalent. You don't have to catch incorrect input.

Output

The corresponding uninteresting number.

Test cases

```<code>  1 -> 11
  2 -> 44
  3 -> 99
 10 -> 10100
174 -> 30306276
</code>```

Scoring

Shortest Code in Bytes wins.

Body:
R, <s>28</s> 27 bytes

Edit: -1 byte thanks to @Dominic van Essen.

(10^nchar(z<-scan())*z+z)*z

Try it online!

Shorter than bouncyball's solution with different approach.

Explanation

z=scan() gets input

10^nchar(z))*z+z is concatenation of the two copies of the number

*z at the end to get the result.


问:
"99 Bottles of Beer"
Write a program that outputs the lyrics to 99 Bottles of Beer, in as few bytes as possible.

Lyrics:

```<code>99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.

98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.

97 bottles of beer on the wall, 97 bottles of beer.
Take one down and pass it around, 96 bottles of beer on the wall.

96 bottles of beer on the wall, 96 bottles of beer.
Take one down and pass it around, 95 bottles of beer on the wall.

95 bottles of beer on the wall, 95 bottles of beer.
Take one down and pass it around, 94 bottles of beer on the wall.

....

3 bottles of beer on the wall, 3 bottles of beer.
Take one down and pass it around, 2 bottles of beer on the wall.

2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.
</code>```

Rules:

Your program must log to STDOUT or an acceptable alternative, or be returned from a function (with or without a trailing newline).

Your program must be a full, runnable program or function.

Languages specifically written to submit a 0-byte answer to this challenge are allowed, just not particularly interesting.

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.

This is different from the output by HQ9+ or 99. Any answers written in these languages will be deleted.

As this is a catalog challenge, this is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

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>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
MIT Scratch 2.0, 184 bytes

Notes: Since this language is graphical, I counted each block/element used, each byte of the strings, and variable invocations as a byte.

Try it online: https://scratch.mit.edu/projects/115797194/#player

Notes: This program does not automatically clear the list after it's run, you have to go to the editor and run the following block:

I have conveniently added it into the project, however it is not part of the program and does not count towards the byte count.

Title: "99 Bottles of Beer"


问:
Determine the winner of a game of War
The card game War is interesting in that the final outcome is entirely determined by the initial arrangement of the deck, so long as certain rules are followed for the order in which cards are picked up from the playing field and moved to decks. In this challenge, there will only be 2 players, simplifying things greatly.

The Game

Each player is dealt a deck of 26 cards.

Each player places the top card in their deck face-up. The player with the higher-ranking card (Ace > King > Queen > Jack > 10 > 9 > 8 > 7 > 6 > 5 > 4 > 3 > 2) wins the round, and places their card on top of their opponent's card, flips them over, and adds them to the bottom of their deck (so their winning card is on the bottom of the deck, and the other player's losing card is just above it). This is done until one of the players runs out of cards.

If the cards are of equal rank, then each player places the top 2 cards of their deck face-up on top of their previous card (so that the card that was on top of the deck is the second card in the stack, and the card that was second-from-top is on top). Then, the ranks (of the top card of each stack) are compared again, and the winner places their entire stack on top of the loser's entire stack, turns the stack upside-down, and places it on the bottom of their deck. If there is another tie, more cards are played in the same way, until a winner is chosen or one player runs out of cards.

If at any point one of the players needs to draw a card from their deck, but their deck is empty, they immediately lose the game.

The Challenge

Given two lists of cards in the players' decks, in any convenient format, output a truthy value if Player 1 wins, and a falsey value if Player 2 wins.

For convenience, a 10 card will be represented with a T, and face cards will be abbreviated (Ace -> A, King -> K, Queen -> Q, Jack -> J), so that all cards are one character long. Alternatively, ranks may be represented with decimal integers 2-14 (Jack -> 11, Queen -> 12, King -> 13, Ace -> 14) or hex digits 2-E (10 -> A, Jack -> B, Queen -> C, King -> D, Ace -> E). Since suits don't matter, suit information will not be given.

You may assume that all games will terminate at some point (though it may take a very long time), and one player will always run out of cards before the other.

Each player places cards simultaneously, and one card at a time, so there is never any ambiguity about which player ran out of cards first.

Test Cases

The test cases use 23456789ABCDE to represent the ranks (in ascending order).

```<code>D58B35926B92C7C4C7E8D3DAA2, 8E47C38A2DEA43467EB9566B95 -> False
669D9D846D4B3BA52452C2EDEB, E747CA988CC76723935A3B8EA5 -> False
5744B95ECDC6D325B28A782A72, 68394D9DA96EBBA8533EE7C6C4 -> True
87DB6C7EBC6C8D722389923DC6, E28435DBEBEA543AA47956594A -> False
589EAB9DCD43E9EC264A5726A8, 48DC2577BD68AB9335263B7EC4 -> True
E3698D7C46A739AE5BE2C49286, BB54B7D78954ED526A83C3CDA2 -> True
32298B5E785DC394467D5C9CB2, 5ED6AAD93E873EA628B6A4BC47 -> True
B4AB985B34756C624C92DE5E97, 3EDD5BA2A68397C26CE837AD48 -> False
9A6D9A5457BB6ACBC5E8D7D4A9, 73E658CE2C3E289B837422D463 -> True
96E64D226BC8B7D6C5974BAE32, 58DC7A8C543E35978AEBA34D29 -> True
C2978A35E74D7652BA9762C458, 9A9BB332BE8C8DD44CE3DE66A5 -> False
BEDB44E947693CD284923CEA82, 8CC3B75756255A683A6AB9E7DD -> False
EEDDCCBBAA8877665544332299, EEDDCCBBAA9988776655443322 -> False
EEDDCCBBAA9988776655443322, DDCCBBAA9988776655443E3E22 -> True
</code>```

Reference Implementation

This reference implementation is written in Python 3, and takes input in the same format as the test cases (except separated by a newline instead of a comma and a space).

#!/usr/bin/env python3

from collections import deque

p1, p2 = [deque(s) for s in (input(),input())]
print(''.join(p1))
print(''.join(p2))

try:
    while p1 and p2:
        p1s = [p1.popleft()]
        p2s = [p2.popleft()]
        while p1s[-1] == p2s[-1]:
            p1s.append(p1.popleft())
            p2s.append(p2.popleft())
            p1s.append(p1.popleft())
            p2s.append(p2.popleft())
        if p1s[-1] > p2s[-1]:
            p1.extend(p2s+p1s)
        else:
            p2.extend(p1s+p2s)
except IndexError:
    pass
finally:
    print(len(p1) > 0)
```

Title: Determine the winner of a game of War

Body:
Haskell, 372

My first Haskell Program

(It's my first functional programming, too...)

w[]_=False
w _[]=True
w a b=if length j==0 then a>b else w (drop(d$head j)a++fst(head j))(drop(d$head j)b++snd(head j))where j=p a b
d(a,b)=quot(maximum[length a,length b])2
f (Just a)=a
p a b=map f$filter(/=Nothing)[t(a!!x,take(x+1)a,b!!x,take(x+1)b)|x<-[0,2..minimum[length a,length b]-1]]
t(a,b,c,d)=if a==c then Nothing else if a>c then Just(d++b,[])else Just([],b++d)

I'd love to have tips on how to improve.

Usage:

w "D58B35926B92C7C4C7E8D3DAA2" "8E47C38A2DEA43467EB9566B95"
w "669D9D846D4B3BA52452C2EDEB" "E747CA988CC76723935A3B8EA5"
w "5744B95ECDC6D325B28A782A72" "68394D9DA96EBBA8533EE7C6C4"
w "87DB6C7EBC6C8D722389923DC6" "E28435DBEBEA543AA47956594A"
w "589EAB9DCD43E9EC264A5726A8" "48DC2577BD68AB9335263B7EC4"
w "E3698D7C46A739AE5BE2C49286" "BB54B7D78954ED526A83C3CDA2"
w "32298B5E785DC394467D5C9CB2" "5ED6AAD93E873EA628B6A4BC47"
w "B4AB985B34756C624C92DE5E97" "3EDD5BA2A68397C26CE837AD48"
w "9A6D9A5457BB6ACBC5E8D7D4A9" "73E658CE2C3E289B837422D463"
w "96E64D226BC8B7D6C5974BAE32" "58DC7A8C543E35978AEBA34D29"
w "C2978A35E74D7652BA9762C458" "9A9BB332BE8C8DD44CE3DE66A5"
w "BEDB44E947693CD284923CEA82" "8CC3B75756255A683A6AB9E7DD"
w "EEDDCCBBAA8877665544332299" "EEDDCCBBAA9988776655443322"
w "EEDDCCBBAA9988776655443322" "DDCCBBAA9988776655443E3E22"

Haskell is quick... :)

real    0m0.039s
user    0m0.022s
sys     0m0.005s


问:
Implement Takewhile

Introduction and Credit

Today without a fancy prelude: Please implement takewhile.

A variation of this (on a non-trivial data structure) was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitly).

Specification

Input

The input will be a list (or your language's equivalent concept) of positive integers.

Output

The output should be a list (or your language's equivalent concept) of positive integers.

What to do?

Your task is to implement takewhile (language built-ins are allowed) with the predicate that the number under consideration is even (to focus on takewhile).

So you iterate over the list from start to end and while the condition (is even) holds, you copy to the output-list and as soon as you hit an element that doesn't make the condition true, you abort the operation and output (a step-by-step example is below). This higher-order functionality is also called takeWhile (takewhile).

Potential corner cases

The order of the output list compared to the input list may not be changed, e.g. [14,42,2] may not become [42,14].

The empty list is a valid in- and output.

Who wins?

This is code-golf so the shortest answer in bytes wins!

Standard rules apply of course.

Test Vectors

```<code>[14, 42, 2324, 97090, 4080622, 171480372] -> [14, 42, 2324, 97090, 4080622, 171480372]
[42, 14, 42, 2324] -> [42, 14, 42, 2324]
[7,14,42] -> []
[] -> []
[171480372, 13, 14, 42] -> [171480372]
[42, 14, 42, 43, 41, 4080622, 171480372] -> [42, 14, 42]
</code>```

Step-by-Step Example

```<code>Example Input: [42, 14, 42, 43, 41, 4080622, 171480372]

Consider first element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42]

Consider second element: 14
14 is even (7*2)
Put 14 into output list, output list is now [42,14]

Consider third element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42,14,42]

Consider fourth element: 43
43 is not even (2*21+1)
Drop 43 and return the current output list

return [42,14,42]
</code>```

答:
JavaScript, <s>27</s> 25 bytes

```<code>a=>a.filter(v=>a=a&&~v%2)
</code>```

The filer expression repeatedly assigns to a and uses the value of a as a filter predicate. a holds either the initial array value (always truthy) or the boolean of whether only even values have been seen. When a turns false (i.e., an odd number appears), then subsequent runs of the a = a && ... logical AND operation short cirucits, and we use false for the rest of the run.

The bitwise NOT ~v turns even numbers to odd and vice versa, so ~v%2 returns a truthy value for even input and falsy values for odd input.

Title: Implement Takewhile

Body:
JavaScript, <s>27</s> 25 bytes

a=>a.filter(v=>a=a&&~v%2)

The filer expression repeatedly assigns to a and uses the value of a as a filter predicate. a holds either the initial array value (always truthy) or the boolean of whether only even values have been seen. When a turns false (i.e., an odd number appears), then subsequent runs of the a = a && ... logical AND operation short cirucits, and we use false for the rest of the run.

The bitwise NOT ~v turns even numbers to odd and vice versa, so ~v%2 returns a truthy value for even input and falsy values for odd input.


问:
Solve the chromatic puzzle
Over at our friends at Puzzling.SE, the following puzzle was posted: Is this chromatic puzzle always solvable? by Edgar G. You can play it here.

Puzzle explanation

Given a m x n grid with tiles of three different colours, you may select any two adjacent tiles, if their colours are different. These two tiles are then converted to the third colour, i.e., the one colour not represented by these two tiles. The puzzle is solved if all tiles have the same colour. Apparently, one can prove that this puzzle is always solvable, if  neither m nor n are divisible by 3.

Of course, this begs for a solving algorithm. You will write a function or program that solves this puzzle. Note that functions with 'side effects' (i.e., the output is on stdout rather than in some awkward data type return value) are explicitly allowed.

Input & Output

The input will be an m x n matrix consisting of the integers 1, 2 and 3 (or 0, 1, 2 if convenient). You may take this input in any sane format. Both m and n are >1 and not divisible by 3. You may assume the puzzle is not solved

You will then solve the puzzle. This will involve a repeated selection of two adjacent tiles to be 'converted' (see above). You will output the two coordinates of these tiles for each step your solving algorithm took. This may also be in any sane output format. You are free to choose between 0-based and 1-based indexing of your coordinates, and whether rows or columns are indexed first. Please mention this in your answer, however.

Your algorithm should run within reasonable time on the original 8x8 case. Brute-forcing it completely is explicitly disallowed, i.e. your algorithm should run under O(k^[m*(n-1)+(m-1)*n]) with k the number of steps needed for the solution. The solution however is not required to be optimal. The proof given in the linked question may give you an idea as to how to do this (e.g., first do all columns using only vertically adjacent tiles, and then do all rows)

Test cases

In these test cases, the coordinates are 1-based and rows are indexed first (like MATLAB/Octave and probably many others).

```<code>Input:
[1 2]
Output: (result: all 3's)
[1 1],[1,2]

Input:
[ 1 2
  3 1 ]
Output: (result: all 1's)
[1 1],[2 1]        (turn left column into 2's)
[2 1],[2 2]        (turn right column into 3's)
[1 1],[1 2]        (turn top row into 1's)
[2 1],[2 2]        (turn bottom row into 1's)

Input:
[1 2 3 2
 3 2 1 1]

Output: (result: all 3's)
[1 1],[1 2]
[1 3],[1 4]
[1 2],[1 3]
[1 1],[1 2]
[1 2],[1 3]
[1 1],[1 2]
[1 3],[1 4]
[2 1],[2 2]
[1 1],[2 1]
[1 2],[2 2]
[1 3],[2 3]
[1 4],[2 4]
</code>```

If desired, I may post a pastebin of larger test cases, but I think this should be sufficient.

答:
Rust, <s>496</s> 495 bytes

Sadly I can't beat OP, but for a Rust answer I am quite satisfied with the bytecount.

```<code>let s=|mut v:Vec<_>,c|{
let p=|v:&mut[_],f,t|{
let x=|v:&mut[_],i|{
let n=v[i]^v[i+1];v[i]=n;v[i+1]=n;
for k in f..t+1{print!("{:?}",if f==t{(k,i,k,i+1)}else{(i,k,i+1,k)});}};
let l=v.len();let t=(1..4).find(|x|l*x)%3==v.iter().fold(0,|a,b|a+b)%3).unwrap();
let mut i=0;while i<l{let c=v[i];if c==t{i+=1;}else if c==v[i+1]{
let j=if let Some(x)=(i+1..l).find(|j|v[j+1]!=c){x}else{i-=1;i};x(v,j);}else{x(v,i);}}t};
p(&mut (0..).zip(v.chunks_mut(c)).map(|(i,x)|{p(x,i,i)}).collect::<Vec<_>>(),0,c-1usize)};
</code>```

Input: a vector of numbers as well as the number of columns. E.g.

```<code>s(vec!{1,2,1,3},2);
</code>```

outputs

```<code> (row1,col1,row2,col2)
</code>```

to the command line.

I first solve every row and then solve the resulting column only once ,but print the steps for all columns. So it is actually quite efficient :-P.

With formating:

```<code>let s=|mut v:Vec<_>,c|{
    let p=|v:&mut[_],f,t|{     // solves a single row/column
        let x=|v:&mut[_],i|{   // makes a move and prints it
            let n=v[i]^v[i+1]; // use xor to calculate the new color
            v[i]=n;
            v[i+1]=n;
            for k in f..t{
                print!("{:?}",if f==t{(k,i,k,i+1)}else{(i,k,i+1,k)});
            }
        };
        let l=v.len();
        // find target color
        // oh man i am so looking forward to sum() being stabilized
        let t=(1..4).find(|x|(l*x)%3==v.iter().fold(0,|a,b|a+b)%3).unwrap();
        let mut i=0;
        while i<l{
            let c=v[i];
            if c==t{             // if the color is target color move on
                i+=1;
            }else if c==v[i+1]{ // if the next color is the same
                                // find the next possible move
                let j=if let Some(x)=(i+1..l).find(|j|v[j+1]!=c){x}else{i-=1;i};
                x(v,j);
            }else{              // colors are different so we can make a move
                x(v,i);
            }
        }
        t
    };
    // first solve all rows and than sovle the resulting column c times
    p(&mut (0..).zip(v.chunks_mut(c)).map(|(i,x)|p(x,i,i)).collect::<Vec<_>>(),0,c-1usize)
};
</code>```

Edit:
now returns the color of the solution which saves me a semicolon^^

Title: Solve the chromatic puzzle

Body:
Rust, <s>496</s> 495 bytes

Sadly I can't beat OP, but for a Rust answer I am quite satisfied with the bytecount.

let s=|mut v:Vec<_>,c|{
let p=|v:&mut[_],f,t|{
let x=|v:&mut[_],i|{
let n=v[i]^v[i+1];v[i]=n;v[i+1]=n;
for k in f..t+1{print!("{:?}",if f==t{(k,i,k,i+1)}else{(i,k,i+1,k)});}};
let l=v.len();let t=(1..4).find(|x|l*x)%3==v.iter().fold(0,|a,b|a+b)%3).unwrap();
let mut i=0;while i<l{let c=v[i];if c==t{i+=1;}else if c==v[i+1]{
let j=if let Some(x)=(i+1..l).find(|j|v[j+1]!=c){x}else{i-=1;i};x(v,j);}else{x(v,i);}}t};
p(&mut (0..).zip(v.chunks_mut(c)).map(|(i,x)|{p(x,i,i)}).collect::<Vec<_>>(),0,c-1usize)};

Input: a vector of numbers as well as the number of columns. E.g.

s(vec!{1,2,1,3},2);

outputs

 (row1,col1,row2,col2)

to the command line.

I first solve every row and then solve the resulting column only once ,but print the steps for all columns. So it is actually quite efficient :-P.

With formating:

let s=|mut v:Vec<_>,c|{
    let p=|v:&mut[_],f,t|{     // solves a single row/column
        let x=|v:&mut[_],i|{   // makes a move and prints it
            let n=v[i]^v[i+1]; // use xor to calculate the new color
            v[i]=n;
            v[i+1]=n;
            for k in f..t{
                print!("{:?}",if f==t{(k,i,k,i+1)}else{(i,k,i+1,k)});
            }
        };
        let l=v.len();
        // find target color
        // oh man i am so looking forward to sum() being stabilized
        let t=(1..4).find(|x|(l*x)%3==v.iter().fold(0,|a,b|a+b)%3).unwrap();
        let mut i=0;
        while i<l{
            let c=v[i];
            if c==t{             // if the color is target color move on
                i+=1;
            }else if c==v[i+1]{ // if the next color is the same
                                // find the next possible move
                let j=if let Some(x)=(i+1..l).find(|j|v[j+1]!=c){x}else{i-=1;i};
                x(v,j);
            }else{              // colors are different so we can make a move
                x(v,i);
            }
        }
        t
    };
    // first solve all rows and than sovle the resulting column c times
    p(&mut (0..).zip(v.chunks_mut(c)).map(|(i,x)|p(x,i,i)).collect::<Vec<_>>(),0,c-1usize)
};

Edit:
now returns the color of the solution which saves me a semicolon^^


问:
Is it a sum-free set?
A set is sum-free if no two (not necessarily distinct) elements when added together are part of the set itself.

For example, {1, 5, 7} is sum-free, because all members are odd, and two odd numbers when added together are always even. On the other hand, {2, 4, 9, 13} is not sum-free, as either 2 + 2 = 4 or 4 + 9 = 13 add together to a member of the set.

Write a program or function that takes a set as input, and outputs a Truthy value if the set is sum-free, and Falsy otherwise.

Examples:

```<code>Sum-free:
{}
{4}
{1, 5, 7}
{16, 1, 4, 9}

Not sum-free:
{0}
{1, 4, 5, 7}
{3, 0}
{16, 1, 4, 8}
</code>```

答:
Factor, 47 bytes

```<code>[ dup dup 2array [ Σ ] product-map ∩ { } = ]
</code>```

∩ { } = is equivalent to but shorter than intersects?.

Σ is shorter than but equivalent to sum.

Thanks, math.unicode!

testing code:

```<code>USING: arrays kernel math.unicode sequences sequences.product ;
IN: sum-free

: sum-free? ( seq -- ? )
  dup dup 2array [ Σ ] product-map ∩ { } = ;

USING: tools.test sum-free ;
IN: sum-free.tests

{ t } [ { 5 7 9 } sum-free? ] unit-test
{ f } [ { 2 4 9 13 } sum-free? ] unit-test
{ t } [ { } sum-free? ] unit-test
{ f } [ { 0 } sum-free? ] unit-test
{ t } [ { 1 } sum-free? ] unit-test
{ f } [ { 0 1 } sum-free? ] unit-test
</code>```

I'm only confident the first two are correct. It's unclear from the question what the rest should be, so I think it's fine for now.

Title: Is it a sum-free set?

Body:
Factor, 47 bytes

[ dup dup 2array [ Σ ] product-map ∩ { } = ]

∩ { } = is equivalent to but shorter than intersects?.

Σ is shorter than but equivalent to sum.

Thanks, math.unicode!

testing code:

USING: arrays kernel math.unicode sequences sequences.product ;
IN: sum-free

: sum-free? ( seq -- ? )
  dup dup 2array [ Σ ] product-map ∩ { } = ;

USING: tools.test sum-free ;
IN: sum-free.tests

{ t } [ { 5 7 9 } sum-free? ] unit-test
{ f } [ { 2 4 9 13 } sum-free? ] unit-test
{ t } [ { } sum-free? ] unit-test
{ f } [ { 0 } sum-free? ] unit-test
{ t } [ { 1 } sum-free? ] unit-test
{ f } [ { 0 1 } sum-free? ] unit-test

I'm only confident the first two are correct. It's unclear from the question what the rest should be, so I think it's fine for now.


Title: Print a bunch of uninteresting numbers!

Body:
Perl 6, 11 bytes

{"$_$_"*$_}

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

my @tests = (
  12 => 14544,
   1 => 11,
   2 => 44,
   3 => 99,
  10 => 10100,
 174 => 30306276,
);

plan +@tests;

my &uninteresting = {"$_$_"*$_}

for @tests -> $_ ( :key($input), :value($expected) ) {
  is uninteresting($input), $expected, .gist
}

1..6
ok 1 - 12 => 14544
ok 2 - 1 => 11
ok 3 - 2 => 44
ok 4 - 3 => 99
ok 5 - 10 => 10100
ok 6 - 174 => 30306276


答:
hashmap, 8 bytes

```<code>i&&+d#d*
</code>```

Explanation:

```<code>i&&+d#d*
i&&      Triple the input
   +     Add them together
    d#d  Convert both into a number
       * Multiply them
</code>```

Title: Print a bunch of uninteresting numbers!

Body:
hashmap, 8 bytes

i&&+d#d*

Explanation:

i&&+d#d*
i&&      Triple the input
   +     Add them together
    d#d  Convert both into a number
       * Multiply them


问:
Holiday Gift Exchange
Another problem from our internal golfing...this one around the holidays last year.

PROBLEM

Andy, Barb, Carl, Didi, Earl, and Fran are buying gifts for each other. Draw names for a gift exchange.

Each person buys one gift and receives one gift.

Nobody buys their own gift.

Running the solution multiple times should produce different results (giver-receiver pair should not be predictable or identical from run to run).

INPUT

None.

OUTPUT

Formatted as in this example:

Andy buys for Barb

  Barb buys for Carl

  Carl buys for Didi

  Didi buys for Earl

  Earl buys for Fran

  Fran buys for Andy

答:
Python - 118 chars

```<code>from random import*;L="Andy Barb Carl Didi Earl Fran".split()
for i in sample(range(6),6):print L[i-1],"buys for",L[i]
</code>```

Python - 120 chars

```<code>import random as R;L="Andy Barb Carl Didi Earl Fran".split();R.shuffle(L)
for i in range(6):print L[i-1],"buys for",L[i]
</code>```

ContentLicense: CC BY-SA 2.5

Title: Holiday Gift Exchange

Body:
Python - 118 chars

from random import*;L="Andy Barb Carl Didi Earl Fran".split()
for i in sample(range(6),6):print L[i-1],"buys for",L[i]

Python - 120 chars

import random as R;L="Andy Barb Carl Didi Earl Fran".split();R.shuffle(L)
for i in range(6):print L[i-1],"buys for",L[i]


问:
Write all possible Braille characters
An interesting puzzle came to me looking at the elevator buttons this morning.

You are required to generate a list of all Braille patterns that fit in a 2x3 grid.  Use a hash # to denote a bump and a hyphen - to denote a flat area.

Expected output sample:

```<code>#-
--
--

##
--
--

#-
#-
--

(and so on...)
</code>```

Rules:

Your program must separate each pattern by at least one character or line.

The patterns may be generated in any order.

All patterns, regardless of what the Braille alphabet actually uses, should be produced.  The completely blank pattern is optional.

Only unique bump patterns should be generated.  The following patterns are considered equivilent as the bumps are in an identical arangement.  In these cases, use the pattern that is closest to the top-left corner (ie. the first option in this example.)

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

Bonus points if you can make it work for any x by y sized grid. (EDIT: Within reasonable bounds.  Up to 4x4 is enough for proof of concept.)

Reading the wiki article, it appears there are 45 patterns (including the blank) that meet this puzzle's rules.

答:
Perl, 71 67 65 char

```<code>y/10/#-/,s/../$&
/g,/^#/m&&print
for map{sprintf"%06b
",$_}18..63
</code>```

Convert int to binary, perform transliteration, and add a newline after every two chars.
The /^#/m test eliminates two patterns (20 and 21) that don't have a raised bump in the leftmost column.

General solution, 150 106 103 100 char

Read x and y from command line args. Newlines are significant

```<code>y/01/-#/,s/.{$x}/$&
/g,/^#/m*/^.*#/&&print
for map{sprintf"%0*b
",$x*$y,$_-1}1..1<<($y=pop)*($x=pop)
</code>```

Iterate over 0..2xy like before, converting each int to binary,
substituting - and # for 0 and 1, and inserting a newline after
every $x characters.

/^#/m tests that there is a raised bump in the leftmost column, and
/^.*#/ tests that there is a raised bump in the top row. Only the
patterns that pass both tests are printed.

Title: Write all possible Braille characters

Body:
Perl, 71 67 65 char

y/10/#-/,s/../$&
/g,/^#/m&&print
for map{sprintf"%06b
",$_}18..63

Convert int to binary, perform transliteration, and add a newline after every two chars.
The /^#/m test eliminates two patterns (20 and 21) that don't have a raised bump in the leftmost column.

General solution, 150 106 103 100 char

Read x and y from command line args. Newlines are significant

y/01/-#/,s/.{$x}/$&
/g,/^#/m*/^.*#/&&print
for map{sprintf"%0*b
",$x*$y,$_-1}1..1<<($y=pop)*($x=pop)

Iterate over 0..2xy like before, converting each int to binary,
substituting - and # for 0 and 1, and inserting a newline after
every $x characters.

/^#/m tests that there is a raised bump in the leftmost column, and
/^.*#/ tests that there is a raised bump in the top row. Only the
patterns that pass both tests are printed.


答:
Batch, <s>27</s> <s>20</s> 18 bytes

```<code>@cmd/cset/a%1%1*%1
</code>```

Edit: Saved 7 bytes thanks to @TessellatingHeckler. Saved a further 2 bytes thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ.

Title: Print a bunch of uninteresting numbers!

Body:
Batch, <s>27</s> <s>20</s> 18 bytes

@cmd/cset/a%1%1*%1

Edit: Saved 7 bytes thanks to @TessellatingHeckler. Saved a further 2 bytes thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ.


答:
Ruby, 266 bytes

More-or-less just a port of the Octave solution, except it solves rows first instead of columns. Input is an array of arrays, with the inner arrays being the rows. Output moves are [row, column, row, column]. Test suite

->m{t=->v{v.size*v.inject(:+)%3}
s=->a,x,r{g=t[a]
(q=(r=0..a.size-2).find{|i|a[i]!=a[i+1]&&g!=a[i]}||r.find{|i|a[i]!=a[i+1]}
a[q,2]=[t[a[q,2]]]*2
p r ?[x,q,x,q+1]:[q,x,q+1,x])while[]!=a-[g]}
m.size.times{|i|s[m[i],i,1]}
m=m.shift.zip *m
m.size.times{|i|s[m[i],i,p]}}
```

<h3>Ungolfed with explanation</h3>

```->m{                                  # Start lambda function, argument `m`
  t=->v{v.size*v.inject(:+)%3}        # Target color function
  s=->a,x,r{                          # Function to determine proper moves
                                      #   a = row array, x = row index, r = horizontal
    g=t[a]                            # Obtain target color
    (
      q=(r=0..a.size-2).find{|i|      # Find the first index `i` from 0 to a.size-2 where...
        a[i]!=a[i+1]                  # ...that element at `i` is different from the next...
        &&g!=a[i]                     # ...and it is not the same as the target color
      } || r.find{|i|a[i]!=a[i+1]}    # If none found just find for different colors
      a[q,2]=[t[a[q,2]]]*2            # Do the color flipping operation
      p r ?[x,q,x,q+1]:[q,x,q+1,x]    # Print the next move based on if `r` is truthy
    ) while[]!=a-[g]}                 # While row is not all the same target color, repeat
m.size.times{|i|                      # For each index `i` within the matrix's rows...
  s[m[i],i,1]                         # ...run the solving function on that row
                                      #   (`r` is truthy so the moves printed are for rows)
}
m=m.shift.zip *m                      # Dark magic to transpose the matrix
m.size.times{|i|s[m[i],i,p]}}         # Run the solving function on all the columns now
                                      #   (`r` is falsy so the moves printed are for columns)
```

Title: Solve the chromatic puzzle

Body:
Over at our friends at Puzzling.SE, the following puzzle was posted: Is this chromatic puzzle always solvable? by Edgar G. You can play it here.

Puzzle explanation

Given a m x n grid with tiles of three different colours, you may select any two adjacent tiles, if their colours are different. These two tiles are then converted to the third colour, i.e., the one colour not represented by these two tiles. The puzzle is solved if all tiles have the same colour. Apparently, one can prove that this puzzle is always solvable, if  neither m nor n are divisible by 3.

Of course, this begs for a solving algorithm. You will write a function or program that solves this puzzle. Note that functions with 'side effects' (i.e., the output is on stdout rather than in some awkward data type return value) are explicitly allowed.

Input & Output

The input will be an m x n matrix consisting of the integers 1, 2 and 3 (or 0, 1, 2 if convenient). You may take this input in any sane format. Both m and n are >1 and not divisible by 3. You may assume the puzzle is not solved

You will then solve the puzzle. This will involve a repeated selection of two adjacent tiles to be 'converted' (see above). You will output the two coordinates of these tiles for each step your solving algorithm took. This may also be in any sane output format. You are free to choose between 0-based and 1-based indexing of your coordinates, and whether rows or columns are indexed first. Please mention this in your answer, however.

Your algorithm should run within reasonable time on the original 8x8 case. Brute-forcing it completely is explicitly disallowed, i.e. your algorithm should run under O(k^[m*(n-1)+(m-1)*n]) with k the number of steps needed for the solution. The solution however is not required to be optimal. The proof given in the linked question may give you an idea as to how to do this (e.g., first do all columns using only vertically adjacent tiles, and then do all rows)

Test cases

In these test cases, the coordinates are 1-based and rows are indexed first (like MATLAB/Octave and probably many others).

```<code>Input:
[1 2]
Output: (result: all 3's)
[1 1],[1,2]

Input:
[ 1 2
  3 1 ]
Output: (result: all 1's)
[1 1],[2 1]        (turn left column into 2's)
[2 1],[2 2]        (turn right column into 3's)
[1 1],[1 2]        (turn top row into 1's)
[2 1],[2 2]        (turn bottom row into 1's)

Input:
[1 2 3 2
 3 2 1 1]

Output: (result: all 3's)
[1 1],[1 2]
[1 3],[1 4]
[1 2],[1 3]
[1 1],[1 2]
[1 2],[1 3]
[1 1],[1 2]
[1 3],[1 4]
[2 1],[2 2]
[1 1],[2 1]
[1 2],[2 2]
[1 3],[2 3]
[1 4],[2 4]
</code>```

If desired, I may post a pastebin of larger test cases, but I think this should be sufficient.

Body:
Ruby, 266 bytes

More-or-less just a port of the Octave solution, except it solves rows first instead of columns. Input is an array of arrays, with the inner arrays being the rows. Output moves are [row, column, row, column]. Test suite

->m{t=->v{v.size*v.inject(:+)%3}
s=->a,x,r{g=t[a]
(q=(r=0..a.size-2).find{|i|a[i]!=a[i+1]&&g!=a[i]}||r.find{|i|a[i]!=a[i+1]}
a[q,2]=[t[a[q,2]]]*2
p r ?[x,q,x,q+1]:[q,x,q+1,x])while[]!=a-[g]}
m.size.times{|i|s[m[i],i,1]}
m=m.shift.zip *m
m.size.times{|i|s[m[i],i,p]}}

Ungolfed with explanation

->m{                                  # Start lambda function, argument `m`
  t=->v{v.size*v.inject(:+)%3}        # Target color function
  s=->a,x,r{                          # Function to determine proper moves
                                      #   a = row array, x = row index, r = horizontal
    g=t[a]                            # Obtain target color
    (
      q=(r=0..a.size-2).find{|i|      # Find the first index `i` from 0 to a.size-2 where...
        a[i]!=a[i+1]                  # ...that element at `i` is different from the next...
        &&g!=a[i]                     # ...and it is not the same as the target color
      } || r.find{|i|a[i]!=a[i+1]}    # If none found just find for different colors
      a[q,2]=[t[a[q,2]]]*2            # Do the color flipping operation
      p r ?[x,q,x,q+1]:[q,x,q+1,x]    # Print the next move based on if `r` is truthy
    ) while[]!=a-[g]}                 # While row is not all the same target color, repeat
m.size.times{|i|                      # For each index `i` within the matrix's rows...
  s[m[i],i,1]                         # ...run the solving function on that row
                                      #   (`r` is truthy so the moves printed are for rows)
}
m=m.shift.zip *m                      # Dark magic to transpose the matrix
m.size.times{|i|s[m[i],i,p]}}         # Run the solving function on all the columns now
                                      #   (`r` is falsy so the moves printed are for columns)


答:
Forth, 63 bytes

This feels horribly inefficient...

```<code>: f dup 2dup 10e s>f flog 1e f+ floor f** s>f f* s>f f+ f>s * ;
</code>```

Try it online

Note that this works on Ideone (gforth-0.7.2), but not repl (JS-Forth), since repl doesn't support pushing numbers to the float stack or the flog and floor operations.

Explanation

```<code>: f                     ( define a word/function named 'f'              )
dup 2dup                ( duplicate 3 times                             )
10e                     ( push 10 to float stack, not used for log{n}   )
s>f flog                ( move # to f-stack and get its log-10          )
1e f+ floor             ( increment the above result by 1 and floor     )
f**                     ( use the 10 pushed earlier, 10**log{n}         )
s>f f* s>f f+           ( mul by n, then add n                          )
f>s * ;                 ( to regular stack, mul by n, end definition    )
</code>```

Title: Print a bunch of uninteresting numbers!

Body:
Forth, 63 bytes

This feels horribly inefficient...

: f dup 2dup 10e s>f flog 1e f+ floor f** s>f f* s>f f+ f>s * ;

Try it online

Note that this works on Ideone (gforth-0.7.2), but not repl (JS-Forth), since repl doesn't support pushing numbers to the float stack or the flog and floor operations.

Explanation

: f                     ( define a word/function named 'f'              )
dup 2dup                ( duplicate 3 times                             )
10e                     ( push 10 to float stack, not used for log{n}   )
s>f flog                ( move # to f-stack and get its log-10          )
1e f+ floor             ( increment the above result by 1 and floor     )
f**                     ( use the 10 pushed earlier, 10**log{n}         )
s>f f* s>f f+           ( mul by n, then add n                          )
f>s * ;                 ( to regular stack, mul by n, end definition    )


答:
Perl 6, <s> 24 21 20 </s> 19 bytes

<s>{not any (@_ X+@_)X==@_}
{so all (@_ X+@_)X!==@_}
{not @_ (&)(@_ X+@_)}
{not @_∩(@_ X+@_)}</s>

{!(@_∩(@_ X+@_))}```

<p>Input is any Positional value like a List.<br>
( a Set is an Associative so you would have to call <code>.keys</code> on it. )</p>

<h3>Test:</h3>

<pre class="lang-perl6 prettyprint-override"><code>#! /usr/bin/env perl6
use v6.c;
use Test;

my @sum-free = (
  (),
  (4,),
  (1, 5, 7),
  (16, 1, 4, 9),
);

my @not-sum-free = (
  (0,),
  (1, 4, 5, 7),
  (3, 0),
  (16, 1, 4, 8),
);

my @tests = ( |(@sum-free X=> True), |(@not-sum-free X=> False) );

plan +@tests;

# store the lambda in lexical namespace for clarity
my &sum-free-set = {!(@_∩(@_ X+@_))}

for @tests -> $_ ( :key(@list), :value($expected) ) {
  is sum-free-set(@list), $expected, .gist
}
</code>```

1..8
ok 1 - () => True
ok 2 - (4) => True
ok 3 - (1 5 7) => True
ok 4 - (16 1 4 9) => True
ok 5 - (0) => False
ok 6 - (1 4 5 7) => False
ok 7 - (3 0) => False
ok 8 - (16 1 4 8) => False
```

Title: Is it a sum-free set?

Body:
A set is sum-free if no two (not necessarily distinct) elements when added together are part of the set itself.

For example, {1, 5, 7} is sum-free, because all members are odd, and two odd numbers when added together are always even. On the other hand, {2, 4, 9, 13} is not sum-free, as either 2 + 2 = 4 or 4 + 9 = 13 add together to a member of the set.

Write a program or function that takes a set as input, and outputs a Truthy value if the set is sum-free, and Falsy otherwise.

Examples:

```<code>Sum-free:
{}
{4}
{1, 5, 7}
{16, 1, 4, 9}

Not sum-free:
{0}
{1, 4, 5, 7}
{3, 0}
{16, 1, 4, 8}
</code>```

Body:
Perl 6, <s> 24 21 20 </s> 19 bytes

<s>{not any (@_ X+@_)X==@_}
{so all (@_ X+@_)X!==@_}
{not @_ (&)(@_ X+@_)}
{not @_∩(@_ X+@_)}</s>

{!(@_∩(@_ X+@_))}

Input is any Positional value like a List.

( a Set is an Associative so you would have to call .keys on it. )

Test:

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

my @sum-free = (
  (),
  (4,),
  (1, 5, 7),
  (16, 1, 4, 9),
);

my @not-sum-free = (
  (0,),
  (1, 4, 5, 7),
  (3, 0),
  (16, 1, 4, 8),
);

my @tests = ( |(@sum-free X=> True), |(@not-sum-free X=> False) );

plan +@tests;

# store the lambda in lexical namespace for clarity
my &sum-free-set = {!(@_∩(@_ X+@_))}

for @tests -> $_ ( :key(@list), :value($expected) ) {
  is sum-free-set(@list), $expected, .gist
}

1..8
ok 1 - () => True
ok 2 - (4) => True
ok 3 - (1 5 7) => True
ok 4 - (16 1 4 9) => True
ok 5 - (0) => False
ok 6 - (1 4 5 7) => False
ok 7 - (3 0) => False
ok 8 - (16 1 4 8) => False


问:
Automate Saving the World
You are Desmond Hume. For the last 3 years, you and your partner, Kelvin, have been slave to a computer that requires a very specific sequence to be entered into it every 108 minutes to save the world.

```<code>4 8 15 16 23 42
</code>```

Your partner died 40 days ago (due to an unfortunate accident involving Kelvin's head and a big rock), and you have no one to talk to. No one to enter the numbers for you. No one to break the monotony. At first it wasn't too bad, but you can't handle the silence anymore. And if you have to listen to "Make Your Own Kind Of Music" one more time, you're going to scream.

You decide that You need to get out. To escape. You decide that you will build a raft and sail off the island. But then you realize the bad news: you're stuck here. You need to keep saving the world.

But then you realize the good news: You are a programmer! You can automate saving the world! Excited, you run over to the computer, and, using your trusty python skills, you whip up a quick script to enter the numbers for you.

import time

while True:
    print "4 8 15 16 23 42"
    time.sleep(60 * 107)
```

<p>Quick, simple, reliable, short, and easy. Everything that a good python script should be. But then, when you try to test it, you get an error. </p>

```Bad command or file name.
```

<p>Huh, strange. Oh well, let's try c++.</p>

<pre class="lang-c++ prettyprint-override"><code>#include <iostream>
#include <unistd.h>

int main()
{
    while (true)
    {
        std::cout << "4 8 15 16 23 42" << std::endl;
        sleep(60 * 107);
    }
}
</code>```

No! C++ isn't found either. You try every language you can think of. Javascript, Ruby, Perl, PHP, C#. Nothing. This computer was made before all of the popular languages of the day.

The Challenge

You must write a program that will:

1) Print exactly this: "4 8 15 16 23 42" (without quotes)

2) Wait some time between 104 and 108 minutes. (According to The Lost Wiki)

3) Repeat forever. (Or until you realize that this is all an elaborate scam, and that you're stuck in a weird limbo due to lazy writing, and asking questions that you don't have answers for. Thanks JJ Abrams!)

However there is a catch: You MUST use a language that the computer in the swan station would actually be capable of running. Assuming that

A) The computer was up to date at the time of construction,

B) There have been no updates to the computers software, and

C) There is no internet connection available (Meaning you can't download Golfscript...),

and making our best guess for the construction date of The Swan Station, (Again, The Lost Wiki.)

This means you have to use a language that was first released on or before Dec 31, 1977.

A few rule clarifications:

Including libraries is OK, but the same rule applies (libraries must be pre-1977).

You do not have to worry about  OS compatibility.

If you use system, or your languages equivalent, you must prove that any system commands you use would have been available before 1978. A wikipedia article is probably the best way to prove this.

It doesn't matter when you start the program, just as long as it ends up in a pattern of alternating printing and sleeping. (print-sleep-print-sleep... and sleep-print-sleep-print... are both acceptable.)

This is Code-Golf, so shortest answer in bytes wins.

答:
ALGOL 60 / 68 / W, <s>74</s> <s>47</s> 50 bytes

Run this full program with a68g save.a68, using algol68g.

ALGOL doesn't have a builtin way to sleep but we can run essentially  /bin/sleep:

```<code>DO print("4 8 15 16 23 42");system("sleep 6380")OD
</code>```

Old answer:

ALGOL doesn't have a sleep builtin, so we can abuse ping which is surely on a Unix of the time (idea from here) for <s>74</s> 69 bytes.

```<code>DO print("4 8 15 16 23 42");system("ping 1.0 -c1 -w6240>/dev/null")OD
</code>```

Title: Automate Saving the World

Body:
ALGOL 60 / 68 / W, <s>74</s> <s>47</s> 50 bytes

Run this full program with a68g save.a68, using algol68g.

ALGOL doesn't have a builtin way to sleep but we can run essentially  /bin/sleep:

DO print("4 8 15 16 23 42");system("sleep 6380")OD

Old answer:

ALGOL doesn't have a sleep builtin, so we can abuse ping which is surely on a Unix of the time (idea from here) for <s>74</s> 69 bytes.

DO print("4 8 15 16 23 42");system("ping 1.0 -c1 -w6240>/dev/null")OD


答:
Japt, 4 bytes

```<code>U²*U
</code>```

² translates to p2, which was (seemingly) designed to shorten the syntax for raising the number to the power of two. For strings, p function is repeating, not exponentiating, but the shortcut still works :) As you may've understood, takes the input as string.

Demo

Title: Print a bunch of uninteresting numbers!

Body:
An uninteresting number (which I totally didn't make up only for this challenge) is created like this:

Take a positive integer N

Create a new number O by adding the digits of N at the end of N

The final uninteresting number is O*N

For example for N=12:

O = 1212

O*N = 1212 * 12

Final number is 14544

Input

A positive integer N (N > 0) or your language's equivalent. You don't have to catch incorrect input.

Output

The corresponding uninteresting number.

Test cases

```<code>  1 -> 11
  2 -> 44
  3 -> 99
 10 -> 10100
174 -> 30306276
</code>```

Scoring

Shortest Code in Bytes wins.

Body:
Japt, 4 bytes

U²*U

² translates to p2, which was (seemingly) designed to shorten the syntax for raising the number to the power of two. For strings, p function is repeating, not exponentiating, but the shortcut still works :) As you may've understood, takes the input as string.

Demo


答:
Haskell, 22

I'm new to Haskell (and functional programming), so expert criticism is welcome.

```<code>f n=(read$n++n)*read n

main=do
  putStrLn $ show $ f "1"
  putStrLn $ show $ f "2"
  putStrLn $ show $ f "3"
  putStrLn $ show $ f "10"
  putStrLn $ show $ f "174"
</code>```

Title: Print a bunch of uninteresting numbers!

Body:
Haskell, 22

I'm new to Haskell (and functional programming), so expert criticism is welcome.

f n=(read$n++n)*read n

main=do
  putStrLn $ show $ f "1"
  putStrLn $ show $ f "2"
  putStrLn $ show $ f "3"
  putStrLn $ show $ f "10"
  putStrLn $ show $ f "174"


答:
ForceLang, 54 bytes, noncompeting

```<code>set a io.readnum()
io.write a.mult number.parse a+""+a
</code>```

Noncompeting, because it requires a language version published after this challenge (containing a patch for a minor parse error relating to the empty string literal).

The original answer, which doesn't require this bugfix (76 bytes):

```<code>set a io.readnum()
set b a+string.builder()
io.write a.mult number.parse b+a
</code>```

Title: Print a bunch of uninteresting numbers!

Body:
ForceLang, 54 bytes, noncompeting

set a io.readnum()
io.write a.mult number.parse a+""+a

Noncompeting, because it requires a language version published after this challenge (containing a patch for a minor parse error relating to the empty string literal).

The original answer, which doesn't require this bugfix (76 bytes):

set a io.readnum()
set b a+string.builder()
io.write a.mult number.parse b+a


答:
Mumps, 11 bytes

```<code>R I W I_I*I
</code>```

This is one of those rare golf challenges where the idiosyncrasies of Mumps can come in very handy. First, all variables are strings, and all math equations are strictly evaluated left-to-right (as in: not PEMDAS), so 1+2*4=12 in Mumps instead of =9 the way PEMDAS would. So, (barely) ungolfed:

```<code>R I ;     Read from stdin to variable I
W I_I*I ; Write out I concatenated with I, then multiplied by I.
</code>```

Word of caution - because the flavour of Mumps that I'm using (InterSystems Ensemble) does not echo the carriage return for stdin, the input and output number will appear concatenated. To rectify that / increase readability, you'd need to add two bytes and add a manual CR/LF, thusly:

```<code>R I W !,I_I*I
</code>```

However, as I didn't see that requirement in the rules of the challenge, I'm pretty sure that I'm good with the shorter code. If I'm mistaken, please feel free to LART me and I'll modify my answer. :-)

Title: Print a bunch of uninteresting numbers!

Body:
Mumps, 11 bytes

R I W I_I*I

This is one of those rare golf challenges where the idiosyncrasies of Mumps can come in very handy. First, all variables are strings, and all math equations are strictly evaluated left-to-right (as in: not PEMDAS), so 1+2*4=12 in Mumps instead of =9 the way PEMDAS would. So, (barely) ungolfed:

R I ;     Read from stdin to variable I
W I_I*I ; Write out I concatenated with I, then multiplied by I.

Word of caution - because the flavour of Mumps that I'm using (InterSystems Ensemble) does not echo the carriage return for stdin, the input and output number will appear concatenated. To rectify that / increase readability, you'd need to add two bytes and add a manual CR/LF, thusly:

R I W !,I_I*I

However, as I didn't see that requirement in the rules of the challenge, I'm pretty sure that I'm good with the shorter code. If I'm mistaken, please feel free to LART me and I'll modify my answer. :-)


答:
C, 50 bytes

Shorter than the other C solution, and thus not a duplicate. I actually wrote this before I noticed Digital Trauma's (nearly) identical comment on the other C solution.

```<code>main(){for(;;sleep(6240))puts("4 8 15 16 23 42");}
</code>```

Title: Automate Saving the World

Body:
You are Desmond Hume. For the last 3 years, you and your partner, Kelvin, have been slave to a computer that requires a very specific sequence to be entered into it every 108 minutes to save the world.

```<code>4 8 15 16 23 42
</code>```

Your partner died 40 days ago (due to an unfortunate accident involving Kelvin's head and a big rock), and you have no one to talk to. No one to enter the numbers for you. No one to break the monotony. At first it wasn't too bad, but you can't handle the silence anymore. And if you have to listen to "Make Your Own Kind Of Music" one more time, you're going to scream.

You decide that You need to get out. To escape. You decide that you will build a raft and sail off the island. But then you realize the bad news: you're stuck here. You need to keep saving the world.

But then you realize the good news: You are a programmer! You can automate saving the world! Excited, you run over to the computer, and, using your trusty python skills, you whip up a quick script to enter the numbers for you.

import time

while True:
    print "4 8 15 16 23 42"
    time.sleep(60 * 107)
```

<p>Quick, simple, reliable, short, and easy. Everything that a good python script should be. But then, when you try to test it, you get an error. </p>

```Bad command or file name.
```

<p>Huh, strange. Oh well, let's try c++.</p>

<pre class="lang-c++ prettyprint-override"><code>#include <iostream>
#include <unistd.h>

int main()
{
    while (true)
    {
        std::cout << "4 8 15 16 23 42" << std::endl;
        sleep(60 * 107);
    }
}
</code>```

No! C++ isn't found either. You try every language you can think of. Javascript, Ruby, Perl, PHP, C#. Nothing. This computer was made before all of the popular languages of the day.

The Challenge

You must write a program that will:

1) Print exactly this: "4 8 15 16 23 42" (without quotes)

2) Wait some time between 104 and 108 minutes. (According to The Lost Wiki)

3) Repeat forever. (Or until you realize that this is all an elaborate scam, and that you're stuck in a weird limbo due to lazy writing, and asking questions that you don't have answers for. Thanks JJ Abrams!)

However there is a catch: You MUST use a language that the computer in the swan station would actually be capable of running. Assuming that

A) The computer was up to date at the time of construction,

B) There have been no updates to the computers software, and

C) There is no internet connection available (Meaning you can't download Golfscript...),

and making our best guess for the construction date of The Swan Station, (Again, The Lost Wiki.)

This means you have to use a language that was first released on or before Dec 31, 1977.

A few rule clarifications:

Including libraries is OK, but the same rule applies (libraries must be pre-1977).

You do not have to worry about  OS compatibility.

If you use system, or your languages equivalent, you must prove that any system commands you use would have been available before 1978. A wikipedia article is probably the best way to prove this.

It doesn't matter when you start the program, just as long as it ends up in a pattern of alternating printing and sleeping. (print-sleep-print-sleep... and sleep-print-sleep-print... are both acceptable.)

This is Code-Golf, so shortest answer in bytes wins.

Body:
C, 50 bytes

Shorter than the other C solution, and thus not a duplicate. I actually wrote this before I noticed Digital Trauma's (nearly) identical comment on the other C solution.

main(){for(;;sleep(6240))puts("4 8 15 16 23 42");}