问:
"Convenient palindrome" checker
If you've ever tried to write palindromic code before, you'd know how much brackets tend to get in your way. ()() is not a palindrome, even though it kinda looks like it should be, while ())( and ()( are both palindromic and both very dumb looking. Wouldn't it be convenient if it was the other way around?

A string is conveniently palindromic if it is equal to the string derived when its reverse has all its parentheses (()), brackets ([]), and braces ({}) flipped. No other characters are special and require flipping. (<> are sometimes paired but often not so they are left out.)

Your task is to write, in your language, a program (taking input on STDIN) or a function (taking a single string argument) which (a) gives a consistent true value* when its argument is conveniently palindromic and a different, consistent false value otherwise, and (b) is itself conveniently palindromic.

For example, the following inputs are conveniently palindromic:

```<code>racecar
(a)(bb)(a)
void main(int argc, *char[] argv) {} (vgra []rahc* ,cgra tni)niam diov
</code>```

And the following are not:

```<code>non-palindrome
A nut for a jar of tuna?
(old [style] parens) )snerap ]elyts[ dlo(
ingirumimusnocte)etconsumimurigni
</code>```

You may not rely on any external state (specific filename, directory structure, other user input, web access, etc) except interpreter/compiler flags.

Also, you may not use "the comment trick" where you comment out or render unused some piece of code by taking advantage of your language's commenting facilities. For instance, all of the following are not allowed, because they contain non-functional parts that can be safely removed or destroyed (at the expense of losing conveniently-palindromic-ness):

```<code>{some code} // {edoc emos}
{some code} NB.BN {edoc emos}
"n\" ;{edoc emos} ;"; {some code}; "\n"
</code>```

Obviously this might not cover every such case, but the spirit of the challenge here is not to use comments and unparsed** code to achieve palindrominess, instead making use of the corrected parens and brackets. I'm looking at you, LISP, Brainfuck.

This is a code-golf, so the shortest code wins, but all lengths of code are welcome.

* By consistent true and false values, I mean that you can return one of a pair of values, such as 1 for true and 0 for false, or False for true and "no" for false, so long as these values are different from each other, and do not change from run to run of your program. Use whatever saves you characters.

** Not to be confused with unexecuted: code that is valid and might do weird things but never called is fine.

Title: "Convenient palindrome" checker

Body:
JavaScript (ES6), 245 bytes

I wanted a JS answer that could be run in the browser, so here it is.

eurt=>eurt==(("",eurt))["split"||"nioj"]("")["map"||"esrever"](x=>({'{':'}','}':'{','[':']',']':'[','(':')',')':'('})[x]||x||[x]({')':'(','(':')',']':'[','[':']','}':'{','{':'}'})>=x)["reverse"||"pam"]("")["join"||"tilps"]((true,""))==true>=true

Removing all code that is never actually run, we get this:

eurt=>eurt==(("",eurt))["split"||"nioj"]("")["map"||"esrever"](x=>({'{':'}','}':'{','[':']',']':'[','(':')',')':'('})[x]||x||[x]({')':'(','(':')',']':'[','[':']','}':'{','{':'}'})>=x)["reverse"||"pam"]("")["join"||"tilps"]((true,""))==true>=true
eurt=>eurt==(("",eurt))["split"        ]("")["map"           ](x=>({'{':'}','}':'{','[':']',']':'[','(':')',')':'('})[x]||x                                                           )["reverse"       ]("")["join"         ]((true,""))==true>=true

Which can be simplified to this:

eurt=>eurt==eurt.split("").map(x=>({'{':'}','}':'{','[':']',']':'[','(':')',')':'('})[x]||x).reverse("").join("")


问:
N(e(s(t))) a string
To "function nest" a string, you must:

Treat the first character as a function, and the following characters as the arguments to that function. For example, if the input string was Hello, then the first step would be:

```<code>H(ello)
</code>```

Then, repeat this same step for every substring. So we get:

```<code>H(ello)
H(e(llo))
H(e(l(lo)))
H(e(l(l(o))))
</code>```

Your task is to write a program or function that "function nests" a string. For example, if the input string was Hello world!, then you should output:

```<code>H(e(l(l(o( (w(o(r(l(d(!)))))))))))
</code>```

The input will only ever contain printable ASCII, and you may take the input and the output in any reasonable format. For example, STDIN/STDOUT, function arguments and return value, reading and writing to a file, etc.

For simplicity's sake, you may also assume the input will not contain parentheses, and will not be empty.

```<code>Input:
Nest a string
Output:
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))

Input:
foobar
Output:
f(o(o(b(a(r)))))

Input:
1234567890
Output:
1(2(3(4(5(6(7(8(9(0)))))))))

Input:
code-golf
Output:
c(o(d(e(-(g(o(l(f))))))))

Input:
a
Output:
a

Input:
42
Output:
4(2)
</code>```

As usual, all of our default rules and loopholes apply, and the shortest answer scored in bytes wins!

答:
Haskell, 30 bytes

```<code>f[x]=[x]
f(a:b)=a:'(':f b++")"
</code>```

Usage example: f "Nest a string" -> "N(e(s(t( (a( (s(t(r(i(n(g))))))))))))".

Take the next char, followed by a (, followed by a recursive call with all but the first char, followed by a ).

ContentLicense: CC BY-SA 3.0

Title: N(e(s(t))) a string

Body:
Haskell, 30 bytes

f[x]=[x]
f(a:b)=a:'(':f b++")"

Usage example: f "Nest a string" -> "N(e(s(t( (a( (s(t(r(i(n(g))))))))))))".

Take the next char, followed by a (, followed by a recursive call with all but the first char, followed by a ).


答:
PHP, 63 Bytes

```<code><?=str_pad(join("(",$s=str_split($argv[1])),count($s)*3-2,")");
</code>```

Previous version 64 Bytes

```<code><?=join("(",$s=str_split($argv[1])).str_pad("",count($s)-1,")");
</code>```

Title: N(e(s(t))) a string

Body:
To "function nest" a string, you must:

Treat the first character as a function, and the following characters as the arguments to that function. For example, if the input string was Hello, then the first step would be:

```<code>H(ello)
</code>```

Then, repeat this same step for every substring. So we get:

```<code>H(ello)
H(e(llo))
H(e(l(lo)))
H(e(l(l(o))))
</code>```

Your task is to write a program or function that "function nests" a string. For example, if the input string was Hello world!, then you should output:

```<code>H(e(l(l(o( (w(o(r(l(d(!)))))))))))
</code>```

The input will only ever contain printable ASCII, and you may take the input and the output in any reasonable format. For example, STDIN/STDOUT, function arguments and return value, reading and writing to a file, etc.

For simplicity's sake, you may also assume the input will not contain parentheses, and will not be empty.

```<code>Input:
Nest a string
Output:
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))

Input:
foobar
Output:
f(o(o(b(a(r)))))

Input:
1234567890
Output:
1(2(3(4(5(6(7(8(9(0)))))))))

Input:
code-golf
Output:
c(o(d(e(-(g(o(l(f))))))))

Input:
a
Output:
a

Input:
42
Output:
4(2)
</code>```

As usual, all of our default rules and loopholes apply, and the shortest answer scored in bytes wins!

Body:
PHP, 63 Bytes

<?=str_pad(join("(",$s=str_split($argv[1])),count($s)*3-2,")");

Previous version 64 Bytes

<?=join("(",$s=str_split($argv[1])).str_pad("",count($s)-1,")");


答:
Java 7,81 79 bytes

Saved 1 byte.Thanks  to kevin.

```<code>String f(char[]a,String b,int l){return l<a.length?f(a,b+'('+a[l],++l)+')':b;}
</code>```

Title: N(e(s(t))) a string

Body:
Java 7,81 79 bytes

Saved 1 byte.Thanks  to kevin.

String f(char[]a,String b,int l){return l<a.length?f(a,b+'('+a[l],++l)+')':b;}


答:
J, 13 bytes

```<code>(,'(',,&')')/
</code>```

J executes from right-to-left so using the insert adverb /, a verb can be used to reduce the letters of the input string.

Usage

```<code>   f =: (,'(',,&')')/
   f 'Nest a string'
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))
   f 'foobar'
f(o(o(b(a(r)))))
   f '1234567890'
1(2(3(4(5(6(7(8(9(0)))))))))
   f 'code-golf'
c(o(d(e(-(g(o(l(f))))))))
</code>```

You can observe the partial outputs between each reduction.

```<code>   |. f\. 'Hello'
o
l(o)
l(l(o))
e(l(l(o)))
H(e(l(l(o))))
</code>```

Explanation

```<code>(,'(',,&')')/  Input: string S
(          )/  Insert this verb between each char and execute (right-to-left)
      ,&')'      Append a ')' to the right char
  '(',           Prepend a '(' to that
 ,               Append to the left char
</code>```

Title: N(e(s(t))) a string

Body:
J, 13 bytes

(,'(',,&')')/

J executes from right-to-left so using the insert adverb /, a verb can be used to reduce the letters of the input string.

Usage

   f =: (,'(',,&')')/
   f 'Nest a string'
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))
   f 'foobar'
f(o(o(b(a(r)))))
   f '1234567890'
1(2(3(4(5(6(7(8(9(0)))))))))
   f 'code-golf'
c(o(d(e(-(g(o(l(f))))))))

You can observe the partial outputs between each reduction.

   |. f\. 'Hello'
o
l(o)
l(l(o))
e(l(l(o)))
H(e(l(l(o))))

Explanation

(,'(',,&')')/  Input: string S
(          )/  Insert this verb between each char and execute (right-to-left)
      ,&')'      Append a ')' to the right char
  '(',           Prepend a '(' to that
 ,               Append to the left char


答:
Factor, 81 bytes

```<code>[ [ >array [ 1string ] map "("join ] [ length 1 - [ 40 ] replicate >string ] bi ]
</code>```

Title: N(e(s(t))) a string

Body:
Factor, 81 bytes

[ [ >array [ 1string ] map "("join ] [ length 1 - [ 40 ] replicate >string ] bi ]


答:
MATL, 16 bytes

```<code>t~40+v3L)7MQ3L)h
</code>```

Try it online!

Explanation

```<code>t     % Implicit input. Duplicate
      % STACK: 'foobar', 'foobar'
~     % Negate. Transforms into an array of zeros
      % STACK: 'foobar', [0 0 0 0 0 0]
40+   % Add 40, element-wise. Gives array containing 40 repeated
      % STACK: 'foobar', [40 40 40 40 40 40]
v     % Concatenate vertically. Gives a two-row char array, with 40 cast into '('
      % STACK: ['foobar'; '((((((']
3L)   % Remove last element. Converts to row vector
      % STACK: 'f(o(o(b(a(r'
7M    % Push array containing 40 again
      % STACK: 'f(o(o(b(a(r', [40 40 40 40 40 40]
Q     % Add 1, element-wise
      % STACK: 'f(o(o(b(a(r', [41 41 41 41 41 41]
h     % Concatenate horizontally, with 41 cast into ')'
      % STACK: 'f(o(o(b(a(r)))))'
      % Implicit display
</code>```

Title: N(e(s(t))) a string

Body:
MATL, 16 bytes

t~40+v3L)7MQ3L)h

Try it online!

Explanation

t     % Implicit input. Duplicate
      % STACK: 'foobar', 'foobar'
~     % Negate. Transforms into an array of zeros
      % STACK: 'foobar', [0 0 0 0 0 0]
40+   % Add 40, element-wise. Gives array containing 40 repeated
      % STACK: 'foobar', [40 40 40 40 40 40]
v     % Concatenate vertically. Gives a two-row char array, with 40 cast into '('
      % STACK: ['foobar'; '((((((']
3L)   % Remove last element. Converts to row vector
      % STACK: 'f(o(o(b(a(r'
7M    % Push array containing 40 again
      % STACK: 'f(o(o(b(a(r', [40 40 40 40 40 40]
Q     % Add 1, element-wise
      % STACK: 'f(o(o(b(a(r', [41 41 41 41 41 41]
h     % Concatenate horizontally, with 41 cast into ')'
      % STACK: 'f(o(o(b(a(r)))))'
      % Implicit display


答:
Brainfuck, <s>42</s> 40 bytes

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

Try it online!

Ungolfed:

```<code>>+[-->+[<]>-]>+     # count to 40 (ASCII for open paren)
>>                  # move to the input holder
,.                  # input the first byte and output it
,                   # input the next byte
[                   # while it's not zero
  <+                # move to the input counter and increment it
  <.                # move to the open paren and output it
  >>.               # move to the input holder and output it
  ,                 # input the next byte
]
<<+                 # move to the open paren and increment it to a close
>                   # move to the input counter
[                   # while it's not zero
  -                 # decrement it
  <.                # move to the close paren and output it
  >                 # move to the input counter
]
</code>```

Title: N(e(s(t))) a string

Body:
Brainfuck, <s>42</s> 40 bytes

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

Try it online!

Ungolfed:

>+[-->+[<]>-]>+     # count to 40 (ASCII for open paren)
>>                  # move to the input holder
,.                  # input the first byte and output it
,                   # input the next byte
[                   # while it's not zero
  <+                # move to the input counter and increment it
  <.                # move to the open paren and output it
  >>.               # move to the input holder and output it
  ,                 # input the next byte
]
<<+                 # move to the open paren and increment it to a close
>                   # move to the input counter
[                   # while it's not zero
  -                 # decrement it
  <.                # move to the close paren and output it
  >                 # move to the input counter
]


答:
Convex, 10 bytes

```<code>_'(*\,(')*
</code>```

Try it online!

Title: N(e(s(t))) a string

Body:
Convex, 10 bytes

_'(*\,(')*

Try it online!


答:
Vim, 17 bytes

$qqha(<Esc>A)<Esc>%h@qq@q

Goes from end to beginning, because otherwise you trip over the )s you've already written. Uses ha instead of i to fail when it reaches the beginning.

Usually, you wouldn't do two separate inserts like this; you'd do something like C()<Esc>P to save a stroke. But the positioning doesn't work as well this time.

Title: N(e(s(t))) a string


答:
C, <s>102</s> 89 bytes

<s>Maybe this can be golfed more?</s> I'm just happy to answer in C! :D

```<code>i=0,j=0;f(char*a){while(*a)putchar(*a),*++a?putchar(40),i++:0;while(j<i)putchar(41),j++;}
</code>```

Title: N(e(s(t))) a string

Body:
C, <s>102</s> 89 bytes

<s>Maybe this can be golfed more?</s> I'm just happy to answer in C! :D

i=0,j=0;f(char*a){while(*a)putchar(*a),*++a?putchar(40),i++:0;while(j<i)putchar(41),j++;}


答:
Brain-Flak 103 97 Bytes

Includes +3 for -c

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

Try it Online!

Explanation:

```<code>#reverse the stack and put a 40 between every number
{({}<><(((((()()){}()){}){}){})>)<>}<>
{                                  }   #repeat this until the stack is empty
 ({}                            )      #pop the top and push it after
    <>                                 #switching stacks and
      <(((((()()){}()){}){}){})>       #pushing a 40 (evaluated as 0)
                                 <>    #switch back to the first stack
                                    <> #switch to the stack that everything is on now

#put as many )s on the other stack as needed
({}                                      ) #pop the top letter and put it  back
                                           #after doing the following
                                           #This leaves ( on the top
   <                                    >  #evalute this part as 0
    ([][()])                               #push the height of the stack minus one
            {                        }    #repeat until the "height" is 0
             ({}[()()]              )     #pop the "height" and push is minus two
                      <            >      #evaluate to 0
                       (        )         #push:
                        ({})              #the top of the stack (putting it back on)
                            ()            #plus one onto
                              <>          #the other stack
                                 <>       #switch back to the other stack

                                      {}  #pop what was the height of the stack

#move the string of letters and (s back, reversing the order again
{        }     # repeat until all elements are moved
 (    )        # push:
  {}           # the top of the stack after
    <>         # switching stacks
       <>      # switch back to the other stack
          <>   # switch to the stack with the final string
            {} #pop the extra (
</code>```

Title: N(e(s(t))) a string

Body:
Brain-Flak 103 97 Bytes

Includes +3 for -c

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

Try it Online!

Explanation:

#reverse the stack and put a 40 between every number
{({}<><(((((()()){}()){}){}){})>)<>}<>
{                                  }   #repeat this until the stack is empty
 ({}                            )      #pop the top and push it after
    <>                                 #switching stacks and
      <(((((()()){}()){}){}){})>       #pushing a 40 (evaluated as 0)
                                 <>    #switch back to the first stack
                                    <> #switch to the stack that everything is on now

#put as many )s on the other stack as needed
({}                                      ) #pop the top letter and put it  back
                                           #after doing the following
                                           #This leaves ( on the top
   <                                    >  #evalute this part as 0
    ([][()])                               #push the height of the stack minus one
            {                        }    #repeat until the "height" is 0
             ({}[()()]              )     #pop the "height" and push is minus two
                      <            >      #evaluate to 0
                       (        )         #push:
                        ({})              #the top of the stack (putting it back on)
                            ()            #plus one onto
                              <>          #the other stack
                                 <>       #switch back to the other stack

                                      {}  #pop what was the height of the stack

#move the string of letters and (s back, reversing the order again
{        }     # repeat until all elements are moved
 (    )        # push:
  {}           # the top of the stack after
    <>         # switching stacks
       <>      # switch back to the other stack
          <>   # switch to the stack with the final string
            {} #pop the extra (


答:
Perl 5, 44 33 bytes (31 + 1 for -l + 1 for -p)

saved 11 bytes thanks to Dada

```<code>s/([\w ])([\w ]+)/$1($2)/&&redo
</code>```

Can be run from the command line with the -p and -e options.

```<code>$ perl -ple 's/([\w ])([\w ]+)/$1($2)/&&redo' <<< 'Hello'
</code>```

Output:

```<code>H(e(l(l(o))))
</code>```

Title: N(e(s(t))) a string

Body:
Perl 5, 44 33 bytes (31 + 1 for -l + 1 for -p)

saved 11 bytes thanks to Dada

s/([\w ])([\w ]+)/$1($2)/&&redo

Can be run from the command line with the -p and -e options.

$ perl -ple 's/([\w ])([\w ]+)/$1($2)/&&redo' <<< 'Hello'

Output:

H(e(l(l(o))))


问:
Export The $PATH Variable, Line-By-Line
Inspired by this question on AskUbuntu.

Your job is extremely simple. Take the PATH environment variable (echo $PATH) and export it such that each entry (separated by the : character) is on its own line.

For example, if the PATH is /bin:/usr/bin:/usr/local/bin, your program should output:

```<code>/bin
/usr/bin
/usr/local/bin
</code>```

Your program may not return a leading newline, but it may return a single trailing newline. You do not need to check if the PATH is right, or that the directory exists. Your program should take no input, meaning that your program is responsible for getting the PATH itself. You may safely assume that objects in the PATH do not contain : or newlines. However, spaces are fair game.

Reference implementations are present in the answers to the question above.

Rules

This is (obviously) code-golf, so the shortest answer will win the prized green checkmark.

The accepted answer will be tested to make sure it's actually legit.

Both Windows and *nix entries are accepted.

However, if you don't explicitly specify Windows, I will try running it in Linux and fail. (If it's obvious (hi, Batch!), you don't need to specify explicitly.)

Only have one solution per answer. If you have both a Windows and *nix version, I will count the shorter one.

If two answers have the same length, I will give priority to the one with the higher vote total. If they have the same vote total, I will count the older one. If the time posted is the same, I will choose the one that executes faster. If they execute in the same amount of time, I don't know.

Leaderboard

var QUESTION_ID=96334,OVERRIDE_USER=15422;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

```

答:
Befunge-98 + EVAR fingerprint, 34 bytes

```<code>"RAVE"4("HTAP"Gv
:!k@:':-!'0*-, >
</code>```

Loads the EVAR fingerprint ("RAVE"4() to easily access environment variables, gets the PATH envvar ("HTAP"G), and for each character, exits the program if the character is "\0" (:!k@), substracts ASCII 48 "0" if the char is ASCII 58 ":" (:':-!'0*-), and outputs the character (,).

Title: Export The $PATH Variable, Line-By-Line

Body:
Befunge-98 + EVAR fingerprint, 34 bytes

"RAVE"4("HTAP"Gv
:!k@:':-!'0*-, >

Loads the EVAR fingerprint ("RAVE"4() to easily access environment variables, gets the PATH envvar ("HTAP"G), and for each character, exits the program if the character is "\0" (:!k@), substracts ASCII 48 "0" if the char is ASCII 58 ":" (:':-!'0*-), and outputs the character (,).


答:
MS-DOS .com file, 30 bytes

```<code>0000   fc be 82 00 b4 02 ac 88 c2 cd 21 ac 3c 0d 74 0d
0010   b2 28 50 cd 21 5a e8 f0 ff b2 29 cd 21 c3
</code>```

The string is passed to the executable using the command line. (One space character between the .COM file name and the string).

The result is written to standard output.

The disassembly is here:

```<code>  fc          cld              ; Make sure DF is not set (lodsb!)
  be 82 00    mov    si,0x82   ; First character of command line args
  b4 02       mov    ah,0x2    ; AH=2 means output for INT 21h
  ac          lodsb            ; Load first character
  88 c2       mov    dl,al     ; Move AL to DL (DL is written to output)
recursiveFunction:
  cd 21       int    0x21      ; Output
  ac          lodsb            ; Get the next character
  3c 0d       cmp    al,0xd    ; If it is "CR" (end of command line) ...
  74 0d       je     doReturn  ; ... return from the recursive function
  b2 28       mov    dl,0x28   ; Output "(" next...
  50          push   ax        ; ... but save character read first
  cd 21       int    0x21      ; (Actual output)
  5a          pop    dx        ; Restore character (but in DL, not in AL)
  e8 f0 ff    call   recursiveFunction  ; Recursively enter the function
doReturn:
  b2 29       mov    dl,0x29   ; Output ")"
  cd 21       int    0x21
  c3          ret              ; Actually return
</code>```

Note: You can exit a DOS .COM file (unlike files with EXE headers) using a "RET" instruction.

Title: N(e(s(t))) a string

Body:
MS-DOS .com file, 30 bytes

0000   fc be 82 00 b4 02 ac 88 c2 cd 21 ac 3c 0d 74 0d
0010   b2 28 50 cd 21 5a e8 f0 ff b2 29 cd 21 c3

The string is passed to the executable using the command line. (One space character between the .COM file name and the string).

The result is written to standard output.

The disassembly is here:

  fc          cld              ; Make sure DF is not set (lodsb!)
  be 82 00    mov    si,0x82   ; First character of command line args
  b4 02       mov    ah,0x2    ; AH=2 means output for INT 21h
  ac          lodsb            ; Load first character
  88 c2       mov    dl,al     ; Move AL to DL (DL is written to output)
recursiveFunction:
  cd 21       int    0x21      ; Output
  ac          lodsb            ; Get the next character
  3c 0d       cmp    al,0xd    ; If it is "CR" (end of command line) ...
  74 0d       je     doReturn  ; ... return from the recursive function
  b2 28       mov    dl,0x28   ; Output "(" next...
  50          push   ax        ; ... but save character read first
  cd 21       int    0x21      ; (Actual output)
  5a          pop    dx        ; Restore character (but in DL, not in AL)
  e8 f0 ff    call   recursiveFunction  ; Recursively enter the function
doReturn:
  b2 29       mov    dl,0x29   ; Output ")"
  cd 21       int    0x21
  c3          ret              ; Actually return

Note: You can exit a DOS .COM file (unlike files with EXE headers) using a "RET" instruction.


答:
><>, 37 bytes

```<code>i:0(?\'('
$,2l~/~
/?(2:<-1$')'
>~ror:
</code>```

Row by row

Pushes each char from input with an opening parenthesis after each

Removes EOF and the last opening parenthesis and pushes the stack length

Uses a comparison with half the stack length to push the closing parenthesis

Prints the content of the stack

Try it online!

Title: N(e(s(t))) a string

Body:
><>, 37 bytes

i:0(?\'('
$,2l~/~
/?(2:<-1$')'
>~ror:

Row by row

Pushes each char from input with an opening parenthesis after each

Removes EOF and the last opening parenthesis and pushes the stack length

Uses a comparison with half the stack length to push the closing parenthesis

Prints the content of the stack

Try it online!


答:
Perl, 36 bytes (34 + 2 for -lpflag)

Thanks to Dada for pointing out a bug and saving one byte (in total)!

Splits the string into an array, then joins it with the (delimiter. We directly add the closing )since lengthreturns the length of the string before the join.

```<code>$_=(join"(",split//).")"x(y///c-1)
</code>```

Try it here!

Title: N(e(s(t))) a string

Body:
Perl, 36 bytes (34 + 2 for -lpflag)

Thanks to Dada for pointing out a bug and saving one byte (in total)!

Splits the string into an array, then joins it with the (delimiter. We directly add the closing )since lengthreturns the length of the string before the join.

$_=(join"(",split//).")"x(y///c-1)

Try it here!


问:
Spaced-out numbers
Given a list of N non-negative integers, output those numbers with each left-padded by spaces to a length of N. (Alternatively, return a character/string list.) You may assume that N is greater than or equal to the number of digits of the largest number in the list. Trailing spaces are allowed in the output.

You may also take a string containing these numbers, but N is not the length of the string, but rather the number of elements in the list; also, you may take a list of strings e.g. ["1", "2", "3"].

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

Test cases

```<code>input => 'output'
0 => '0'
1 => '1'
2 3 => ' 2 3'
2 10 => ' 210'
4 5 6 => '  4  5  6'
17 19 20 => ' 17 19 20'
7 8 9 10 => '   7   8   9  10'
100 200 300 0 => ' 100 200 300   0'
1000 400 30 7 => '1000 400  30   7'
1 33 333 7777 => '   1  33 3337777'
0 0 0 0 0 0 => '     0     0     0     0     0     0'
</code>```

答:
Pyth - 7 bytes

Straightforward answer using padding builtin.

```<code>sm.[;lQ
</code>```

Test Suite.

Title: Spaced-out numbers

Body:
Pyth - 7 bytes

Straightforward answer using padding builtin.

sm.[;lQ

Test Suite.


答:
Ruby, 27 bytes

```<code>->s{s.chars*?(+?)*~-s.size}
</code>```

Explanation

```<code>->s{                       # Declare anonymous lambda taking argument s
    s.chars                # Get the array of chars representing s
           *?(             # Join the elements back into a string using "("s as separators
              +?)*~-s.size # Append (s.size - 1) ")"s to the end
</code>```

Title: N(e(s(t))) a string

Body:
Ruby, 27 bytes

->s{s.chars*?(+?)*~-s.size}

Explanation

->s{                       # Declare anonymous lambda taking argument s
    s.chars                # Get the array of chars representing s
           *?(             # Join the elements back into a string using "("s as separators
              +?)*~-s.size # Append (s.size - 1) ")"s to the end


答:
R, 61 bytes

cat(gsub("(?<=.)(?=.)","(",x,F,T),rep(")",nchar(x)-1),sep="")
```

Regex finds and replaces spaces between characters with "(". Then cat and rep add ")" n-1 times at the end.

Title: N(e(s(t))) a string

Body:
To "function nest" a string, you must:

Treat the first character as a function, and the following characters as the arguments to that function. For example, if the input string was Hello, then the first step would be:

```<code>H(ello)
</code>```

Then, repeat this same step for every substring. So we get:

```<code>H(ello)
H(e(llo))
H(e(l(lo)))
H(e(l(l(o))))
</code>```

Your task is to write a program or function that "function nests" a string. For example, if the input string was Hello world!, then you should output:

```<code>H(e(l(l(o( (w(o(r(l(d(!)))))))))))
</code>```

The input will only ever contain printable ASCII, and you may take the input and the output in any reasonable format. For example, STDIN/STDOUT, function arguments and return value, reading and writing to a file, etc.

For simplicity's sake, you may also assume the input will not contain parentheses, and will not be empty.

```<code>Input:
Nest a string
Output:
N(e(s(t( (a( (s(t(r(i(n(g))))))))))))

Input:
foobar
Output:
f(o(o(b(a(r)))))

Input:
1234567890
Output:
1(2(3(4(5(6(7(8(9(0)))))))))

Input:
code-golf
Output:
c(o(d(e(-(g(o(l(f))))))))

Input:
a
Output:
a

Input:
42
Output:
4(2)
</code>```

As usual, all of our default rules and loopholes apply, and the shortest answer scored in bytes wins!

Body:
R, 61 bytes

cat(gsub("(?<=.)(?=.)","(",x,F,T),rep(")",nchar(x)-1),sep="")

Regex finds and replaces spaces between characters with "(". Then cat and rep add ")" n-1 times at the end.


答:
Perl, 25 bytes

Thanks to @Ton Hospel for golfing out 4 bytes.

24 bytes of code + -F.

```<code>$"="(";say"@F".")"x$#F
</code>```

Needs -F and -E flags :

```<code>echo -n "I love lisp" | perl -F -E '$"="(";say"@F".")"x$#F'
</code>```

Note that if you try this on an old version of perl, you might need to add -a flag.

Another interesting way (a little bit longer though : 28 bytes) :

Thanks to Ton Hospel once again for helping me getting this one right.

```<code>#!/usr/bin/perl -p
s/.(?=.)/s%\Q$'%($&)%/reg
</code>```

(To use  it, put the code inside a file and call it with echo -n "Hello" | perl nest.pl)

Title: N(e(s(t))) a string

Body:
Perl, 25 bytes

Thanks to @Ton Hospel for golfing out 4 bytes.

24 bytes of code + -F.

$"="(";say"@F".")"x$#F

Needs -F and -E flags :

echo -n "I love lisp" | perl -F -E '$"="(";say"@F".")"x$#F'

Note that if you try this on an old version of perl, you might need to add -a flag.

Another interesting way (a little bit longer though : 28 bytes) :

Thanks to Ton Hospel once again for helping me getting this one right.

#!/usr/bin/perl -p
s/.(?=.)/s%\Q$'%($&)%/reg

(To use  it, put the code inside a file and call it with echo -n "Hello" | perl nest.pl)


问:
Tips for golfing in 05AB1E
Do you have any tips for code-golfing in 05AB1E, a golfing language created by Adnan?

Your tips should be at least somewhat specific to 05AB1E.

Please post one tip per answer.

答:
Automatic vectorization

Note that some operators in 05AB1E vectorize automatically on arrays. For example, the code 5L3+, which disassembles to the following pseudocode:

```<code>[1, 2, 3, 4, 5] + 3
</code>```

would become:

```<code>[4, 5, 6, 7, 8]
</code>```

If it doesn't vectorize automatically, you can also use the € operator. It takes a single character command, and performs that (monadic) operator on each element. An example to split each element is the following code (try it here):

```<code>€S
</code>```

Whereas the normal S operator would split each element in the array and flattens it into a single array (try it here).

Title: Tips for golfing in 05AB1E

Body:
Automatic vectorization

Note that some operators in 05AB1E vectorize automatically on arrays. For example, the code 5L3+, which disassembles to the following pseudocode:

[1, 2, 3, 4, 5] + 3

would become:

[4, 5, 6, 7, 8]

If it doesn't vectorize automatically, you can also use the € operator. It takes a single character command, and performs that (monadic) operator on each element. An example to split each element is the following code (try it here):

€S

Whereas the normal S operator would split each element in the array and flattens it into a single array (try it here).


答:
Pyth - 9 bytes

```<code>+j\(Qsm\)
</code>```

Try it online here.

Title: N(e(s(t))) a string

Body:
Pyth - 9 bytes

+j\(Qsm\)

Try it online here.


答:
><>, <s>19</s> 18 bytes

```<code>io8i:&0(.')('o&!
o
</code>```

Try it online!

Explanation

The first line is an input loop which prints everything up to the last character of the input (including all the () and leaves the right amount of ) on the stack:

```<code>io                 Read and print the first character.
  8                Push an 8 (the x-coordinate of the . in the program).
   i               Read a character. Pushes -1 at EOF.
    :&             Put a copy in the register.
      0(           Check if negative. Gives 1 at EOF, 0 otherwise.
        .          Jump to (8, EOF?). As long as we're not at EOF, this is
                   a no-op (apart from popping the two coordinates). At EOF
                   it takes us to the second line.
         ')('      Push both characters.
             o     Output the '('.
              &    Push the input character from the register.
               !   Skip the 'i' at the beginning of the line, so that the next
                   iteration starts with 'o', printing the last character.
</code>```

Once we hit EOF, the instruction pointer ends up on the second line and we'll simply execute o in a loop, printing all the ), until the stack is empty and the program errors out.

Title: N(e(s(t))) a string

Body:
><>, <s>19</s> 18 bytes

io8i:&0(.')('o&!
o

Try it online!

Explanation

The first line is an input loop which prints everything up to the last character of the input (including all the () and leaves the right amount of ) on the stack:

io                 Read and print the first character.
  8                Push an 8 (the x-coordinate of the . in the program).
   i               Read a character. Pushes -1 at EOF.
    :&             Put a copy in the register.
      0(           Check if negative. Gives 1 at EOF, 0 otherwise.
        .          Jump to (8, EOF?). As long as we're not at EOF, this is
                   a no-op (apart from popping the two coordinates). At EOF
                   it takes us to the second line.
         ')('      Push both characters.
             o     Output the '('.
              &    Push the input character from the register.
               !   Skip the 'i' at the beginning of the line, so that the next
                   iteration starts with 'o', printing the last character.

Once we hit EOF, the instruction pointer ends up on the second line and we'll simply execute o in a loop, printing all the ), until the stack is empty and the program errors out.


答:
Perl 5, 27 bytes (25 + 1 for -l + 1 for -n)

This is a translation of Wheat Wizard's approach to Perl.

```<code>say$_.")"x s/.(?!$)/$&(/g
</code>```

Run it like this:

```<code>perl -nlE 'say$_.")"x s/.(?!$)/$&(/g' <<< 'Hello'
</code>```

Explanation:

```<code>say$_.")"x s/.(?!$)/$&(/g
           s/.(?!$)/   /g # replace every char not followed by end of string ...
                    $&    # ... with the full match (that's the one char)
                       (  # and an open parenthesis
           s/.(?!$)/$&(/g # this operates on and changes $_ and ...
                          # ... returns the number of substitutes
      ")"x                # repeat closing paren number of substitues times
     .                    # append
   $_                     # to the string that has already been changed to f(o(o
say                       # print with newline
</code>```

Title: N(e(s(t))) a string

Body:
Perl 5, 27 bytes (25 + 1 for -l + 1 for -n)

This is a translation of Wheat Wizard's approach to Perl.

say$_.")"x s/.(?!$)/$&(/g

Run it like this:

perl -nlE 'say$_.")"x s/.(?!$)/$&(/g' <<< 'Hello'

Explanation:

say$_.")"x s/.(?!$)/$&(/g
           s/.(?!$)/   /g # replace every char not followed by end of string ...
                    $&    # ... with the full match (that's the one char)
                       (  # and an open parenthesis
           s/.(?!$)/$&(/g # this operates on and changes $_ and ...
                          # ... returns the number of substitutes
      ")"x                # repeat closing paren number of substitues times
     .                    # append
   $_                     # to the string that has already been changed to f(o(o
say                       # print with newline


问:
Calculate A190810
Your task is pretty simple, calculate the n-th element of A190810.

Elements of A190810 are calculated according to these rules:

The first element is 1

The sequence is increasing

If x occurs in the sequence, then 2x+1 and 3x-1 also do

You can use 1-based or 0-based indexing, but if you use 0-based indexing, please say it in the answer.

Test cases

```<code>a(1) = 1
a(2) = 2
a(3) = 3
a(4) = 5
a(5) = 7
a(10) = 17
a(20) = 50
a(30) = 95
a(55) = 255
</code>```

Since this is code-golf, the shortest answer in bytes wins!

答:
Perl, <s>173</s> 132 bytes +1 for -n = 133

```<code>sub c{my$a=pop;return($a==1||($a%2&&c(($a-1)/2))?1:$a%3!=2?0:$a%3==2?c(($a+1)/3):1)}while($#b<$_){$i++;@b=(@b,$i)if c$i}say$b[$_-1];
</code>```

Ungolfed:

```<code>my @array = ();
my $n = <>;
sub chk {
    my $a = shift;
    return 1 if ($a == 1);
    if ($a % 2 == 0) {
        if ($a % 3 != 2) {
            return 0;
        } else {
            return chk(($a + 1) / 3);
        }
    } else {
        if (chk(($a - 1) / 2) == 0) {
            if ($a % 3 != 2) {
                return 0;
            } else {
                return chk(($a + 1) / 3);
            }
        } else {
            return 1
        }
    }
}
my $i = 1;
while ($#array < $n-1) {
    push(@array,$i) if (chk($i) == 1);
    $i++;
}
print $array[$n];
</code>```

I can probably do better if I thought more about it, but this is what I came up with after just a few minutes.  My first time golfing, so this was pretty fun!

Thanks to @Dada and @TùxCräftîñg (and a bunch of minor byte-optimizations) for -40 bytes

Title: Calculate A190810

Body:
Perl, <s>173</s> 132 bytes +1 for -n = 133

sub c{my$a=pop;return($a==1||($a%2&&c(($a-1)/2))?1:$a%3!=2?0:$a%3==2?c(($a+1)/3):1)}while($#b<$_){$i++;@b=(@b,$i)if c$i}say$b[$_-1];

Ungolfed:

my @array = ();
my $n = <>;
sub chk {
    my $a = shift;
    return 1 if ($a == 1);
    if ($a % 2 == 0) {
        if ($a % 3 != 2) {
            return 0;
        } else {
            return chk(($a + 1) / 3);
        }
    } else {
        if (chk(($a - 1) / 2) == 0) {
            if ($a % 3 != 2) {
                return 0;
            } else {
                return chk(($a + 1) / 3);
            }
        } else {
            return 1
        }
    }
}
my $i = 1;
while ($#array < $n-1) {
    push(@array,$i) if (chk($i) == 1);
    $i++;
}
print $array[$n];

I can probably do better if I thought more about it, but this is what I came up with after just a few minutes.  My first time golfing, so this was pretty fun!

Thanks to @Dada and @TùxCräftîñg (and a bunch of minor byte-optimizations) for -40 bytes


答:
MATL, 14 bytes

```<code>'%%%dd'inYDGYD
</code>```

Try it out at MATL Online

This uses formatted string creation by first constructing the format string: %(NUM)d and then applies string formatting again using this format string and the input.

Title: Spaced-out numbers

Body:
Given a list of N non-negative integers, output those numbers with each left-padded by spaces to a length of N. (Alternatively, return a character/string list.) You may assume that N is greater than or equal to the number of digits of the largest number in the list. Trailing spaces are allowed in the output.

You may also take a string containing these numbers, but N is not the length of the string, but rather the number of elements in the list; also, you may take a list of strings e.g. ["1", "2", "3"].

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

Test cases

```<code>input => 'output'
0 => '0'
1 => '1'
2 3 => ' 2 3'
2 10 => ' 210'
4 5 6 => '  4  5  6'
17 19 20 => ' 17 19 20'
7 8 9 10 => '   7   8   9  10'
100 200 300 0 => ' 100 200 300   0'
1000 400 30 7 => '1000 400  30   7'
1 33 333 7777 => '   1  33 3337777'
0 0 0 0 0 0 => '     0     0     0     0     0     0'
</code>```

Body:
MATL, 14 bytes

'%%%dd'inYDGYD

Try it out at MATL Online

This uses formatted string creation by first constructing the format string: %(NUM)d and then applies string formatting again using this format string and the input.

ContentLicense: CC BY-SA 4.0


答:
Pyke, 9 bytes

```<code>\(JQl\)*+
</code>```

Try it here!

Title: N(e(s(t))) a string

Body:
Pyke, 9 bytes

\(JQl\)*+

Try it here!


问:
Nest a string inside an array n times
You must produce a function which nests a string s inside an array, n times

```<code>>>> N("stackoverflow",2)
[['stackoverflow']]
</code>```

Parameters:

s - An ascii string

n - An integer >= 0

Rules

Shortest code wins.

The output will be a nested array, list or tuple (or similar type based off an array)

Test Cases

```<code>>>> N("stackoverflow",0)
'stackoverflow'
>>> N("stackoverflow",1)
['stackoverflow']
>>> N("stackoverflow",5)
[[[[['stackoverflow']]]]]
</code>```

Inspired by: Nesting a string inside a list n times ie list of a list of a list

答:
Haskell, 41 bytes

Actually, it can be done with Haskell's standard list type. Here is how:

```<code>n?s|m<-([1..n]>>)=read$m"["++show s++m"]"
</code>```

m is a local helper function that repeats a string n times. It is used in ? to prepend n [ and append n ] to the result of show s, which for a string s is that string surrounded by quotation marks and with its possible own quotation marks escaped. This is then parsed by read which tries to return the type at which the result is used. The infered type of ? is (Enum a2, Num a2, Read a, Show a1) => a2 -> a1 -> a. It could be specialized by setting a1 to String and a2 to Integer or Int, removing all but one of the constraints. But of course it is golfier to let the compiler infer a complicated type than to explicitely state a simple one.

Now simply calling the function in the interpreter gives an ambigous type variable error, but we can state the expected type or use the value in a way that gives enough information to infer the type:

```<code>Prelude> 2 ? "codegolf" :: [[String]]
[["codegolf"]]
Prelude> putStrLn $ 2 ? "hi" !! 0 !! 0
hi
Prelude> [[["test"]]] ++  (3 ? "hi")
[[["test"]],[["hi"]]]
Prelude> map(map("a":)) $  [2 ? "x" ++ 2 ? "y"] ++ 3 ? "z"
[[["a","x"],["a","y"]],[["a","z"]]]
Prelude> let x=(2 ? "golf") in (x,"code"++x!!0!!0)
([["golf"]],"codegolf")
Prelude> 0 ? "hi" ++ "!"
"hi!"
</code>```

There is no reason to only use strings:

```<code>Prelude> map(map not) $ 2 ? False
[[True]]
</code>```

Title: Nest a string inside an array n times

Body:
Haskell, 41 bytes

Actually, it can be done with Haskell's standard list type. Here is how:

n?s|m<-([1..n]>>)=read$m"["++show s++m"]"

m is a local helper function that repeats a string n times. It is used in ? to prepend n [ and append n ] to the result of show s, which for a string s is that string surrounded by quotation marks and with its possible own quotation marks escaped. This is then parsed by read which tries to return the type at which the result is used. The infered type of ? is (Enum a2, Num a2, Read a, Show a1) => a2 -> a1 -> a. It could be specialized by setting a1 to String and a2 to Integer or Int, removing all but one of the constraints. But of course it is golfier to let the compiler infer a complicated type than to explicitely state a simple one.

Now simply calling the function in the interpreter gives an ambigous type variable error, but we can state the expected type or use the value in a way that gives enough information to infer the type:

Prelude> 2 ? "codegolf" :: [[String]]
[["codegolf"]]
Prelude> putStrLn $ 2 ? "hi" !! 0 !! 0
hi
Prelude> [[["test"]]] ++  (3 ? "hi")
[[["test"]],[["hi"]]]
Prelude> map(map("a":)) $  [2 ? "x" ++ 2 ? "y"] ++ 3 ? "z"
[[["a","x"],["a","y"]],[["a","z"]]]
Prelude> let x=(2 ? "golf") in (x,"code"++x!!0!!0)
([["golf"]],"codegolf")
Prelude> 0 ? "hi" ++ "!"
"hi!"

There is no reason to only use strings:

Prelude> map(map not) $ 2 ? False
[[True]]


问:
String Calculator
Assume you're writing in one method, (or whatever you call them) with 3 inputs: the first string, a character that contains a +, - or * symbol, and the second string.

Example in Java:

```<code>public String strCalc(String str1, char sym, String str2) {
    //code...
}
</code>```

What it should return:

```<code>str1 sym str2 ans
A     +  A   =  B
A     +  B   =  C
B     +  B   =  D
Z     +  A   =  AA
W     +  B   =  Y
A     -  A   =  ' ' (Space Character)
A     -  B   =  -A
A     -  C   =  -B
B     -  A   =  A
CA    -  A   =  BZ
A     *  A   =  A
B     *  B   =  D
</code>```

Think of a one-indexed base 26.
Then convert the numbers back to letters based on their position in the alphabet.

```<code>0 = ' ' (Space Character)
1 = A
2 = B
3 = C
4 = D
5 = E
6 = F
7 = G
8 = H
9 = I
10 = J
11 = K
and so on...
</code>```

This is code-golf, so the shortest code in bytes not including the method declaration wins.

答:
Assembler x86 (32-bit) - 142 bytes

The 142 bytes are the compiled size (not the source code size, which is larger). Note that for assembler the size of the compiled code is not dependend on the compiler used but it should always be 142 bytes.

The calling convention is "_cdecl" so you can call the function from C:

```<code>const char *strCalc(const char *num1,
    char operation, const char *num2, char *bufferEnd);
</code>```

The function accepts negative inputs (such as "-AB") and zero (" "). However malformed inputs might crash the program!

The last argument points to the LAST byte of a buffer used to store the sring because C does not support strings without pre-allocated buffers.

The function returns the pointer to the string (somewhere in the buffer). The function may be called the following way:

```<code>#include <stdio.h>

const char *strCalc(const char *num1, char operation, const char *num2, char *bufferEnd);

main(int argc,char **argv)
{
    char buf[21];
    puts(strCalc(argv[1],argv[2][0],argv[3],buf+20));
}
</code>```

Here is the actual function (Linux users: Replace "_strCalc" by "strCalc"):

```<code>    .globl _strCalc
    .text
_strCalc:
    push %ebx
    push %esi
    push %edi
    mov 16(%esp), %esi
    call loadNum
    push %ebx
    mov 28(%esp), %esi
    call loadNum
    pop %eax
    # This assumes that the operation is ONLY +, * or -!
    cmpb $0x2B, 20(%esp)
    je isPlus
    jb isMultiply
    sub %ebx, %eax
    jmp calcDone
isPlus:
    add %ebx, %eax
    jmp calcDone
isMultiply:
    xor %edx, %edx
    imul %ebx
calcDone:
    push %eax
    mov 32(%esp), %edi
    std
    xor %al, %al
    stosb
    pop %eax
    call writeOut
    mov %al, (%edi)
    mov %edi, %eax
    inc %eax
    pop %edi
    pop %esi
    pop %ebx
    # Needed due to MSVCRT.DLL bug!
    cld
    ret

    # Write EAX to the buffer
    # EDI points to the last character to be
    # written (the terminating NUL has already been written)
    # Returns: EDI pointer to the first character!
writeOut:
    test %eax, %eax
    jnz notZero
    mov $0x20, %al
    stosb
    ret
notZero:
    jns notNegative
    neg %eax
    call writeOut
    mov $0x2D,%al
    stosb
    ret
notNegative:
    xor %edx, %edx
    dec %eax
    div %ecx
    xchg %al, %dl
    add $0x41, %al
    stosb
    xchg %al, %dl
    test %eax, %eax
    jnz notNegative
    xchg %al, %dl
    ret

    # Load number from string ESI points to to EBX
    # Destroys EAX, ECX, EDX
    # Allows negative and zero inputs!
    # Assumes syntactically correct numbers!
    # Sets ECX to 26 (needed later!)
loadNum:
    xor %ebx, %ebx
    xor %eax, %eax
    mov $26, %al
    mov %eax, %ecx
nextLoad:
    cld
    lodsb
    and $0xDF, %al
    jz endOfLoad
    sub $0x40, %al
    jc negativeInput
    xchg %eax, %ebx
    mul %ecx
    add %eax, %ebx
    jmp nextLoad
negativeInput:
    call loadNum
    neg %ebx
endOfLoad:
    ret
</code>```

Title: String Calculator

Body:
Assembler x86 (32-bit) - 142 bytes

The 142 bytes are the compiled size (not the source code size, which is larger). Note that for assembler the size of the compiled code is not dependend on the compiler used but it should always be 142 bytes.

The calling convention is "_cdecl" so you can call the function from C:

const char *strCalc(const char *num1,
    char operation, const char *num2, char *bufferEnd);

The function accepts negative inputs (such as "-AB") and zero (" "). However malformed inputs might crash the program!

The last argument points to the LAST byte of a buffer used to store the sring because C does not support strings without pre-allocated buffers.

The function returns the pointer to the string (somewhere in the buffer). The function may be called the following way:

#include <stdio.h>

const char *strCalc(const char *num1, char operation, const char *num2, char *bufferEnd);

main(int argc,char **argv)
{
    char buf[21];
    puts(strCalc(argv[1],argv[2][0],argv[3],buf+20));
}

Here is the actual function (Linux users: Replace "_strCalc" by "strCalc"):

    .globl _strCalc
    .text
_strCalc:
    push %ebx
    push %esi
    push %edi
    mov 16(%esp), %esi
    call loadNum
    push %ebx
    mov 28(%esp), %esi
    call loadNum
    pop %eax
    # This assumes that the operation is ONLY +, * or -!
    cmpb $0x2B, 20(%esp)
    je isPlus
    jb isMultiply
    sub %ebx, %eax
    jmp calcDone
isPlus:
    add %ebx, %eax
    jmp calcDone
isMultiply:
    xor %edx, %edx
    imul %ebx
calcDone:
    push %eax
    mov 32(%esp), %edi
    std
    xor %al, %al
    stosb
    pop %eax
    call writeOut
    mov %al, (%edi)
    mov %edi, %eax
    inc %eax
    pop %edi
    pop %esi
    pop %ebx
    # Needed due to MSVCRT.DLL bug!
    cld
    ret

    # Write EAX to the buffer
    # EDI points to the last character to be
    # written (the terminating NUL has already been written)
    # Returns: EDI pointer to the first character!
writeOut:
    test %eax, %eax
    jnz notZero
    mov $0x20, %al
    stosb
    ret
notZero:
    jns notNegative
    neg %eax
    call writeOut
    mov $0x2D,%al
    stosb
    ret
notNegative:
    xor %edx, %edx
    dec %eax
    div %ecx
    xchg %al, %dl
    add $0x41, %al
    stosb
    xchg %al, %dl
    test %eax, %eax
    jnz notNegative
    xchg %al, %dl
    ret

    # Load number from string ESI points to to EBX
    # Destroys EAX, ECX, EDX
    # Allows negative and zero inputs!
    # Assumes syntactically correct numbers!
    # Sets ECX to 26 (needed later!)
loadNum:
    xor %ebx, %ebx
    xor %eax, %eax
    mov $26, %al
    mov %eax, %ecx
nextLoad:
    cld
    lodsb
    and $0xDF, %al
    jz endOfLoad
    sub $0x40, %al
    jc negativeInput
    xchg %eax, %ebx
    mul %ecx
    add %eax, %ebx
    jmp nextLoad
negativeInput:
    call loadNum
    neg %ebx
endOfLoad:
    ret


问:
Real Chebyshev Rotation
This is a challenge inspired by Chebyshev Rotation. I suggest looking at answers there to get inspiration for this challenge.

Given a point on the plane there is a unique square (a rectangle with equal sides) that is centered on the origin and intersects that point (interactive demo):

Given a point p and a distance d, return the point obtained by moving distance d from p, counter-clockwise (and clockwise for negative  d), along the perimeter of the square centered on the origin that intersects p. Your answer must be accurate to at least 4 decimal digits.

Testcases:

```<code>(0, 0), 100 -> (0, 0)
(1, 1), 81.42 -> (-0.4200, 1.0000)
(42.234, 234.12), 2303.34 -> (-234.1200, 80.0940)
(-23, -39.234), -234.3 -> (39.2340, -21.8960)
</code>```

The following test cases are from the original challenge by Martin Ender, and all are with d = 1:

```<code>(0, 0)       -> (0, 0)
(1, 0)       -> (1, 1)
(1, 1)       -> (0, 1)
(0, 1)       -> (-1, 1)
(-1, 1)      -> (-1, 0)
(-1, 0)      -> (-1, -1)
(-1, -1)     -> (0, -1)
(0, -1)      -> (1, -1)
(1, -1)      -> (1, 0)
(95, -12)    -> (95, -11)
(127, 127)   -> (126, 127)
(-2, 101)    -> (-3, 101)
(-65, 65)    -> (-65, 64)
(-127, 42)   -> (-127, 41)
(-9, -9)     -> (-8, -9)
(126, -127)  -> (127, -127)
(105, -105)  -> (105, -104)
</code>```

答:
JavaScript (ES6), 147 bytes

```<code>f=(x,y,d,s=Math.max(x,y,-x,-y),c=(d/8%s+s)%s*8,v=0,w=x+y>0?1:-1,b=(v?x:y)*w+c-s)=>c?b>0?f(v?s*w:x,v?y:s*w,d,s,b,!v,v?w:-w):[x+c*w*v,y+c*w*!v]:[x,y]
</code>```

Explanation: Works by trying to add the direction vector while keeping within the bounds of the square. Any overshoot is recursively passed back with the direction rotated anticlockwise by 90°. The direction is actually encoded using a vertical flag v and a unit w so that the vectors (1, 0), (0, 1), (-1, 0) and (0, -1) are encoded with v of 0, 1, 0, 1 and w of 1, 1, -1, -1 respectively. The direction vector may not initially point in a suitable direction but it never points backwards so it will eventually rotate into a usable direction.

```<code>f=(x,y,d,                   Input parameters
 s=Math.max(x,y,-x,-y),     Calculate half the side of the square
 c=(d/8%s+s)%s*8,           Reduce the distance modulo the perimeter
 v=0,                       Initial vertical flag
 w=x+y>0?1:-1,              Initial direction
 b=(v?x:y)*w+c-s)=>         Will we overshoot the corner?
  c?b>0?f(v?s*w:x,v?y:s*w,  Advance to the next corner
          d,s,b,!v,v?w:-w): Rotate the direction
        [x+c*w*v,y+c*w*!v]: Advance the remaining amout
    [x,y]                   Nothing to do, zero input
</code>```

Title: Real Chebyshev Rotation

Body:
JavaScript (ES6), 147 bytes

f=(x,y,d,s=Math.max(x,y,-x,-y),c=(d/8%s+s)%s*8,v=0,w=x+y>0?1:-1,b=(v?x:y)*w+c-s)=>c?b>0?f(v?s*w:x,v?y:s*w,d,s,b,!v,v?w:-w):[x+c*w*v,y+c*w*!v]:[x,y]

Explanation: Works by trying to add the direction vector while keeping within the bounds of the square. Any overshoot is recursively passed back with the direction rotated anticlockwise by 90°. The direction is actually encoded using a vertical flag v and a unit w so that the vectors (1, 0), (0, 1), (-1, 0) and (0, -1) are encoded with v of 0, 1, 0, 1 and w of 1, 1, -1, -1 respectively. The direction vector may not initially point in a suitable direction but it never points backwards so it will eventually rotate into a usable direction.

f=(x,y,d,                   Input parameters
 s=Math.max(x,y,-x,-y),     Calculate half the side of the square
 c=(d/8%s+s)%s*8,           Reduce the distance modulo the perimeter
 v=0,                       Initial vertical flag
 w=x+y>0?1:-1,              Initial direction
 b=(v?x:y)*w+c-s)=>         Will we overshoot the corner?
  c?b>0?f(v?s*w:x,v?y:s*w,  Advance to the next corner
          d,s,b,!v,v?w:-w): Rotate the direction
        [x+c*w*v,y+c*w*!v]: Advance the remaining amout
    [x,y]                   Nothing to do, zero input


答:
Mathematica, <s>45</s> 43 bytes

```<code>#2<>"("<>#<>")"&~Fold~Reverse@Characters@#&
</code>```

Title: N(e(s(t))) a string

Body:
Mathematica, <s>45</s> 43 bytes

#2<>"("<>#<>")"&~Fold~Reverse@Characters@#&


问:
Tips for Golfing in ECMAScript 6 and above
This is similar to other "Tips for golfing in <...>" but specifically targeting the newer features in JavaScript brought up in ECMAScript 6 and above.

JavaScript inherently is a very verbose language, function(){}, .forEach(), converting string to array, array-like object to array, etc, etc are super bloats and not healthy for Golfing.

ES6+, on the other hand, has some super handy features and reduced footprint. x=>y, [...x], etc. are just some of the examples.

Please post some nice tricks that can help shave off those few extra bytes from your code.

NOTE: Tricks for ES5 are already available in Tips for golfing in JavaScript; answers to this thread should focus on tricks only available in ES6 and other future ES versions.

However, this thread is also for users who currently golf using ES5 features. Answers may also contain tips to help them understand and map ES6 features to their style of ES5 coding.

答:
Destructuring assignments

ES6 introduces new syntax for destructuring assignments, i.e. cutting a value into pieces and assigning each piece to a different variable. Here are a few examples:

Strings and arrays

```<code>a=s[0];b=s[1];       // 14 bytes
[a,b]=s;             //  8 bytes

a=s[0];s=s.slice(1); // 20 bytes
a=s.shift();         // 12 bytes, only works if s is an array
[a,...s]=s;          // 11 bytes, converts s to an array
</code>```

Objects

```<code>a=o.asdf;b=o.bye;c=o.length; // 28 bytes
{asdf:a,bye:b,length:c}=o;   // 26 bytes

a=o.a;b=o.b;c=o.c; // 18 bytes
{a,b,c}=o;         // 10 bytes
</code>```

These assignments can also be used in function parameters:

```<code>f=a=>a[0]+a[1]+a[2]
f=([a,b,c])=>a+b+c

f=b=>b[1]?b[0]+f(b.slice(1)):b[0]*2
f=b=>b[1]?b.shift()+f(b):b[0]*2
f=([a,...b])=>b[0]?a+f(b):a*2
</code>```

Body:
Destructuring assignments

ES6 introduces new syntax for destructuring assignments, i.e. cutting a value into pieces and assigning each piece to a different variable. Here are a few examples:

Strings and arrays

a=s[0];b=s[1];       // 14 bytes
[a,b]=s;             //  8 bytes

a=s[0];s=s.slice(1); // 20 bytes
a=s.shift();         // 12 bytes, only works if s is an array
[a,...s]=s;          // 11 bytes, converts s to an array

Objects

a=o.asdf;b=o.bye;c=o.length; // 28 bytes
{asdf:a,bye:b,length:c}=o;   // 26 bytes

a=o.a;b=o.b;c=o.c; // 18 bytes
{a,b,c}=o;         // 10 bytes

These assignments can also be used in function parameters:

f=a=>a[0]+a[1]+a[2]
f=([a,b,c])=>a+b+c

f=b=>b[1]?b[0]+f(b.slice(1)):b[0]*2
f=b=>b[1]?b.shift()+f(b):b[0]*2
f=([a,...b])=>b[0]?a+f(b):a*2


问:
(KevinC's) Triangular DeciDigits Sequence
Input:

A positive integer n which is 1 <= n <= 25000.

Output:

In this sequence we start with the decimal number 1/n.

Then we take the sum of digits up until the n'th digit after the comma (1-indexed); followed by the sum of digits up until the (n-1)'th, then (n-2)'th, etc. Continue until n is 1.

The output is the sum of all these combined.

For example:

```<code>n = 7
1/7 = 0.1428571428...
7th digit-sum = 1+4+2+8+5+7+1 = 28
6th digit-sum = 1+4+2+8+5+7 = 27
5th digit-sum = 1+4+2+8+5 = 20
4th digit-sum = 1+4+2+8 = 15
3rd digit-sum = 1+4+2 = 7
2nd digit-sum = 1+4 = 5
1st digit     = 1
Output = 28+27+20+15+7+5+1 = 103
</code>```

Challenge rules:

If the decimal of 1/n doesn't have n digits after the comma, the missing ones will be counted as 0 (i.e. 1/2 = 0.50 => (5+0) + (5) = 10).

You take the digits without rounding (i.e. the digits of 1/6 are 166666 and not 166667)

General rules:

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

First 1 - 50 in the sequence:

```<code>0, 10, 18, 23, 10, 96, 103, 52, 45, 10, 270, 253, 402, 403, 630, 183, 660, 765, 819, 95, 975, 1034, 1221, 1500, 96, 1479, 1197, 1658, 1953, 1305, 1674, 321, 816, 2490, 2704, 4235, 2022, 3242, 2295, 268, 2944, 3787, 3874, 4097, 1980, 4380, 4968, 3424, 4854, 98
</code>```

Last 24990 - 25000 in the sequence:

```<code>1405098782, 1417995426, 1364392256, 1404501980, 1408005544, 1377273489, 1395684561, 1405849947, 1406216741, 1142066735, 99984
</code>```

Body:
C, 53 bytes

f(n,i,x,s){while(i)x=10*(x%n),s+=i--*(x/n);return s;}

Below the main for to do some test...

//44,79
#define R return
#define F for
#define U unsigned
#define N int
#define B break
#define I if
#define L(i) for(;i-->0;)
#define J(a,b)  if(a)goto b
#define G goto
#define P printf
#define D double
#define C unsigned char
#define A getchar()
#define O putchar
#define M main
#define Y malloc
#define Z free
#define S sizeof
#define T struct
#define E else
#define Q static
#define X continue
main()
{N  k, a=0, b=0, i;

 F(i=1;i<50;++i)
       P("f(%u)=%u |", i, f(i,i,1,0));
 P("\n");
 F(i=24990;i<=25000;++i)
       P("f(%u)=%u |", i, f(i,i,1,0));
 P("\n");
 R 0;
}

/*
f(1)=0 |f(2)=10 |f(3)=18 |f(4)=23 |f(5)=10 |f(6)=96 |f(7)=103 |f(8)=52 |f(9)=45
f(10)=10 |f(11)=270 |f(12)=253 |f(13)=402 |f(14)=403 |f(15)=630 |f(16)=183 |f(17)=660
f(18)=765 |f(19)=819 |f(20)=95 |f(21)=975 |f(22)=1034 |f(23)=1221 |f(24)=1500
f(25)=96 |f(26)=1479 |f(27)=1197 |f(28)=1658 |f(29)=1953 |f(30)=1305 |f(31)=1674
f(32)=321 |f(33)=816 |f(34)=2490 |f(35)=2704 |f(36)=4235 |f(37)=2022 |f(38)=3242
f(39)=2295 |f(40)=268 |f(41)=2944 |f(42)=3787 |f(43)=3874 |f(44)=4097 |f(45)=1980
f(46)=4380 |f(47)=4968 |f(48)=3424 |f(49)=4854 |
f(24990)=1405098782 |f(24991)=1417995426 |f(24992)=1364392256 |f(24993)=1404501980
f(24994)=1408005544 |f(24995)=1377273489 |f(24996)=1395684561 |f(24997)=1405849947
f(24998)=1406216741 |f(24999)=1142066735 |f(25000)=99984
*/