问:
Can you Golf Golf?
You are required to generate a random 18-hole golf course.

Example output:

```<code>[3 4 3 5 5 4 4 4 5 3 3 4 4 3 4 5 5 4]
</code>```

Rules:

Your program must output a list of hole lengths for exactly 18 holes

Each hole must have a length of 3, 4 or 5

The hole lengths must add up to 72 for the entire course

Your program must be able to produce every possible hole configuration with some non-zero-probability (the probabilities of each configuration need not be equal, but feel free to claim extra kudos if this is the case)

答:
16-bit x86 machine code under MS-DOS - 45 bytes

Hexdump:

```<code>0E5F576A12595188ECE44088C3E44130D8240374F400C4AAE2EF595E80FC2475DFAC0432CD29B020CD29E2F5C3
</code>```

Base64 coded binary:

```<code>Dl9XahJZUYjs5ECIw+RBMNgkA3T0AMSq4u9ZXoD8JHXfrAQyzSmwIM0p4vXD
</code>```

Actual source code with some comments:

```<code> bits 16
 org 0x100

again:
 push cs               ; Save whatever CS we get.
 pop di                ; Use CS:DI as our course buffer..
 push di               ; Save for later use in the print loop
 push 18               ; We need 18 holes for our golf course.
 pop cx                ; ch = 0, cl = 18.
 push cx               ; Save for later use.
 mov ah, ch            ; Zero out ah.
generate_course:
 in al, 0x40           ; Port 0x40 is the 8253 PIT Counter 0.
 mov bl, al            ; Save the first "random" value in bl.
 in al, 0x41           ; Port 0x41 is the 8253 PIT Counter 1.
 xor al, bl            ; Add some more pseudo randomness.
 and al, 3             ; We only need the two lower bits.
 jz generate_course    ; If zero, re-generate a value, since we need only 3, 4, 5 holes.
 add ah, al            ; Sum in ah register.
 stosb                 ; Store in the course buffer.
 loop generate_course  ; Loop for 18 holes.
 pop cx                ; cx = 18.
 pop si                ; si = course buffer.
 cmp ah, 36            ; 72 holes?
 jne again             ; No, re-generate the whole course.

print:                 ; Yup, we have a nice course.
 lodsb                 ; Load the next hole.
 add al, '2'           ; Add ASCII '2' to get '3', '4' or '5'
 int 0x29              ; Undocumented MS-DOS print function.
 mov al, ' '           ; Print a space too for better readability.
 int 0x29              ; Print the character.
 loop print            ; Print the whole course.
 ret                   ; Return to the beginning of the PSP where a INT 0x20 happen to be.
</code>```

Compile with nasm 18h.asm -o 18h.com and run under MS-DOS (or Dosbox), or NTVDM from a 32-bit Windows version.

Sample output:

```<code>4 5 4 5 4 5 3 4 3 4 3 4 4 5 4 3 5 3
</code>```

Title: Can you Golf Golf?

Body:
16-bit x86 machine code under MS-DOS - 45 bytes

Hexdump:

0E5F576A12595188ECE44088C3E44130D8240374F400C4AAE2EF595E80FC2475DFAC0432CD29B020CD29E2F5C3

Base64 coded binary:

Dl9XahJZUYjs5ECIw+RBMNgkA3T0AMSq4u9ZXoD8JHXfrAQyzSmwIM0p4vXD

Actual source code with some comments:

 bits 16
 org 0x100

again:
 push cs               ; Save whatever CS we get.
 pop di                ; Use CS:DI as our course buffer..
 push di               ; Save for later use in the print loop
 push 18               ; We need 18 holes for our golf course.
 pop cx                ; ch = 0, cl = 18.
 push cx               ; Save for later use.
 mov ah, ch            ; Zero out ah.
generate_course:
 in al, 0x40           ; Port 0x40 is the 8253 PIT Counter 0.
 mov bl, al            ; Save the first "random" value in bl.
 in al, 0x41           ; Port 0x41 is the 8253 PIT Counter 1.
 xor al, bl            ; Add some more pseudo randomness.
 and al, 3             ; We only need the two lower bits.
 jz generate_course    ; If zero, re-generate a value, since we need only 3, 4, 5 holes.
 add ah, al            ; Sum in ah register.
 stosb                 ; Store in the course buffer.
 loop generate_course  ; Loop for 18 holes.
 pop cx                ; cx = 18.
 pop si                ; si = course buffer.
 cmp ah, 36            ; 72 holes?
 jne again             ; No, re-generate the whole course.

print:                 ; Yup, we have a nice course.
 lodsb                 ; Load the next hole.
 add al, '2'           ; Add ASCII '2' to get '3', '4' or '5'
 int 0x29              ; Undocumented MS-DOS print function.
 mov al, ' '           ; Print a space too for better readability.
 int 0x29              ; Print the character.
 loop print            ; Print the whole course.
 ret                   ; Return to the beginning of the PSP where a INT 0x20 happen to be.

Compile with nasm 18h.asm -o 18h.com and run under MS-DOS (or Dosbox), or NTVDM from a 32-bit Windows version.

Sample output:

4 5 4 5 4 5 3 4 3 4 3 4 4 5 4 3 5 3


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

答:
COBOL, 240 bytes

Yes, the leading whitespace is significant. Compile and run like cobc -x save.cob; ./save. (The -x option produces an executable as opposed to a shared lib and thus I don't think it needs to be counted.)

```<code>       IDENTIFICATION DIVISION.
       PROGRAM-ID.S.
       PROCEDURE DIVISION.
           PERFORM UNTIL 1<>1
              DISPLAY"4 8 15 16 23 42"
              CALL"C$SLEEP"USING BY CONTENT 6402
           END-PERFORM.
           GOBACK.
</code>```

If we want to be boring, we can add the --free compilation option for free-format code, then 158 + 6 = 164 bytes but this would be unlikely to work back in '77.

```<code>IDENTIFICATION DIVISION.
PROGRAM-ID.S.
PROCEDURE DIVISION.
PERFORM UNTIL 1<>1
DISPLAY"4 8 15 16 23 42"
CALL"C$SLEEP"USING BY CONTENT 6402
END-PERFORM.
GOBACK.
</code>```

ContentLicense: CC BY-SA 3.0

Title: Automate Saving the World

Body:
COBOL, 240 bytes

Yes, the leading whitespace is significant. Compile and run like cobc -x save.cob; ./save. (The -x option produces an executable as opposed to a shared lib and thus I don't think it needs to be counted.)

       IDENTIFICATION DIVISION.
       PROGRAM-ID.S.
       PROCEDURE DIVISION.
           PERFORM UNTIL 1<>1
              DISPLAY"4 8 15 16 23 42"
              CALL"C$SLEEP"USING BY CONTENT 6402
           END-PERFORM.
           GOBACK.

If we want to be boring, we can add the --free compilation option for free-format code, then 158 + 6 = 164 bytes but this would be unlikely to work back in '77.

IDENTIFICATION DIVISION.
PROGRAM-ID.S.
PROCEDURE DIVISION.
PERFORM UNTIL 1<>1
DISPLAY"4 8 15 16 23 42"
CALL"C$SLEEP"USING BY CONTENT 6402
END-PERFORM.
GOBACK.


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

答:
Mathematica, 24 bytes

```<code>a=FromDigits;a[#<>#]a@#&
</code>```

Anonymous function, takes a string representing a number as input and generates its corresponding uninteresting number.

Title: Print a bunch of uninteresting numbers!

Body:
Mathematica, 24 bytes

a=FromDigits;a[#<>#]a@#&

Anonymous function, takes a string representing a number as input and generates its corresponding uninteresting number.


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

答:
JavaScript (ES6), 116 bytes

```<code>(n,t,s)=>[...Array(n)].map((_,i)=>++i&&t.reduce((r,a)=>r*i+a)%251,t=[...Array(t)].map(_=>--t?Math.random()*251|0:s))
</code>```

I'd like to think this is one of the rare cases where reduce beats map.

Title: Shamir's Secret Sharing

Body:
JavaScript (ES6), 116 bytes

(n,t,s)=>[...Array(n)].map((_,i)=>++i&&t.reduce((r,a)=>r*i+a)%251,t=[...Array(t)].map(_=>--t?Math.random()*251|0:s))

I'd like to think this is one of the rare cases where reduce beats map.


答:
Coffeescript, <s>36</s> <s>34</s> 19 bytes

Thanks to @Fawful for shaving off 2 bytes, and to @joeytwiddle for some more

```<code>a=(n)->(""+n+n|0)*n
</code>```

Neater script and explanation:

a=(n)->               # Creates a new function
       (""+n+n|0)     # Concatenate as strings, then convert back to integer
                 *n   # then multiplies it by n
```

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:
Coffeescript, <s>36</s> <s>34</s> 19 bytes

Thanks to @Fawful for shaving off 2 bytes, and to @joeytwiddle for some more

a=(n)->(""+n+n|0)*n

Neater script and explanation:

a=(n)->               # Creates a new function
       (""+n+n|0)     # Concatenate as strings, then convert back to integer
                 *n   # then multiplies it by n


问:
Rearrange a number into alphabetical order
Given a non-negative integer (n), create a function that returns n in alphabetical order, according to the literal spelling of each digit in n.

Examples:

```<code>Input: 101
>> one, zero, one
>> one, one, zero
Output: 110

Input: 31948
>> three, one, nine, four, eight
>> eight, four, nine, one, three
Output: 84913

Input: 5544
>> five, five, four, four
>> five, five, four, four
Output: 5544

Input: 1234567890
Output: 8549176320
</code>```

Note: the operations in the example are illustrative only and do not need to be included in the output. Only the alphabetically-sorted number needs to be returned.

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

Edit: the input can be taken in any desired format that best suits your language, and the output can be produced similarly by returning from the function or printing. The input will always be a natural number (including 0) and will not contain leading 0's.

Relevant OEIS entry (A057846) found by @DomHastings

答:
05AB1E, <s>12</s> <s>11</s> 10 bytes

```<code>•OWÿ¾•vy†J
</code>```

Explained

```<code>•OWÿ¾•        # push sortorder (236719458)
      v       # for each number in sortorder
       y†     # filter to the front
         J    # join
              # implicitly print
</code>```

Try it online

Saved 1 byte thanks to Adnan

Body:
05AB1E, <s>12</s> <s>11</s> 10 bytes

•OWÿ¾•vy†J

Explained

•OWÿ¾•        # push sortorder (236719458)
      v       # for each number in sortorder
       y†     # filter to the front
         J    # join
              # implicitly print

Try it online

Saved 1 byte thanks to Adnan


答:
Haskell, <s>62 51</s> 44 bytes

As @nimi suggested, using a list comprehension is shorter than composing functions:

```<code>f x=0+read[a|a<-"8549176320",b<-show x,a==b]
</code>```

For reference my version:

```<code>f n=read.(=<<)(\x->filter(==x)$show n)$"8549176320"
</code>```

The pointfree version is a bit longer:

```<code>f=flip(read.)"8549176320".(=<<).flip(filter.(==)).show
</code>```

Straightforward: Filter the digits in the correct order and then concatenate the result.

Title: Rearrange a number into alphabetical order

Body:
Given a non-negative integer (n), create a function that returns n in alphabetical order, according to the literal spelling of each digit in n.

Examples:

```<code>Input: 101
>> one, zero, one
>> one, one, zero
Output: 110

Input: 31948
>> three, one, nine, four, eight
>> eight, four, nine, one, three
Output: 84913

Input: 5544
>> five, five, four, four
>> five, five, four, four
Output: 5544

Input: 1234567890
Output: 8549176320
</code>```

Note: the operations in the example are illustrative only and do not need to be included in the output. Only the alphabetically-sorted number needs to be returned.

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

Edit: the input can be taken in any desired format that best suits your language, and the output can be produced similarly by returning from the function or printing. The input will always be a natural number (including 0) and will not contain leading 0's.

Relevant OEIS entry (A057846) found by @DomHastings

Body:
Haskell, <s>62 51</s> 44 bytes

As @nimi suggested, using a list comprehension is shorter than composing functions:

f x=0+read[a|a<-"8549176320",b<-show x,a==b]

For reference my version:

f n=read.(=<<)(\x->filter(==x)$show n)$"8549176320"

The pointfree version is a bit longer:

f=flip(read.)"8549176320".(=<<).flip(filter.(==)).show

Straightforward: Filter the digits in the correct order and then concatenate the result.


答:
Racket, <s>74</s> 62 bytes

```<code>(λ(n)(*((λ(m)(string->number(string-append m m)))(~a n))n))
</code>```

I hate the length of built-in function names in Racket sometimes.   Other times, I discover a really concisely named version of a function and transform a number->string into ~a.

Title: Print a bunch of uninteresting numbers!

Body:
Racket, <s>74</s> 62 bytes

(λ(n)(*((λ(m)(string->number(string-append m m)))(~a n))n))

I hate the length of built-in function names in Racket sometimes.   Other times, I discover a really concisely named version of a function and transform a number->string into ~a.


答:
Python 3 with NumPy, 103 bytes

```<code>from numpy import*
lambda n,t,s:[poly1d(append(random.randint(0,251,t-1),s))(i+1)%251for i in range(n)]
</code>```

I can honestly say that I never expected to use NumPy for code golf...

An anonymous function that takes input via argument and returns a list.

How it works

```<code>from numpy import*         Import everything in the NumPy library
lambda n,t,s...            Function with input number of players n, threshold value t and
                           secret s
random.randint(0,251,t-1)  Generate a NumPy array R of t-1 random integers in [0,250]
append(...,s)              Append s to R
poly1d(...)                Generate a polynomial p of order t-1 with coefficients R and
                           constant term s
...for i in range(n)       For all integers i in [0,n-1]...
...(i+1)                   ...evaluate p(i+1), so for all integers in [1,n]...
...%251                    ...and take modulo 251
...:[...]                  return as list
</code>```

Try it on Ideone

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:
Python 3 with NumPy, 103 bytes

from numpy import*
lambda n,t,s:[poly1d(append(random.randint(0,251,t-1),s))(i+1)%251for i in range(n)]

I can honestly say that I never expected to use NumPy for code golf...

An anonymous function that takes input via argument and returns a list.

How it works

from numpy import*         Import everything in the NumPy library
lambda n,t,s...            Function with input number of players n, threshold value t and
                           secret s
random.randint(0,251,t-1)  Generate a NumPy array R of t-1 random integers in [0,250]
append(...,s)              Append s to R
poly1d(...)                Generate a polynomial p of order t-1 with coefficients R and
                           constant term s
...for i in range(n)       For all integers i in [0,n-1]...
...(i+1)                   ...evaluate p(i+1), so for all integers in [1,n]...
...%251                    ...and take modulo 251
...:[...]                  return as list

Try it on Ideone


问:
Print the amount of ones in a binary number without using bitwise operators

Description

Given a number, print the amount of 1s it has in binary representation.

Input

A number >= 0 in base 10 that won't exceed the highest number your language is able to handle.

Output

The amount of 1s in binary representation.

Winning condition

The shortest code wins.

Disallowed

Bitwise operators. Other operators, like addition and multiplication, are allowed.

Built-in base conversion functions.

Examples

```<code>Input:     Ouput:

56432      8

Input:     Output:

45781254   11

Input:     Output:

0          0
</code>```

答:
Ocaml, 45 characters

Based on @Leah Xue's solution. Three spaces could be removed and it's sligthly shorter (~3 characters) to use function instead of if-then-else.

```<code>let rec o=function 0->0|x->(x mod 2)+(o(x/2))
</code>```

Body:
Ocaml, 45 characters

Based on @Leah Xue's solution. Three spaces could be removed and it's sligthly shorter (~3 characters) to use function instead of if-then-else.

let rec o=function 0->0|x->(x mod 2)+(o(x/2))


答:
Python 2 - 95 bytes

```<code>def s(n):
    l=list("8549176320")
    return "".join(sorted(list(n),key=lambda x: l.index(x)))
</code>```

Attempting further golfing...I think the line 2 is unnecessary and this can become 1 lambda.

EDIT: 49 char version in comments, thx to xnor and vaultah for help.

Body:
Python 2 - 95 bytes

def s(n):
    l=list("8549176320")
    return "".join(sorted(list(n),key=lambda x: l.index(x)))

Attempting further golfing...I think the line 2 is unnecessary and this can become 1 lambda.

EDIT: 49 char version in comments, thx to xnor and vaultah for help.


答:
Pyth, <s>12</s> 10 bytes

```<code>ox`C" »Ä\0
</code>```

Not sure if it can be golfed further. Input needs to be enclosed in quotes.

2 bytes saved thanks to @isaacg!

In pythonic pseudocode:

```<code>                Q = input()
o          Q    sort(Q, key = lambda N:
  `C" »Ä\0        repr(base256toDec(" »Ä\0"))
 x        N         .index(N)     # 8 being absent from the number yields -1
                )
</code>```

Test it here.

Body:
Pyth, <s>12</s> 10 bytes

ox`C" »Ä\0

Not sure if it can be golfed further. Input needs to be enclosed in quotes.

2 bytes saved thanks to @isaacg!

In pythonic pseudocode:

                Q = input()
o          Q    sort(Q, key = lambda N:
  `C" »Ä\0        repr(base256toDec(" »Ä\0"))
 x        N         .index(N)     # 8 being absent from the number yields -1
                )

Test it here.


问:
Domain Name Appraisal
Domain name trading is big business.  One of the most useful tools for domain name trading is an automatic appraisal tool, so that you can easily estimate how much a given domain is worth.  Unfortunately, many automatic appraisal services require a membership/subscription to use.  In this challenge, you will write a simple appraisal tool that can roughly estimate the values of .com domains.

Input / Output

As input, your program should take a list of domain names, one per line.  Each domain name will match the regex ^[a-z0-9][a-z0-9-]*[a-z0-9]$, meaning that it is composed of lowercase letters, digits, and hyphens.  Each domain is at least two characters long and neither begins nor ends with a hyphen.  The .com is omitted from each domain, since it is implied.

As an alternative form of input, you can choose to accept a domain name as an array of integers, instead of a string of characters, as long as you specify your desired character-to-integer conversion.

Your program should output a list of integers, one per line, which gives the appraised prices of the corresponding domains.

Internet and Additional Files

Your program may have access to additional files, as long as you provide these files as part of your answer.  Your program is also allowed to access a dictionary file (a list of valid words, which you don't have to provide).

(Edit) I have decided to expand this challenge to allow your program to access the internet.  There are a couple restrictions, being that your program cannot look up the prices (or price histories) of any domains, and that it only uses pre-existing services (the latter to cover up some loopholes).

The only limit on total size is the answer size limit imposed by SE.

Example input

These are some recently-sold domains.  Disclaimer: Although none of these sites seem malicious, I do not know who controls them and thus advise against visiting them.

```<code>6d3
buyspydrones
arcader
counselar
ubme
7483688
buy-bikes
learningmusicproduction
</code>```

Example Output

These numbers are real.

```<code>635
31
2000
1
2001
5
160
1
</code>```

Scoring

Scoring will be based on "difference of logarithms." For example, if a domain sold for $300 and your program appraised it at $500, your score for that domain is abs(ln(500)-ln(300)) = 0.5108. No domain will have a price less than $1. Your overall score is your average score for the set of domains, with lower scores better.

To get an idea what scores you should expect, simply guessing a constant 36 for the training data below results in a score of about 1.6883. A successful algorithm has a score less than this.

I chose to use logarithms because the values span several orders of magnitude, and the data will be filled with outliers.  The use of absolute difference instead of difference squared will help reduce the effect of outliers in scoring. (Also, note that I am using the natural logarithm, not base 2 or base 10.)

Data Source

I have skimmed a list of over 1,400 recently sold .com domains from Flippa, a domain auction website.  This data will make up the training data set.  After the submission period is over, I will wait an additional month to create a test data set, with which the submissions will be scored.  I might also choose to collect data from other sources to increase the size of the training/test sets.

The training data is available at the following gist.  (Disclaimer: Although I have used some simple filtering to remove some blatantly NSFW domains, several might still be contained in this list. Also, I advise against visiting any domain you don't recognize.)  The numbers on the right-hand side are the true prices.  https://gist.github.com/PhiNotPi/46ca47247fe85f82767c82c820d730b5

Here is a graph of the price distribution of the training data set.  The x-axis the the natural log of price, with y-axis being count.  Each bar has a width of 0.5.  The spikes on the left correspond to $1 and $6 since the source website requires bids to increment at least $5.  The test data may have a slightly different distribution.

Here is a link to the same graph with a bar width of 0.2.  In that graph you can see spikes at $11 and $16.

答:
Perl, 1.38605

I figured I should go ahead and post my own submission, in the hope that it spurs competition.  Its score of 1.38605 means that it is typically off by a factor of 3.999 (that was my stopping point).  I didn't use any machine learning libraries, just straight up Perl.  It does require access to a dictionary; I used the one from here.

Please feel free to use some of the numbers/statistics from my program in your own.

```<code>use strict;

my %dict;
my $dictname = "dict.txt";
open(my $dfh, '<', $dictname);
while (my $row = <$dfh>) {
  chomp $row;
  $dict{lc $row} = 1;
}

my $domain = <>;
chomp($domain);

my $guess = 1;

if($domain =~ /^[a-z]*$/){
    my @bylength = (200000,20001,401,45,45,41,26,26,26,26,26,24);
  if(length($domain) < ~~@bylength+2){
    $guess *= $bylength[length($domain)-2];
  } else {
    $guess *= 18;
  }
} elsif ($domain =~ /^[0-9]*$/){
  my @bylength = (300000,30001,6000,605,50);
  if(length($domain) < ~~@bylength+2){
    $guess *= $bylength[length($domain)-2];
  } else {
    $guess *= 7;
  }
} elsif ($domain =~ /^[a-z0-9]*$/){
  my @bylength = (52300,523,28);
  if(length($domain) < ~~@bylength+2){
    $guess *= $bylength[length($domain)-2];
  } else {
    $guess *= 23;
  }
} else {
  my @bylength = (50000,500,42,32,32,31);
  if(length($domain) < ~~@bylength+2){
    $guess *= $bylength[length($domain)-2];
  } else {
    $guess *= 12;
  }
}

my $wordfact = 1;

my $leftword = 0;
for(my $i = 1; $i <= length($domain); $i++){
  my $word = substr $domain, 0, $i;
  if(exists($dict{$word})){
    $leftword = $i;
  }
}

$wordfact *= ($leftword/length($domain))**2 * 0.8 + ($leftword/length($domain)) * -0.1 + 0.9;

if($leftword/length($domain) >= 0.8){
  $wordfact *= 2.4;
}

my $rightword = 0;
for(my $i = 1; $i <= length($domain); $i++){
  my $word = substr $domain, length($domain)-$i, $i;
  if(exists($dict{$word})){
    $rightword = $i;
  }
}

$wordfact *= ($rightword/length($domain))**2 * 0.9 + ($rightword/length($domain)) * -0.2 + 1;

$guess *= $wordfact;

my $charfact = 1;
my %charfacts = (
  i => 1.12, #500
  l => 0.84,
  s => 1.09,
  a => 0.94,
  r => 1.03,
  o => 0.97,
  c => 1.22, #400
  d => 0.88,
  u => 1.07,
  t => 0.95,
  e => 1.08,
  m => 0.91, #300
  p => 1.08,
  y => 0.92,
  g => 0.97,
  ne => 0.56, #100
  n => 1.13,
  z => 0.67,
  re => 1.30,
  es => 0.75,
);
while(my ($key,$value) = each %charfacts){
  if($domain =~ /$key/){
    $charfact *= $value;
  }
}
$guess *= $charfact;

$guess = int($guess + 0.5);
if($guess <= 0){
  $guess = 1;
}

print $guess;
</code>```

Here's a graph made by my scoring program, showing a scatter plot of appraisal over actual price and a histogram of the errors.  In the scatter plot .:oO@ mean 10, 20, 30, 40, 50 domains at that point, respectively. In the histogram each O represents 16 domains.

The scale is set at 1 character width = e^(1/3).

There are three main steps to this program.  The results from each step are multiplied together.

Categorization by character class and length.  It determines if the domain is all letters, all numbers, letters and numbers, or if it contains a hyphen.  It then gives a numerical value determined by the domain's length. I found that there is a strange dip in value around length 5. I suspect this is due to sampling: shorter domains are valuable due to their length (even if the letters are nonsense), while most longer domains tend to be words/phrases.  I order to prevent overfitting, I put a restriction in that domains cannot be penalized for being shorter (so length 5 is at least as good as length 6).

Evaluation of word content.  I use the dictionary to determine the lengths of the left-hand and right-hand words in a domain name.  For example, myawesomesite -> my & site -> 2 & 4.  Then, I try to do some fitting based on what proportion of the domain name is made up by those words.  Low values typically indicate that the domain does not contain a word, contains a pluralized/modified word not in the dictionary, contains a word surrounded by other characters (internal words are not detected, although I tried that with no improvement), or contains a several-word phrase.  High values indicate that it is a single word or a likely a two word phrase.

Evaluation of character content.  I looked for substrings that were contained in lot of domains and which appeared to affect the values of the domain.  I believe this is caused by certain types of words being more popular/more attractive, for various reasons. For example, the letter i appeared in about half of the domains (741 of them), and bumps up domain value by about 12% on average.  That's not overfitting; there's something real there, that I don't fully understand.  The letter l appears in 514 domains and has a factor of 0.84.  Some of the less common letters/digraphs, like ne which appeared 125 times and has a really low factor of 0.56, might be overfitting.

In order to improve upon this program, I would probably need to use machine learning of some kind.  Also, I could look for relationships between length, word content, and character content to find better ways of combining those separate results into the overall appraisal value.

Title: Domain Name Appraisal

Body:
Perl, 1.38605

I figured I should go ahead and post my own submission, in the hope that it spurs competition.  Its score of 1.38605 means that it is typically off by a factor of 3.999 (that was my stopping point).  I didn't use any machine learning libraries, just straight up Perl.  It does require access to a dictionary; I used the one from here.

Please feel free to use some of the numbers/statistics from my program in your own.

use strict;

my %dict;
my $dictname = "dict.txt";
open(my $dfh, '<', $dictname);
while (my $row = <$dfh>) {
  chomp $row;
  $dict{lc $row} = 1;
}

my $domain = <>;
chomp($domain);

my $guess = 1;

if($domain =~ /^[a-z]*$/){
    my @bylength = (200000,20001,401,45,45,41,26,26,26,26,26,24);
  if(length($domain) < ~~@bylength+2){
    $guess *= $bylength[length($domain)-2];
  } else {
    $guess *= 18;
  }
} elsif ($domain =~ /^[0-9]*$/){
  my @bylength = (300000,30001,6000,605,50);
  if(length($domain) < ~~@bylength+2){
    $guess *= $bylength[length($domain)-2];
  } else {
    $guess *= 7;
  }
} elsif ($domain =~ /^[a-z0-9]*$/){
  my @bylength = (52300,523,28);
  if(length($domain) < ~~@bylength+2){
    $guess *= $bylength[length($domain)-2];
  } else {
    $guess *= 23;
  }
} else {
  my @bylength = (50000,500,42,32,32,31);
  if(length($domain) < ~~@bylength+2){
    $guess *= $bylength[length($domain)-2];
  } else {
    $guess *= 12;
  }
}

my $wordfact = 1;

my $leftword = 0;
for(my $i = 1; $i <= length($domain); $i++){
  my $word = substr $domain, 0, $i;
  if(exists($dict{$word})){
    $leftword = $i;
  }
}

$wordfact *= ($leftword/length($domain))**2 * 0.8 + ($leftword/length($domain)) * -0.1 + 0.9;

if($leftword/length($domain) >= 0.8){
  $wordfact *= 2.4;
}

my $rightword = 0;
for(my $i = 1; $i <= length($domain); $i++){
  my $word = substr $domain, length($domain)-$i, $i;
  if(exists($dict{$word})){
    $rightword = $i;
  }
}

$wordfact *= ($rightword/length($domain))**2 * 0.9 + ($rightword/length($domain)) * -0.2 + 1;

$guess *= $wordfact;

my $charfact = 1;
my %charfacts = (
  i => 1.12, #500
  l => 0.84,
  s => 1.09,
  a => 0.94,
  r => 1.03,
  o => 0.97,
  c => 1.22, #400
  d => 0.88,
  u => 1.07,
  t => 0.95,
  e => 1.08,
  m => 0.91, #300
  p => 1.08,
  y => 0.92,
  g => 0.97,
  ne => 0.56, #100
  n => 1.13,
  z => 0.67,
  re => 1.30,
  es => 0.75,
);
while(my ($key,$value) = each %charfacts){
  if($domain =~ /$key/){
    $charfact *= $value;
  }
}
$guess *= $charfact;

$guess = int($guess + 0.5);
if($guess <= 0){
  $guess = 1;
}

print $guess;

Here's a graph made by my scoring program, showing a scatter plot of appraisal over actual price and a histogram of the errors.  In the scatter plot .:oO@ mean 10, 20, 30, 40, 50 domains at that point, respectively. In the histogram each O represents 16 domains.

The scale is set at 1 character width = e^(1/3).

There are three main steps to this program.  The results from each step are multiplied together.

Categorization by character class and length.  It determines if the domain is all letters, all numbers, letters and numbers, or if it contains a hyphen.  It then gives a numerical value determined by the domain's length. I found that there is a strange dip in value around length 5. I suspect this is due to sampling: shorter domains are valuable due to their length (even if the letters are nonsense), while most longer domains tend to be words/phrases.  I order to prevent overfitting, I put a restriction in that domains cannot be penalized for being shorter (so length 5 is at least as good as length 6).

Evaluation of word content.  I use the dictionary to determine the lengths of the left-hand and right-hand words in a domain name.  For example, myawesomesite -> my & site -> 2 & 4.  Then, I try to do some fitting based on what proportion of the domain name is made up by those words.  Low values typically indicate that the domain does not contain a word, contains a pluralized/modified word not in the dictionary, contains a word surrounded by other characters (internal words are not detected, although I tried that with no improvement), or contains a several-word phrase.  High values indicate that it is a single word or a likely a two word phrase.

Evaluation of character content.  I looked for substrings that were contained in lot of domains and which appeared to affect the values of the domain.  I believe this is caused by certain types of words being more popular/more attractive, for various reasons. For example, the letter i appeared in about half of the domains (741 of them), and bumps up domain value by about 12% on average.  That's not overfitting; there's something real there, that I don't fully understand.  The letter l appears in 514 domains and has a factor of 0.84.  Some of the less common letters/digraphs, like ne which appeared 125 times and has a really low factor of 0.56, might be overfitting.

In order to improve upon this program, I would probably need to use machine learning of some kind.  Also, I could look for relationships between length, word content, and character content to find better ways of combining those separate results into the overall appraisal value.


答:
JavaScript (ES6), 54

Edit same char count, but avoiding the global variable z

Input / output as strings

```<code>n=>[...n].sort((a,b)=>n[a]-n[b],n='9487216503').join``
</code>```

Test

f=n=>[...n].sort((a,b)=>n[a]-n[b],n='9487216503').join``

function test() {
  O.textContent=f(I.value)
}

test()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id=I type=number value=31948 oninput='test()'>
<pre id=O>``````

Body:
JavaScript (ES6), 54

Edit same char count, but avoiding the global variable z

Input / output as strings

n=>[...n].sort((a,b)=>n[a]-n[b],n='9487216503').join``

Test

f=n=>[...n].sort((a,b)=>n[a]-n[b],n='9487216503').join``

function test() {
  O.textContent=f(I.value)
}

test()

<input id=I type=number value=31948 oninput='test()'>
<pre id=O></pre>


答:
Mathematica <s>35 78</s> 47 bytes

31 bytes saved thanks to a suggestion by LIAMnYP!

```<code>FromDigits@SortBy[IntegerDigits@#,IntegerName]&
</code>```

IntegerDigits breaks up the number into digits which are then sorted according to their names in English. FromDigits assembles the digits into a base-10 number.

```<code>FromDigits@SortBy[IntegerDigits@#,IntegerName]&[1234567890]
</code>```

8549176320

Body:
Mathematica <s>35 78</s> 47 bytes

31 bytes saved thanks to a suggestion by LIAMnYP!

FromDigits@SortBy[IntegerDigits@#,IntegerName]&

IntegerDigits breaks up the number into digits which are then sorted according to their names in English. FromDigits assembles the digits into a base-10 number.

FromDigits@SortBy[IntegerDigits@#,IntegerName]&[1234567890]

8549176320


答:
Perl, 37 bytes

36 bytes code + 1 byte command line (-F)

```<code>say sort{8549176320=~/$b.*$a/||-1}@F
</code>```

Usage example:

```<code>echo -n "04823" | perl -F -M5.010 entry.pl
</code>```

Body:
Perl, 37 bytes

36 bytes code + 1 byte command line (-F)

say sort{8549176320=~/$b.*$a/||-1}@F

Usage example:

echo -n "04823" | perl -F -M5.010 entry.pl


问:
Golf to find Boring numbers
If an integer has a digit/sequence of digits in it which repeats continuously (You will understand why I said "continuously") 5 or more times, we call It "Boring".

For example, 11111 is Boring, whereas 12345 is not.

Instructions

Take an Integer as Input

Output a truthy value if the integer is boring, and a falsey value if the integer is not boring.

Example

11111=>true or 1 (1 repeats 5 times)

12345=>false or 0

1112111=>false or 0

4242424242=>true or 1 (42 repeats 5 times)

-11111=>true or 1

3452514263534543543543543543876514264527473275=>true or 1 (543 repeats 5 times)

If you use other types of "truth" and "false", specify it.

Rules

Basic code-golf rules apply.

Good luck!

答:
JS without regexes, 166

```<code>b=s=>{for(let i=0;i<s.length-4;i++){for(let n=1;n<=Math.floor((s.length-i)/5);n++){if([1,2,3,4].every(k=>s.slice(i,i+n)==s.slice(i+n*k,i+n*(k+1))))return 1}}return 0}
</code>```

non minified:

```<code>// test any start pos, and length
var b = s => {
    for (let i = 0; i <= s.length - 5; i++) {
        for (let n = 1; n <= Math.floor((s.length - i) / 5); n++) {
            // test if s is boring at position i, with length n
            if ([1, 2, 3, 4].every(k => s.slice(i, i + n) === s.slice(i + n * k, i + n * (k + 1)))) {
                return 1;
            }
        }
    }
    return 0;
};

console.log(b('11111'));
console.log(b('12345'));
console.log(b('1112111'));
console.log(b('-11111'));
console.log(b('3452514263534543543543543543876514264527473275'));
</code>```

Title: Golf to find Boring numbers

Body:
JS without regexes, 166

b=s=>{for(let i=0;i<s.length-4;i++){for(let n=1;n<=Math.floor((s.length-i)/5);n++){if([1,2,3,4].every(k=>s.slice(i,i+n)==s.slice(i+n*k,i+n*(k+1))))return 1}}return 0}

non minified:

// test any start pos, and length
var b = s => {
    for (let i = 0; i <= s.length - 5; i++) {
        for (let n = 1; n <= Math.floor((s.length - i) / 5); n++) {
            // test if s is boring at position i, with length n
            if ([1, 2, 3, 4].every(k => s.slice(i, i + n) === s.slice(i + n * k, i + n * (k + 1)))) {
                return 1;
            }
        }
    }
    return 0;
};

console.log(b('11111'));
console.log(b('12345'));
console.log(b('1112111'));
console.log(b('-11111'));
console.log(b('3452514263534543543543543543876514264527473275'));


答:
C, <s>142</s> <s>141</s> 117

Pass parameter as long long * to f(); the function modifies the parameter:

```<code>f(long long*n){char*c="8549176320",g[10]={0};for(;*n;*n/=10)++g[*n%10];for(;*c;++c)for(;g[*c-48]--;*n=*n*10+*c-48);}
</code>```

long long is necessary since the last test case overflowed an int when sorted.

Body:
C, <s>142</s> <s>141</s> 117

Pass parameter as long long * to f(); the function modifies the parameter:

f(long long*n){char*c="8549176320",g[10]={0};for(;*n;*n/=10)++g[*n%10];for(;*c;++c)for(;g[*c-48]--;*n=*n*10+*c-48);}

long long is necessary since the last test case overflowed an int when sorted.


答:
Racket, <s>142</s> 130 bytes

```<code>(λ(n)(string->number(list->string(sort(string->list(~a n))char<? #:key(λ(m)(string-ref "9487216503"(-(char->integer m)48)))))))
</code>```

Of which conversions are <s>more than</s> almost half of the length (<s>76</s> 64 bytes).

Body:
Racket, <s>142</s> 130 bytes

(λ(n)(string->number(list->string(sort(string->list(~a n))char<? #:key(λ(m)(string-ref "9487216503"(-(char->integer m)48)))))))

Of which conversions are <s>more than</s> almost half of the length (<s>76</s> 64 bytes).


答:
Mathematica 26

```<code>Count[n~IntegerDigits~2,1]
</code>```

Title: Print the amount of ones in a binary number without using bitwise operators

Body:
Description

Given a number, print the amount of 1s it has in binary representation.

Input

A number >= 0 in base 10 that won't exceed the highest number your language is able to handle.

Output

The amount of 1s in binary representation.

Winning condition

The shortest code wins.

Disallowed

Bitwise operators. Other operators, like addition and multiplication, are allowed.

Built-in base conversion functions.

Examples

```<code>Input:     Ouput:

56432      8

Input:     Output:

45781254   11

Input:     Output:

0          0
</code>```

Body:
Mathematica 26

Count[n~IntegerDigits~2,1]


问:
Highly composite numbers
A highly composite number is a positive integer that has more divisors than any smaller positive integer has. This is OEIS sequence A002182. Its first 20 terms are

```<code>1, 2, 4, 6, 12, 24, 36, 48, 60, 120, 180, 240, 360, 720, 840, 1260, 1680, 2520, 5040, 7560
</code>```

For example, 4 is in the sequence because it has 3 divisors (namely 1, 2, 4), whereas 3 only has 2 divisors, 2 also has 2 divisors, and 1 has 1 divisors.

Challenge

Given a positive integer input n, output either the n-th highly composite number or the first n highly composite numbers, at your choice (but the choice must be the same for every input n).

Rules

The program or function should theoretically work for arbitrarily large inputs given infinite time and memory, and without considering data type limitations. Essentially, this means no hardcoding a finite number of values.

In practice, the program or function should run in a reasonable amount of time, say less than 1 minute, for n up to 20. Maximum input or output may be limited by your language standard data type (but again, the algorithm should theoretically work for arbitrarily large numbers).

Any reasonable input and output format is allowed, including unary.

Code golf. Fewest bytes wins.

答:
Python 3, 97 bytes

```<code>i=p=q=0;n=int(input())
while q<n:
 c=j=0;i+=1
 while j<i:j+=1;c+=i%j==0
 if c>p:p=c;q+=1
print(i)
</code>```

A full program that takes input from STDIN and prints the output to STDOUT. This returns the nth 1-indexed highly composite number.

How it works

This is a straightforward implementation. The input n is the highly composite number index.

The program iterates over the integers i. For each integer j less than i, i mod j is taken; if this is 0, j must be a factor of i and the counter c is incremented, giving the number of divisors of i after looping. p is the previous highest number of divisors, so if c > p, a new highly composite number has been found and the counter q is incremented. Once q = n, i must be the nth highly composite number, and this is printed.

Try it on Ideone

(This takes ~15 seconds for n = 20, which exceeds the time limit for Ideone. Hence, the example given is for n = 18.)

Title: Highly composite numbers

Body:
Python 3, 97 bytes

i=p=q=0;n=int(input())
while q<n:
 c=j=0;i+=1
 while j<i:j+=1;c+=i%j==0
 if c>p:p=c;q+=1
print(i)

A full program that takes input from STDIN and prints the output to STDOUT. This returns the nth 1-indexed highly composite number.

How it works

This is a straightforward implementation. The input n is the highly composite number index.

The program iterates over the integers i. For each integer j less than i, i mod j is taken; if this is 0, j must be a factor of i and the counter c is incremented, giving the number of divisors of i after looping. p is the previous highest number of divisors, so if c > p, a new highly composite number has been found and the counter q is incremented. Once q = n, i must be the nth highly composite number, and this is printed.

Try it on Ideone

(This takes ~15 seconds for n = 20, which exceeds the time limit for Ideone. Hence, the example given is for n = 18.)


答:
MATL, 19 bytes

```<code>Vt'8549176320'&m2$S
</code>```

Try it online!

Explanation

```<code>V              % Implicitly input number. Convert to string (¹)
t              % Push copy of (¹)
'8549176320'   % Push this string (²), which defines order
&m             % Indices (³) of each element of (¹) in (²)
2$S            % Sort copy of (¹) according to (³). Implicitly display
</code>```

Body:
Given a non-negative integer (n), create a function that returns n in alphabetical order, according to the literal spelling of each digit in n.

Examples:

```<code>Input: 101
>> one, zero, one
>> one, one, zero
Output: 110

Input: 31948
>> three, one, nine, four, eight
>> eight, four, nine, one, three
Output: 84913

Input: 5544
>> five, five, four, four
>> five, five, four, four
Output: 5544

Input: 1234567890
Output: 8549176320
</code>```

Note: the operations in the example are illustrative only and do not need to be included in the output. Only the alphabetically-sorted number needs to be returned.

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

Edit: the input can be taken in any desired format that best suits your language, and the output can be produced similarly by returning from the function or printing. The input will always be a natural number (including 0) and will not contain leading 0's.

Relevant OEIS entry (A057846) found by @DomHastings

Body:
MATL, 19 bytes

Vt'8549176320'&m2$S

Try it online!

Explanation

V              % Implicitly input number. Convert to string (¹)
t              % Push copy of (¹)
'8549176320'   % Push this string (²), which defines order
&m             % Indices (³) of each element of (¹) in (²)
2$S            % Sort copy of (¹) according to (³). Implicitly display


答:
Ruby, 60 bytes

```<code>->n{n.to_s.chars.sort_by{|c|'8549176320'.index c}.join.to_i}
</code>```

Body:
Ruby, 60 bytes

->n{n.to_s.chars.sort_by{|c|'8549176320'.index c}.join.to_i}


答:
Perl 6, <s> 32 </s> 28 bytes

<s>{+[~] .comb.sort: *.Str.uniname}</s>
{+[~] .comb.sort: *.uniname}
```

<h3>Explanation:</h3>

<pre class="lang-perl6 prettyprint-override"><code>{
  # turn the following into a Numeric
  +

  # fold the following list using string concatenation operator
  [~]

    # split $_ into individual characters
    # (implicit method call on implicit parameter)
    .comb

    .sort:
    *.uniname # sort by the Unicode name of the character (digit)
}
</code>```

Test:

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

my @tests = (
  101 => 110,
  31948 => 84913,
  5544 => 5544,
  1234567890 => 8549176320,
);

# give the lambda a lexical name for clarity
my &int-sort = {+[~] .comb.sort: *.uniname}

plan 3 * @tests;

for @tests -> $_ ( :key($input), :value($expected) ) {
  put '';
  isa-ok $input, Int, "input ($input) is an Int";

  my $output = int-sort $input;

  is $output, $expected, .gist;
  isa-ok $output, Int, "output ($output) is an Int"
}
```

<pre class="lang-perl6 prettyprint-override"><code>1..12

ok 1 - input (101) is an Int
ok 2 - 101 => 110
ok 3 - output (110) is an Int

ok 4 - input (31948) is an Int
ok 5 - 31948 => 84913
ok 6 - output (84913) is an Int

ok 7 - input (5544) is an Int
ok 8 - 5544 => 5544
ok 9 - output (5544) is an Int

ok 10 - input (1234567890) is an Int
ok 11 - 1234567890 => 8549176320
ok 12 - output (8549176320) is an Int
</code>```

Body:
Perl 6, <s> 32 </s> 28 bytes

<s>{+[~] .comb.sort: *.Str.uniname}</s>
{+[~] .comb.sort: *.uniname}

Explanation:

{
  # turn the following into a Numeric
  +

  # fold the following list using string concatenation operator
  [~]

    # split $_ into individual characters
    # (implicit method call on implicit parameter)
    .comb

    .sort:
    *.uniname # sort by the Unicode name of the character (digit)
}

Test:

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

my @tests = (
  101 => 110,
  31948 => 84913,
  5544 => 5544,
  1234567890 => 8549176320,
);

# give the lambda a lexical name for clarity
my &int-sort = {+[~] .comb.sort: *.uniname}

plan 3 * @tests;

for @tests -> $_ ( :key($input), :value($expected) ) {
  put '';
  isa-ok $input, Int, "input ($input) is an Int";

  my $output = int-sort $input;

  is $output, $expected, .gist;
  isa-ok $output, Int, "output ($output) is an Int"
}

1..12

ok 1 - input (101) is an Int
ok 2 - 101 => 110
ok 3 - output (110) is an Int

ok 4 - input (31948) is an Int
ok 5 - 31948 => 84913
ok 6 - output (84913) is an Int

ok 7 - input (5544) is an Int
ok 8 - 5544 => 5544
ok 9 - output (5544) is an Int

ok 10 - input (1234567890) is an Int
ok 11 - 1234567890 => 8549176320
ok 12 - output (8549176320) is an Int


答:
J, <s>32</s> 30 bytes

```<code>251|(1+i.@{.)p.~{:0}251?@#~1&{
</code>```

Takes a list with the values n, t, and s.

Saved 2 bytes by using the replace at index 0 idea from @Dennis's solution.

Explanation

```<code>251|(1+i.@{.)p.~{:0}251?@#~1&{  Input: [n t s]
                           1&{  Select at index 1 (t)
                    251  #~     Create that many copies of 251
                       ?@       Generate that many random integers in [0, 251)
                {:              Get the tail of the input (s)
                  0}            Replace the value at index 0 of the random integer list
                                with s to make a coefficient list of the polynomial
          {.                    Get the head of the input (n)
       i.@                      Make the range [0, n-1]
     1+                         Add 1 to each to get [1, n]
             p.~                Evaluate the polynomial at each value [1, n]
251|                            Take each value mod 251 and return
</code>```

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:
J, <s>32</s> 30 bytes

251|(1+i.@{.)p.~{:0}251?@#~1&{

Takes a list with the values n, t, and s.

Saved 2 bytes by using the replace at index 0 idea from @Dennis's solution.

Explanation

251|(1+i.@{.)p.~{:0}251?@#~1&{  Input: [n t s]
                           1&{  Select at index 1 (t)
                    251  #~     Create that many copies of 251
                       ?@       Generate that many random integers in [0, 251)
                {:              Get the tail of the input (s)
                  0}            Replace the value at index 0 of the random integer list
                                with s to make a coefficient list of the polynomial
          {.                    Get the head of the input (n)
       i.@                      Make the range [0, n-1]
     1+                         Add 1 to each to get [1, n]
             p.~                Evaluate the polynomial at each value [1, n]
251|                            Take each value mod 251 and return


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

```

答:
C#, 267 bytes

```<code>()=>{for(int x=99;x>0;){string e="",s="s",t=x>1?s:e,b=" bottle",o=" of beer",w=$"{o} on the wall",a=x+b+t;System.Console.Write($"{a+w}, {a+o}.\n"+(x-->1?$"Take one down and pass it around, {x+b+(x>1?s:e)+w}.\n\n":$"Go to the store and buy some more, 99{b}s{w}."));}};
</code>```

C# lambda where the output is stdout and without output. You can try it on .NetFiddle.

Code :

```<code>()=>{
    for (int x=99;x>0;) {
        string e="",s="s",t=x>1?s:e,b=" bottle",o=" of beer",w=$"{o} on the wall",a=x+b+t;
        System.Console.Write($"{a+w}, {a+o}.\n"+(x-->1
            ?$"Take one down and pass it around, {x+b+(x>1?s:e)+w}.\n\n"
            :$"Go to the store and buy some more, 99{b}s{w}."));
}};
</code>```

Kudos to Igby Largeman for his solution. I think it is better than mine (shorter if it had use a lambda too).

ContentLicense: CC BY-SA 4.0

Title: "99 Bottles of Beer"

Body:
C#, 267 bytes

()=>{for(int x=99;x>0;){string e="",s="s",t=x>1?s:e,b=" bottle",o=" of beer",w=$"{o} on the wall",a=x+b+t;System.Console.Write($"{a+w}, {a+o}.\n"+(x-->1?$"Take one down and pass it around, {x+b+(x>1?s:e)+w}.\n\n":$"Go to the store and buy some more, 99{b}s{w}."));}};

C# lambda where the output is stdout and without output. You can try it on .NetFiddle.

Code :

()=>{
    for (int x=99;x>0;) {
        string e="",s="s",t=x>1?s:e,b=" bottle",o=" of beer",w=$"{o} on the wall",a=x+b+t;
        System.Console.Write($"{a+w}, {a+o}.\n"+(x-->1
            ?$"Take one down and pass it around, {x+b+(x>1?s:e)+w}.\n\n"
            :$"Go to the store and buy some more, 99{b}s{w}."));
}};

Kudos to Igby Largeman for his solution. I think it is better than mine (shorter if it had use a lambda too).


答:
Haskell, 80 (63?)

It would be 63 if there were no import statement.

```<code>import Data.List
f x=or$tail[isInfixOf(concat$replicate 5 b)x|b<-subsequences x]
</code>```

Usage

```<code>f "11111211"
f "11111"
f "12345"
f "1112111"
f "4242424242"
f "-11111"
f "3452514263534543543543543543876514264527473275"
</code>```

By the way, consecutive makes more sense to me than continuously.

(Sorry, I can't comment yet.)

Title: Golf to find Boring numbers

Body:
If an integer has a digit/sequence of digits in it which repeats continuously (You will understand why I said "continuously") 5 or more times, we call It "Boring".

For example, 11111 is Boring, whereas 12345 is not.

Instructions

Take an Integer as Input

Output a truthy value if the integer is boring, and a falsey value if the integer is not boring.

Example

11111=>true or 1 (1 repeats 5 times)

12345=>false or 0

1112111=>false or 0

4242424242=>true or 1 (42 repeats 5 times)

-11111=>true or 1

3452514263534543543543543543876514264527473275=>true or 1 (543 repeats 5 times)

If you use other types of "truth" and "false", specify it.

Rules

Basic code-golf rules apply.

Good luck!

Body:
Haskell, 80 (63?)

It would be 63 if there were no import statement.

import Data.List
f x=or$tail[isInfixOf(concat$replicate 5 b)x|b<-subsequences x]

Usage

f "11111211"
f "11111"
f "12345"
f "1112111"
f "4242424242"
f "-11111"
f "3452514263534543543543543543876514264527473275"

By the way, consecutive makes more sense to me than continuously.

(Sorry, I can't comment yet.)


问:
Expand a bash brace expansion
For mostly historical reasons, bash is quite a hodge-podge of syntax and programming paradigms - this can make it awkward and sometimes frustrating to golf in.  However it does have a few tricks up its sleeve that can often make it competitive with other mainstream script languages.  One of these is brace expansion.

There are two basic types of brace expansion:

List braces may contain comma-separated lists of arbitrary strings (including duplicates and the empty string).  For example {a,b,c,,pp,cg,pp,} will expand to a b c  pp cg pp (note the spaces around the empty strings).

Sequence braces may contain sequence endpoints separated by ... Optionally another .. may follow, followed by a step size.  Sequence endpoints may be either integers or characters.  The sequence will automatically ascend or descend according to which endpoint is greater.  For example:

{0..15} will expand to 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

{-10..-5} will expand to -10 -9 -8 -7 -6 -5

{3..-6..2} will expand to 3 1 -1 -3 -5

{a..f} will expand to a b c d e f

{Z..P..3} will expand to Z W T Q

Beyond this, sequence and list braces may exist with list braces:

{a,b,{f..k},p} will expand to a b f g h i j k p

{a,{b,c}} will expand to a b c

Braces expand with non-whitespace strings either side of them.  For example:

c{a,o,ha,}t will expand to cat cot chat ct

This also works for multiple braces concatenated together:

{ab,fg}{1..3} will expand to ab1 ab2 ab3 fg1 fg2 fg3

This can get quite complex.  For example:

{A..C}{x,{ab,fg}{1..3},y,} will expand to Ax Aab1 Aab2 Aab3 Afg1 Afg2 Afg3 Ay A Bx Bab1 Bab2 Bab3 Bfg1 Bfg2 Bfg3 By B Cx Cab1 Cab2 Cab3 Cfg1 Cfg2 Cfg3 Cy C

However, if there is whitespace between expansions, then they simply expand as separate expansions.  For example:

{a..c} {1..5} will expand to a b c 1 2 3 4 5

Note how order is always preserved.

Entries for this challenge will expand bash brace expansions as described above.  In particular:

eval by bash (or other shells that perform similar expansion) is not allowed

sequence braces will always be number-to-number, lowercase-to-lowercase or uppercase-to-uppercase with no mixing.  Numbers will be integers in the 32-bit signed range.  If given, the optional step size will always be a positive integer.  (Note that bash will also expand {A..z} as well, but this may be ignored for this challenge)

individual items in list braces will always be composed only of upper- and lower-case alphanumeric characters (empty string included)

list braces may contain arbitrary nestings of other brace expansions

braces may be concatenated arbitrary numbers of times.  This will be limited by your language's memory, so the expectation is that you can theoretically do arbitrary numbers of concatenations but if/when you run out of memory that won't count against you.

The examples in the text above serve as testcases.  Summarised, with each line of input corresponding to the same line of output, they are:

Input

```<code>{0..15}
{-10..-5}
{3..-6..2}
{a..f}
{Z..P..3}
{a,b,{f..k},p}
{a,{b,c}}
c{a,o,ha,}t
{ab,fg}{1..3}
{A..C}{x,{ab,fg}{1..3},y,}
{a..c} {1..5}
{a{0..100..10},200}r
</code>```

Output

```<code>0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
-10 -9 -8 -7 -6 -5
3 1 -1 -3 -5
a b c d e f
Z W T Q
a b f g h i j k p
a b c
cat cot chat ct
ab1 ab2 ab3 fg1 fg2 fg3
Ax Aab1 Aab2 Aab3 Afg1 Afg2 Afg3 Ay A Bx Bab1 Bab2 Bab3 Bfg1 Bfg2 Bfg3 By B Cx Cab1 Cab2 Cab3 Cfg1 Cfg2 Cfg3 Cy C
a b c 1 2 3 4 5
a0r a10r a20r a30r a40r a50r a60r a70r a80r a90r a100r 200r
</code>```

答:
JavaScript (Firefox 30-57), <s>465</s> <s>427</s> 425 bytes

```<code>f=s=>/\{/.test(s)?f(s.replace(/([^,{}]*\{[^{}]*\})+[^,{}]*/,t=>t.split(/[{}]+/).map(u=>u.split`,`).reduce((a,b)=>[for(c of a)for(d of b)c+d]))):s.split`,`.join` `
s=>f(`{${s.split` `}}`.replace(/\{(-?\w+)\.\.(-?\w+)(\.\.(\d+))?\}/g,(m,a,o,_,e)=>{m=(a>'@')+(a>'_');a=parseInt(a,m?36:10);o=parseInt(o,m?36:10);e=+e||1;if(o<a)e=-e;for(r=[];e<0?o<=a:a<=o;a+=e)r.push(m?a.toString(36):a);r=`{${r}}`;return m-1?r:r.toUpperCase()}))
</code>```

ES6 version of f weighs in at an extra 10 bytes:

f=s=>/\{/.test(s)?f(s.replace(/([^,{}]*\{[^{}]*\})+[^,{}]*/,t=>t.split(/[{}]+/).map(u=>u.split`,`).reduce((a,b)=>[].concat(...a.map(c=>b.map(d=>c+d)))))):s.split`,`.join` `
g=s=>f(`{${s.split` `}}`.replace(/\{(-?\w+)\.\.(-?\w+)(\.\.(\d+))?\}/g,(m,a,o,_,e)=>{m=(a>'@')+(a>'_');a=parseInt(a,m?36:10);o=parseInt(o,m?36:10);e=+e||1;if(o<a)e=-e;for(r=[];e<0?o<=a:a<=o;a+=e)r.push(m?a.toString(36):a);r=`{${r}}`;return m-1?r:r.toUpperCase()}))
h=(s,t=s.replace(/\{[^{}]*\}/,""))=>s!=t?h(t):!/[{}]/.test(s)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input oninput="o.textContent=h(this.value)?g(this.value):'{Invalid}'"><div id=o></code>```

Explanation: Starts by changing spaces into commas and wrapping the entire string in {} for consistency (thanks to @Blue for the idea). Then searches for all the {..} constructs and expands them into {,} constructs. Next uses recursion to repeatedly expands all {,} constructs from the inside out. Finally replaces all commas with spaces.

```<code>f=s=>/\{/.test(s)?                  while there are still {}s
 f(s.replace(                       recursive replacement
  /([^,{}]*\{[^{}]*\})+[^,{}]*/,    match the deepest group of {}s
  t=>t.match(/[^{}]+/g              split into {} terms and/or barewords
   ).map(u=>u.split`,`              turn each term into an array
   ).reduce((a,b)=>                 loop over all the arrays
    [for(c of a)for(d of b)c+d]))   cartesian product
  ):s.split`,`.join` `              finally replace commas with spaces
s=>f(                               change spaces into commas and wrap
 `{${s.split` `}}`.replace(         match all {..} seqences
   /\{([-\w]+)\.\.([-\w]+)(\.\.(\d+))?\}/g,(m,a,o,_,e)=>{
    m=(a>'@')+(a>'_');              sequence type 0=int 1=A-Z 2=a-z
    a=parseInt(a,m?36:10);          convert start to number
    o=parseInt(o,m?36:10);          convert stop to number
    e=+e||1;                        convert step to number (default 1)
    if(o<a)e=-e;                    check if stepping back
    for(r=[];e<0?o<=a:a<=o;a+=e)    loop over each value
     r.push(m?a.toString(36):a);    convert back to string
    r=`{${r}}`;                     join together and wrap in {}
    return m-1?r:r.toUpperCase()})) convert type 1 back to upper case
</code>```

Title: Expand a bash brace expansion

Body:
JavaScript (Firefox 30-57), <s>465</s> <s>427</s> 425 bytes

f=s=>/\{/.test(s)?f(s.replace(/([^,{}]*\{[^{}]*\})+[^,{}]*/,t=>t.split(/[{}]+/).map(u=>u.split`,`).reduce((a,b)=>[for(c of a)for(d of b)c+d]))):s.split`,`.join` `
s=>f(`{${s.split` `}}`.replace(/\{(-?\w+)\.\.(-?\w+)(\.\.(\d+))?\}/g,(m,a,o,_,e)=>{m=(a>'@')+(a>'_');a=parseInt(a,m?36:10);o=parseInt(o,m?36:10);e=+e||1;if(o<a)e=-e;for(r=[];e<0?o<=a:a<=o;a+=e)r.push(m?a.toString(36):a);r=`{${r}}`;return m-1?r:r.toUpperCase()}))

ES6 version of f weighs in at an extra 10 bytes:

f=s=>/\{/.test(s)?f(s.replace(/([^,{}]*\{[^{}]*\})+[^,{}]*/,t=>t.split(/[{}]+/).map(u=>u.split`,`).reduce((a,b)=>[].concat(...a.map(c=>b.map(d=>c+d)))))):s.split`,`.join` `
g=s=>f(`{${s.split` `}}`.replace(/\{(-?\w+)\.\.(-?\w+)(\.\.(\d+))?\}/g,(m,a,o,_,e)=>{m=(a>'@')+(a>'_');a=parseInt(a,m?36:10);o=parseInt(o,m?36:10);e=+e||1;if(o<a)e=-e;for(r=[];e<0?o<=a:a<=o;a+=e)r.push(m?a.toString(36):a);r=`{${r}}`;return m-1?r:r.toUpperCase()}))
h=(s,t=s.replace(/\{[^{}]*\}/,""))=>s!=t?h(t):!/[{}]/.test(s)

<input oninput="o.textContent=h(this.value)?g(this.value):'{Invalid}'"><div id=o>

Explanation: Starts by changing spaces into commas and wrapping the entire string in {} for consistency (thanks to @Blue for the idea). Then searches for all the {..} constructs and expands them into {,} constructs. Next uses recursion to repeatedly expands all {,} constructs from the inside out. Finally replaces all commas with spaces.

f=s=>/\{/.test(s)?                  while there are still {}s
 f(s.replace(                       recursive replacement
  /([^,{}]*\{[^{}]*\})+[^,{}]*/,    match the deepest group of {}s
  t=>t.match(/[^{}]+/g              split into {} terms and/or barewords
   ).map(u=>u.split`,`              turn each term into an array
   ).reduce((a,b)=>                 loop over all the arrays
    [for(c of a)for(d of b)c+d]))   cartesian product
  ):s.split`,`.join` `              finally replace commas with spaces
s=>f(                               change spaces into commas and wrap
 `{${s.split` `}}`.replace(         match all {..} seqences
   /\{([-\w]+)\.\.([-\w]+)(\.\.(\d+))?\}/g,(m,a,o,_,e)=>{
    m=(a>'@')+(a>'_');              sequence type 0=int 1=A-Z 2=a-z
    a=parseInt(a,m?36:10);          convert start to number
    o=parseInt(o,m?36:10);          convert stop to number
    e=+e||1;                        convert step to number (default 1)
    if(o<a)e=-e;                    check if stepping back
    for(r=[];e<0?o<=a:a<=o;a+=e)    loop over each value
     r.push(m?a.toString(36):a);    convert back to string
    r=`{${r}}`;                     join together and wrap in {}
    return m-1?r:r.toUpperCase()})) convert type 1 back to upper case


问:
Is this number a prime?
Believe it or not, we do not yet have a code golf challenge for a simple primality test. While it may not be the most interesting challenge, particularly for "usual" languages, it can be nontrivial in many languages.

Rosetta code features lists by language of idiomatic approaches to primality testing, one using the Miller-Rabin test specifically and another using trial division. However, "most idiomatic" often does not coincide with "shortest." In an effort to make Programming Puzzles and Code Golf the go-to site for code golf, this challenge seeks to compile a catalog of the shortest approach in every language, similar to "Hello, World!" and Golf you a quine for great good!.

Furthermore, the capability of implementing a primality test is part of our definition of programming language, so this challenge will also serve as a directory of proven programming languages.

Task

Write a full program that, given a strictly positive integer n as input, determines whether n is prime and prints a truthy or falsy value accordingly.

For the purpose of this challenge, an integer is prime if it has exactly two strictly positive divisors. Note that this excludes 1, who is its only strictly positive divisor.

Your algorithm must be deterministic (i.e., produce the correct output with probability 1) and should, in theory, work for arbitrarily large integers. In practice, you may assume that the input can be stored in your data type, as long as the program works for integers from 1 to 255.

Input

If your language is able to read from STDIN, accept command-line arguments or any other alternative form of user input, you can read the integer as its decimal representation, unary representation (using a character of your choice), byte array (big or little endian) or single byte (if this is your languages largest data type).

If (and only if) your language is unable to accept any kind of user input, you may hardcode the input in your program.

In this case, the hardcoded integer must be easily exchangeable. In particular, it may appear only in a single place in the entire program.

For scoring purposes, submit the program that corresponds to the input 1.

Output

Output has to be written to STDOUT or closest alternative.

If possible, output should consist solely of a truthy or falsy value (or a string representation thereof), optionally followed by a single newline.

The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation.

Additional rules

This is not about finding the language with the shortest approach for prime testing, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted.

Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

The language Piet, for example, will be scored in codels, which is the natural choice for this language.

Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

Unlike our usual rules, feel free to use a language (or language version) even if it's newer than this challenge. If anyone wants to abuse this by creating a language where the empty program performs a primality test, then congrats for paving the way for a very boring answer.

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

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

Built-in functions for testing primality are allowed. This challenge is meant to catalog the shortest possible solution in each language, so if it's shorter to use a built-in in your language, go for it.

Unless they have been overruled earlier, all standard code-golf rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

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

Catalog

The Stack Snippet at the bottom of this post generates the catalog 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

```

答:
APL (NARS2000), 6 bytes

Function: 0∘π

Program: 0π⎕

Title: Is this number a prime?


答:
Jelly, 11 bytes

```<code>“U1°ŀ”OṾf@€
</code>```

Try it here.

Explanation

```<code>“U1°ŀ”O       Get the Unicode ordinals of “U1°ŀ”
                (all of which are coincidentally single bytes
                in the Jelly code page!)
              The result is [85, 49, 176, 320].
       Ṿ      Uneval. This gets us the string “85,49,176,320”.
        f@€   For each char in this string, extract all chars
                from the first command line argument that
                equal it.
</code>```

Body:
Jelly, 11 bytes

“U1°ŀ”OṾf@€

Try it here.

Explanation

“U1°ŀ”O       Get the Unicode ordinals of “U1°ŀ”
                (all of which are coincidentally single bytes
                in the Jelly code page!)
              The result is [85, 49, 176, 320].
       Ṿ      Uneval. This gets us the string “85,49,176,320”.
        f@€   For each char in this string, extract all chars
                from the first command line argument that
                equal it.


问:
Array Sandwiches
(Adapted from Problem C of the first qualifier of the ACM Programming Contest of 2012/2013)

You have several arrays, named \$A_1, A_2, ... , A_n\$, each sorted in ascending order. Every item in the array will be a 32-bit integer.

A sandwich is a set of indices \$j_1, j_2, ... , j_n\$ such that \$A_1[j_1] ≤ A_2[j_2] ≤ ... ≤ A_n[j_n]\$. \$A_i[0]\$ is the first element of \$A_i\$.

Given some arrays, output every possible sandwich that you can have from those arrays, separated by a newline.

If there is somehow a built-in function which does this in your language, don't use it.

Input can be given in any way, output must be separated with whitespace, but can given in any order.

Test Case:

```<code>[[1, 5, 7, 10], [2, 6, 6, 8, 12], [4, 5, 9]]
</code>```

Output:

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

Test Case:

```<code>[[10, 20, 30], [1, 2, 3]]
</code>```

Output:

Shortest code wins.

答:
Python 120

```<code>f=lambda p,k=0:['%i '%j+m for j,v in enumerate(p[0])if v>=k for m in f(p[1:],v)]if p else['']
print'\n'.join(f(input()))
</code>```

... still think, "enumerate" is a very long word.

Title: Array Sandwiches

Body:
Python 120

f=lambda p,k=0:['%i '%j+m for j,v in enumerate(p[0])if v>=k for m in f(p[1:],v)]if p else['']
print'\n'.join(f(input()))

... still think, "enumerate" is a very long word.


答:
Factor, 128

```<code>[ 10 base> [ 48 - ] { } map-as dup [ number>text ] map zip [ second first ] sort-with [ first ] map [ 48 + ] ""map-as 10 >base ]
</code>```

Hooray for builtins! :D

Body:
Factor, 128

[ 10 base> [ 48 - ] { } map-as dup [ number>text ] map zip [ second first ] sort-with [ first ] map [ 48 + ] ""map-as 10 >base ]

Hooray for builtins! :D