问:
Print a Negative of your Code
Consider a square of printable ASCII characters (code points 0x20 to 0x7E) for side length N, like the following (here, N = 6):

```<code>=\
 g \
7
m+y "g
  L ~
e> PHq
</code>```

We also require each row and each column to contain at least 1 space and 1 non-space character. (The above example satisfies this.)

We define the negative of such a square, to be a square of the same size, where each space is replaced with a non-space and vice versa. E.g., the following would be a valid negative of the above example:

```<code>  1234
a b cd
 ZYXWV
   !
{} [ ]
  ?
</code>```

The choice of non-space characters is irrelevant (as long as they are from the printable ASCII range).

The Challenge

You're to write a program, with square source code with side length N > 1, which prints a negative of itself to STDOUT. Trailing spaces have to be printed. You may or may not print a single trailing newline.

The usual quine rules also apply, so you must not read your own source code, directly or indirectly. Likewise, you must not assume a REPL environment, which automatically prints the value of each entered expression.

The winner is the program with the lowest side length N. In the event of a tie, the submission with the fewest non-space characters in the source code wins. If there's still a tie, the earliest answer wins.

答:
Befunge-98, 8x8 (56 non-spaces [11 nops])

Note: In the interest of good sports-person-ship, this reads its own source via ', making it a cheat-quine to some. Read the debate here.

Program

```<code> 07'?>:8v
v y+da:%<
<v ':vj!-
,+# '<zzv
v1#a vj!<
>z,\1 -\v
z>+,$v z<
1_@#:<v -
zzzzzv<z
</code>```

Output

```<code>(
 ,
  &
   %
    $
     #
      "
       !
</code>```

Explanation

The un-golfed version

```<code>07'?>:8%:ad+y-!jv>'n,$v
  !jv   a,\1-\v > 's,
    >         >       v
    v-1_@#:           <
</code>```

(non-space and space are replaced with 'n and 's for readability sake.)

This solution is based off of the fact that using an index [0,width^2) mod the width of the square can tell you if you are at the end of the row or on the diagonal. Since all spaces are placed along the diagonal, it is easy to tell when to print a non-space!

In Pseudocode

```<code>const int WIDTH = 8
push 0    //Because of the way the 'y' instruction works when picking
int row=7 //8-1 rows
int i=63  //Starting at the end allows for the cheaper i != 0
do
{
    pick variable row from the stack bottom + 1//ad+y
    if(i%WIDTH == row)
    {
        print non-space
    }
    else
    {
        print space
        if(i%WIDTH == 0)
        {
            print new-line
            --row
        }
    }
  --i
}
while(i != 0);
</code>```

Discussion

I'm very proud of it, though I wish I could have made every non-space also a non-nop. I'm also proud that I didn't use the standard Befunge get-increment-put trope! It prints out different symbols for non-space because I had the room for it and didn't want to be boring.

Try it on Windows with BefungeSharp!

Title: Print a Negative of your Code

Body:
Befunge-98, 8x8 (56 non-spaces [11 nops])

Note: In the interest of good sports-person-ship, this reads its own source via ', making it a cheat-quine to some. Read the debate here.

Program

 07'?>:8v
v y+da:%<
<v ':vj!-
,+# '<zzv
v1#a vj!<
>z,\1 -\v
z>+,$v z<
1_@#:<v -
zzzzzv<z

Output

(
 ,
  &
   %
    $
     #
      "
       !

Explanation

The un-golfed version

07'?>:8%:ad+y-!jv>'n,$v
  !jv   a,\1-\v > 's,
    >         >       v
    v-1_@#:           <

(non-space and space are replaced with 'n and 's for readability sake.)

This solution is based off of the fact that using an index [0,width^2) mod the width of the square can tell you if you are at the end of the row or on the diagonal. Since all spaces are placed along the diagonal, it is easy to tell when to print a non-space!

In Pseudocode

const int WIDTH = 8
push 0    //Because of the way the 'y' instruction works when picking
int row=7 //8-1 rows
int i=63  //Starting at the end allows for the cheaper i != 0
do
{
    pick variable row from the stack bottom + 1//ad+y
    if(i%WIDTH == row)
    {
        print non-space
    }
    else
    {
        print space
        if(i%WIDTH == 0)
        {
            print new-line
            --row
        }
    }
  --i
}
while(i != 0);

Discussion

I'm very proud of it, though I wish I could have made every non-space also a non-nop. I'm also proud that I didn't use the standard Befunge get-increment-put trope! It prints out different symbols for non-space because I had the room for it and didn't want to be boring.

Try it on Windows with BefungeSharp!


问:
Output "Fit" numbers

"Fit Numbers"

Sam has a "brilliant" idea for compression! Can you help?

Here is a rundown of Sam's compression scheme. First take in a base 10 representation of any natural number strictly smaller than 2^16, and write it as a binary string without any leading zeros.

```
1 -> 1
9 -> 1001
15 ->1111
13 ->1101
16 -> 10000
17 -> 10001
65535 -> 111111111111111
```

Now replace any group of one or more zeros with a single zero. This is because the number has gotten leaner. Your binary string now will look like this.

```
1 -> 1 -> 1
9 -> 1001 -> 101
15 ->1111 -> 1111
13 ->1101 -> 1101
16 -> 10000 -> 10
17 -> 10001 -> 101
65535 -> 111111111111111 -> 111111111111111
```

Now you convert the binary string back to a base 10 representation, and output it in any acceptable format. Here are your test cases. The first integer represents an input, and the last integer represents an output. Note that some numbers do not change, and thus can be called "fit"

```
1 -> 1 -> 1 -> 1
9 -> 1001 -> 101 -> 5
15 ->1111 -> 1111 -> 15
13 ->1101 -> 1101 -> 13
16 -> 10000 -> 10 -> 2
17 -> 10001 -> 101 -> 5
65535 -> 1111111111111111 -> 1111111111111111 -> 65535
65000 -> 1111110111101000 -> 11111101111010 -> 16250
```

You may use any language, but please note that Sam hates standard loopholes. This is code golf so the code can be as short as possible to make room for the "compressed" numbers".

Note:This is NOT an acceptable compression scheme. Using this will promptly get you fired.

Citation-Needed: I do not take credit for this concept. This comes from @Conor O' Brien's blog here see this OEIS of fit numbers. https://oeis.org/A090078

答:
Pyth, 12

```<code>i:.BQ"0+"\02
</code>```

Online.

```<code>  .BQ            # Convert input from base 10 to base 2
 :   "0+"\0      # Replace multiple zeroes with single zero
i          2     # Convert back from base 2 to base 10
</code>```

ContentLicense: CC BY-SA 3.0

Title: Output "Fit" numbers

Body:
Pyth, 12

i:.BQ"0+"\02

Online.

  .BQ            # Convert input from base 10 to base 2
 :   "0+"\0      # Replace multiple zeroes with single zero
i          2     # Convert back from base 2 to base 10


问:
Play a sound, any sound
Your program has to make the computer produce a sound, any sound.

Shortest code wins, not sooner than 10 days after the first valid answer. If there is a tie, the one submitted sooner, wins.

The program should run on a reasonable, not too uncommon personal computer.

Opening a pop-up, message box, etc. (for example, on a web page) does not count, as they might or might not produce a sound, depending on a lot of settings.

Just entering a wrong command or invalid character on a console and receiving a warning beep does not count, just as the compiler/interpreter/OS beeping on an error or crash does not count either. Your code must be a valid program.

答:
brainfuck: 8

```<code>+++++++.
</code>```

Prints the bell character.

Title: Play a sound, any sound

Body:
brainfuck: 8

+++++++.

Prints the bell character.


问:
Alphabet to Number and Number to Alphabet

Challenge

In this challenge you have to take a number as input and output the corresponding letter of the alphabet, and vice versa. (1 <=> A, 2 <=> B) etc.

```<code>1 -> A
2 -> B
...
26 -> Z

A -> 1
B -> 2
...
Z -> 26
</code>```

Rules

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

The input will only consist of either an uppercase letter from A to Z or an integer from 1 to 26 inclusive.

Trailing whitespaces (space and newline) are allowed.

答:
MATL, 10 bytes

```<code>6WZ~t42>?c
</code>```

Explanation:

```<code>6W              % 2**6 = 64, but golfier looking
  Z~            % bit-wise XOR with input
    t42>?       % if result is greater than 42
         c      % convert it to a character
                % else, don't
</code>```

Try it online! with numeric inputs.

Try it online! with alphabetic inputs.

Body:
MATL, 10 bytes

6WZ~t42>?c

Explanation:

6W              % 2**6 = 64, but golfier looking
  Z~            % bit-wise XOR with input
    t42>?       % if result is greater than 42
         c      % convert it to a character
                % else, don't

Try it online! with numeric inputs.

Try it online! with alphabetic inputs.


问:
How many lights are on?
You are little speck on a Cartesian plane. Pondering your existence, you decide to roam around your plane and touch things. You notice that every coordinate pair you visit has a light switch. To entertain yourself, you decide to toggle every switch that you come across.

The Challenge: Create a program that will take an input of random length, using only the characters v,^,<, and >. These characters correspond to movements.

< moves you one unit to the left

^ moves you one unit up

> moves you one unit to the right

v moves you one unit down

Using this randomly generated input, calculate how many switches will be left in the ON position, assuming you start at (0,0), all lights begin in the OFF state, and you don't turn on any lights until you make your first move. (Meaning, if you start at (0,0), and move up 1 unit to (0,1), there will now be 1 light on). If you come across a switch that is on the ON position, it will be turned OFF.

Test cases:

```<code>v>v<^^<v<<^<^><<>^^>>><v>vv^v>v^><><<^>><<<vvv^vvv>v>>v><vv^^<<>vv^^>v^<>>^^<^^>^^v<^>^<vvv^v^v><^<<v<<>><<>v>>^><^>^^<>>>>vv>^<<^<<><vvv<v^>>vvv>v^>>><<v^>^^^^v>>^>^v>v<vv^<>^<<v>vv>><^^<^><vv^^v<v<v^^^>v<^vv^v<><vv^^^>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>>^^vv>^^^vv>><><v>v<^v^>>>vv^><>><v<^v<>^><v<^^^^>><^<>v>^v<^vv>v>v<^<>v>v>^<vv>v<^>vvv<v^<vv<vv<>v>^><v^v<>>>>>v>><^v<>v>^v><v^v^vv<>^<vvv^>><v^<vvv^^<^vvv^v^<>><v>v^^v<><>v^^^v<<<^><v<<<>><<vv<<><vvv^v>>v^v<v^>>><<v<>^v><>vv<<v>v^vv>v^v<^<vv<><><^v>^<vv>v^^>>^^^><vv<><^>>>^<v^<<^^>^>vv^><v<vvv>^^>>>^><<vv>vv>^<>>^^><^v><<>^<<<v^>^
</code>```

yields 1408 lights on.

To generate input, you may use the following Python script:

import random
length = random.randint(15, 10000)
walk = ''
chars = ['v', '<', '>', '^']
for i in range(length):
    walk += random.choice(chars)
print(walk)
```

Standard code-golf scoring, winner is the smallest number of bytes.

答:
Perl, 49 bytes

Includes +1 for -p
Run with the control string on STDIN

```<code>./lights.pl <<< "<<>"
</code>```

lights.pl:

```<code>#!/usr/bin/perl -p
$\-=1-($a{$x+=/</-/>/,$y+=/\^/-/v/}^=2)for/./g}{
</code>```

If input is restricted to 10000 bytes this reduces to 44+1:

```<code>$\+=$#{$x+=/</-/>/.e5+/\^/-/v/}*=-1for/./g}{
</code>```

Title: How many lights are on?

Body:
Perl, 49 bytes

Includes +1 for -p
Run with the control string on STDIN

./lights.pl <<< "<<>"

lights.pl:

#!/usr/bin/perl -p
$\-=1-($a{$x+=/</-/>/,$y+=/\^/-/v/}^=2)for/./g}{

If input is restricted to 10000 bytes this reduces to 44+1:

$\+=$#{$x+=/</-/>/.e5+/\^/-/v/}*=-1for/./g}{


问:
Identify a string from its substrings

Introduction

I've previously created two challenges where the idea is to reconstruct an object using as few query-type operations as possible; this will be the third.

The task

Your inputs shall be a non-empty string S over the alphabet abc and its length, and your output shall be S.
With no restrictions, this would of course be a trivial task; the catch is that you're not allowed to access S directly.
The only thing you're allowed to do to S is to call the function num_occur(T, S), where T is some other string, and num_occur counts the number of occurrences of T in S.
Overlapping occurrences are counted as distinct, so num_occur(T, S) really returns the number of indices i such that

```<code>S[i, i+1, …, i+length(T)-1] == T</code>```

For example, num_occur("aba", "cababaababb") will return 3.
Note also that num_occur(S, S) will return 1.
The result of num_occur("", S) is undefined, and you should not call the function on an empty string.

In short, you should write a function or program that takes S and length(S) as inputs, calls num_occur on some shorter strings and S some number of times, reconstructs S from that information and returns it.

Rules and scoring

Your goal is to write a program that makes as few calls to num_occur as possible.
In this repository, you will find a file called abc_strings.txt.
The file contains 100 strings, each on its own line, between lengths 50 and 99.
Your score is the total number of calls to num_occur on these inputs, lower score being better.
Your solution will preferably keep track of this number as it runs, and print it upon finishing.
The strings are generated by choosing uniformly random letters from abc; you are allowed to optimize for this method of generating the strings, but not the strings themselves.

There is no time limit, except that you should run your solution on the test cases before submitting it.
You solution should work for any valid input S, not just the test cases.

You are encouraged to share your implementation of num_occur too, if you're not using someone else's.
To get the ball rolling, here's an implementation in Python:

```<code>def num_occur(needle, haystack):
    num = 0
    for i in range(len(haystack) - len(needle) + 1):
        if haystack[i : i + len(needle)] == needle:
            num += 1
    return num
</code>```

答:
Javascript, <s>14325</s> 14311 calls

We start with an empty string and go our way recursively by adding a new letter at the end or at the beginning of the current string while we still have at least one match.

All previous results from numOccur() are saved in the sym object and we use this data to reject immediately any new string that can't possibly be a candidate.

EDIT: Because we always start with 'a', we always know the exact number of a in the string. We use this information to end the process earlier when we detect that only a sequence of a is missing. Also fixed the regular expression which was invalid in Chrome and IE.

```<code>var test = [
  'ccccbcbbbbacbaaababbccaacbccaaaaccbccaaaaaabcbbbab',
  // etc.
];
var call = 0;

function guess(S, len) {
  var sym = {};
  recurse(S, len, "", sym);
  return sym.result;
}

function recurse(S, len, s, sym) {
  var dictionary = [];

  if(s == '' || (isCandidate(s, sym) && (sym[s] = numOccur(S, s)))) {
    if(s.length == len) {
      sym.result = s;
    }
    else if(sym['a'] && count(s, 'a') == sym['a'] - (len - s.length)) {
      dictionary = [ Array(len - s.length + 1).join('a') ];
    }
    else {
      dictionary = [ "a", "b", "c" ];
    }
    dictionary.some(function(e) {
      return recurse(S, len, s + e, sym) || recurse(S, len, e + s, sym);
    });
    return true;
  }
  return false;
}

function isCandidate(s, sym) {
  return sym[s] === undefined && Object.keys(sym).every(function(k) {
    return count(s, k) <= sym[k];
  });
}

function count(s0, s1) {
  return (s0.match(new RegExp(s1, 'g')) || []).length;
}

function numOccur(S, s) {
  call++;
  return count(S, s);
}

test.forEach(function(S) {
  if(guess(S, S.length) != S) {
    console.log("Failed for: '" + S + "'");
  }
});
console.log(call + " calls");
</code>```

Full executable snippet below.

var test = [
  'ccccbcbbbbacbaaababbccaacbccaaaaccbccaaaaaabcbbbab',
  'caccbbababbaaaccbcabbaabaabcacabacaababcabcbbacaac',
  'bbbbaacabcabacaccaaaabaaacaacabbcbacabaccbbcbabbcbc',
  'abbcbcbccbccaacaccaccaabaccbbcabaaccabccbbbabbbcabc',
  'aabacbbbcaaabcccaccccbcaabcacaccbabbbcccacabaaababca',
  'bccbbaaccaaccacabaaaabbbbaababacabaaabacbcacbbbbabaa',
  'bbbcbcabbacbaacbacabcbabbacacbbcbcabbaabbbccbacaaacac',
  'ccbcbbbaaaaaccbaacbabbbcbccbabaabccbcbcbcbabcbbccacba',
  'aacbcbcabcbcbccbabbacacbcaaababbbcacaacaccbabbbbabcaac',
  'bcabacaabbacccacaabcaaacbcbcbacabbababcabbbbacbaaaabbb',
  'abbaccccabbbcbbaacccacbcaacababaccabbabbacbbbaabaacbaba',
  'cabbacabacccabcabacbaacbaababcaccbacbaaaacbbabbbccabbbb',
  'bcabccaaabcbaaccaabccbbcbabaccababbbaccccacaaccaccacbcab',
  'abbcbabaacbcbbabbccccbccabcbbaccacbabcacbaacbccbcabcccbc',
  'bcbacabbaabcccabccacbcbccbcbbbccacbbccaabaacccccbcabaaccc',
  'baccbcacaccacbbbcccbaaacbaccacbbacbbbaccccacbabcbbbaacabb',
  'bcccabaaaabcbbbaaccbcaccbaabacccaaacbaabaccccacabaccacbcac',
  'baabcbbcaabcacbabbcacccbcabbabaacbbbababbbbbccccccbcbbcbcc',
  'bacacbbabbcbbcaacabcccccbbacabcaabbbcbbabaacbcbbaccaaacbbac',
  'ccabccbccbaaacbcccccabacbbabbbbccbccccabaabaabbaacbabcabbcb',
  'abbaccbcaabacbbacabaabbcbacbacacabccbbcccaccbbacbbbaacbaccab',
  'bbbbaaabababcccbbbababacbacbaabbabccacccaaacabaccababaccbcac',
  'bbcbbbbcccaccbbbcbcaaccbcacaabbbbabaaabbbaaacbbaaccbacaccabbb',
  'cacabcabcbcbbbbcabbbccccccccacaaabaacbcaabbabcacbcbcccccacaab',
  'babbcacabaabbccabcbbaacccaaccbabcbbcbcbbbcabbcccbcacbabccaccac',
  'ccbbcbcbcaacbcaaccacbcaabbbcbbaccbbabacacccccaccaababcacccccba',
  'bcccbcacccccabccabccbcbccaccaaacbcacabaabcbcccaccaaaabbcacbbcaa',
  'cbbcacbbacaacbabccaabbaabacacbcbcbabcaccabbbbcabbbabaaacccaabcc',
  'aabbaacccaaacbcaabcabaabbbaababbbbcbacabbbbbbbbccaccccbbaccbbaaa',
  'abbcccabbabbaccccaacbabbccccbbbbccaaacaabacbabbabcabacbaabcbcacb',
  'bcacbccccaacbbcaccbcbcbbabacabacabbcaaabbccabcccbaacabcbbcacababb',
  'acabacaabcabbcccccbcacaccccbccaaaacacbbbccbcaabaacbbbacabcbcaabca',
  'caabbaccaacbbcbaacbcabccacacabbcbcbbacabbbaacccaacccabaaaccbbacbaa',
  'baaabbcbbbaacabacbcaaacabbacaacbacabbcabcccbabcbbacacbbababccacabc',
  'abbbacbaabcabbcabbbabaababbaabcacbabbaababcabbbccccbcaacbbcccabaccb',
  'caaababcacccaccababaccbabbccaabbbbbabaabcabccbabbbbbbcbacbabcbcccbb',
  'abbbcaaaaacaaacbbbcbacabbcbbbccacaccacacabacacbbccbbbcbaccabbcbaabbc',
  'bacacbcccabcabaabacccbcaaabcabbbcccaacbabacbaabbcccacaacbabbcacbaabb',
  'bacaaaccbaababbbbbcaabcabaacccabacccbabcbccbbcbcaacbbaabcaccaaaacaabb',
  'bbacaacccaaacacccbbacbcbbaaaccccabbbbcbbbabaaaaccbccaababaccbbccacaca',
  'aacccccbabaccbcbcbbaccbacbcbacaababaaaccbaaabaabcccccacbbaabcccaababcc',
  'babacacbbbacbbbbbabbabababacabacaaacbbccaccabacaacbabbbaccacccbcaaabbb',
  'bcaccabbabbcbcabccbbcaacbbcbacbcabaaaaaacaaacaccbcaaccaaccacbaccacaabbc',
  'acbcbbcbbaacbbbabbaabacabbcccabacabcabacccacbcaacacabcaaaabbabcccbcbabb',
  'ccbcbcccbccbbbabaabbaababbcbacacbcbaacaccccccbcbacacbcabaaaacaacbbbbacba',
  'cccbcbaaabcbbcbabbbaccabbabcacbaccbcababbababcbcaccabbbccabaabaaccccacbb',
  'bbabcbcaabbacaabcababbbccbccccaaaabaccbbbbababbcabbabbaccaaaabbcbbbcbaccc',
  'cbacaccaaaacaacbbcbbacaccabacaacacaacaacabccaaaccccacaaaaabcbcabaabaacccb',
  'bcacbccabcccabababbbbcabaacabcbbaacaaaabbbacccaaabccbaabcbbabbbcccabaabbbb',
  'cbccacabaaacabbccbacabccacabcbaccbababcccabbabbbbbbccbaabbaacaacaaaabcbabb',
  'abcbcabbcabaababccbcacabbcbcabcaabbbabbcaaabaaaaacbaabaaababccacbabcbaccbab',
  'aabbabbbcacaaaabcbcabccccacbacbccacacaabccacccaaacacbcccaabbbccacacbbccbbac',
  'caacbbccacaaaacabaacbcaaaccbbabbcacababbbabcbccbaabccaababbcbacbccababbcbbbc',
  'aaabaaaabbbbbcbbbacabccbaaaaabaacbacbcccbccacccacaaacaccbbabcbcccbbccccabbcb',
  'cccccacacbacbbcbbcabcbaabbcbbbacabcbbccccaaacabcababbcaaccaabccabaccbcaccbaba',
  'ccaaaccbccacabcacaccbccaabacacabaabbbaacbcacaacbaaabbbbabbabcccabcabbaccacacc',
  'cbbbcaccbcacccbacccaaaabacaacccbcbcbabbbaababacccccccabbaaabbcbaabbbbbbaaaaaaa',
  'ccbcbcbaabbccabbabbccbacbabacbcacbccacaabbcacaaccabbbbcbacbbcaaabaabccaacccacb',
  'caaabcabaacbbabcbccabcacbbcccabcacbbcaabaacaaabbbcacaaccaccaaaacaaccbbaaaacaaac',
  'bbacacbbaaaacbcabbbbbaabacaccabcbabbccbbbabbbacccababbcababcbbcacbababbbaaabcca',
  'bbacbbacacaccccbabbbbcabbcccbcacaabbcabbccaaaaabcbbcccaccbcbbbccabcbaccacbacbaba',
  'baccbcababbacabcbabacaababbaabcabbcbcbccabacbbaaaaabacaaacaacbacbcabacabaaccbcab',
  'accacccabccbabcbcbaababacabcabbcaccbccabbabcbcabbaabccacbbbbcaacbccaababbababbaba',
  'bbcccbcbcbccccbcaaccaaacacbbaacbcccbbcabbbccabaacbacaaaccbcbaacababaccacbcbaaccac',
  'acbccccaabcabbbcbbccbccbacbcabcccacbcabbaacbababbbcbbccacbacccbbbaccbaaaabbbabaccb',
  'babcacaccbccbaaabaabbbaabcaabaaccccacaacbaccbcbabbbbbbabcbbbbacbacbabcbbbacbbbbbbc',
  'caabcaaaaabacccacbbbaabaabccaabcbaabbcbcbbbccbabbccbcbabbbbccacbcbcbacaaccccacbbabc',
  'bbaaabbabccaccacbcbbccaaaaababbacccbabcbacabacbaacbcabaaacacaaaaacaaacabbbbccabbbca',
  'bbcbccababbbaabbabcbbaacbccbaacbababbabcbaaccbcbcabacaabacaacabcababbaaabbbbbbccccbb',
  'acabcabccaaccccacbcaabaccacaaabcbabbabbaccbbaaacacabcabbcabababaccccbcbabaacbbcccbab',
  'bacaaaaacbcacbbbaaaaabbbbcbbcbbbcaccccbacaccbbcbabbbccbaaabbcbaccacacbcbcacbcbaaabacc',
  'bbcaabccbcaccbabbacbaacacccccaabbbccbccbbbcccbacaaaccccbccbbbbabccaaacaabbbbacaacabab',
  'aaaccccbbabbcacabaacacbabbcacbcccbcbaaacaabaabacbbaabcbbbbbcacbaccaacaacbccacbbcacbbaa',
  'bbcacabcbbcbabbabbbacaaabcabbbbacbacbabacbbbbbabacabbabaabcabbaabbbaaccbcabcababcaaacc',
  'ccccbaacbbcaccaccbaaacaccbabbabaabbababcacacaaccbbcbccaaaaaaacbccacbacbabbbabcabaabaabb',
  'abacacbaccacaaacaccbcbabcaacbccaccbbacbabcababcaabcaabcbcabbcbacabaaaaaabaccccbbbcbabac',
  'ccccacbaaabaaacabbabacbbacbabcbbcaaaaacaccacabcaacabcbcbcaccabcaaccbaccabcccbccacccbacbc',
  'bcaabcaacacccbcababccacacbccccccbbaaabacabbcbbbcbaaacbbacababbaccccacbbcbacaacbabcbaccbc',
  'cbcbbaabacbaacbbcabbbbaccbaabbacbcccaaabbabacabbbababcaabcacbaccacacaccbbbbcbcbbaaacbcbba',
  'ccbcabcaabcbabbbcbcbbabacabacbbaccbbcbcabcaccaaccbaccbaacacacbbaacaaaaabcaaaacbcccbcccaaa',
  'cbbababacbbabbabaabaaaabcacbacbcccbacbccbbcaabcabaccacccbbcaacacccccaccabaabccacbaccabaaba',
  'cbbbaaacaccbcabccacbccabacbcbcccccacaccbbcccbcbbbaababcaaaacaabbbccbacbaccabccccbbbcaaaabb',
  'bbabbacaaccacccbbcabbacbcbabcccaccacbacbccababbbcacbabbbcabbbbacabcabcbaacbaabcbccacaaaccbc',
  'babcbaabccabcabaaabcaaaabaaaaccbcbcacbbbccaccccaacbcbabbbaaaccacaaabacbbabbcacbcaaaaabaabab',
  'acbabbccacaccabccbcbabacccbabbaacbccbcaabccbcbababccacbbbaabbaaaababbcaaaaabccbacbbcacbcacba',
  'cbccbbaacacccacacacbbbcbbccabcaaaabbcacacacaccbacaacbcbcbccaacaaaaaacbacacbabbbcccabbbbababa',
  'cabaabaccbbcccabaccbbacbcabbbbbaccccccbcbcbcbbccbaaabbbbcabacabccaacbcbcbabccbbcabacababccaab',
  'bccaacbabcbccaccbabcbbcbaaccbaacabbcabbbacbbccabcabccabccbacbaacbccabccaabaaabcaababacacccaac',
  'aacabcccaaccacbbcbbbbacaacacbcbcaabbcbbacbabcbccaabcbbbbaabccbbbacaababcabaacaccababacbcbccbba',
  'caaabbcbcbcabccccacacaaababbacbabacbaaccbcbabbaaacbbccccaaaabbccbcabcbccbbaaccbbbabcaabcbbbcab',
  'aacbbcbbcbaccccbaaaabcbaaabaaacaacaaacacacabaaabacbaaaacccbaaabbbcbbbacbcbccabccaabbaabcbcbccba',
  'abaccbcacabbbbacabaacaccbcbaabbaccaabbbbbababbbcbbbbacaacabbbabcaccbacabbabcbbacbbaaccbcbacaabc',
  'aacaaaacccabcccacacbaaccccababcaccaccacbbbacabccbbcbbbacaccbbbbbaabacbacbcbcabccaaccababacaabcbb',
  'baabbabaaccabcbbabcacccccaabbccbccbcaacbbbccccbbcbacaabcccccbbabbabbcacbbccbcacabbbbaaaaccbcacca',
  'aabacbaacbbccabbbacbcbbbabacaacccabbcabacacaaaabbcbbbcbbbcababbccbbacbbabcaacbacbbcaabbbcbaaaccaa',
  'aacabaaccaaabcacccabbaabbcacbabccacabaccaaaaccccccaabcbbbaabcbcccacaccbcaaacaaaabaababccbbbcccaac',
  'bcaccbcacaccbacbcccbcbbcabaabbabcccbaaababbbabbcbcbcaabbabbccccbabccabbccccabaaabccbacabccabbbacaa',
  'ccaacbabcccbabacabaccccbcbbcccbbbacbbbcccacababccbbaaaaababbabccbccabcccbccabaccbcbcacbbbaacabccaa',
  'caccbababcbcbabccabcbbaccbbbabcbacbcbcbcabcbacbcacabbcaabbbbbbbcbbaabcacccbcaabccacbccbbcccaabcbcac',
  'bbcccaabacbacbccbbbbbaabccaaabbaabcaabbcbabbbaabcbcbacbaccabacacaaaababccaaaccacaabaabcacbcaccbaabb'
];
var call = 0;

function guess(S, len) {
  var sym = {};
  recurse(S, len, "", sym);
  return sym.result;
}

function recurse(S, len, s, sym) {
  var dictionary = [];

  if(s == '' || (isCandidate(s, sym) && (sym[s] = numOccur(S, s)))) {
    if(s.length == len) {
      sym.result = s;
    }
    else if(sym['a'] && count(s, 'a') == sym['a'] - (len - s.length)) {
      dictionary = [ Array(len - s.length + 1).join('a') ];
    }
    else {
      dictionary = [ "a", "b", "c" ];
    }
    dictionary.some(function(e) {
      return recurse(S, len, s + e, sym) || recurse(S, len, e + s, sym);
    });
    return true;
  }
  return false;
}

function isCandidate(s, sym) {
  return sym[s] === undefined && Object.keys(sym).every(function(k) {
    return count(s, k) <= sym[k];
  });
}

function count(s0, s1) {
  return (s0.match(new RegExp(s1, 'g')) || []).length;
}

function numOccur(S, s) {
  call++;
  return count(S, s);
}

test.forEach(function(S) {
  if(guess(S, S.length) != S) {
    console.log("Failed for: '" + S + "'");
  }
});
console.log(call + " calls");```

Title: Identify a string from its substrings

Body:
Javascript, <s>14325</s> 14311 calls

We start with an empty string and go our way recursively by adding a new letter at the end or at the beginning of the current string while we still have at least one match.

All previous results from numOccur() are saved in the sym object and we use this data to reject immediately any new string that can't possibly be a candidate.

EDIT: Because we always start with 'a', we always know the exact number of a in the string. We use this information to end the process earlier when we detect that only a sequence of a is missing. Also fixed the regular expression which was invalid in Chrome and IE.

var test = [
  'ccccbcbbbbacbaaababbccaacbccaaaaccbccaaaaaabcbbbab',
  // etc.
];
var call = 0;

function guess(S, len) {
  var sym = {};
  recurse(S, len, "", sym);
  return sym.result;
}

function recurse(S, len, s, sym) {
  var dictionary = [];

  if(s == '' || (isCandidate(s, sym) && (sym[s] = numOccur(S, s)))) {
    if(s.length == len) {
      sym.result = s;
    }
    else if(sym['a'] && count(s, 'a') == sym['a'] - (len - s.length)) {
      dictionary = [ Array(len - s.length + 1).join('a') ];
    }
    else {
      dictionary = [ "a", "b", "c" ];
    }
    dictionary.some(function(e) {
      return recurse(S, len, s + e, sym) || recurse(S, len, e + s, sym);
    });
    return true;
  }
  return false;
}

function isCandidate(s, sym) {
  return sym[s] === undefined && Object.keys(sym).every(function(k) {
    return count(s, k) <= sym[k];
  });
}

function count(s0, s1) {
  return (s0.match(new RegExp(s1, 'g')) || []).length;
}

function numOccur(S, s) {
  call++;
  return count(S, s);
}

test.forEach(function(S) {
  if(guess(S, S.length) != S) {
    console.log("Failed for: '" + S + "'");
  }
});
console.log(call + " calls");

Full executable snippet below.

var test = [
  'ccccbcbbbbacbaaababbccaacbccaaaaccbccaaaaaabcbbbab',
  'caccbbababbaaaccbcabbaabaabcacabacaababcabcbbacaac',
  'bbbbaacabcabacaccaaaabaaacaacabbcbacabaccbbcbabbcbc',
  'abbcbcbccbccaacaccaccaabaccbbcabaaccabccbbbabbbcabc',
  'aabacbbbcaaabcccaccccbcaabcacaccbabbbcccacabaaababca',
  'bccbbaaccaaccacabaaaabbbbaababacabaaabacbcacbbbbabaa',
  'bbbcbcabbacbaacbacabcbabbacacbbcbcabbaabbbccbacaaacac',
  'ccbcbbbaaaaaccbaacbabbbcbccbabaabccbcbcbcbabcbbccacba',
  'aacbcbcabcbcbccbabbacacbcaaababbbcacaacaccbabbbbabcaac',
  'bcabacaabbacccacaabcaaacbcbcbacabbababcabbbbacbaaaabbb',
  'abbaccccabbbcbbaacccacbcaacababaccabbabbacbbbaabaacbaba',
  'cabbacabacccabcabacbaacbaababcaccbacbaaaacbbabbbccabbbb',
  'bcabccaaabcbaaccaabccbbcbabaccababbbaccccacaaccaccacbcab',
  'abbcbabaacbcbbabbccccbccabcbbaccacbabcacbaacbccbcabcccbc',
  'bcbacabbaabcccabccacbcbccbcbbbccacbbccaabaacccccbcabaaccc',
  'baccbcacaccacbbbcccbaaacbaccacbbacbbbaccccacbabcbbbaacabb',
  'bcccabaaaabcbbbaaccbcaccbaabacccaaacbaabaccccacabaccacbcac',
  'baabcbbcaabcacbabbcacccbcabbabaacbbbababbbbbccccccbcbbcbcc',
  'bacacbbabbcbbcaacabcccccbbacabcaabbbcbbabaacbcbbaccaaacbbac',
  'ccabccbccbaaacbcccccabacbbabbbbccbccccabaabaabbaacbabcabbcb',
  'abbaccbcaabacbbacabaabbcbacbacacabccbbcccaccbbacbbbaacbaccab',
  'bbbbaaabababcccbbbababacbacbaabbabccacccaaacabaccababaccbcac',
  'bbcbbbbcccaccbbbcbcaaccbcacaabbbbabaaabbbaaacbbaaccbacaccabbb',
  'cacabcabcbcbbbbcabbbccccccccacaaabaacbcaabbabcacbcbcccccacaab',
  'babbcacabaabbccabcbbaacccaaccbabcbbcbcbbbcabbcccbcacbabccaccac',
  'ccbbcbcbcaacbcaaccacbcaabbbcbbaccbbabacacccccaccaababcacccccba',
  'bcccbcacccccabccabccbcbccaccaaacbcacabaabcbcccaccaaaabbcacbbcaa',
  'cbbcacbbacaacbabccaabbaabacacbcbcbabcaccabbbbcabbbabaaacccaabcc',
  'aabbaacccaaacbcaabcabaabbbaababbbbcbacabbbbbbbbccaccccbbaccbbaaa',
  'abbcccabbabbaccccaacbabbccccbbbbccaaacaabacbabbabcabacbaabcbcacb',
  'bcacbccccaacbbcaccbcbcbbabacabacabbcaaabbccabcccbaacabcbbcacababb',
  'acabacaabcabbcccccbcacaccccbccaaaacacbbbccbcaabaacbbbacabcbcaabca',
  'caabbaccaacbbcbaacbcabccacacabbcbcbbacabbbaacccaacccabaaaccbbacbaa',
  'baaabbcbbbaacabacbcaaacabbacaacbacabbcabcccbabcbbacacbbababccacabc',
  'abbbacbaabcabbcabbbabaababbaabcacbabbaababcabbbccccbcaacbbcccabaccb',
  'caaababcacccaccababaccbabbccaabbbbbabaabcabccbabbbbbbcbacbabcbcccbb',
  'abbbcaaaaacaaacbbbcbacabbcbbbccacaccacacabacacbbccbbbcbaccabbcbaabbc',
  'bacacbcccabcabaabacccbcaaabcabbbcccaacbabacbaabbcccacaacbabbcacbaabb',
  'bacaaaccbaababbbbbcaabcabaacccabacccbabcbccbbcbcaacbbaabcaccaaaacaabb',
  'bbacaacccaaacacccbbacbcbbaaaccccabbbbcbbbabaaaaccbccaababaccbbccacaca',
  'aacccccbabaccbcbcbbaccbacbcbacaababaaaccbaaabaabcccccacbbaabcccaababcc',
  'babacacbbbacbbbbbabbabababacabacaaacbbccaccabacaacbabbbaccacccbcaaabbb',
  'bcaccabbabbcbcabccbbcaacbbcbacbcabaaaaaacaaacaccbcaaccaaccacbaccacaabbc',
  'acbcbbcbbaacbbbabbaabacabbcccabacabcabacccacbcaacacabcaaaabbabcccbcbabb',
  'ccbcbcccbccbbbabaabbaababbcbacacbcbaacaccccccbcbacacbcabaaaacaacbbbbacba',
  'cccbcbaaabcbbcbabbbaccabbabcacbaccbcababbababcbcaccabbbccabaabaaccccacbb',
  'bbabcbcaabbacaabcababbbccbccccaaaabaccbbbbababbcabbabbaccaaaabbcbbbcbaccc',
  'cbacaccaaaacaacbbcbbacaccabacaacacaacaacabccaaaccccacaaaaabcbcabaabaacccb',
  'bcacbccabcccabababbbbcabaacabcbbaacaaaabbbacccaaabccbaabcbbabbbcccabaabbbb',
  'cbccacabaaacabbccbacabccacabcbaccbababcccabbabbbbbbccbaabbaacaacaaaabcbabb',
  'abcbcabbcabaababccbcacabbcbcabcaabbbabbcaaabaaaaacbaabaaababccacbabcbaccbab',
  'aabbabbbcacaaaabcbcabccccacbacbccacacaabccacccaaacacbcccaabbbccacacbbccbbac',
  'caacbbccacaaaacabaacbcaaaccbbabbcacababbbabcbccbaabccaababbcbacbccababbcbbbc',
  'aaabaaaabbbbbcbbbacabccbaaaaabaacbacbcccbccacccacaaacaccbbabcbcccbbccccabbcb',
  'cccccacacbacbbcbbcabcbaabbcbbbacabcbbccccaaacabcababbcaaccaabccabaccbcaccbaba',
  'ccaaaccbccacabcacaccbccaabacacabaabbbaacbcacaacbaaabbbbabbabcccabcabbaccacacc',
  'cbbbcaccbcacccbacccaaaabacaacccbcbcbabbbaababacccccccabbaaabbcbaabbbbbbaaaaaaa',
  'ccbcbcbaabbccabbabbccbacbabacbcacbccacaabbcacaaccabbbbcbacbbcaaabaabccaacccacb',
  'caaabcabaacbbabcbccabcacbbcccabcacbbcaabaacaaabbbcacaaccaccaaaacaaccbbaaaacaaac',
  'bbacacbbaaaacbcabbbbbaabacaccabcbabbccbbbabbbacccababbcababcbbcacbababbbaaabcca',
  'bbacbbacacaccccbabbbbcabbcccbcacaabbcabbccaaaaabcbbcccaccbcbbbccabcbaccacbacbaba',
  'baccbcababbacabcbabacaababbaabcabbcbcbccabacbbaaaaabacaaacaacbacbcabacabaaccbcab',
  'accacccabccbabcbcbaababacabcabbcaccbccabbabcbcabbaabccacbbbbcaacbccaababbababbaba',
  'bbcccbcbcbccccbcaaccaaacacbbaacbcccbbcabbbccabaacbacaaaccbcbaacababaccacbcbaaccac',
  'acbccccaabcabbbcbbccbccbacbcabcccacbcabbaacbababbbcbbccacbacccbbbaccbaaaabbbabaccb',
  'babcacaccbccbaaabaabbbaabcaabaaccccacaacbaccbcbabbbbbbabcbbbbacbacbabcbbbacbbbbbbc',
  'caabcaaaaabacccacbbbaabaabccaabcbaabbcbcbbbccbabbccbcbabbbbccacbcbcbacaaccccacbbabc',
  'bbaaabbabccaccacbcbbccaaaaababbacccbabcbacabacbaacbcabaaacacaaaaacaaacabbbbccabbbca',
  'bbcbccababbbaabbabcbbaacbccbaacbababbabcbaaccbcbcabacaabacaacabcababbaaabbbbbbccccbb',
  'acabcabccaaccccacbcaabaccacaaabcbabbabbaccbbaaacacabcabbcabababaccccbcbabaacbbcccbab',
  'bacaaaaacbcacbbbaaaaabbbbcbbcbbbcaccccbacaccbbcbabbbccbaaabbcbaccacacbcbcacbcbaaabacc',
  'bbcaabccbcaccbabbacbaacacccccaabbbccbccbbbcccbacaaaccccbccbbbbabccaaacaabbbbacaacabab',
  'aaaccccbbabbcacabaacacbabbcacbcccbcbaaacaabaabacbbaabcbbbbbcacbaccaacaacbccacbbcacbbaa',
  'bbcacabcbbcbabbabbbacaaabcabbbbacbacbabacbbbbbabacabbabaabcabbaabbbaaccbcabcababcaaacc',
  'ccccbaacbbcaccaccbaaacaccbabbabaabbababcacacaaccbbcbccaaaaaaacbccacbacbabbbabcabaabaabb',
  'abacacbaccacaaacaccbcbabcaacbccaccbbacbabcababcaabcaabcbcabbcbacabaaaaaabaccccbbbcbabac',
  'ccccacbaaabaaacabbabacbbacbabcbbcaaaaacaccacabcaacabcbcbcaccabcaaccbaccabcccbccacccbacbc',
  'bcaabcaacacccbcababccacacbccccccbbaaabacabbcbbbcbaaacbbacababbaccccacbbcbacaacbabcbaccbc',
  'cbcbbaabacbaacbbcabbbbaccbaabbacbcccaaabbabacabbbababcaabcacbaccacacaccbbbbcbcbbaaacbcbba',
  'ccbcabcaabcbabbbcbcbbabacabacbbaccbbcbcabcaccaaccbaccbaacacacbbaacaaaaabcaaaacbcccbcccaaa',
  'cbbababacbbabbabaabaaaabcacbacbcccbacbccbbcaabcabaccacccbbcaacacccccaccabaabccacbaccabaaba',
  'cbbbaaacaccbcabccacbccabacbcbcccccacaccbbcccbcbbbaababcaaaacaabbbccbacbaccabccccbbbcaaaabb',
  'bbabbacaaccacccbbcabbacbcbabcccaccacbacbccababbbcacbabbbcabbbbacabcabcbaacbaabcbccacaaaccbc',
  'babcbaabccabcabaaabcaaaabaaaaccbcbcacbbbccaccccaacbcbabbbaaaccacaaabacbbabbcacbcaaaaabaabab',
  'acbabbccacaccabccbcbabacccbabbaacbccbcaabccbcbababccacbbbaabbaaaababbcaaaaabccbacbbcacbcacba',
  'cbccbbaacacccacacacbbbcbbccabcaaaabbcacacacaccbacaacbcbcbccaacaaaaaacbacacbabbbcccabbbbababa',
  'cabaabaccbbcccabaccbbacbcabbbbbaccccccbcbcbcbbccbaaabbbbcabacabccaacbcbcbabccbbcabacababccaab',
  'bccaacbabcbccaccbabcbbcbaaccbaacabbcabbbacbbccabcabccabccbacbaacbccabccaabaaabcaababacacccaac',
  'aacabcccaaccacbbcbbbbacaacacbcbcaabbcbbacbabcbccaabcbbbbaabccbbbacaababcabaacaccababacbcbccbba',
  'caaabbcbcbcabccccacacaaababbacbabacbaaccbcbabbaaacbbccccaaaabbccbcabcbccbbaaccbbbabcaabcbbbcab',
  'aacbbcbbcbaccccbaaaabcbaaabaaacaacaaacacacabaaabacbaaaacccbaaabbbcbbbacbcbccabccaabbaabcbcbccba',
  'abaccbcacabbbbacabaacaccbcbaabbaccaabbbbbababbbcbbbbacaacabbbabcaccbacabbabcbbacbbaaccbcbacaabc',
  'aacaaaacccabcccacacbaaccccababcaccaccacbbbacabccbbcbbbacaccbbbbbaabacbacbcbcabccaaccababacaabcbb',
  'baabbabaaccabcbbabcacccccaabbccbccbcaacbbbccccbbcbacaabcccccbbabbabbcacbbccbcacabbbbaaaaccbcacca',
  'aabacbaacbbccabbbacbcbbbabacaacccabbcabacacaaaabbcbbbcbbbcababbccbbacbbabcaacbacbbcaabbbcbaaaccaa',
  'aacabaaccaaabcacccabbaabbcacbabccacabaccaaaaccccccaabcbbbaabcbcccacaccbcaaacaaaabaababccbbbcccaac',
  'bcaccbcacaccbacbcccbcbbcabaabbabcccbaaababbbabbcbcbcaabbabbccccbabccabbccccabaaabccbacabccabbbacaa',
  'ccaacbabcccbabacabaccccbcbbcccbbbacbbbcccacababccbbaaaaababbabccbccabcccbccabaccbcbcacbbbaacabccaa',
  'caccbababcbcbabccabcbbaccbbbabcbacbcbcbcabcbacbcacabbcaabbbbbbbcbbaabcacccbcaabccacbccbbcccaabcbcac',
  'bbcccaabacbacbccbbbbbaabccaaabbaabcaabbcbabbbaabcbcbacbaccabacacaaaababccaaaccacaabaabcacbcaccbaabb'
];
var call = 0;

function guess(S, len) {
  var sym = {};
  recurse(S, len, "", sym);
  return sym.result;
}

function recurse(S, len, s, sym) {
  var dictionary = [];

  if(s == '' || (isCandidate(s, sym) && (sym[s] = numOccur(S, s)))) {
    if(s.length == len) {
      sym.result = s;
    }
    else if(sym['a'] && count(s, 'a') == sym['a'] - (len - s.length)) {
      dictionary = [ Array(len - s.length + 1).join('a') ];
    }
    else {
      dictionary = [ "a", "b", "c" ];
    }
    dictionary.some(function(e) {
      return recurse(S, len, s + e, sym) || recurse(S, len, e + s, sym);
    });
    return true;
  }
  return false;
}

function isCandidate(s, sym) {
  return sym[s] === undefined && Object.keys(sym).every(function(k) {
    return count(s, k) <= sym[k];
  });
}

function count(s0, s1) {
  return (s0.match(new RegExp(s1, 'g')) || []).length;
}

function numOccur(S, s) {
  call++;
  return count(S, s);
}

test.forEach(function(S) {
  if(guess(S, S.length) != S) {
    console.log("Failed for: '" + S + "'");
  }
});
console.log(call + " calls");


问:
All in all it's just, uh, another trick in code golf
The purpose of this challenge is to produce an ASCII version of the cover of this great album by the rock band Pink Floyd.

The brick junctions are made of characters _ and |. Bricks have width 7 and height 2 characters, excluding junctions. So the basic unit, including the junctions, is:

```<code>_________
|       |
|       |
_________
</code>```

Each row of bricks is offset by half a brick width (4 chars) with respect to the previous row:

```<code>________________________________________
  |       |       |       |       |
  |       |       |       |       |
________________________________________
      |       |       |       |       |
      |       |       |       |       |
________________________________________
  |       |       |       |       |
  |       |       |       |       |
</code>```

The wall is parameterized as follows. All parameters are measured in chars including junctions:

Horizontal offset of first row, F. This is the distance between the left margin and the first vertical junction of the upmost row. (Remember also the half-brick relative offset between rows). Its possible values are 0, 1, ..., 7.

Total width, W. This includes junctions. Its value is a positive integer.

Total height, H. This includes junctions. Its value is a positive integer.

The top of the wall always coincides with the top of a row. The bottom may be ragged (if the total height is not a multiple of 3). For example, here's the output for 6, 44, 11:

```<code>____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
</code>```

and a visual explanation of parameters:

```<code>          F=6
         ......
     .   ____________________________________________
     .         |       |       |       |       |
     .         |       |       |       |       |
     .   ____________________________________________
     .     |       |       |       |       |       |
H=11 .     |       |       |       |       |       |
     .   ____________________________________________
     .         |       |       |       |       |
     .         |       |       |       |       |
     .   ____________________________________________
     .     |       |       |       |       |       |

         ............................................
                             W=44
</code>```

Additional rules

You may provide a program or a function.

Input format is flexible as usual. Output may be through STDOUT or an argument returned by a function. In this case it may be a string with newlines or an array of strings.

Trailing spaces or newlines are allowed.

Shortest code in bytes wins.

Test cases

Inputs are in the order given above, that is: horizontal offset of first row, total width, total height.

```<code>6, 44, 11:
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |

2, 20, 10:
____________________
  |       |       |
  |       |       |
____________________
      |       |
      |       |
____________________
  |       |       |
  |       |       |
____________________

1, 1, 1:
_

1, 2, 3:
__
 |
 |

3, 80, 21:
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
</code>```

答:
Java, <s>149</s>, <s>147</s>, <s>146</s>, 143 bytes

Golfed:

String f(int o,int w,int h){String s="";for(int y=0,x;y<h;++y){for(x=0;x<w;++x){s+=y%3>0?(x-o+(y-1)/3%2*4)%8==0?'|':' ':'_';}s+='\n';}return s;}
```

<p>Ungolfed:</p>

<pre class="lang-java prettyprint-override"><code>public class AllInAllItsJustUhAnotherTrickInCodeGolf {

  public static void main(String[] args) {
    int offset = 6;
    int width = 44;
    int height = 11;
    System.out.println(new AllInAllItsJustUhAnotherTrickInCodeGolf()
        .f(offset, width, height));
  }

  // Begin golf
  String f(int o, int w, int h) {
    String s = "";
    for (int y = 0, x; y < h; ++y) {
      for (x = 0; x < w; ++x) {
        s += y % 3 > 0 ? (x - o + (y - 1) / 3 % 2 * 4) % 8 == 0 ? '|' : ' ' : '_';
      }
      s += '\n';
    }
    return s;
  }
  // End golf

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Java, <s>149</s>, <s>147</s>, <s>146</s>, 143 bytes

Golfed:

String f(int o,int w,int h){String s="";for(int y=0,x;y<h;++y){for(x=0;x<w;++x){s+=y%3>0?(x-o+(y-1)/3%2*4)%8==0?'|':' ':'_';}s+='\n';}return s;}

Ungolfed:

public class AllInAllItsJustUhAnotherTrickInCodeGolf {

  public static void main(String[] args) {
    int offset = 6;
    int width = 44;
    int height = 11;
    System.out.println(new AllInAllItsJustUhAnotherTrickInCodeGolf()
        .f(offset, width, height));
  }

  // Begin golf
  String f(int o, int w, int h) {
    String s = "";
    for (int y = 0, x; y < h; ++y) {
      for (x = 0; x < w; ++x) {
        s += y % 3 > 0 ? (x - o + (y - 1) / 3 % 2 * 4) % 8 == 0 ? '|' : ' ' : '_';
      }
      s += '\n';
    }
    return s;
  }
  // End golf

}


答:
ASM: 10 bytes

```<code>3C 40 77 04 2C 40 EB 02 04 40
</code>```

Explanation:
This is the assembled representation of a program that does exactly what is asked. It is not fully functional, because it needs some directives, but if it is added to the code segment of an assembly program it should work. It receives the input in the AL register, and if its a letter it subtracts 40h from the ASCII code value, leaving just the number(i.e B=42h, 42h-40h=2h). If the input is a number it does the opposite procedure by adding 40h. It leaves the result in the AL register. Below is the assembly source code

```<code>cmp al,40h
ja letter_to_number
sub al,40h
jmp continue
letter_to_number: add ax,40h
continue:
</code>```

Also,  if you convert all the other answers to machine code, I am positive that mine would be the smallest.

Title: Alphabet to Number and Number to Alphabet

Body:
Challenge

In this challenge you have to take a number as input and output the corresponding letter of the alphabet, and vice versa. (1 <=> A, 2 <=> B) etc.

```<code>1 -> A
2 -> B
...
26 -> Z

A -> 1
B -> 2
...
Z -> 26
</code>```

Rules

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

The input will only consist of either an uppercase letter from A to Z or an integer from 1 to 26 inclusive.

Trailing whitespaces (space and newline) are allowed.

Body:
ASM: 10 bytes

3C 40 77 04 2C 40 EB 02 04 40

Explanation:
This is the assembled representation of a program that does exactly what is asked. It is not fully functional, because it needs some directives, but if it is added to the code segment of an assembly program it should work. It receives the input in the AL register, and if its a letter it subtracts 40h from the ASCII code value, leaving just the number(i.e B=42h, 42h-40h=2h). If the input is a number it does the opposite procedure by adding 40h. It leaves the result in the AL register. Below is the assembly source code

cmp al,40h
ja letter_to_number
sub al,40h
jmp continue
letter_to_number: add ax,40h
continue:

Also,  if you convert all the other answers to machine code, I am positive that mine would be the smallest.


答:
SQF, 72 bytes

Using the function-as-a-file format:

```<code>i=_this;if((str i)==i)then{toString[i+64]}else{((toArray i)select 0)-64}
</code>```

Call as: ARG call NAME_OF_COMPILED_FUNCTION

Body:
SQF, 72 bytes

Using the function-as-a-file format:

i=_this;if((str i)==i)then{toString[i+64]}else{((toArray i)select 0)-64}

Call as: ARG call NAME_OF_COMPILED_FUNCTION


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

答:
Perl 5 - 130 bytes

```<code>sub z{$_[0]=~y/<//c}
sub d{$_=$_[0];{s/><//&&redo}-1+z$_}
sub b{()=$_[0]=~/<>/g}
sub g{(grep{$_[0]=~/<(<(?1)*>){$_}>/}0..z$_)[-1]}
</code>```

These take input as a string using angle brackets (e.g. <<><>>). z (size) and b (breadth) count the substrings for either all nodes or leafs, d (depth) collapses adjacent nodes until there's no branching then gets the size, and g (degree) uses a recursive regex to test for the presence of nodes of each degree up to the size then returns the largest found.

Title: Show off your tree analysing toolbox

Body:
Perl 5 - 130 bytes

sub z{$_[0]=~y/<//c}
sub d{$_=$_[0];{s/><//&&redo}-1+z$_}
sub b{()=$_[0]=~/<>/g}
sub g{(grep{$_[0]=~/<(<(?1)*>){$_}>/}0..z$_)[-1]}

These take input as a string using angle brackets (e.g. <<><>>). z (size) and b (breadth) count the substrings for either all nodes or leafs, d (depth) collapses adjacent nodes until there's no branching then gets the size, and g (degree) uses a recursive regex to test for the presence of nodes of each degree up to the size then returns the largest found.


问:
Tips for golfing in vim
I've recently realized how vim works great for golfing, especially for kolmogorov-complexity. Also, according to meta vim is a perfectly acceptable 'programming language' at least, for the scope of this site, that is.

What general tips do you have for golfing in Vim? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Vim (e.g. "remove comments" is not an answer).

Please post one tip per answer.

答:
There are three "change case" operators,

```<code>gu    "Convert to lowercase
gU    "Convert to uppercase
g~    "Toggle case
</code>```

Since these are operators, they take a motion, so to convert the current character to lowercase you would use

```<code>gul
</code>```

Here's where the fun trick comes in. :) If you want to change the case of a single character or the current line, it's a byte shorter in visual mode. For example gul is equivalent to

```<code>vu
</code>```

And gu_ (_ is current line) is equivalent to

```<code>Vu
</code>```

This trick does not work for toggling, because v? triggers a backwards search in visual mode, (just like v/ but moving in the opposite direction) so you need vg? instead. However, here's where you can use the ~ operator, to save even more bytes! (Thanks @Doorknob for pointing this out)

You can see this trick in action on my vim answer here, and on the equivalent V answer on the and post.

Title: Tips for golfing in vim

Body:
There are three "change case" operators,

gu    "Convert to lowercase
gU    "Convert to uppercase
g~    "Toggle case

Since these are operators, they take a motion, so to convert the current character to lowercase you would use

gul

Here's where the fun trick comes in. :) If you want to change the case of a single character or the current line, it's a byte shorter in visual mode. For example gul is equivalent to

vu

And gu_ (_ is current line) is equivalent to

Vu

This trick does not work for toggling, because v? triggers a backwards search in visual mode, (just like v/ but moving in the opposite direction) so you need vg? instead. However, here's where you can use the ~ operator, to save even more bytes! (Thanks @Doorknob for pointing this out)

You can see this trick in action on my vim answer here, and on the equivalent V answer on the and post.


答:
Retina, 30 bytes

```<code>.+
$*1;
+`(1+)\1
$1;
1;
1
;+
0
</code>```

Try it online!

And here I thought Retina would be amongst the first answers...

Title: Output "Fit" numbers

Body:
"Fit Numbers"

Sam has a "brilliant" idea for compression! Can you help?

Here is a rundown of Sam's compression scheme. First take in a base 10 representation of any natural number strictly smaller than 2^16, and write it as a binary string without any leading zeros.

```
1 -> 1
9 -> 1001
15 ->1111
13 ->1101
16 -> 10000
17 -> 10001
65535 -> 111111111111111
```

Now replace any group of one or more zeros with a single zero. This is because the number has gotten leaner. Your binary string now will look like this.

```
1 -> 1 -> 1
9 -> 1001 -> 101
15 ->1111 -> 1111
13 ->1101 -> 1101
16 -> 10000 -> 10
17 -> 10001 -> 101
65535 -> 111111111111111 -> 111111111111111
```

Now you convert the binary string back to a base 10 representation, and output it in any acceptable format. Here are your test cases. The first integer represents an input, and the last integer represents an output. Note that some numbers do not change, and thus can be called "fit"

```
1 -> 1 -> 1 -> 1
9 -> 1001 -> 101 -> 5
15 ->1111 -> 1111 -> 15
13 ->1101 -> 1101 -> 13
16 -> 10000 -> 10 -> 2
17 -> 10001 -> 101 -> 5
65535 -> 1111111111111111 -> 1111111111111111 -> 65535
65000 -> 1111110111101000 -> 11111101111010 -> 16250
```

You may use any language, but please note that Sam hates standard loopholes. This is code golf so the code can be as short as possible to make room for the "compressed" numbers".

Note:This is NOT an acceptable compression scheme. Using this will promptly get you fired.

Citation-Needed: I do not take credit for this concept. This comes from @Conor O' Brien's blog here see this OEIS of fit numbers. https://oeis.org/A090078

Body:
Retina, 30 bytes

.+
$*1;
+`(1+)\1
$1;
1;
1
;+
0

Try it online!

And here I thought Retina would be amongst the first answers...


答:
cat/type/PHP 1

This is actually polyglot. It runs in cat (or Microsoft Cat called type) and PHP.

```<code>$ xxd file
0000000: 07                                       .
</code>```

Execution:

```<code>$ xxd -r > file
0000000: 07                                       .
^D
$ cat file # cat could be replaced with type (on Windows) or with php
</code>```

Title: Play a sound, any sound

Body:
Your program has to make the computer produce a sound, any sound.

Shortest code wins, not sooner than 10 days after the first valid answer. If there is a tie, the one submitted sooner, wins.

The program should run on a reasonable, not too uncommon personal computer.

Opening a pop-up, message box, etc. (for example, on a web page) does not count, as they might or might not produce a sound, depending on a lot of settings.

Just entering a wrong command or invalid character on a console and receiving a warning beep does not count, just as the compiler/interpreter/OS beeping on an error or crash does not count either. Your code must be a valid program.

Body:
cat/type/PHP 1

This is actually polyglot. It runs in cat (or Microsoft Cat called type) and PHP.

$ xxd file
0000000: 07                                       .

Execution:

$ xxd -r > file
0000000: 07                                       .
^D
$ cat file # cat could be replaced with type (on Windows) or with php


问:
Input ∩ Source Code

Intro

The challenge is to create a program/function that prints the intersection of its own source code and a given string input. This is code golf and to be more precise:

Let I be the input set

{"a","b","c"}

Let S be the source code set

{"b","f"}

Then the intersection is what they share

I ∩ S = {"b"}

Input

Input is flexible. It should be able to handle the character encoding used for the source code.

Output

Output is flexible. It should be the set of characters that the input and source code share. Also, sets are unordered collections of distinct objects. In summary:

Output is flexible:

Could be any data structure (string or otherwise)

Could unordered

Could have a trailing \n

Should be distinct

Restriction

Similar to quine challenges, the program/function may not read its own source code and 0-byte solutions are not allowed.

Examples

#1

```<code>functor x(I){ return I ∩ self; }

Inputs                                Outputs
------                                -------
enter preformatted text here      ->  {"e","n","t","r","f","o","x"}

["Albrt"," Einstin"]              ->  {"l","r","t","n","s"}
</code>```

#2

```<code>(_)->_&"(_)->&\"\\"

Inputs                                Outputs
------                                -------
"Security at the expense of       ->  "
usability comes at the expense
of security."

(0____0)                          ->  (_)
</code>```

#3

```<code>ಠa益длф

Inputs                                Outputs
------                                -------
Far out in the uncharted backwaters ->"a"
of the unfashionable end of the
Western Spiral arm of the Galaxy lies
a small unregarded yellow sun.
Orbiting this at a distance of roughly
ninety-eight million miles is an
utterly insignificant little blue-green
planet whose ape-descended life forms
are so amazingly primitive that they
still think digital watches are a pretty
neat idea.

(ノಠ益ಠ)ノ彡┻━┻                      ->"ಠ益"
</code>```

Test Cases

```<code>Albert Einstein

\__( O__O)_/

!@#$%^&*()_+{}|:"<>?

1234567890-=[]\;',./

(ノಠ益ಠ)ノ彡┻━┻

“¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶”

┬──┬ ノ( ゜-゜ノ)

Far out in the uncharted backwaters of the unfashionable end of the Western Spiral arm of the Galaxy lies a small unregarded yellow sun. Orbiting this at a distance of roughly ninety-eight million miles is an utterly insignificant little blue-green planet whose ape-descended life forms are so amazingly primitive that they still think digital watches are a pretty neat idea.
</code>```

Update

[16-08-10]: sets are unordered collections of distinct objects

[16-08-10]: trailing newline is acceptable

答:
Vim, <s>78 68 78 79</s> 61 keystrokes

Completely changed my approach:

```<code>oo/\$kjxd<esc>/o<cr>xj$/\/<cr>xj$/\\<cr>xj$/$<cr>xj$/k<cr>xj$/x<cr>xj$/j<cr>xj$/d<cr>xkdd
</code>```

How it works:

First, it makes a line with all the program characters, then, it finds the first instance of each of the program characters, which is either in the input, if the input and output intersect, or the output if they don't, deletes it, moves to the last character of the file (so it wraps around) and does that for each unique character in source, except d, where instead of moving to the end of the file, it finishes up by deleting the input

Title: Input ∩ Source Code

Body:
Vim, <s>78 68 78 79</s> 61 keystrokes

Completely changed my approach:

oo/\$kjxd<esc>/o<cr>xj$/\/<cr>xj$/\\<cr>xj$/$<cr>xj$/k<cr>xj$/x<cr>xj$/j<cr>xj$/d<cr>xkdd

How it works:

First, it makes a line with all the program characters, then, it finds the first instance of each of the program characters, which is either in the input, if the input and output intersect, or the output if they don't, deletes it, moves to the last character of the file (so it wraps around) and does that for each unique character in source, except d, where instead of moving to the end of the file, it finishes up by deleting the input


答:
Ruby, <s>8x8</s> 7x7

```<code> print(
 (?f+"\
 "*6+?\
 )*6).!
 $><<"\
 f"<<!1
;
</code>```

Output:

```<code>f
f
f
f
f
f
 ffalse
</code>```

Previous version, 8x8 with 20 spaces:

```<code>  puts((
  "ff"+#
  ?\s*6+
  ?\n)*7
  );$><<
  ?\s*2+
  ?f;p:p
.!
</code>```

Output:

```<code>ff
ff
ff
ff
ff
ff
ff
  ffalse
</code>```

Title: Print a Negative of your Code

Body:
Consider a square of printable ASCII characters (code points 0x20 to 0x7E) for side length N, like the following (here, N = 6):

```<code>=\
 g \
7
m+y "g
  L ~
e> PHq
</code>```

We also require each row and each column to contain at least 1 space and 1 non-space character. (The above example satisfies this.)

We define the negative of such a square, to be a square of the same size, where each space is replaced with a non-space and vice versa. E.g., the following would be a valid negative of the above example:

```<code>  1234
a b cd
 ZYXWV
   !
{} [ ]
  ?
</code>```

The choice of non-space characters is irrelevant (as long as they are from the printable ASCII range).

The Challenge

You're to write a program, with square source code with side length N > 1, which prints a negative of itself to STDOUT. Trailing spaces have to be printed. You may or may not print a single trailing newline.

The usual quine rules also apply, so you must not read your own source code, directly or indirectly. Likewise, you must not assume a REPL environment, which automatically prints the value of each entered expression.

The winner is the program with the lowest side length N. In the event of a tie, the submission with the fewest non-space characters in the source code wins. If there's still a tie, the earliest answer wins.

Body:
Ruby, <s>8x8</s> 7x7

 print(
 (?f+"\
 "*6+?\
 )*6).!
 $><<"\
 f"<<!1
;

Output:

f
f
f
f
f
f
 ffalse

Previous version, 8x8 with 20 spaces:

  puts((
  "ff"+#
  ?\s*6+
  ?\n)*7
  );$><<
  ?\s*2+
  ?f;p:p
.!

Output:

ff
ff
ff
ff
ff
ff
ff
  ffalse


答:
Mathematica, 77 bytes

```<code>s=LeafCount
d=Depth@#-2&
b=Length@Level[#,{-2}]&
g=Max[Length@#,##&@@#]&//@#&
</code>```

Take any Mathematica expression as input.

Title: Show off your tree analysing toolbox

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

Body:
Mathematica, 77 bytes

s=LeafCount
d=Depth@#-2&
b=Length@Level[#,{-2}]&
g=Max[Length@#,##&@@#]&//@#&

Take any Mathematica expression as input.


答:
Jelly, <s>13</s> 7 bytes

6 bytes thanks to Zgarb for his algorithm.

```
<s>BŒgµL*x@Ḣµ€FḄ</s>
BŒgḄBFḄ
```

Try it online!

Title: Output "Fit" numbers

Body:
Jelly, <s>13</s> 7 bytes

6 bytes thanks to Zgarb for his algorithm.

<s>BŒgµL*x@Ḣµ€FḄ</s>
BŒgḄBFḄ

Try it online!


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

答:
Pip, 8 bytes

```<code>(zr*r*h)
</code>```

z is a built-in for the lowercase alphabet, h for 100. r is a special variable: each time it is evaluated, it generates a random number with uniform distribution, 0 <= r < 1. Thus, r*r*h squares the uniform distribution and scales it a hundredfold (saving a character over using 26). The result is used to index into z, auto-truncated and with index wrapping.

Try it here (frequency chart of 100,000 runs, takes about 30 seconds).

Body:
Pip, 8 bytes

(zr*r*h)

z is a built-in for the lowercase alphabet, h for 100. r is a special variable: each time it is evaluated, it generates a random number with uniform distribution, 0 <= r < 1. Thus, r*r*h squares the uniform distribution and scales it a hundredfold (saving a character over using 26). The result is used to index into z, auto-truncated and with index wrapping.

Try it here (frequency chart of 100,000 runs, takes about 30 seconds).


答:
Java, 61 bytes

```<code>int f(char c){return c^64;}char f(int i){return(char)(i^64);}
</code>```

Ungolf'd:

```<code>int f(char c) {
    return c^64;
}

char f(int i) {
    return (char) (i^64);
}
</code>```

Calling f('A') invokes the first function, retuning an int 1;  calling f(1) invokes the second function, returning the char "A".

Body:
Java, 61 bytes

int f(char c){return c^64;}char f(int i){return(char)(i^64);}

Ungolf'd:

int f(char c) {
    return c^64;
}

char f(int i) {
    return (char) (i^64);
}

Calling f('A') invokes the first function, retuning an int 1;  calling f(1) invokes the second function, returning the char "A".


问:
Convert from base 10 to base 2 without built-in base conversions
Background:

You have been given an assignment to convert base 10 numbers to base 2 without using any premade base conversion functions. You can't use any imported libraries either.

Problem:

Convert an input string from base 10 (decimal) to base 2 (binary). You may not use any premade base conversion code/functions/methods, or imported libraries. Since this is code-golf, the shortest answer in bytes will win.

Input will be anything from -32768 to 32767 (include sign byte handling in your code)

答:
Dyalog APL, 11 bytes

2|⌊⎕÷2*⌽⍳16
```

2| The division remainder when halved of

⌊ the rounded down value of

⎕ the input

÷ divided by each of

2* two to the power of each of

⍳16 {0, 1, 2, ..., 15}

Requires ⎕IO←0 which is default on many systems.

TryAPL online!

Body:
Dyalog APL, 11 bytes

2|⌊⎕÷2*⌽⍳16

2| The division remainder when halved of

⌊ the rounded down value of

⎕ the input

÷ divided by each of

2* two to the power of each of

⍳16 {0, 1, 2, ..., 15}

Requires ⎕IO←0 which is default on many systems.

TryAPL online!


答:
Dyalog APL, 19 bytes

{2⊥⍵/⍨~0 0⍷⍵}2∘⊥⍣¯1
```

TryAPL online!

This function is really an "atop" of two functions, the first function is:

2∘⊥⍣¯1 the inverse of binary-to-decimal conversion, i.e. binary-from-decimal conversion

 two 2 is bound ∘ to -to-decimal ⊥

 repeat the operation ⍣ negative one time ¯1 (i.e. once, but inverted)

In the second function, the above's binary result is represented by ⍵:

{2⊥⍵/⍨~0 0⍷⍵}

 0 0⍷⍵ Boolean for where {0, 0} begins in ⍵

 ~ Boolean negation, so now we have ᴛʀᴜᴇ everywhere but at non-first zeros in zero-runs

 ⍵/⍨ use that to filter ⍵, so this removes our unwanted zeros

 2⊥ convert binary-to-decimal

Title: Output "Fit" numbers

Body:
Dyalog APL, 19 bytes

{2⊥⍵/⍨~0 0⍷⍵}2∘⊥⍣¯1

TryAPL online!

This function is really an "atop" of two functions, the first function is:

2∘⊥⍣¯1 the inverse of binary-to-decimal conversion, i.e. binary-from-decimal conversion

 two 2 is bound ∘ to -to-decimal ⊥

 repeat the operation ⍣ negative one time ¯1 (i.e. once, but inverted)

In the second function, the above's binary result is represented by ⍵:

{2⊥⍵/⍨~0 0⍷⍵}

 0 0⍷⍵ Boolean for where {0, 0} begins in ⍵

 ~ Boolean negation, so now we have ᴛʀᴜᴇ everywhere but at non-first zeros in zero-runs

 ⍵/⍨ use that to filter ⍵, so this removes our unwanted zeros

 2⊥ convert binary-to-decimal


答:
C: 19

```<code>main(){puts("\a");}
</code>```

edit: header file is not needed for "puts"

Title: Play a sound, any sound

Body:
C: 19

main(){puts("\a");}

edit: header file is not needed for "puts"


问:
Permutapalindromic numbers
Given an integer N as input, output the Nth permutapalindromic number.

A permutapalindromic number is a strictly positive integer such that there is at least one permutation of its digits that results in a palindrome (i.e. a number that is its own reverse).

For example, 117 is a permutapalindromic number since its digits can be permuted into 171, which is a palindrome.

We consider that numbers like 10 are not permutapalindromic numbers, even though 01 = 1 is a palindrome. We impose that the palindromic permutation must not have a leading zero (as such, 0 itself is not permutapalindromic).

Numbers that are already palindromes are also permutapalindromic, since permuting nothing is valid.

Inputs and outputs

N may be either 0-indexed or 1-indexed. Please indicate which of the two your answer uses.

The input can be taken through STDIN, as a function argument, or anything similar in your language of choice. The output can be written to STDOUT, returned from a function, or anything similar in your language of choice.

The input and output must be in the decimal base.

Test cases

The following test cases are 1-indexed. Your program must be able to pass any of the test cases presented here in at most 1 minute.

```<code>N      Output

1      1
2      2
3      3
4      4
5      5
6      6
7      7
8      8
9      9
10     11
42     181
100    404
128    511
256    994
270    1166
</code>```

Scoring

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

答:
Brachylog, <s>21</s> 20 bytes

1 byte thanks to Fatalize.

Did you design the challenge for Brachylog?

```<code>:1yt.
0<.={@epcPrP!}
</code>```

Try it online!

270 takes about half a minute here.

```<code>Z = 1166
real    0m27.066s
user    0m26.983s
sys     0m0.030s

Exit code:     0
</code>```

Predicate 0 (main predicate)

```<code>:1yt.
:1y    find the first Input solutions to predicate 1
   t.  unify the output with the last element
</code>```

Predicate 1 (auxiliary predicate)

```<code>0<.={@epcPrP!}
0<.              0 < Output
  .=             Assign a value to Output (choice point)
    {        }   Inline predicate:
     @e              Digits of the Output
       p             A permutation (choice point)
        c            Concatenate (fails if leading zero present)
         P           store as P
          rP         assert that P reversed is still P
            !        remove the choice point in this predicate, so
                     that it will not return twice for the same number.
</code>```

Title: Permutapalindromic numbers

Body:
Brachylog, <s>21</s> 20 bytes

1 byte thanks to Fatalize.

Did you design the challenge for Brachylog?

:1yt.
0<.={@epcPrP!}

Try it online!

270 takes about half a minute here.

Z = 1166
real    0m27.066s
user    0m26.983s
sys     0m0.030s

Exit code:     0

Predicate 0 (main predicate)

:1yt.
:1y    find the first Input solutions to predicate 1
   t.  unify the output with the last element

Predicate 1 (auxiliary predicate)

0<.={@epcPrP!}
0<.              0 < Output
  .=             Assign a value to Output (choice point)
    {        }   Inline predicate:
     @e              Digits of the Output
       p             A permutation (choice point)
        c            Concatenate (fails if leading zero present)
         P           store as P
          rP         assert that P reversed is still P
            !        remove the choice point in this predicate, so
                     that it will not return twice for the same number.


答:
Ruby, 72 66 bytes

```<code>->f,w,h{h.times{|i|puts i%3<1??_*w:((?|+' '*7)*w)[8-f+i%6/4*4,w]}}
</code>```

Thanks @Value Ink for 6 bytes!

Simple string multiplication and slicing.

Works in Ruby 2.3.0 (Ideone's version 2.1 threw syntax error).

Title: All in all it's just, uh, another trick in code golf

Body:
The purpose of this challenge is to produce an ASCII version of the cover of this great album by the rock band Pink Floyd.

The brick junctions are made of characters _ and |. Bricks have width 7 and height 2 characters, excluding junctions. So the basic unit, including the junctions, is:

```<code>_________
|       |
|       |
_________
</code>```

Each row of bricks is offset by half a brick width (4 chars) with respect to the previous row:

```<code>________________________________________
  |       |       |       |       |
  |       |       |       |       |
________________________________________
      |       |       |       |       |
      |       |       |       |       |
________________________________________
  |       |       |       |       |
  |       |       |       |       |
</code>```

The wall is parameterized as follows. All parameters are measured in chars including junctions:

Horizontal offset of first row, F. This is the distance between the left margin and the first vertical junction of the upmost row. (Remember also the half-brick relative offset between rows). Its possible values are 0, 1, ..., 7.

Total width, W. This includes junctions. Its value is a positive integer.

Total height, H. This includes junctions. Its value is a positive integer.

The top of the wall always coincides with the top of a row. The bottom may be ragged (if the total height is not a multiple of 3). For example, here's the output for 6, 44, 11:

```<code>____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
</code>```

and a visual explanation of parameters:

```<code>          F=6
         ......
     .   ____________________________________________
     .         |       |       |       |       |
     .         |       |       |       |       |
     .   ____________________________________________
     .     |       |       |       |       |       |
H=11 .     |       |       |       |       |       |
     .   ____________________________________________
     .         |       |       |       |       |
     .         |       |       |       |       |
     .   ____________________________________________
     .     |       |       |       |       |       |

         ............................................
                             W=44
</code>```

Additional rules

You may provide a program or a function.

Input format is flexible as usual. Output may be through STDOUT or an argument returned by a function. In this case it may be a string with newlines or an array of strings.

Trailing spaces or newlines are allowed.

Shortest code in bytes wins.

Test cases

Inputs are in the order given above, that is: horizontal offset of first row, total width, total height.

```<code>6, 44, 11:
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |
  |       |       |       |       |       |
____________________________________________
      |       |       |       |       |
      |       |       |       |       |
____________________________________________
  |       |       |       |       |       |

2, 20, 10:
____________________
  |       |       |
  |       |       |
____________________
      |       |
      |       |
____________________
  |       |       |
  |       |       |
____________________

1, 1, 1:
_

1, 2, 3:
__
 |
 |

3, 80, 21:
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
       |       |       |       |       |       |       |       |       |       |
       |       |       |       |       |       |       |       |       |       |
________________________________________________________________________________
   |       |       |       |       |       |       |       |       |       |
   |       |       |       |       |       |       |       |       |       |
</code>```

Body:
Ruby, 72 66 bytes

->f,w,h{h.times{|i|puts i%3<1??_*w:((?|+' '*7)*w)[8-f+i%6/4*4,w]}}

Thanks @Value Ink for 6 bytes!

Simple string multiplication and slicing.

Works in Ruby 2.3.0 (Ideone's version 2.1 threw syntax error).


答:
Brachylog, 19 bytes

```<code>~l<:1at.
.=pPrPl~l?
</code>```

Try it online!

Takes about 17 seconds for N = 270.

Explanation

Main predicate:

```<code>~l            Create a list whose length is Input.
  <           The list is strictly increasing.
   :1a        Apply predicate 1 to each element of the list.
      t.      Output is the last element of the list.
</code>```

Predicate 1:

```<code>.=            Input = Output = an integer
  pPrP        A permutation P of the Output is its own reverse
      l~l?    The length of P is equal to the length of the Input
</code>```

Title: Permutapalindromic numbers

Body:
Given an integer N as input, output the Nth permutapalindromic number.

A permutapalindromic number is a strictly positive integer such that there is at least one permutation of its digits that results in a palindrome (i.e. a number that is its own reverse).

For example, 117 is a permutapalindromic number since its digits can be permuted into 171, which is a palindrome.

We consider that numbers like 10 are not permutapalindromic numbers, even though 01 = 1 is a palindrome. We impose that the palindromic permutation must not have a leading zero (as such, 0 itself is not permutapalindromic).

Numbers that are already palindromes are also permutapalindromic, since permuting nothing is valid.

Inputs and outputs

N may be either 0-indexed or 1-indexed. Please indicate which of the two your answer uses.

The input can be taken through STDIN, as a function argument, or anything similar in your language of choice. The output can be written to STDOUT, returned from a function, or anything similar in your language of choice.

The input and output must be in the decimal base.

Test cases

The following test cases are 1-indexed. Your program must be able to pass any of the test cases presented here in at most 1 minute.

```<code>N      Output

1      1
2      2
3      3
4      4
5      5
6      6
7      7
8      8
9      9
10     11
42     181
100    404
128    511
256    994
270    1166
</code>```

Scoring

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

Body:
Brachylog, 19 bytes

~l<:1at.
.=pPrPl~l?

Try it online!

Takes about 17 seconds for N = 270.

Explanation

Main predicate:

~l            Create a list whose length is Input.
  <           The list is strictly increasing.
   :1a        Apply predicate 1 to each element of the list.
      t.      Output is the last element of the list.

Predicate 1:

.=            Input = Output = an integer
  pPrP        A permutation P of the Output is its own reverse
      l~l?    The length of P is equal to the length of the Input


答:
Dyalog APL, 51 bytes

One-indexed.

{⍵⊃{⍵/⍨{(⍵≤9)∨(1<≢c~'0')∧1≥+/2|+⌿c∘.=∪c←⍕⍵}¨⍵}⍳5×⍵}
```

{ a function where ⍵ represents the argument

⍵⊃{ use the argument to pick from the result of the function

⍵/⍨{ filter the argument with the result of the function

(⍵≤9)∨ the argument is less or equal to 9, OR

(1<≢c~'0')∧ there remains more than one digit when zeros are removed AND

1≥+/ 0 or 1 is the sum of

2| the oddnesses of

+⌿ of the column sums of

c∘.=∪c the comparison table of c and the unique elements of c, where c...

←⍕⍵ is the string representation of the argument

}¨⍵ applied to each of the arguments

}⍳5×⍵ applied to {1, 2, 3, ..., 5 times the argument}

} [end of function]

Finishes all the test cases instantly on TryAPL

Title: Permutapalindromic numbers

Body:
Dyalog APL, 51 bytes

One-indexed.

{⍵⊃{⍵/⍨{(⍵≤9)∨(1<≢c~'0')∧1≥+/2|+⌿c∘.=∪c←⍕⍵}¨⍵}⍳5×⍵}

{ a function where ⍵ represents the argument

⍵⊃{ use the argument to pick from the result of the function

⍵/⍨{ filter the argument with the result of the function

(⍵≤9)∨ the argument is less or equal to 9, OR

(1<≢c~'0')∧ there remains more than one digit when zeros are removed AND

1≥+/ 0 or 1 is the sum of

2| the oddnesses of

+⌿ of the column sums of

c∘.=∪c the comparison table of c and the unique elements of c, where c...

←⍕⍵ is the string representation of the argument

}¨⍵ applied to each of the arguments

}⍳5×⍵ applied to {1, 2, 3, ..., 5 times the argument}

} [end of function]

Finishes all the test cases instantly on TryAPL


问:
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, 97 95 bytes

```<code>t=rjson::fromJSON(f="http://www.medalbot.com/api/v1/medals")
for(i in 1:3)cat(t[[c(i,2)]],"\n")
</code>```

Little improvement over user5957401's answer, no sorting required, and shorter library name.
Also my first attempt at golfing ;)

Title: Quick Golf: The Gold Leader

Body:
R, 97 95 bytes

t=rjson::fromJSON(f="http://www.medalbot.com/api/v1/medals")
for(i in 1:3)cat(t[[c(i,2)]],"\n")

Little improvement over user5957401's answer, no sorting required, and shorter library name.
Also my first attempt at golfing ;)