答:
Ruby, <s>405</s> <s>403</s> <s>401</s> 400 bytes

A wise man (Jamie Zawinski) once said, "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems."

I don't think I fully appreciated that quote until I tried to solve this problem with recursive regex. Initially, the regex cases seemed simple, until I had to deal with the edge cases involving letters adjacent to brackets, and then I knew that I was in hell.

Anyways, run it online here with test cases

->s{s.gsub!(/{(-?\w+)..(-?\w+)(..(\d+))?}/){x,y=$1,$2;a,b,c=[x,y,$4].map &:to_i
$1[/\d/]?0:(a,b=x,y)
k=ax{x[0].gsub(/^{(.*)}$/){$1}.scan(/(({(\g<1>|,)*}|[^,{}]|(?<=,|^)(?=,|$))+)/).map{|i|i=i[0];i[?{]?r[i]:i}.flatten}
r=->x{i=x.scan(/({(\g<1>)*}|[^{} ]+)/).map(&t)
i.shift.product(*i).map &:join}
s.split.map(&r)*' '}
```
<p>Ungolfed:</p>
<pre class="lang-ruby prettyprint-override"><code>->s{
  s.gsub!(/{(-?\w+)..(-?\w+)(..(\d+))?}/){  # Replace all range-type brackets {a..b..c}
    x,y=$1,$2;a,b,c=[x,y,$4].map &:to_i     # Set up int variables
    $1[/\d/]?0:(a,b=x,y)                    # Use int variables for a,b if they're numbers
    k=a<b ?[*a..b]:[*b..a].reverse          # Create an array for the range in the correct direction
    '{'+                                    # Return the next bit surrounded by brackets
      0.step(k.size-1,$4?c:1).map{|i|k[i]   # If c exists, use it as the step size for the array
      }*','                                 # Join with commas
      +'}'
  }
  r=1                                       # Dummy value to forward-declare the parse function `r`
  t=->x{                                    # Function to parse a bracket block
    x=x[0].gsub(/^{(.*)}$/){$1}             # Remove outer brackets if both are present
                                            # x[0] is required because of quirks in the `scan` function
    x=x.scan(/(({(\g<1>|,)*}|[^,{}]|(?<=,|^)(?=,|$))+)/)
                                            # Regex black magic: collect elements of outer bracket
    x.map{|i|i=i[0];i[?{]?r[i]:i}.flatten   # For each element with brackets, run parse function
  }
  r=->x{                                    # Function to parse bracket expansions a{b,c}{d,e}
    i=x.scan(/({(\g<1>)*}|[^{} ]+)/)        # Regex black magic: scan for adjacent sets of brackets
    i=i.map(&t)                             # Map all elements against the bracket parser function `t`
    i.shift.product(*i).map &:join          # Combine the adjacent sets with cartesian product and join them together
  }
  s.split.map(&r)*' '                       # Split on whitespace, parse each bracket collection
                                            #   and re-join with spaces
}
</code>```

Title: Expand a bash brace expansion

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

There are two basic types of brace expansion:

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

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

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

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

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

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

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

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

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

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

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

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

This also works for multiple braces concatenated together:

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

This can get quite complex.  For example:

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

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

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

Note how order is always preserved.

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

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

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

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

list braces may contain arbitrary nestings of other brace expansions

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

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

Input

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

Output

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

Body:
Ruby, <s>405</s> <s>403</s> <s>401</s> 400 bytes

A wise man (Jamie Zawinski) once said, "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems."

I don't think I fully appreciated that quote until I tried to solve this problem with recursive regex. Initially, the regex cases seemed simple, until I had to deal with the edge cases involving letters adjacent to brackets, and then I knew that I was in hell.

Anyways, run it online here with test cases

->s{s.gsub!(/{(-?\w+)..(-?\w+)(..(\d+))?}/){x,y=$1,$2;a,b,c=[x,y,$4].map &:to_i
$1[/\d/]?0:(a,b=x,y)
k=a<b ?[*a..b]:[*b..a].reverse
?{+0.step(k.size-1,$4?c:1).map{|i|k[i]}*?,+?}}
r=1
t=->x{x[0].gsub(/^{(.*)}$/){$1}.scan(/(({(\g<1>|,)*}|[^,{}]|(?<=,|^)(?=,|$))+)/).map{|i|i=i[0];i[?{]?r[i]:i}.flatten}
r=->x{i=x.scan(/({(\g<1>)*}|[^{} ]+)/).map(&t)
i.shift.product(*i).map &:join}
s.split.map(&r)*' '}

Ungolfed:

->s{
  s.gsub!(/{(-?\w+)..(-?\w+)(..(\d+))?}/){  # Replace all range-type brackets {a..b..c}
    x,y=$1,$2;a,b,c=[x,y,$4].map &:to_i     # Set up int variables
    $1[/\d/]?0:(a,b=x,y)                    # Use int variables for a,b if they're numbers
    k=a<b ?[*a..b]:[*b..a].reverse          # Create an array for the range in the correct direction
    '{'+                                    # Return the next bit surrounded by brackets
      0.step(k.size-1,$4?c:1).map{|i|k[i]   # If c exists, use it as the step size for the array
      }*','                                 # Join with commas
      +'}'
  }
  r=1                                       # Dummy value to forward-declare the parse function `r`
  t=->x{                                    # Function to parse a bracket block
    x=x[0].gsub(/^{(.*)}$/){$1}             # Remove outer brackets if both are present
                                            # x[0] is required because of quirks in the `scan` function
    x=x.scan(/(({(\g<1>|,)*}|[^,{}]|(?<=,|^)(?=,|$))+)/)
                                            # Regex black magic: collect elements of outer bracket
    x.map{|i|i=i[0];i[?{]?r[i]:i}.flatten   # For each element with brackets, run parse function
  }
  r=->x{                                    # Function to parse bracket expansions a{b,c}{d,e}
    i=x.scan(/({(\g<1>)*}|[^{} ]+)/)        # Regex black magic: scan for adjacent sets of brackets
    i=i.map(&t)                             # Map all elements against the bracket parser function `t`
    i.shift.product(*i).map &:join          # Combine the adjacent sets with cartesian product and join them together
  }
  s.split.map(&r)*' '                       # Split on whitespace, parse each bracket collection
                                            #   and re-join with spaces
}


问:
Determine the "Luck" of a string
Given a string, return that string's "luck".

A string's luck, as I completely just made up for the purpose of this challenge, is an integer, determined as so:

The base luck for a string is 1.

For each consecutive letter it shares with the word "lucky" (case insensitive), multiply the luck by 2. For instance, if your string was "lumberjack" or "smack" you'd multiply by 4. (More specifically, 2^number of consecutive characters shared.)

The shared letters have to be in the same consecutive order it appears in "lucky" but can start anywhere in the word for the same value ("luc" has the same 8* multiplier as "cky").

If the word has multiple occurrences where it shares consecutive characters with lucky, use the longest consecutive string of the characters.

For ANY letter it shares with the word "omen" subtract 2 from the luck.

It can match a character any amount of times, in any order. For instance the string "nnnnnomemenn" loses 24 luck (12 matching letters)

Example:

```<code>luck("lucky")
>>32
</code>```

2^5 (5 consecutive letters) = 32

```<code>luck("firetruck")
>>6
</code>```

2^3 - 2 (3 consecutive letters from uck, e shared with omen)

```<code>luck("memes")
>>-7
</code>```

1 - 8 (base amount, 4 shared with "omen")

This is code golf, so the answer with the fewest bytes wins.

You can input and output any way you'd like - write a function, use standard input, etc.

For functions, assume whatever data type would make sense for that language. (For example, in JavaScript, you'd be passed a String and return a Number)

Edit: You can assume any input is lowercase.

答:
Ruby: 100 bytes

->s{2**(m=0;4.times{|j|1.upto(5){|i|m=[i,m].max if s.match"lucky"[j,i]}};m)-s.scan(/[omen]/).size*2}
```

ContentLicense: CC BY-SA 3.0

Title: Determine the "Luck" of a string


答:
Python 3, <s>168</s> <s>157</s> <s>152</s> <s>139</s> <s>144</s> 136 bytes

EDIT: Really obvious things I should have seen easier have been changed, and some slightly less obvious.

Edit 2: stoopid (˚n˚). The program threw errors. I fixed it up. not actually 153 :(

Thanks to Leaky Nun for saving 5 bytes, and to jmilloy for saving <s>13</s> 8 bytes.

s=input()
p=q=k=len(s)
m=0
while-~p:
 while-~q:m=(m,q-p)[(s[p:q]in"lucky")*q-p>m];q-=1
 p-=1;q=k
print(2**m-2*sum(i in"omen"for i in s))
```

The program runs through all possibly possible substrings in input (possibly possible, because it computes impossible substrings as well, 8 to 7, for example), checks if the substring is in "lucky", then sets the exponent of 2 to the length of the substring should it be greater than the current value. Possibly could be improved by using only one while loop. Could possibly use some improvement; I'm still getting the hang of this.

Title: Determine the "Luck" of a string

Body:
Given a string, return that string's "luck".

A string's luck, as I completely just made up for the purpose of this challenge, is an integer, determined as so:

The base luck for a string is 1.

For each consecutive letter it shares with the word "lucky" (case insensitive), multiply the luck by 2. For instance, if your string was "lumberjack" or "smack" you'd multiply by 4. (More specifically, 2^number of consecutive characters shared.)

The shared letters have to be in the same consecutive order it appears in "lucky" but can start anywhere in the word for the same value ("luc" has the same 8* multiplier as "cky").

If the word has multiple occurrences where it shares consecutive characters with lucky, use the longest consecutive string of the characters.

For ANY letter it shares with the word "omen" subtract 2 from the luck.

It can match a character any amount of times, in any order. For instance the string "nnnnnomemenn" loses 24 luck (12 matching letters)

Example:

```<code>luck("lucky")
>>32
</code>```

2^5 (5 consecutive letters) = 32

```<code>luck("firetruck")
>>6
</code>```

2^3 - 2 (3 consecutive letters from uck, e shared with omen)

```<code>luck("memes")
>>-7
</code>```

1 - 8 (base amount, 4 shared with "omen")

This is code golf, so the answer with the fewest bytes wins.

You can input and output any way you'd like - write a function, use standard input, etc.

For functions, assume whatever data type would make sense for that language. (For example, in JavaScript, you'd be passed a String and return a Number)

Edit: You can assume any input is lowercase.

Body:
Python 3, <s>168</s> <s>157</s> <s>152</s> <s>139</s> <s>144</s> 136 bytes

EDIT: Really obvious things I should have seen easier have been changed, and some slightly less obvious.

Edit 2: stoopid (˚n˚). The program threw errors. I fixed it up. not actually 153 :(

Thanks to Leaky Nun for saving 5 bytes, and to jmilloy for saving <s>13</s> 8 bytes.

s=input()
p=q=k=len(s)
m=0
while-~p:
 while-~q:m=(m,q-p)[(s[p:q]in"lucky")*q-p>m];q-=1
 p-=1;q=k
print(2**m-2*sum(i in"omen"for i in s))

The program runs through all possibly possible substrings in input (possibly possible, because it computes impossible substrings as well, 8 to 7, for example), checks if the substring is in "lucky", then sets the exponent of 2 to the length of the substring should it be greater than the current value. Possibly could be improved by using only one while loop. Could possibly use some improvement; I'm still getting the hang of this.


答:
Ruby, <s>91</s> 87 bytes

String#count's finnicky usage strikes again! (When passed a String, it counts all occurrences of each letter in the function argument instead of all occurrences of the entire string.)

Try it online

->s{2**(z=0..5).max_by{|j|z.map{|i|s[b="lucky"[i,j]]?b.size: 0}.max}-2*s.count("omen")}
```
<p>A version that takes in lines from STDIN and prints them: 89 bytes (86 +3 from the <code>-n</code> flag)</p>
<pre class="lang-ruby prettyprint-override"><code>p 2**(z=0..5).max_by{|j|z.map{|i|$_[b="lucky"[i,j]]?b.size: 0}.max}-2*$_.count("omen")
</code>```

Title: Determine the "Luck" of a string

Body:
Ruby, <s>91</s> 87 bytes

String#count's finnicky usage strikes again! (When passed a String, it counts all occurrences of each letter in the function argument instead of all occurrences of the entire string.)

Try it online

->s{2**(z=0..5).max_by{|j|z.map{|i|s[b="lucky"[i,j]]?b.size: 0}.max}-2*s.count("omen")}

A version that takes in lines from STDIN and prints them: 89 bytes (86 +3 from the -n flag)

p 2**(z=0..5).max_by{|j|z.map{|i|$_[b="lucky"[i,j]]?b.size: 0}.max}-2*$_.count("omen")


答:
Javascript - 206 Bytes

r=>{var a="lucky";r:for(var e=5;e>0;e--)for(var n=0;6>n+e;n++){var o=a.substring(n,e+n);if(r.includes(o))break r}for(var t=0,e=0;e<r.length;e++)('omen'.indexOf(r[e])+1)&&t++;return Math.pow(2,o.length)-2*t}
```

Title: Determine the "Luck" of a string


问:
Write a brainfuck compiler
Write a program that takes a brainfuck program and compiles it to executable machine code. You can target x86, x86_64, jvm (java bytecode) or armv6, and use one of the following executable formats: ELF, a.out, class file, exe, com. The executable should work in Linux or Windows (or Java on either).

Neither your program nor the generated executable may run any external program (such as another compiler, assembler or interpreter).

Shortest code wins.

答:
C, <s>866</s>  783 bytes

Since my code outputs 32 bit ELF executable I can't promise that it will work on everyones setup. It took enough tweaking to get the executable to stop segfaulting on my computer.

For anyone trying to run this:

```<code>$ uname --all
Linux 4.4.0-24-generic #43-Ubuntu SMP Wed Jun 8 19:27:37 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
</code>```

A Brainfuck program is read from stdin and the compiled ELF is written to stdout.

```<code>#define P *(t++)
#define C case
#define B break
char a[30000],b[65535],f,*t=b;*c[100];**d=c;main(g){P=188;t+=4;while((f=getchar())!=-1)switch(f){C'>':P=68;B;C'<':P=76;B;C'+':P=254;P=4;P=36;B;C'-':P=254;P=12;P=36;B;C'.':P=187;t+=4;P=137;P=225;P=186;P=1;t+=3;P=184;P=4;t+=3;P=205;P=128;B;C',':P=187;P=1;t+=3;P=137;P=225;P=186;P=1;t+=3;P=184;P=3;t+=3;P=205;P=128;B;C'[':P=138;P=4;P=36;P=133;P=192;P=15;P=132;t+=4;*d=(int*)t-1;d++;B;C']':P=138;P=4;P=36;P=133;P=192;P=15;P=133;t+=4;d--;g=((char*)(*d+1))-t;*((int*)t-1)=g;**d=-g;B;}P=184;P=1;t+=3;P=187;t+=4;P=205;P=128;*(int*)(b+1)=0x8048054+t-b;long long z[]={282579962709375,0,4295163906,223472812116,0,4297064500,4294967296,577727389698621440,36412867248128,30064779550,140720308490240};write(1,&z,84);write(1,b,t-b);write(1,a,30000);}
</code>```

Ungolfed

In the ungolfed version of the code, you can get a better idea of what's going on. The character array at the end of the golfed code is an encoding of the ELF and program header in the ungolfed code. This code also show how each Brainfuck instruction is translated into bytecode.

```<code>#include <linux/elf.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>

#define MAX_BIN_LEN 65535
#define MAX_JUMPS 100

unsigned int org = 0x08048000;

unsigned char move_right[] = {0x44};                              /*inc   esp         */

unsigned char move_left[]  = {0x4c};                              /*dec   esp         */

unsigned char inc_cell[]   = {0xfe,0x04,0x24};                    /*inc   [esp]       */

unsigned char dec_cell[]   = {0xfe,0x0c,0x24};                    /*dec   [esp]       */

unsigned char read_char[]  = {0xbb,0x00,0x00,0x00,0x00,           /*mov   ebx,  0     */
                              0x89,0xe1,                          /*mov   ecx,  esp   */
                              0xba,0x01,0x00,0x00,0x00,           /*mov   edx,  1     */
                              0xb8,0x03,0x00,0x00,0x00,           /*mov   eax,  3     */
                              0xcd,0x80};                         /*int   0x80        */

unsigned char print_char[] = {0xbb,0x01,0x00,0x00,0x00,           /*mov   ebx,  1     */
                              0x89,0xe1,                          /*mov   ecx,  esp   */
                              0xba,0x01,0x00,0x00,0x00,           /*mov   edx,  1     */
                              0xb8,0x04,0x00,0x00,0x00,           /*mov   eax,  4     */
                              0xcd,0x80};                         /*int   0x80        */

unsigned char loop_start[] = {0x8a,0x04,0x24,                     /*mov   eax,  [esp] */
                              0x85,0xc0,                          /*test  eax,  eax   */
                              0x0f,0x84,0x00,0x00,0x00,0x00};     /*je    int32_t     */

unsigned char loop_end[]   = {0x8a,0x04,0x24,                     /*mov   eax,  [esp] */
                              0x85,0xc0,                          /*test  eax,  eax   */
                              0x0f,0x85,0x00,0x00,0x00,0x00};     /*jne   int32_t     */

unsigned char call_exit[]  = {0xb8,0x01,0x00,0x00,0x00,           /*mov   eax,  1     */
                              0xbb,0x00,0x00,0x00,0x00,           /*mov   ebx,  0     */
                              0xcd,0x80};                         /*int   0x80        */
unsigned char prelude[]    = {0xbc,0x00,0x00,0x00,0x00};          /*mov   esp, int32_t*/

unsigned char tape[100];

int main(){
    unsigned char text[MAX_BIN_LEN];
    unsigned char *txt_ptr = text;

    int32_t *loop_jmps[MAX_JUMPS];
    int32_t **loop_jmps_ptr = loop_jmps;

    Elf32_Off entry;

    entry = org + sizeof(Elf32_Ehdr) + 1 * sizeof(Elf32_Phdr);

    memcpy(txt_ptr,prelude,sizeof(prelude));
    txt_ptr += sizeof(prelude);
    char input;
    while((input = getchar()) != -1){
        switch(input){
            case '>':
                memcpy(txt_ptr,move_right,sizeof(move_right));
                txt_ptr += sizeof(move_right);
                break;
            case '<':
                memcpy(txt_ptr,move_left,sizeof(move_left));
                txt_ptr += sizeof(move_left);
                break;
            case '+':
                memcpy(txt_ptr,inc_cell,sizeof(inc_cell));
                txt_ptr += sizeof(inc_cell);
                break;
            case '-':
                memcpy(txt_ptr,dec_cell,sizeof(dec_cell));
                txt_ptr += sizeof(dec_cell);
                break;
            case '.':
                memcpy(txt_ptr,print_char,sizeof(print_char));
                txt_ptr += sizeof(print_char);
                break;
            case ',':
                memcpy(txt_ptr,read_char,sizeof(read_char));
                txt_ptr += sizeof(read_char);
                break;
            case '[':
                memcpy(txt_ptr,loop_start,sizeof(loop_start));
                txt_ptr += sizeof(loop_start);
                *loop_jmps_ptr = (int32_t*) txt_ptr - 1;
                loop_jmps_ptr++;
                break;
            case ']':
                memcpy(txt_ptr,loop_end,sizeof(loop_end));
                txt_ptr += sizeof(loop_end);
                loop_jmps_ptr--;
                int32_t offset = ((unsigned char*) (*loop_jmps_ptr + 1)) - txt_ptr;
                *((int32_t*)txt_ptr - 1) = offset;
                **loop_jmps_ptr = -offset;
                break;
        }
    }

    memcpy(txt_ptr,call_exit,sizeof(call_exit));
    txt_ptr += sizeof(call_exit);

    *(int32_t*)(text + 1) = entry + (txt_ptr - text);

    Elf32_Ehdr ehdr = {
        {0x7F,'E','L','F',ELFCLASS32,ELFDATA2LSB,EV_CURRENT,0,0,0,0,0,0,0,0,0},
        ET_EXEC,
        EM_386,
        EV_CURRENT,
        entry,
        sizeof(Elf32_Ehdr),
        0,
        0,
        sizeof(Elf32_Ehdr),
        sizeof(Elf32_Phdr),
        1,
        0,
        0,
        SHN_UNDEF,
    };

    Elf32_Phdr phdr = {
        PT_LOAD,
        0,
        org,
        org,
        sizeof(Elf32_Ehdr) + sizeof(Elf32_Phdr) + (txt_ptr - text),
        sizeof(Elf32_Ehdr) + sizeof(Elf32_Phdr) + (txt_ptr - text),
        PF_R | PF_X | PF_W,
        0x1000,
    };

    int out = open("a.out",O_CREAT|O_TRUNC|O_WRONLY,S_IRWXU);
    write(out,&ehdr,sizeof(Elf32_Ehdr));
    write(out,&phdr,sizeof(Elf32_Phdr));

    write(out,text,txt_ptr-text);
    write(out,tape,sizeof(tape));
    close(out);
}
</code>```

Self Modifying BrainFuck

In order to save on bytes, the tape for my compiler isn't allocated in a .bss section or anything fancy like that. Instead, the tape is 30,000 null bytes written directly after the compiled byte code of the Brainfuck program. Knowing this, and being aware of what byte code is generated by my compiler means that you can generate or modify byte code at runtime. A simple illustration of this 'feature' is a Brainfuck program that sets its own exit value.

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

The program goes off the left edge of the tape into the byte code to the point that the exit code is normally set 0. Incrementing this byte causes the exit code to be set to 1 instead of 0 when the program eventually exits. With persistence, this could be used to do system level programming in Brainfuck.

Title: Write a brainfuck compiler

Body:
C, <s>866</s>  783 bytes

Since my code outputs 32 bit ELF executable I can't promise that it will work on everyones setup. It took enough tweaking to get the executable to stop segfaulting on my computer.

For anyone trying to run this:

$ uname --all
Linux 4.4.0-24-generic #43-Ubuntu SMP Wed Jun 8 19:27:37 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

A Brainfuck program is read from stdin and the compiled ELF is written to stdout.

#define P *(t++)
#define C case
#define B break
char a[30000],b[65535],f,*t=b;*c[100];**d=c;main(g){P=188;t+=4;while((f=getchar())!=-1)switch(f){C'>':P=68;B;C'<':P=76;B;C'+':P=254;P=4;P=36;B;C'-':P=254;P=12;P=36;B;C'.':P=187;t+=4;P=137;P=225;P=186;P=1;t+=3;P=184;P=4;t+=3;P=205;P=128;B;C',':P=187;P=1;t+=3;P=137;P=225;P=186;P=1;t+=3;P=184;P=3;t+=3;P=205;P=128;B;C'[':P=138;P=4;P=36;P=133;P=192;P=15;P=132;t+=4;*d=(int*)t-1;d++;B;C']':P=138;P=4;P=36;P=133;P=192;P=15;P=133;t+=4;d--;g=((char*)(*d+1))-t;*((int*)t-1)=g;**d=-g;B;}P=184;P=1;t+=3;P=187;t+=4;P=205;P=128;*(int*)(b+1)=0x8048054+t-b;long long z[]={282579962709375,0,4295163906,223472812116,0,4297064500,4294967296,577727389698621440,36412867248128,30064779550,140720308490240};write(1,&z,84);write(1,b,t-b);write(1,a,30000);}

Ungolfed

In the ungolfed version of the code, you can get a better idea of what's going on. The character array at the end of the golfed code is an encoding of the ELF and program header in the ungolfed code. This code also show how each Brainfuck instruction is translated into bytecode.

#include <linux/elf.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdint.h>

#define MAX_BIN_LEN 65535
#define MAX_JUMPS 100

unsigned int org = 0x08048000;

unsigned char move_right[] = {0x44};                              /*inc   esp         */

unsigned char move_left[]  = {0x4c};                              /*dec   esp         */

unsigned char inc_cell[]   = {0xfe,0x04,0x24};                    /*inc   [esp]       */

unsigned char dec_cell[]   = {0xfe,0x0c,0x24};                    /*dec   [esp]       */

unsigned char read_char[]  = {0xbb,0x00,0x00,0x00,0x00,           /*mov   ebx,  0     */
                              0x89,0xe1,                          /*mov   ecx,  esp   */
                              0xba,0x01,0x00,0x00,0x00,           /*mov   edx,  1     */
                              0xb8,0x03,0x00,0x00,0x00,           /*mov   eax,  3     */
                              0xcd,0x80};                         /*int   0x80        */

unsigned char print_char[] = {0xbb,0x01,0x00,0x00,0x00,           /*mov   ebx,  1     */
                              0x89,0xe1,                          /*mov   ecx,  esp   */
                              0xba,0x01,0x00,0x00,0x00,           /*mov   edx,  1     */
                              0xb8,0x04,0x00,0x00,0x00,           /*mov   eax,  4     */
                              0xcd,0x80};                         /*int   0x80        */

unsigned char loop_start[] = {0x8a,0x04,0x24,                     /*mov   eax,  [esp] */
                              0x85,0xc0,                          /*test  eax,  eax   */
                              0x0f,0x84,0x00,0x00,0x00,0x00};     /*je    int32_t     */

unsigned char loop_end[]   = {0x8a,0x04,0x24,                     /*mov   eax,  [esp] */
                              0x85,0xc0,                          /*test  eax,  eax   */
                              0x0f,0x85,0x00,0x00,0x00,0x00};     /*jne   int32_t     */

unsigned char call_exit[]  = {0xb8,0x01,0x00,0x00,0x00,           /*mov   eax,  1     */
                              0xbb,0x00,0x00,0x00,0x00,           /*mov   ebx,  0     */
                              0xcd,0x80};                         /*int   0x80        */
unsigned char prelude[]    = {0xbc,0x00,0x00,0x00,0x00};          /*mov   esp, int32_t*/

unsigned char tape[100];

int main(){
    unsigned char text[MAX_BIN_LEN];
    unsigned char *txt_ptr = text;

    int32_t *loop_jmps[MAX_JUMPS];
    int32_t **loop_jmps_ptr = loop_jmps;

    Elf32_Off entry;

    entry = org + sizeof(Elf32_Ehdr) + 1 * sizeof(Elf32_Phdr);

    memcpy(txt_ptr,prelude,sizeof(prelude));
    txt_ptr += sizeof(prelude);
    char input;
    while((input = getchar()) != -1){
        switch(input){
            case '>':
                memcpy(txt_ptr,move_right,sizeof(move_right));
                txt_ptr += sizeof(move_right);
                break;
            case '<':
                memcpy(txt_ptr,move_left,sizeof(move_left));
                txt_ptr += sizeof(move_left);
                break;
            case '+':
                memcpy(txt_ptr,inc_cell,sizeof(inc_cell));
                txt_ptr += sizeof(inc_cell);
                break;
            case '-':
                memcpy(txt_ptr,dec_cell,sizeof(dec_cell));
                txt_ptr += sizeof(dec_cell);
                break;
            case '.':
                memcpy(txt_ptr,print_char,sizeof(print_char));
                txt_ptr += sizeof(print_char);
                break;
            case ',':
                memcpy(txt_ptr,read_char,sizeof(read_char));
                txt_ptr += sizeof(read_char);
                break;
            case '[':
                memcpy(txt_ptr,loop_start,sizeof(loop_start));
                txt_ptr += sizeof(loop_start);
                *loop_jmps_ptr = (int32_t*) txt_ptr - 1;
                loop_jmps_ptr++;
                break;
            case ']':
                memcpy(txt_ptr,loop_end,sizeof(loop_end));
                txt_ptr += sizeof(loop_end);
                loop_jmps_ptr--;
                int32_t offset = ((unsigned char*) (*loop_jmps_ptr + 1)) - txt_ptr;
                *((int32_t*)txt_ptr - 1) = offset;
                **loop_jmps_ptr = -offset;
                break;
        }
    }

    memcpy(txt_ptr,call_exit,sizeof(call_exit));
    txt_ptr += sizeof(call_exit);

    *(int32_t*)(text + 1) = entry + (txt_ptr - text);

    Elf32_Ehdr ehdr = {
        {0x7F,'E','L','F',ELFCLASS32,ELFDATA2LSB,EV_CURRENT,0,0,0,0,0,0,0,0,0},
        ET_EXEC,
        EM_386,
        EV_CURRENT,
        entry,
        sizeof(Elf32_Ehdr),
        0,
        0,
        sizeof(Elf32_Ehdr),
        sizeof(Elf32_Phdr),
        1,
        0,
        0,
        SHN_UNDEF,
    };

    Elf32_Phdr phdr = {
        PT_LOAD,
        0,
        org,
        org,
        sizeof(Elf32_Ehdr) + sizeof(Elf32_Phdr) + (txt_ptr - text),
        sizeof(Elf32_Ehdr) + sizeof(Elf32_Phdr) + (txt_ptr - text),
        PF_R | PF_X | PF_W,
        0x1000,
    };

    int out = open("a.out",O_CREAT|O_TRUNC|O_WRONLY,S_IRWXU);
    write(out,&ehdr,sizeof(Elf32_Ehdr));
    write(out,&phdr,sizeof(Elf32_Phdr));

    write(out,text,txt_ptr-text);
    write(out,tape,sizeof(tape));
    close(out);
}

Self Modifying BrainFuck

In order to save on bytes, the tape for my compiler isn't allocated in a .bss section or anything fancy like that. Instead, the tape is 30,000 null bytes written directly after the compiled byte code of the Brainfuck program. Knowing this, and being aware of what byte code is generated by my compiler means that you can generate or modify byte code at runtime. A simple illustration of this 'feature' is a Brainfuck program that sets its own exit value.

 <<<<<<+

The program goes off the left edge of the tape into the byte code to the point that the exit code is normally set 0. Incrementing this byte causes the exit code to be set to 1 instead of 0 when the program eventually exits. With persistence, this could be used to do system level programming in Brainfuck.


答:
Pyth, <s>27</s> <s>26</s> 28 bytes

```<code>-^2le+k}#"lucky".:Q)yl@"omen
</code>```

1 byte saved thanks to OP :-)

Explanation:

```<code>                                 Implicit Q as input
                .:Q              Find all substrings of input
     +k}#"lucky"                 Filter for substring of "lucky", prepend "" in case of []
    e                            Take last element, which is longest
   l                             Get its length
 ^2                              Raise two to that
                      @"omen"Q   Filter Q for characters in "omen"
                     l           Get length; counts how many characters in "omen" there are
                    y            Double that
-                                Find the difference
</code>```

Test it here.

Title: Determine the "Luck" of a string

Body:
Pyth, <s>27</s> <s>26</s> 28 bytes

-^2le+k}#"lucky".:Q)yl@"omen

1 byte saved thanks to OP :-)

Explanation:

                                 Implicit Q as input
                .:Q              Find all substrings of input
     +k}#"lucky"                 Filter for substring of "lucky", prepend "" in case of []
    e                            Take last element, which is longest
   l                             Get its length
 ^2                              Raise two to that
                      @"omen"Q   Filter Q for characters in "omen"
                     l           Get length; counts how many characters in "omen" there are
                    y            Double that
-                                Find the difference

Test it here.


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

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

Expected output sample:

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

##
--
--

#-
#-
--

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

Rules:

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

The patterns may be generated in any order.

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

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

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

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

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

答:
GolfScript, <s>34</s> 32 chars

```<code>44,{84+2base(;{'-#'=}/@\n.}%2/n*
</code>```

Turns out that there are shorter solutions than simply generating all 64 patterns and filtering out the bad ones.  In fact, by suitably mapping bits to grid positions, it's possible to map all valid (non-empty) patterns to a consecutive range of numbers, as this program does.

Specifically, the mapping I use is:

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

where the numbers denote the bit position (starting from the least significant bit 0) mapped to that position in the grid.  With this mapping, the valid grids correspond to the numbers 20 to 63 inclusive.

This is almost the same as the obvious mapping obtained by writing out the 6-bit number in binary and adding line breaks between every second bit, except that the bits 1 and 2 are swapped — and indeed, that's exactly how my program computes it.  (I also add 64 to the numbers before converting them to binary, and then strip the extra high bit off; that's just to zero-pad the numbers to 6 bits, since GolfScript's base would otherwise not return any leading zeros.)

Ps. Online demo here. (Server seems overloaded lately; if you get a timeout, try again or download the interpreter and test it locally.)

Edit: Managed to save two chars by avoiding unnecessary array building and dumping.  Phew!

Title: Write all possible Braille characters

Body:
GolfScript, <s>34</s> 32 chars

44,{84+2base(;{'-#'=}/@\n.}%2/n*

Turns out that there are shorter solutions than simply generating all 64 patterns and filtering out the bad ones.  In fact, by suitably mapping bits to grid positions, it's possible to map all valid (non-empty) patterns to a consecutive range of numbers, as this program does.

Specifically, the mapping I use is:

5 4
3 1
2 0

where the numbers denote the bit position (starting from the least significant bit 0) mapped to that position in the grid.  With this mapping, the valid grids correspond to the numbers 20 to 63 inclusive.

This is almost the same as the obvious mapping obtained by writing out the 6-bit number in binary and adding line breaks between every second bit, except that the bits 1 and 2 are swapped — and indeed, that's exactly how my program computes it.  (I also add 64 to the numbers before converting them to binary, and then strip the extra high bit off; that's just to zero-pad the numbers to 6 bits, since GolfScript's base would otherwise not return any leading zeros.)

Ps. Online demo here. (Server seems overloaded lately; if you get a timeout, try again or download the interpreter and test it locally.)

Edit: Managed to save two chars by avoiding unnecessary array building and dumping.  Phew!


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

The Algorithm

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

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

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

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

Reference Implementation

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

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

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

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

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

<h2>Verification</h2>

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

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

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

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

var prime = 251;

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

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

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

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

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

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

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

t must be less than or equal to n!

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

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

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

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

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

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

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

Valid:

```

Rules

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

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

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

答:
Java 8, 224 bytes:

```<code>(n,t,s)->{int[]W=new int[t-1];for(int i=0;i<t-1;i++){W[i]=new java.util.Random().nextInt(251);};long[]O=new long[n];for(int i=1;i<=n;i++){long T=0;for(int h=1;h<t;h++){T+=W[h-1]*Math.pow(i,h);}O[i-1]=((T+s)%251);}return O;};
</code>```

A Java 8 lambda expression. Outputs a comma separated integer array, and works perfectly until values in the output array reach beyond the range of the Java's long, or 64-bit signed integer, data type, upon which -200 is output into the array.

Try It Online! (Ideone)

Title: Shamir's Secret Sharing

Body:
Java 8, 224 bytes:

(n,t,s)->{int[]W=new int[t-1];for(int i=0;i<t-1;i++){W[i]=new java.util.Random().nextInt(251);};long[]O=new long[n];for(int i=1;i<=n;i++){long T=0;for(int h=1;h<t;h++){T+=W[h-1]*Math.pow(i,h);}O[i-1]=((T+s)%251);}return O;};

A Java 8 lambda expression. Outputs a comma separated integer array, and works perfectly until values in the output array reach beyond the range of the Java's long, or 64-bit signed integer, data type, upon which -200 is output into the array.

Try It Online! (Ideone)


问:
Diamond with numbers
Inspired by this, print an ascii diamond pattern built using 0-9.

Rules

Input n should be between 0-9, anything outside that range is undefined

The diamond should be padded with spaces

The middle line should always have no padding and be the only line to contain n, in the center

Print to stdout

As always, this is code-golf

Test Cases

n = 0

```
0
```

n = 1, print

```
 0
010
 0
```

n = 2, print

```
  0
 010
01210
 010
  0
```

n = 9, print

```
         0
        010
       01210
      0123210
     012343210
    01234543210
   0123456543210
  012345676543210
 01234567876543210
0123456789876543210
 01234567876543210
  012345676543210
   0123456543210
    01234543210
     012343210
      0123210
       01210
        010
         0
```

答:
Vitsy, 50 bytes

I don't think I'm done golfing yet!

```<code>VVHr1mV{V2*1+\[2m]
:Xru
v&VvD([D\[' 'O]]-H1ml\NaOY
</code>```

Explanation:

```<code>VVHr1mV{V2*1+\[2m]
V                  Pop n, set n as the global final variable (GFV).
 V                 Push the GFV to the current stack.
  H                Pop n, pop o, push each item of the range from o to n.
   r               Reverse the current program stack.
    1m             Call the method on line index 1.
      V{           Push the GFV to the bottom of the current stack.
        V2*1+      Push the GFV*2+1 to the stack.
             \[  ] Pop n, do the stuff in brackets n times.
               2m  Call the method on line index 2. Note that this is necessary due
                   to an unknown bug.

:Xru
:                  Clone the current stack, pushing a second stack to the stack
                   stack and jumping to it.
 X                 Pop n and discard.
  r                Reverse the current stack.
   u               Pop the current stack and concatenate it to the previous.

v&VvD([D\[' 'O]]-H1ml\NaOY
v                  Pop n, save as a temporary variable.
 &                 Push a new stack to the stack stack and jump to it.
  V                Push the GFV.
   v               Push the temp var, clear the temp var memory.
    D([        ]   If the top item is not zero, do the stuff in brackets.
                   This is necessary as all loops always apply once.
       D\[' 'O]    Peek n, output n spaces.
   -               Pop n, pop o, push o-n.
    H              Pop n, pop o, push each item of the range from o to n.
     1m            Call the method at line index 1.
       l\N         Output all numbers in this stack.
          aO       Output a newline.
            Y      Pop and discard the current stack from the stack stack.
</code>```

Try it online!

Title: Diamond with numbers

Body:
Vitsy, 50 bytes

I don't think I'm done golfing yet!

VVHr1mV{V2*1+\[2m]
:Xru
v&VvD([D\[' 'O]]-H1ml\NaOY

Explanation:

VVHr1mV{V2*1+\[2m]
V                  Pop n, set n as the global final variable (GFV).
 V                 Push the GFV to the current stack.
  H                Pop n, pop o, push each item of the range from o to n.
   r               Reverse the current program stack.
    1m             Call the method on line index 1.
      V{           Push the GFV to the bottom of the current stack.
        V2*1+      Push the GFV*2+1 to the stack.
             \[  ] Pop n, do the stuff in brackets n times.
               2m  Call the method on line index 2. Note that this is necessary due
                   to an unknown bug.

:Xru
:                  Clone the current stack, pushing a second stack to the stack
                   stack and jumping to it.
 X                 Pop n and discard.
  r                Reverse the current stack.
   u               Pop the current stack and concatenate it to the previous.

v&VvD([D\[' 'O]]-H1ml\NaOY
v                  Pop n, save as a temporary variable.
 &                 Push a new stack to the stack stack and jump to it.
  V                Push the GFV.
   v               Push the temp var, clear the temp var memory.
    D([        ]   If the top item is not zero, do the stuff in brackets.
                   This is necessary as all loops always apply once.
       D\[' 'O]    Peek n, output n spaces.
   -               Pop n, pop o, push o-n.
    H              Pop n, pop o, push each item of the range from o to n.
     1m            Call the method at line index 1.
       l\N         Output all numbers in this stack.
          aO       Output a newline.
            Y      Pop and discard the current stack from the stack stack.

Try it online!


问:
Run Stackylogic
Stackylogic is a logic-based programming language I made up that take in 0's and 1's for input and outputs a single 0 or 1 upon completion.

A Stackylogic program consists of lines that can only contain the three characters 01? as well as exactly one < at the end of one of the lines. Lines may not be empty and the line with the < must have at least one 0, 1, or ? before it.

Here's a sample program that (as I'll explain) computes the NAND of two bits:

```<code>1
?<
11
?
0
</code>```

Every line in a Stackylogic program is considered a stack, with the bottom on the left and the top on the right. Implicitly, there is an empty stack (empty line) before the first line in a program and after the last line.

The <, which we'll call the cursor, marks the stack to start on when a Stackylogic program is run. Execution of a Stackylogic program proceeds as follows:

Pop the top character off the stack the cursor is currently pointing to.

If the character is ?, prompt the user for a 0 or a 1 and act as if that was the character.

If the character is 0, move the cursor one stack up (to the line above the current line).

If the character is 1, move the cursor one stack down (to the line below the current line).

If the stack the cursor moves to is empty, output the last value that was popped off a stack (always a 0 or 1), and end the program.

Else, if the stack the cursor moves to is not empty, go back to step 1 and repeat the process.

Notice that Stackylogic programs always end because they must eventually deplete their stacks.

NAND Example

In the NAND program the cursor starts on a ?:

```<code>1
?<
11
?
0
</code>```

We'll assume the user inputs a 1 once the ? is popped, which means the cursor will move down, making the program look like this:

```<code>1

11<
?
0
</code>```

Now a plain 1 is at the top of the cursor stack. It is duly popped and the cursor moves again:

```<code>1

1
?<
0
</code>```

Now assume the user inputs 0 for the ?, which means the cursor will move up:

```<code>1

1<

0
</code>```

Again, a 1 is on the cursor stack so the cursor pops and moves down:

```<code>1

<
0
</code>```

Finally the cursor stack is empty, so the last value popped, the 1, is output and the program ends.

This is accurate for a NAND gate because 1 NAND 0 is 1. This of course works for the other three two-bit inputs if you care to check.

OR Example

This Stackylogic program simulates an OR gate:

```<code>?
?<
</code>```

It's easy to see that an initial input of 1 will push the cursor to the implicit empty stack below the last line, ending the program and outputting the 1 that was just input.

For an input of 00 on the other hand, the cursor will make its way to the implicit empty stack at the top, ending the program and outputting the last 0 to be input.

Challenge

Write a program or function that takes in a Stackylogic program as a string and runs it, printing or returning the resulting 0 or 1.

Upon ?'s, you may prompt the user for a 0 or 1 input, or read the value from a preset string of 0's and 1's that you also take as input. (This could be another string input to your program/function or you could just assume the first or last line of the program string will be the input stream).

You may assume the program and the input are always well formed. You may optionally assume input programs come with a single trailing newline (though remember there is always an implicit empty stack at the end).

The shortest code in bytes wins.

More Sample Programs

```<code>ZERO
0<

ONE
1<

BUFFER
?<

NOT
1
?<
0

AND
?<
?

NAND
1
?<
11
?
0

OR
?
?<

NOR
1
?
00
?<
0

XOR(v1)
?
0
1?<
?
0

XOR(v2)
?
?<
11
?
0

XNOR(v1)
1
?
0?<
1
?

XNOR(v2)
1
?
00
?<
?

MEDIAN(v1)
1
???<
0

MEDIAN(v2)
?
1?<
??
</code>```

Thanks Martin for the median programs.

答:
Convex, <s>102</s> 95 bytes

Well, a list-of-stacks-based language coded in a stack-based language turned out to be quite difficult. <s>Mark my words: I will get this to 100 bytes or less!</s> EDIT: Success!

```<code>N/S\+{s)_'<={R:M;}{R):R;+}?}%'<-M){(æ=)s_:Q;"?10 ""l+ M):M; M(:M; W:M;A~p"S/Ë~~_!S*+tM)Q:A;}h;;
</code>```

Try it online!

Program input is via command-line args. Input 0s and 1s normally (on TIO, this means newline-separated in the "input" box).

Explanation:

All of the code can be split into three pieces:

```<code>N/S\+
</code>```

This bit simply takes the input program and converts it into an array of lines, and also adds " " lines to the beginning of the array. Since Convex's arrays wrap, having only an empty stack at the beggining will do.

```<code>{s)_'<={R:M;}{R):R;+}?}%'<-
</code>```

This part determines what line (or stack) to start execution with. It searches through each line and puts the correct stack number into the M variable.

```<code>M){(æ=)s_:Q;"?10 ""l+ M):M; M(:M; W:M;A~p"S/Ë~~_!S*+tM)Q:A;}h;;
</code>```

This is the fun bit! It continually loops until it reaches a line with only a space (" ") on it (symbolizing an empty stack). If the line is not empty it does the following:

Pop the last character off the stack.

Switch statement:

If the character is a ?, take input and append that character to the line.

If the character is a 0, move the line pointer up one.

If the character is a 1, move the line pointer down one.

If the character is a (space), print the most-recently popped item and end program.

Title: Run Stackylogic

Body:
Convex, <s>102</s> 95 bytes

Well, a list-of-stacks-based language coded in a stack-based language turned out to be quite difficult. <s>Mark my words: I will get this to 100 bytes or less!</s> EDIT: Success!

N/S\+{s)_'<={R:M;}{R):R;+}?}%'<-M){(æ=)s_:Q;"?10 ""l+ M):M; M(:M; W:M;A~p"S/Ë~~_!S*+tM)Q:A;}h;;

Try it online!

Program input is via command-line args. Input 0s and 1s normally (on TIO, this means newline-separated in the "input" box).

Explanation:

All of the code can be split into three pieces:

N/S\+

This bit simply takes the input program and converts it into an array of lines, and also adds " " lines to the beginning of the array. Since Convex's arrays wrap, having only an empty stack at the beggining will do.

{s)_'<={R:M;}{R):R;+}?}%'<-

This part determines what line (or stack) to start execution with. It searches through each line and puts the correct stack number into the M variable.

M){(æ=)s_:Q;"?10 ""l+ M):M; M(:M; W:M;A~p"S/Ë~~_!S*+tM)Q:A;}h;;

This is the fun bit! It continually loops until it reaches a line with only a space (" ") on it (symbolizing an empty stack). If the line is not empty it does the following:

Pop the last character off the stack.

Switch statement:

If the character is a ?, take input and append that character to the line.

If the character is a 0, move the line pointer up one.

If the character is a 1, move the line pointer down one.

If the character is a (space), print the most-recently popped item and end program.


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

```

答:
Gopher, 48 Bytes

Hello World (42 Characters)

```<code>&++<'×<&÷+<^-<<×-<#!+<$@-<&@<×-<@++<@<.!<=
</code>```

Hello, World (45 Characters)

```<code>&++<'×<&÷+<^-<<×-<#÷+<!×<$@-<&@<×-<@++<@<.!<=
</code>```

Hello, World! (50 Characters)

```<code>&++<'×<?^×+<^-<<×-<#÷+<@÷<'?^-<?^<×-<÷--<@<.!-<+<=
</code>```

Hello, World! (48 Characters)

```<code>&++<'×<&÷+<^-<<×-<#÷+<!×<$@-<&@<×-<@++<@<.!-<+<=
</code>```

Click Here to Run the Code

This is an esolang I created myself, Not strictly designed for golfing, But it can be fun

As far as I am aware, This is also the shortest Hello World in Gopher, Prove me wrong though
It'll help me improve the optimiser I built for it!

ContentLicense: CC BY-SA 4.0

Title: "Hello, World!"

Body:
Gopher, 48 Bytes

Hello World (42 Characters)

&++<'×<&÷+<^-<<×-<#!+<$@-<&@<×-<@++<@<.!<=

Hello, World (45 Characters)

&++<'×<&÷+<^-<<×-<#÷+<!×<$@-<&@<×-<@++<@<.!<=

Hello, World! (50 Characters)

&++<'×<?^×+<^-<<×-<#÷+<@÷<'?^-<?^<×-<÷--<@<.!-<+<=

Hello, World! (48 Characters)

&++<'×<&÷+<^-<<×-<#÷+<!×<$@-<&@<×-<@++<@<.!-<+<=

Click Here to Run the Code

This is an esolang I created myself, Not strictly designed for golfing, But it can be fun

As far as I am aware, This is also the shortest Hello World in Gopher, Prove me wrong though
It'll help me improve the optimiser I built for it!


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

Take a positive integer N

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

The final uninteresting number is O*N

For example for N=12:

O = 1212

O*N = 1212 * 12

Final number is 14544

Input

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

Output

The corresponding uninteresting number.

Test cases

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

Scoring

Shortest Code in Bytes wins.

答:
Common Lisp (Lispworks), <s>91</s> <s>78</s> 77 bytes

```<code>(defun f(n)(*(parse-integer(concatenate'string #1=(write-to-string n)#1#))n))
</code>```

Title: Print a bunch of uninteresting numbers!

Body:
Common Lisp (Lispworks), <s>91</s> <s>78</s> 77 bytes

(defun f(n)(*(parse-integer(concatenate'string #1=(write-to-string n)#1#))n))


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

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

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

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

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

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

Test Case:

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

Output:

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

Test Case:

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

Output:

Shortest code wins.

答:
APL (33)

```<code>↑1-⍨B/⍨{(⍳⍴A)∘≡⍋⍵⌷¨A}¨B←,⍳⊃∘⍴¨A←⎕
</code>```

Input is read from the keyboad, but it must be given as an APL list, i.e.

```<code>(1 5 7 10) (2 6 6 8 12) (4 5 9)
</code>```

Explanation:

B←,⍳⊃∘⍴¨A←⎕: A is evaluated input, B is all possible sets of indices in the lists given in A.

{(⍳⍴A)∘≡⍋⍵⌷¨A}¨B: for each set of indices, get the values from the lists (⍵⌷¨A) and see if they are sorted ((⍳⍴A)∘=⍋)

B/⍨: select from B all sets of indices where the previous expression was true (i.e. all the sandwiches)

1-⍨: subtract one from all indices, because this question assumed 0-based arrays and APL-arrays are 1-based by default.

↑: arrange the list of sets of indices as a matrix (so each set is on its own line)

Title: Array Sandwiches

Body:
APL (33)

↑1-⍨B/⍨{(⍳⍴A)∘≡⍋⍵⌷¨A}¨B←,⍳⊃∘⍴¨A←⎕

Input is read from the keyboad, but it must be given as an APL list, i.e.

(1 5 7 10) (2 6 6 8 12) (4 5 9)

Explanation:

B←,⍳⊃∘⍴¨A←⎕: A is evaluated input, B is all possible sets of indices in the lists given in A.

{(⍳⍴A)∘≡⍋⍵⌷¨A}¨B: for each set of indices, get the values from the lists (⍵⌷¨A) and see if they are sorted ((⍳⍴A)∘=⍋)

B/⍨: select from B all sets of indices where the previous expression was true (i.e. all the sandwiches)

1-⍨: subtract one from all indices, because this question assumed 0-based arrays and APL-arrays are 1-based by default.

↑: arrange the list of sets of indices as a matrix (so each set is on its own line)


问:
Generate a Stack Exchange Favicon
Do you recognize the PPCG logo?
it looks like this, when you do an ascii art of it.

```<code>+---+
|PCG|
+---+
   v
</code>```

Now, In this Code Golf, You will make a code, that makes logos for other sites, similar to the PPCG logo.

What You should do

The "Shortened" string will be the string, with all upper case letters and numbers in the input string.(Which would be PPCG when the input string is Programming Puzzles & Code Golf)

The "Box" (

```<code>+---+
|   |
+---+
   v
</code>```

)
should fit the Shortened string perfectly.(No bigger or smaller)

Also the v part should be exactly 1 down and 1 left to the down right +.

Then output the box which has the shortened string in it.

Example

Stack Overflow:

```<code>+--+
|SO|
+--+
  v
</code>```

Area 51:

```<code>+---+
|A51|
+---+
   v
</code>```

Rules

You may assume that the input contains at least one digit or upper case letter.

Standard code-golf rules apply.

答:
V 34 bytes

```<code>Ó[^A-Z0-9]
ys$|ÄVr-r+$.YLppVr x$rv
</code>```

Note that this worked in an older version, but doesn't work in the current version on try it online. I changed Ä to YP which is functionally equivalent.

Try it online!

Explanation:

```<code>Ó[^A-Z0-9]
</code>```

Remove everything except for digits and uppercase characters.

```<code>ys$|              "Surround this line with '|' characters.
    Ä             "Duplicate this line
     Vr-          "Replace this whole duplicated line with '-' characters
        r+        "replace the first character with '+'
          $       "Move to the end of the line, and
           .      "Repeat our last command. This is the same as 'r+'
            Y     "Yank the current line
              pp  "and paste it twice
             L    "At the end of our text
</code>```

Now, the buffer looks like this:

```<code>+---+
|A51|
+---+
+---+
</code>```

And our cursor is at the first column of the last line.

```<code>Vr                 "Change the whole last line to spaces
   x               "Delete a character
    $rv            "And change the last character to a 'v'
</code>```

Non-competing version: (31 bytes)

Title: Generate a Stack Exchange Favicon

Body:
V 34 bytes

Ó[^A-Z0-9]
ys$|ÄVr-r+$.YLppVr x$rv

Note that this worked in an older version, but doesn't work in the current version on try it online. I changed Ä to YP which is functionally equivalent.

Try it online!

Explanation:

Ó[^A-Z0-9]

Remove everything except for digits and uppercase characters.

ys$|              "Surround this line with '|' characters.
    Ä             "Duplicate this line
     Vr-          "Replace this whole duplicated line with '-' characters
        r+        "replace the first character with '+'
          $       "Move to the end of the line, and
           .      "Repeat our last command. This is the same as 'r+'
            Y     "Yank the current line
              pp  "and paste it twice
             L    "At the end of our text

Now, the buffer looks like this:

+---+
|A51|
+---+
+---+

And our cursor is at the first column of the last line.

Vr                 "Change the whole last line to spaces
   x               "Delete a character
    $rv            "And change the last character to a 'v'

Non-competing version: (31 bytes)


答:
Python 3, 318

```<code>def s(f,z):
 p=b="";g=0;a=[];n=a.append;n(p)
 for i in f:
  if i=="\n":n(p);p=''
  else:p+=i
 n(p);p=b;n(p)
 while g<len(a):
  if'<'in a[g]:q=g;a[q]=a[q][:-1]
  g+=1
 while 1:
  v=a[q]
  if v=='':print(b);break
  if v[-1]=='1':a[q]=v[:-1];q+=1;b=1
  elif v[-1]=="0":a[q]=v[:-1];q-=1;b=0
  else:a[q]=v[:-1]+z[0];z=z[1:]
</code>```

F being the program, z being input. Yes, my variable names are insane.

Title: Run Stackylogic

Body:
Stackylogic is a logic-based programming language I made up that take in 0's and 1's for input and outputs a single 0 or 1 upon completion.

A Stackylogic program consists of lines that can only contain the three characters 01? as well as exactly one < at the end of one of the lines. Lines may not be empty and the line with the < must have at least one 0, 1, or ? before it.

Here's a sample program that (as I'll explain) computes the NAND of two bits:

```<code>1
?<
11
?
0
</code>```

Every line in a Stackylogic program is considered a stack, with the bottom on the left and the top on the right. Implicitly, there is an empty stack (empty line) before the first line in a program and after the last line.

The <, which we'll call the cursor, marks the stack to start on when a Stackylogic program is run. Execution of a Stackylogic program proceeds as follows:

Pop the top character off the stack the cursor is currently pointing to.

If the character is ?, prompt the user for a 0 or a 1 and act as if that was the character.

If the character is 0, move the cursor one stack up (to the line above the current line).

If the character is 1, move the cursor one stack down (to the line below the current line).

If the stack the cursor moves to is empty, output the last value that was popped off a stack (always a 0 or 1), and end the program.

Else, if the stack the cursor moves to is not empty, go back to step 1 and repeat the process.

Notice that Stackylogic programs always end because they must eventually deplete their stacks.

NAND Example

In the NAND program the cursor starts on a ?:

```<code>1
?<
11
?
0
</code>```

We'll assume the user inputs a 1 once the ? is popped, which means the cursor will move down, making the program look like this:

```<code>1

11<
?
0
</code>```

Now a plain 1 is at the top of the cursor stack. It is duly popped and the cursor moves again:

```<code>1

1
?<
0
</code>```

Now assume the user inputs 0 for the ?, which means the cursor will move up:

```<code>1

1<

0
</code>```

Again, a 1 is on the cursor stack so the cursor pops and moves down:

```<code>1

<
0
</code>```

Finally the cursor stack is empty, so the last value popped, the 1, is output and the program ends.

This is accurate for a NAND gate because 1 NAND 0 is 1. This of course works for the other three two-bit inputs if you care to check.

OR Example

This Stackylogic program simulates an OR gate:

```<code>?
?<
</code>```

It's easy to see that an initial input of 1 will push the cursor to the implicit empty stack below the last line, ending the program and outputting the 1 that was just input.

For an input of 00 on the other hand, the cursor will make its way to the implicit empty stack at the top, ending the program and outputting the last 0 to be input.

Challenge

Write a program or function that takes in a Stackylogic program as a string and runs it, printing or returning the resulting 0 or 1.

Upon ?'s, you may prompt the user for a 0 or 1 input, or read the value from a preset string of 0's and 1's that you also take as input. (This could be another string input to your program/function or you could just assume the first or last line of the program string will be the input stream).

You may assume the program and the input are always well formed. You may optionally assume input programs come with a single trailing newline (though remember there is always an implicit empty stack at the end).

The shortest code in bytes wins.

More Sample Programs

```<code>ZERO
0<

ONE
1<

BUFFER
?<

NOT
1
?<
0

AND
?<
?

NAND
1
?<
11
?
0

OR
?
?<

NOR
1
?
00
?<
0

XOR(v1)
?
0
1?<
?
0

XOR(v2)
?
?<
11
?
0

XNOR(v1)
1
?
0?<
1
?

XNOR(v2)
1
?
00
?<
?

MEDIAN(v1)
1
???<
0

MEDIAN(v2)
?
1?<
??
</code>```

Thanks Martin for the median programs.

Body:
Python 3, 318

def s(f,z):
 p=b="";g=0;a=[];n=a.append;n(p)
 for i in f:
  if i=="\n":n(p);p=''
  else:p+=i
 n(p);p=b;n(p)
 while g<len(a):
  if'<'in a[g]:q=g;a[q]=a[q][:-1]
  g+=1
 while 1:
  v=a[q]
  if v=='':print(b);break
  if v[-1]=='1':a[q]=v[:-1];q+=1;b=1
  elif v[-1]=="0":a[q]=v[:-1];q-=1;b=0
  else:a[q]=v[:-1]+z[0];z=z[1:]

F being the program, z being input. Yes, my variable names are insane.


答:
Lua, <s>145</s> 99 Bytes

Not much to say, manipulating strings is always wordy in lua :). Takes a command-line argument and output via STDOUT

Thanks to @LeakyNun for saving me 45 Bytes !

n=(...):gsub("[^%u%d]","")s="+"..("-"):rep(#n).."+\n"return s.."|"..n.."|\n"..s..(" "):rep(#n).."V"
```

<p><strong>100 Bytes proposed by @LeakyNun</strong></p>

<pre class="lang-lua prettyprint-override"><code>n=(...):gsub("[^A-Z%d]","")s="+"..("-"):rep(#n).."+\n"return s.."|"..n.."|\n"..s..(" "):rep(#n).."V"
</code>```

OLD 145 Bytes

g="|"..(...):gsub("%a+",function(w)return w:sub(1,1)end):gsub("%s",'').."|"S="+"..g.rep("-",#g-2).."+"p=print
p(S)p(g)p(S)p(g.rep(" ",#g-2).."v")
```

<h3>Ungolfed</h3>

<pre class="lang-lua prettyprint-override"><code>g="|"                            -- g is the second, and starts with a |
  ..(...):gsub("%a+",            -- append the string resulting of the iteration on each word
    function(w)                  -- in the input, applying an anonymous function
      return w:sub(1,1)          -- that return the first character of the word
    end):gsub("%s",'')           -- then remove all spaces
  .."|"                          -- and append a |
S="+"..g.rep("-",#g-2).."+"      -- construct the top and bot of the box
p=print                          -- alias for print
p(S)p(g)p(S)                     -- output the box
p(g.rep(" ",#g-2).."v")          -- output #g-2 spaces (size of the shortened name), then v
</code>```

Title: Generate a Stack Exchange Favicon

Body:
Do you recognize the PPCG logo?
it looks like this, when you do an ascii art of it.

```<code>+---+
|PCG|
+---+
   v
</code>```

Now, In this Code Golf, You will make a code, that makes logos for other sites, similar to the PPCG logo.

What You should do

The "Shortened" string will be the string, with all upper case letters and numbers in the input string.(Which would be PPCG when the input string is Programming Puzzles & Code Golf)

The "Box" (

```<code>+---+
|   |
+---+
   v
</code>```

)
should fit the Shortened string perfectly.(No bigger or smaller)

Also the v part should be exactly 1 down and 1 left to the down right +.

Then output the box which has the shortened string in it.

Example

Stack Overflow:

```<code>+--+
|SO|
+--+
  v
</code>```

Area 51:

```<code>+---+
|A51|
+---+
   v
</code>```

Rules

You may assume that the input contains at least one digit or upper case letter.

Standard code-golf rules apply.

Body:
Lua, <s>145</s> 99 Bytes

Not much to say, manipulating strings is always wordy in lua :). Takes a command-line argument and output via STDOUT

Thanks to @LeakyNun for saving me 45 Bytes !

n=(...):gsub("[^%u%d]","")s="+"..("-"):rep(#n).."+\n"return s.."|"..n.."|\n"..s..(" "):rep(#n).."V"

100 Bytes proposed by @LeakyNun

n=(...):gsub("[^A-Z%d]","")s="+"..("-"):rep(#n).."+\n"return s.."|"..n.."|\n"..s..(" "):rep(#n).."V"

OLD 145 Bytes

g="|"..(...):gsub("%a+",function(w)return w:sub(1,1)end):gsub("%s",'').."|"S="+"..g.rep("-",#g-2).."+"p=print
p(S)p(g)p(S)p(g.rep(" ",#g-2).."v")

Ungolfed

g="|"                            -- g is the second, and starts with a |
  ..(...):gsub("%a+",            -- append the string resulting of the iteration on each word
    function(w)                  -- in the input, applying an anonymous function
      return w:sub(1,1)          -- that return the first character of the word
    end):gsub("%s",'')           -- then remove all spaces
  .."|"                          -- and append a |
S="+"..g.rep("-",#g-2).."+"      -- construct the top and bot of the box
p=print                          -- alias for print
p(S)p(g)p(S)                     -- output the box
p(g.rep(" ",#g-2).."v")          -- output #g-2 spaces (size of the shortened name), then v


答:
ES6, 190 bytes

```<code>f=(p,i)=>{
n=p.split`<`[0].split`\n`.length-1
p=p.split`\n`.map(o=>o.split``)
i=i.split``
p[n].pop()
while(p[n]&&p[n].length){
c=p[n].pop()
v=c=='?'?i.shift():Number(c)
n+=v*2-1
}
return v
}
</code>```

Use like f(program, input)

Title: Run Stackylogic

Body:
ES6, 190 bytes

f=(p,i)=>{
n=p.split`<`[0].split`\n`.length-1
p=p.split`\n`.map(o=>o.split``)
i=i.split``
p[n].pop()
while(p[n]&&p[n].length){
c=p[n].pop()
v=c=='?'?i.shift():Number(c)
n+=v*2-1
}
return v
}

Use like f(program, input)


答:
2sable, <s>36</s> <s>34</s> <s>33</s> <s>32</s> 31 bytes

Presenting 2sable :). Although it has a lot in common with 05AB1E, this one actually auto joins the stack rather than outputting the top of the stack. Code:

```<code>žKA-Ã©g'-×'+DŠJDU„
|Â®sX¶®gð×'v
</code>```

Uses the CP-1252 encoding.

Title: Generate a Stack Exchange Favicon

Body:
2sable, <s>36</s> <s>34</s> <s>33</s> <s>32</s> 31 bytes

Presenting 2sable :). Although it has a lot in common with 05AB1E, this one actually auto joins the stack rather than outputting the top of the stack. Code:

žKA-Ã©g'-×'+DŠJDU„
|Â®sX¶®gð×'v

Uses the CP-1252 encoding.


答:
Java, <s>256</s> <s>255</s> <s>231</s> <s>219</s> <s>215</s> 213 bytes

```<code>int f(char[][]p,char[]I){int l=p.length,d=0,j=-1,c=0,k=0,i[]=new int[l];while(++j<l)if(p[j][i[j]=p[j].length-1]==60)i[k=j]--;try{for(;;k+=c>48?1:-1)c=(c=p[k][i[k]--])>49?I[d++]:c;}catch(Throwable t){}return c-48;}
</code>```

Demo on Ideone.

Takes the program and input as arguments and returns the result as an integer.

Title: Run Stackylogic

Body:
Java, <s>256</s> <s>255</s> <s>231</s> <s>219</s> <s>215</s> 213 bytes

int f(char[][]p,char[]I){int l=p.length,d=0,j=-1,c=0,k=0,i[]=new int[l];while(++j<l)if(p[j][i[j]=p[j].length-1]==60)i[k=j]--;try{for(;;k+=c>48?1:-1)c=(c=p[k][i[k]--])>49?I[d++]:c;}catch(Throwable t){}return c-48;}

Demo on Ideone.

Takes the program and input as arguments and returns the result as an integer.


答:
Perl, 57 bytes

56 bytes code + 1 for -p.

y/a-z //d;$d="-"x y///c;$_="+$d+
|$_|
+$d+
".$"x y///c.v
```

I originally tried to make this only using regexes, but it was much larger than I'd hoped, so I've used some string repetition instead.

Try it online!

Title: Generate a Stack Exchange Favicon

Body:
Perl, 57 bytes

56 bytes code + 1 for -p.

y/a-z //d;$d="-"x y///c;$_="+$d+
|$_|
+$d+
".$"x y///c.v

I originally tried to make this only using regexes, but it was much larger than I'd hoped, so I've used some string repetition instead.

Try it online!


答:
Python 3.5, <s>114</s> <s>93</s> 112 bytes:

```<code>import re;Y=re.findall('[A-Z0-9]',input());I='+'+'-'*len(Y)+'+\n|';print(I+''.join(Y)+I[::-1]+'\n'+' '*len(Y)+'v')
</code>```

A full program. Basically uses a regular expression to match all occurrences of uppercase letters and numbers, then creates the box of the exact size based on the length of the list of matches, and finally puts the joined list of matches "inside" it.

Try It Online! (Ideone)

Title: Generate a Stack Exchange Favicon

Body:
Python 3.5, <s>114</s> <s>93</s> 112 bytes:

import re;Y=re.findall('[A-Z0-9]',input());I='+'+'-'*len(Y)+'+\n|';print(I+''.join(Y)+I[::-1]+'\n'+' '*len(Y)+'v')

A full program. Basically uses a regular expression to match all occurrences of uppercase letters and numbers, then creates the box of the exact size based on the length of the list of matches, and finally puts the joined list of matches "inside" it.

Try It Online! (Ideone)


问:
Score a game of Yahtzee
For each of the 13 rows of a Yahtzee scoresheet you are given (from stdin)
a space separated list of 5 numbers (dice).
Your task is to calculate the score for each line and output the Grand Total of the game.

Example

Input and how to interpret it:

```<code>Input       Box              Score
6 1 4 1 3   Aces              2
3 2 2 1 2   Twos              6
6 3 2 3 3   Threes            9
4 2 3 6 5   Fours             4
6 3 5 5 1   Fives            10
1 5 6 5 6   Sixes            12
            Bonus             -
4 2 4 4 1   3 of a kind      15
2 2 3 2 4   4 of a kind       -
3 2 2 2 3   Full house       25
1 3 1 6 1   Small straight    -
2 5 4 6 3   Large straight   40
2 2 2 2 2   Yahtzee          50
5 5 4 5 2   Chance           21
            Grand Total     194
</code>```

We will disregard the Yahtzee Bonus and Joker rules, and only sum up the scores from the Upper and Lower Section and the Bonus in the Upper Section. If in doubt, refer to these rules.

May the shortest code win!

答:
R - 264

```<code>S=sum;
P=prod;
T=function(i)table(x[i,]);
Z=function(i,...)any(sapply(list(...),function(y)all(y%in%x[i,])))
S((x[1:6,]==(R=row(x[1:6,])))*R)+ # Upper section
S(x[7,])*any(T(7)>2)+             # 3 of a kind
S(x[8,])*any(T(8)>3)+             # 4 of a kind
25*(P(T(9))%in%5:6)+              # Full house
30*Z(10,1:4,2:5,3:6)+             # Small straight
40*Z(11,1:5,2:6)+                 # Large straight
50*(P(T(12))==5)+                 # Yahtzee
S(x[13,])                         # Chance
</code>```

(264 characters when excluding the comments)

With the input

```<code>x <- as.matrix(read.table("http://pastebin.com/raw.php?i=ZRMC9B4x"))
</code>```

Output

```<code>[1] 194
</code>```

Title: Score a game of Yahtzee

Body:
R - 264

S=sum;
P=prod;
T=function(i)table(x[i,]);
Z=function(i,...)any(sapply(list(...),function(y)all(y%in%x[i,])))
S((x[1:6,]==(R=row(x[1:6,])))*R)+ # Upper section
S(x[7,])*any(T(7)>2)+             # 3 of a kind
S(x[8,])*any(T(8)>3)+             # 4 of a kind
25*(P(T(9))%in%5:6)+              # Full house
30*Z(10,1:4,2:5,3:6)+             # Small straight
40*Z(11,1:5,2:6)+                 # Large straight
50*(P(T(12))==5)+                 # Yahtzee
S(x[13,])                         # Chance

(264 characters when excluding the comments)

With the input

x <- as.matrix(read.table("http://pastebin.com/raw.php?i=ZRMC9B4x"))

Output

[1] 194


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

Examples:

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

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

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

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

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

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

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

Relevant OEIS entry (A057846) found by @DomHastings

答:
PHP, 126 bytes

As far as I know php doesn't have any builtins that would really help with this (the best I could do using a usort(str_split()) was 5 bytes longer) so the only thing I'm happy within this answer is the games played with $i to save a couple of bytes on the itteration.

```<code><?php for($i=-1;$i<9;)$a[++$i]=preg_replace("/[^$i]/","",$argv[1]);array_multisort([9,4,8,7,2,1,6,5,0,3],$a);echo implode($a);
</code>```

Body:
PHP, 126 bytes

As far as I know php doesn't have any builtins that would really help with this (the best I could do using a usort(str_split()) was 5 bytes longer) so the only thing I'm happy within this answer is the games played with $i to save a couple of bytes on the itteration.

<?php for($i=-1;$i<9;)$a[++$i]=preg_replace("/[^$i]/","",$argv[1]);array_multisort([9,4,8,7,2,1,6,5,0,3],$a);echo implode($a);


问:
Showcase of Languages

Notes

This thread is open and unlocked only because the community decided to make an exception. Please do not use this question as evidence that you can ask similar questions here. Please do not create additional showcase questions.

This is no longer a popularity-contest, nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes.

This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible.

How this works

All answers should include the name of the programming language at the top of the post, prefixed by a #.

Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language.

Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions.

The snippets do not need to be related. In fact, snippets that are too related may be redundant.

Since this is not a contest, all programming languages are welcome, whenever they were created.

Answers that contain more than a handful of code snippets should use a Stack Snippet to collapse everything except the factoid and one of the snippets.

Whenever possible, there should be only one answer per programming language. This is a community wiki, so feel free to add snippets to any answer, even if you haven't created it yourself. There is a Stack Snippet for compressing posts, which should mitigate the effect of the 30,000 character limit.

Answers that predate these guidelines should be edited. Please help updating them as needed.

Current answers, sorted alphabetically by language name

$.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/44680/answers?site=codegolf&filter=withbody",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('
' + temp.innerText || temp.textContent + '');}}})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="http://codegolf.stackexchange.com"><ul id="list"></ul></code>```

答:
Majc (formely hashmap)

Factoid

hashmap is not necessarily a golfing language, although it's commands can make it so. (Also it's spelled hashmap, not Hashmap).

It was renamed in June 11, 2016 to Majc.

0 byte snippet:

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

This does nothing.

1 byte snippet:

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

Clear the stack... now.. there's nothing in the stack.. so...

2 byte snippet:

```<code>id
</code>```

Convert input to a number, this is also the long version of h.

3 byte snippet:

```<code>h2^
</code>```

h is short for id, so we're taking the input as a number and get it's squared.

4 byte snippet:

```<code>{}:a
</code>```

5 byte snippet:

```<code>isrsr
</code>```

Kind of lost ideas here, but i takes an input, sr reverses it.

I'm not sure if this still works but this created a code block (based on CJam) and assigns it to variable a.
Code blocks are like anonymous functions (unless assigned to a variable).

Title: Showcase of Languages

Body:
Majc (formely hashmap)

Factoid

hashmap is not necessarily a golfing language, although it's commands can make it so. (Also it's spelled hashmap, not Hashmap).

It was renamed in June 11, 2016 to Majc.

0 byte snippet:

This does nothing.

1 byte snippet:

.

Clear the stack... now.. there's nothing in the stack.. so...

2 byte snippet:

id

Convert input to a number, this is also the long version of h.

3 byte snippet:

h2^

h is short for id, so we're taking the input as a number and get it's squared.

4 byte snippet:

{}:a

5 byte snippet:

isrsr

Kind of lost ideas here, but i takes an input, sr reverses it.

I'm not sure if this still works but this created a code block (based on CJam) and assigns it to variable a.
Code blocks are like anonymous functions (unless assigned to a variable).


Title: Generate a Stack Exchange Favicon

Body:
JavaScript (ES6), 99 bytes

(s,t=s.replace(/[^0-9A-Z]/g,``),g=c=>t.replace(/./g,c))=>`${s=`+${g(`-`)}+
`}|${t}|
${s}${g(` `))v`


答:
Python 3, <s>147</s> <s>146</s> <s>145</s> 144 bytes

1 byte thanks to @Lynn.

def f(p):
 i=p[:p.find("<")].count("\n");p=p.split()
 try:
  while 1:*p[i],c=p[i];c=c>"<"and input()or c;i+=c<"<"and int(c)*2-1
 except:return c
```

Title: Run Stackylogic


答:
Python 3, <s>121</s> 124 bytes

Fixed stupid mistake

```<code>s=''
for i in input():_=ord(i);s+=("",i)[91>_>64or 47<_<58]
x=len(s)
c='+'+"-"*x+'+'
print(c+"\n|"+s+"|\n"+c+"\n"+" "*x+"v")
</code>```

does not import libraries like other python answer.

Title: Generate a Stack Exchange Favicon

Body:
Python 3, <s>121</s> 124 bytes

Fixed stupid mistake

s=''
for i in input():_=ord(i);s+=("",i)[91>_>64or 47<_<58]
x=len(s)
c='+'+"-"*x+'+'
print(c+"\n|"+s+"|\n"+c+"\n"+" "*x+"v")

does not import libraries like other python answer.


答:
TSQL, 260 bytes

Used reversed bubble sort to avoid refering to the length, to save some bytes

Golfed:

```<code>DECLARE @ varchar(99)=101

,@i INT=99,@j INT=98WHILE @i>1SELECT
@=IIF(CHARINDEX(x,'598327614')>CHARINDEX(y,'598327614'),STUFF(STUFF(@,@j,1,x),@i,1,y),@),@i-=IIF(@j=1,1,0),@j=IIF(@j=1,@i,@j-1)FROM(SELECT
SUBSTRING(@,@i,1)x,SUBSTRING(@,@j,1)y)z
PRINT @
</code>```

Ungolfed:

```<code>DECLARE @s BIGINT=1234567890

DECLARE @ char(99)=@s,@i INT=99,@j INT=98
WHILE @i>1
  SELECT
    @=IIF(CHARINDEX(x,'236719458')>CHARINDEX(y,'236719458'),
        STUFF(STUFF(@,@j,1,x),@i,1,y),@),
    @i-=IIF(@j=1,1,0),
    @j=IIF(@j=1,@i,@j-1)
  FROM(SELECT SUBSTRING(@,@i,1)x,SUBSTRING(@,@j,1)y)z
PRINT CAST(@ as bigint)
</code>```

Insisting on using integer types as input and output added 37 bytes

Title: Rearrange a number into alphabetical order

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

Examples:

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

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

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

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

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

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

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

Relevant OEIS entry (A057846) found by @DomHastings

Body:
TSQL, 260 bytes

Used reversed bubble sort to avoid refering to the length, to save some bytes

Golfed:

DECLARE @ varchar(99)=101

,@i INT=99,@j INT=98WHILE @i>1SELECT
@=IIF(CHARINDEX(x,'598327614')>CHARINDEX(y,'598327614'),STUFF(STUFF(@,@j,1,x),@i,1,y),@),@i-=IIF(@j=1,1,0),@j=IIF(@j=1,@i,@j-1)FROM(SELECT
SUBSTRING(@,@i,1)x,SUBSTRING(@,@j,1)y)z
PRINT @

Ungolfed:

DECLARE @s BIGINT=1234567890

DECLARE @ char(99)=@s,@i INT=99,@j INT=98
WHILE @i>1
  SELECT
    @=IIF(CHARINDEX(x,'236719458')>CHARINDEX(y,'236719458'),
        STUFF(STUFF(@,@j,1,x),@i,1,y),@),
    @i-=IIF(@j=1,1,0),
    @j=IIF(@j=1,@i,@j-1)
  FROM(SELECT SUBSTRING(@,@i,1)x,SUBSTRING(@,@j,1)y)z
PRINT CAST(@ as bigint)

Insisting on using integer types as input and output added 37 bytes


答:
APL, 23 bytes

```<code>{⍎n['8549176320'⍋n←⍕⍵]}
</code>```

Explanation:

n←⍕⍵: get the string representation of n and store it in n

'8549176320'⍋: find a permutation of n that sorts n given the order 8549176320.

n[...]: reorder n by that permutation

⍎: evaluate the result (to turn it back into a number)

Body:
APL, 23 bytes

{⍎n['8549176320'⍋n←⍕⍵]}

Explanation:

n←⍕⍵: get the string representation of n and store it in n

'8549176320'⍋: find a permutation of n that sorts n given the order 8549176320.

n[...]: reorder n by that permutation

⍎: evaluate the result (to turn it back into a number)