答:
JavaScript (ES6), 136 <s>138</s>

Assuming a terminating newline in the program

(p,i,j=0)=>eval("for(p=`\n${p}`.split`\n`.map((x,i)=>((c=(x=[...x]).pop())=='<'?k=i:x.push(c),x));a=p[k].pop();k-=1-c-c)c=1/a?a:i[j++]")
```
<p><em>Less golfed</em></p>
<pre class="lang-js prettyprint-override"><code>(p, i, j=0)=>{
  p=`\n${p}`
     .split`\n`
     .map(
       (x,i)=>
       (
         x = [...x],
         c = x.pop(),
         c == '<' ? k=i : x.push(c),
         x
       )
     )
  for(; a = p[k].pop(); k -= 1-c-c)
    c = 1/a ? a : i[j++];
  return c;
}
</code>```

Test

F=(p,i,j=0)=>eval("for(p=`\n${p}`.split`\n`.map((x,i)=>((c=(x=[...x]).pop())=='<'?k=i:x.push(c),x));a=p[k].pop();k-=1-c-c)c=1/a?a:i[j++]")

function run() {
  var pgm=P.value+'\n'
  var i=I.value
  O.textContent = F(pgm,i)
}

run()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#P { width:60%; height: 6em }
#I { width:50%;  }</code>```

Program

<textarea id=P>1
?<
11
?
0</textarea>

Input

<input id=I value=01>
<button onclick='run()'>Run</button>

Output

```</code>```

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:
JavaScript (ES6), 136 <s>138</s>

Assuming a terminating newline in the program

(p,i,j=0)=>eval("for(p=`\n${p}`.split`\n`.map((x,i)=>((c=(x=[...x]).pop())=='<'?k=i:x.push(c),x));a=p[k].pop();k-=1-c-c)c=1/a?a:i[j++]")

Less golfed

(p, i, j=0)=>{
  p=`\n${p}`
     .split`\n`
     .map(
       (x,i)=>
       (
         x = [...x],
         c = x.pop(),
         c == '<' ? k=i : x.push(c),
         x
       )
     )
  for(; a = p[k].pop(); k -= 1-c-c)
    c = 1/a ? a : i[j++];
  return c;
}

Test

F=(p,i,j=0)=>eval("for(p=`\n${p}`.split`\n`.map((x,i)=>((c=(x=[...x]).pop())=='<'?k=i:x.push(c),x));a=p[k].pop();k-=1-c-c)c=1/a?a:i[j++]")

function run() {
  var pgm=P.value+'\n'
  var i=I.value
  O.textContent = F(pgm,i)
}

run()

#P { width:60%; height: 6em }
#I { width:50%;  }

Program<br>
<textarea id=P>1
?&lt;
11
?
0</textarea><br>
Input<br>
<input id=I value=01>
<button onclick='run()'>Run</button>
<br>Output
<pre id=O></pre>


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

答:
Clojure, 53 bytes

Well, list comprehension idea from Haskell solution seems to be the shortest:

```<code>#(apply str(for[p"8549176320"b(str %):when(= p b)]p))
</code>```

My original approach is 1 byte longer:

```<code>#(apply str(sort-by(zipmap"549176320"(range))(str %)))
</code>```

You can see both function online here: https://ideone.com/afac5n

ContentLicense: CC BY-SA 3.0

Body:
Clojure, 53 bytes

Well, list comprehension idea from Haskell solution seems to be the shortest:

#(apply str(for[p"8549176320"b(str %):when(= p b)]p))

My original approach is 1 byte longer:

#(apply str(sort-by(zipmap"549176320"(range))(str %)))

You can see both function online here: https://ideone.com/afac5n


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

答:
Pyke, 39 bytes

```<code>cFDh~u{!Ih(sil\-*\+R\+sj\|i\|++jild*\v+
</code>```

Try it here!

12 bytes of mini-string creation, 20 bytes of formatting. Joy!

Title: Generate a Stack Exchange Favicon

Body:
Pyke, 39 bytes

cFDh~u{!Ih(sil\-*\+R\+sj\|i\|++jild*\v+

Try it here!

12 bytes of mini-string creation, 20 bytes of formatting. Joy!


答:
Vim, 42 strokes

```<code>:s/[^A-Z0-9]//g
YPVr-i+<DOWN><LEFT>|<ESC><C-V>ky$pYjppVr $xrv
</code>```

Replace <DOWN> with ↓, <LEFT> with ←, <ESC> with esc and <C-V> with CTRL+V.

Here's an animation of this script running (old version which uses a V instead of a v):

Explanation of the script:

```<code>:s/[^A-Z0-9]//g                               # Remove all the characters that are not uppercase or numbers using a Regex.
YPVr-                                         # Duplicate the current, and replace all the characters of the upper one with dashes.
     i+<DOWN><LEFT>|<ESC>                     # Insert a + on the upper line, and a | on the second line.
                         <C-V>ky$p            # Copy the + and | to the end of both lines.
                                  Yjpp        # Copy the upper line to the bottom two times.
                                      Vr $    # Replace the bottom most line with spaces and put the cursor on the last character.
                                          xrv # Remove the last character and replace the second last character with a 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:
Vim, 42 strokes

:s/[^A-Z0-9]//g
YPVr-i+<DOWN><LEFT>|<ESC><C-V>ky$pYjppVr $xrv

Replace <DOWN> with ↓, <LEFT> with ←, <ESC> with esc and <C-V> with CTRL+V.

Here's an animation of this script running (old version which uses a V instead of a v):

Explanation of the script:

:s/[^A-Z0-9]//g                               # Remove all the characters that are not uppercase or numbers using a Regex.
YPVr-                                         # Duplicate the current, and replace all the characters of the upper one with dashes.
     i+<DOWN><LEFT>|<ESC>                     # Insert a + on the upper line, and a | on the second line.
                         <C-V>ky$p            # Copy the + and | to the end of both lines.
                                  Yjpp        # Copy the upper line to the bottom two times.
                                      Vr $    # Replace the bottom most line with spaces and put the cursor on the last character.
                                          xrv # Remove the last character and replace the second last character with a v.


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

答:
JavaScript (ES7), <s>123</s> <s>112</s> 107 bytes

```<code>s=>2**[5,4,3,2,1,0].find((i,_,a)=>a.some(j=>s.includes("luckyL".substr(j,i))))-2*~-s.split(/[omen]/).length
</code>```

Edit: Saved 11 bytes thanks to @Titus by assuming that the letter L does not appear in the input. Saved 5 bytes thanks to @Oriol. ES6 version for <s>125</s> <s>114</s> 109 bytes:

f=
s=>(1<<[5,4,3,2,1,0].find((i,_,a)=>a.some(j=>s.includes("luckyL".substr(j,i)))))-2*~-s.split(/[omen]/).length
;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input oninput=o.textContent=f(this.value)><pre id=o>``````

Title: Determine the "Luck" of a string

Body:
JavaScript (ES7), <s>123</s> <s>112</s> 107 bytes

s=>2**[5,4,3,2,1,0].find((i,_,a)=>a.some(j=>s.includes("luckyL".substr(j,i))))-2*~-s.split(/[omen]/).length

Edit: Saved 11 bytes thanks to @Titus by assuming that the letter L does not appear in the input. Saved 5 bytes thanks to @Oriol. ES6 version for <s>125</s> <s>114</s> 109 bytes:

f=
s=>(1<<[5,4,3,2,1,0].find((i,_,a)=>a.some(j=>s.includes("luckyL".substr(j,i)))))-2*~-s.split(/[omen]/).length
;

<input oninput=o.textContent=f(this.value)><pre id=o></pre>


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

```

答:
Casio BASIC, 15 bytes

There is a TI-BASIC answer, but no Casio BASIC ? what a shame !

Fortunately, I went here

```<code>"Hello, World!"
</code>```

Unlike in TI-BASIC, you can't thug around the closing " (you still can with parentheses tho).
However, lowercase letters are 1 byte long (on recent models, it might not have been the case with previous ones, but writing lowercase letters was a PITA anyway).

ContentLicense: CC BY-SA 4.0

Title: "Hello, World!"

Body:
Casio BASIC, 15 bytes

There is a TI-BASIC answer, but no Casio BASIC ? what a shame !

Fortunately, I went here

"Hello, World!"

Unlike in TI-BASIC, you can't thug around the closing " (you still can with parentheses tho).
However, lowercase letters are 1 byte long (on recent models, it might not have been the case with previous ones, but writing lowercase letters was a PITA anyway).


答:
Retina, 43 bytes

```<code>[^A-Z\d]

.+
+$.&$*-+¶|$&|¶+$.&$*-+¶$.&$* V
</code>```

Try it online!

This is the perfect challenge to demonstrate Retina, Martin Ender's golfing language.

This solution is divided into two steps (what we call stages), both stages being a replacement stage.

The first stage:

```
[^A-Z\d]

```

This matches the substrings which match [^A-Z\d], which is the characters that are not uppercase and not digits, and then substitute them by nothing, meaning deleting them.

The second stage:

```<code>.+
+$.&$*-+¶|$&|¶+$.&$*-+¶$.&$* V
</code>```

The .+ matches the whole result, and then substitutes it with the second line.

In the second line:

$& refers to the whole match

$.& refers to the length of the whole match

$* means take the previous integer, repeat the next character that many times. Here $.&$*- means to repeat - however long the match is.

¶ refers to a new-line.

Title: Generate a Stack Exchange Favicon

Body:
Retina, 43 bytes

[^A-Z\d]

.+
+$.&$*-+¶|$&|¶+$.&$*-+¶$.&$* V

Try it online!

This is the perfect challenge to demonstrate Retina, Martin Ender's golfing language.

This solution is divided into two steps (what we call stages), both stages being a replacement stage.

The first stage:

[^A-Z\d]

This matches the substrings which match [^A-Z\d], which is the characters that are not uppercase and not digits, and then substitute them by nothing, meaning deleting them.

The second stage:

.+
+$.&$*-+¶|$&|¶+$.&$*-+¶$.&$* V

The .+ matches the whole result, and then substitutes it with the second line.

In the second line:

$& refers to the whole match

$.& refers to the length of the whole match

$* means take the previous integer, repeat the next character that many times. Here $.&$*- means to repeat - however long the match is.

¶ refers to a new-line.


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

答:
Retina, <s>79</s> <s>78</s> <s>73</s> <s>68</s> <s>66</s> <s>65</s> <s>63</s> <s>62</s> <s>55</s> 44 bytes

Byte count assumes ISO 8859-1 encoding.

```<code>+`(.)([^_]*)\?<|(¶.*)0<|1<(¶.+)
$2$1$4<$3
1<
</code>```

Input is via STDIN and is expected to be the user input separated by two linefeeds from the source code.

Try it online! (The first two lines enable a test suite, where each line is a separate test case with / instead of linefeeds.)

I'm not entirely sure what happened here. <s>This feels like a really clunky solution and</s> this is really not the kind of problem Retina was made for but it still beats all the current answers for some reason.

Explanation

The final version of this actually ended up being fairly simple.

```<code>+`(.)([^_]*)\?<|(¶.*)0<|1<(¶.+)
$2$1$4<$3
</code>```

The first stage is simply a loop (due to the + option) which does the actual interpreting of the language. The stage is a single regex substitution, but in fact it's really three different substitutions squeezed into one stage, by making use of the fact that capturing groups from unused branches are simply considered empty during the substitution.

Processing ?:

```<code>(.)([^_]*)\?<
$2$1<
</code>```

This simply takes the first character of the input, then matches arbitrary characters until it finds ?<, and puts that first character in front of the < (deleting the ?).

Processing 0:

```<code>(¶.*)0<
<$1
</code>```

This matches the line preceding a 0< and puts it after the <, removing 0. (Effectively, this just deletes the 0 and moves the < one line upwards.)

Processing 1:

```<code>1<(¶.+)
$1<
</code>```

Pretty much the same thing, except that we move < one line down while deleting a 1. One important detail to notice is the use of + instead of *, that is, we require the next line not to be empty.

The interesting part is figuring out why this works and why we don't need to keep track of the last value we popped to determine the final output. To do that, we need to consider how the above loop can terminate. Since every possible match changes the string (since at least one character is dropped from it), we only need to consider cases where the match fails altogether.

If the character in front of < is ? the only way for the match to fail is that there isn't non-linefeed character anywhere in front of it, but that can't happen because we're guaranteed that there's always enough input.

If the character in front of < is 0, the regex will always match, since there's always another line above the current one (which may be the empty line separating input from source code).

If the character in front of < is 1, the regex will fail if either we're on the last line (since the ¶ will fail to match) or if the next line is empty (since the .+ will fail to match). Note that both of those cases correspond to terminating the program after popping a 1.

Finally, there's also the possibility that < isn't preceded by any of ?01. It turns out we can only reach this situation by popping a 0 and moving up to an empty line, so that the < is now preceded by a linefeed.

So, when the program terminates on a 1, the < will still be after that 1. But if the program terminates on a 0, it will have moved to an empty line. We can easily turn this information into the desired output with a simple match stage:

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

This simply counts the matches of 1< in the string. By the above reasoning this will be 1 if the program terminated on a 1, and 0 if it terminated on a 0.

Title: Run Stackylogic

Body:
Retina, <s>79</s> <s>78</s> <s>73</s> <s>68</s> <s>66</s> <s>65</s> <s>63</s> <s>62</s> <s>55</s> 44 bytes

Byte count assumes ISO 8859-1 encoding.

+`(.)([^_]*)\?<|(¶.*)0<|1<(¶.+)
$2$1$4<$3
1<

Input is via STDIN and is expected to be the user input separated by two linefeeds from the source code.

<a href="http://retina.tryitonline.net/#code=JShTYC8KK2AoLikoW15fXSopXD88fCjCti4qKTA8fDE8KMK2LispCiQyJDEkNDwkMwoxPA&input=Ly8wPAovLzE8CjAvLz88CjEvLz88CjAvLzEvPzwvMAoxLy8xLz88LzAKMDAvLz88Lz8KMDEvLz88Lz8KMTAvLz88Lz8KMTEvLz88Lz8KMDAvLzEvPzwvMTEvPy8wCjAxLy8xLz88LzExLz8vMAoxMC8vMS8_PC8xMS8_LzAKMTEvLzEvPzwvMTEvPy8wCjAwMC8vPy8_MC8_PC8_MS8_CjAwMS8vPy8_MC8_PC8_MS8_CjAxMC8vPy8_MC8_PC8_MS8_CjAxMS8vPy8_MC8_PC8_MS8_CjEwMC8vPy8_MC8_PC8_MS8_CjEwMS8vPy8_MC8_PC8_MS8_CjExMC8vPy8_MC8_PC8_MS8_CjExMS8vPy8_MC8_PC8_MS8_">Try it online! (The first two lines enable a test suite, where each line is a separate test case with / instead of linefeeds.)

I'm not entirely sure what happened here. <s>This feels like a really clunky solution and</s> this is really not the kind of problem Retina was made for but it still beats all the current answers for some reason.

Explanation

The final version of this actually ended up being fairly simple.

+`(.)([^_]*)\?<|(¶.*)0<|1<(¶.+)
$2$1$4<$3

The first stage is simply a loop (due to the + option) which does the actual interpreting of the language. The stage is a single regex substitution, but in fact it's really three different substitutions squeezed into one stage, by making use of the fact that capturing groups from unused branches are simply considered empty during the substitution.

Processing ?:

(.)([^_]*)\?<
$2$1<

This simply takes the first character of the input, then matches arbitrary characters until it finds ?<, and puts that first character in front of the < (deleting the ?).

Processing 0:

(¶.*)0<
<$1

This matches the line preceding a 0< and puts it after the <, removing 0. (Effectively, this just deletes the 0 and moves the < one line upwards.)

Processing 1:

1<(¶.+)
$1<

Pretty much the same thing, except that we move < one line down while deleting a 1. One important detail to notice is the use of + instead of *, that is, we require the next line not to be empty.

The interesting part is figuring out why this works and why we don't need to keep track of the last value we popped to determine the final output. To do that, we need to consider how the above loop can terminate. Since every possible match changes the string (since at least one character is dropped from it), we only need to consider cases where the match fails altogether.

If the character in front of < is ? the only way for the match to fail is that there isn't non-linefeed character anywhere in front of it, but that can't happen because we're guaranteed that there's always enough input.

If the character in front of < is 0, the regex will always match, since there's always another line above the current one (which may be the empty line separating input from source code).

If the character in front of < is 1, the regex will fail if either we're on the last line (since the ¶ will fail to match) or if the next line is empty (since the .+ will fail to match). Note that both of those cases correspond to terminating the program after popping a 1.

Finally, there's also the possibility that < isn't preceded by any of ?01. It turns out we can only reach this situation by popping a 0 and moving up to an empty line, so that the < is now preceded by a linefeed.

So, when the program terminates on a 1, the < will still be after that 1. But if the program terminates on a 0, it will have moved to an empty line. We can easily turn this information into the desired output with a simple match stage:

1<

This simply counts the matches of 1< in the string. By the above reasoning this will be 1 if the program terminated on a 1, and 0 if it terminated on a 0.


答:
Common Lisp, 104

```<code>(lambda(n)(#1=parse-integer(sort(format()"~A"n)'string<= :key(lambda(u)(format()"~R"(#1#(string u)))))))
</code>```

Ungolfed

```<code>(lambda (n)
  (parse-integer
   (sort (format nil "~A" n)
         #'string<=
         :key (lambda (u) (format nil "~R" (parse-integer (string u)))))))
</code>```

Convert integer as string, sort characters using the string<= comparison while using a custom :key function which converts a given character as the English representation of the numerical value it represents. Usually I would not use a key function which does as much as this one, but it costs less in bytes than decorate/sort/undecorate.

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:
Common Lisp, 104

(lambda(n)(#1=parse-integer(sort(format()"~A"n)'string<= :key(lambda(u)(format()"~R"(#1#(string u)))))))

Ungolfed

(lambda (n)
  (parse-integer
   (sort (format nil "~A" n)
         #'string<=
         :key (lambda (u) (format nil "~R" (parse-integer (string u)))))))

Convert integer as string, sort characters using the string<= comparison while using a custom :key function which converts a given character as the English representation of the numerical value it represents. Usually I would not use a key function which does as much as this one, but it costs less in bytes than decorate/sort/undecorate.


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

答:
J, <s>35</s> 33 chars

```<code>3 2$"1'-#'{~(2 A.i.6){"1#:20+i.44
</code>```

Uses the approach Ilmari Karonen came up with in their Golfscript solution.  However, since the J verb #: (antibase) stores the bits (or, well, digits in the generic case) in a list, we need to index it from the left instead of right (i.e. index 0 is the leftmost, highest bit).

The solution is rather straightforward: 20+i.44 gives a list of the numbers 20..63, inclusive.  #: takes the antibase-2 of each element in this list, and thus produces a list of bitpatterns for each number in that range.  { selects (basically reorders) the bits into the right pattern, and then { is used again in order to use the digits as indices in the string '-#' in order to prepare the output.  Finally, we arrange each entry into a 2-by-3 rectangle with $ (shape).

```<code>3 2$"1'-#'{~(2 A.i.6){"1#:20+i.44      N.B. use A. (anagram) to generate the right permutation
</code>```

```<code>3 2$"1'-#'{~0 1 2 4 3 5{"1#:20+i.44
</code>```

Title: Write all possible Braille characters

Body:
J, <s>35</s> 33 chars

3 2$"1'-#'{~(2 A.i.6){"1#:20+i.44

Uses the approach Ilmari Karonen came up with in their Golfscript solution.  However, since the J verb #: (antibase) stores the bits (or, well, digits in the generic case) in a list, we need to index it from the left instead of right (i.e. index 0 is the leftmost, highest bit).

The solution is rather straightforward: 20+i.44 gives a list of the numbers 20..63, inclusive.  #: takes the antibase-2 of each element in this list, and thus produces a list of bitpatterns for each number in that range.  { selects (basically reorders) the bits into the right pattern, and then { is used again in order to use the digits as indices in the string '-#' in order to prepare the output.  Finally, we arrange each entry into a 2-by-3 rectangle with $ (shape).

3 2$"1'-#'{~(2 A.i.6){"1#:20+i.44      N.B. use A. (anagram) to generate the right permutation

3 2$"1'-#'{~0 1 2 4 3 5{"1#:20+i.44


答:
05AB1E, <s>58</s> <s>56</s> <s>55</s> <s>53</s> <s>51</s> <s>50</s> 46 bytes

Saved 2 bytes thanks to Emigna! Code:

```<code>õ|`õ)[¤'<å#À]`¨[¬V¨Y'?QiI«ëYi1U)À`ëY_i0U)Á`ëXq
</code>```

Uses the CP-1252 encoding. Try it online!.

Title: Run Stackylogic

Body:
05AB1E, <s>58</s> <s>56</s> <s>55</s> <s>53</s> <s>51</s> <s>50</s> 46 bytes

Saved 2 bytes thanks to Emigna! Code:

õ|`õ)[¤'<å#À]`¨[¬V¨Y'?QiI«ëYi1U)À`ëY_i0U)Á`ëXq

Uses the CP-1252 encoding. Try it online!.


答:
Pyth, <s>38</s> 37 bytes

```<code>
Jj*\-lK@jrG1UTz"++"jK"||"JtXJ"-+"" v</code>```

Try it online.

Note the newline in the start.

Title: Generate a Stack Exchange Favicon

Body:
Pyth, <s>38</s> 37 bytes

Jj*\-lK@jrG1UTz"++"jK"||"JtXJ"-+"" v

Try it online.

Note the newline in the start.


答:
05AB1E, <s>36</s> <s>32</s> <s>28</s> 26 bytes

```<code>Œv'¸éyåiyˆ}}¯é¤go¹'ƒÖ¦Ãg·-
</code>```

Explanation

```<code>Œv         }                  # for each substring of input
  '¸éyåi  }                   # if substring is part of "lucky"
        yˆ                    # add it to global array
            ¯é¤               # get the longest such substring
               go             # raise 2 to its length
                 ¹'ƒÖ¦Ã       # remove all chars from input that isn't in "omen"
                       g·     # get length and multiply by 2
                         -    # subtract
                              # implicitly display
</code>```

Try it online

Saved 2 bytes thanks to Adnan

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:
05AB1E, <s>36</s> <s>32</s> <s>28</s> 26 bytes

Œv'¸éyåiyˆ}}¯é¤go¹'ƒÖ¦Ãg·-

Explanation

Œv         }                  # for each substring of input
  '¸éyåi  }                   # if substring is part of "lucky"
        yˆ                    # add it to global array
            ¯é¤               # get the longest such substring
               go             # raise 2 to its length
                 ¹'ƒÖ¦Ã       # remove all chars from input that isn't in "omen"
                       g·     # get length and multiply by 2
                         -    # subtract
                              # implicitly display

Try it online

Saved 2 bytes thanks to Adnan


答:
TSQL, 233 bytes

Golfed:

```<code>DECLARE @t varchar(99)='oluck'

,@z INT=0,@a INT=0,@ INT=1,@c INT=0WHILE @a<LEN(@t)SELECT
@a+=IIF(@=1,1,0),@z=IIF('LUCKY'LIKE'%'+x+'%'and @>@z,@,@z),@c+=IIF(x
IN('O','M','E','N'),2,0),@=IIF(@+@a-1=LEN(@t),1,@+1)FROM(SELECT
SUBSTRING(@t,@a,@)x)x PRINT POWER(2,@z)-@c
</code>```

Ungolfed:

```<code>DECLARE @t varchar(99)='oluck'

,@z INT=0
,@a INT=0
,@  INT=1
,@c INT=0
WHILE @a<LEN(@t)
  SELECT
    @a+=IIF(@=1,1,0),
    @z=IIF('LUCKY'LIKE'%'+x+'%'and @>@z,@,@z),
    @c+=IIF(x IN('O','M','E','N'),2,0),
    @=IIF(@+@a-1=LEN(@t),1,@+1)
    FROM(SELECT SUBSTRING(@t,@a,@)x)x
PRINT POWER(2,@z)-@c
</code>```

Try it online

Title: Determine the "Luck" of a string

Body:
TSQL, 233 bytes

Golfed:

DECLARE @t varchar(99)='oluck'

,@z INT=0,@a INT=0,@ INT=1,@c INT=0WHILE @a<LEN(@t)SELECT
@a+=IIF(@=1,1,0),@z=IIF('LUCKY'LIKE'%'+x+'%'and @>@z,@,@z),@c+=IIF(x
IN('O','M','E','N'),2,0),@=IIF(@+@a-1=LEN(@t),1,@+1)FROM(SELECT
SUBSTRING(@t,@a,@)x)x PRINT POWER(2,@z)-@c

Ungolfed:

DECLARE @t varchar(99)='oluck'

,@z INT=0
,@a INT=0
,@  INT=1
,@c INT=0
WHILE @a<LEN(@t)
  SELECT
    @a+=IIF(@=1,1,0),
    @z=IIF('LUCKY'LIKE'%'+x+'%'and @>@z,@,@z),
    @c+=IIF(x IN('O','M','E','N'),2,0),
    @=IIF(@+@a-1=LEN(@t),1,@+1)
    FROM(SELECT SUBSTRING(@t,@a,@)x)x
PRINT POWER(2,@z)-@c

Try it online


答:
PHP program, <s>139</s> 135 <s>108</s> bytes

quantum leap fails for multiple substrings where the first occurence is shorter. :(

actually I could save another 7 bytes in PHP<5.4 with register_globals on

```<code><?for($s=$argv[1];$i<5;$i++)for($j=6;--$j;)$r=max($r,strstr($s,substr('lucky*',$i,$j))?2**$j:1);echo$r-2*preg_match_all('/[omen]/',$s);
</code>```

usage: php -d error_reporting=0 <filename> <string>

+5 for a function:

```<code>function f($s){for(;$i<5;$i++)for($j=6;--$j;)$r=max($r,strstr($s,substr('lucky*',$i,$j))?2**$j:1);return$r-2*preg_match_all('/[omen]/',$s);}
</code>```

tests (on the function)

```<code>echo '<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';
foreach([
    'lumberjack'=>0,        'smack'=>2,
    'nnnnnomemenn'=>-23,    'lucky'=>32,
    'omen'=>-7,             'firetruck'=>6,
    'memes'=>-7,            'determine the “luck” of a string'=>0,
    'amazing'=>-3,          'wicked'=>2,
    'chucky'=>16,           'uckyuke'=>14,
    'ugly'=>2,              'lucy'=>8,
    'lukelucky'=>30
] as $x=>$e){
    $y=f($x);
    echo"$h<tr><td>",$x,'</td><td>',$y,'</td><td>',$e,'</td><td>',$e==$y?'Y':'N',"</td></tr>";
}echo '</table>';
</code>```

Title: Determine the "Luck" of a string

Body:
PHP program, <s>139</s> 135 <s>108</s> bytes

quantum leap fails for multiple substrings where the first occurence is shorter. :(

actually I could save another 7 bytes in PHP<5.4 with register_globals on

<?for($s=$argv[1];$i<5;$i++)for($j=6;--$j;)$r=max($r,strstr($s,substr('lucky*',$i,$j))?2**$j:1);echo$r-2*preg_match_all('/[omen]/',$s);

usage: php -d error_reporting=0 <filename> <string>

+5 for a function:

function f($s){for(;$i<5;$i++)for($j=6;--$j;)$r=max($r,strstr($s,substr('lucky*',$i,$j))?2**$j:1);return$r-2*preg_match_all('/[omen]/',$s);}

tests (on the function)

echo '<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';
foreach([
    'lumberjack'=>0,        'smack'=>2,
    'nnnnnomemenn'=>-23,    'lucky'=>32,
    'omen'=>-7,             'firetruck'=>6,
    'memes'=>-7,            'determine the “luck” of a string'=>0,
    'amazing'=>-3,          'wicked'=>2,
    'chucky'=>16,           'uckyuke'=>14,
    'ugly'=>2,              'lucy'=>8,
    'lukelucky'=>30
] as $x=>$e){
    $y=f($x);
    echo"$h<tr><td>",$x,'</td><td>',$y,'</td><td>',$e,'</td><td>',$e==$y?'Y':'N',"</td></tr>";
}echo '</table>';


答:
Excel VBA, <s>375</s> <s>359</s> 358 bytes:

It works, I give up on trying to make it shorter...

Edit: Switched to case statement from if statements, -16 bytes

Edit2: Got rid of u and replaced with Len(b), -1 byte

```<code>Function b(x)
For i = 1 To Len(x)
a = Mid(x, i, 1)
e = Asc(a)
If e > 64 And e < 91 Or e > 47 And e < 58 Then b = b & a
Next i
For Z = 1 To 4
y = ""
Select Case Z
Case 2
y = "|" & b & "|"
Case 4
For i = 1 To Len(b)
y = y & " "
Next i
y = y & "v"
Case Else
y = "+"
For i = 1 To Len(b)
y = y & "-"
Next i
y = y & "+"
End Select
Debug.Print y
Next Z
End Function
</code>```

Title: Generate a Stack Exchange Favicon

Body:
Excel VBA, <s>375</s> <s>359</s> 358 bytes:

It works, I give up on trying to make it shorter...

Edit: Switched to case statement from if statements, -16 bytes

Edit2: Got rid of u and replaced with Len(b), -1 byte

Function b(x)
For i = 1 To Len(x)
a = Mid(x, i, 1)
e = Asc(a)
If e > 64 And e < 91 Or e > 47 And e < 58 Then b = b & a
Next i
For Z = 1 To 4
y = ""
Select Case Z
Case 2
y = "|" & b & "|"
Case 4
For i = 1 To Len(b)
y = y & " "
Next i
y = y & "v"
Case Else
y = "+"
For i = 1 To Len(b)
y = y & "-"
Next i
y = y & "+"
End Select
Debug.Print y
Next Z
End Function


答:
C#, 183 177 165 bytes

```<code>string h(string s){s=string.Concat(s.Where(n=>n>47&n<58|n>64 &n<91));int m=s.Length;var x=new string('-',m);return$"+{x}+\n|{s}|\n+{x}+\n{new string(' ', m + 1)}v";}
</code>```

multiplying chars is terrible in C#.
suggestions appreciated

thanks alot to aloisdg for -18 bytes

Title: Generate a Stack Exchange Favicon

Body:
C#, 183 177 165 bytes

string h(string s){s=string.Concat(s.Where(n=>n>47&n<58|n>64 &n<91));int m=s.Length;var x=new string('-',m);return$"+{x}+\n|{s}|\n+{x}+\n{new string(' ', m + 1)}v";}

multiplying chars is terrible in C#.
suggestions appreciated

thanks alot to aloisdg for -18 bytes


答:
Python 3, 234 bytes

This is a direct translation of my Factor answer, just for fun.

```<code>def f(n):
 s=list(map(int,str(n)))
 return int("".join(list(map(str,list(map(lambda x:x[1],sorted(list(zip(list(map(lambda t:{0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"}[t],s)),s)))))))))
</code>```

The semantics of the evaluation of "lazy" map and zip objects is the most subtle hard-to-find-bug-inducing piece of genuine horse excrement in the universe. Sometimes, s = map(f, x) won't allow s to be used properly or at all.

Body:
Python 3, 234 bytes

This is a direct translation of my Factor answer, just for fun.

def f(n):
 s=list(map(int,str(n)))
 return int("".join(list(map(str,list(map(lambda x:x[1],sorted(list(zip(list(map(lambda t:{0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"}[t],s)),s)))))))))

The semantics of the evaluation of "lazy" map and zip objects is the most subtle hard-to-find-bug-inducing piece of genuine horse excrement in the universe. Sometimes, s = map(f, x) won't allow s to be used properly or at all.


问:
Calculate golden ratio
Write the shortest code, in number of bytes, to display, return, or evaluate to the golden ratio (that is, the positive root of the quadratic equation: \$x^2-x-1=0\$, approximately
1.618033988749895), to at least 15 significant figures. No input will be given to your program.

Sample in Stutsk programming language:

```<code>1 100 { 1 + 1 swp / } repeat print
</code>```

答:
Ruby - 14 chars

```<code>(5**0.5)/2+0.5
</code>```

Based on the Javascript Perl answer above.

Title: Calculate golden ratio

Body:
Ruby - 14 chars

(5**0.5)/2+0.5

Based on the Javascript Perl answer above.


答:
-- Oracle 11 (SQL): 164 bytes

```<code>  SELECT LISTAGG(DECODE(s,0,'zero',TO_CHAR(TO_DATE(s,'j'),'jsp')),',')WITHIN GROUP(ORDER BY 1)FROM(SELECT SUBSTR(&1,level,1)s FROM dual CONNECT BY LEVEL<=LENGTH(&1));
</code>```

Long form and explanation

```<code>  SELECT LISTAGG(DECODE(s,0,'zero',TO_CHAR(TO_DATE(s,'j'),'jsp')),',') WITHIN GROUP (ORDER BY 1)
  FROM ( SELECT SUBSTR(&1,level,1)s FROM dual
           CONNECT BY LEVEL <= LENGTH(&1)
        );
</code>```

Get the input as parameter to script:

```<code>  SELECT &1 FROM dual
</code>```

"create" rows by using connect by based on length of input:

```<code>  CONNECT BY LEVEL <= LENGTH(&1)
</code>```

Rip out each digit from the string for each position:

```<code>  SELECT SUBSTR(&1,level,1)s FROM dual
</code>```

Convert the digit to Julian date, and back to Char to get spelling:

```<code>  TO_CHAR(TO_DATE(s,'j'),'jsp')
</code>```

Check for zero - special case.

```<code>  DECODE(s,0,'zero'
</code>```

Use LISTAGG function to concatenate rows back into a single row list, comma delimited, ordered alphabetically

```<code>  LISTAGG(DECODE(s,0,'zero',TO_CHAR(TO_DATE(s,'j'),'jsp')),',') WITHIN GROUP (ORDER BY 1)
</code>```

Always fun trying to tweak SQL for things like this ... :) really tests my knowledge of the bugger ...

Body:
-- Oracle 11 (SQL): 164 bytes

  SELECT LISTAGG(DECODE(s,0,'zero',TO_CHAR(TO_DATE(s,'j'),'jsp')),',')WITHIN GROUP(ORDER BY 1)FROM(SELECT SUBSTR(&1,level,1)s FROM dual CONNECT BY LEVEL<=LENGTH(&1));

Long form and explanation

  SELECT LISTAGG(DECODE(s,0,'zero',TO_CHAR(TO_DATE(s,'j'),'jsp')),',') WITHIN GROUP (ORDER BY 1)
  FROM ( SELECT SUBSTR(&1,level,1)s FROM dual
           CONNECT BY LEVEL <= LENGTH(&1)
        );

Get the input as parameter to script:

  SELECT &1 FROM dual

"create" rows by using connect by based on length of input:

  CONNECT BY LEVEL <= LENGTH(&1)

Rip out each digit from the string for each position:

  SELECT SUBSTR(&1,level,1)s FROM dual

Convert the digit to Julian date, and back to Char to get spelling:

  TO_CHAR(TO_DATE(s,'j'),'jsp')

Check for zero - special case.

  DECODE(s,0,'zero'

Use LISTAGG function to concatenate rows back into a single row list, comma delimited, ordered alphabetically

  LISTAGG(DECODE(s,0,'zero',TO_CHAR(TO_DATE(s,'j'),'jsp')),',') WITHIN GROUP (ORDER BY 1)

Always fun trying to tweak SQL for things like this ... :) really tests my knowledge of the bugger ...


问:
Add two numbers
Input: Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their sum. Use the same format for output integers as input integers. For example, the input 5 16 would lead to the output 21.

Restrictions: No standard loopholes please. This is code-golf, answer in lowest amount of bytes wins.

Notes: This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is.

Test cases:

```<code>1 2 -> 3
14 15 -> 29
7 9 -> 16
-1 8 -> 7
8 -9 -> -1
-8 -9 -> -17
</code>```

Or as CSV:

```<code>a,b,c
1,2,3
14,15,29
7,9,16
-1,8,7
8,-9,-1
-8,-9,-17
</code>```

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Shakespeare Programming Language (SPL) , <s>137</s> 135 bytes

Complete program, golfed:

```<code>.
A.
B.
Act I
Scene I
[Enter A and B]
A: Listen to your heart!
B: Listen to your heart! You are the sum of me and you. Open your heart!
</code>```

And a brief explanation:

```<code>----
.                                 <- Title, everything before the first
                                     full stop is considered as the tittle and treated as a comment
----
A.                                <- Dramatis personae. Here are introduced the characters in the play.
                                     |Characters are treated as variables.
B.                                <--
----
Act I                             <- Acts and scenes are used to divide a program into smaller
                                     chunks in order to be able to refer to them later.
                                     |
Scene I                           <--
----
[Enter A and B]                   <- Characters on stage in the current scene, which are the
                                     variables the program will have access to.
----
A: Listen to your heart!          <- Line of code. All of them have the same structure
                                     Variable: code. In this case, the concrete sentence
                                    "Listen to your heart!" reads an input number and stores it
                                     on the character (variable) refered to.
B: Listen to your heart!          <- Same as above
   You are the sum of me and you. <- Sum the values of itself and the caharacter (variable)
                                     refered to.
   Open your heart!               <- Output the value of the character (value) refered to.
</code>```

I am not actualy sure this is the shortest it can go. Check the official page for more info.

Edit 1: Removed the : after Act I and Scene I as it seems that everything after the roman numeral is ignored, thus saving 2 bytes.

Title: Add two numbers

Body:
Shakespeare Programming Language (SPL) , <s>137</s> 135 bytes

Complete program, golfed:

.
A.
B.
Act I
Scene I
[Enter A and B]
A: Listen to your heart!
B: Listen to your heart! You are the sum of me and you. Open your heart!

And a brief explanation:

----
.                                 <- Title, everything before the first
                                     full stop is considered as the tittle and treated as a comment
----
A.                                <- Dramatis personae. Here are introduced the characters in the play.
                                     |Characters are treated as variables.
B.                                <--
----
Act I                             <- Acts and scenes are used to divide a program into smaller
                                     chunks in order to be able to refer to them later.
                                     |
Scene I                           <--
----
[Enter A and B]                   <- Characters on stage in the current scene, which are the
                                     variables the program will have access to.
----
A: Listen to your heart!          <- Line of code. All of them have the same structure
                                     Variable: code. In this case, the concrete sentence
                                    "Listen to your heart!" reads an input number and stores it
                                     on the character (variable) refered to.
B: Listen to your heart!          <- Same as above
   You are the sum of me and you. <- Sum the values of itself and the caharacter (variable)
                                     refered to.
   Open your heart!               <- Output the value of the character (value) refered to.

I am not actualy sure this is the shortest it can go. Check the official page for more info.

Edit 1: Removed the : after Act I and Scene I as it seems that everything after the roman numeral is ignored, thus saving 2 bytes.


问:
Tips for code-golfing in C#
What general tips do you have for golfing in C#? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C# (e.g. "remove comments" is not an answer). Please post one tip per answer.

-- borrowed from marcog's idea ;)

答:
When to use a space and when you can remove it.

After []

int[] f(char[] a){Console.Write('a');}

int[]f(char[]a){Console.Write('a');}

Before $

return $"{a}"

return$"{a}"

example: Code golf to make logos for New Stack exchange sites

(Add yours in comment I will edit)

ContentLicense: CC BY-SA 2.5

Title: Tips for code-golfing in C#


答:
Use the one character non-short-circuiting variants of logical operators where possible:

i>0||i<42

i>0|i<42

or

i>0&&i<42

i>0&i<42

The difference between the two are one byte (yeah!) and the short-circuit principle. In our first example if i>0 is true, i<42 wont be checked. We dont need it. With the bitwise, both will be evaluated.

example: Code golf to make logos for New Stack exchange sites

Learn more about them on MSDN.

Title: Tips for code-golfing in C#

Body:
What general tips do you have for golfing in C#? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C# (e.g. "remove comments" is not an answer). Please post one tip per answer.

-- borrowed from marcog's idea ;)


答:
When you want to join something to output a string without delimiter, you should use string.Concat(), instead of string.Join("",);

string.Join("",)

string.Concat()

One byte free!

example: Code golf to make logos for New Stack exchange sites

Also Concat() has a lot more signatures than Join. Check them on MSDN: Concat and Join.

Title: Tips for code-golfing in C#


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

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

Instructions

Take an Integer as Input

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

Example

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

12345=>false or 0

1112111=>false or 0

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

-11111=>true or 1

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

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

Rules

Basic code-golf rules apply.

Good luck!

答:
Clojure, 24 bytes

```<code>#(re-find #"(.+)\1{4}"%)
</code>```

Uses clojure's falsey values of nil/false and truthy values for everything else. Specifically, nil when no match is found for false, and an array [] for true when a match is found like for 11111 then ["11111" "1"] is true.

Title: Golf to find Boring numbers

Body:
Clojure, 24 bytes

#(re-find #"(.+)\1{4}"%)

Uses clojure's falsey values of nil/false and truthy values for everything else. Specifically, nil when no match is found for false, and an array [] for true when a match is found like for 11111 then ["11111" "1"] is true.


答:
PHP (<7.0), <s>195</s> 192 bytes

Takes the program as first argument and each value as an additional argument.

Note that I tested this with split(" ",..) asn spaces rather than newlines but it should work anyway.

Gives a deprecated notice if run in php >5.3.
Also gives a warning if you go off the top of the program. However it still works and outputs correctly so it's fine.

```<code><?php foreach(split("\n",$argv[++$t])as$l)$p[]=str_split($l);for($i=-1;end($p[++$i])!='<';);array_pop($p[$i]);for(;($v=array_pop($p[$i]))!==null;$i+=$n?:-1)($n=$v)=='?'&&$n=$argv[++$t];echo$n;
</code>```

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:
PHP (<7.0), <s>195</s> 192 bytes

Takes the program as first argument and each value as an additional argument.

Note that I tested this with split(" ",..) asn spaces rather than newlines but it should work anyway.

Gives a deprecated notice if run in php >5.3.
Also gives a warning if you go off the top of the program. However it still works and outputs correctly so it's fine.

<?php foreach(split("\n",$argv[++$t])as$l)$p[]=str_split($l);for($i=-1;end($p[++$i])!='<';);array_pop($p[$i]);for(;($v=array_pop($p[$i]))!==null;$i+=$n?:-1)($n=$v)=='?'&&$n=$argv[++$t];echo$n;


答:
Python 2, 113 bytes

```<code>def f(n):c=filter(lambda x:x.isupper()^x.isdigit(),n);L=len(c);h='+'+L*'-'+'+\n';return h+'|'+c+'|\n'+h+' '*L+'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:
Python 2, 113 bytes

def f(n):c=filter(lambda x:x.isupper()^x.isdigit(),n);L=len(c);h='+'+L*'-'+'+\n';return h+'|'+c+'|\n'+h+' '*L+'v'


答:
Remember that C# uses unicode (which includes ascii). All char are int under the hood.

For example 'a' is 97.

n=>char.IsDigit(n)|char.IsUpper(n)

n=>n>47&n<58|n>64&n<91 // note that I use a bitwise comparator see

example: Code golf to make logos for New Stack exchange sites

Since char are int, you can increment them:

for(int x=31;x<126;)Console.Write((char)++x);

for(char x=' ';x<127;)Console.Write(x++);

example: Print the ASCII printable character set

Use the unicode table for reference. Be careful one byte != one character.

Title: Tips for code-golfing in C#


答:
Mathematica, 86 bytes

Code:

```<code>2^StringLength@LongestCommonSubsequence[#,"lucky"]-2StringCount[#,{"o","m","e","n"}]&
</code>```

Explanation:

LongestCommonSubsequence returns the longest contiguous substring common to the input and "lucky". StringLength gives its length. StringCount counts the number of occurrences of the characters of "omen" in the input.

Title: Determine the "Luck" of a string

Body:
Mathematica, 86 bytes

Code:

2^StringLength@LongestCommonSubsequence[#,"lucky"]-2StringCount[#,{"o","m","e","n"}]&

Explanation:

LongestCommonSubsequence returns the longest contiguous substring common to the input and "lucky". StringLength gives its length. StringCount counts the number of occurrences of the characters of "omen" in the input.


答:
C, <s>264</s> <s>249</s> <s>244</s> 242

C doesn't do so well with manipulating strings, but this is pretty short.

It works by scanning the string for the cursor (<), moving back 1 place, reading the command, replacing it with a tab character, and moving either forward or backward one line. Input is in the form of a C char array, like char array[]="1\n?<\n11\n?\n0";result = f(array);, although carriage returns are permitted as well.

Although the input string is modified, the length is not changed.

t;f(char*n){char*p=strchr(n,60);for(*p--=9;;){if(*p==63)scanf("%d",&t),*p=t+48;if(*p^49){for(*p--=9;p>n&&*p^10;--p);for(--p;p>n&&*p==9;--p);if(p<n||*p==10)return 0;}else{for(*p++=9;*p&&*p^10;++p);for(p+=!!*p;*p>10;++p);if(*--p<11)return 1;}}}
```

<h2>Test program</h2>

<p>Run this program with each test case as a separate parameter, using a single backslash in place of newlines. Test cases will be separated by a blank line.</p>

<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, const char **argv)
{
    while (*++argv)
    {
        char *input=malloc(strlen(*argv)+1),*p;
        strcpy(input,*argv);
        printf("testing %s\n",input);
        for (p=input;*p;++p)
            if (*p=='\\')
                *p=10;
        printf("result: %d\n\n",f(input));
        free(input);
    }
    return 0;
}
</code>```

Title: Run Stackylogic

Body:
C, <s>264</s> <s>249</s> <s>244</s> 242

C doesn't do so well with manipulating strings, but this is pretty short.

It works by scanning the string for the cursor (<), moving back 1 place, reading the command, replacing it with a tab character, and moving either forward or backward one line. Input is in the form of a C char array, like char array[]="1\n?<\n11\n?\n0";result = f(array);, although carriage returns are permitted as well.

Although the input string is modified, the length is not changed.

t;f(char*n){char*p=strchr(n,60);for(*p--=9;;){if(*p==63)scanf("%d",&t),*p=t+48;if(*p^49){for(*p--=9;p>n&&*p^10;--p);for(--p;p>n&&*p==9;--p);if(p<n||*p==10)return 0;}else{for(*p++=9;*p&&*p^10;++p);for(p+=!!*p;*p>10;++p);if(*--p<11)return 1;}}}

Test program

Run this program with each test case as a separate parameter, using a single backslash in place of newlines. Test cases will be separated by a blank line.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, const char **argv)
{
    while (*++argv)
    {
        char *input=malloc(strlen(*argv)+1),*p;
        strcpy(input,*argv);
        printf("testing %s\n",input);
        for (p=input;*p;++p)
            if (*p=='\\')
                *p=10;
        printf("result: %d\n\n",f(input));
        free(input);
    }
    return 0;
}


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

答:
Python 3, 43 bytes

x=int(input());print(10**len(str(x))*x+x)*x
```

Title: Print a bunch of uninteresting numbers!


答:
Haskell (134 132 Bytes)

```<code>import Data.List
c[]=[]
c s@(_:x)=inits s++c x
l=length
g q=2^(maximum$map(\z->l q-l(q\\z))$c"lucky")-2*(l$intersect q"omen")
</code>```

Not a code golfer nor a Haskell programmer, so would love some tips on this one.

(Example: g "firetruck")

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:
Haskell (134 132 Bytes)

import Data.List
c[]=[]
c s@(_:x)=inits s++c x
l=length
g q=2^(maximum$map(\z->l q-l(q\\z))$c"lucky")-2*(l$intersect q"omen")

Not a code golfer nor a Haskell programmer, so would love some tips on this one.

(Example: g "firetruck")


答:
Use Action like Func to set a function to a variable. Action returns nothing (void) so it is great for printing.

For example:

```<code>Action<string>w=Console.WriteLine;
w("Hello World");
</code>```

This tips is inspired by @W0lf great example of use of Func with ReadLine.

Title: Tips for code-golfing in C#

Body:
Use Action like Func to set a function to a variable. Action returns nothing (void) so it is great for printing.

For example:

Action<string>w=Console.WriteLine;
w("Hello World");

This tips is inspired by @W0lf great example of use of Func with ReadLine.


问:
Truncate consecutive character runs to n length

The challenge

Given an input string, and an integer n - truncate any runs of consecutive characters to a maximum of n length. The characters can be anything, including special characters. The function should be case sensitive, and n can range from 0 to infinity.

Example inputs/outputs:

```<code>f("aaaaaaabbbccCCCcc", 2) //"aabbccCCcc"
f("aaabbbc", 1) //"abc"
f("abcdefg", 0) //""
f("aaaaaaabccccccccCCCCCC@", 4) //"aaaabccccCCCC@"
</code>```

Scoring

The scoring is based on the number of bytes used.
Thus

```<code>function f(s,n){return s.replace(new RegExp("(.)\\1{"+n+",}","g"),function(x){return x.substr(0, n);});}
</code>```

would be 104 points.

Happy golfing!

Edit: removed language restriction, but I still would love to see javascript answers

答:
MATL, 9 bytes

```<code>Y'i2$X<Y"
</code>```

Try it Online

Explanation

```<code>        % Implicitly grab input as a string
Y'      % Perform run-length encoding. Pushes the values and the run-lengths to the stack
i       % Explicitly grab the second input
2$X<    % Compute the minimum of the run lengths and the max run-length
Y"      % Perform run-length decoding with these new run lengths
        % Implicitly display the result
</code>```

Body:
MATL, 9 bytes

Y'i2$X<Y"

Try it Online

Explanation

        % Implicitly grab input as a string
Y'      % Perform run-length encoding. Pushes the values and the run-lengths to the stack
i       % Explicitly grab the second input
2$X<    % Compute the minimum of the run lengths and the max run-length
Y"      % Perform run-length decoding with these new run lengths
        % Implicitly display the result


问:
Implement Takewhile

Introduction and Credit

Today without a fancy prelude: Please implement takewhile.

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

Specification

Input

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

Output

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

What to do?

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

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

Potential corner cases

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

The empty list is a valid in- and output.

Who wins?

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

Standard rules apply of course.

Test Vectors

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

Step-by-Step Example

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

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

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

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

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

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

答:
Perl 5 + Perligata, 173 bytes

145 bytes, plus 28 for -MLingua::Romana::Perligata

Use as perl -MLingua::Romana::Perligata foo.pl; input (from stdin) and output (to stdout) are underscore-separated strings of decimal integers. Tested on Strawberry 5.20.2 with version 0.6 of Perligata, released two days ago; I don't know whether it works with Perligata version 0.50.

```<code>huic vestibulo perlegementum da.his _ scindementa da.per in his fac sic
si recidementum hoc tum II fac sic I exi cis
hoc tum _ egresso scribe
cis
</code>```

Obviously this is clear as a bell. In case it's not, run it with -MLingua::Romana::Perligata=converte instead of -MLingua::Romana::Perligata, and perl will, instead of running the script, output a translation into regular Perl:

```<code> $_ = Lingua::Romana::Perligata::getline (*STDIN );
 @_ = split ( '_');
for $_ (@_) {if ( ($_ % 2)) {exit ( 1)}
;
print (STDOUT $_, '_')}
</code>```

For a token-by-token analysis, use -MLingua::Romana::Perligata=discribe.

Golfing notes:

It seems from the documentation that ultimus si recidementum hoc tum II fac. would work instead of si recidementum hoc tum II fac sic ultimus cis, saving 7 bytes. But it doesn't (it gives a "iussa absentia" error).

Undocumented (but unsurprising), you don't need a space after ..

(Also unsurprising,) scinde doesn't need a second argument, and uses hoc. Alas, exi needs an argument.

Instead of huic vestibulo perlegementum da, I tried -pMLingua::Romana::Perligata, but couldn't get it to work.

Just for kicks (although this whole answer was just for kicks):

After cleaning it up to Huic vestibulo perlegementum da. His lacunam scindementa da. Per in his fac sic si recidementum hoc tum II fac sic I exi cis. Hoc tum lacunam egresso scribe cis., Google Translate gives This court perlegementum grant. His gap scindementa grant. 2 By that time, do so in the following 1, Go out and do so if recidementum on this side. This was the gap as soon as write on this side..

Title: Implement Takewhile

Body:
Perl 5 + Perligata, 173 bytes

145 bytes, plus 28 for -MLingua::Romana::Perligata

Use as perl -MLingua::Romana::Perligata foo.pl; input (from stdin) and output (to stdout) are underscore-separated strings of decimal integers. Tested on Strawberry 5.20.2 with version 0.6 of Perligata, released two days ago; I don't know whether it works with Perligata version 0.50.

huic vestibulo perlegementum da.his _ scindementa da.per in his fac sic
si recidementum hoc tum II fac sic I exi cis
hoc tum _ egresso scribe
cis

Obviously this is clear as a bell. In case it's not, run it with -MLingua::Romana::Perligata=converte instead of -MLingua::Romana::Perligata, and perl will, instead of running the script, output a translation into regular Perl:

 $_ = Lingua::Romana::Perligata::getline (*STDIN );
 @_ = split ( '_');
for $_ (@_) {if ( ($_ % 2)) {exit ( 1)}
;
print (STDOUT $_, '_')}

For a token-by-token analysis, use -MLingua::Romana::Perligata=discribe.

Golfing notes:

It seems from the documentation that ultimus si recidementum hoc tum II fac. would work instead of si recidementum hoc tum II fac sic ultimus cis, saving 7 bytes. But it doesn't (it gives a "iussa absentia" error).

Undocumented (but unsurprising), you don't need a space after ..

(Also unsurprising,) scinde doesn't need a second argument, and uses hoc. Alas, exi needs an argument.

Instead of huic vestibulo perlegementum da, I tried -pMLingua::Romana::Perligata, but couldn't get it to work.

Just for kicks (although this whole answer was just for kicks):

After cleaning it up to Huic vestibulo perlegementum da. His lacunam scindementa da. Per in his fac sic si recidementum hoc tum II fac sic I exi cis. Hoc tum lacunam egresso scribe cis., Google Translate gives This court perlegementum grant. His gap scindementa grant. 2 By that time, do so in the following 1, Go out and do so if recidementum on this side. This was the gap as soon as write on this side..


答:
C, <s>81</s> 78

Modifies the incoming string.

c,a;f(p,n)char*p;{char*s=p;for(;*p;s+=c<n)*s=*p++,a^*s?c=0:++c,a=*s;c=a=*s=0;}
```

<h2>Test Program</h2>

<p>Requires two parameters, the first is the string to truncate, the second is the length limit.</p>

<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, const char **argv)
{
    char *input=malloc(strlen(argv[1])+1);
    strcpy(input,argv[1]);
    f(input,atoi(argv[2]));
    printf("%s\n",input);
    free(input);
    return 0;
}
</code>```

Explanation:

c,a;                 //declare two global integers, initialized to zero.
                     //c is the run length, a is the previous character
f(char*p,int n){...} //define function f to truncate input
char*s=p;            //copy p to s; p is source, s is destination
for(;*p              //while there is a source character
;s+=c<n)             //increment copied pointer if run is under the limit
*s=*p++,             //copy from source to destination, increment source
a^*s?c=0:++c,        //if previous character != current then run=0 else increment run
a=*s;                //previous character = current source character
c=a=*s=0;            //after loop, terminate destination string with NUL and reset c and a.
```

This works because the source pointer will always be equal to or greater than the destination pointer, so we can write over the string as we parse it.

Title: Truncate consecutive character runs to n length

Body:
The challenge

Given an input string, and an integer n - truncate any runs of consecutive characters to a maximum of n length. The characters can be anything, including special characters. The function should be case sensitive, and n can range from 0 to infinity.

Example inputs/outputs:

```<code>f("aaaaaaabbbccCCCcc", 2) //"aabbccCCcc"
f("aaabbbc", 1) //"abc"
f("abcdefg", 0) //""
f("aaaaaaabccccccccCCCCCC@", 4) //"aaaabccccCCCC@"
</code>```

Scoring

The scoring is based on the number of bytes used.
Thus

```<code>function f(s,n){return s.replace(new RegExp("(.)\\1{"+n+",}","g"),function(x){return x.substr(0, n);});}
</code>```

would be 104 points.

Happy golfing!

Edit: removed language restriction, but I still would love to see javascript answers

Body:
C, <s>81</s> 78

Modifies the incoming string.

c,a;f(p,n)char*p;{char*s=p;for(;*p;s+=c<n)*s=*p++,a^*s?c=0:++c,a=*s;c=a=*s=0;}

Test Program

Requires two parameters, the first is the string to truncate, the second is the length limit.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, const char **argv)
{
    char *input=malloc(strlen(argv[1])+1);
    strcpy(input,argv[1]);
    f(input,atoi(argv[2]));
    printf("%s\n",input);
    free(input);
    return 0;
}

Explanation:

c,a;                 //declare two global integers, initialized to zero.
                     //c is the run length, a is the previous character
f(char*p,int n){...} //define function f to truncate input
char*s=p;            //copy p to s; p is source, s is destination
for(;*p              //while there is a source character
;s+=c<n)             //increment copied pointer if run is under the limit
*s=*p++,             //copy from source to destination, increment source
a^*s?c=0:++c,        //if previous character != current then run=0 else increment run
a=*s;                //previous character = current source character
c=a=*s=0;            //after loop, terminate destination string with NUL and reset c and a.

This works because the source pointer will always be equal to or greater than the destination pointer, so we can write over the string as we parse it.


答:
dc - 11 chars

```<code>15k5v2/.5+p
</code>```

The most character-consuming task is setting the decimal precision..

Title: Calculate golden ratio

Body:
Write the shortest code, in number of bytes, to display, return, or evaluate to the golden ratio (that is, the positive root of the quadratic equation: \$x^2-x-1=0\$, approximately
1.618033988749895), to at least 15 significant figures. No input will be given to your program.

Sample in Stutsk programming language:

```<code>1 100 { 1 + 1 swp / } repeat print
</code>```

Body:
dc - 11 chars

15k5v2/.5+p

The most character-consuming task is setting the decimal precision..


答:
CJam, 12 bytes

```<code>{e`\af.e<e~}
</code>```

Try it online!

Explanation

```<code>e`   e# Run-length encode the input. Gives a list of pair [length character].
\a   e# Swap with maximum and wrap in an array.
f.e< e# For each run, clamp the run-length to the given maximum.
e~   e# Run-length decode.
</code>```

Body:
CJam, 12 bytes

{e`\af.e<e~}

Try it online!

Explanation

e`   e# Run-length encode the input. Gives a list of pair [length character].
\a   e# Swap with maximum and wrap in an array.
f.e< e# For each run, clamp the run-length to the given maximum.
e~   e# Run-length decode.


答:
Javascript ES5, 73

```<code>function f(s,n){return s.replace(RegExp("(.)(\\1{"+n+"})\\1*","g"),"$2")}
</code>```

Re-uses Lynn's regex from her Python answer.

Body:
Javascript ES5, 73

function f(s,n){return s.replace(RegExp("(.)(\\1{"+n+"})\\1*","g"),"$2")}

Re-uses Lynn's regex from her Python answer.


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

```
<s>rm,hS,Qhdedrz8 9</s>
ss<RQmM_Mrz8
```

Try it online!

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

<s>rm,hS,Qhdedrz8 9</s>
ss<RQmM_Mrz8

Try it online!


答:
Python 2, 56 bytes

```<code>import re
lambda s,n:re.sub(r'(.)(\1{%d})\1*'%n,r'\2',s)
</code>```

Body:
Python 2, 56 bytes

import re
lambda s,n:re.sub(r'(.)(\1{%d})\1*'%n,r'\2',s)


答:
Haskell, 36 bytes

```<code>import Data.List
(.group).(=<<).take
</code>```

Point-free version of \n s -> concatMap (take n) (group s).

Body:
Haskell, 36 bytes

import Data.List
(.group).(=<<).take

Point-free version of \n s -> concatMap (take n) (group s).


答:
Python (139 Bytes)

```<code>import itertools as t
s=input()
print 2**max([j-i for i,j in t.combinations(range(6),2)if'lucky'[i:j]in s]+[0])-2*sum(_ in'omen'for _ in s)
</code>```

Title: Determine the "Luck" of a string

Body:
Python (139 Bytes)

import itertools as t
s=input()
print 2**max([j-i for i,j in t.combinations(range(6),2)if'lucky'[i:j]in s]+[0])-2*sum(_ in'omen'for _ in s)


问:
Normal sentences
Write a program or function which, given an input string and a standard deviation σ, outputs that string along the normal distribution curve with mean 0 and standard deviation σ.

Normal distribution curve

The y coordinate of each character c is:

where σ is given as input, and where x is the x axis coordinate of c.

The character in the center of the string has x = 0. If the string's length is even, either of the two middle characters can be chosen as the center.

Characters are separated by steps of 0.1 (e.g. the character to the left of the center one has x = -0.1, the one to the right of the middle one has x = 0.1, etc.).

Printing the string

Lines, like characters, are separated by steps of 0.1.

Each character is printed on the line with the y value that is closest to its own y value (if the value is precisely in between the values of two lines, choose the one with the biggest value (just like how round usually returns 1.0 for 0.5)).

For example, if the y coordinate of the center value (i.e. the maximum value) is 0.78 and the y coordinate of the first character is 0.2, then there will 9 lines: the center character being printed on line 0 and the first character being printed on line 8.

Inputs and outputs

You may take both inputs (the string and σ) as program arguments, through STDIN, function arguments or anything similar in your language.

The string will only contain printable ASCII characters. The string can be empty.

σ > 0.

You may print the output to STDOUT, in a file, or return it from a function (as long as it is a string and not say a list of strings for each line).

A trailing new line is acceptable.

Trailing spaces are acceptable as long as they don't make the line exceed the last line in length (so no trailing space is acceptable on the last line).

Test cases

```<code>σ    String

0.5  Hello, World!

     , W
   lo   or
  l       l
 e         d
H           !

0.5  This is a perfectly normal sentence

                tly
              ec    n
             f       o
            r         r
           e           m
          p             a
        a                l
      s                    se
This i                       ntence

1.5  Programming Puzzles & Code Golf is a question and answer site for programming puzzle enthusiasts and code golfers.

                                                d answer site for p
                                      uestion an                   rogramming
                      Code Golf is a q                                        puzzle enthusia
Programming Puzzles &                                                                        sts and code golfers.

0.3  .....................

          .
         . .

        .   .

       .     .

      .       .

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

Scoring

This is code-golf,

```<code>                 nsw
                a   er
              t
             s         i
            e           n
           t
         or               by
       sh                   te
so the                        s wins.
</code>```

Title: Normal sentences

Body:
Ruby: <s>273</s> 254 Bytes

->n,s{j,o,g,r,l=-(n.size/2),[],0,{}
n.gsub(/./){(r[((2*Math::PI)**-0.5*10*Math.exp(-(j/1e1)**2/2/s/s)/s).round]||="")<<$&
j+=1}
r.sort.map{|y, c|o<<(l ?$/*(y-l-1):"")+(" "*g)+(c[0,(h=c.size)/2])+(" "*(n.size-g*2-h))+(c[h/2,h])
g+=h/2
l=y}
puts o.reverse}

A huge thanks to Kevin Lau for saving 18 bytes!