答:
JavaScript, 147 bytes

Conor´s answer fixed with the regex from my PHP answer and golfed down.

```<code>t=i=>i.match(/(\d)\1*|\*/g).map(w=>(" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]]||"*")[w.length-1]).join``.replace(/.\*/g,"")
</code>```

breakdown

```<code>t=i=>i
    .match(/(\d)\1*|\*/g)   // split input to streaks of equal numbers and single `*`
    .map(w=>                // replace each item with ...
                            // .. take string depending on the digit
        (" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]]
        ||"*")              // .. ("*" for not a digit)
        [w.length-1]        // -> the (item length)th character of that string
    )
    .join``                 // join without delimiter
    .replace(/.\*/g,"")     // and recursively remove every (letter,asterisk) combination
</code>```

rotating version, 158 bytes

added s= to remember the string and %s.length to rotate.

```<code>t=i=>i.match(/(\d)\1*|\*/g).map(w=>(s=" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]]||"*")[w.length%s.length-1]).join``.replace(/.\*/g,"")
</code>```

Title: Create a T9 keyboard

Body:
This question asks for a T9 dictionary matching functionality which is a very interesting problem. But T9 has another way of typing and that is typing character-by-character. You would NOT need a dictionary to implement this keyboard.

Here is key-map of a T9 keyboard if you forgot:

```<code>+-------+-------+-------+
|   1   |   2   |   3   |
|  .?!  |  ABC  |  DEF  |
+-------+-------+-------+
|   4   |   5   |   6   |
|  GHI  |  JKL  |  MNO  |
+-------+-------+-------+
|   7   |   8   |   9   |
| PQRS  |  TUV  |  WXYZ |
+-------+-------+-------+
|   *   |   0   |   #   |
|   ←   | SPACE |   →   |
+-------+-------+-------+
</code>```

How T9 works

To type a character with T9, you need to press number key representing that character n times. n is order of that character written on that key. Numbers are the last character you can type for each key. For example, to type B I press 2 two times, or to type 5 I press 5 four times. To finish typing this character I press #. * is simply backspace. In our version of keyboard there is no capitalization.

Input and output examples:

```<code>8#99999#055#33#999#22#666#2#777#3# → T9 KEYBOARD
</code>```

Explanation:

8 selects T and # moves to next character

99999 select last character of 9 key which is 9 and # moves to next charachter

0 inserts a space

33 selects second character of  3 key which is K and # moves to next character

And so on...

Rules

Your function or program should accept a string representing T9 keypresses. Output is the resulting text from those keypresses, as outlined above.

This is basic code golf, so the winner is shortest in bytes, and standard rules/loopholes apply.

Body:
JavaScript, 147 bytes

Conor´s answer fixed with the regex from my PHP answer and golfed down.

t=i=>i.match(/(\d)\1*|\*/g).map(w=>(" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]]||"*")[w.length-1]).join``.replace(/.\*/g,"")

breakdown

t=i=>i
    .match(/(\d)\1*|\*/g)   // split input to streaks of equal numbers and single `*`
    .map(w=>                // replace each item with ...
                            // .. take string depending on the digit
        (" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]]
        ||"*")              // .. ("*" for not a digit)
        [w.length-1]        // -> the (item length)th character of that string
    )
    .join``                 // join without delimiter
    .replace(/.\*/g,"")     // and recursively remove every (letter,asterisk) combination

rotating version, 158 bytes

added s= to remember the string and %s.length to rotate.

t=i=>i.match(/(\d)\1*|\*/g).map(w=>(s=" 0~.?!1~ABC2~DEF3~GHI4~JKL5~MNO6~PQRS7~TUV8~WXYZ9".split`~`[w[0]]||"*")[w.length%s.length-1]).join``.replace(/.\*/g,"")


问:
StringgnirtSStringgnirtSStringgnirtS
Here is a relatively simple challenge for you.

Given a string of length N, output the string forwards, then backwards, then forwards, then backwards... etc. N times. For example, if your input was

```<code>Hello!
</code>```

You should output:

```<code>Hello!!olleHHello!!olleHHello!!olleH
</code>```

You may also optionally output one trailing newline.

Your submission may be either a full program or a function, and you may take input and output in any reasonable format. For example, you may take IO from STDIN/STDOUT, function arguments and return value, from a file, etc. You can safely assume that the input string will not be empty, and will only contain printable ASCII. You must output the new string on a single line. So, for example, if the output to the last example was

```<code>Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
</code>```

This would not be a valid solution!

Here are some more test cases:

```<code>Input:
a
Output:
a

Input:
abcd
Output:
abcddcbaabcddcba

Input:
OK!
Output:
OK!!KOOK!

Input:
4815162342
Output:
4815162342243261518448151623422432615184481516234224326151844815162342243261518448151623422432615184

Input:
PPCG
Output:
PPCGGCPPPPCGGCPP

Input:
42
Output:
4224
</code>```

Leaderboards

Since this is a code-golf challenge, standard loopholes are banned, and the shortest answer in bytes wins! However, this is also a competition to have the shortest answer in any particular langauge. While it's unlikely that a Java answer will beat an answer in perl, or some golfing language, it's still very impressive to have the shortest Java answer. So, you can use this leaderboard to see both

The shortest answer out of all languages, and

The shortest answer in each individual language.

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 leaderboard snippet:

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

var QUESTION_ID=93261,OVERRIDE_USER=31716;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

```

答:
Vim, <s>39</s>, 34 keystrokes

```<code>:se ri
Y:s/./<C-r>"/g
<C-o>qqgJC<C-r>"<esc>gJ@qq@q
</code>```

5 bytes saved thanks to @Lynn!

Here is a gif of it happening live: (Note that this gif is of a previous version since I haven't had time to re-record it yet).

And here is an explanation of how it works:

```<code>:se ri                  "Turn 'reverse indent' on.
Y                       "Yank this line
:s/./<C-r>"/g           "Replace every character on this line with the register
                        "We just yanked followed by a newline
<C-o>                   "Jump to our previous location
     qq                 "Start recording in register 'q'
       gJ               "Join these two lines
         C              "Delete this line, and enter insert mode
          <C-r>"<esc>   "Paste the line we just deleted backwards
gJ                      "Join these two lines
  @q                    "Call macro 'q'. This will run until we hit the bottom of the buffer.
    q                   "Stop recording.
     @q                 "Start our recursive macro
</code>```

On a side note, Y grabs an extra newline, which is usually an obnoxious feature. This is probably the first ever time that it has actually saved several bytes!

ContentLicense: CC BY-SA 3.0

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Vim, <s>39</s>, 34 keystrokes

:se ri
Y:s/./<C-r>"/g
<C-o>qqgJC<C-r>"<esc>gJ@qq@q

5 bytes saved thanks to @Lynn!

Here is a gif of it happening live: (Note that this gif is of a previous version since I haven't had time to re-record it yet).

And here is an explanation of how it works:

:se ri                  "Turn 'reverse indent' on.
Y                       "Yank this line
:s/./<C-r>"/g           "Replace every character on this line with the register
                        "We just yanked followed by a newline
<C-o>                   "Jump to our previous location
     qq                 "Start recording in register 'q'
       gJ               "Join these two lines
         C              "Delete this line, and enter insert mode
          <C-r>"<esc>   "Paste the line we just deleted backwards
gJ                      "Join these two lines
  @q                    "Call macro 'q'. This will run until we hit the bottom of the buffer.
    q                   "Stop recording.
     @q                 "Start our recursive macro

On a side note, Y grabs an extra newline, which is usually an obnoxious feature. This is probably the first ever time that it has actually saved several bytes!


问:
An A , or An An?
In English, there is the fun and simple difference between an and a: you use an when preceding a word starting with a vowel sound, and a when the word starts with a consonant sound.

For the sake of simplicity in this challenge, an precedes a word that starts with a vowel (aeiou), and a precedes a word that starts with a consonant.

Input

A string comprising only printable ASCII characters, with [?] appearing in places where you must choose to insert an or a. [?] will always appear before a word. You can assume that the sentence will be grammatically correct and formatted like normal.

Output

The input string with [?] replaced with the appropriate word (an or a). You do have to worry about capitalization!

When to Capitalize

Capitalize a word if it is preceded by no characters (is the first one in the input) or if it is preceded by one of .?! followed by a space.

Examples

```<code>Input: Hello, this is [?] world!
Output: Hello, this is a world!

Input: How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.
Output: How about we build a big building. It will have an orange banana hanging out of a window.

Input: [?] giant en le sky.
Output: A giant en le sky.

Input: [?] yarn ball? [?] big one!
Output: A yarn ball? A big one!

Input: [?] hour ago I met [?] European.
Output: A hour ago I met an European.

Input: Hey sir [Richard], how 'bout [?] cat?
Output: Hey sir [Richard], how 'bout a cat?
</code>```

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

答:
Minkolang 0.15, 75 bytes

```<code>od4&r$O."]?["30$Z3&00w4X"Aa"I2-"Aa ."40$Z,*2&$rxr$O" aeiou"od0Z1=3&"n"r5X$r
</code>```

Try it here!

Explanation

```<code>od                                                                    Take character from input and duplicate (0 if input is empty)
  4&                                                                  Pop top of stack; jump 4 spaces if not 0
    r$O.                                                              Reverse stack, output whole stack as characters, and stop.

    "]?["                                                             Push "[?]" on the stack
         30$Z                                                         Pop the top 3 items and count its occurrences in the stack
              3&                                                      Pop top of stack; jump 3 spaces if not 0
                00w                                                   Wormhole to (0,0) in the code box

                3X                                                    Dump the top 3 items of stack
                  "Aa"                                                Push "aA"
                      I2-                                             Push the length of stack minus 2
                         "Aa ."40$Z,                                  Push ". aA" and count its occurrences, negating the result
                                    *                                 Multiply the top two items of the stack
                                     2&$r                             Pop top of stack and swap the top two items if 0
                                         x                            Dump top of stack
                                          r                           Reverse stack
                                           $O                         Output whole stack as characters
                                             " aeiou"                 Push a space and the vowels
                                                     od               Take a character from input and duplicate
                                                       0Z             Pop top of stack and count its occurrences in the stack (either 1 or 2)
                                                         1=           1 if equal to 1, 0 otherwise
                                                           3&         Pop top of stack; jump 3 spaces if not 0
                                                             "n"      Push "n" if top of stack is 0

                                                             r        Reverse stack
                                                              5X      Dump top five items of stack
                                                                $r    Swap top two items of stack
</code>```

Note that because Minkolang is toroidal, when the program counter moves off the right edge, it reappears on the left. Certainly golfable, but because I had to add 21 bytes because of the spec, I may not try.

Title: An A , or An An?

Body:
Minkolang 0.15, 75 bytes

od4&r$O."]?["30$Z3&00w4X"Aa"I2-"Aa ."40$Z,*2&$rxr$O" aeiou"od0Z1=3&"n"r5X$r

Try it here!

Explanation

od                                                                    Take character from input and duplicate (0 if input is empty)
  4&                                                                  Pop top of stack; jump 4 spaces if not 0
    r$O.                                                              Reverse stack, output whole stack as characters, and stop.

    "]?["                                                             Push "[?]" on the stack
         30$Z                                                         Pop the top 3 items and count its occurrences in the stack
              3&                                                      Pop top of stack; jump 3 spaces if not 0
                00w                                                   Wormhole to (0,0) in the code box

                3X                                                    Dump the top 3 items of stack
                  "Aa"                                                Push "aA"
                      I2-                                             Push the length of stack minus 2
                         "Aa ."40$Z,                                  Push ". aA" and count its occurrences, negating the result
                                    *                                 Multiply the top two items of the stack
                                     2&$r                             Pop top of stack and swap the top two items if 0
                                         x                            Dump top of stack
                                          r                           Reverse stack
                                           $O                         Output whole stack as characters
                                             " aeiou"                 Push a space and the vowels
                                                     od               Take a character from input and duplicate
                                                       0Z             Pop top of stack and count its occurrences in the stack (either 1 or 2)
                                                         1=           1 if equal to 1, 0 otherwise
                                                           3&         Pop top of stack; jump 3 spaces if not 0
                                                             "n"      Push "n" if top of stack is 0

                                                             r        Reverse stack
                                                              5X      Dump top five items of stack
                                                                $r    Swap top two items of stack

Note that because Minkolang is toroidal, when the program counter moves off the right edge, it reappears on the left. Certainly golfable, but because I had to add 21 bytes because of the spec, I may not try.


答:
Java, 151 bytes

```<code>public static void r(String s){String t = new StringBuffer(s).reverse().toString();for(int i=0;i<s.length();i++){System.out.print(((i%2==1)?t:s));}}
</code>```

}

Ungolfed:

```<code>public static void r(String s) {
    String t = new StringBuffer(s).reverse().toString();
    for(int i = 0; i < s.length();i++) {
        System.out.print(((i % 2 == 1) ? t : s));
    }
}
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Here is a relatively simple challenge for you.

Given a string of length N, output the string forwards, then backwards, then forwards, then backwards... etc. N times. For example, if your input was

```<code>Hello!
</code>```

You should output:

```<code>Hello!!olleHHello!!olleHHello!!olleH
</code>```

You may also optionally output one trailing newline.

Your submission may be either a full program or a function, and you may take input and output in any reasonable format. For example, you may take IO from STDIN/STDOUT, function arguments and return value, from a file, etc. You can safely assume that the input string will not be empty, and will only contain printable ASCII. You must output the new string on a single line. So, for example, if the output to the last example was

```<code>Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
</code>```

This would not be a valid solution!

Here are some more test cases:

```<code>Input:
a
Output:
a

Input:
abcd
Output:
abcddcbaabcddcba

Input:
OK!
Output:
OK!!KOOK!

Input:
4815162342
Output:
4815162342243261518448151623422432615184481516234224326151844815162342243261518448151623422432615184

Input:
PPCG
Output:
PPCGGCPPPPCGGCPP

Input:
42
Output:
4224
</code>```

Leaderboards

Since this is a code-golf challenge, standard loopholes are banned, and the shortest answer in bytes wins! However, this is also a competition to have the shortest answer in any particular langauge. While it's unlikely that a Java answer will beat an answer in perl, or some golfing language, it's still very impressive to have the shortest Java answer. So, you can use this leaderboard to see both

The shortest answer out of all languages, and

The shortest answer in each individual language.

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 leaderboard snippet:

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Java, 151 bytes

public static void r(String s){String t = new StringBuffer(s).reverse().toString();for(int i=0;i<s.length();i++){System.out.print(((i%2==1)?t:s));}}

}

Ungolfed:

public static void r(String s) {
    String t = new StringBuffer(s).reverse().toString();
    for(int i = 0; i < s.length();i++) {
        System.out.print(((i % 2 == 1) ? t : s));
    }
}


答:
Perl, 48 bytes

Saved 1 byte due to Ton Hospel.

#!perl -p
s;\[\?];A.n x$'=~/^ [aeiou]/i^$"x/[^.?!] \G/;eg
```

<p>Counting the shebang as one, input is taken from stdin.</p>

<p><strong>Explanation</strong></p>

<pre class="lang-perl prettyprint-override"><code>#!perl -p               # for each line of input, set $_, auto-print result

s;                      # begin regex substitution, with delimiter ;
\[\?]                   # match [?] literally, and replace with:
;
A.n x$'=~/^ [aeiou]/i   # 'A', concatenate with 'n' if post-match ($')
                        #   matches space followed by a vowel
^$"x/[^.?!] \G/         # if the match is preceded by /[^.?!] /, xor with a space
                        #   this will change An -> an

;eg                     # regex options eval, global
</code>```

Sample Usage

$ echo Hello, this is [?] world! | perl a-an.pl
Hello, this is a world!

$ echo How about we build [?] big building. It will have [?] orange banana hanging out of [?] window. | perl a-an.pl
How about we build a big building. It will have an orange banana hanging out of a window.

$ echo [?] giant en le sky. [?] yarn ball? | perl a-an.pl
A giant en le sky. A yarn ball?

$ echo [?] hour ago I met [?] European. | perl a-an.pl
A hour ago I met an European.
```

Title: An A , or An An?

Body:
In English, there is the fun and simple difference between an and a: you use an when preceding a word starting with a vowel sound, and a when the word starts with a consonant sound.

For the sake of simplicity in this challenge, an precedes a word that starts with a vowel (aeiou), and a precedes a word that starts with a consonant.

Input

A string comprising only printable ASCII characters, with [?] appearing in places where you must choose to insert an or a. [?] will always appear before a word. You can assume that the sentence will be grammatically correct and formatted like normal.

Output

The input string with [?] replaced with the appropriate word (an or a). You do have to worry about capitalization!

When to Capitalize

Capitalize a word if it is preceded by no characters (is the first one in the input) or if it is preceded by one of .?! followed by a space.

Examples

```<code>Input: Hello, this is [?] world!
Output: Hello, this is a world!

Input: How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.
Output: How about we build a big building. It will have an orange banana hanging out of a window.

Input: [?] giant en le sky.
Output: A giant en le sky.

Input: [?] yarn ball? [?] big one!
Output: A yarn ball? A big one!

Input: [?] hour ago I met [?] European.
Output: A hour ago I met an European.

Input: Hey sir [Richard], how 'bout [?] cat?
Output: Hey sir [Richard], how 'bout a cat?
</code>```

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

Body:
Perl, 48 bytes

Saved 1 byte due to Ton Hospel.

#!perl -p
s;\[\?];A.n x$'=~/^ [aeiou]/i^$"x/[^.?!] \G/;eg

Counting the shebang as one, input is taken from stdin.

Explanation

#!perl -p               # for each line of input, set $_, auto-print result

s;                      # begin regex substitution, with delimiter ;
\[\?]                   # match [?] literally, and replace with:
;
A.n x$'=~/^ [aeiou]/i   # 'A', concatenate with 'n' if post-match ($')
                        #   matches space followed by a vowel
^$"x/[^.?!] \G/         # if the match is preceded by /[^.?!] /, xor with a space
                        #   this will change An -> an

;eg                     # regex options eval, global

Sample Usage

$ echo Hello, this is [?] world! | perl a-an.pl
Hello, this is a world!

$ echo How about we build [?] big building. It will have [?] orange banana hanging out of [?] window. | perl a-an.pl
How about we build a big building. It will have an orange banana hanging out of a window.

$ echo [?] giant en le sky. [?] yarn ball? | perl a-an.pl
A giant en le sky. A yarn ball?

$ echo [?] hour ago I met [?] European. | perl a-an.pl
A hour ago I met an European.


答:
2sable, 3 bytes

Code:

```<code>gGÂ
</code>```

Explanation:

```<code>g   # Get the length of the input
 G  # Do the following n - 1 times:
  Â # Bifurcate, which duplicates a and reverses the duplicate
</code>```

Uses the CP-1252 encoding. Try it online!

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
2sable, 3 bytes

Code:

gGÂ

Explanation:

g   # Get the length of the input
 G  # Do the following n - 1 times:
  Â # Bifurcate, which duplicates a and reverses the duplicate

Uses the CP-1252 encoding. Try it online!


答:
Actually, 12 bytes

```<code>;;l)Rkp;)αHΣ
</code>```

Try it online!

Explanation:

```<code>;;l)Rkp;)αHΣ
;;l           dupe string twice, use one copy to get length (call it L)
   )          move length to bottom of stack
    R         reverse one copy of string
     k        pop entire stack and push as list
      p       pop L from list
       ;)     dupe L, move one copy to bottom
         α    repeat each element (the forward and reversed string) of the list L times
          H   first L elements in list (trim off excess elements)
           Σ  concatenate
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Actually, 12 bytes

;;l)Rkp;)αHΣ

Try it online!

Explanation:

;;l)Rkp;)αHΣ
;;l           dupe string twice, use one copy to get length (call it L)
   )          move length to bottom of stack
    R         reverse one copy of string
     k        pop entire stack and push as list
      p       pop L from list
       ;)     dupe L, move one copy to bottom
         α    repeat each element (the forward and reversed string) of the list L times
          H   first L elements in list (trim off excess elements)
           Σ  concatenate


问:
Test if given number is a Keith number
Since Fibonacci numbers and sequences seems like a popular subject for code golf I thought that it might be a fun challenge to code golf with Keith numbers.

So I propose a challenge that is to create a function that takes an integer and gives back a true or false depending on the number is a Keith number or not.

More about Keith numbers

In recreational mathematics, a Keith number or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence:
  14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, …

Numberphile has a video explaining how to calculate a Keith number. But basically you take the digits of a number. Add them together and then take the last digits of the original number and add them to the sum of the calculation, rinse and repeat. And example to make it clear.

14
1 + 4 = 5

  4 + 5 = 9

  5 + 9 = 14

Input

An integer.

Output

True if the number is a Keith number. False if it's not..

ContentLicense: CC BY-SA 4.0

Title: Test if given number is a Keith number

Body:
C, 123

k(v){
    int g[9],i,n,s,t=v;
    for(n=s=0;t;t/=10)s+=g[n++]=t%10;
    for(i=n;s<v;){
        i=(i+n-1)%n;
        t=g[i];g[i]=s;s=s*2-t;
    }
    return n>1&&s==v;
}

test via harness:

main(i){
    for(i=0;i<20000;i++)
        if(k(i)) printf("%d ",i);
}

gives:

14 19 28 47 61 75 197 742 1104 1537 2208 2580 3684 4788 7385 7647 7909


答:
JavaScript (ES 6), <s>59</s> 50 bytes

9 Bytes thanks to Hedi and Huntro.

```<code>f=(s,n=1)=>s[n]?s+f([...s].reverse().join``,n+1):s
</code>```

recursive function.

Reversing the string takes almost half of the size (<s>25</s> 22 bytes!) ...

Why isn´t there a native way for that?

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
JavaScript (ES 6), <s>59</s> 50 bytes

9 Bytes thanks to Hedi and Huntro.

f=(s,n=1)=>s[n]?s+f([...s].reverse().join``,n+1):s

recursive function.

Reversing the string takes almost half of the size (<s>25</s> 22 bytes!) ...

Why isn´t there a native way for that?


答:
PHP, 54 bytes

```<code>while($i++<strlen($s=$argv[1])){echo$s;$s=strrev($s);}
</code>```

There are a lot of ways to do that, in almost every language I guess.

These two are my favourites:

an evil eval (62 bytes)

```<code>eval(str_repeat('echo$s;$s=strrev($s);',strlen($s=$argv[1])));
</code>```

and a substr solution (69 bytes)

```<code><?=substr(str_repeat(($s=$argv[1]).strrev($s),$n=strlen($s)),-$n*$n);
</code>```

and while we´re at unsensible coding, take these 61:

```<code>$s=$argv[1];L:echo$s;$s=strrev($s);if(++$i<strlen($s))goto L;
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
PHP, 54 bytes

while($i++<strlen($s=$argv[1])){echo$s;$s=strrev($s);}

There are a lot of ways to do that, in almost every language I guess.

These two are my favourites:

an evil eval (62 bytes)

eval(str_repeat('echo$s;$s=strrev($s);',strlen($s=$argv[1])));

and a substr solution (69 bytes)

<?=substr(str_repeat(($s=$argv[1]).strrev($s),$n=strlen($s)),-$n*$n);

and while we´re at unsensible coding, take these 61:

$s=$argv[1];L:echo$s;$s=strrev($s);if(++$i<strlen($s))goto L;


答:
PHP, <s>54</s> 52 bytes

(49 bytes, but do not work if string contains '0')

```<code>for(;($a=$argv[1])[$i++];)echo$i%2?$a:strrev($a);
</code>```

(52 bytes)

```<code><?=str_pad('',strlen($a=$argv[1])**2,$a.strrev($a));
</code>```

(54 bytes)

```<code>for(;$i++<strlen($a=$argv[1]);)echo$i%2?$a:strrev($a);
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
PHP, <s>54</s> 52 bytes

(49 bytes, but do not work if string contains '0')

for(;($a=$argv[1])[$i++];)echo$i%2?$a:strrev($a);

(52 bytes)

<?=str_pad('',strlen($a=$argv[1])**2,$a.strrev($a));

(54 bytes)

for(;$i++<strlen($a=$argv[1]);)echo$i%2?$a:strrev($a);


答:
Brain-Flak, <s>418</s> <s>378</s> 228 bytes

This is my Brain-Flak masterpiece.  It may not be well golfed but the challenge is the most difficult I have ever encountered.

Try it online!

```<code>(([])[()]){({}[()]<(({}(<()>))<{({}[()]<(({}()<(({}<>))>)<({()<({}[()]<({}<({}<>)<>>)>)>}{}<>){({}[()]<({}<>)<>>)}{}>)>)}{}{}<>([]){{}({}<>)<>([])}{}<>>)>)}{}([(({}))]{({})({}[()])}{}){(({}[({}<>)<>])<<>({}<><{(({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}<>([]){{}({}<>)<>([])}{}<>>)}{}>)>)}
</code>```

Explanation

This explanation is now a bit outdated but it still does a pretty good job of explaining the program.

This explanation is going to go a little different from my regular explanation process.  I am going to explain how I came about this result rather than explain the result in order.  Here it goes:

Roller

After working at the problem a quite a bit I came up with this code:

```<code>(n[()])({()<({}[()]<({}<({}<>)<>>)>)>}{}<>){({}[()]<({}<>)<>>)}{}<>
</code>```

This code (where n is the literal for some number. e.g. ()()) will take the item on the top of the stack and move it down n steps.  With n as the stack height this will perform a stack "roll".  i.e. move the top item to the bottom of the stack.  Here's how it works:

We put the place we want to move the item to minus one on the stack.  Why minus one?  I don't know it just works that way.

```<code>(n[()])
</code>```

We then loop until this number reaches zero keeping track of the loop with a ().

```<code>{()<({}[()]<...>)>)>}{}
</code>```

Each time we loop we pick up the top item and move the item underneath it to the other stack.  This puts the number on top in its place.

```<code>({}<({}<>)<>>)
</code>```

All we need to do now is put the numbers we moved back.  We switch to the off stack and push the number of runs the loop made.

```<code>(...<>)
</code>```

We loop decrementing the newly pushed number until it reaches zero.  Each time we move one number back.

```<code>{({}[()]<({}<>)<>>)}{}<>
</code>```

Reverse

I next modified the roll to make a full stack reverse:

```<code>(n){(({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}<>([]){{}({}<>)<>([])}{}<>>)}{}
</code>```

Once again n represents the depth of the reverse.  That is the top n items on the stack will be reversed.  How it works:

The reverse is just a fancily wrapped roller.  We simply roll the top of the stack n times decrementing the depth of the roll by one each time.

```<code>(n){(({}[()])<ROLLER>)}{}
</code>```

Duplicate

In place duplication is hard. Really hard.  After I figured out how to reverse the stack it still took a great deal of effort to come up with the duplication algorithm.

Here it is:

```<code>(((n)<{({}[()]<(({}<>))<>>)}{}<>>)<{({}[()]<({}<>)<>([][()])({()<({}[()]<({}<({}<>)<>>)>)>}{}<>){({}[()]<({}<>)<>>)}{}<>>)}{}<>([]){{}({}<>)<>([])}{}<>([]){(({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}<>([]){{}({}<>)<>([])}{}<>>)}{}>)
</code>```

Its a bit of a big one but here's how it works:

Start by pushing n.  n is the depth of the duplicate.  We also open two parentheses.  These allow us to store the value of the n in the scope until its needed again.

```<code>(n[()])({()<({}[()]<({}<({}<>)<>>)>)>}{}<>){({}[()]<({}<>)<>>)}{}<>
</code>```0

Next we loop n times each time pushing the top value of the stack to the off stack twice.  This makes the initial duplicates for each number on the stack.

```<code>(n[()])({()<({}[()]<({}<({}<>)<>>)>)>}{}<>){({}[()]<({}<>)<>>)}{}<>
</code>```1

Now we have two copies of each number on the offstack.  We need to separate these into two groups.

So we switch to the offstack and recall one of the ns we saved at the beginning.

```<code>(n[()])({()<({}[()]<({}<({}<>)<>>)>)>}{}<>){({}[()]<({}<>)<>>)}{}<>
</code>```2

We loop n times.

```<code>{({}[()]<...>)}{}
</code>```

Each time we move one copy to the mainstack.

```<code>({}<>)<>
</code>```

And roll one copy to the bottom of the stack. (This assumes the offstack was empty to begin with making this duplicate not stack clean)

```<code>([][()])ROLLER
</code>```

Once that is done we have split the original into two groups the "original" and a copy on the offstack (the copy is actually in reverse).  So we just move the copy to the main stack and we can be done with it.

```<code>([]){{}({}<>)<>([])}{}<>
</code>```

Skeleton program

Now that I have made all of the pieces of the program,  I just have to insert them into a frame.

The frame doubles the text one less than the stack's height times Using duplicate.

```<code>(([])[()])
{
 ({}[()]<
  DUPLICATE
 >)
>)}{}
</code>```

And then reverses the stack in decreasing increments of the initial stack height from n^2-n to 0.

```<code>(({}))
{
 (({}[()])<
  ({}<>)<>(({}))({<({}[()])><>({})<>}{})<>{}<>
  ({}<({}<>)<>>)<>({}<>)
  ({}<
   REVERSE
  >)
 >)
}{}{}
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Brain-Flak, <s>418</s> <s>378</s> 228 bytes

This is my Brain-Flak masterpiece.  It may not be well golfed but the challenge is the most difficult I have ever encountered.

Try it online!

(([])[()]){({}[()]<(({}(<()>))<{({}[()]<(({}()<(({}<>))>)<({()<({}[()]<({}<({}<>)<>>)>)>}{}<>){({}[()]<({}<>)<>>)}{}>)>)}{}{}<>([]){{}({}<>)<>([])}{}<>>)>)}{}([(({}))]{({})({}[()])}{}){(({}[({}<>)<>])<<>({}<><{(({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}<>([]){{}({}<>)<>([])}{}<>>)}{}>)>)}

Explanation

This explanation is now a bit outdated but it still does a pretty good job of explaining the program.

This explanation is going to go a little different from my regular explanation process.  I am going to explain how I came about this result rather than explain the result in order.  Here it goes:

Roller

After working at the problem a quite a bit I came up with this code:

(n[()])({()<({}[()]<({}<({}<>)<>>)>)>}{}<>){({}[()]<({}<>)<>>)}{}<>

This code (where n is the literal for some number. e.g. ()()) will take the item on the top of the stack and move it down n steps.  With n as the stack height this will perform a stack "roll".  i.e. move the top item to the bottom of the stack.  Here's how it works:

We put the place we want to move the item to minus one on the stack.  Why minus one?  I don't know it just works that way.

(n[()])

We then loop until this number reaches zero keeping track of the loop with a ().

{()<({}[()]<...>)>)>}{}

Each time we loop we pick up the top item and move the item underneath it to the other stack.  This puts the number on top in its place.

({}<({}<>)<>>)

All we need to do now is put the numbers we moved back.  We switch to the off stack and push the number of runs the loop made.

(...<>)

We loop decrementing the newly pushed number until it reaches zero.  Each time we move one number back.

{({}[()]<({}<>)<>>)}{}<>

Reverse

I next modified the roll to make a full stack reverse:

(n){(({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}<>([]){{}({}<>)<>([])}{}<>>)}{}

Once again n represents the depth of the reverse.  That is the top n items on the stack will be reversed.  How it works:

The reverse is just a fancily wrapped roller.  We simply roll the top of the stack n times decrementing the depth of the roll by one each time.

(n){(({}[()])<ROLLER>)}{}

Duplicate

In place duplication is hard. Really hard.  After I figured out how to reverse the stack it still took a great deal of effort to come up with the duplication algorithm.

Here it is:

(((n)<{({}[()]<(({}<>))<>>)}{}<>>)<{({}[()]<({}<>)<>([][()])({()<({}[()]<({}<({}<>)<>>)>)>}{}<>){({}[()]<({}<>)<>>)}{}<>>)}{}<>([]){{}({}<>)<>([])}{}<>([]){(({}[()])<{({}[()]<({}<({}<>)<>>)>)}{}<>([]){{}({}<>)<>([])}{}<>>)}{}>)

Its a bit of a big one but here's how it works:

Start by pushing n.  n is the depth of the duplicate.  We also open two parentheses.  These allow us to store the value of the n in the scope until its needed again.

(((n)<

Next we loop n times each time pushing the top value of the stack to the off stack twice.  This makes the initial duplicates for each number on the stack.

{({}[()]<(({}<>))<>>)}{}

Now we have two copies of each number on the offstack.  We need to separate these into two groups.

So we switch to the offstack and recall one of the ns we saved at the beginning.

<>>)

We loop n times.

{({}[()]<...>)}{}

Each time we move one copy to the mainstack.

({}<>)<>

And roll one copy to the bottom of the stack. (This assumes the offstack was empty to begin with making this duplicate not stack clean)

([][()])ROLLER

Once that is done we have split the original into two groups the "original" and a copy on the offstack (the copy is actually in reverse).  So we just move the copy to the main stack and we can be done with it.

([]){{}({}<>)<>([])}{}<>

Skeleton program

Now that I have made all of the pieces of the program,  I just have to insert them into a frame.

The frame doubles the text one less than the stack's height times Using duplicate.

(([])[()])
{
 ({}[()]<
  DUPLICATE
 >)
>)}{}

And then reverses the stack in decreasing increments of the initial stack height from n^2-n to 0.

(({}))
{
 (({}[()])<
  ({}<>)<>(({}))({<({}[()])><>({})<>}{})<>{}<>
  ({}<({}<>)<>>)<>({}<>)
  ({}<
   REVERSE
  >)
 >)
}{}{}


答:
Brachylog, 16 bytes

```<code>l-I,?r:?r:Ij@2hc
</code>```

Try it online!

Explanation

```<code>l-I,                I = length(Input) - 1
    ?r              Reverse the Input
      :?r           The list [Input, Reverse of the Input]
         :Ij        Append I times that list to itself
            @2h     Split in half and take the first part
               c    Concatenate into a string
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Brachylog, 16 bytes

l-I,?r:?r:Ij@2hc

Try it online!

Explanation

l-I,                I = length(Input) - 1
    ?r              Reverse the Input
      :?r           The list [Input, Reverse of the Input]
         :Ij        Append I times that list to itself
            @2h     Split in half and take the first part
               c    Concatenate into a string


问:
Shuffle a mapping
We define a map as a set of key-value pairs.  For this challenge, you need to take each of the values and assign them to a randomly chosen key.

You must randomly shuffle the values, and output the resulting map.  This means that each time we run your program, we have a chance of getting a different output

Each possible permutation of the values must have a non-zero chance of appearing.

All of the original keys and original values must appear in the resulting array.  Repeated values must appear the same number of times in the resulting array.

For example, if your map was:

```<code>[0:10, 1:10, 5:5]
</code>```

all of the following must have a chance of appearing:

```<code>[0:10, 1:10, 5:5]  (original map)
[0:10, 1:5,  5:10]
[0:10, 1:10, 5:5]  (technically the same map, but I swapped the two tens)
[0:10, 1:5,  5:10]
[0:5,  1:10, 5:10]
[0:5,  1:10, 5:10]
</code>```

Acceptable input/outputs:

Your languages' native map

You can input an array of key-value pairs.  You may not input 2 arrays, one with keys, the other with values.

You can use a string representation of any the above

If you input an array or a map, you can modify the original object instead of returning

The input type must match the output type

If you input an array, the order of the keys must be maintained.

You can assume that the keys are unique, but you cannot assume that values are unique.

This is a code-golf, so answer as short as possible

答:
R,  47 (28) bytes

A bit late to the party but though I'd post a solution in R using builtins.

The closest thing R has to an array with key/value mapping is a list. The following function takes a list object as input and outputs a list with its values shuffled.

```<code>function(x)return(setNames(sample(x),names(x)))
</code>```

Explained

The builtin setNames() can assign names to objects by inputting a R-vector of names. Hence, first shuffle the list by sample() which shuffles the pairs, and then assign the names in the original order using names().

Example:

```<code>z  <- list(fish = 1, dog = 2, cat = 3, monkey = 4, harambe = 69)

f=function(x)return(setNames(sample(x),names(x)))
f(z)

$fish
[1] 3

$dog
[1] 1

$cat
[1] 2

$monkey
[1] 69

$harambe
[1] 4
</code>```

If x is assumed to be defined there's no need for function wrapping and the program reduces to 28 bytes.

```<code>setNames(sample(x),names(x))
</code>```

Title: Shuffle a mapping

Body:
R,  47 (28) bytes

A bit late to the party but though I'd post a solution in R using builtins.

The closest thing R has to an array with key/value mapping is a list. The following function takes a list object as input and outputs a list with its values shuffled.

function(x)return(setNames(sample(x),names(x)))

Explained

The builtin setNames() can assign names to objects by inputting a R-vector of names. Hence, first shuffle the list by sample() which shuffles the pairs, and then assign the names in the original order using names().

Example:

z  <- list(fish = 1, dog = 2, cat = 3, monkey = 4, harambe = 69)

f=function(x)return(setNames(sample(x),names(x)))
f(z)

$fish
[1] 3

$dog
[1] 1

$cat
[1] 2

$monkey
[1] 69

$harambe
[1] 4

If x is assumed to be defined there's no need for function wrapping and the program reduces to 28 bytes.

setNames(sample(x),names(x))


答:
Haskell, <s>40</s> <s>36</s> 32 Bytes

```<code>m s=take(length s^2)$cycle$s++reverse s
</code>```

Example:

```<code>*Main> m "Hello!"
"Hello!!olleHHello!!olleHHello!!olleH"
</code>```

Even shorter (credit to Damien):

```<code>q s=zip(s>>[s,reverse s])s>>=fst
</code>```

s>>[s,reverse s] cycles ["abc","cba",...] which is zipped to correct size and concatMap'ped with fst

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Haskell, <s>40</s> <s>36</s> 32 Bytes

m s=take(length s^2)$cycle$s++reverse s

Example:

*Main> m "Hello!"
"Hello!!olleHHello!!olleHHello!!olleH"

Even shorter (credit to Damien):

q s=zip(s>>[s,reverse s])s>>=fst

s>>[s,reverse s] cycles ["abc","cba",...] which is zipped to correct size and concatMap'ped with fst


答:
Groovy, 51 bytes

```<code>def d(s){s.size().times{print(it%2?s.reverse():s)}}
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Groovy, 51 bytes

def d(s){s.size().times{print(it%2?s.reverse():s)}}


答:
Ruby, <s>78</s> 72 bytes

->s{s.gsub(/(^|\. )?\K\[\?\]( [aeiou])?/i){"anAn"[$1?2:0,$2?2:1]+"#$2"}}
```

<ul>
<li>Saved 6 bytes thanks to @Jordan</li>
</ul>

<p><strong>Ungolfed</strong></p>

<pre class="lang-rb prettyprint-override"><code>def f(s)
    s.gsub(/(^|\. )?\[\?\]( [aeiou])?/i) do |m|
        capitalize = $1
        vowel = $2
        replacement = if vowel then
            capitalize ? "An" : "an"
        else
            capitalize ? "A" : "a"
        end
        m.sub('[?]', replacement)
    end
end
</code>```

Title: An A , or An An?

Body:
Ruby, <s>78</s> 72 bytes

->s{s.gsub(/(^|\. )?\K\[\?\]( [aeiou])?/i){"anAn"[$1?2:0,$2?2:1]+"#$2"}}

Saved 6 bytes thanks to @Jordan

Ungolfed

def f(s)
    s.gsub(/(^|\. )?\[\?\]( [aeiou])?/i) do |m|
        capitalize = $1
        vowel = $2
        replacement = if vowel then
            capitalize ? "An" : "an"
        else
            capitalize ? "A" : "a"
        end
        m.sub('[?]', replacement)
    end
end


答:
Lua 5.1, 70 Bytes

```<code>function f(s)return(s..s:reverse()):rep(#s/2)..(#s%2==1 and s or"")end
</code>```

Had odd numbers not been possible, I could have done it in 48 bytes by sheering off the ..(#s%2==1 and s or""), but the test cases prevented that.

This was the shortest of three methods I tried, the others being.

```<code>function f(s)local o return s:gsub(".",function()o=~o return o and s or s:reverse()end)end
</code>```

and

```<code>function f(s)local o,t t=""for _ in s:gmatch(".")do o,t=~o,t..(o and s:reverse()or s)end return t end
</code>```

the locals were added in those two examples, for confidence that this function would always work.

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Lua 5.1, 70 Bytes

function f(s)return(s..s:reverse()):rep(#s/2)..(#s%2==1 and s or"")end

Had odd numbers not been possible, I could have done it in 48 bytes by sheering off the ..(#s%2==1 and s or""), but the test cases prevented that.

This was the shortest of three methods I tried, the others being.

function f(s)local o return s:gsub(".",function()o=~o return o and s or s:reverse()end)end

and

function f(s)local o,t t=""for _ in s:gmatch(".")do o,t=~o,t..(o and s:reverse()or s)end return t end

the locals were added in those two examples, for confidence that this function would always work.


答:
Perl, 24 bytes

Includes +2 for -lp

Give input on STDIN:

```<code>rev.pl <<< Hello!
</code>```

rev.pl:

```<code>#!/usr/bin/perl -lp
s%.%s/.?/chop/eg;$`%eg
</code>```

Surprisingly this does not use the builtin reverse operator. That name is just soooo long, all solutions I could think of with reverse are at least 1 byte longer.

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Here is a relatively simple challenge for you.

Given a string of length N, output the string forwards, then backwards, then forwards, then backwards... etc. N times. For example, if your input was

```<code>Hello!
</code>```

You should output:

```<code>Hello!!olleHHello!!olleHHello!!olleH
</code>```

You may also optionally output one trailing newline.

Your submission may be either a full program or a function, and you may take input and output in any reasonable format. For example, you may take IO from STDIN/STDOUT, function arguments and return value, from a file, etc. You can safely assume that the input string will not be empty, and will only contain printable ASCII. You must output the new string on a single line. So, for example, if the output to the last example was

```<code>Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
</code>```

This would not be a valid solution!

Here are some more test cases:

```<code>Input:
a
Output:
a

Input:
abcd
Output:
abcddcbaabcddcba

Input:
OK!
Output:
OK!!KOOK!

Input:
4815162342
Output:
4815162342243261518448151623422432615184481516234224326151844815162342243261518448151623422432615184

Input:
PPCG
Output:
PPCGGCPPPPCGGCPP

Input:
42
Output:
4224
</code>```

Leaderboards

Since this is a code-golf challenge, standard loopholes are banned, and the shortest answer in bytes wins! However, this is also a competition to have the shortest answer in any particular langauge. While it's unlikely that a Java answer will beat an answer in perl, or some golfing language, it's still very impressive to have the shortest Java answer. So, you can use this leaderboard to see both

The shortest answer out of all languages, and

The shortest answer in each individual language.

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 leaderboard snippet:

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Perl, 24 bytes

Includes +2 for -lp

Give input on STDIN:

rev.pl <<< Hello!

rev.pl:

#!/usr/bin/perl -lp
s%.%s/.?/chop/eg;$`%eg

Surprisingly this does not use the builtin reverse operator. That name is just soooo long, all solutions I could think of with reverse are at least 1 byte longer.


答:
JavaScript (ES6), 90 <s> 86 87 85</s>

Edit once more as the spec for capitalization has changed (more sensible now)

Edit again 1 byte save thx @Huntro

Edit 2 more bytes to manage quotes and the like, as pointed out by IsmaelMiguel (even if I don't know if it's requested by op). Note that previously I had counted 86 bytes but they were 85

<s>Trying to follow the capitalization rule stated in the comments event if it's incomplete (at least)</s>

x=>x.replace(/([^!?.] )?\[\?](\W*.)/g,(a,b,c)=>(b?b+'a':'A')+(/[aeiou]/i.test(c)?'n'+c:c))
```
<p><strong>Test</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>f=x=>x.replace(/([^!?.] )?\[\?](\W*.)/g,(a,b,c)=>(b?b+'a':'A')+(/[aeiou]/i.test(c)?'n'+c:c))

function go() {
  var i=I.value, o=f(i)
  O.innerHTML = '<i>'+i+'</i>\n<b>'+o+'</b>\n\n'+O.innerHTML
}

go()</code>```

#I { width:80% }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input value='How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.' id=I><button onclick='go()'>GO</button><pre id=O>``````

Title: An A , or An An?

Body:
In English, there is the fun and simple difference between an and a: you use an when preceding a word starting with a vowel sound, and a when the word starts with a consonant sound.

For the sake of simplicity in this challenge, an precedes a word that starts with a vowel (aeiou), and a precedes a word that starts with a consonant.

Input

A string comprising only printable ASCII characters, with [?] appearing in places where you must choose to insert an or a. [?] will always appear before a word. You can assume that the sentence will be grammatically correct and formatted like normal.

Output

The input string with [?] replaced with the appropriate word (an or a). You do have to worry about capitalization!

When to Capitalize

Capitalize a word if it is preceded by no characters (is the first one in the input) or if it is preceded by one of .?! followed by a space.

Examples

```<code>Input: Hello, this is [?] world!
Output: Hello, this is a world!

Input: How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.
Output: How about we build a big building. It will have an orange banana hanging out of a window.

Input: [?] giant en le sky.
Output: A giant en le sky.

Input: [?] yarn ball? [?] big one!
Output: A yarn ball? A big one!

Input: [?] hour ago I met [?] European.
Output: A hour ago I met an European.

Input: Hey sir [Richard], how 'bout [?] cat?
Output: Hey sir [Richard], how 'bout a cat?
</code>```

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

Body:
JavaScript (ES6), 90 <s> 86 87 85</s>

Edit once more as the spec for capitalization has changed (more sensible now)

Edit again 1 byte save thx @Huntro

Edit 2 more bytes to manage quotes and the like, as pointed out by IsmaelMiguel (even if I don't know if it's requested by op). Note that previously I had counted 86 bytes but they were 85

<s>Trying to follow the capitalization rule stated in the comments event if it's incomplete (at least)</s>

x=>x.replace(/([^!?.] )?\[\?](\W*.)/g,(a,b,c)=>(b?b+'a':'A')+(/[aeiou]/i.test(c)?'n'+c:c))

Test

f=x=>x.replace(/([^!?.] )?\[\?](\W*.)/g,(a,b,c)=>(b?b+'a':'A')+(/[aeiou]/i.test(c)?'n'+c:c))

function go() {
  var i=I.value, o=f(i)
  O.innerHTML = '<i>'+i+'</i>\n<b>'+o+'</b>\n\n'+O.innerHTML
}

go()

#I { width:80% }

<input value='How about we build [?] big building. It will have [?] orange banana hanging out of [?] window.' id=I><button onclick='go()'>GO</button><pre id=O></pre>


答:
Retina, 27 bytes

Byte count assumes ISO 8859-1 encoding.

```<code>.
±$_
O$^`(?(\G)[^±]|±)

±

</code>```

Try it online!

Explanation

```<code>.
±$_
</code>```

Replace each character with the entire input, preceded by ± to separate copies.

```<code>O$^`(?(\G)[^±]|±)

</code>```

The regex matches the characters in every other copy, by either matching a ± that is not adjacent to the previous match, or a non-± that is. These characters are reversed. Since each copy is the same width that is identical to reversing each copy individually.

```<code>±

</code>```

Remove the separators.

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Retina, 27 bytes

Byte count assumes ISO 8859-1 encoding.

.
±$_
O$^`(?(\G)[^±]|±)

±

Try it online!

Explanation

.
±$_

Replace each character with the entire input, preceded by ± to separate copies.

O$^`(?(\G)[^±]|±)

The regex matches the characters in every other copy, by either matching a ± that is not adjacent to the previous match, or a non-± that is. These characters are reversed. Since each copy is the same width that is identical to reversing each copy individually.

±

Remove the separators.


问:
Simplify a continued fraction
Continued fractions are expressions that describe fractions iteratively. They can be represented graphically:

$$
a_0 +\cfrac 1
 {a_1 + \cfrac 1
  {a_2 + \cfrac 1
   {\ddots + \cfrac 1
    {a_n}
   }
  }
 }
$$

Or they can be represented as a list of values: \$[a_0 ; a_1, a_2, \dots, a_n]\$

The challenge:

take a base number: \$a_0\$ and a list of denominator values: \$[a_1, a_2, \dots, a_n]\$ and simplify the continued fraction to a simplified rational fraction: return or print numerator and denominator separately.

Examples:

\$\sqrt 19\$: [4;2,1,3,1,2]: 170/39

\$e\$: [1;0,1,1,2,1,1]: 19/7

\$\pi\$: [3;7,15,1,292,1]: 104348/33215

\$ϕ\$: [1;1,1,1,1,1]: 13/8

Example implementation: (python)

def foo(base, sequence):
    numerator = 1
    denominator = sequence[-1]
    for d in sequence[-2::-1]:
        temp = denominator
        denominator = d * denominator + numerator
        numerator = temp
    return numerator + base * denominator, denominator```

Winning:
 shortest code in bytes: --no builtins that do the entire problem allowed--

Title: Simplify a continued fraction

Body:
 Common Lisp, 54

A somewhat verbose fold-right:

(lambda(s)(reduce(lambda(a r)(+(/ r)a))s :from-end t))

Tests

PASS  NAME  ACTUAL               EXPECTED
===============================================
T     √19   170/39               170/39
T     ℯ     19/7                 19/7
T     π     104348/33215         104348/33215
T     ϕ     13/8                 13/8


答:
C#, 137 bytes

```<code>void S(string i){Console.WriteLine(string.Join("",i.Select((c,n)=>(n%2==0)?i:i.Reverse()).Select(x=>new string(x.ToArray())).ToList()));}
</code>```

Ungolfed:

```<code>void S(string i)
{
    Console.WriteLine(string.Join("",
    i.Select((c, n) => (n%2 == 0) ? i : i.Reverse()).Select(x => new
    string(x.ToArray())).ToList()));
}
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
C#, 137 bytes

void S(string i){Console.WriteLine(string.Join("",i.Select((c,n)=>(n%2==0)?i:i.Reverse()).Select(x=>new string(x.ToArray())).ToList()));}

Ungolfed:

void S(string i)
{
    Console.WriteLine(string.Join("",
    i.Select((c, n) => (n%2 == 0) ? i : i.Reverse()).Select(x => new
    string(x.ToArray())).ToList()));
}


答:
Java, <s>127</s> <s>111</s> 88 bytes

```<code>(s,r)->{for(int i=0;i++<s.length();)r+=i%2<1?new StringBuffer(s).reverse():s;return r;};
</code>```

Ungolfed test program

```<code>    public static void main(String[] args) {
    BiFunction<String, String, String> func = (s, r) -> {
        for (int i = 0; i++ < s.length();) {
            r += i % 2 < 1 ? new StringBuffer(s).reverse() : s;
        }
        return r;
    };
    System.out.println(func.apply("Hello!", ""));
}
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Java, <s>127</s> <s>111</s> 88 bytes

(s,r)->{for(int i=0;i++<s.length();)r+=i%2<1?new StringBuffer(s).reverse():s;return r;};

Ungolfed test program

    public static void main(String[] args) {
    BiFunction<String, String, String> func = (s, r) -> {
        for (int i = 0; i++ < s.length();) {
            r += i % 2 < 1 ? new StringBuffer(s).reverse() : s;
        }
        return r;
    };
    System.out.println(func.apply("Hello!", ""));
}


答:
CJam, 10 bytes

```<code>l_,({_W%}*
</code>```

Try it online!

Explanation

```<code>l            e# Read line
 _           e# Duplicate
  ,(         e# Length minus 1
    {   }*   e# Run code block that many times
     _       e# Duplicate
      W%     e# Reverse
             e# Implicitly display
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
CJam, 10 bytes

l_,({_W%}*

Try it online!

Explanation

l            e# Read line
 _           e# Duplicate
  ,(         e# Length minus 1
    {   }*   e# Run code block that many times
     _       e# Duplicate
      W%     e# Reverse
             e# Implicitly display


问:
Generate a Universal-binary-function Lookup Table
This is tangentially related to my quest to invent an esoteric programming language.

A table of the binary numbers 0 .. 15 can be used to implement a Universal Binary Function using indexing operations. Given two 1-bit inputs X and Y, all 16 possible functions can be encoded in a 4-bit opcode.

```<code>X Y  F|0 1 2 3 4 5 6 7 8 9 A B C D E F
- -    - - - - - - - - - - - - - - - -
0 0    0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
0 1    0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1
1 0    0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
1 1    0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
       -     -   - -   -   -   -   - -
       0    ~X  ~Y ^   &   Y   X   | 1
      ZERO    NOT-Y   AND         OR
          NOT-X   XOR              ONE
</code>```

So this set of 16 functions can be applied to binary inputs as the function

U(f,x,y): (f >> ((x<<1) | y)) & 1,

or

U(f,x,y): (f / 2^(x×2 + y)) % 2,

or with indexing or matrix partitioning.

It will be useful to know the most compact way to represent or generate such a table of values for any possible languages to be built upon this type of binary operation.

The goal:

Generate this exact text output:

```<code>0101010101010101
0011001100110011
0000111100001111
0000000011111111
</code>```

That's it! Shortest-code wins.

Body:
///, 51 bytes

Try it online

/a/0101/aaaa
/b/0011/bbbb
/z/0000//o/1111/zozo
zzoo


答:
Perl, 120 <s>138</s>

```<code>%c=qw(> $p++ < $p-- + D++ - D-- [ while(D){ ] } . print+chrD , D=ord(getc));
$/=$,;$_=<>;s/./$c{$&};/g;s[D]'$b[$p]'g;eval
</code>```

This runs hello.bf and primes.bf flawlessly:

```<code>$ perl bf.pl hello.bf
Hello World!
$ perl bf.pl prime.bf
Primes up to: 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
</code>```

Initialization: The opcode to Perl translation table is stored in %c.  The readable form looks like this:

```<code>%c=(
  '>' => '$p++',
  '<' => '$p--',
  '+' => '$b[$p]++',
  '-' => '$b[$p]--',
  '[' => 'while($b[$p]){',
  ']' => '}',
  '.' => 'print chr$b[$p]',
  ',' => '$b[$p]=ord(getc)',
);
</code>```

Step 1: Slurp program input to $_ and transform it to Perl code using the translation table.  Comments are automatically stripped (replaced with undef) in this step.

Step 2: Uncompress all $b[$p] occurrences

Step 3: Launch the program using eval.

Title: Interpret brainfuck

Body:
Write the shortest program in your favourite language to interpret a brainfuck program. The program is read from a file. Input and output are standard input and standard output.

Cell size: 8bit unsigned. Overflow is undefined.

Array size: 30000 bytes (not circled)

Bad commands are not part of the input

Comments begin with # and extend to the end of line Comments are everything not in +-.,[]<>

no EOF symbol

A very good test can be found here. It reads a number and then prints the prime numbers up to that number. To prevent link rot, here is a copy of the code:

```<code>compute prime numbers
to use type the max number then push Alt 1 0
===================================================================
======================== OUTPUT STRING ============================
===================================================================
>++++++++[<++++++++>-]<++++++++++++++++.[-]
>++++++++++[<++++++++++>-]<++++++++++++++.[-]
>++++++++++[<++++++++++>-]<+++++.[-]
>++++++++++[<++++++++++>-]<+++++++++.[-]
>++++++++++[<++++++++++>-]<+.[-]
>++++++++++[<++++++++++>-]<+++++++++++++++.[-]
>+++++[<+++++>-]<+++++++.[-]
>++++++++++[<++++++++++>-]<+++++++++++++++++.[-]
>++++++++++[<++++++++++>-]<++++++++++++.[-]
>+++++[<+++++>-]<+++++++.[-]
>++++++++++[<++++++++++>-]<++++++++++++++++.[-]
>++++++++++[<++++++++++>-]<+++++++++++.[-]
>+++++++[<+++++++>-]<+++++++++.[-]
>+++++[<+++++>-]<+++++++.[-]

===================================================================
======================== INPUT NUMBER  ============================
===================================================================
+                          cont=1
[
 -                         cont=0
 >,
 ======SUB10======
 ----------

 [                         not 10
  <+>                      cont=1
  =====SUB38======
  ----------
  ----------
  ----------
  --------

  >
  =====MUL10=======
  [>+>+<<-]>>[<<+>>-]<     dup

  >>>+++++++++
  [
   <<<
   [>+>+<<-]>>[<<+>>-]<    dup
   [<<+>>-]
   >>-
  ]
  <<<[-]<
  ======RMOVE1======
  <
  [>+<-]
 ]
 <
]
>>[<<+>>-]<<

===================================================================
======================= PROCESS NUMBER  ===========================
===================================================================

==== ==== ==== ====
numd numu teid teiu
==== ==== ==== ====

>+<-
[
 >+
 ======DUP======
 [>+>+<<-]>>[<<+>>-]<

 >+<--

 >>>>>>>>+<<<<<<<<   isprime=1

 [
  >+

  <-

  =====DUP3=====
  <[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<<<

  =====DUP2=====
  >[>>+>+<<<-]>>>[<<<+>>>-]<<< <

  >>>

  ====DIVIDES=======
  [>+>+<<-]>>[<<+>>-]<   DUP i=div

  <<
  [
    >>>>>+               bool=1
    <<<
    [>+>+<<-]>>[<<+>>-]< DUP
    [>>[-]<<-]           IF i THEN bool=0
    >>
    [                    IF i=0
      <<<<
      [>+>+<<-]>>[<<+>>-]< i=div
      >>>
      -                  bool=0
    ]
    <<<
    -                    DEC i
    <<
    -
  ]

  +>>[<<[-]>>-]<<
  >[-]<                  CLR div
  =====END DIVIDES====

  [>>>>>>[-]<<<<<<-]     if divides then isprime=0

  <<

  >>[-]>[-]<<<
 ]

 >>>>>>>>
 [
  -
  <<<<<<<[-]<<

  [>>+>+<<<-]>>>[<<<+>>>-]<<<

  >>

  ===================================================================
  ======================== OUTPUT NUMBER  ===========================
  ===================================================================
  [>+<-]>

  [
   ======DUP======
   [>+>+<<-]>>[<<+>>-]<

   ======MOD10====
   >+++++++++<
   [
    >>>+<<              bool= 1
    [>+>[-]<<-]         bool= ten==0
    >[<+>-]             ten = tmp
    >[<<++++++++++>>-]  if ten=0 ten=10
    <<-                 dec ten
    <-                  dec num
   ]
   +++++++++            num=9
   >[<->-]<             dec num by ten

   =======RROT======
      [>+<-]
   <  [>+<-]
   <  [>+<-]
   >>>[<<<+>>>-]
   <

   =======DIV10========
   >+++++++++<
   [
    >>>+<<                bool= 1
    [>+>[-]<<-]           bool= ten==0
    >[<+>-]               ten = tmp
    >[<<++++++++++>>>+<-] if ten=0 ten=10  inc div
    <<-                   dec ten
    <-                    dec num
   ]
   >>>>[<<<<+>>>>-]<<<<   copy div to num
   >[-]<                  clear ten

   =======INC1=========
   <+>
  ]

  <
  [
   =======MOVER=========
   [>+<-]

   =======ADD48========
   +++++++[<+++++++>-]<->

   =======PUTC=======
   <.[-]>

   ======MOVEL2========
   >[<<+>>-]<

   <-
  ]

  >++++[<++++++++>-]<.[-]

  ===================================================================
  =========================== END FOR ===============================
  ===================================================================

  >>>>>>>
 ]
 <<<<<<<<

 >[-]<
  [-]
 <<-
]

======LF========

++++++++++.[-]
@
</code>```

Example run:

```<code>$ python2 bf.py PRIME.BF
Primes up to: 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
</code>```

Body:
Perl, 120 <s>138</s>

%c=qw(> $p++ < $p-- + D++ - D-- [ while(D){ ] } . print+chrD , D=ord(getc));
$/=$,;$_=<>;s/./$c{$&};/g;s[D]'$b[$p]'g;eval

This runs hello.bf and primes.bf flawlessly:

$ perl bf.pl hello.bf
Hello World!
$ perl bf.pl prime.bf
Primes up to: 100
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Initialization: The opcode to Perl translation table is stored in %c.  The readable form looks like this:

%c=(
  '>' => '$p++',
  '<' => '$p--',
  '+' => '$b[$p]++',
  '-' => '$b[$p]--',
  '[' => 'while($b[$p]){',
  ']' => '}',
  '.' => 'print chr$b[$p]',
  ',' => '$b[$p]=ord(getc)',
);

Step 1: Slurp program input to $_ and transform it to Perl code using the translation table.  Comments are automatically stripped (replaced with undef) in this step.

Step 2: Uncompress all $b[$p] occurrences

Step 3: Launch the program using eval.


问:
Interpret whatfuck
Smallfuck is a brainfuck-like language with 1-bit cells.  It has the following instructions:

```<code>> Increment the pointer
< Decrement the pointer
* Flip the current bit
[ If the current bit is not set, jump to the instruction after the matching ]
] If the current bit is set, jump to the instruction after the matching [
    ( or just jump unconditionally to matching [ )
</code>```

Whatfuck adds one more instruction:

```<code>? Nondeterministically set the current bit to 0 or 1.
</code>```

A whatfuck program does not take any input.  It can result in one of 3 possibilities: 1 (accept), 0 (reject) or it may never halt.

The program will result in 1 if there exists a sequence of bits chosen for ?s which results in the program terminating with 1 as the current bit.

The program terminates with 0 if all possible choices terminate with current bit 0,

If some choices don't terminate, and all choices which terminate do so with 0, then the program will never terminate.

Your interpreter should run all possibilities simultaneously.  You can't try 0 first and then try 1, because some programs will not terminate when they should.  For example, *[?*]* will accept with the choice 1, but never terminate if you always choose 0.

As an example, here is a python 2 interpreter I wrote, not golfed

Rules

Your interpreter must accept a whatfuck program from stdin and print its result.

You may assume the whatfuck program only contains characters []<>*?

The array of bits is unbounded on both ends.

Shortest code wins.

Some Test Cases

This will fail if your code always tries 0 first

```<code>*[?*]*
1
</code>```

Is there a subset of {-7,-3, 5, 8} whose sum is 3?

```<code>*<<<<<?[<<<<<<<<<<<<<<]?[<<<<<<]?[>>>>>>>>>>]?[>>>>>>>>>>>>>>>>]<
1
</code>```

Is there a subset of {-7,-3, 5, 8} whose sum is 4?

```<code>*<<<<<<<?[<<<<<<<<<<<<<<]?[<<<<<<]?[>>>>>>>>>>]?[>>>>>>>>>>>>>>>>]<
0
</code>```

Is there a way to assign boolean values to a,b and c such that

(a XOR b) AND (a XOR c) AND (b XOR c) is true?

```<code>?[*>*>*<<]?[*>*>>*<<<]?[*>>*>*<<<]>[*>[*>[*>*<]<]<]>>>
0
</code>```

答:
Python, 305 chars

```<code>P=raw_input()+'$'
S=[(0,0,[])]
F={}
R={}
i=r=0
for c in P:
 if'['==c:S+=i,
 if']'==c:j=S.pop();F[j]=R[i]=i-j
 i+=1
while S*(1-r):p,t,B=S.pop(0);c=P[p];b=B.count(t)%2;p+=1+F.get(p,0)*(1-b)-R.get(p,0)*b;t+=(c=='>')-(c=='<');B=B+[t]*(c=='*');r|=(c=='$')&b;S+=[(p,t,B)]*(c!='$')+[(p,t,B+[t])]*(c=='?')
print r
</code>```

Keeps track of the nondeterministic set of states in S, each with a code position p,  a tape position t, and a list of tape indexes B.  A tape index can appear multiple times in the list B, the tape at that index is 1 if the index appears an odd number of times in B.

Title: Interpret whatfuck

Body:
Python, 305 chars

P=raw_input()+'$'
S=[(0,0,[])]
F={}
R={}
i=r=0
for c in P:
 if'['==c:S+=i,
 if']'==c:j=S.pop();F[j]=R[i]=i-j
 i+=1
while S*(1-r):p,t,B=S.pop(0);c=P[p];b=B.count(t)%2;p+=1+F.get(p,0)*(1-b)-R.get(p,0)*b;t+=(c=='>')-(c=='<');B=B+[t]*(c=='*');r|=(c=='$')&b;S+=[(p,t,B)]*(c!='$')+[(p,t,B+[t])]*(c=='?')
print r

Keeps track of the nondeterministic set of states in S, each with a code position p,  a tape position t, and a list of tape indexes B.  A tape index can appear multiple times in the list B, the tape at that index is 1 if the index appears an odd number of times in B.


答:
Batch, 136 bytes

```<code>@set/ps=
@for %%v in (a e i o u)do @call set s=%%s:[?] %%v=an %%v%%
@set s=%s:[?]=a%
@if %s:~0,1%==a set s=A%s:~1%
@echo %s:. a=. A%
</code>```

Takes a line of input on STDIN.

Title: An A , or An An?

Body:
Batch, 136 bytes

@set/ps=
@for %%v in (a e i o u)do @call set s=%%s:[?] %%v=an %%v%%
@set s=%s:[?]=a%
@if %s:~0,1%==a set s=A%s:~1%
@echo %s:. a=. A%

Takes a line of input on STDIN.


问:
Make me a mooncake!
The mid-autumn festival has begun!

Unfortunately, all my mooncakes were stolen -- they're getting too expensive for small folk such as myself, and I fear I won't be able to eat any this year!

So I turn to you for help. Would you be able to make me some?

For those unaware, let me educate you on what a mooncake looks like.

Mooncakes come in many different sizes!

So I'm gonna give you my input, n, when I want one.

Here are some examples of the output I want:

Mooncake of size n = 3:

```<code>    (@@@@@)
    (@MAF@)
    (@@@@@)
</code>```

Mooncake of size n = 6:

```<code>    (@@@@@@@@@@@)
    (@         @)
    (@    M    @)
    (@    F    @)
    (@         @)
    (@@@@@@@@@@@)
</code>```

That is to say, a mooncake of size n is:

n lines high

2n - 1 @s long

2n + 1 characters long (@s and brackets)

And you better not throw me your too-tiny practice mooncakes!

Assume input will always be n >= 3.

Mooncakes also contain one of the following decorations:

MF

MAF

HMF

JCJ

TTT

ZJ

LF

RF

CF

Which one, it doesn't matter - as long as it is vertically and horizontally centered.

It can be written vertically or horizontally too!

I want variety!

If you're really going to make me two of the same mooncake, the decoration better be different!

That is, multiple executions of your program with the exact same input must not always yield the same decoration.

I can't wait to eat your moon cakes, so the sooner I can receive them (the shorter your code) the better!

Good Luck!

For those wondering about the decorations:

They are the initials of all alternative names for the Mid-Autumn Festival.

A list can be found in the Wikipedia page linked at the top of this post.

Clarifications:

There are no rules regarding leading and trailing whitespace.

Have as much or as little as you like!

The decorations must be in the very center of your mooncake!

On horizontal decorations, this means it must be on the middle line of your cake, and the number of characters to the left and right of the decoration string must be equal.

On vertical decorations, this means it must reside in the middle column of your cake, and the number of characters above and below the decoration must be equal.

Not all decorations must be used!

The only requirement is that there must be more than one possibility for any given input n. The possibilities also do not need to be even.

Functions are acceptable.

答:
Pyth, <s>99</s> <s>79</s> <s>71</s> <s>68</s> 64 bytes

Pyth is <s>very bad</s> all right at making strings.  Or maybe I'm just <s>bad</s> getting better at golfing them.

```<code>jmj.[-yQ3@,k@,@,O"MC"\FgydQOc"MAFHMF"3Q>2ahydQ@" @"sIcdtQc2"(@@)
</code>```

Can create the decorations MAF and HMF horizontally, and the decorations MF and CF vertically.

Try it online!

Title: Make me a mooncake!

Body:
Pyth, <s>99</s> <s>79</s> <s>71</s> <s>68</s> 64 bytes

Pyth is <s>very bad</s> all right at making strings.  Or maybe I'm just <s>bad</s> getting better at golfing them.

jmj.[-yQ3@,k@,@,O"MC"\FgydQOc"MAFHMF"3Q>2ahydQ@" @"sIcdtQc2"(@@)

Can create the decorations MAF and HMF horizontally, and the decorations MF and CF vertically.

Try it online!


答:
PHP, <s>342</s> <s>292</s> <s>249</s> <s>185</s> <s>178</s> 176 bytes

```<code>for(;$i<$n=$argv[1];)$o.=str_pad("(@",2*$n-1," @"[$i++%($n-1)<1])."@)
";$p=F.[M,AM,R,MH][rand()&2|$d=$n&1];$f=$n*($n+$d)-2;for($i=2+$d;$i--;$f+=$d?:2*$n+2)$o[$f]=$p[$i];echo$o;
</code>```

Call with php -r '' <size>

history

Rev 1: initial version; all sizes (including tiny cakes), all decorations, all possible directions

Rev. 2: removed tiny cakes (-36 bytes), restructured decoration options, removed one decoration item (-21) and a single byte golf (-1).

Rev. 3: Down to four decorations; (-17), only horizontal for odd sizes (-18) plus minor golfing (-8).

Rev. 4: Thanks to Jörg for golfing down the "paint cake" part; he took off an amazing (-31).

Another -6 with my additional golfing, and -27 for using a single string instead of an array of strings.

Rev. 5: -7 bytes mostly thanks to Christallkeks

breakdown

This is getting slimmer by the hour. :)

```<code>// paint cake
for(;$i<$n=$argv[1];)$o.=str_pad("(@",2*$n-1," @"[$i++%($n-1)<1])."@)\n";

// add deco
$p=F.[M,AM,R,MH][rand()&2|$d=$n&1];
$f=$n*($n+$d)-2;
for($i=2+$d;$i--;$f+=$d?:2*$n+2)$o[$f]=$p[$i];

// output
echo$o;
</code>```

Title: Make me a mooncake!

Body:
The mid-autumn festival has begun!

Unfortunately, all my mooncakes were stolen -- they're getting too expensive for small folk such as myself, and I fear I won't be able to eat any this year!

So I turn to you for help. Would you be able to make me some?

For those unaware, let me educate you on what a mooncake looks like.

Mooncakes come in many different sizes!

So I'm gonna give you my input, n, when I want one.

Here are some examples of the output I want:

Mooncake of size n = 3:

```<code>    (@@@@@)
    (@MAF@)
    (@@@@@)
</code>```

Mooncake of size n = 6:

```<code>    (@@@@@@@@@@@)
    (@         @)
    (@    M    @)
    (@    F    @)
    (@         @)
    (@@@@@@@@@@@)
</code>```

That is to say, a mooncake of size n is:

n lines high

2n - 1 @s long

2n + 1 characters long (@s and brackets)

And you better not throw me your too-tiny practice mooncakes!

Assume input will always be n >= 3.

Mooncakes also contain one of the following decorations:

MF

MAF

HMF

JCJ

TTT

ZJ

LF

RF

CF

Which one, it doesn't matter - as long as it is vertically and horizontally centered.

It can be written vertically or horizontally too!

I want variety!

If you're really going to make me two of the same mooncake, the decoration better be different!

That is, multiple executions of your program with the exact same input must not always yield the same decoration.

I can't wait to eat your moon cakes, so the sooner I can receive them (the shorter your code) the better!

Good Luck!

For those wondering about the decorations:

They are the initials of all alternative names for the Mid-Autumn Festival.

A list can be found in the Wikipedia page linked at the top of this post.

Clarifications:

There are no rules regarding leading and trailing whitespace.

Have as much or as little as you like!

The decorations must be in the very center of your mooncake!

On horizontal decorations, this means it must be on the middle line of your cake, and the number of characters to the left and right of the decoration string must be equal.

On vertical decorations, this means it must reside in the middle column of your cake, and the number of characters above and below the decoration must be equal.

Not all decorations must be used!

The only requirement is that there must be more than one possibility for any given input n. The possibilities also do not need to be even.

Functions are acceptable.

Body:
PHP, <s>342</s> <s>292</s> <s>249</s> <s>185</s> <s>178</s> 176 bytes

for(;$i<$n=$argv[1];)$o.=str_pad("(@",2*$n-1," @"[$i++%($n-1)<1])."@)
";$p=F.[M,AM,R,MH][rand()&2|$d=$n&1];$f=$n*($n+$d)-2;for($i=2+$d;$i--;$f+=$d?:2*$n+2)$o[$f]=$p[$i];echo$o;

Call with php -r '<code>' <size>

history

Rev 1: initial version; all sizes (including tiny cakes), all decorations, all possible directions

Rev. 2: removed tiny cakes (-36 bytes), restructured decoration options, removed one decoration item (-21) and a single byte golf (-1).

Rev. 3: Down to four decorations; (-17), only horizontal for odd sizes (-18) plus minor golfing (-8).

Rev. 4: Thanks to Jörg for golfing down the "paint cake" part; he took off an amazing (-31).

Another -6 with my additional golfing, and -27 for using a single string instead of an array of strings.

Rev. 5: -7 bytes mostly thanks to Christallkeks

breakdown

This is getting slimmer by the hour. :)

// paint cake
for(;$i<$n=$argv[1];)$o.=str_pad("(@",2*$n-1," @"[$i++%($n-1)<1])."@)\n";

// add deco
$p=F.[M,AM,R,MH][rand()&2|$d=$n&1];
$f=$n*($n+$d)-2;
for($i=2+$d;$i--;$f+=$d?:2*$n+2)$o[$f]=$p[$i];

// output
echo$o;


答:
Pyth, <s>71</s> <s>65</s> <s>59</s> 58 bytes

Saved 1 byte thanks to @StevenH.

```<code>jjRc"(@@)"2++J*KtytQ\@m.[Kd;.[ttQ@,,O"MC"\F]Oc"MAFHMF"3QkJ
</code>```

Try it online. Test suite.

So much padding.

Title: Make me a mooncake!

Body:
Pyth, <s>71</s> <s>65</s> <s>59</s> 58 bytes

Saved 1 byte thanks to @StevenH.

jjRc"(@@)"2++J*KtytQ\@m.[Kd;.[ttQ@,,O"MC"\F]Oc"MAFHMF"3QkJ

Try it online. Test suite.

So much padding.


答:
JavaScript (ES6), 44 bytes

```<code>a=>a.reduceRight(([n,d],v)=>[v*n+d,n],[1,0])
</code>```

Title: Simplify a continued fraction

Body:
Continued fractions are expressions that describe fractions iteratively. They can be represented graphically:

$$
a_0 +\cfrac 1
 {a_1 + \cfrac 1
  {a_2 + \cfrac 1
   {\ddots + \cfrac 1
    {a_n}
   }
  }
 }
$$

Or they can be represented as a list of values: \$[a_0 ; a_1, a_2, \dots, a_n]\$

The challenge:

take a base number: \$a_0\$ and a list of denominator values: \$[a_1, a_2, \dots, a_n]\$ and simplify the continued fraction to a simplified rational fraction: return or print numerator and denominator separately.

Examples:

\$\sqrt 19\$: [4;2,1,3,1,2]: 170/39

\$e\$: [1;0,1,1,2,1,1]: 19/7

\$\pi\$: [3;7,15,1,292,1]: 104348/33215

\$ϕ\$: [1;1,1,1,1,1]: 13/8

Example implementation: (python)

def foo(base, sequence):
    numerator = 1
    denominator = sequence[-1]
    for d in sequence[-2::-1]:
        temp = denominator
        denominator = d * denominator + numerator
        numerator = temp
    return numerator + base * denominator, denominator```

Winning:
 shortest code in bytes: --no builtins that do the entire problem allowed--

Body:
JavaScript (ES6), 44 bytes

a=>a.reduceRight(([n,d],v)=>[v*n+d,n],[1,0])


答:
R, 53 bytes

Assumes that the input is space- or newline-separated for each character.

```<code>cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
</code>```

Some test cases:

```<code>> cat(rep(c(i<-scan(,""),rev(i)),len=length(i)^2),sep="")
1: h e l l o !
7:
Read 6 items
hello!!ollehhello!!ollehhello!!olleh

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: a
2:
Read 1 item
a

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: a b c d
5:
Read 4 items
abcddcbaabcddcba

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: O K !
4:
Read 3 items
OK!!KOOK!

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: 4 8 1 5 1 6 2 3 4 2
11:
Read 10 items
4815162342243261518448151623422432615184481516234224326151844815162342243261518448151623422432615184

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: P P C G
5:
Read 4 items
PPCGGCPPPPCGGCPP

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: 4 2
3:
Read 2 items
4224
</code>```

Title: StringgnirtSStringgnirtSStringgnirtS

Body:
Here is a relatively simple challenge for you.

Given a string of length N, output the string forwards, then backwards, then forwards, then backwards... etc. N times. For example, if your input was

```<code>Hello!
</code>```

You should output:

```<code>Hello!!olleHHello!!olleHHello!!olleH
</code>```

You may also optionally output one trailing newline.

Your submission may be either a full program or a function, and you may take input and output in any reasonable format. For example, you may take IO from STDIN/STDOUT, function arguments and return value, from a file, etc. You can safely assume that the input string will not be empty, and will only contain printable ASCII. You must output the new string on a single line. So, for example, if the output to the last example was

```<code>Hello!
!olleH
Hello!
!olleH
Hello!
!olleH
</code>```

This would not be a valid solution!

Here are some more test cases:

```<code>Input:
a
Output:
a

Input:
abcd
Output:
abcddcbaabcddcba

Input:
OK!
Output:
OK!!KOOK!

Input:
4815162342
Output:
4815162342243261518448151623422432615184481516234224326151844815162342243261518448151623422432615184

Input:
PPCG
Output:
PPCGGCPPPPCGGCPP

Input:
42
Output:
4224
</code>```

Leaderboards

Since this is a code-golf challenge, standard loopholes are banned, and the shortest answer in bytes wins! However, this is also a competition to have the shortest answer in any particular langauge. While it's unlikely that a Java answer will beat an answer in perl, or some golfing language, it's still very impressive to have the shortest Java answer. So, you can use this leaderboard to see both

The shortest answer out of all languages, and

The shortest answer in each individual language.

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 leaderboard snippet:

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
R, 53 bytes

Assumes that the input is space- or newline-separated for each character.

cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")

Some test cases:

> cat(rep(c(i<-scan(,""),rev(i)),len=length(i)^2),sep="")
1: h e l l o !
7:
Read 6 items
hello!!ollehhello!!ollehhello!!olleh

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: a
2:
Read 1 item
a

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: a b c d
5:
Read 4 items
abcddcbaabcddcba

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: O K !
4:
Read 3 items
OK!!KOOK!

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: 4 8 1 5 1 6 2 3 4 2
11:
Read 10 items
4815162342243261518448151623422432615184481516234224326151844815162342243261518448151623422432615184

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: P P C G
5:
Read 4 items
PPCGGCPPPPCGGCPP

> cat(rep(c(i<-scan(,""),rev(i)),l=length(i)^2),sep="")
1: 4 2
3:
Read 2 items
4224


问:
Output an upside-down tent
Given an integer, output an upside-down tent.

The input determines both the size of the tent (absolute value) and whether the entrance is on the left side (negative numbers) or the right side (positive numbers).

```<code>If input = -1:
____
\/_/

If input = -2:
________
\  /   /
 \/___/

If input = -3:
____________
\    /     /
 \  /     /
  \/_____/

If input = 1:
____
\_\/

If input = 2:
________
\   \  /
 \___\/

If input = 3:
____________
\     \    /
 \     \  /
  \_____\/

et cetera
</code>```

Note that the top of the tent (i.e. the last line) has 2 * abs(input) - 1 underscores.

There can be no leading spaces, such that the first line directly starts with an underscore.

Assume that the input will never be 0.

Your code should be as short as possible.

This challenge is based on a chat mini challenge by Helka Homba, which is allowed to be used in real challenges under the conditions of Calvin's Hobbies Public License.

答:
Batch, 289 bytes

```<code>@echo off
set/pn=
set u=
for /l %%i in (2,1,%n:-=%)do call set u=_%%u%%_
echo _%u%__%u%_
set l=
set m=%u%/_%u%
if %n% gtr 0 set m=%u%_\%u%
set m=%m:_= %
for /l %%i in (2,1,%n:-=%)do call:l
set m=%m: =_%
:l
echo %l%\%m%/
set l= %l%
if %n% gtr 0 set m=  %m:~0,-2%
set m=%m:~2%
</code>```

Takes input on STDIN. Starts by creating a string of 2*(abs(n)-1) underscores. This is then repeated plus an additional 4 underscores for the base of the tent. The rest of the tent then consists of an indent (which increases by 1 on each line), a \, the middle of the tent, and a /. The middle of the tent starts as 2*(abs(n)-1) spaces, plus either \ or / plus a space (which I can't represent in Markdown), plus another 2*(abs(n)-1) spaces. I reuse the underscore string and change them to spaces for convenience, but then change the spaces back to underscores for the last line. Each line removes two spaces from one side of the middle of the tent, although it's slightly golfier to move the two spaces to the start of the string first if necessary.

Title: Output an upside-down tent

Body:
Batch, 289 bytes

@echo off
set/pn=
set u=
for /l %%i in (2,1,%n:-=%)do call set u=_%%u%%_
echo _%u%__%u%_
set l=
set m=%u%/_%u%
if %n% gtr 0 set m=%u%_\%u%
set m=%m:_= %
for /l %%i in (2,1,%n:-=%)do call:l
set m=%m: =_%
:l
echo %l%\%m%/
set l= %l%
if %n% gtr 0 set m=  %m:~0,-2%
set m=%m:~2%

Takes input on STDIN. Starts by creating a string of 2*(abs(n)-1) underscores. This is then repeated plus an additional 4 underscores for the base of the tent. The rest of the tent then consists of an indent (which increases by 1 on each line), a \, the middle of the tent, and a /. The middle of the tent starts as 2*(abs(n)-1) spaces, plus either \ or / plus a space (which I can't represent in Markdown), plus another 2*(abs(n)-1) spaces. I reuse the underscore string and change them to spaces for convenience, but then change the spaces back to underscores for the last line. Each line removes two spaces from one side of the middle of the tent, although it's slightly golfier to move the two spaces to the start of the string first if necessary.