答:
R, 97 bytes

```<code>b=F;for(j in 1:1e4){for(i in which(!j%%1:j)[-1])if(which(!i%%1:i)[2]==i)b=i<=j^0.5;if(b)print(j)}
</code>```

ungolfed

```<code>b <- F                               #Initializes
for (j in 1:1e4){                    #Loop across integers 1..10^4
    a <- which(!j%%1:j)[-1]          #Finds all factors
    for (i in a)                     #Loop across factors
         b <- which(!i%%1:i)[2]==i   #Tests primeness
         if(b) c <- i<=j^0.5         #If prime, tests smoothness
    if(c) print(j)                   #If biggest prime factor gives smooth
}                                    #result, Prints the number.
</code>```

Title: Pretty Smooth Moves

Body:
In arithmetic, an n-smooth number, where n is a given prime number, is mathematically defined as a positive integer that has no prime factors greater than n. For example, 42 is 7-smooth because all its prime factors are less than or equal to 7, but 44 is not 7-smooth because it also has 11 as a prime factor.

Define a pretty smooth number as a number with no prime factors greater than its own square root. Thus, the list of pretty smooth numbers can be formulated as follows:

(EDITED!) 1 is a pretty smooth number, due to its complete lack of any prime factors. (Note that in the original version of this question, 1 was erroneously excluded from the list, so if you exclude it from your outputs you won't be marked wrong.)

Between 4 (= 22) and 8, the pretty smooth numbers are 2-smooth, meaning they have 2 as their only prime factor.

Between 9 (= 32) and 24, the pretty smooth numbers are 3-smooth, and can have 2s and 3s in their prime factorizations.

Between 25 (= 52) and 48, the pretty smooth numbers are 5-smooth, and can have 2s, 3s, and 5s in their prime factorizations.

And so on, upgrading the criteria every time the square of the next prime number is reached.

The list of pretty smooth numbers is fixed, and begins as follows: 1, 4, 8, 9, 12, 16, 18, 24, 25, ...

Your challenge is to write code that will output all pretty smooth numbers up to and including 10,000 (= 1002). There must be at least one separator (it doesn't matter what kind -- space, comma, newline, anything) between each number in the list and the next, but it is completely irrelevant what character is used.

As per usual, lowest byte count wins -- obviously, simply outputting the list isn't going to be too beneficial to you here. Good luck!

Body:
R, 97 bytes

b=F;for(j in 1:1e4){for(i in which(!j%%1:j)[-1])if(which(!i%%1:i)[2]==i)b=i<=j^0.5;if(b)print(j)}

ungolfed

b <- F                               #Initializes
for (j in 1:1e4){                    #Loop across integers 1..10^4
    a <- which(!j%%1:j)[-1]          #Finds all factors
    for (i in a)                     #Loop across factors
         b <- which(!i%%1:i)[2]==i   #Tests primeness
         if(b) c <- i<=j^0.5         #If prime, tests smoothness
    if(c) print(j)                   #If biggest prime factor gives smooth
}                                    #result, Prints the number.


问:
Wave-Particle Duality Laterally Programmatically
Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as . or          ., or the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as \ or /\/ or \/\/\/\/\/\/.

In either case, propagate the particle/wave to the right by one unit.

Specifically, in the particle case, insert a space before the ., moving it one place to the right, then output the resulting string. For example:

. →  .

 . →   .

  . →    .

   . →     .

    . →      .

     . →       .

      . →        .

       . →         .

In the wave case, append either / or \ appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:

/ → /\

\ → \/

/\ → /\/

\/ → \/\

/\/ → /\/\

\/\ → \/\/

/\/\ → /\/\/

\/\/ → \/\/\

In either case, the output may not have trailing spaces but an optional trailing newline is allowed.

The shortest code in bytes wins.

ContentLicense: CC BY-SA 3.0

Body:
C#, 54 bytes

s=>s.EndsWith(".")?" "+s:s+(s.EndsWith("/")?"\\":"/");


问:
Evaluate an expression of ternary operators
Consider a grammar over the alphabet {0, 1, ?, :} defined by the production rule

s → 0 ┃ 1 ┃ 0 ? s : s ┃ 1 ? s : s

Given a string generated from s, parse it as an expression where ?: is right-associative (for example, a?B?X:Y:c?d:e?f:g means a?(B?X:Y):(c?d:(e?f:g))) and evaluate it with the following semantics:

```<code>eval(0) = 0
eval(1) = 1
eval(0?a:b) = eval(b)
eval(1?a:b) = eval(a)
</code>```

If the result is 0, output some fixed value; if the output is 1, output a different fixed value. Specify your chosen output values (e.g. 0/1, or False/True) in your answer.

Test cases

```<code>0 -> 0
1 -> 1
0?0:1 -> 1
0?1:0 -> 0
1?0:1 -> 0
1?1:0 -> 1
0?1?0:1:1 -> 1
1?0?1:1:1 -> 1
1?0:1?0:1?1:1 -> 0
1?1?1:0?1?0:0:0:0 -> 1
1?0:1?0?1:1?1:0:1?1?1:1:1?0:1 -> 0
1?1?1:0?0?1:1:0?1:0:1?1?0?0:0:1?1:0:0?1?0:1:1?0:1 -> 1
0?0?1?0?0:1:0?0:0:0?0?1:1:1?0:1:0?0?0?1:0:0?1:1:1?1?0:1:1 -> 0
</code>```

Rules

You may not use language built-ins that interpret strings as code in some programming language and run it (such as JavaScript/Perl/Ruby/Python’s eval).

That said, your code doesn’t actually have to parse and then evaluate the input string. You can take any approach the achieves equivalent results and doesn’t violate the previous rule.

Your program will be checked against perl -le 'print eval<>'.

The shortest code (in bytes) wins.

Body:
SED, 75 74 68 (40 + 1 for -r) 41

:
s,(.*)1\?(.):.,\1\2,
s,(.*)0\?.:,\1,
t


问:
Match up to 10 in an array

Challenge

Given an array of single digit number, work out if any 2 of them add up to 10 and print them out

Example

Input

(1,2,3,4,5,5,6,7)

This returns ((4,6),(5,5),(3,7))

Input

(1,2,3,4,5)

This returns (). as there is only one 5

Input

(5,5,5,5,5)

This returns ((5,5),(5,5)) as there is odd number of 5s and each 5 can be used only once

Rules

Here are the rules!

Assume input will only be an unsorted array of positive single digit integers

Each number will be pair up only once, which means if there are three 5s it only form 1 pair (5,5). If there are (3,3,7) it will only form 1 pair (3,7)

For the input: You can use any type of parentheses(or lack of) as long as readers can tell that the input is a single array of numbers.

For the output: It must look like an array of pairs. Where the array is the same form as your input.(If you did not use any parenheses in your input, you have to use some kind of symbols so that any readers can tell they are pairs in an array)

Test Cases

```<code>(1,2,3,4,5,5,6,7) =((4,6),(5,5),(3,7))
(1,2,3,4,5) = ()
(5,5,5,5,5) = ((5,5),(5,5))
(1,2,3,3,4,5,6,7)=((3,7),(4,6))
(9,8,7,6,4,4,3,1)=((9,1),(7,3),(6,4))
</code>```

Good luck!

The shorter an answer is, the better!

Edit 1: update the rules and Testcases from comments

Edit 2: update rules to define format of input.

Edit 3: update rules to define format of output. trying to be as accommodating as possible.

Title: Match up to 10 in an array

Body:
Perl, 72 with the -p flag

perl -p -e 's/^/@/;1while s/(@.*)(.)(.*)((??{10-$2}))/($2,$4)$1$3/;s/(.*)@.*/($1)/'


问:
Given an integer, compute its Levenshtein code
Disclaimer: Levenshtein coding is completely unrelated to the Levenshtein edit distance metric.

<Insert long story about why Levenshtein codes need to be calculated here.>

The code

Levenshtein coding is a system of assigning binary codes to nonnegative integers that retains some weird property in probability which isn't relevant for this challenge. We will denote this code as L(n). Wikipedia describes this as a five-step process:

Initialize the step count variable C to 1.

Write the binary representation of the number without the leading 1 to the beginning of the code.

Let M be the number of bits written in step 2.

If M is not 0, increment C, repeat from step 2 with M as the new number.

Write C 1 bits and a 0 to the beginning of the code.

However, the code can also be described recursively:

If the number is 0, then its code is 0.

Write the binary representation of the number without the leading 1 to the beginning of the code.

Let M be the number of bits written in step 2.

Write L(M) to the beginning of the code.

Write a 1 bit to the beginning of the code.

For those who prefer examples, here is the recursive process for L(87654321), with  denoting concatenation:

The challenge

Write a program or function that, given a number n, outputs the bitstring L(n) in any reasonable format (this includes returning a number with said bits). Standard loopholes are, as always, disallowed.

Examples

Input: 5

Output: 1110001

Input: 30

Output: 111100001110

Input: 87654321

Output: 111110000101001001110010111111110110001

Input: 0

Output: 0

答:
PHP, 116 114 bytes

```<code><?$f=function($i)use(&$f){$b=decbin($i);return!$b?0:preg_replace('/^1/',1 .$f(~~log10($b)),$b);};echo$f($argv[1]);
</code>```

Provide the number as the first argument.

Update:

Saved a byte by replacing strlen($b)-1 with ~~log10($b) (finally understood why everybody else was using logarithm) and another by concatenating differently.

Body:
PHP, 116 114 bytes

<?$f=function($i)use(&$f){$b=decbin($i);return!$b?0:preg_replace('/^1/',1 .$f(~~log10($b)),$b);};echo$f($argv[1]);

Provide the number as the first argument.

Update:

Saved a byte by replacing strlen($b)-1 with ~~log10($b) (finally understood why everybody else was using logarithm) and another by concatenating differently.


问:
Smallest positive integer which is coprime to the last two predecessors and has not yet appeared; a(1)=1, a(2)=2

Definition

Two integers are coprime if they share no positive common divisors other than 1.

a(1) = 1

a(2) = 2

a(n) is the smallest positive integer which is coprime to the a(n-1) and a(n-2) and has not yet appeared, for integer n >= 3.

Task

Given positive integer n, output/print a(n).

Example

a(11) = 6 because 6 is coprime with the last two predecessors (namely, 11 and 13) and 6 has not appeared before.

Notes

Note that the sequence is not ascending, meaning that an element can be smaller than its predecessor.

Specs

You must use 1-indexed.

Testcases

```<code>n      a(n)
1      1
2      2
3      3
4      5
5      4
6      7
7      9
8      8
9      11
10     13
11     6
12     17
13     19
14     10
15     21
16     23
17     16
18     15
19     29
20     14
100    139
1000   1355
10000  13387
100000 133361
</code>```

Scoring

Since coprime means that the two numbers share only one divisor (1), and 1 is a small number, your code should be as small as possible in terms of byte-count.

References

OEIS A084937

答:
Haskell, <s>81</s> 73 bytes

```<code>c l@(m:n:_)=m:c([x|x<-[1..],gcd(m*n)x<2,all(/=x)l]!!0:l)
((0:1:c[2,1])!!)
</code>```

Usage example: ((0:1:c[2,1])!!) 12-> 17.

Build the list of all a(n), starting with 0 to fix the 1-based index and 1 and followed by c[2,1]. c takes the head of it's argument list l followed by a recursive call with then next number that fits (co-prime, not seen before) added in front of l. Pick the nth element of this list.

Body:
Haskell, <s>81</s> 73 bytes

c l@(m:n:_)=m:c([x|x<-[1..],gcd(m*n)x<2,all(/=x)l]!!0:l)
((0:1:c[2,1])!!)

Usage example: ((0:1:c[2,1])!!) 12-> 17.

Build the list of all a(n), starting with 0 to fix the 1-based index and 1 and followed by c[2,1]. c takes the head of it's argument list l followed by a recursive call with then next number that fits (co-prime, not seen before) added in front of l. Pick the nth element of this list.


问:
Right and tfeL truncatable primes
A right-truncatable prime is a prime where every prefix is a prime (in base 10).  A left-truncatable prime is exactly the opposite, where every postfix is a prime (primes that start with 0 aren't allowed).  Both of these sequences are finite (There are only 83 Right-truncatables, while there are 4260 Left-truncatables).

You need to write a program that accepts a single number as input, and produces the nth right-truncatable prime.  However, when the program is read arranged backwards, it should produce the nth left-truncatable prime.

To arrange a program backwards, we split the program into words, then reverse the order of the words.  A word can consist of any number of characters.

For example, if the following was your program:

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

The following would all be allowed as possible backwards arrangements:

Splitting on each character:

```<code>0987654321
dlrow olleh
</code>```

Splitting on whitespace:

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

Splitting arbitrarily (pipes added for clarity):

```<code>hel|lo w|orld
1|23456|7|8|90

908723456orld
1lo whel
</code>```

When arranging your program backwards, all whitespace must be considered and reversed, just like any other character.

Forward test inputs:

```<code>1:  2
2:  3
21: 379
60: 239933
83: 73939133
</code>```

Backward test inputs:

```<code>1:    2
2:    3
39:   647
187:  29173
4260: 357686312646216567629137
</code>```

Programs should be able to run in a reasonable amount of time (less than a minute)

This is a code-golf, so the program with the fewest bytes wins!

答:
Jelly, <s>26</s> 23 bytes

Forward

```<code>Ñ¶p9¶7ÆR2ĿV€$ÆPÐf$ÐĿFị@
</code>```

Try it online!

Words

Ñ ¶ p 9 ¶ 7ÆR2ĿV€$ÆPÐf$ÐĿFị@

Backward

```<code>7ÆR2ĿV€$ÆPÐf$ÐĿFị@¶9p¶Ñ
</code>```

Try it online!

Words

7ÆR2ĿV€$ÆPÐf$ÐĿFị@ ¶ 9 p ¶ Ñ

How it works

All Jelly programs consist of links (Jelly's take on functions), which are separated by linefeeds or pilcrows (¶). The last of them is the main link; it is called automatically when the program is run.

The forward program works as follows.

```<code>Ñ                   Helper link. Unused.

p9                  Helper link. Take the Cartesian product with [1, ..., 9].

7ÆR2ĿV€$ÆPÐf$ÐĿFị@  Main link. Argument: n

7ÆR                 Yield all primes up to 7.
             ÐĿ
            $ÐĿ     Combine the two quicklinks to the left into a monadic chain,
                    and call it repeatedly until the results are no longer unique.
                    Return the array of all intermediate results.
       $              Combine the two links to the left into a monadic chain.
   2Ŀ               Call the helper link on line 2.
     Ṿ€                 Eval each array in the product. This casts to string
                        before evaluating, thus concatenating both numbers.
        ÆPÐf        Filter by primality; keep only primes.
               F    Flatten the resulting array.
                ị@  Retrieve the element at index n.
</code>```

The backward program does almost exactly the same; there are only two differences.

The main link is now Ñ, which simply calls the link below it (wrapping around), i.e., the main link of the forward program.

9p instead of p9 return the reversed Cartesian product.

Title: Right and tfeL truncatable primes

Body:
Jelly, <s>26</s> 23 bytes

Forward

Ñ¶p9¶7ÆR2ĿV€$ÆPÐf$ÐĿFị@

Try it online!

Words

Ñ ¶ p 9 ¶ 7ÆR2ĿV€$ÆPÐf$ÐĿFị@

Backward

7ÆR2ĿV€$ÆPÐf$ÐĿFị@¶9p¶Ñ

Try it online!

Words

7ÆR2ĿV€$ÆPÐf$ÐĿFị@ ¶ 9 p ¶ Ñ

How it works

All Jelly programs consist of links (Jelly's take on functions), which are separated by linefeeds or pilcrows (¶). The last of them is the main link; it is called automatically when the program is run.

The forward program works as follows.

Ñ                   Helper link. Unused.

p9                  Helper link. Take the Cartesian product with [1, ..., 9].

7ÆR2ĿV€$ÆPÐf$ÐĿFị@  Main link. Argument: n

7ÆR                 Yield all primes up to 7.
             ÐĿ
            $ÐĿ     Combine the two quicklinks to the left into a monadic chain,
                    and call it repeatedly until the results are no longer unique.
                    Return the array of all intermediate results.
       $              Combine the two links to the left into a monadic chain.
   2Ŀ               Call the helper link on line 2.
     Ṿ€                 Eval each array in the product. This casts to string
                        before evaluating, thus concatenating both numbers.
        ÆPÐf        Filter by primality; keep only primes.
               F    Flatten the resulting array.
                ị@  Retrieve the element at index n.

The backward program does almost exactly the same; there are only two differences.

The main link is now Ñ, which simply calls the link below it (wrapping around), i.e., the main link of the forward program.

9p instead of p9 return the reversed Cartesian product.


答:
SED, 41 36 27

saved 7 thanks to charlie

```<code> s|\.| .|;s|/$|/\\|;t;s|$|/|
</code>```

uses 3 substitutions:

s/\./ ./ adds a space if there is a .

s|/$|/\\|,s|$|/| adds the appropriate slash to the end

uses | instead of / as the delimiter

t branches to the end if the second regex matches so it doesn't add the other slash

Title: Wave-Particle Duality Laterally Programmatically

Body:
Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as . or          ., or the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as \ or /\/ or \/\/\/\/\/\/.

In either case, propagate the particle/wave to the right by one unit.

Specifically, in the particle case, insert a space before the ., moving it one place to the right, then output the resulting string. For example:

. →  .

 . →   .

  . →    .

   . →     .

    . →      .

     . →       .

      . →        .

       . →         .

In the wave case, append either / or \ appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:

/ → /\

\ → \/

/\ → /\/

\/ → \/\

/\/ → /\/\

\/\ → \/\/

/\/\ → /\/\/

\/\/ → \/\/\

In either case, the output may not have trailing spaces but an optional trailing newline is allowed.

The shortest code in bytes wins.

Body:
SED, 41 36 27

saved 7 thanks to charlie

 s|\.| .|;s|/$|/\\|;t;s|$|/|

uses 3 substitutions:

s/\./ ./ adds a space if there is a .

s|/$|/\\|,s|$|/| adds the appropriate slash to the end

uses | instead of / as the delimiter

t branches to the end if the second regex matches so it doesn't add the other slash


答:
R, 141 bytes

```<code> f=Vectorize(function(n)ifelse(n>3,{c=3;a=f(n-1);b=f(n-2);d=f(4:n-3);while(!c%%which(!a%%1:a)[-1]||!c%%which(!b%%1:b)[-1]||c%in%d)c=c+1;c},n))
</code>```

ungolfed

```<code>f=Vectorize( function(n)     #build a recursive function. Vectorize allows
    if(n>3) {                #the function to be called on vectors.
        c=3                  #Tests size. Builds some frequent variables.
        a=f(n-1)
        b=f(n-2)
        d=f(4:n-3)           #Should really golf this out, but its horribly slow.
        while(!c%%which(!a%%1:a)[-1]||!c%%which(!b%%1:b)[-1]||c%in%d)
              c=c+1          #If we are coprime and not already seen. add.
        c
     } else n)               #First three are 1,2,3.
</code>```

Title: Smallest positive integer which is coprime to the last two predecessors and has not yet appeared; a(1)=1, a(2)=2

Body:
Definition

Two integers are coprime if they share no positive common divisors other than 1.

a(1) = 1

a(2) = 2

a(n) is the smallest positive integer which is coprime to the a(n-1) and a(n-2) and has not yet appeared, for integer n >= 3.

Task

Given positive integer n, output/print a(n).

Example

a(11) = 6 because 6 is coprime with the last two predecessors (namely, 11 and 13) and 6 has not appeared before.

Notes

Note that the sequence is not ascending, meaning that an element can be smaller than its predecessor.

Specs

You must use 1-indexed.

Testcases

```<code>n      a(n)
1      1
2      2
3      3
4      5
5      4
6      7
7      9
8      8
9      11
10     13
11     6
12     17
13     19
14     10
15     21
16     23
17     16
18     15
19     29
20     14
100    139
1000   1355
10000  13387
100000 133361
</code>```

Scoring

Since coprime means that the two numbers share only one divisor (1), and 1 is a small number, your code should be as small as possible in terms of byte-count.

References

OEIS A084937

Body:
R, 141 bytes

 f=Vectorize(function(n)ifelse(n>3,{c=3;a=f(n-1);b=f(n-2);d=f(4:n-3);while(!c%%which(!a%%1:a)[-1]||!c%%which(!b%%1:b)[-1]||c%in%d)c=c+1;c},n))

ungolfed

f=Vectorize( function(n)     #build a recursive function. Vectorize allows
    if(n>3) {                #the function to be called on vectors.
        c=3                  #Tests size. Builds some frequent variables.
        a=f(n-1)
        b=f(n-2)
        d=f(4:n-3)           #Should really golf this out, but its horribly slow.
        while(!c%%which(!a%%1:a)[-1]||!c%%which(!b%%1:b)[-1]||c%in%d)
              c=c+1          #If we are coprime and not already seen. add.
        c
     } else n)               #First three are 1,2,3.


问:
Pretty Smooth Moves
In arithmetic, an n-smooth number, where n is a given prime number, is mathematically defined as a positive integer that has no prime factors greater than n. For example, 42 is 7-smooth because all its prime factors are less than or equal to 7, but 44 is not 7-smooth because it also has 11 as a prime factor.

Define a pretty smooth number as a number with no prime factors greater than its own square root. Thus, the list of pretty smooth numbers can be formulated as follows:

(EDITED!) 1 is a pretty smooth number, due to its complete lack of any prime factors. (Note that in the original version of this question, 1 was erroneously excluded from the list, so if you exclude it from your outputs you won't be marked wrong.)

Between 4 (= 22) and 8, the pretty smooth numbers are 2-smooth, meaning they have 2 as their only prime factor.

Between 9 (= 32) and 24, the pretty smooth numbers are 3-smooth, and can have 2s and 3s in their prime factorizations.

Between 25 (= 52) and 48, the pretty smooth numbers are 5-smooth, and can have 2s, 3s, and 5s in their prime factorizations.

And so on, upgrading the criteria every time the square of the next prime number is reached.

The list of pretty smooth numbers is fixed, and begins as follows: 1, 4, 8, 9, 12, 16, 18, 24, 25, ...

Your challenge is to write code that will output all pretty smooth numbers up to and including 10,000 (= 1002). There must be at least one separator (it doesn't matter what kind -- space, comma, newline, anything) between each number in the list and the next, but it is completely irrelevant what character is used.

As per usual, lowest byte count wins -- obviously, simply outputting the list isn't going to be too beneficial to you here. Good luck!

答:
Pyth, 12 bytes

```<code>g#^ePT2tS^T4
</code>```

Does not include 1.

Title: Pretty Smooth Moves

Body:
Pyth, 12 bytes

g#^ePT2tS^T4

Does not include 1.


答:
Python 2, 143 139 bytes

```<code>I=1
a={2}
def f(s):
 for d in'123456789':u=d[I:]+s+d*I;z=int(u);z+=z<3;z%91>0<2==pow(2,z,z)>a.add(z)<f(u)
f('')
lambda n:sorted(a)[~-n]
I=0
</code>```

Consists of five parts:

I=1

A newline

a={2}…[~-n]

A newline

I=0

So reversal is just flipping the value of I.

Explanation

The function f performs a recursive search for either left-truncatable primes (LTPs) or right-truncatable primes (RTPs), depending on the value of the global I. These values get added to the set a. Then, lambda n:sorted(a)[~-n] returns the n-th one.

Let’s define a leaf as either an LTP, an RTP, some non-zero digit + an LTP, or an RTP + some non-zero digit. These are all the values that f could ever want to check for primality.

I designed a Fermat pseudoprime test that works for all leaves:

(63973 is a Carmichael number.)

If this test returns true, then z should be added to the set a and we should recurse on str(z). The responsible bit of code is:

```<code>z+=z<3;z%91>0<2==pow(2,z,z)>a.add(z)<f(u)
</code>```

First, we wish to deal with the case z == 2. We do so by simply dodging it here and hard-coding 2 when we initially define a! (EDIT: And nothing harmful happens if we also catch z == 1.) So we can assume that z ≥ 3 now.

I’ve translated some “and”s into a short-circuiting chained comparison: the first three comparisons have to succeed before a.add(z) and f(u) are ever evaluated. Here are all their roles:

z%91>0 encodes our first condition. (63973 is divisible by 91, which is not a leaf itself, so that’s how we recognize it.)

0<2 is always true, but chaining is shorter than and.

2==pow(2,z,z) encodes our second condition.

pow(2,z,z)>a.add(z) triggers the addition, and is always true, since set.add returns None, and integers are always greater than None.

a.add(z)<f(u) triggers the recursion. Its truth value is unimportant.

Acknowledgements

Dennis saved four bytes (u=[d+s,s+d][I] → u=d[I:]+s+d*I; z==2 → z<3 and the mod 91 trick). Thanks!

Title: Right and tfeL truncatable primes

Body:
A right-truncatable prime is a prime where every prefix is a prime (in base 10).  A left-truncatable prime is exactly the opposite, where every postfix is a prime (primes that start with 0 aren't allowed).  Both of these sequences are finite (There are only 83 Right-truncatables, while there are 4260 Left-truncatables).

You need to write a program that accepts a single number as input, and produces the nth right-truncatable prime.  However, when the program is read arranged backwards, it should produce the nth left-truncatable prime.

To arrange a program backwards, we split the program into words, then reverse the order of the words.  A word can consist of any number of characters.

For example, if the following was your program:

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

The following would all be allowed as possible backwards arrangements:

Splitting on each character:

```<code>0987654321
dlrow olleh
</code>```

Splitting on whitespace:

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

Splitting arbitrarily (pipes added for clarity):

```<code>hel|lo w|orld
1|23456|7|8|90

908723456orld
1lo whel
</code>```

When arranging your program backwards, all whitespace must be considered and reversed, just like any other character.

Forward test inputs:

```<code>1:  2
2:  3
21: 379
60: 239933
83: 73939133
</code>```

Backward test inputs:

```<code>1:    2
2:    3
39:   647
187:  29173
4260: 357686312646216567629137
</code>```

Programs should be able to run in a reasonable amount of time (less than a minute)

This is a code-golf, so the program with the fewest bytes wins!

Body:
Python 2, 143 139 bytes

I=1
a={2}
def f(s):
 for d in'123456789':u=d[I:]+s+d*I;z=int(u);z+=z<3;z%91>0<2==pow(2,z,z)>a.add(z)<f(u)
f('')
lambda n:sorted(a)[~-n]
I=0

Consists of five parts:

I=1

A newline

a={2}…[~-n]

A newline

I=0

So reversal is just flipping the value of I.

Explanation

The function f performs a recursive search for either left-truncatable primes (LTPs) or right-truncatable primes (RTPs), depending on the value of the global I. These values get added to the set a. Then, lambda n:sorted(a)[~-n] returns the n-th one.

Let’s define a leaf as either an LTP, an RTP, some non-zero digit + an LTP, or an RTP + some non-zero digit. These are all the values that f could ever want to check for primality.

I designed a Fermat pseudoprime test that works for all leaves:

(63973 is a Carmichael number.)

If this test returns true, then z should be added to the set a and we should recurse on str(z). The responsible bit of code is:

z+=z<3;z%91>0<2==pow(2,z,z)>a.add(z)<f(u)

First, we wish to deal with the case z == 2. We do so by simply dodging it here and hard-coding 2 when we initially define a! (EDIT: And nothing harmful happens if we also catch z == 1.) So we can assume that z ≥ 3 now.

I’ve translated some “and”s into a short-circuiting chained comparison: the first three comparisons have to succeed before a.add(z) and f(u) are ever evaluated. Here are all their roles:

z%91>0 encodes our first condition. (63973 is divisible by 91, which is not a leaf itself, so that’s how we recognize it.)

0<2 is always true, but chaining is shorter than and.

2==pow(2,z,z) encodes our second condition.

pow(2,z,z)>a.add(z) triggers the addition, and is always true, since set.add returns None, and integers are always greater than None.

a.add(z)<f(u) triggers the recursion. Its truth value is unimportant.

Acknowledgements

Dennis saved four bytes (u=[d+s,s+d][I] → u=d[I:]+s+d*I; z==2 → z<3 and the mod 91 trick). Thanks!


问:
Write a program that uses all printable non-alphanumeric ASCII symbols
In particular, use each of these symbols at least once in your source code:

```<code>! " # $ % & ' () * + , - .  / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
</code>```

Symbols inside comments, string literals, regexps (or any other kinds of literals etc.) don't count (but their delimiters such as /**/ or "" do count).

The program should not perform any action. It just has to compile and do nothing when run.

If for some reason some of the symbols cannot be used in the language of your choice, explain that rigorously (what and why must be excluded).

Update: A few answers used symbols withing regular expressions. I'd consider this a bit problematic, it's the same thing as putting them into string literals or comments (that's why I put etc. in that requirement). Please try without this. I also updated the requirement above.

Update: Shortest code wins (tagged as code-golf). As suggested, we'll most likely need some tie-breaker criteria. I suggest that if there is a tie, the winning one is the one in which the ASCII symbols appear as much ordered as possible. Formally: Filter out the first occurrence of each of the listed symbols from a program. This will result in a permutation on the listed symbols. The program with less inversion number of its permutation wins.

Update: I'd be happy to see some/more solutions in regular/mainstream languages, such as C(++), Java, Scala, Haskell, etc.

答:
Scheme, 41 characters

```<code>(define !$%&*+,-./:<=>?@[\]^_`{|}~ "#'");
</code>```

This takes advantage of Scheme's incredible tolerance for characters in variable names. In this program I create a variable with the name !$%&*+,-./:<=>?@[]^_`{|}~ which Scheme happily accepts.

Body:
Scheme, 41 characters

(define !$%&*+,-./:<=>?@[\]^_`{|}~ "#'");

This takes advantage of Scheme's incredible tolerance for characters in variable names. In this program I create a variable with the name !$%&*+,-./:<=>?@[]^_`{|}~ which Scheme happily accepts.


问:
Quick Golf: The Gold Leader

Challenge

Using data from the API here, output the names of the three countries with the most Olympic gold medals at the 2016 Rio Olympic Games (i.e. the first element of the returned list).

For example, at the time of posting (18:23 UTC+1, Monday, 15th August), the USA, the UK and China have the most gold medals, so the output would be:

```<code>United States
Great Britain
China
</code>```

The country names must be separated by newlines and you may have a leading or trailing newlines.

Once the Olympics have finished, the program does not have to work as expected.

URL shorteners are disallowed but JSON parsing libraries are allowed.

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

I'm going to keep trying to get an Olympics themed challenge in here

Leaderboard

var QUESTION_ID=89919,OVERRIDE_USER=30525;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
R, 98, 112, 108 bytes

golfed 4 thanks to @miff

```<code>a=jsonlite::fromJSON(readLines("http://www.medalbot.com/api/v1/medals"))
cat(a$c[order(-a$g)[1:3]],sep="\n")
</code>```

First line imports data using a JSON library. Second line grabs the relevant country names. It sorts the countries by gold medals in increasing order, reverses the indices, and takes the first 3, printing them.

Title: Quick Golf: The Gold Leader

Body:
R, 98, 112, 108 bytes

golfed 4 thanks to @miff

a=jsonlite::fromJSON(readLines("http://www.medalbot.com/api/v1/medals"))
cat(a$c[order(-a$g)[1:3]],sep="\n")

First line imports data using a JSON library. Second line grabs the relevant country names. It sorts the countries by gold medals in increasing order, reverses the indices, and takes the first 3, printing them.


答:
JavaScript + jQuery, <s>114</s> 100 bytes

$.get("www.medalbot.com/api/v1/medals",a=>alert(a[0][c='country_name']+'\n'+a[1][c]+'\n'+a[2][c]))
```

For the reason of Cross Origin Requests, this must be run from the medalbot.com domain (with jQuery).

History

-14 bytes thanks to @YetiCGN

-2 bytes thanks to Yay295

Title: Quick Golf: The Gold Leader

Body:
Challenge

Using data from the API here, output the names of the three countries with the most Olympic gold medals at the 2016 Rio Olympic Games (i.e. the first element of the returned list).

For example, at the time of posting (18:23 UTC+1, Monday, 15th August), the USA, the UK and China have the most gold medals, so the output would be:

```<code>United States
Great Britain
China
</code>```

The country names must be separated by newlines and you may have a leading or trailing newlines.

Once the Olympics have finished, the program does not have to work as expected.

URL shorteners are disallowed but JSON parsing libraries are allowed.

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

I'm going to keep trying to get an Olympics themed challenge in here

Leaderboard

var QUESTION_ID=89919,OVERRIDE_USER=30525;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
JavaScript + jQuery, <s>114</s> 100 bytes

$.get("www.medalbot.com/api/v1/medals",a=>alert(a[0][c='country_name']+'\n'+a[1][c]+'\n'+a[2][c]))

For the reason of Cross Origin Requests, this must be run from the medalbot.com domain (with jQuery).

History

-14 bytes thanks to @YetiCGN

-2 bytes thanks to Yay295


答:
bash + w3m + jq, 83 59 bytes

```<code>w3m medalbot.com/api/v1/medals|jq -r '.[:3][].country_name'
</code>```

Thanks to Jordan for three bytes.

Thanks to YOU for 24 more bytes! Turns out the data is sorted. Wow. :D

Title: Quick Golf: The Gold Leader

Body:
bash + w3m + jq, 83 59 bytes

w3m medalbot.com/api/v1/medals|jq -r '.[:3][].country_name'

Thanks to Jordan for three bytes.

Thanks to YOU for 24 more bytes! Turns out the data is sorted. Wow. :D


答:
Python 3, <s>202</s>, 164 bytes.

Python 3 does not do short url/json handling. :/

Didn't realize the API already sorts by gold count

```<code>from urllib.request import*
import json
print('\n'.join(x['country_name']for x in json.loads(urlopen('http://www.medalbot.com/api/v1/medals').read().decode())[:3]))
</code>```

Title: Quick Golf: The Gold Leader

Body:
Python 3, <s>202</s>, 164 bytes.

Python 3 does not do short url/json handling. :/

Didn't realize the API already sorts by gold count

from urllib.request import*
import json
print('\n'.join(x['country_name']for x in json.loads(urlopen('http://www.medalbot.com/api/v1/medals').read().decode())[:3]))


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

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

The Rules

Each submission must be a full program.

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

The program must not write anything to STDERR.

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

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

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

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

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

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

For inspiration, check the Hello World Collection.

The Catalogue

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

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

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

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

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

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

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

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

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Caker, 294 bytes

```<code>ωΩθΩθθΩθΩθθθΘΩθθΩθθΩθΩθΩθΘθθΩθΩθθΩθθΘΩθθΩθΩθθΩθθΘΩθθΩθΩθθθθΘθΩθΩθθΩθθΘΩθΩθθθθθΘΩθΩθΩθΩθΩθθθΘθθΩθΩθθθθΘθθθΩθθΩθΩθΘΩθθΩθΩθθΩθθΘΩθθΩθθΩθΩθθΘΩθΩθθθθΩθΘ
</code>```

Explanation:

ω flip the cell at the left of the tape head if the current cell is 0, at the right otherwise

Ω move the tape head leftward if the current cell is 0, rightward otherwise

θ push the current bit on the print stack

Θ print the character in the print stack and clear the print stack

ContentLicense: CC BY-SA 4.0

Title: "Hello, World!"

Body:
Caker, 294 bytes

ωΩθΩθθΩθΩθθθΘΩθθΩθθΩθΩθΩθΘθθΩθΩθθΩθθΘΩθθΩθΩθθΩθθΘΩθθΩθΩθθθθΘθΩθΩθθΩθθΘΩθΩθθθθθΘΩθΩθΩθΩθΩθθθΘθθΩθΩθθθθΘθθθΩθθΩθΩθΘΩθθΩθΩθθΩθθΘΩθθΩθθΩθΩθθΘΩθΩθθθθΩθΘ

Explanation:

ω flip the cell at the left of the tape head if the current cell is 0, at the right otherwise

Ω move the tape head leftward if the current cell is 0, rightward otherwise

θ push the current bit on the print stack

Θ print the character in the print stack and clear the print stack


答:
PHP, <s>205 139 124 116 111</s> 109 bytes

I just wanted to use the new spaceship operator for PHP 7 once (EDIT: It's superfluous, as sorting isn't required):

```<code><?$d=json_decode(file_get_contents('http://www.medalbot.com/api/v1/medals'),1);usort($d,function($a,$b){$g='gold_count';return$b[$g]<=>$a[$g];});$c='country_name';foreach([0,1,2]as$i){echo$d[$i][$c]."\n";}
</code>```

If we omit the unneccesary sorting step and assume the API delivers the data already sorted by gold_count descending (as it would seem), we can shorten this further:

```<code>while($i<3)echo json_decode(file_get_contents('http://medalbot.com/api/v1/medals'))[+$i++]->country_name."
";
</code>```

Note: The line break within the string is intentional to save a byte from \n

History

Ommitted some quotes and braces that will throw notice's, removed the $c variable for country_name index. Thanks to @manatwork for these tipps to save even more characters.

Thanks to @jeroen for pointing out the shorter while loop, also switched to object access to go from 124 to 116

Saved 5 more bytes by calling the API within the loop. Granted, it takes longer and clobbers the API, but it's Code Golf. Needs PHP 5.5 to work because of array dereferencing.

Saved 2 more bytes by removing the short open tag, as per this meta answer

Title: Quick Golf: The Gold Leader

Body:
PHP, <s>205 139 124 116 111</s> 109 bytes

I just wanted to use the new spaceship operator for PHP 7 once (EDIT: It's superfluous, as sorting isn't required):

<?$d=json_decode(file_get_contents('http://www.medalbot.com/api/v1/medals'),1);usort($d,function($a,$b){$g='gold_count';return$b[$g]<=>$a[$g];});$c='country_name';foreach([0,1,2]as$i){echo$d[$i][$c]."\n";}

If we omit the unneccesary sorting step and assume the API delivers the data already sorted by gold_count descending (as it would seem), we can shorten this further:

while($i<3)echo json_decode(file_get_contents('http://medalbot.com/api/v1/medals'))[+$i++]->country_name."
";

Note: The line break within the string is intentional to save a byte from \n

History

Ommitted some quotes and braces that will throw notice's, removed the $c variable for country_name index. Thanks to @manatwork for these tipps to save even more characters.

Thanks to @jeroen for pointing out the shorter while loop, also switched to object access to go from 124 to 116

Saved 5 more bytes by calling the API within the loop. Granted, it takes longer and clobbers the API, but it's Code Golf. Needs PHP 5.5 to work because of array dereferencing.

Saved 2 more bytes by removing the short open tag, as per this meta answer


答:
MATL, 67 bytes

```<code>'http://www.medalbot.com/api/v1/medals'Xi'(?<="c.+e": ")[^"]+'XX3:)
</code>```

This doesn't work online because function Xi (urlread) is disallowed.

Example run:

```<code>>> matl
 > 'http://www.medalbot.com/api/v1/medals'Xi'(?<="c.+e": ")[^"]+'XX3:)
 >
United States
Great Britain
China
</code>```

Explanation

This reads the contents as a string and then applies the regex '(?<="c.+e": ")[^"]+' to extract country names. The regex uses look-behind with "c.+e" instead of "country_name" to reduce code length.

```<code>'http://www.medalbot.com/api/v1/medals'   % Push string representing the URL
Xi                                        % Read URL contents as a string
'(?<="c.+e": ")[^"]+'                     % String for regex matching
XX                                        % Apply regex
3:)                                       % Get first 3 results
</code>```

Title: Quick Golf: The Gold Leader

Body:
MATL, 67 bytes

'http://www.medalbot.com/api/v1/medals'Xi'(?<="c.+e": ")[^"]+'XX3:)

This doesn't work online because function Xi (urlread) is disallowed.

Example run:

>> matl
 > 'http://www.medalbot.com/api/v1/medals'Xi'(?<="c.+e": ")[^"]+'XX3:)
 >
United States
Great Britain
China

Explanation

This reads the contents as a string and then applies the regex '(?<="c.+e": ")[^"]+' to extract country names. The regex uses look-behind with "c.+e" instead of "country_name" to reduce code length.

'http://www.medalbot.com/api/v1/medals'   % Push string representing the URL
Xi                                        % Read URL contents as a string
'(?<="c.+e": ")[^"]+'                     % String for regex matching
XX                                        % Apply regex
3:)                                       % Get first 3 results


答:
JavaScript (ES6), 53 bytes

```<code>f=s=>s[1]?f(s.replace(/0\?.:|1\?(.):.(?!\?)/,"$1")):s
</code>```

Returns 0 or 1 for valid input; hangs for invalid input. Explanation: because reversing a string is awkward in JavaScript, my first 71-byte attempt worked by using a negative lookahead for a ? which would otherwise disturb the associativity:

```<code>f=s=>s[1]?f(s.replace(/(.)\?(.):(.)(?!\?)/,(_,a,b,c)=>+a?b:c)):s
</code>```

Since this was somewhat long I wondered whether I could improve matters by incorporating the decision making into the regexp. As it turned out, it wasn't an immediate success, as it also took 71 bytes:

```<code>f=s=>s[1]?f(s.replace(/0\?.:(.)(?!\?)|1\?(.):.(?!\?)/,"$1$2")):s
</code>```

Then it occurred to me that 0?0: and 0?1: are always no-ops, without concern for associativity. This saved me almost 25%.

Title: Evaluate an expression of ternary operators

Body:
Consider a grammar over the alphabet {0, 1, ?, :} defined by the production rule

s → 0 ┃ 1 ┃ 0 ? s : s ┃ 1 ? s : s

Given a string generated from s, parse it as an expression where ?: is right-associative (for example, a?B?X:Y:c?d:e?f:g means a?(B?X:Y):(c?d:(e?f:g))) and evaluate it with the following semantics:

```<code>eval(0) = 0
eval(1) = 1
eval(0?a:b) = eval(b)
eval(1?a:b) = eval(a)
</code>```

If the result is 0, output some fixed value; if the output is 1, output a different fixed value. Specify your chosen output values (e.g. 0/1, or False/True) in your answer.

Test cases

```<code>0 -> 0
1 -> 1
0?0:1 -> 1
0?1:0 -> 0
1?0:1 -> 0
1?1:0 -> 1
0?1?0:1:1 -> 1
1?0?1:1:1 -> 1
1?0:1?0:1?1:1 -> 0
1?1?1:0?1?0:0:0:0 -> 1
1?0:1?0?1:1?1:0:1?1?1:1:1?0:1 -> 0
1?1?1:0?0?1:1:0?1:0:1?1?0?0:0:1?1:0:0?1?0:1:1?0:1 -> 1
0?0?1?0?0:1:0?0:0:0?0?1:1:1?0:1:0?0?0?1:0:0?1:1:1?1?0:1:1 -> 0
</code>```

Rules

You may not use language built-ins that interpret strings as code in some programming language and run it (such as JavaScript/Perl/Ruby/Python’s eval).

That said, your code doesn’t actually have to parse and then evaluate the input string. You can take any approach the achieves equivalent results and doesn’t violate the previous rule.

Your program will be checked against perl -le 'print eval<>'.

The shortest code (in bytes) wins.

Body:
JavaScript (ES6), 53 bytes

f=s=>s[1]?f(s.replace(/0\?.:|1\?(.):.(?!\?)/,"$1")):s

Returns 0 or 1 for valid input; hangs for invalid input. Explanation: because reversing a string is awkward in JavaScript, my first 71-byte attempt worked by using a negative lookahead for a ? which would otherwise disturb the associativity:

f=s=>s[1]?f(s.replace(/(.)\?(.):(.)(?!\?)/,(_,a,b,c)=>+a?b:c)):s

Since this was somewhat long I wondered whether I could improve matters by incorporating the decision making into the regexp. As it turned out, it wasn't an immediate success, as it also took 71 bytes:

f=s=>s[1]?f(s.replace(/0\?.:(.)(?!\?)|1\?(.):.(?!\?)/,"$1$2")):s

Then it occurred to me that 0?0: and 0?1: are always no-ops, without concern for associativity. This saved me almost 25%.


Title: Match up to 10 in an array

Body:
Challenge

Given an array of single digit number, work out if any 2 of them add up to 10 and print them out

Example

Input

(1,2,3,4,5,5,6,7)

This returns ((4,6),(5,5),(3,7))

Input

(1,2,3,4,5)

This returns (). as there is only one 5

Input

(5,5,5,5,5)

This returns ((5,5),(5,5)) as there is odd number of 5s and each 5 can be used only once

Rules

Here are the rules!

Assume input will only be an unsorted array of positive single digit integers

Each number will be pair up only once, which means if there are three 5s it only form 1 pair (5,5). If there are (3,3,7) it will only form 1 pair (3,7)

For the input: You can use any type of parentheses(or lack of) as long as readers can tell that the input is a single array of numbers.

For the output: It must look like an array of pairs. Where the array is the same form as your input.(If you did not use any parenheses in your input, you have to use some kind of symbols so that any readers can tell they are pairs in an array)

Test Cases

```<code>(1,2,3,4,5,5,6,7) =((4,6),(5,5),(3,7))
(1,2,3,4,5) = ()
(5,5,5,5,5) = ((5,5),(5,5))
(1,2,3,3,4,5,6,7)=((3,7),(4,6))
(9,8,7,6,4,4,3,1)=((9,1),(7,3),(6,4))
</code>```

Good luck!

The shorter an answer is, the better!

Edit 1: update the rules and Testcases from comments

Edit 2: update rules to define format of input.

Edit 3: update rules to define format of output. trying to be as accommodating as possible.

Body:
PHP 150 149 148 146 142 --> 140

Use with PHP CLI.

<?$a=fgetcsv(STDIN);for($i=0;$i<$c=count($a);$i++){for($j=$i+1;$j<$c;$j++)if($a[$i]+$a[$j]==10){echo"({$a[$i]},{$a[$j]})";$a[$i]=$a[$j]=0;}}

Input: 1,2,3,4,5,5,6,7

Output: (3,7)(4,6)(5,5)

Un-golfed:

<?php

$a = fgetcsv(STDIN);
$c = count($a);
for ($i = 0; $i < $c; $i++) {
    for ($j = ($i + 1); $j < $c; $j++) {
        if ($a[$i] + $a[$j] == 10) {
            echo "({$a[$i]},{$a[$j]})";
            $a[$i] = 0;
            $a[$j] = 0;
        }
    }
}

?>


答:
JavaScript (ES6), 122 Bytes

```<code>fetch`http://www.medalbot.com/api/v1/medals`.then(a=>a.json()).then(b=>alert(b.slice(0,3).map(c=>c.country_name).join`\n`))
</code>```

Due to a browser safety issue, this code must be run on medalbot.com. It does not however take advantage of that and could potentially be run elsewhere. Also note that I inserted the \n character, but am only counting is as one, because I could replace it with one

Node.js (ES6), 173 Bytes

```<code>require("http").get("http://www.medalbot.com/api/v1/medals",s=>s.on("data",d=>t+=d,t="").on("end",q=>console.log(JSON.parse(t).slice(0,3).map(a=>a.country_name).join`\n`)))
</code>```

This would have been so much shorter if the API returned the data all in one stretch, but since it returns in two sections, I must concatenate the parts and combine them, and then parse them.

Node.js (ES6) + Request, 138 Bytes

```<code>require("request")("http://www.medalbot.com/api/v1/medals",(e,r,b)=>console.log(JSON.parse(b).slice(0,3).map(a=>a.country_name).join`\n`))
</code>```

Better, but still not as good as the browser version. Thanks fetch API! Request is a popular HTTP client library used to simplify requests, and you can see that take effect here.

Title: Quick Golf: The Gold Leader

Body:
JavaScript (ES6), 122 Bytes

fetch`http://www.medalbot.com/api/v1/medals`.then(a=>a.json()).then(b=>alert(b.slice(0,3).map(c=>c.country_name).join`\n`))

Due to a browser safety issue, this code must be run on medalbot.com. It does not however take advantage of that and could potentially be run elsewhere. Also note that I inserted the \n character, but am only counting is as one, because I could replace it with one

Node.js (ES6), 173 Bytes

require("http").get("http://www.medalbot.com/api/v1/medals",s=>s.on("data",d=>t+=d,t="").on("end",q=>console.log(JSON.parse(t).slice(0,3).map(a=>a.country_name).join`\n`)))

This would have been so much shorter if the API returned the data all in one stretch, but since it returns in two sections, I must concatenate the parts and combine them, and then parse them.

Node.js (ES6) + Request, 138 Bytes

require("request")("http://www.medalbot.com/api/v1/medals",(e,r,b)=>console.log(JSON.parse(b).slice(0,3).map(a=>a.country_name).join`\n`))

Better, but still not as good as the browser version. Thanks fetch API! Request is a popular HTTP client library used to simplify requests, and you can see that take effect here.


答:
PowerShell v4+, <s>88</s> 69 bytes

```<code>(ConvertFrom-Json(iwr medalbot.com/api/v1/medals))[0..2].country_name
</code>```

Uses iwr (the alias for Invoke-WebRequest) to grab the API.  We feed that as the input parameter to the ConvertFrom-Json built-in that pulls the JSON text into a custom object array. We encapsulate that object array in parens, take the first three elements [0..2], and take the .country_name of each thereof.

Requires at least v4+ for the multiple-object-properties, else we'd need to use something like |Select "country_name" instead. Requires at least v3+ for the ConvertFrom-Json built-in.

```<code>PS C:\Tools\Scripts\golfing> .\olympics-gold-leader.ps1
United States
Great Britain
China
</code>```

Title: Quick Golf: The Gold Leader

Body:
PowerShell v4+, <s>88</s> 69 bytes

(ConvertFrom-Json(iwr medalbot.com/api/v1/medals))[0..2].country_name

Uses iwr (the alias for Invoke-WebRequest) to grab the API.  We feed that as the input parameter to the ConvertFrom-Json built-in that pulls the JSON text into a custom object array. We encapsulate that object array in parens, take the first three elements [0..2], and take the .country_name of each thereof.

Requires at least v4+ for the multiple-object-properties, else we'd need to use something like |Select "country_name" instead. Requires at least v3+ for the ConvertFrom-Json built-in.

PS C:\Tools\Scripts\golfing> .\olympics-gold-leader.ps1
United States
Great Britain
China


答:
BASH + w3m + core utils, 70 bytes

```<code>w3m www.medalbot.com/api/v1/medals|grep -m3 tr|cut -f6- -d\ |tr -d \",
</code>```

Looks like the output comes sorted already. Just need to throw out all of the extra text.

Title: Quick Golf: The Gold Leader

Body:
BASH + w3m + core utils, 70 bytes

w3m www.medalbot.com/api/v1/medals|grep -m3 tr|cut -f6- -d\ |tr -d \",

Looks like the output comes sorted already. Just need to throw out all of the extra text.


答:
bash + w3m + grep + cut, <s>65</s> <s>59</s> <s>58</s> 54 bytes

```<code>w3m medalbot.com/api/v1/medals|grep -m3 m|cut -d\" -f4
</code>```

6 bytes less thanks to @Joe's suggestions.

1 byte less thanks to @YOU.

4 bytes less thanks to @manatwork's suggestion that the medalbot API seems to work without www. subdomain too.

Title: Quick Golf: The Gold Leader

Body:
bash + w3m + grep + cut, <s>65</s> <s>59</s> <s>58</s> 54 bytes

w3m medalbot.com/api/v1/medals|grep -m3 m|cut -d\" -f4

6 bytes less thanks to @Joe's suggestions.

1 byte less thanks to @YOU.

4 bytes less thanks to @manatwork's suggestion that the medalbot API seems to work without www. subdomain too.


问:
Random Golf of the Day #7: A distinctly random character

About the Series

This is a guest entry for the Random Golf of the Day series.

First off, you may treat this like any other code golf challenge, and answer it without worrying about the series at all. However, there is a leaderboard across all challenges. You can find the leaderboard along with some more information about the series in the first post.

Input

No input is taken.

Output

A single letter of the alphabet (case irrelevant), with an optional trailing newline. Each letter must have non-zero probability of being chosen, and all 26 probabilities must be distinct. To remove all ambiguity: Distinct means that there must not be two probabilities that are equal to each other.

Scoring

This is code golf. Shortest code in bytes wins.

A valid entry is a full program or function that has zero probability of not terminating.

Alphabet

To avoid confusion, the particular alphabet to be used is the Latin alphabet:

Either

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
</code>```

or

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

You may choose to output upper case or lower case. Alternatively, you may choose to output different cases on different runs if that helps. The probability for a given letter is the probability of that letter appearing in either case (upper or lower).

Explanation

As it won't be at all obvious from the output, please include a clear explanation of how you achieved the 26 distinct probabilities.

Leaderboard

(from here)

var QUESTION_ID=89621,OVERRIDE_USER=20283;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```
</div>
</div>
</p>

<p><strong>The first post of the series also generates an overall leaderboard.</strong></p>

<p>To make sure that your answers show up, please start every answer with a headline, using the following Markdown template:</p>

```## Language Name, N bytes
```

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

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

(The language is not currently shown, but the snippet does require and parse it, and I may add a by-language leaderboard in the future.)

答:
LaTeX, <s>122</s> 115 bytes

-7 bytes by replacing pgfmathparse{Hex(...)} with pgfmathHex{...}.

Or, if I'm allowed to skip the document class definition & setup, and just count the package import and functional code: 65 bytes.

pgfmathHex parses the expression and its (hexadecimal) result is then fed into \char which turns the code point into a unicode character. The expression itself is identical to many other answers here.

```<code>\documentclass{book}\usepackage{tikz}\begin{document}\pgfmathHex{65+sqrt(rnd)*26}\char"\pgfmathresult\char"\pgfmathresult\end{document}
</code>```

Ungolfed (with cherry-picked for loop for page-filling output):

```<code>\documentclass{book}
\usepackage{tikz}
\begin{document}
\noindent
\foreach \n in {0,...,1513}
{
\pgfmathHex{65+sqrt(rnd)*26}\char"\pgfmathresult
}
\end{document}
</code>```

Output (w/ free page number :) ):

Body:
LaTeX, <s>122</s> 115 bytes

-7 bytes by replacing pgfmathparse{Hex(...)} with pgfmathHex{...}.

Or, if I'm allowed to skip the document class definition & setup, and just count the package import and functional code: 65 bytes.

pgfmathHex parses the expression and its (hexadecimal) result is then fed into \char which turns the code point into a unicode character. The expression itself is identical to many other answers here.

\documentclass{book}\usepackage{tikz}\begin{document}\pgfmathHex{65+sqrt(rnd)*26}\char"\pgfmathresult\char"\pgfmathresult\end{document}

Ungolfed (with cherry-picked for loop for page-filling output):

\documentclass{book}
\usepackage{tikz}
\begin{document}
\noindent
\foreach \n in {0,...,1513}
{
\pgfmathHex{65+sqrt(rnd)*26}\char"\pgfmathresult
}
\end{document}

Output (w/ free page number :) ):


答:
C (+sockets), <s>433</s> <s>429</s> <s>280</s> <s>276</s> <s>270</s> 259 bytes

#define H"medalbot.com"
char**p,B[999],*b=B;main(f){connect(f=socket(2,1,getaddrinfo("www."H,"80",0,&p)),p[4],16);send(f,"GET http://"H"/api/v1/medals HTTP/1.1\r\nHost:"H"\r\n\r\n",69);read(f,b,998);for(f=3;f--;puts(p))b=strchr(p=strstr(++b,"_n")+9,34),*b=0;}
```

<p>So it turns out that C isn't great at downloading resources from the internet and parsing them as JSON. Who knew?</p>

<p>This code is (naturally) super lax with error checking, so I guess if medalbot.com wanted to send malicious data they'd be able to trigger buffer overflows, etc. Also the latest code expects certain values for the constants (e.g. <code>AF_INET = 2</code>) which will <em>probably</em> be the case everywhere, but it's not guaranteed.</p>

<p>Here's the original code which isn't so fragile (but still isn't very robust or safe):</p>

<pre class="lang-c prettyprint-override"><code>#include<netdb.h>
#define H"medalbot.com"
char*b,*B,d[999];struct addrinfo*p,h;main(f){h.ai_socktype=SOCK_STREAM;getaddrinfo("www."H,"80",&h,&p);f=socket(p->ai_family,p->ai_socktype,p->ai_protocol);connect(f,p->ai_addr,p->ai_addrlen);send(f,"GET http://"H"/api/v1/medals HTTP/1.1\r\nHost: "H":80\r\nConnection: close\r\n\r\n",92,0);recv(f,d,998,0);for(f=0,b=d;f<3;++f)B=strstr(b,"_n")+9,b=strchr(B,'}'),*strchr(B,'"')=0,puts(B);}
</code>```

Breakdown:

                            // No imports needed whatsoever!
#define H"medalbot.com"     // Re-use the host in multiple places
char**p,                    // This is actually a "struct addrinfo*"
    B[999],                 // The download buffer (global to init with 0)
    *b=B;                   // A mutable pointer to the buffer

main(f){
    // Hope for the best: try the first suggested address with no fallback:
    // (medalbot.com runs on Heroku which has dynamic IPs, so we must look up the
    // IP each time using getaddrinfo)
    f=socket(2,1,getaddrinfo("www."H,"80",0,&p));
                            // 2 = AF_INET
                            // 1 = SOCK_STREAM
                            //     (may not match getaddrinfo, but works anyway)
                            // 0 = IP protocol (getaddrinfo returns 0 on success)
    connect(f,p[4],16);     // struct addrinfo contains a "struct sockaddr" pointer
                            // which is aligned at 32 bytes (4*8)

    // Send the HTTP request (not quite standard, but works. 69 bytes long)
    send(f,"GET http://"H"/api/v1/medals HTTP/1.1\r\nHost:"H"\r\n\r\n",69);
    // (omit flags arg in send and hope 0 will be assumed)

    read(f,b,998);          // Get first 998 bytes of response; same as recv(...,0)

    // Loop through the top 3 & print country names:
    // (p is re-used as a char* now)
    for(f=3;f--;puts(p))        // Loop and print:
        p=strstr(++b,"_n")+9,   //  Find "country_name": "
        b=strchr(p,34),         //  Jump to closing "
        *b=0;                   //  Set the closing " to \0
}
```

This isn't very nice for the server since we don't send Connection: close\r\n as part of the HTTP request. It also omits the Accept header since medalbot.com doesn't seem to be using compression in any case, and misses the space after Host: (again, the server seems to be OK with this). It doesn't seem as though anything else can be removed though.

Once the olympics end, the most likely behaviour for this program is to segfault trying to read memory location 9. Unless an evil hacker takes over the domain, in which case the most likely behaviour is for it to set some byte to 0 in the address info structs, which probably isn't too dangerous actually. But who can tell with these evil hackers?

Title: Quick Golf: The Gold Leader

Body:
C (+sockets), <s>433</s> <s>429</s> <s>280</s> <s>276</s> <s>270</s> 259 bytes

#define H"medalbot.com"
char**p,B[999],*b=B;main(f){connect(f=socket(2,1,getaddrinfo("www."H,"80",0,&p)),p[4],16);send(f,"GET http://"H"/api/v1/medals HTTP/1.1\r\nHost:"H"\r\n\r\n",69);read(f,b,998);for(f=3;f--;puts(p))b=strchr(p=strstr(++b,"_n")+9,34),*b=0;}

So it turns out that C isn't great at downloading resources from the internet and parsing them as JSON. Who knew?

This code is (naturally) super lax with error checking, so I guess if medalbot.com wanted to send malicious data they'd be able to trigger buffer overflows, etc. Also the latest code expects certain values for the constants (e.g. AF_INET = 2) which will probably be the case everywhere, but it's not guaranteed.

Here's the original code which isn't so fragile (but still isn't very robust or safe):

#include<netdb.h>
#define H"medalbot.com"
char*b,*B,d[999];struct addrinfo*p,h;main(f){h.ai_socktype=SOCK_STREAM;getaddrinfo("www."H,"80",&h,&p);f=socket(p->ai_family,p->ai_socktype,p->ai_protocol);connect(f,p->ai_addr,p->ai_addrlen);send(f,"GET http://"H"/api/v1/medals HTTP/1.1\r\nHost: "H":80\r\nConnection: close\r\n\r\n",92,0);recv(f,d,998,0);for(f=0,b=d;f<3;++f)B=strstr(b,"_n")+9,b=strchr(B,'}'),*strchr(B,'"')=0,puts(B);}

Breakdown:

                            // No imports needed whatsoever!
#define H"medalbot.com"     // Re-use the host in multiple places
char**p,                    // This is actually a "struct addrinfo*"
    B[999],                 // The download buffer (global to init with 0)
    *b=B;                   // A mutable pointer to the buffer

main(f){
    // Hope for the best: try the first suggested address with no fallback:
    // (medalbot.com runs on Heroku which has dynamic IPs, so we must look up the
    // IP each time using getaddrinfo)
    f=socket(2,1,getaddrinfo("www."H,"80",0,&p));
                            // 2 = AF_INET
                            // 1 = SOCK_STREAM
                            //     (may not match getaddrinfo, but works anyway)
                            // 0 = IP protocol (getaddrinfo returns 0 on success)
    connect(f,p[4],16);     // struct addrinfo contains a "struct sockaddr" pointer
                            // which is aligned at 32 bytes (4*8)

    // Send the HTTP request (not quite standard, but works. 69 bytes long)
    send(f,"GET http://"H"/api/v1/medals HTTP/1.1\r\nHost:"H"\r\n\r\n",69);
    // (omit flags arg in send and hope 0 will be assumed)

    read(f,b,998);          // Get first 998 bytes of response; same as recv(...,0)

    // Loop through the top 3 & print country names:
    // (p is re-used as a char* now)
    for(f=3;f--;puts(p))        // Loop and print:
        p=strstr(++b,"_n")+9,   //  Find "country_name": "
        b=strchr(p,34),         //  Jump to closing "
        *b=0;                   //  Set the closing " to \0
}

This isn't very nice for the server since we don't send Connection: close\r\n as part of the HTTP request. It also omits the Accept header since medalbot.com doesn't seem to be using compression in any case, and misses the space after Host: (again, the server seems to be OK with this). It doesn't seem as though anything else can be removed though.

Once the olympics end, the most likely behaviour for this program is to segfault trying to read memory location 9. Unless an evil hacker takes over the domain, in which case the most likely behaviour is for it to set some byte to 0 in the address info structs, which probably isn't too dangerous actually. But who can tell with these evil hackers?


答:
Ruby, <s>97</s> 79 + -rnet/http (11) = 90 bytes

Uses a modification of the regex pattern from Luis Mendo's MATL answer, further optimized by @Jordan, since Ruby doesn't support quantifiers in lookbehinds.

-18 bytes from @Jordan.

```<code>puts Net::HTTP.get("www.medalbot.com","/api/v1/medals").scan(/"c.+"(.+)"/)[0,3]
</code>```

Title: Quick Golf: The Gold Leader

Body:
Challenge

Using data from the API here, output the names of the three countries with the most Olympic gold medals at the 2016 Rio Olympic Games (i.e. the first element of the returned list).

For example, at the time of posting (18:23 UTC+1, Monday, 15th August), the USA, the UK and China have the most gold medals, so the output would be:

```<code>United States
Great Britain
China
</code>```

The country names must be separated by newlines and you may have a leading or trailing newlines.

Once the Olympics have finished, the program does not have to work as expected.

URL shorteners are disallowed but JSON parsing libraries are allowed.

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

I'm going to keep trying to get an Olympics themed challenge in here

Leaderboard

var QUESTION_ID=89919,OVERRIDE_USER=30525;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Ruby, <s>97</s> 79 + -rnet/http (11) = 90 bytes

Uses a modification of the regex pattern from Luis Mendo's MATL answer, further optimized by @Jordan, since Ruby doesn't support quantifiers in lookbehinds.

-18 bytes from @Jordan.

puts Net::HTTP.get("www.medalbot.com","/api/v1/medals").scan(/"c.+"(.+)"/)[0,3]


答:
Actually, 11 bytes

```<code>4╤R`;yM²≤`░
</code>```

Try it online!

Does not include 1.

Explanation:

```<code>4╤R`;yM²≤`░
4╤R          range(10**4)
   `;yM²≤`░  filter: take values where
    ;yM²       the square of the largest prime factor
        ≤      is less than or equal to the value
</code>```

Title: Pretty Smooth Moves

Body:
In arithmetic, an n-smooth number, where n is a given prime number, is mathematically defined as a positive integer that has no prime factors greater than n. For example, 42 is 7-smooth because all its prime factors are less than or equal to 7, but 44 is not 7-smooth because it also has 11 as a prime factor.

Define a pretty smooth number as a number with no prime factors greater than its own square root. Thus, the list of pretty smooth numbers can be formulated as follows:

(EDITED!) 1 is a pretty smooth number, due to its complete lack of any prime factors. (Note that in the original version of this question, 1 was erroneously excluded from the list, so if you exclude it from your outputs you won't be marked wrong.)

Between 4 (= 22) and 8, the pretty smooth numbers are 2-smooth, meaning they have 2 as their only prime factor.

Between 9 (= 32) and 24, the pretty smooth numbers are 3-smooth, and can have 2s and 3s in their prime factorizations.

Between 25 (= 52) and 48, the pretty smooth numbers are 5-smooth, and can have 2s, 3s, and 5s in their prime factorizations.

And so on, upgrading the criteria every time the square of the next prime number is reached.

The list of pretty smooth numbers is fixed, and begins as follows: 1, 4, 8, 9, 12, 16, 18, 24, 25, ...

Your challenge is to write code that will output all pretty smooth numbers up to and including 10,000 (= 1002). There must be at least one separator (it doesn't matter what kind -- space, comma, newline, anything) between each number in the list and the next, but it is completely irrelevant what character is used.

As per usual, lowest byte count wins -- obviously, simply outputting the list isn't going to be too beneficial to you here. Good luck!

Body:
Actually, 11 bytes

4╤R`;yM²≤`░

Try it online!

Does not include 1.

Explanation:

4╤R`;yM²≤`░
4╤R          range(10**4)
   `;yM²≤`░  filter: take values where
    ;yM²       the square of the largest prime factor
        ≤      is less than or equal to the value


答:
CJam (57 bytes)

```<code>"http://www.medalbot.com/api/v1/medals"gN/3>9%3<{'"/3=N}%
</code>```

Online demo not available because it fetches content from the web. This cheats by not actually parsing JSON, but assuming that the structure won't change. (But then so do most of the existing answers, in different ways).

Title: Quick Golf: The Gold Leader

Body:
CJam (57 bytes)

"http://www.medalbot.com/api/v1/medals"gN/3>9%3<{'"/3=N}%

Online demo not available because it fetches content from the web. This cheats by not actually parsing JSON, but assuming that the structure won't change. (But then so do most of the existing answers, in different ways).


问:
Is it a wordinian?
What is the shortest way to see if an input is a wordinian using any programming language?

A wordinian is a word that contains words of length 1 to the original word's length. For example,

bin

'I' is a word

  'in' is a word

  'bin' is a word

Or,

stage

'a' is a word

  'ta' is a word (yes it is)

  'age' is a word

  'stag' is a word

  'stage' is a word

Input

Your code should take a word and a dictionary as inputs, in any reasonable format.

Output

The output should be a value to indicate true or false, to tell us if the word is a wordinian.

For more info on wordinians click here.

Here is a list of words that I will be using as inputs and subwords. Also, in response to @xnor, it has to contain subwords of each length, not a chain of subwords. Note that only one word will be used as an input.

答:
Perl, 86 bytes

Requires -E at no extra cost.

chop(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x
```

<p>Accepts all input via STDIN. First input is target word, rest of input is dictionary. Prints <code>1</code> on success, empty string on failure.</p>

<h3>Usage</h3>

<pre class="lang-sh prettyprint-override"><code>perl -E 'chomp(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x' <<< 'stage
a
ta
age
stag
stage'
1
perl -E 'chomp(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x' <<< 'stage
a
at
age
stag
stage'

perl -E 'chomp(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x' <<< 'bin
i
in
bin'
1
</code>```

Title: Is it a wordinian?

Body:
Perl, 86 bytes

Requires -E at no extra cost.

chop(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x

Accepts all input via STDIN. First input is target word, rest of input is dictionary. Prints 1 on success, empty string on failure.

Usage

perl -E 'chomp(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x' <<< 'stage
a
ta
age
stag
stage'
1
perl -E 'chomp(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x' <<< 'stage
a
at
age
stag
stage'

perl -E 'chomp(($s,@d)=<>);for$=(1..($x=length$s)){$-+=!!grep$s=~/$_/,grep$===y///c,@d}say$-==$x' <<< 'bin
i
in
bin'
1


问:
Implement DES key expansion
I wanted to make a challenge to do the full DES encryption algorithm, but that may be a bit too involved to get a ton of participation. This challenge is to simply generate the 16 48-bit subkeys used to encrypt data:

The algorithm is described well enough on wikipedia, and all relevant shift tables and such data are on this page.

Your task is to write a program or function that accepts 64 bits of input, and outputs the 16 48-bit keys. I am not picky about input or output formats, but hex coded is fairly standard.

You can check your results against the examples on this page, or this page

Shortest code wins.

答:
Perl - 384 314 chars

input is in decimal (from STDIN), output in binary. includes all necessary tables. feel free to improve anything

```<code>use Math'BaseConvert b10;
@_=sprintf("%064b",<>)=~/./g;
$s=b10 cG4xqQ8GMvUpZSqYtTAVVCZyBjrZs7FkNdowNTFBipcmG28UIKQKyfLYHWWjdq;
$s=~s/../$_[$&-1]/g;
map{
  $n=28-$_;
  $s=~s/(.{$_})(.{$n})(.{$_})(.+)/$2$1$4$3/;
  $_=b10"G._NqruyC5whI_KjAHzrS3ZgLTX7BzGp0.zML.AaubJCuwPtzPomq";
  s|..|($s=~/./g)[$&-1]|eg;
  say$_
}b10("3_AUuKOqD")=~/./g
</code>```

Title: Implement DES key expansion

Body:
Perl - 384 314 chars

input is in decimal (from STDIN), output in binary. includes all necessary tables. feel free to improve anything

use Math'BaseConvert b10;
@_=sprintf("%064b",<>)=~/./g;
$s=b10 cG4xqQ8GMvUpZSqYtTAVVCZyBjrZs7FkNdowNTFBipcmG28UIKQKyfLYHWWjdq;
$s=~s/../$_[$&-1]/g;
map{
  $n=28-$_;
  $s=~s/(.{$_})(.{$n})(.{$_})(.+)/$2$1$4$3/;
  $_=b10"G._NqruyC5whI_KjAHzrS3ZgLTX7BzGp0.zML.AaubJCuwPtzPomq";
  s|..|($s=~/./g)[$&-1]|eg;
  say$_
}b10("3_AUuKOqD")=~/./g


答:
Python 2, 120 113 bytes

from urllib import*
for x in list(urlopen("http://www.medalbot.com/api/v1/medals"))[3:26:9]:
    print x[21:-4]
```

Thanks @Nick T and @Value Ink

Title: Quick Golf: The Gold Leader

Body:
Python 2, 120 113 bytes

from urllib import*
for x in list(urlopen("http://www.medalbot.com/api/v1/medals"))[3:26:9]:
    print x[21:-4]

Thanks @Nick T and @Value Ink


答:
Python 3, 108 bytes

```<code>lambda w,d,r=range:all(any(i in d for i in j)for j in[[w[i:i+s]for i in r(len(w)+1-s)]for s in r(1,len(w))])
</code>```

An anonymous function that takes input, via argument, of a word w as a string and a dictionary d as a list of strings and returns True or False.

How it works

The first step is a list comprehension that generates a list of lists of all substrings of w excluding w, grouped by length. For example, for 'stage', the list [['s', 't', 'a', 'g', 'e'], ['st', 'ta', 'ag', 'ge'], ['sta', 'tag', 'age'], ['stag', 'tage']] is generated. This is achieved by looping over all valid start indices i for each substring length s, and slicing every s-length substring using w[i:i+s]. For each list in this list, the presence of each substring in the dictionary is checked; calling any returns a hit if at least one match for a given length is found. Finally, calling all checks if a match has been found for all substring lengths, and the result of this is returned.

Try it on Ideone

Title: Is it a wordinian?

Body:
What is the shortest way to see if an input is a wordinian using any programming language?

A wordinian is a word that contains words of length 1 to the original word's length. For example,

bin

'I' is a word

  'in' is a word

  'bin' is a word

Or,

stage

'a' is a word

  'ta' is a word (yes it is)

  'age' is a word

  'stag' is a word

  'stage' is a word

Input

Your code should take a word and a dictionary as inputs, in any reasonable format.

Output

The output should be a value to indicate true or false, to tell us if the word is a wordinian.

For more info on wordinians click here.

Here is a list of words that I will be using as inputs and subwords. Also, in response to @xnor, it has to contain subwords of each length, not a chain of subwords. Note that only one word will be used as an input.

Body:
Python 3, 108 bytes

lambda w,d,r=range:all(any(i in d for i in j)for j in[[w[i:i+s]for i in r(len(w)+1-s)]for s in r(1,len(w))])

An anonymous function that takes input, via argument, of a word w as a string and a dictionary d as a list of strings and returns True or False.

How it works

The first step is a list comprehension that generates a list of lists of all substrings of w excluding w, grouped by length. For example, for 'stage', the list [['s', 't', 'a', 'g', 'e'], ['st', 'ta', 'ag', 'ge'], ['sta', 'tag', 'age'], ['stag', 'tage']] is generated. This is achieved by looping over all valid start indices i for each substring length s, and slicing every s-length substring using w[i:i+s]. For each list in this list, the presence of each substring in the dictionary is checked; calling any returns a hit if at least one match for a given length is found. Finally, calling all checks if a match has been found for all substring lengths, and the result of this is returned.

Try it on Ideone


答:
Mathematica <s>96</s> 66 bytes

@alephalpha found a way to work directly from the file (without saving it), thereby saving 30 bytes!

```<code>Import["http://www.medalbot.com/api/v1/medals","RawJSON"][[;;3,2]]
</code>```

Import imports the file as a Raw JSON file.
[[;;3,2]]takes rows 1-3, second entry (country name).

Title: Quick Golf: The Gold Leader

Body:
Mathematica <s>96</s> 66 bytes

@alephalpha found a way to work directly from the file (without saving it), thereby saving 30 bytes!

Import["http://www.medalbot.com/api/v1/medals","RawJSON"][[;;3,2]]

Import imports the file as a Raw JSON file.
[[;;3,2]]takes rows 1-3, second entry (country name).


问:
Show off your tree analysing toolbox
As a programmer or computer scientist one might encounter quite a lot of trees - of course not the woody growing-in-the-wrong-direction kind, but the nice, pure mathematical kind:

```<code>  *<- root (also a node)
 /|\<- edge
* * *<- inner node
|  / \
* *   *<- leaf (also a node)
  |
  *
</code>```

Naturally over time we all have put together our own small handy toolbox to analyse such trees as we encounter them, right?
Now is the time to show it off!

Task

The toolbox must include the following functions:

size: The number of nodes in the tree.

depth: The number of edges on the longest path from the root to any leaf.

breadth: The number of leaves.

degree: The maximum number of child nodes for any node.

You have to submit a program or function for each of the tools, however they might share subroutines (e.g. parsing) which then have to be submitted only once. Note that those subroutines need to be full programs or functions too.

Input Format

The trees can be given in any reasonable format capturing the structure, e.g. the tree

```<code>  *
 / \
*   *
</code>```

could be represented through parentheses (()()), lists of lists [[],[]], or data structures with a constructor T[T[],T[]].
However not through linearisation [2,0,0] or a format like (size, depth, breath, degree, whatever-else-is-needed-to-make-this-format-unique-for-every-tree).
Generally speaking, your tree format should not contain numbers.

Output Format

A natural number for each of the properties described above.

Scoring

Lowest code in bytes for the 4 functions in every language wins, thus I will not accept an answer.

Feel free to provide additional tree tools like fold, isBinaryTree, preLinearise, postLinearize, or whatever you like. Of course those don't have to be included in the byte count.

Examples

First the tree is given in the sample formats from above, then the results of the functions as (size, depth, breadth, degree).

```<code>()
[]
T[]
(1,0,1,0)

(()())
[[],[]]
T[T[],T[]]
(3,1,2,2)

((())()((())()))
[[[]],[],[[[]],[]]]
T[T[T[]],T[],T[T[T[]],T[]]]
(8,3,4,3)

((()())((())()((())()))(()())(()))
[[[],[]],[[[]],[],[[[]],[]]],[[],[]],[[]]]
T[T[T[],T[]],T[T[T[]],T[],T[T[T[]],T[]]],T[T[],T[]],T[T[]]]
(17,4,9,4)

((((((((()))))))))
[[[[[[[[[]]]]]]]]]
T[T[T[T[T[T[T[T[T[]]]]]]]]]
(9,8,1,1)

(((((((()()))((()()))))((((()()))((()()))))))((((((()()))((()()))))((((()()))((()())))))))
[[[[[[[[],[]]],[[[],[]]]]],[[[[[],[]]],[[[],[]]]]]]],[[[[[[[],[]]],[[[],[]]]]],[[[[[],[]]],[[[],[]]]]]]]]
T[T[T[T[T[T[T[T[],T[]]],T[T[T[],T[]]]]],T[T[T[T[T[],T[]]],T[T[T[],T[]]]]]]],T[T[T[T[T[T[T[],T[]]],T[T[T[],T[]]]]],T[T[T[T[T[],T[]]],T[T[T[],T[]]]]]]]]
(45,7,16,2)
</code>```

答:
JavaScript (ES6), 131 bytes

```<code>s=a=>a.reduce((r,e)=>r+s(e),1)
d=a=>Math.max(...a.map(d),-1)+1
b=a=>a.reduce((r,e)=>r+b(e),+!a[0])
g=a=>Math.max(...a.map(g),a.length)
</code>```

Since all the functions are recursive, I've given them one letter names to save bytes: size, depth, breadth and degree. Takes input using the [,] format.

Title: Show off your tree analysing toolbox

Body:
JavaScript (ES6), 131 bytes

s=a=>a.reduce((r,e)=>r+s(e),1)
d=a=>Math.max(...a.map(d),-1)+1
b=a=>a.reduce((r,e)=>r+b(e),+!a[0])
g=a=>Math.max(...a.map(g),a.length)

Since all the functions are recursive, I've given them one letter names to save bytes: size, depth, breadth and degree. Takes input using the [,] format.


答:
Mathematica, 90 bytes

```<code>Sort[MemberQ[DictionaryWordQ/@StringPartition[#,t,1],True]~Table~{t,StringLength@#}][[1]]&
</code>```

Uses Mathematica's builtin DictionaryWordQ.

Taking input d as dictionary is 5 bytes shorter, but much slower for long lists:

```<code>m=MemberQ;Sort[m[d~m~#&/@StringPartition[#,t,1],True]~Table~{t,StringLength@#}][[1]]&
</code>```

Title: Is it a wordinian?

Body:
Mathematica, 90 bytes

Sort[MemberQ[DictionaryWordQ/@StringPartition[#,t,1],True]~Table~{t,StringLength@#}][[1]]&

Uses Mathematica's builtin DictionaryWordQ.

Taking input d as dictionary is 5 bytes shorter, but much slower for long lists:

m=MemberQ;Sort[m[d~m~#&/@StringPartition[#,t,1],True]~Table~{t,StringLength@#}][[1]]&


答:
Ruby, 44 bytes

7 Bytes off thanks to @NotThatCharles and his set operator tricks!

2 bytes off thanks to @Jordan with the Ruby 2.3 safe navigation operator trick w[x]&.size :)

->w,d{[*1..w.size]-d.map{|x|w[x]&.size}==[]}
```

It's an anonymous functions which takes a word w and a dictionary (array of words) d. Creates two arrays: The first containing the numbers 1 up to and including the length of w; The second array is d with each word mapped to their size if they are a substring of w, otherwise nil. Then it does set substraction to check whether the second array contains all element of the first array.

Title: Is it a wordinian?

Body:
Ruby, 44 bytes

7 Bytes off thanks to @NotThatCharles and his set operator tricks!

2 bytes off thanks to @Jordan with the Ruby 2.3 safe navigation operator trick w[x]&.size :)

->w,d{[*1..w.size]-d.map{|x|w[x]&.size}==[]}

It's an anonymous functions which takes a word w and a dictionary (array of words) d. Creates two arrays: The first containing the numbers 1 up to and including the length of w; The second array is d with each word mapped to their size if they are a substring of w, otherwise nil. Then it does set substraction to check whether the second array contains all element of the first array.