问:
Letter-replacement challenge
The idea is simple. You've to create a "visualised" letter-replacement, by providing 3 strings (input can be comma separated, separate inputs, or as an array). The first segment is the word you want to correct, and the second segment is the letters you want to replace, and the third segment is the replacement for the letters in segment 2.

For example:

```<code>|    | Input                       | Starting Word | Output      |
|----|-----------------------------|---------------|-------------|
| #1 | Hello world -wo -ld +Ea +th | Hello world   | Hello Earth |
| #2 | Hello World -wo -ld +Ea +th | Hello World   | Hello Worth |
| #3 | Hello -llo +y               | Hello         | Hey         |
| #4 | Red -R -d +Gr +en           | Red           | Green       |
| #5 | mississippi -is -i +lz +p   | mississippi   | mlzslzspppp |
| #6 | Football -o -a +a +i        | Football      | Fiitbill    |
| #7 | mississippi -is -i +iz +p   | mississippi   | mpzspzspppp |
</code>```

Explanation

The replacements are to be done step-by-step with their respective pair. Here's an illustration with an input of mississippi -is -i +iz +p to give the output mpzspzsppp (see example #7 above)

```<code>| Step  | Input                         | Output        |
|------ |---------------------------    |-------------  |
| #1    | mississippi -is -i +iz +p     |               |
| #2    | mississippi -is +iz           | mizsizsippi   |
| #3    | mizsizsippi -i +p             | mpzspzspppp   |
</code>```

Rules

Inputs are always in this order <starting_string> <list_of_letters_to_replace> <replacement_letters>.

Letters to replace and replacement groups will never be mixed (ie: there will never be -a +i -e +o).

Letters to replace are always prefixed with - and replacement letters are always prefixed with +. (The prefix is mandatory)

There may be more than one set of letters to replace, so you'd need to look at the prefix.

Assume the amount of letter groups to replace and the amount of replacement letter groups are always equal (ie: there will never be -a -e +i)

Replacements are case-sensitive (see example #1 and #2).

Replacements are done in the order they were given in the input.

Letter replacements can be replaced with other replacements. See example #6.

The first segment (starting word) will never include - or + characters.

This is code-golf so shortest bytes win.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by 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=96473,OVERRIDE_USER=38505;function answersUrl(e){return"http://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"http://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

```

答:
JavaScript (ES6), <s>85</s> 83 bytes

```<code>f=(s,n=1,l=s.split(/ \W/))=>(r=l[n+l.length/2|0])?f(s.split(l[n]).join(r),n+1):l[0]
</code>```

Test cases

f=(s,n=1,l=s.split(/ \W/))=>(r=l[n+l.length/2|0])?f(s.split(l[n]).join(r),n+1):l[0]

console.log(f("Hello world -wo -ld +Ea +th"));
console.log(f("Hello World -wo -ld +Ea +th"));
console.log(f("Hello -llo +y"));
console.log(f("Red -R -d +Gr +en"));
console.log(f("mississippi -is -i +lz +p"));
console.log(f("Football -o -a +a +i"));
console.log(f("mississippi -is -i +iz +p"));```

Title: Letter-replacement challenge

Body:
JavaScript (ES6), <s>85</s> 83 bytes

f=(s,n=1,l=s.split(/ \W/))=>(r=l[n+l.length/2|0])?f(s.split(l[n]).join(r),n+1):l[0]

Test cases

f=(s,n=1,l=s.split(/ \W/))=>(r=l[n+l.length/2|0])?f(s.split(l[n]).join(r),n+1):l[0]

console.log(f("Hello world -wo -ld +Ea +th"));
console.log(f("Hello World -wo -ld +Ea +th"));
console.log(f("Hello -llo +y"));
console.log(f("Red -R -d +Gr +en"));
console.log(f("mississippi -is -i +lz +p"));
console.log(f("Football -o -a +a +i"));
console.log(f("mississippi -is -i +iz +p"));


答:
Java 7, <s>153</s> 133 bytes

```<code>String c(String[]a){String r=a[0],z[]=a[1].split(" ?-");for(int i=0;i<z.length;r=r.replace(z[i],a[2].split(" ?[+]")[i++]));return r;}
</code>```

Ungolfed & test code:

Try it here.

```<code>class M{
  static String c(String[] a){
    String r = a[0],
           z[] = a[1].split(" ?-");
    for(int i = 0; i < z.length; r = r.replace(z[i], a[2].split(" ?[+]")[i++]));
    return r;
  }

  public static void main(String[] a){
    System.out.println(c(new String[]{ "Hello world", "-wo -ld", "+Ea +th" }));
    System.out.println(c(new String[]{ "Hello World", "-wo -ld", "+Ea +th" }));
    System.out.println(c(new String[]{ "Hello", "-llo", "+y" }));
    System.out.println(c(new String[]{ "Red", "-R -d", "+Gr +en" }));
    System.out.println(c(new String[]{ "mississippi", "-is -i", "+lz +p" }));
    System.out.println(c(new String[]{ "Football", "-o -a", "+a +i" }));
    System.out.println(c(new String[]{ "mississippi", "-is -i", "+iz +p" }));
  }
}
</code>```

Output:

```<code>Hello Earth
Hello Worth
Hey
Green
mlzslzspppp
Fiitbill
mpzspzspppp
</code>```

ContentLicense: CC BY-SA 3.0

Title: Letter-replacement challenge

Body:
The idea is simple. You've to create a "visualised" letter-replacement, by providing 3 strings (input can be comma separated, separate inputs, or as an array). The first segment is the word you want to correct, and the second segment is the letters you want to replace, and the third segment is the replacement for the letters in segment 2.

For example:

```<code>|    | Input                       | Starting Word | Output      |
|----|-----------------------------|---------------|-------------|
| #1 | Hello world -wo -ld +Ea +th | Hello world   | Hello Earth |
| #2 | Hello World -wo -ld +Ea +th | Hello World   | Hello Worth |
| #3 | Hello -llo +y               | Hello         | Hey         |
| #4 | Red -R -d +Gr +en           | Red           | Green       |
| #5 | mississippi -is -i +lz +p   | mississippi   | mlzslzspppp |
| #6 | Football -o -a +a +i        | Football      | Fiitbill    |
| #7 | mississippi -is -i +iz +p   | mississippi   | mpzspzspppp |
</code>```

Explanation

The replacements are to be done step-by-step with their respective pair. Here's an illustration with an input of mississippi -is -i +iz +p to give the output mpzspzsppp (see example #7 above)

```<code>| Step  | Input                         | Output        |
|------ |---------------------------    |-------------  |
| #1    | mississippi -is -i +iz +p     |               |
| #2    | mississippi -is +iz           | mizsizsippi   |
| #3    | mizsizsippi -i +p             | mpzspzspppp   |
</code>```

Rules

Inputs are always in this order <starting_string> <list_of_letters_to_replace> <replacement_letters>.

Letters to replace and replacement groups will never be mixed (ie: there will never be -a +i -e +o).

Letters to replace are always prefixed with - and replacement letters are always prefixed with +. (The prefix is mandatory)

There may be more than one set of letters to replace, so you'd need to look at the prefix.

Assume the amount of letter groups to replace and the amount of replacement letter groups are always equal (ie: there will never be -a -e +i)

Replacements are case-sensitive (see example #1 and #2).

Replacements are done in the order they were given in the input.

Letter replacements can be replaced with other replacements. See example #6.

The first segment (starting word) will never include - or + characters.

This is code-golf so shortest bytes win.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by 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=96473,OVERRIDE_USER=38505;function answersUrl(e){return"http://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"http://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 7, <s>153</s> 133 bytes

String c(String[]a){String r=a[0],z[]=a[1].split(" ?-");for(int i=0;i<z.length;r=r.replace(z[i],a[2].split(" ?[+]")[i++]));return r;}

Ungolfed & test code:

Try it here.

class M{
  static String c(String[] a){
    String r = a[0],
           z[] = a[1].split(" ?-");
    for(int i = 0; i < z.length; r = r.replace(z[i], a[2].split(" ?[+]")[i++]));
    return r;
  }

  public static void main(String[] a){
    System.out.println(c(new String[]{ "Hello world", "-wo -ld", "+Ea +th" }));
    System.out.println(c(new String[]{ "Hello World", "-wo -ld", "+Ea +th" }));
    System.out.println(c(new String[]{ "Hello", "-llo", "+y" }));
    System.out.println(c(new String[]{ "Red", "-R -d", "+Gr +en" }));
    System.out.println(c(new String[]{ "mississippi", "-is -i", "+lz +p" }));
    System.out.println(c(new String[]{ "Football", "-o -a", "+a +i" }));
    System.out.println(c(new String[]{ "mississippi", "-is -i", "+iz +p" }));
  }
}

Output:

Hello Earth
Hello Worth
Hey
Green
mlzslzspppp
Fiitbill
mpzspzspppp


答:
Pyke, <s>13</s> 11 bytes

```<code>z[zdcmt)[.:
</code>```

Try it here!

```<code>z           - input()
 [zdcmt)    - def func():
  zdc       -  input().split(" ")
     mt     -  map(>[1:], ^)
            - func()
        [   - func()
         .: - translate()
</code>```

Or 2 bytes if in a different input format:

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

Try it here!

Title: Letter-replacement challenge

Body:
Pyke, <s>13</s> 11 bytes

z[zdcmt)[.:

Try it here!

z           - input()
 [zdcmt)    - def func():
  zdc       -  input().split(" ")
     mt     -  map(>[1:], ^)
            - func()
        [   - func()
         .: - translate()

Or 2 bytes if in a different input format:

.:

Try it here!


问:
Chebyshev Rotation
Consider a regular grid, where each cell has integer coordinates. We can group the cells into (square-shaped) "rings" where the cells in each ring have the same Chebyshev distance (or chessboard distance) from the origin. Your task is to take such a cell coordinate and rotate that cell by one position counter-clockwise within its ring. This implements the following mapping:

So for example if the input is (3, -2) you should output (3, -1). Note that (0, 0) is the only input that should map to itself.

Rules

The I/O format is fairly flexible. You can use two individual numbers, a pair/list/array/tuple of numbers, a single complex number, a string containing two numbers, etc.

You may assume that -128 < x,y < 128.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

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

Test Cases

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

答:
R, 131 110 bytes

A function that takes the two integers, x,y as inputs and writes the output to stdout. The solution follows @Dennis' control flow scheme but could probably be golfed.

EDIT: Updated code based on @JDL's suggestions and saved a bunch of bytes.

```<code>function(x,y){X=sign(x+y);Y=sign(y-x);if(!X|!Y){x=x-X;y=y-Y}else if(X==Y&X&Y)x=x-X else if(X-Y&X)y=y-Y;c(x,y)}
</code>```

Ungolfed

```<code>f=function(x,y){
    X=sign(x+y)                 # calculate sign
    Y=sign(y-x)                 #  =||=
    if(!X|!Y){x=x-X;y=y-Y}      # if at least one is 0: subtract sign
    else if(X==Y&X&Y)x=x-X      # if signs are equal and non-zero: add sign to x
    else if(X-Y&X)y=y-Y         # if signs are not equal and non-zero: add sign to y
    c(x,y)                      # print to stdout
}
</code>```

Title: Chebyshev Rotation

Body:
R, 131 110 bytes

A function that takes the two integers, x,y as inputs and writes the output to stdout. The solution follows @Dennis' control flow scheme but could probably be golfed.

EDIT: Updated code based on @JDL's suggestions and saved a bunch of bytes.

function(x,y){X=sign(x+y);Y=sign(y-x);if(!X|!Y){x=x-X;y=y-Y}else if(X==Y&X&Y)x=x-X else if(X-Y&X)y=y-Y;c(x,y)}

Ungolfed

f=function(x,y){
    X=sign(x+y)                 # calculate sign
    Y=sign(y-x)                 #  =||=
    if(!X|!Y){x=x-X;y=y-Y}      # if at least one is 0: subtract sign
    else if(X==Y&X&Y)x=x-X      # if signs are equal and non-zero: add sign to x
    else if(X-Y&X)y=y-Y         # if signs are not equal and non-zero: add sign to y
    c(x,y)                      # print to stdout
}


答:
05AB1E, <s>15</s> 17 bytes

```<code>IIð¡€áIð¡€á‚øvy`:
</code>```

Try it online!

Explanation

```<code>I                   # read starting string
 I                  # read letters to be replaced
  ð¡                # split on space
    €á              # and remove "-"
      I             # read replacement letters
       ð¡           # split on space
         €á         # and remove "+"
           ‚ø       # zip to produce pairs of [letters to replace, replacement letters]
             vy`:   # for each pair, replace in starting string
</code>```

Or with a less strict input format

```<code>vy`:
</code>```

Try it online

Title: Letter-replacement challenge

Body:
05AB1E, <s>15</s> 17 bytes

IIð¡€áIð¡€á‚øvy`:

Try it online!

Explanation

I                   # read starting string
 I                  # read letters to be replaced
  ð¡                # split on space
    €á              # and remove "-"
      I             # read replacement letters
       ð¡           # split on space
         €á         # and remove "+"
           ‚ø       # zip to produce pairs of [letters to replace, replacement letters]
             vy`:   # for each pair, replace in starting string

Or with a less strict input format

vy`:

Try it online


答:
R, 98 94 bytes

Edit: saved 4 bytes thanks to @rturnbull

```<code>i=scan(,"");s=i[1];i=gsub("\\+|-","",i[-1]);l=length(i)/2;for(j in 1:l)s=gsub(i[j],i[l+j],s);s
</code>```

Ungolfed and test cases

Because scan (reads input from stdin) doesn't work properly in R-fiddle I showcase the program by wrapping it in a function instead. Note that the function takes a vector as an input and can be run by e.g.: f(c("Hello world", "-wo", "-ld", "+Ea", "+th")). The gofled program above would prompt the user to input using stdin whereby typing "Hello world" -wo -ld -Ea +th in the console would yield the same result.

Run the code on R-fiddle

```<code>f=function(i){
    s=i[1]                                   # Separate first element
    i=gsub("\\+|-","",i[-1])                 # Remove + and - from all elements except first, store as vector i
    l=length(i)/2                            # calculate the length of the vector i (should always be even)
    for(j in 1:l)s=gsub(i[j],i[l+j],s)       # iteratively match element j in i and substitute with element l+j in i
    s                                        # print to stdout
}
</code>```

Title: Letter-replacement challenge

Body:
R, 98 94 bytes

Edit: saved 4 bytes thanks to @rturnbull

i=scan(,"");s=i[1];i=gsub("\\+|-","",i[-1]);l=length(i)/2;for(j in 1:l)s=gsub(i[j],i[l+j],s);s

Ungolfed and test cases

Because scan (reads input from stdin) doesn't work properly in R-fiddle I showcase the program by wrapping it in a function instead. Note that the function takes a vector as an input and can be run by e.g.: f(c("Hello world", "-wo", "-ld", "+Ea", "+th")). The gofled program above would prompt the user to input using stdin whereby typing "Hello world" -wo -ld -Ea +th in the console would yield the same result.

Run the code on R-fiddle

f=function(i){
    s=i[1]                                   # Separate first element
    i=gsub("\\+|-","",i[-1])                 # Remove + and - from all elements except first, store as vector i
    l=length(i)/2                            # calculate the length of the vector i (should always be even)
    for(j in 1:l)s=gsub(i[j],i[l+j],s)       # iteratively match element j in i and substitute with element l+j in i
    s                                        # print to stdout
}


答:
PHP, <s>98</s> 97 bytes

```<code>for($s=$argv[$i=1];$v=$argv[++$i];)$r[$v[0]>'+'][]=substr($v,1);echo str_replace($r[1],$r[0],$s);
</code>```

This challenge describes the exact behaviour of str_replace so for php it's all about making the arrays of replacements. I tried to do it using only one "substring" but that might not be the best solution. Use like:

```<code>php -r "for($s=$argv[$i=1];$v=$argv[++$i];)$r[$v[0]>'+'][]=substr($v,1);echo str_replace($r[1],$r[0],$s);" "mississippi" "-is" "-i" "+iz" "+p"
</code>```

edit: 1 byte saved thanks to Titus

Title: Letter-replacement challenge

Body:
PHP, <s>98</s> 97 bytes

for($s=$argv[$i=1];$v=$argv[++$i];)$r[$v[0]>'+'][]=substr($v,1);echo str_replace($r[1],$r[0],$s);

This challenge describes the exact behaviour of str_replace so for php it's all about making the arrays of replacements. I tried to do it using only one "substring" but that might not be the best solution. Use like:

php -r "for($s=$argv[$i=1];$v=$argv[++$i];)$r[$v[0]>'+'][]=substr($v,1);echo str_replace($r[1],$r[0],$s);" "mississippi" "-is" "-i" "+iz" "+p"

edit: 1 byte saved thanks to Titus


问:
Exploded Suffixes
Given an ASCII string, output the exploded suffixes of it. For example, if the string was abcde, there are 5 suffixes, ordered longest to shortest:

```<code>abcde
bcde
cde
de
e
</code>```

Each suffix is then exploded, meaning each character is copied as many times as its one-indexed location in that suffix. For example, exploding the suffixes of abcde,

```<code>abcde
12345
abbcccddddeeeee

bcde
1234
bccdddeeee

cde
123
cddeee

de
12
dee

e
1
e
</code>```

Altogether, the exploded suffixes of abcde are

```<code>abbcccddddeeeee
bccdddeeee
cddeee
dee
e
</code>```

Rules

This is code-golf so the shortest code wins.

The input will consist of the printable ASCII characters. (This excludes newlines but includes spaces.)

The output will have each string on a separate line.

Trailing spaces are allowed on each line and there may be an extra newline at the end.

Test Cases

```<code>''

'a'
a

'bc'
bcc
c

'xyz'
xyyzzz
yzz
z

'code-golf'
coodddeeee-----ggggggooooooollllllllfffffffff
oddeee----gggggoooooolllllllffffffff
dee---ggggooooollllllfffffff
e--gggoooolllllffffff
-ggooollllfffff
goolllffff
ollfff
lff
f

's p a c e'
s  ppp    aaaaa      ccccccc        eeeeeeeee
 pp   aaaa     cccccc       eeeeeeee
p  aaa    ccccc      eeeeeee
 aa   cccc     eeeeee
a  ccc    eeeee
 cc   eeee
c  eee
 ee
e
</code>```

Title: Exploded Suffixes

Body:
Ruby, 51 bytes

Uses the -n flag for +1 byte.

(k=0;puts$_.gsub(/./){$&*k+=1};$_[0]="")while$_>$/


答:
PHP, 103 bytes (99 with short tags)

```<code><?php for($s=$argv[1];""!=$s[$i++];$o.="
")for($j=0;""!=$l=$s[$j+$i-1];)$o.=str_pad('',++$j,$l);echo$o;
</code>```

I'm pretty certain this isn't the shortest possible answer.

Title: Exploded Suffixes

Body:
Given an ASCII string, output the exploded suffixes of it. For example, if the string was abcde, there are 5 suffixes, ordered longest to shortest:

```<code>abcde
bcde
cde
de
e
</code>```

Each suffix is then exploded, meaning each character is copied as many times as its one-indexed location in that suffix. For example, exploding the suffixes of abcde,

```<code>abcde
12345
abbcccddddeeeee

bcde
1234
bccdddeeee

cde
123
cddeee

de
12
dee

e
1
e
</code>```

Altogether, the exploded suffixes of abcde are

```<code>abbcccddddeeeee
bccdddeeee
cddeee
dee
e
</code>```

Rules

This is code-golf so the shortest code wins.

The input will consist of the printable ASCII characters. (This excludes newlines but includes spaces.)

The output will have each string on a separate line.

Trailing spaces are allowed on each line and there may be an extra newline at the end.

Test Cases

```<code>''

'a'
a

'bc'
bcc
c

'xyz'
xyyzzz
yzz
z

'code-golf'
coodddeeee-----ggggggooooooollllllllfffffffff
oddeee----gggggoooooolllllllffffffff
dee---ggggooooollllllfffffff
e--gggoooolllllffffff
-ggooollllfffff
goolllffff
ollfff
lff
f

's p a c e'
s  ppp    aaaaa      ccccccc        eeeeeeeee
 pp   aaaa     cccccc       eeeeeeee
p  aaa    ccccc      eeeeeee
 aa   cccc     eeeeee
a  ccc    eeeee
 cc   eeee
c  eee
 ee
e
</code>```

Body:
PHP, 103 bytes (99 with short tags)

<?php for($s=$argv[1];""!=$s[$i++];$o.="
")for($j=0;""!=$l=$s[$j+$i-1];)$o.=str_pad('',++$j,$l);echo$o;

I'm pretty certain this isn't the shortest possible answer.


答:
Python 3, 93 byte

```<code>def f(s):
  s,m,p=s
  for n,o in zip(m.split(),p.split()):s=s.replace(n[1:],o[1:])
  return s
</code>```

Try it online!

Input is a list with strings, replacement strings are space separated.

Example input:
['mississippi','-is -i','+iz +p']

Title: Letter-replacement challenge

Body:
Python 3, 93 byte

def f(s):
  s,m,p=s
  for n,o in zip(m.split(),p.split()):s=s.replace(n[1:],o[1:])
  return s

Try it online!

Input is a list with strings, replacement strings are space separated.

Example input:
['mississippi','-is -i','+iz +p']


Title: Letter-replacement challenge

Body:
PHP, 164 Bytes

preg_match_all("#^[^-+]+|-[\S]+|[+][\S]+#",$argv[1],$t);for($s=($a=$t[0])[0];++$i<$c=count($a)/2;)$s=str_replace(trim($a[+$i],"-"),trim($a[$i+$c^0],"+"),$s);echo$s;


问:
Golf you a quine for great good!
Using your language of choice, golf a quine.

A quine is a non-empty computer program which takes no input and produces a copy of its own source code as its only output.

No cheating -- that means that you can't just read the source file and print it. Also, in many languages, an empty file is also a quine: that isn't considered a legit quine either.

No error quines -- there is already a separate challenge for error quines.

Points for:

Smallest code (in bytes)

Most obfuscated/obscure solution

Using esoteric/obscure languages

Successfully using languages that are difficult to golf in

The following Stack Snippet can be used to get a quick view of the current score in each language, and thus to know which languages have existing answers and what sort of target you have to beat:

var QUESTION_ID=69;
var OVERRIDE_USER=98;

var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(index){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}
function commentUrl(index,answers){return"https://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}
function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=!1;comment_page=1;getComments()}})}
function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}
getAnswers();var SCORE_REG=(function(){var headerTag=String.raw `h\d`
var score=String.raw `\-?\d+\.?\d*`
var normalText=String.raw `[^\n<>]*`
var strikethrough=String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>`
var noDigitText=String.raw `[^\n\d<>]*`
var htmlTag=String.raw `<[^\n<>]+>`
return new RegExp(String.raw `<${headerTag}>`+String.raw `\s*([^\n,]*[^\s,]),.*?`+String.raw `(${score})`+String.raw `(?=`+String.raw `${noDigitText}`+String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+String.raw `</${headerTag}>`+String.raw `)`)})();var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}
function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))
body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)
valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,})});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)
lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+a.language+'').text().toLowerCase();languages[lang]=languages[lang]||{lang:a.language,user:a.user,size:a.size,link:a.link,uniq:lang}});var langs=[];for(var lang in languages)
if(languages.hasOwnProperty(lang))
langs.push(languages[lang]);langs.sort(function(a,b){if(a.uniq>b.uniq)return 1;if(a.uniq<b.uniq)return-1;return 0});for(var i=0;i<langs.length;++i)
{var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

  <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654">

Winners by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

 ```

ContentLicense: CC BY-SA 4.0

Title: Golf you a quine for great good!

Body:
Yup, <s>1165</s> <s>879</s> <s>606</s> <s>561</s> <s>540</s> <s>522</s> 498 + 7 = 505 bytes

Requires the -cheat flag to allow the definition of aliases.

022222120211111102222122021121202222212021112202222110222212202112110222221202122212022222102222212021222120222221022222102222210222221202222110222211022222210222221022222210222212202222221022221102211110222221022221220222212202112120221111022212202211210222212022222102211120222122022111202222120212212021221202222221022111102221210222122022222102222120212212022221102211110222122022221102222120212212022112120221111022212202112120222212=%;0e-=<;0<-=>;:0~--=1;1>=2;0%{{>0<~{~>~<<}>>>]}>]}${<#}%{@}

<a href="http://yup.tryitonline.net/#code=MDIyMjIyMTIwMjExMTExMTAyMjIyMTIyMDIxMTIxMjAyMjIyMjEyMDIxMTEyMjAyMjIyMTEwMjIyMjEyMjAyMTEyMTEwMjIyMjIxMjAyMTIyMjEyMDIyMjIyMTAyMjIyMjEyMDIxMjIyMTIwMjIyMjIxMDIyMjIyMTAyMjIyMjEwMjIyMjIxMjAyMjIyMTEwMjIyMjExMDIyMjIyMjEwMjIyMjIxMDIyMjIyMjEwMjIyMjEyMjAyMjIyMjIxMDIyMjIxMTAyMjExMTEwMjIyMjIxMDIyMjIxMjIwMjIyMjEyMjAyMTEyMTIwMjIxMTExMDIyMjEyMjAyMjExMjEwMjIyMjEyMDIyMjIyMTAyMjExMTIwMjIyMTIyMDIyMTExMjAyMjIyMTIwMjEyMjEyMDIxMjIxMjAyMjIyMjIxMDIyMTExMTAyMjIxMjEwMjIyMTIyMDIyMjIyMTAyMjIyMTIwMjEyMjEyMDIyMjIxMTAyMjExMTEwMjIyMTIyMDIyMjIxMTAyMjIyMTIwMjEyMjEyMDIyMTEyMTIwMjIxMTExMDIyMjEyMjAyMTEyMTIwMjIyMjEyPSU7MGUtPTw7MDwtPT47OjB-LS09MTsxPj0yOzAle3s-MDx-e34-fjw8fT4-Pl19Pl19JHs8I30le0B9&input=&args=LWNoZWF0">Try it online!

Explanation

There are two parts to this (as with most quines). The data:

022222120211111102222122021121202222212021112202222110222212202112110222221202122212022222102222212021222120222221022222102222210222221202222110222211022222210222221022222210222212202222221022221102211110222221022221220222212202112120221111022212202211210222212022222102211120222122022111202222120212212021221202222221022111102221210222122022222102222120212212022221102211110222122022221102222120212212022112120221111022212202112120222212

And the decoder:

=%;0e-=<;0<-=>;:0~--=1;1>=2;0%{{>0<~{~>~<<}>>>]}>]}${<#}%{@}

The data is merely a binary encoding of the decoder (or rather its reverse). Each 0 starts a new character and the 1s and 2s are the 0- and 1-bits, respectively.

Note that 0 is a standard Yup command which pushes a zero, while 1 and 2 are not defined at this point. However, we assign the entire data part to the command % so that the 1 and 2 can remain undefined until % is actually used.

Next, we define some more commands:

0e-=<;
0<-=>;
:0~--=1;
1>=2;

< decrements the top of the stack, > increments it. 1 (somewhat unintuitively) doubles the top of the stack. 2 doubles it and then increments it. Thanks to these definitions, something like 0221111 will actually leave a 48 (110000 in binary) on the stack.

The remaining 32 bytes do the actual decoding in two parts. First we need to reconstruct the data string.

0%                ` Push a zero and then the data.
{                 ` For each value...
  {               `   Until that value is zero...
    >0<~{~>~<<}>  `   divmod 2. The div is the input to the next iteration,
                  `   the mod gives us the next bit.
    >>]           `   Increment twice (gives 2 or 3) and put at the bottom
                  `   of the stack.
  }
  >]              ` Increment the 0 and put it at the bottom as well.
}
$                 ` Reverse the entire stack.
{<#}              ` Decrement and print each number.

And finally, we push the data again and print each value as a character:

%{@}

For future reference, here is a CJam script to encode the data.


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

答:
Python, 32 bytes

```<code>N=lambda s,n:n and[N(s,n-1)]or s
</code>```

Title: Nest a string inside an array n times

Body:
Python, 32 bytes

N=lambda s,n:n and[N(s,n-1)]or s


答:
Javascript ES6, 23 bytes

Recursive function

f=(a,i)=>i?f([a],--i):a

console.log(f("stackoverflow",0))
console.log(f("stackoverflow",1))
console.log(f("stackoverflow",2))
console.log(f("stackoverflow",5))```
</div>
</div>
</p>
<p>Currying results in the same length</p>
```f=a=>i=>i?f([a])(--i):a
```

Title: Nest a string inside an array n times

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

Body:
Javascript ES6, 23 bytes

Recursive function

f=(a,i)=>i?f([a],--i):a

console.log(f("stackoverflow",0))
console.log(f("stackoverflow",1))
console.log(f("stackoverflow",2))
console.log(f("stackoverflow",5))

Currying results in the same length

f=a=>i=>i?f([a])(--i):a


答:
Mathematica, 13 bytes

```<code>List~Nest~##&
</code>```

Title: Nest a string inside an array n times

Body:
Mathematica, 13 bytes

List~Nest~##&


答:
Ruby, 25 characters

Rewrite of jamylak's Python solution.

f=->s,n{n>0?[f[s,n-1]]:s}
```

<p>Sample run:</p>

```irb(main):001:0> f=->s,n{n>0?[f[s,n-1]]:s}
=> #<Proc:0x00000002006e80@(irb):1 (lambda)>

irb(main):002:0> f["stackoverflow",0]
=> "stackoverflow"

irb(main):003:0> f["stackoverflow",1]
=> ["stackoverflow"]

irb(main):004:0> f["stackoverflow",5]
=> [[[[["stackoverflow"]]]]]
```

Title: Nest a string inside an array n times

Body:
Ruby, 25 characters

Rewrite of jamylak's Python solution.

f=->s,n{n>0?[f[s,n-1]]:s}

Sample run:

irb(main):001:0> f=->s,n{n>0?[f[s,n-1]]:s}
=> #<Proc:0x00000002006e80@(irb):1 (lambda)>

irb(main):002:0> f["stackoverflow",0]
=> "stackoverflow"

irb(main):003:0> f["stackoverflow",1]
=> ["stackoverflow"]

irb(main):004:0> f["stackoverflow",5]
=> [[[[["stackoverflow"]]]]]


答:
05AB1E, 3 bytes

Code

```<code>`F)
</code>```

Explanation

```<code>`   # Flatten the input array on the stack.
 F  # Element_2 times do:
  ) # Wrap the total stack into a single array.
</code>```

This means that this also works for the 0-testcase, since the string is already on the stack.

Try it online!

Title: Nest a string inside an array n times

Body:
05AB1E, 3 bytes

Code

`F)

Explanation

`   # Flatten the input array on the stack.
 F  # Element_2 times do:
  ) # Wrap the total stack into a single array.

This means that this also works for the 0-testcase, since the string is already on the stack.

Try it online!


问:
Combinatorial products of unique primes

Statement of problem

Given a set of unique, consecutive primes (not necessarily including 2), generate the products of all combinations of first powers of these primes — e.g., no repeats — and also 1. For example, given the set { 2, 3, 5, 7 }, you produce { 1, 2, 3, 5, 6, 7, 10, 14, 15, 21, 30, 35, 42, 70, 105, 210 } because:

```<code>  1  =  1
  2  =  2
  3  =  3
  5  =  5
  6  =  2 x 3
  7  =  7
 10  =  2 x 5
 14  =  2 x 7
 15  =  3 x 5
 21  =  3 x 7
 30  =  2 x 3 x 5
 35  =  5 x 7
 42  =  2 x 3 x 7
 70  =  2 x 5 x 7
105  =  3 x 5 x 7
210  =  2 x 3 x 5 x 7
</code>```

Note that if the cardinality of your input set is k, this will give you 2^k members in your output set.

Rules/Conditions

You can use any language. Aim for the smallest character count of source code.

Your solution must be either a complete program or a complete function. The function can be anonymous (if your language supports anonymous functions).

Your solution should be able to support products up to at least 2^31. Don't worry about detecting or handling integer overflow if you are passed numbers whose product is too great to represent. However, please state the limits of your calculations.

You may accept either a list or a set and produce either a list or a set. You may assume the input is sorted but you are not required to produce sorted output.

Background

When or why is this useful? One place it is very useful is in generating a table of multipliers to race in parallel in an integer factoring algorithm known as Square Forms Factorization. There, each odd multiplier you try decreases the probability of the algorithm failing (to find a factor) by approximately 50% on hard semiprimes. So with the set of generating primes { 3, 5, 7, 11 }, which produces a set of 16 trial multipliers to race in parallel, the algorithm fails approximately 2^–16 of the time on hard semiprimes. Adding 13 to the primes list produces a set of 32 trial multipliers, reducing the chance of failure to approximately 2^–32, giving a drastic improvement in outcome at no additional computational expense (because even with twice as many multipliers racing in parallel, on average it still finds the answer in the same total number of steps).

答:
PHP, 97 Bytes

```<code><?for(;$i++<array_product($a=$_GET[a]);){$t=$i;foreach($a as$d)$t%$d?:$t/=$d;if($t<2)echo"$i\n";}
</code>```

Title: Combinatorial products of unique primes

Body:
PHP, 97 Bytes

<?for(;$i++<array_product($a=$_GET[a]);){$t=$i;foreach($a as$d)$t%$d?:$t/=$d;if($t<2)echo"$i\n";}


答:
Jelly, 2 bytes

```<code>W¡
</code>```

Slightly confusing, since: (1) Jelly has no strings, only lists of characters; and (2); the output wont show the nesting. To see that this actually is doing what is asked look at a Python string representation of the result with:

```<code>W¡ŒṘ
</code>```

An extra pair of [] will be present since the string itself will be a list of characters. For example

How?

```<code>W¡ - Main link: s, n
W  - wrap left, initially s, in a list
 ¡ - repeat previous link n times
</code>```

The proof-of-concept code adds:

```<code>W¡ŒṘ - Main link: s, n
  ŒṘ - Python string representation
</code>```

Title: Nest a string inside an array n times

Body:
Jelly, 2 bytes

W¡

Slightly confusing, since: (1) Jelly has no strings, only lists of characters; and (2); the output wont show the nesting. To see that this actually is doing what is asked look at a Python string representation of the result with:

W¡ŒṘ

An extra pair of [] will be present since the string itself will be a list of characters. For example

How?

W¡ - Main link: s, n
W  - wrap left, initially s, in a list
 ¡ - repeat previous link n times

The proof-of-concept code adds:

W¡ŒṘ - Main link: s, n
  ŒṘ - Python string representation


答:
PHP, 60 Bytes

```<code>for($r=$argv[1];$i++<$argv[2];)$r=[$r];echo json_encode($r);
</code>```

48 Bytes if it looks only like the task

```<code>for($r=$argv[1];$i++<$argv[2];)$r="[$r]";echo$r;
</code>```

Title: Nest a string inside an array n times

Body:
PHP, 60 Bytes

for($r=$argv[1];$i++<$argv[2];)$r=[$r];echo json_encode($r);

48 Bytes if it looks only like the task

for($r=$argv[1];$i++<$argv[2];)$r="[$r]";echo$r;


答:
Perl, 58 bytes

57 bytes code + 1 for -p.

Requires first item on one line, then the replacements on the next. Big thanks to @Dada who came up with a different approach to help reduce by 4 bytes!

$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee
```

<h3>Usage</h3>

<pre class="lang-sh prettyprint-override"><code>perl -pe '$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee' <<< 'Football
-o -a +a +i'
Fiitbill
</code>```

perl -pe '$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee' <<< 'mississippi
-is -i +iz +p'
mpzspzspppp
```

<pre class="lang-sh prettyprint-override"><code>perl -pe '$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee' <<< 'mississippi
-ippi -i -mess +ee +e +tenn'
tennessee
</code>```

Title: Letter-replacement challenge

Body:
The idea is simple. You've to create a "visualised" letter-replacement, by providing 3 strings (input can be comma separated, separate inputs, or as an array). The first segment is the word you want to correct, and the second segment is the letters you want to replace, and the third segment is the replacement for the letters in segment 2.

For example:

```<code>|    | Input                       | Starting Word | Output      |
|----|-----------------------------|---------------|-------------|
| #1 | Hello world -wo -ld +Ea +th | Hello world   | Hello Earth |
| #2 | Hello World -wo -ld +Ea +th | Hello World   | Hello Worth |
| #3 | Hello -llo +y               | Hello         | Hey         |
| #4 | Red -R -d +Gr +en           | Red           | Green       |
| #5 | mississippi -is -i +lz +p   | mississippi   | mlzslzspppp |
| #6 | Football -o -a +a +i        | Football      | Fiitbill    |
| #7 | mississippi -is -i +iz +p   | mississippi   | mpzspzspppp |
</code>```

Explanation

The replacements are to be done step-by-step with their respective pair. Here's an illustration with an input of mississippi -is -i +iz +p to give the output mpzspzsppp (see example #7 above)

```<code>| Step  | Input                         | Output        |
|------ |---------------------------    |-------------  |
| #1    | mississippi -is -i +iz +p     |               |
| #2    | mississippi -is +iz           | mizsizsippi   |
| #3    | mizsizsippi -i +p             | mpzspzspppp   |
</code>```

Rules

Inputs are always in this order <starting_string> <list_of_letters_to_replace> <replacement_letters>.

Letters to replace and replacement groups will never be mixed (ie: there will never be -a +i -e +o).

Letters to replace are always prefixed with - and replacement letters are always prefixed with +. (The prefix is mandatory)

There may be more than one set of letters to replace, so you'd need to look at the prefix.

Assume the amount of letter groups to replace and the amount of replacement letter groups are always equal (ie: there will never be -a -e +i)

Replacements are case-sensitive (see example #1 and #2).

Replacements are done in the order they were given in the input.

Letter replacements can be replaced with other replacements. See example #6.

The first segment (starting word) will never include - or + characters.

This is code-golf so shortest bytes win.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by 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=96473,OVERRIDE_USER=38505;function answersUrl(e){return"http://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"http://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, 58 bytes

57 bytes code + 1 for -p.

Requires first item on one line, then the replacements on the next. Big thanks to @Dada who came up with a different approach to help reduce by 4 bytes!

$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee

Usage

perl -pe '$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee' <<< 'Football
-o -a +a +i'
Fiitbill

perl -pe '$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee' <<< 'mississippi
-is -i +iz +p'
mpzspzspppp

perl -pe '$a=<>;1while$a=~s%-(\S*)(.*?)\+(\S*)%"s/$1/$3/g;q{$2}"%ee' <<< 'mississippi
-ippi -i -mess +ee +e +tenn'
tennessee


答:
05AB1E, 2 bytes

```<code>æP
</code>```

Try it online!

Explanation

```<code>æ   # powerset
 P  # product
</code>```

Title: Combinatorial products of unique primes

Body:
Statement of problem

Given a set of unique, consecutive primes (not necessarily including 2), generate the products of all combinations of first powers of these primes — e.g., no repeats — and also 1. For example, given the set { 2, 3, 5, 7 }, you produce { 1, 2, 3, 5, 6, 7, 10, 14, 15, 21, 30, 35, 42, 70, 105, 210 } because:

```<code>  1  =  1
  2  =  2
  3  =  3
  5  =  5
  6  =  2 x 3
  7  =  7
 10  =  2 x 5
 14  =  2 x 7
 15  =  3 x 5
 21  =  3 x 7
 30  =  2 x 3 x 5
 35  =  5 x 7
 42  =  2 x 3 x 7
 70  =  2 x 5 x 7
105  =  3 x 5 x 7
210  =  2 x 3 x 5 x 7
</code>```

Note that if the cardinality of your input set is k, this will give you 2^k members in your output set.

Rules/Conditions

You can use any language. Aim for the smallest character count of source code.

Your solution must be either a complete program or a complete function. The function can be anonymous (if your language supports anonymous functions).

Your solution should be able to support products up to at least 2^31. Don't worry about detecting or handling integer overflow if you are passed numbers whose product is too great to represent. However, please state the limits of your calculations.

You may accept either a list or a set and produce either a list or a set. You may assume the input is sorted but you are not required to produce sorted output.

Background

When or why is this useful? One place it is very useful is in generating a table of multipliers to race in parallel in an integer factoring algorithm known as Square Forms Factorization. There, each odd multiplier you try decreases the probability of the algorithm failing (to find a factor) by approximately 50% on hard semiprimes. So with the set of generating primes { 3, 5, 7, 11 }, which produces a set of 16 trial multipliers to race in parallel, the algorithm fails approximately 2^–16 of the time on hard semiprimes. Adding 13 to the primes list produces a set of 32 trial multipliers, reducing the chance of failure to approximately 2^–32, giving a drastic improvement in outcome at no additional computational expense (because even with twice as many multipliers racing in parallel, on average it still finds the answer in the same total number of steps).

Body:
05AB1E, 2 bytes

æP

Try it online!

Explanation

æ   # powerset
 P  # product


问:
Directories required for creating a folder tree
Say that you have this folder structure on your coumputer:

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

And you want to have these folders:

```<code>/a/b
/a/c
/b/b
</code>```

You would need to create four directories, using mkdir for example:

```<code>mkdir /a/b
mkdir /a/c
mkdir /b
mkdir /b/b
</code>```

Write a program that, given existing and required directory structures, will output the directories that need to be created.

Input

First line has two numbers: n, number of existing directories, and m, number of required directories
Next n lines has the list of existing directories
Next m lines has the list of required directories

Example:

```<code>1 3
/a
/a/b
/a/c
/b/b
</code>```

Output

Directories you need to create

Example:

```<code>/a/b
/a/c
/b
/b/b
</code>```

答:
Python

In Python, you would just use os.makedirs(). See the docs at the bottom of this post

import sys

num_existing, num_required = map(int, next(sys.stdin).split())

sep = "/"
directory = {}

for i,path in enumerate(s.rstrip("\n") for s in sys.stdin):
    d = directory
    base = ""
    for p in path.split(sep)[1:]:
        base += sep+p
        if p not in d:
            if i >= num_existing:
                print base
            d[p]={}
        d = d[p]
```
<p>Python docs for <code>os.makedirs()</code></p>
<pre class="lang-py prettyprint-override"><code>>>> import os
>>> help(os.makedirs)

Help on function makedirs in module os:

makedirs(name, mode=511)
    makedirs(path [, mode=0777])

    Super-mkdir; create a leaf directory and all intermediate ones.
    Works like mkdir, except that any intermediate path segment (not
    just the rightmost) will be created if it does not exist.  This is
    recursive.
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Python

In Python, you would just use os.makedirs(). See the docs at the bottom of this post

import sys

num_existing, num_required = map(int, next(sys.stdin).split())

sep = "/"
directory = {}

for i,path in enumerate(s.rstrip("\n") for s in sys.stdin):
    d = directory
    base = ""
    for p in path.split(sep)[1:]:
        base += sep+p
        if p not in d:
            if i >= num_existing:
                print base
            d[p]={}
        d = d[p]

Python docs for os.makedirs()

>>> import os
>>> help(os.makedirs)

Help on function makedirs in module os:

makedirs(name, mode=511)
    makedirs(path [, mode=0777])

    Super-mkdir; create a leaf directory and all intermediate ones.
    Works like mkdir, except that any intermediate path segment (not
    just the rightmost) will be created if it does not exist.  This is
    recursive.


答:
Brachylog, 10 bytes

```<code>tT,?h:T:gi
</code>```

Try it online!

Explanation

```<code>tT,            T is the integer (second element of the Input)
   ?h:T:g      The list [String, T, built-in_group]
         i     Iterate: Apply built-in_group T times to String
</code>```

This would be 3 bytes if it wasn't bugged. Here we need all this to get the list [String, T, built-in_group] even though [String, T] is already our input.

Unfortunately :g directly results in [[String, T], built-in_group], which is not recognized properly by i because the integer T is inside the first list.

Title: Nest a string inside an array n times

Body:
Brachylog, 10 bytes

tT,?h:T:gi

Try it online!

Explanation

tT,            T is the integer (second element of the Input)
   ?h:T:g      The list [String, T, built-in_group]
         i     Iterate: Apply built-in_group T times to String

This would be 3 bytes if it wasn't bugged. Here we need all this to get the list [String, T, built-in_group] even though [String, T] is already our input.

Unfortunately :g directly results in [[String, T], built-in_group], which is not recognized properly by i because the integer T is inside the first list.


答:
Vim, 25 bytes

qq+dE+r-PdiW:1s<C-R>"-g<CR>@qq@q

Assumes input in this format:

```<code>mississippi
-is -i
+lz +p
</code>```

+dE+r-PdiW: Combines - and + into single register, with the + turned into a -.

:1s<C-R>"-g: Uses the register as a code snippet, inserted directly into the :s command, with - as the separator.

Title: Letter-replacement challenge

Body:
Vim, 25 bytes

qq+dE+r-PdiW:1s<C-R>"-g<CR>@qq@q

Assumes input in this format:

mississippi
-is -i
+lz +p

+dE+r-PdiW: Combines - and + into single register, with the + turned into a -.

:1s<C-R>"-g: Uses the register as a code snippet, inserted directly into the :s command, with - as the separator.


答:
R, 39 40 bytes

EDIT: Fixed the n=0 issue thanks to @rturnbull.

Function that takes two inputs s (string) and n (nestedness) and outputs the nested list. Note that R-class list natively prints output differently than most other languages, however, is functionally similar to a key/value map (with possibly unnamed keys) or a list in python.

```<code>f=function(s,n)if(n)list(f(s,n-1))else s
</code>```

Example

```<code>> f=function(s,n)if(n)list(f(s,n-1))else s
> f("hello",3)
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[1] "hello"

> # to access the string nested 5 times in the "list-object" named "list" we can do the following
> list = f("nested string",5)
> list[[1]][[1]][[1]][[1]][[1]]
[1] "nested string"
</code>```

Title: Nest a string inside an array n times

Body:
R, 39 40 bytes

EDIT: Fixed the n=0 issue thanks to @rturnbull.

Function that takes two inputs s (string) and n (nestedness) and outputs the nested list. Note that R-class list natively prints output differently than most other languages, however, is functionally similar to a key/value map (with possibly unnamed keys) or a list in python.

f=function(s,n)if(n)list(f(s,n-1))else s

Example

> f=function(s,n)if(n)list(f(s,n-1))else s
> f("hello",3)
[[1]]
[[1]][[1]]
[[1]][[1]][[1]]
[1] "hello"

> # to access the string nested 5 times in the "list-object" named "list" we can do the following
> list = f("nested string",5)
> list[[1]][[1]][[1]][[1]][[1]]
[1] "nested string"


问:
Natural Pi #1 - Sand

Goal

Generate (N) random line segments of uniform length (l), check if they cross the equidistant (t) parallel lines.

Simulation

What are we simulating? Buffon's needle. Smooth out the sand in your sandbox, draw a set of equally spaced parallel lines (call the distance in between t). Take a straight stick of length l and drop it N times into the sandbox. Let the number of times it crossed a line be c. Then Pi = (2 * l * n) / (t * c)!

How are we simulating this?

Take input N,t,l

With N, t, l all being positive integers

Do the following N times:

Generate a uniformly random integer coordinate x,y

With 1 <= x, y <= 10^6

x,y is the center of a line segment of length l

Generate a uniformly random integer a

With 1 <= a <= 180

Let P be the point where the line segment would cross the x-axis

Then a is the angle (x,y), P, (inf,0)

Count the number, c, of line segments that cross the line x = i*t for any integer i

Return (2 * l * N) / (t * c)

Specification

Input

Flexible, take input in any of the standard ways (eg function parameter,STDIN) and in any standard format (eg String, Binary)

Output

Flexible, give output in any of the standard ways (eg return, print)

White space, trailing and leading white space is acceptable

Accuracy, please provide at least 4 decimal places of accuracy (ie 3.1416)

Scoring

Shortest code wins!

Test Cases

Your output may not line up with these, because of random chance. But on average, you should get about this much accuracy for the given value of N, t, l.

```<code>Input (N,t,l)    ->  Output
-----------        ------
10,10,5          -> ?.????
10,100,50        -> ?.????
1000,1000,600    -> 3.????
10000,1000,700   -> 3.1???
100000,1000,700  -> 3.14??
</code>```

TL;DR

These challenges are simulations of algorithms that only require nature and your brain (and maybe some re-usable resources) to approximate Pi. If you really need Pi during the zombie apocalypse, these methods don't waste ammo! There are nine challenges total.

答:
Perl, 97 bytes

#!perl -p
/ \d+/;$_*=2*$'/$&/map{($x=(1+~~rand 1e6)/$&)-$a..$x+($a=$'/$&/2*sin~~rand(180)*71/4068)-1}1..$_
```

<p>Counting the shebang as one, input is taken from stdin, space separated. If non-integer random values were allowed, this could be somewhat shorter.</p>

<p>I have taken one liberty, approximating <em>π/180</em> as <em>71/4068</em>, which is accurate within <em>1.48·10<sup>-9</sup></em>.</p>

<p><strong>Sample Usage</strong></p>

<pre class="lang-perl prettyprint-override"><code>$ echo 1000000 1000 70000 | perl pi-sand.pl
3.14115345174061
</code>```

More-or-less mathematically equivalent substitutions

Assuming the x-coordinate represents the left-most point of the needle, rather than its middle, as specified in the problem description:

89 bytes

#!perl -p
/ \d+/;$_*=2*$'/$&/map{($x=(1+~~rand 1e6)/$&)..$x+($'/$&*sin~~rand(180)*71/4068)-1}1..$_
```

<p>The problem specifies that <code>x</code> is to be sampled as a random integer. If we project the line spacing to a gap of one, this will leave us with values of the form <code>n/t</code> with <code>0 <= n < t</code>, not necessarily uniform, if <code>t</code> does not evenly divide <code>1e6</code>. Assuming that a uniform distribution is nonetheless acceptable:</p>

<p><strong>76 bytes</strong></p>

<pre class="lang-perl prettyprint-override"><code>#!perl -p
/ \d+/;$_*=2*$'/$&/map{($x=rand)..$x+($'/$&*sin~~rand(180)*71/4068)-1}1..$_
</code>```

Note that since rand will always be less than one (and therefore truncated to zero), it is not necessary at the start of the range:

70 bytes

#!perl -p
/ \d+/;$_*=2*$'/$&/map{1..(rand)+($'/$&*sin~~rand(180)*71/4068)}1..$_
```

<p>Assuming that the angle of the needle need not be an integer degree, but only uniformly random:</p>

<p><strong>59 bytes</strong></p>

<pre class="lang-perl prettyprint-override"><code>#!perl -p
/ \d+/;$_*=2*$'/$&/map{1..(rand)+abs$'/$&*sin rand$`}1..$_
</code>```

Assuming that the angle may be any uniform distribution:

52 bytes

#!perl -p
/ \d+/;$_*=2*$'/$&/map{1..(rand)+abs$'/$&*sin}1..$_
```

<p>The above is a mathematically correct simulation of Buffon's Needle. However, at this point I think most people would agree that this isn't actually what the question asked for.</p>

<hr>

<p><strong>Really pushin' it</strong></p>

<p>We could just throw away half of the test cases, whenever the second endpoint is to the left of the first (rather than swapping them):</p>

<p><strong>47 bytes</strong></p>

<pre class="lang-perl prettyprint-override"><code>#!perl -p
/ \d+/;$_*=$'/$&/map{1..(rand)+$'/$&*sin}1..$_
</code>```

Note that the values of t and l are inconsequential to the results of the experiment. We could just ignore them (implicitly assuming them to be equal):

28 bytes

#!perl -p
$_/=map{1..(rand)+sin}1..$_
```

Obviously non-competing, but you have to admit, it does have a certain elegance to it.

Title: Natural Pi #1 - Sand

Body:
Perl, 97 bytes

#!perl -p
/ \d+/;$_*=2*$'/$&/map{($x=(1+~~rand 1e6)/$&)-$a..$x+($a=$'/$&/2*sin~~rand(180)*71/4068)-1}1..$_

Counting the shebang as one, input is taken from stdin, space separated. If non-integer random values were allowed, this could be somewhat shorter.

I have taken one liberty, approximating π/180 as 71/4068, which is accurate within 1.48·10-9.

Sample Usage

$ echo 1000000 1000 70000 | perl pi-sand.pl
3.14115345174061

More-or-less mathematically equivalent substitutions

Assuming the x-coordinate represents the left-most point of the needle, rather than its middle, as specified in the problem description:

89 bytes

#!perl -p
/ \d+/;$_*=2*$'/$&/map{($x=(1+~~rand 1e6)/$&)..$x+($'/$&*sin~~rand(180)*71/4068)-1}1..$_

The problem specifies that x is to be sampled as a random integer. If we project the line spacing to a gap of one, this will leave us with values of the form n/t with 0 <= n < t, not necessarily uniform, if t does not evenly divide 1e6. Assuming that a uniform distribution is nonetheless acceptable:

76 bytes

#!perl -p
/ \d+/;$_*=2*$'/$&/map{($x=rand)..$x+($'/$&*sin~~rand(180)*71/4068)-1}1..$_

Note that since rand will always be less than one (and therefore truncated to zero), it is not necessary at the start of the range:

70 bytes

#!perl -p
/ \d+/;$_*=2*$'/$&/map{1..(rand)+($'/$&*sin~~rand(180)*71/4068)}1..$_

Assuming that the angle of the needle need not be an integer degree, but only uniformly random:

59 bytes

#!perl -p
/ \d+/;$_*=2*$'/$&/map{1..(rand)+abs$'/$&*sin rand$`}1..$_

Assuming that the angle may be any uniform distribution:

52 bytes

#!perl -p
/ \d+/;$_*=2*$'/$&/map{1..(rand)+abs$'/$&*sin}1..$_

The above is a mathematically correct simulation of Buffon's Needle. However, at this point I think most people would agree that this isn't actually what the question asked for.

Really pushin' it

We could just throw away half of the test cases, whenever the second endpoint is to the left of the first (rather than swapping them):

47 bytes

#!perl -p
/ \d+/;$_*=$'/$&/map{1..(rand)+$'/$&*sin}1..$_

Note that the values of t and l are inconsequential to the results of the experiment. We could just ignore them (implicitly assuming them to be equal):

28 bytes

#!perl -p
$_/=map{1..(rand)+sin}1..$_

Obviously non-competing, but you have to admit, it does have a certain elegance to it.


答:
Java and C#, 62 bytes

```<code>Object f(String s,int n){return n<1?s:new Object[]{f(s,n-1)};}
</code>```

Should work without modification in both Java and C#.

Title: Nest a string inside an array n times

Body:
Java and C#, 62 bytes

Object f(String s,int n){return n<1?s:new Object[]{f(s,n-1)};}

Should work without modification in both Java and C#.


答:
CJam, <s>7</s> 6 bytes

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

Online interpreter

This is an unnamed function that takes its arguments from the stack as S N, S being the string and N being the wraps. You can execute it with the ~ operator, meaning eval.

Explanation:

```<code>{{a}*}
{      Open block    [A B]
 {     Open block    [A]
  a    Wrap in array [[A]]
   }   Close block   [A B λwrap]
    *  Repeat        [A:wrap(*B)]
     } Close block   ["S" N λ(λwrap)repeat]
</code>```

Title: Nest a string inside an array n times

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

Body:
CJam, <s>7</s> 6 bytes

{{a}*}

Online interpreter

This is an unnamed function that takes its arguments from the stack as S N, S being the string and N being the wraps. You can execute it with the ~ operator, meaning eval.

Explanation:

{{a}*}
{      Open block    [A B]
 {     Open block    [A]
  a    Wrap in array [[A]]
   }   Close block   [A B λwrap]
    *  Repeat        [A:wrap(*B)]
     } Close block   ["S" N λ(λwrap)repeat]


答:
R, 108 bytes

Read input from stdin and prints to stdout

```<code>s=scan(,"");n=nchar(s);for(i in 1:n)cat(do.call("rep",list(strsplit(s,"")[[1]][i:n],1:(n-i+1))),"\n",sep="")
</code>```

I felt the use of do.call was appropriate here. It basically takes two inputs: 1. a function name in form of a string (rep here) and a list of arguments and 2. iteratively applies calls the function using the arguments in the list.

E.g.:

rep("c",3) produces the vector "c" "c" "c"

do.call("rep",list(c("a","b","c"),1:3)) produces the vector "a" "b" "b" "c" "c" "c"

which is equivalent to consecutively calling rep("a",1), rep("b",2) and rep("c",3)

Title: Exploded Suffixes

Body:
Given an ASCII string, output the exploded suffixes of it. For example, if the string was abcde, there are 5 suffixes, ordered longest to shortest:

```<code>abcde
bcde
cde
de
e
</code>```

Each suffix is then exploded, meaning each character is copied as many times as its one-indexed location in that suffix. For example, exploding the suffixes of abcde,

```<code>abcde
12345
abbcccddddeeeee

bcde
1234
bccdddeeee

cde
123
cddeee

de
12
dee

e
1
e
</code>```

Altogether, the exploded suffixes of abcde are

```<code>abbcccddddeeeee
bccdddeeee
cddeee
dee
e
</code>```

Rules

This is code-golf so the shortest code wins.

The input will consist of the printable ASCII characters. (This excludes newlines but includes spaces.)

The output will have each string on a separate line.

Trailing spaces are allowed on each line and there may be an extra newline at the end.

Test Cases

```<code>''

'a'
a

'bc'
bcc
c

'xyz'
xyyzzz
yzz
z

'code-golf'
coodddeeee-----ggggggooooooollllllllfffffffff
oddeee----gggggoooooolllllllffffffff
dee---ggggooooollllllfffffff
e--gggoooolllllffffff
-ggooollllfffff
goolllffff
ollfff
lff
f

's p a c e'
s  ppp    aaaaa      ccccccc        eeeeeeeee
 pp   aaaa     cccccc       eeeeeeee
p  aaa    ccccc      eeeeeee
 aa   cccc     eeeeee
a  ccc    eeeee
 cc   eeee
c  eee
 ee
e
</code>```

Body:
R, 108 bytes

Read input from stdin and prints to stdout

s=scan(,"");n=nchar(s);for(i in 1:n)cat(do.call("rep",list(strsplit(s,"")[[1]][i:n],1:(n-i+1))),"\n",sep="")

I felt the use of do.call was appropriate here. It basically takes two inputs: 1. a function name in form of a string (rep here) and a list of arguments and 2. iteratively applies calls the function using the arguments in the list.

E.g.:

rep("c",3) produces the vector "c" "c" "c"

do.call("rep",list(c("a","b","c"),1:3)) produces the vector "a" "b" "b" "c" "c" "c"

which is equivalent to consecutively calling rep("a",1), rep("b",2) and rep("c",3)


答:
Jellyfish, 8 bytes

```<code>p\Ai
 ;i
</code>```

Try it online!

Unary ; wraps its argument in a list. Binary \ on a function and a value n iterates that function n times.

Title: Nest a string inside an array n times

Body:
Jellyfish, 8 bytes

p\Ai
 ;i

Try it online!

Unary ; wraps its argument in a list. Binary \ on a function and a value n iterates that function n times.


答:
MATL, 6 bytes

```<code>ji:"Xh
</code>```

This produces a nested cell array as the output. With MATL's default display, however, you can't necessary see that's what it is since it won't show all of the curly braces. The demo below is a slightly modified version which shows the string representation of the output.

```<code>ji:"Xh]&D
</code>```

Try it Online

Explanation

```<code>j       % Explicitly grab the first input as a string
i       % Explicitly grab the second input as an integer (n)
:"      % Create an array [1...n] and loop through it
    Xh  % Each time through the loop place the entire stack into a cell array
        % Implicit end of for loop and display
</code>```

Title: Nest a string inside an array n times

Body:
MATL, 6 bytes

ji:"Xh

This produces a nested cell array as the output. With MATL's default display, however, you can't necessary see that's what it is since it won't show all of the curly braces. The demo below is a slightly modified version which shows the string representation of the output.

ji:"Xh]&D

Try it Online

Explanation

j       % Explicitly grab the first input as a string
i       % Explicitly grab the second input as an integer (n)
:"      % Create an array [1...n] and loop through it
    Xh  % Each time through the loop place the entire stack into a cell array
        % Implicit end of for loop and display


问:
Display a Connect Four game
Connect Four is a game where two players take turns to drop disks into columns of a vertically mounted grid, and attempt to connect four disks orthogonally or diagonally. When a column is chosen, the disk falls to the lowest empty position in that column, so any game may be completely specified by the size of the grid and the sequence of columns chosen. The task is to generate the configuration of the grid given this information.

Input

Width w and Height h of the grid, both positive integers.

Sequence of columns c1, c2, ..., cn chosen by the players, in any reasonable format (list, array etc.); either 0-based (0 to w-1) or 1-based (1 to w) indexing can be used.

It may be assumed that all of the column numbers lie within the grid (so the sequence won't contain -3 or w+50) and that any column number appears at most h times in the sequence (so a column can't be chosen once it is full).

Note that the sequence of columns may not constitute a complete game, nor a legal game. For instance, the players could opt to continue playing even after a player has connected four disks.

Output

Any reasonable representation of the resulting state of each position in the grid, either "occupied by Player 1", "occupied by Player 2", or "empty". Player 1 always moves first.

For example, a string, array, tuple etc. with each position containing one of three symbols (ASCII character, number etc.) representing the state of that position in the grid. The grid may be transposed.

For list/tuple/array outputs, the separator cannot be one of the three representative symbols. For string outputs, trailing spaces at the end of each line are permitted, provided a space is not one of the three representative symbols. Trailing newlines at the very end are permitted.

Test cases

Here, string output is used, with X, O, . denoting "occupied by Player 1", "occupied by Player 2", "empty".

```<code>IN: Width 1 Height 1 Sequence (empty sequence)
OUT:
.

IN: Width 7 Height 6 Sequence 4 4 5 5 6 7 3 [1-based]
                              3 3 4 4 5 6 2 [0-based]
OUT:
.......
.......
.......
.......
...OO..
..XXXXO

IN: Width 5 Height 5 Sequence 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 [1-based]
                              0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 [0-based]
OUT:
XOXOX
OXOXO
XOXOX
OXOXO
xOXOX

IN: Width 4 Height 4 Sequence 3 3 2 4 3 2 4 2 2 3 4 4 1 1 1 1 [1-based]
                              2 2 1 3 2 1 3 1 1 2 3 3 0 0 0 0 [0-based]
OUT:
OXOO
XOXX
OOOX
XXXO

IN: Width 10 Height 10 Sequence 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 1 10  [1-based]
                                0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0  9 0  9  [0-based]
OUT:
X.........
X.........
X.........
X.........
X.........
X.........
X.........
X.........
X........O
XOOOOOOOOO
</code>```

Shortest code in bytes wins.

答:
Python 2, <s>143</s> <s>131</s> 107 Bytes

This doesn't use any real fancy tricks, <s>except list transposition to make index access easier</s> since we can print the board transposed. Definitely not done with this just yet. Moves are taken as 0-based numbers. Byte count comes before commenting.

Jonathan Allan had a better approach to building the board, mine is improved slightly since the slicing is a bit shorter [-j:] -> [:j] and the list comprehension helps shorten printing.

i,j,k=input()                                     # split up the input
t=0                                               # keep track of whose move it is
g=i*['']                                          # board init
for b in k:g[b]+='XO'[t%2];t+=1                   # read moves sequentially, place pieces
print'\n'.join(''.join((m+'.'*j)[:j])for m in g)  # build the board
```

<p>Example Input: <code>[7, 6, [3, 3, 4, 4, 5, 6, 2]]</code></p>

<p>Example Output:</p>

<pre class="lang-py prettyprint-override"><code>......
......
X.....
XO....
XO....
X.....
O.....
</code>```

Try it online or view all test cases.

Title: Display a Connect Four game

Body:
Python 2, <s>143</s> <s>131</s> 107 Bytes

This doesn't use any real fancy tricks, <s>except list transposition to make index access easier</s> since we can print the board transposed. Definitely not done with this just yet. Moves are taken as 0-based numbers. Byte count comes before commenting.

Jonathan Allan had a better approach to building the board, mine is improved slightly since the slicing is a bit shorter [-j:] -> [:j] and the list comprehension helps shorten printing.

i,j,k=input()                                     # split up the input
t=0                                               # keep track of whose move it is
g=i*['']                                          # board init
for b in k:g[b]+='XO'[t%2];t+=1                   # read moves sequentially, place pieces
print'\n'.join(''.join((m+'.'*j)[:j])for m in g)  # build the board

Example Input: [7, 6, [3, 3, 4, 4, 5, 6, 2]]

Example Output:

......
......
X.....
XO....
XO....
X.....
O.....

Try it online or view all test cases.


答:
JavaScript (ES6), 20 bytes

```<code>d=>g=n=>n--?[g(n)]:d
</code>```

Although people normally nag me to curry my functions for the 1-byte saving, this is a case where it actually contributes to the solution.

Title: Nest a string inside an array n times

Body:
JavaScript (ES6), 20 bytes

d=>g=n=>n--?[g(n)]:d

Although people normally nag me to curry my functions for the 1-byte saving, this is a case where it actually contributes to the solution.


答:
PHP, 44 bytes

```<code>function n($s,$n){return$n?n([$s],--$n):$s;}
</code>```

nothing sophisticated, just a recursive function

Title: Nest a string inside an array n times

Body:
PHP, 44 bytes

function n($s,$n){return$n?n([$s],--$n):$s;}

nothing sophisticated, just a recursive function