问:
Expand a C array
In the C programming language, arrays are defined like this:

```<code>int foo[] = {4, 8, 15, 16, 23, 42};      //Foo implicitly has a size of 6
</code>```

The size of the array is inferred from the initializing elements, which in this case is 6. You can also write a C array this way, explicitly sizing it then defining each element in order:

```<code>int foo[6];        //Give the array an explicit size of 6
foo[0] = 4;
foo[1] = 8;
foo[2] = 15;
foo[3] = 16;
foo[4] = 23;
foo[5] = 42;
</code>```

The challenge

You must write a program or function that expands arrays from the first way to the second. Since you are writing a program to make code longer, and you love irony, you must make your code as short as possible.

The input will be a string representing the original array, and the output will be the expanded array-definition. You can safely assume that the input will always look like this:

```<code><type> <array_name>[] = {<int>, <int>, <int> ... };
</code>```

"Type" and "array_name" will made up entirely of alphabet characters and underscores _. The elements of the list will always be a number in the range -2,147,483,648 to 2,147,483,647. Inputs in any other format do not need to be handled.

The whitespace in your output must exactly match the whitespace in the test output, although a trailing newline is allowed.

Test IO:

```<code>#in
short array[] = {4, 3, 2, 1};

#out
short array[4];
array[0] = 4;
array[1] = 3;
array[2] = 2;
array[3] = 1;

#in
spam EGGS[] = {42};

#out
spam EGGS[1];
EGGS[0] = 42;

#in
terrible_long_type_name awful_array_name[] = {7, -8, 1337, 0, 13};

#out
terrible_long_type_name awful_array_name[5];
awful_array_name[0] = 7;
awful_array_name[1] = -8;
awful_array_name[2] = 1337;
awful_array_name[3] = 0;
awful_array_name[4] = 13;
</code>```

Submissions in any language are encouraged, but bonus points if you can do it in C.

Leaderboard:

Here is a leaderboard showing the top answers:

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Python 2, 159 bytes

s=input().split()
t,n,v=s[0],s[1][:-2],''.join(s[3:])
a=v[1:-2].split(',')
print'%s %s[%d];'%(t,n,len(a))
for i in range(len(a)):print'%s[%d] = %s;'%(n,i,a[i])
```

Try it online

Thanks Kevin Lau for some golfing suggestions

Title: Expand a C array

Body:
Python 2, 159 bytes

s=input().split()
t,n,v=s[0],s[1][:-2],''.join(s[3:])
a=v[1:-2].split(',')
print'%s %s[%d];'%(t,n,len(a))
for i in range(len(a)):print'%s[%d] = %s;'%(n,i,a[i])

Try it online

Thanks Kevin Lau for some golfing suggestions


答:
Ruby, <s>127</s> <s>110</s> <s>108</s> <s>99</s> 88 bytes

<s>Anonymous function with a single argument as input.</s> Full program, reads the input from STDIN. (If you pipe a file in, the trailing newline is optional.) <s>Returns</s> Prints the output string.

Took @TimmyD bragging about their solution beating all other non-esolangs as a challenge, and finally overcome the (at the time of writing) 114 byte Powershell solution they had posted. <s>Cᴏɴᴏʀ O'Bʀɪᴇɴ's trick with splitting on ] and splicing the second half to get the numbers helped.</s>

I need to use the splat operator more. It's so useful!

Borrowed a trick from @Neil's JavaScript ES6 answer to save more bytes by scanning for words instead of using gsub and split..

```<code>t,n,*l=gets.scan /-?\w+/;i=-1
puts t+" #{n}[#{l.size}];",l.map{|e|n+"[#{i+=1}] = #{e};"}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Expand a C array

Body:
In the C programming language, arrays are defined like this:

```<code>int foo[] = {4, 8, 15, 16, 23, 42};      //Foo implicitly has a size of 6
</code>```

The size of the array is inferred from the initializing elements, which in this case is 6. You can also write a C array this way, explicitly sizing it then defining each element in order:

```<code>int foo[6];        //Give the array an explicit size of 6
foo[0] = 4;
foo[1] = 8;
foo[2] = 15;
foo[3] = 16;
foo[4] = 23;
foo[5] = 42;
</code>```

The challenge

You must write a program or function that expands arrays from the first way to the second. Since you are writing a program to make code longer, and you love irony, you must make your code as short as possible.

The input will be a string representing the original array, and the output will be the expanded array-definition. You can safely assume that the input will always look like this:

```<code><type> <array_name>[] = {<int>, <int>, <int> ... };
</code>```

"Type" and "array_name" will made up entirely of alphabet characters and underscores _. The elements of the list will always be a number in the range -2,147,483,648 to 2,147,483,647. Inputs in any other format do not need to be handled.

The whitespace in your output must exactly match the whitespace in the test output, although a trailing newline is allowed.

Test IO:

```<code>#in
short array[] = {4, 3, 2, 1};

#out
short array[4];
array[0] = 4;
array[1] = 3;
array[2] = 2;
array[3] = 1;

#in
spam EGGS[] = {42};

#out
spam EGGS[1];
EGGS[0] = 42;

#in
terrible_long_type_name awful_array_name[] = {7, -8, 1337, 0, 13};

#out
terrible_long_type_name awful_array_name[5];
awful_array_name[0] = 7;
awful_array_name[1] = -8;
awful_array_name[2] = 1337;
awful_array_name[3] = 0;
awful_array_name[4] = 13;
</code>```

Submissions in any language are encouraged, but bonus points if you can do it in C.

Leaderboard:

Here is a leaderboard showing the top answers:

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Ruby, <s>127</s> <s>110</s> <s>108</s> <s>99</s> 88 bytes

<s>Anonymous function with a single argument as input.</s> Full program, reads the input from STDIN. (If you pipe a file in, the trailing newline is optional.) <s>Returns</s> Prints the output string.

Took @TimmyD bragging about their solution beating all other non-esolangs as a challenge, and finally overcome the (at the time of writing) 114 byte Powershell solution they had posted. <s>Cᴏɴᴏʀ O'Bʀɪᴇɴ's trick with splitting on ] and splicing the second half to get the numbers helped.</s>

I need to use the splat operator more. It's so useful!

Borrowed a trick from @Neil's JavaScript ES6 answer to save more bytes by scanning for words instead of using gsub and split..

t,n,*l=gets.scan /-?\w+/;i=-1
puts t+" #{n}[#{l.size}];",l.map{|e|n+"[#{i+=1}] = #{e};"}


答:
Julia, <s>154</s> <s>134</s> 101 bytes

f(s,c=matchall(r"-?\w+",s),n=endof(c)-2)=c[]" "c[2]"[$n];
"join([c[2]"[$i] = "c[i+3]";
"for i=0:n-1])
```

<p>This is a function that accepts a string and returns a string with a single trailing newline.</p>

<p>Ungolfed:</p>

<pre class="lang-default prettyprint-override"><code>function f(s, c = matchall(r"-?\w+", s), n = endof(c) - 2)
    c[] " " c[2] "[$n];\n" join([c[2] "[$i] = " x[i+3] ";\n" for i = 0:n-1])
end
</code>```

We define c to be an array of matches of the input on the regular expression -?\w+. It caputres the type, array name, then each value. We store n as the length of c - 2, which is the number of values. The output is constructed as the type, name and length string interpolated, combined with each definition line separated by newlines. For whatever reason, c[] is the same as c[1].

Saved 32 bytes with help from Dennis!

Title: Expand a C array

Body:
Julia, <s>154</s> <s>134</s> 101 bytes

f(s,c=matchall(r"-?\w+",s),n=endof(c)-2)=c[]" "c[2]"[$n];
"join([c[2]"[$i] = "c[i+3]";
"for i=0:n-1])

This is a function that accepts a string and returns a string with a single trailing newline.

Ungolfed:

function f(s, c = matchall(r"-?\w+", s), n = endof(c) - 2)
    c[] " " c[2] "[$n];\n" join([c[2] "[$i] = " x[i+3] ";\n" for i = 0:n-1])
end

We define c to be an array of matches of the input on the regular expression -?\w+. It caputres the type, array name, then each value. We store n as the length of c - 2, which is the number of values. The output is constructed as the type, name and length string interpolated, combined with each definition line separated by newlines. For whatever reason, c[] is the same as c[1].

Saved 32 bytes with help from Dennis!


答:
Pyth - <s>53</s> <s>50</s> <s>46</s> <s>45</s> 44 bytes

2 bytes saved thanks to @FryAmTheEggman.

```<code>+Jhcz\[+`]lKcPecz\{d\;j.es[ecJd`]kd\=dPb\;)K
</code>```

Test Suite.

Title: Expand a C array

Body:
Pyth - <s>53</s> <s>50</s> <s>46</s> <s>45</s> 44 bytes

2 bytes saved thanks to @FryAmTheEggman.

+Jhcz\[+`]lKcPecz\{d\;j.es[ecJd`]kd\=dPb\;)K

Test Suite.


答:
Vim, <s>54, 52, 49</s> 47 keystrokes

```<code>2wa0<esc>qqYp<c-a>6ldf @qq@q$dT]dd:%norm dwf{xwC;<CR>gg"0P
</code>```

Explanation:

```<code>2wa0<esc>                     'Move 2 words forward, and insert a 0.
         qq                   'Start recording in register Q
           Yp                 'Duplicate the line
             <c-a>6l          'Increment the next number then move 6 spaces right
                    df        'Delete until the next space
                       @qq@q  'Recursively call this macro
</code>```

Now our buffer looks like this:

```<code>int foo[0] = {4, 8, 15, 16, 23, 42};
int foo[1] = {8, 15, 16, 23, 42};
int foo[2] = {15, 16, 23, 42};
int foo[3] = {16, 23, 42};
int foo[4] = {23, 42};
int foo[5] = {42};
int foo[6] = {42};
</code>```

and our cursor is on the last line.

Second half:

```<code>$                           'Move to the end of the line
 dT]                        'Delete back until we hit a ']'
    dd                      'Delete this whole line.
      :%norm         <CR>   'Apply the following keystrokes to every line:
             dw             'Delete a word (in this case "int")
               f{x          '(f)ind the next '{', then delete it.
                  wC;       'Move a word, then (C)hange to the end of this line,
                            'and enter a ';'

</code>```

Now everything looks good, we just need to add the original array-declaration. So we do:

```<code>gg        'Move to line one
  "0P     'Print buffer '0' behind us. Buffer '0' always holds the last deleted line,
          'Which in this case is "int foo[6];"
</code>```

Title: Expand a C array

Body:
Vim, <s>54, 52, 49</s> 47 keystrokes

2wa0<esc>qqYp<c-a>6ldf @qq@q$dT]dd:%norm dwf{xwC;<CR>gg"0P

Explanation:

2wa0<esc>                     'Move 2 words forward, and insert a 0.
         qq                   'Start recording in register Q
           Yp                 'Duplicate the line
             <c-a>6l          'Increment the next number then move 6 spaces right
                    df        'Delete until the next space
                       @qq@q  'Recursively call this macro

Now our buffer looks like this:

int foo[0] = {4, 8, 15, 16, 23, 42};
int foo[1] = {8, 15, 16, 23, 42};
int foo[2] = {15, 16, 23, 42};
int foo[3] = {16, 23, 42};
int foo[4] = {23, 42};
int foo[5] = {42};
int foo[6] = {42};

and our cursor is on the last line.

Second half:

$                           'Move to the end of the line
 dT]                        'Delete back until we hit a ']'
    dd                      'Delete this whole line.
      :%norm         <CR>   'Apply the following keystrokes to every line:
             dw             'Delete a word (in this case "int")
               f{x          '(f)ind the next '{', then delete it.
                  wC;       'Move a word, then (C)hange to the end of this line,
                            'and enter a ';'

Now everything looks good, we just need to add the original array-declaration. So we do:

gg        'Move to line one
  "0P     'Print buffer '0' behind us. Buffer '0' always holds the last deleted line,
          'Which in this case is "int foo[6];"


答:
05AB1E, <s>52</s> <s>50</s> 47 bytes

Code:

```<code>… = ¡`¦¨¨ð-',¡©gr¨s«„];«,®v¹ð¡¦¬s\¨N"] = "y';J,
</code>```

Uses CP-1252 encoding. Try it online!.

Title: Expand a C array

Body:
05AB1E, <s>52</s> <s>50</s> 47 bytes

Code:

… = ¡`¦¨¨ð-',¡©gr¨s«„];«,®v¹ð¡¦¬s\¨N"] = "y';J,

Uses CP-1252 encoding. Try it online!.


Title: Expand a C array

Body:
JavaScript ES6, <s>134</s> <s>132</s> <s>130</s> 129 bytes

Saved 1 byte thanks to Neil.

x=>(m=x.match(/(\w+) (\w+).+{(.+)}/),m[1]+` `+(q=m[2])+`[${q.length-1}];
`+m[3].split`, `.map((t,i)=>q+`[${i}] = ${t};`).join`
`)


答:
Retina, <s>108</s> <s>104</s> <s>100</s> 69 bytes

Byte count assumes ISO 8859-1 encoding.

```<code>].+{((\S+ ?)+)
$#2];$1
+`((\w+\[).+;(\S+ )*)(-?\d+).+
$1¶$2$#3] = $4;
</code>```

Beat this, PowerShell...

Code explanation

First line: ].+{((\S+ ?)+)

First, we need to keep the type, array name, and opening bracket (it saves a byte), so we don't match them. So we match the closing bracket, any number of characters, and an opening curly brace: ].+{. Then we match the number list. Shortest I've been able to find so far is this: ((\S+ ?)+). We match any number of non-space characters (this includes numbers, possible negative sign, and possible comma), followed by a space, that may or may not be there: \S+ ?. This group of characters is then repeated as many times as needed: (\S+ ?)+ and put into the large capturing group. Note that we don't match the closing curly brace or semicolon. Third line explanation tells why.

Second line: $#2];$1

Since we only matched a part of input, the unmatched parts will still be there. So we put the length of the list after the unmatched opening bracket: $#2. The replace modifier # helps us with that, as it gives us the number of matches a particular capturing group made. In this case capturing group 2. Then we put a closing bracket and a semicolon, and finally our whole list.

With input short array[] = {4, 3, 2, 1};, the internal representation after this replacing is:

```short array[4];4, 3, 2, 1};```

(note the closing curly brace and semicolon)

Third line: +`((\w+[).+;(\S+ )*)(-?\d+).+

This is a looped section. That means it runs until no stage in the loop makes a change to the input. First we match the array name, followed by an opening bracket: (\w+\[). Then an arbitrary number of any characters and a semicolon: .+;. Then we match the list again, but this time only numbers and the comma after each number, which have a space following them: (\S+ )*. Then we capture the last number in the list: (-?\d+) and any remaining characters behind it: .+.

Fourth line: $1¶$2$#3] = $4;

We then replace it with the array name and list followed by a newline: $1¶. Next, we put the array name, followed by the length of previously matched list, without the last element (essentially list.length - 1): $2$#3. Followed by a closing bracket and assigment operator with spaces, and this followed by the last element of our number list: ] = $4;

After first replacing, the internal representation looks like this:

```<code>short array[4];4, 3, 2,
array[3] = 1;
</code>```

Note that the closing curly brace and the semicolon disappeared, thanks to the .+ at the end of third line.
After three more replacings, the internal representation looks like this:

```<code>short array[4];
array[0] = 4;
array[1] = 3;
array[2] = 2;
array[3] = 1;
</code>```

Since there's nothing more to match by third line, fourth doesn't replace anything and the string is returned.

TL;DR: First we change up the int list format a bit. Then we take the last element of the list and the name, and put them after the array initialization. We do this until the int list is empty. Then we give the changed code back.

Try it online!

Title: Expand a C array

Body:
Retina, <s>108</s> <s>104</s> <s>100</s> 69 bytes

Byte count assumes ISO 8859-1 encoding.

].+{((\S+ ?)+)
$#2];$1
+`((\w+\[).+;(\S+ )*)(-?\d+).+
$1¶$2$#3] = $4;

Beat this, PowerShell...

Code explanation

First line: ].+{((\S+ ?)+)

First, we need to keep the type, array name, and opening bracket (it saves a byte), so we don't match them. So we match the closing bracket, any number of characters, and an opening curly brace: ].+{. Then we match the number list. Shortest I've been able to find so far is this: ((\S+ ?)+). We match any number of non-space characters (this includes numbers, possible negative sign, and possible comma), followed by a space, that may or may not be there: \S+ ?. This group of characters is then repeated as many times as needed: (\S+ ?)+ and put into the large capturing group. Note that we don't match the closing curly brace or semicolon. Third line explanation tells why.

Second line: $#2];$1

Since we only matched a part of input, the unmatched parts will still be there. So we put the length of the list after the unmatched opening bracket: $#2. The replace modifier # helps us with that, as it gives us the number of matches a particular capturing group made. In this case capturing group 2. Then we put a closing bracket and a semicolon, and finally our whole list.

With input short array[] = {4, 3, 2, 1};, the internal representation after this replacing is:

short array[4];4, 3, 2, 1};

(note the closing curly brace and semicolon)

Third line: +`((\w+[).+;(\S+ )*)(-?\d+).+

This is a looped section. That means it runs until no stage in the loop makes a change to the input. First we match the array name, followed by an opening bracket: (\w+\[). Then an arbitrary number of any characters and a semicolon: .+;. Then we match the list again, but this time only numbers and the comma after each number, which have a space following them: (\S+ )*. Then we capture the last number in the list: (-?\d+) and any remaining characters behind it: .+.

Fourth line: $1¶$2$#3] = $4;

We then replace it with the array name and list followed by a newline: $1¶. Next, we put the array name, followed by the length of previously matched list, without the last element (essentially list.length - 1): $2$#3. Followed by a closing bracket and assigment operator with spaces, and this followed by the last element of our number list: ] = $4;

After first replacing, the internal representation looks like this:

short array[4];4, 3, 2,
array[3] = 1;

Note that the closing curly brace and the semicolon disappeared, thanks to the .+ at the end of third line.
After three more replacings, the internal representation looks like this:

short array[4];
array[0] = 4;
array[1] = 3;
array[2] = 2;
array[3] = 1;

Since there's nothing more to match by third line, fourth doesn't replace anything and the string is returned.

TL;DR: First we change up the int list format a bit. Then we take the last element of the list and the name, and put them after the array initialization. We do this until the int list is empty. Then we give the changed code back.

Try it online!


答:
MATL, <s>68</s> <s>64</s> 58 bytes

```<code>'\w+'XX2:H#)XKxXIZc'['KnV'];'v!K"I2X)'['X@qV'] = '@g';'6$h
</code>```

This isn't C, <s>but it does use C-like sprintf function</s> Nah, that was wasting 4 bytes.

Try it online!

```<code>          % Take input implicitly
'\w+'XX   % Find substrings that match regex '\w+'. Gives a cell array
2:H#)     % Split into a subarray with the first two substrings (type and name), and
          % another with the rest (numbers that form the array)
XKx       % Copy the latter (numbers) into clipboard K. Delete it
XI        % Copy the former (type and name) into clipboard I
Zc        % Join the first two substrings with a space
'['       % Push this string
K         % Paste array of numbers
nV        % Get its length. Convert to string
'];'      % Push this string
v!        % Concatenate all strings up to now. Gives first line of the output
K"        % For each number in the array
  I2X)    %   Get name of array as a string
  '['     %   Push this string
  X@qV    %   Current iteration index, starting at 0, as a string
  '] = '  %   Push this string
  @g      %   Current number of the array, as a string
  ';'     %   Push this string
  5$h     %   Concatenate top 6 strings. This is a line of the output
          % Implicity end for each
          % Implicitly display
</code>```

Title: Expand a C array

Body:
MATL, <s>68</s> <s>64</s> 58 bytes

'\w+'XX2:H#)XKxXIZc'['KnV'];'v!K"I2X)'['X@qV'] = '@g';'6$h

This isn't C, <s>but it does use C-like sprintf function</s> Nah, that was wasting 4 bytes.

Try it online!

          % Take input implicitly
'\w+'XX   % Find substrings that match regex '\w+'. Gives a cell array
2:H#)     % Split into a subarray with the first two substrings (type and name), and
          % another with the rest (numbers that form the array)
XKx       % Copy the latter (numbers) into clipboard K. Delete it
XI        % Copy the former (type and name) into clipboard I
Zc        % Join the first two substrings with a space
'['       % Push this string
K         % Paste array of numbers
nV        % Get its length. Convert to string
'];'      % Push this string
v!        % Concatenate all strings up to now. Gives first line of the output
K"        % For each number in the array
  I2X)    %   Get name of array as a string
  '['     %   Push this string
  X@qV    %   Current iteration index, starting at 0, as a string
  '] = '  %   Push this string
  @g      %   Current number of the array, as a string
  ';'     %   Push this string
  5$h     %   Concatenate top 6 strings. This is a line of the output
          % Implicity end for each
          % Implicitly display


问:
Sort an Integer List

The Challenge

It's quite simple really, sort a list of numbers.

Details

You must sort a list of numbers in ascending order, without using any built-in sorting functions/libraries/etc (i.e. list.sort() in Python).

Input/output can be done in any method you choose, as long as it is human readable.

Standard loopholes are disallowed as always.

Shortest code in bytes wins.

You must explain/list what sort method you used (Bubble, Insertion, Selection, etc.)

Input will not contain duplicates.

Sample Input/Output

Input: 99,-2,53,4,67,55,23,43,88,-22,36,45

Output: -22,-2,4,23,36,43,45,53,55,67,88,99

Note: A near direct opposite of Sort a List of Numbers

答:
Ruby, 40 bytes

Selection sort. Anonymous function; takes the list as argument.

```<code>->a{r=[];r<<a.delete(a.min)while[]!=a;r}
</code>```

Title: Sort an Integer List

Body:
Ruby, 40 bytes

Selection sort. Anonymous function; takes the list as argument.

->a{r=[];r<<a.delete(a.min)while[]!=a;r}


问:
Numbers with Rotational Symmetry
Given an integer, output a truthy value if it is the same upside-down (rotated 180°) or a falsy value otherwise.

0, 1, and 8 have rotational symmetry. 6 becomes 9 and vice versa.

Sequence of numbers producing truthy results: OEIS A000787

```<code>0, 1, 8, 11, 69, 88, 96, 101, 111, 181, 609, 619, 689, 808, 818, 888, 906, 916, 986, 1001, 1111, 1691, 1881, 1961, 6009, 6119, 6699, 6889, 6969, 8008, 8118, 8698, 8888, 8968, 9006, 9116, 9696, 9886, 9966, 10001, 10101, 10801, 11011, 11111, 11811, 16091, ...
</code>```

This question is inspired by my own reputation at the time of posting: 6009.

答:
05AB1E, <s>22</s> <s>16</s> <s>15</s> 14 bytes

Code:

```<code>Â23457ð«-69Â‡Q
</code>```

Try it online!

Previous code:

```<code>Â69Â‡Q¹¹„vd•ÃQ*
</code>```

To figure out if the string is rotational symmetric, we just need to transliterate 69 with 96, reverse the string and check if they are equal. The other thing we need to know is if the number only contains the digits 0, 1, 8, 6 and 9. So that's exactly what we are going to do:

```<code>Â                     # Bifurcate the input, which pushes input and input[::-1]
 69Â                  # Bifurcate 69, which pushes 69 and 96.
    ‡                 # Transliterate 69 with 96 in the input, e.g. 1299 becomes 1266.
     Q                # Check for equality.
      ¹¹              # Push input again twice.
        „vd•          # Compressed version for 10869.
</code>```

The „vd• part actually converts the string vd from base 190 to base 10. You can try this out here.

```<code>            Ã        # Keep the characters of the second string in the first string.
                       667788 would become 6688 (since 7 is not in 10869).
             Q       # Check for equality.
              *      # Multiply the top two numbers, which actually does an AND function.
</code>```

Uses CP-1252 encoding. Try it online!

ContentLicense: CC BY-SA 4.0

Title: Numbers with Rotational Symmetry

Body:
05AB1E, <s>22</s> <s>16</s> <s>15</s> 14 bytes

Code:

Â23457ð«-69Â‡Q

Try it online!

Previous code:

Â69Â‡Q¹¹„vd•ÃQ*

To figure out if the string is rotational symmetric, we just need to transliterate 69 with 96, reverse the string and check if they are equal. The other thing we need to know is if the number only contains the digits 0, 1, 8, 6 and 9. So that's exactly what we are going to do:

Â                     # Bifurcate the input, which pushes input and input[::-1]
 69Â                  # Bifurcate 69, which pushes 69 and 96.
    ‡                 # Transliterate 69 with 96 in the input, e.g. 1299 becomes 1266.
     Q                # Check for equality.
      ¹¹              # Push input again twice.
        „vd•          # Compressed version for 10869.

The „vd• part actually converts the string vd from base 190 to base 10. You can try this out here.

            Ã        # Keep the characters of the second string in the first string.
                       667788 would become 6688 (since 7 is not in 10869).
             Q       # Check for equality.
              *      # Multiply the top two numbers, which actually does an AND function.

Uses CP-1252 encoding. Try it online!


答:
GNU sed, 84 bytes

(including +1 for -r flag)

```<code>:
s/^6(.*)9$/\1/
s/^9(.*)6$/\1/
s/^([081])(.*)\1$/\2/
t
s/^[081]$//
s/.+/0/
s/^$/1/
</code>```

If the line ends with a rotation of its beginning character, trim both ends by one.  Repeat until there's no match.  Account for a single symmetric character, then if anything remains, the input was not symmetric, and we return false; otherwise return true.

Title: Numbers with Rotational Symmetry

Body:
Given an integer, output a truthy value if it is the same upside-down (rotated 180°) or a falsy value otherwise.

0, 1, and 8 have rotational symmetry. 6 becomes 9 and vice versa.

Sequence of numbers producing truthy results: OEIS A000787

```<code>0, 1, 8, 11, 69, 88, 96, 101, 111, 181, 609, 619, 689, 808, 818, 888, 906, 916, 986, 1001, 1111, 1691, 1881, 1961, 6009, 6119, 6699, 6889, 6969, 8008, 8118, 8698, 8888, 8968, 9006, 9116, 9696, 9886, 9966, 10001, 10101, 10801, 11011, 11111, 11811, 16091, ...
</code>```

This question is inspired by my own reputation at the time of posting: 6009.

Body:
GNU sed, 84 bytes

(including +1 for -r flag)

:
s/^6(.*)9$/\1/
s/^9(.*)6$/\1/
s/^([081])(.*)\1$/\2/
t
s/^[081]$//
s/.+/0/
s/^$/1/

If the line ends with a rotation of its beginning character, trim both ends by one.  Repeat until there's no match.  Account for a single symmetric character, then if anything remains, the input was not symmetric, and we return false; otherwise return true.


问:
Tips for golfing in Ruby
What general tips can you give for golfing in Ruby?

I'm looking for ideas that can be applied to code golf problems in general that are specific to Ruby. (For example, "Remove comments" would not be an answer.)

Please post one tip per answer.

答:
<< trick

```<code>a.push x
</code>```

can be shortened to:

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

for -4 bytes.

Title: Tips for golfing in Ruby

Body:
<< trick

a.push x

can be shortened to:

a<<x

for -4 bytes.


答:
Python 2, 34 bytes

def f(s):m=min(s);print m;f(s-{m})
```
<p>Takes input as a set, printing its elements in increasing order, terminating with error.</p>
<p>A clean termination can be done in 41 bytes:</p>
<pre class="lang-python prettyprint-override"><code>def f(s):
 if s:m=min(s);print m;f(s-{m})
</code>```

or

l=input()
while l:m=min(l);print m;l-={m}
```
<p>The input can be take as a list for 39 bytes, or 38 bytes in Python 3.5:</p>
<pre class="lang-python prettyprint-override"><code>def f(l):m=min(l);print m;f(set(l)-{m})
def f(l):m=min(l);print(m);f({*l}-{m})
</code>```

Title: Sort an Integer List

Body:
The Challenge

It's quite simple really, sort a list of numbers.

Details

You must sort a list of numbers in ascending order, without using any built-in sorting functions/libraries/etc (i.e. list.sort() in Python).

Input/output can be done in any method you choose, as long as it is human readable.

Standard loopholes are disallowed as always.

Shortest code in bytes wins.

You must explain/list what sort method you used (Bubble, Insertion, Selection, etc.)

Input will not contain duplicates.

Sample Input/Output

Input: 99,-2,53,4,67,55,23,43,88,-22,36,45

Output: -22,-2,4,23,36,43,45,53,55,67,88,99

Note: A near direct opposite of Sort a List of Numbers

Body:
Python 2, 34 bytes

def f(s):m=min(s);print m;f(s-{m})

Takes input as a set, printing its elements in increasing order, terminating with error.

A clean termination can be done in 41 bytes:

def f(s):
 if s:m=min(s);print m;f(s-{m})

or

l=input()
while l:m=min(l);print m;l-={m}

The input can be take as a list for 39 bytes, or 38 bytes in Python 3.5:

def f(l):m=min(l);print m;f(set(l)-{m})
def f(l):m=min(l);print(m);f({*l}-{m})


答:
PowerShell v2+, <s>114</s> 105 bytes

```<code>$a,$b,$c,$d=-split$args-replace'\[]';"$a $b[$(($d=-join$d|iex|iex).length)];";$d|%{"$b[$(($i++))] = $_;"}
</code>```

Takes input string $args and -replaces the square bracket with nothing, then performs a -split on whitespace. We store the first bit into $a, the second bit into $b, the = into $c, and the array elements into $d. For the example below, this stores foo into $a and bar into $b, and all of the array into $d.

We then output our first line with "$a ..." and in the middle transform $d from a an array of strings of form {1,,2,,...100}; to a regular int array by -joining it together into one string, then running it through iex twice (similar to eval). We store that resultant array back in $d before calling the .length method to populate the appropriate number in between the [] in the output line.

We then send $d through a loop with |%{...}. Each iteration we output "$b..." with a counter variable $i encapsulated in brackets and the current value $_. The $i variable starts uninitialized (equivalent to $null) but the ++ will cast it to an int before the output, so it will start output at 0, all before incrementing $i for the next loop iteration.

All output lines are left on the pipeline, and output to the terminal is implicit at program termination.

Example

```<code>PS C:\Tools\Scripts\golfing> .\expand-a-c-array.ps1 "foo bar[] = {1, 2, 3, -99, 100};"
foo bar[5];
bar[0] = 1;
bar[1] = 2;
bar[2] = 3;
bar[3] = -99;
bar[4] = 100;
</code>```

Title: Expand a C array

Body:
PowerShell v2+, <s>114</s> 105 bytes

$a,$b,$c,$d=-split$args-replace'\[]';"$a $b[$(($d=-join$d|iex|iex).length)];";$d|%{"$b[$(($i++))] = $_;"}

Takes input string $args and -replaces the square bracket with nothing, then performs a -split on whitespace. We store the first bit into $a, the second bit into $b, the = into $c, and the array elements into $d. For the example below, this stores foo into $a and bar into $b, and all of the array into $d.

We then output our first line with "$a ..." and in the middle transform $d from a an array of strings of form {1,,2,,...100}; to a regular int array by -joining it together into one string, then running it through iex twice (similar to eval). We store that resultant array back in $d before calling the .length method to populate the appropriate number in between the [] in the output line.

We then send $d through a loop with |%{...}. Each iteration we output "$b..." with a counter variable $i encapsulated in brackets and the current value $_. The $i variable starts uninitialized (equivalent to $null) but the ++ will cast it to an int before the output, so it will start output at 0, all before incrementing $i for the next loop iteration.

All output lines are left on the pipeline, and output to the terminal is implicit at program termination.

Example

PS C:\Tools\Scripts\golfing> .\expand-a-c-array.ps1 "foo bar[] = {1, 2, 3, -99, 100};"
foo bar[5];
bar[0] = 1;
bar[1] = 2;
bar[2] = 3;
bar[3] = -99;
bar[4] = 100;


答:
Seriously, 6 bytes

```<code>,;l@╨m
</code>```

Try it online!

This does the same thing as many other answers: generate all permutations, select minimum. I kinda forgot that this would work while I was working on the below solution.

Explanation:

```<code>,;l@╨m
,;l@    push len(input), input
    ╨m  minimum permutation
</code>```

Seriously, 25 bytes (non-competing)

This would be competitive if it wasn't for a bug in the shuffle command that I just fixed.

```<code>,1WX╚;;pX@dXZ`i@-0<`MπYWX
</code>```

Try it online!
This implements the best sorting algorithm ever: Bogosort!

Explanation:

```<code>,1WX╚;;pX@dXZ`i@-0<`MπYWX
,                          get input
 1W                    WX  do-while:
   X                         discard
    ╚                        shuffle
     ;;                      dupe twice
       pX@dX                 remove first element of first dupe and last element of second dupe
            Z                zip
             `i@-0<`MπY      test if all differences are positive (if any are not, the list is not sorted), negate (1 if not sorted else 0)
</code>```

Title: Sort an Integer List

Body:
Seriously, 6 bytes

,;l@╨m

Try it online!

This does the same thing as many other answers: generate all permutations, select minimum. I kinda forgot that this would work while I was working on the below solution.

Explanation:

,;l@╨m
,;l@    push len(input), input
    ╨m  minimum permutation

Seriously, 25 bytes (non-competing)

This would be competitive if it wasn't for a bug in the shuffle command that I just fixed.

,1WX╚;;pX@dXZ`i@-0<`MπYWX

Try it online!
This implements the best sorting algorithm ever: Bogosort!

Explanation:

,1WX╚;;pX@dXZ`i@-0<`MπYWX
,                          get input
 1W                    WX  do-while:
   X                         discard
    ╚                        shuffle
     ;;                      dupe twice
       pX@dX                 remove first element of first dupe and last element of second dupe
            Z                zip
             `i@-0<`MπY      test if all differences are positive (if any are not, the list is not sorted), negate (1 if not sorted else 0)


答:
Pyth - 21 bytes

```<code>&!-z+`180K`69qzX_z_KK
</code>```

Test Suite.

Title: Numbers with Rotational Symmetry

Body:
Pyth - 21 bytes

&!-z+`180K`69qzX_z_KK

Test Suite.


答:
Java 8, <s>112</s> 92 bytes

Here is another selection sort. The input is a List t of integers and the sorted output is printed to standard out.

t->{for(;0<t.size();System.out.println(t.remove(t.indexOf(java.util.Collections.min(t)))));}
```

Update

-20 [16-08-21] Used a lambda

Title: Sort an Integer List

Body:
Java 8, <s>112</s> 92 bytes

Here is another selection sort. The input is a List t of integers and the sorted output is printed to standard out.

t->{for(;0<t.size();System.out.println(t.remove(t.indexOf(java.util.Collections.min(t)))));}

Update

-20 [16-08-21] Used a lambda


答:
Python 3.6 (pre-release), 133

m,p=str.split,print;y,u=m(input(),'[');t,n=m(y);i=m(u[5:-2],', ')
l=len(i);p(t,n+f'[{l}];')
for x in range(l):p(n+f'[{x}] = {i[x]};')
```
<p>Makes heavy use of f-strings.</p>
<p>Ungolfed version:</p>
<pre class="lang-python prettyprint-override"><code>y, u = input().split('[')
t, n = y.split()
i = u[5:-2].split(', ')
l = len(i)
print(t, n + f'[{l}];')
for x in range(l):
    print(n + f'[{x}] = {i[x]};')
</code>```

Title: Expand a C array

Body:
In the C programming language, arrays are defined like this:

```<code>int foo[] = {4, 8, 15, 16, 23, 42};      //Foo implicitly has a size of 6
</code>```

The size of the array is inferred from the initializing elements, which in this case is 6. You can also write a C array this way, explicitly sizing it then defining each element in order:

```<code>int foo[6];        //Give the array an explicit size of 6
foo[0] = 4;
foo[1] = 8;
foo[2] = 15;
foo[3] = 16;
foo[4] = 23;
foo[5] = 42;
</code>```

The challenge

You must write a program or function that expands arrays from the first way to the second. Since you are writing a program to make code longer, and you love irony, you must make your code as short as possible.

The input will be a string representing the original array, and the output will be the expanded array-definition. You can safely assume that the input will always look like this:

```<code><type> <array_name>[] = {<int>, <int>, <int> ... };
</code>```

"Type" and "array_name" will made up entirely of alphabet characters and underscores _. The elements of the list will always be a number in the range -2,147,483,648 to 2,147,483,647. Inputs in any other format do not need to be handled.

The whitespace in your output must exactly match the whitespace in the test output, although a trailing newline is allowed.

Test IO:

```<code>#in
short array[] = {4, 3, 2, 1};

#out
short array[4];
array[0] = 4;
array[1] = 3;
array[2] = 2;
array[3] = 1;

#in
spam EGGS[] = {42};

#out
spam EGGS[1];
EGGS[0] = 42;

#in
terrible_long_type_name awful_array_name[] = {7, -8, 1337, 0, 13};

#out
terrible_long_type_name awful_array_name[5];
awful_array_name[0] = 7;
awful_array_name[1] = -8;
awful_array_name[2] = 1337;
awful_array_name[3] = 0;
awful_array_name[4] = 13;
</code>```

Submissions in any language are encouraged, but bonus points if you can do it in C.

Leaderboard:

Here is a leaderboard showing the top answers:

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Python 3.6 (pre-release), 133

m,p=str.split,print;y,u=m(input(),'[');t,n=m(y);i=m(u[5:-2],', ')
l=len(i);p(t,n+f'[{l}];')
for x in range(l):p(n+f'[{x}] = {i[x]};')

Makes heavy use of f-strings.

Ungolfed version:

y, u = input().split('[')
t, n = y.split()
i = u[5:-2].split(', ')
l = len(i)
print(t, n + f'[{l}];')
for x in range(l):
    print(n + f'[{x}] = {i[x]};')


答:
C, 72 bytes

```<code>i,j;a(int*l,int n){for(i=0;i=i?:--n;j>l[n]?l[i]=l[n],l[n]=j:0)j=l[--i];}
</code>```

Bubblesort. The first argument is a pointer to the array, the second argument is the length of the array. Works with gcc.

Title: Sort an Integer List

Body:
C, 72 bytes

i,j;a(int*l,int n){for(i=0;i=i?:--n;j>l[n]?l[i]=l[n],l[n]=j:0)j=l[--i];}

Bubblesort. The first argument is a pointer to the array, the second argument is the length of the array. Works with gcc.


答:
Jolf, 13 bytes

Uses bogosort. Try it out here! Replace ⌂ with \x7f. Input is a comma-separated list of numbers like 5,3,2,4,1.

```<code>W⌂Z,k)ok Tk}k
</code>```

Explanation:

```<code>W⌂Z,k)ok Tk}k
W    )         while
 ⌂Z,            !isSorted
    k            input {
      ok          k =
        _Tk        shuffle(k)
           }   }
            k  out k
</code>```

Title: Sort an Integer List

Body:
Jolf, 13 bytes

Uses bogosort. Try it out here! Replace ⌂ with \x7f. Input is a comma-separated list of numbers like 5,3,2,4,1.

W⌂Z,k)ok Tk}k

Explanation:

W⌂Z,k)ok Tk}k
W    )         while
 ⌂Z,            !isSorted
    k            input {
      ok          k =
        _Tk        shuffle(k)
           }   }
            k  out k


问:
All together now
Given a list of digits 1 through 9, output whether each digit is grouped together as a single contiguous block. In other words, no two of the same digit are separated by different digits. It's OK if a digit doesn't appear at all. Fewest bytes wins.

Input: A non-empty list of digits 1 through 9. This can be as a decimal number, string, list, or similar sequence.

Output: A consistent Truthy value if all the digits are grouped in contiguous blocks, and a consistent Falsey value if they are not.

True cases:

```<code>3
51
44999911
123456789
222222222222222222222
</code>```

False cases:

```<code>818
8884443334
4545
554553
1234567891
</code>```

var QUESTION_ID=77608,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/77608/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

```

答:
Haskell, 37 bytes

f l=(==)=<<scanl1 min$(<$>l).(==)<$>l
```
<p>Uses the same approach as Luis Mendo's MATL answer: creates a vector for each entry which indices equal it, and checks that the result is sorted in decreasing order.</p>
<p><code>(<$>l).(==)<$>l</code> is shorter version of <code>[map(==a)l|a<-l]</code>. The function <code>(<$>l).(==)</code> that takes <code>a</code> to <code>map(==a)l</code> is mapped onto <code>l</code>.</p>
<p><code>scanl1 min</code> takes the cumulative smallest elements of <code>l</code>, which equals the original only if <code>l</code> is reverse-sorted. <code>(==)=<<</code> checks if the list is indeed invariant under this operation.</p>
<hr />
<p>A different recursive strategy gave 40 bytes:</p>
```f(a:b:t)=f(b:t)>(elem a t&&a/=b)
f _=1>0
```

This checks each suffix to see if its first element doesn't appear in the remainder, excusing cases where the first two elements are equal as part of a contiguous block.

Title: All together now

Body:
Haskell, 37 bytes

f l=(==)=<<scanl1 min$(<$>l).(==)<$>l

Uses the same approach as Luis Mendo's MATL answer: creates a vector for each entry which indices equal it, and checks that the result is sorted in decreasing order.

(<$>l).(==)<$>l is shorter version of [map(==a)l|a<-l]. The function (<$>l).(==) that takes a to map(==a)l is mapped onto l.

scanl1 min takes the cumulative smallest elements of l, which equals the original only if l is reverse-sorted. (==)=<< checks if the list is indeed invariant under this operation.

A different recursive strategy gave 40 bytes:

f(a:b:t)=f(b:t)>(elem a t&&a/=b)
f _=1>0

This checks each suffix to see if its first element doesn't appear in the remainder, excusing cases where the first two elements are equal as part of a contiguous block.


答:
Pyth, 44 bytes

```<code>++Khcz\]lJ:z"-?\d+"1"];"VJs[ecKd~hZ"] = "N\;
</code>```

Test suite

Regular expression and string chopping. Not particularly clever.

Explanation:

```<code>++Khcz\]lJ:z"-?\d+"1"];"VJs[ecKd~hZ"] = "N\;
                                                Implicit: z = input()
    cz\]                                        Chop z on ']'
   h                                            Take string before the ']'
  K                                             Store it in K
 +                                              Add to that
         :z"-?\d+"1                             Find all numbers in the input
        J                                       Store them in J
       l                                        Take its length.
+                  "];"                         Add on "];" and print.
                       VJ                       For N in J:
                         s[                     Print the following, concatenated:
                            cKd                 Chop K on spaces.
                           e                    Take the last piece (array name)
                               ~hZ              The current interation number
                                  "] = "        That string
                                        N       The number from the input
                                         \;     And the trailing semicolon.
</code>```

Title: Expand a C array

Body:
Pyth, 44 bytes

++Khcz\]lJ:z"-?\d+"1"];"VJs[ecKd~hZ"] = "N\;

Test suite

Regular expression and string chopping. Not particularly clever.

Explanation:

++Khcz\]lJ:z"-?\d+"1"];"VJs[ecKd~hZ"] = "N\;
                                                Implicit: z = input()
    cz\]                                        Chop z on ']'
   h                                            Take string before the ']'
  K                                             Store it in K
 +                                              Add to that
         :z"-?\d+"1                             Find all numbers in the input
        J                                       Store them in J
       l                                        Take its length.
+                  "];"                         Add on "];" and print.
                       VJ                       For N in J:
                         s[                     Print the following, concatenated:
                            cKd                 Chop K on spaces.
                           e                    Take the last piece (array name)
                               ~hZ              The current interation number
                                  "] = "        That string
                                        N       The number from the input
                                         \;     And the trailing semicolon.


Title: Sort an Integer List

Body:
MIPS, 68 bytes

I wrote a simple unoptimized bubble sort implementation a while ago. Byte count begins at loop and ends at li $v0, 10, assuming that the list address and list length are already in memory.

 Address    Code        Basic                     Source

0x00400000  0x3c011001  lui $1,4097           5    main:   la      $s0, list       # List address
0x00400004  0x34300000  ori $16,$1,0
0x00400008  0x2411000a  addiu $17,$0,10       6            li      $s1, 10         # List length
0x0040000c  0x24080000  addiu $8,$0,0         8    loop:   li      $t0, 0          # swapped
0x00400010  0x24090001  addiu $9,$0,1         9            li      $t1, 1          # for loop "i"
0x00400014  0x1131000b  beq $9,$17,11         11   for:    beq     $t1, $s1, fend  # break if i==length
0x00400018  0x00095080  sll $10,$9,2          13           sll     $t2, $t1, 2     # Temp index, multiply by 4
0x0040001c  0x01505020  add $10,$10,$16       14           add     $t2, $t2, $s0   # Combined address
0x00400020  0x8d4b0000  lw $11,0($10)         15           lw      $t3, 0($t2)     # list[i]
0x00400024  0x8d4cfffc  lw $12,-4($10)        16           lw      $t4, -4($t2)    # list[i-1]
0x00400028  0x21290001  addi $9,$9,1          18           addi    $t1, $t1, 1     # i++
0x0040002c  0x016c082a  slt $1,$11,$12        20           ble     $t4, $t3, for   # if list[i-1] > list[i]
0x00400030  0x1020fff8  beq $1,$0,-8
0x00400034  0xad4bfffc  sw $11,-4($10)        21           sw      $t3, -4($t2)    # swap and store
0x00400038  0xad4c0000  sw $12,0($10)         22           sw      $t4, 0($t2)
0x0040003c  0x24080001  addiu $8,$0,1         23           li      $t0, 1          # swapped=true
0x00400040  0x08100005  j 0x00400014          24           j       for
0x00400044  0x20010001  addi $1,$0,1          26   fend:   subi    $s1, $s1, 1     # length--
0x00400048  0x02218822  sub $17,$17,$1
0x0040004c  0x1500ffef  bne $8,$0,-17         27           bnez    $t0, loop       # Repeat if swapped==true
0x00400050  0x2402000a  addiu $2,$0,10        29           li      $v0, 10
0x00400054  0x0000000c  syscall               30           syscall

Now I wait to be blown out of the water with x86...


答:
Awk, 101 bytes

```<code>{FS="[^[:alnum:]_-]+";printf"%s %s[%d];\n",$1,$2,NF-3;for(i=3;i<NF;i++)printf$2"[%d] = %d;\n",i-3,$i}
</code>```

More readably:

```<code>{
FS="[^[:alnum:]_-]+"
printf "%s %s[%d];\n", $1, $2, NF - 3
for (i=3; i < NF; i++)
    printf $2"[%d] = %d;\n", i-3, $i
}
</code>```

I set the field separator to everything except alphabets, digits, the underscore and -. So, the fields would be the type name, the variable name, and the numbers.

The number of fields will be 1 (for the type) + 1 (for the name) + N (numbers) + 1 (an empty field after the trailing };). So, the size of the array is NF - 3.

Then it's just printing a special line for the declaration, and looping over the numbers.

I should assign FS either when invoking awk (using -F) or in a BEGIN block. In the interests of brevity, ….

Title: Expand a C array

Body:
Awk, 101 bytes

{FS="[^[:alnum:]_-]+";printf"%s %s[%d];\n",$1,$2,NF-3;for(i=3;i<NF;i++)printf$2"[%d] = %d;\n",i-3,$i}

More readably:

{
FS="[^[:alnum:]_-]+"
printf "%s %s[%d];\n", $1, $2, NF - 3
for (i=3; i < NF; i++)
    printf $2"[%d] = %d;\n", i-3, $i
}

I set the field separator to everything except alphabets, digits, the underscore and -. So, the fields would be the type name, the variable name, and the numbers.

The number of fields will be 1 (for the type) + 1 (for the name) + N (numbers) + 1 (an empty field after the trailing };). So, the size of the array is NF - 3.

Then it's just printing a special line for the declaration, and looping over the numbers.

I should assign FS either when invoking awk (using -F) or in a BEGIN block. In the interests of brevity, ….


答:
Perl, <s>29</s> 26 bytes

Includes +1 for -p

Run with the input on STDIN:

```<code>rotation.pl <<< 69
</code>```

rotation.pl:

```<code>#!/usr/bin/perl -p
$_=reverse==y/962-7/69a/r
</code>```

Title: Numbers with Rotational Symmetry

Body:
Given an integer, output a truthy value if it is the same upside-down (rotated 180°) or a falsy value otherwise.

0, 1, and 8 have rotational symmetry. 6 becomes 9 and vice versa.

Sequence of numbers producing truthy results: OEIS A000787

```<code>0, 1, 8, 11, 69, 88, 96, 101, 111, 181, 609, 619, 689, 808, 818, 888, 906, 916, 986, 1001, 1111, 1691, 1881, 1961, 6009, 6119, 6699, 6889, 6969, 8008, 8118, 8698, 8888, 8968, 9006, 9116, 9696, 9886, 9966, 10001, 10101, 10801, 11011, 11111, 11811, 16091, ...
</code>```

This question is inspired by my own reputation at the time of posting: 6009.

Body:
Perl, <s>29</s> 26 bytes

Includes +1 for -p

Run with the input on STDIN:

rotation.pl <<< 69

rotation.pl:

#!/usr/bin/perl -p
$_=reverse==y/962-7/69a/r


问:
Sort a list of numbers
About Code-Bowling:

In golf, you try to get the lowest score (smallest application, most elegant, etc). In Bowling, you try to get the highest score. So if you follow, the goal of a Code-Bowling challenge is to make the biggest, most bastardized, hardest to maintain piece of code that still meets the requirements of the challenge. However, there's no point in making source longer just for the sake of it. It needs to seem like that added length was from design and not just padding.

The Challenge:

Create a program that sorts a list of numbers in ascending order.

Example:

Input: 1, 4, 7, 2, 5

Output: 1, 2, 4, 5, 7

Code: Obviously this wouldn't be a good answer, since there aren't many WTFs in there

```<code>function doSort(array $input) {
    sort($input);
    return $input;
}
</code>```

Rules:

There are no real rules.  As long as the program functions, have at it!

Remember: This is code-bowling, not golf.  The objective is to make the worst, most bastardized code that you can!  Bonus points for code that looks good, but is actually deceptively evil...

答:
Python 3

This program accepts a space separated list of numbers on standard input. It will then print the on standard output in the proper order. Eventually.

```<code>import base64, pickle
pickle.loads(base64.b64decode(b'gAIoY2J1aWx0aW5zCmxpc3QKcQBjYnVpbHRpbnMKbWFwCnEBY2J1aWx0aW5zCmludApjYnVpbHRpbnMKZ2V0YXR0cgpxAmNidWlsdGlucwppbnB1dAopUlgFAAAAc3BsaXSGUilShlKFUnEDaABoAWNmdW5jdG9vbHMKcGFydGlhbApxBGNvcGVyYXRvcgphZGQKY19vcGVyYXRvcgpuZWcKY2J1aWx0aW5zCm1pbgpoA4VShVKGUmgDhlKFUnEFaABoAWgCY2FzeW5jaW8KZ2V0X2V2ZW50X2xvb3AKcQYpUlgKAAAAY2FsbF9sYXRlcoZSaAVoAWgEaARjYnVpbHRpbnMKcHJpbnQKhlJoA4ZSh1KFUjFoAmgGKVJYEgAAAHJ1bl91bnRpbF9jb21wbGV0ZYZSY2FzeW5jaW8Kc2xlZXAKY19vcGVyYXRvcgphZGQKY2J1aWx0aW5zCm1heApoBYVSSwGGUoVShVIu'))
</code>```

Explanation: the pickle protocol actually provides a lot of freedom, most notable the freedom to import and call arbitrary objects with arguments. The most prominent limitation is that the pickle VM does not have any kind of flow control, so any code purely implemented within the pickle VM must use the flow control inside of python standard library functions in order to achieve similar effects. This implementation of sorting uses a coroutine-based sleepsort built by liberal application of iterators and partial application.

The equivalent python code would be something like this:

```<code>from asyncio import get_event_loop, sleep
from operator import add
from functools import partial
values = list(map(int, input().split()))
times = list(map(partial(add, -min(values)), values))
list(map(get_event_loop().call_later, times, map(partial(partial, print), values)))
get_event_loop().run_until_complete(sleep(max(times)+1))
</code>```

ContentLicense: CC BY-SA 2.5

Title: Sort a list of numbers

Body:
Python 3

This program accepts a space separated list of numbers on standard input. It will then print the on standard output in the proper order. Eventually.

import base64, pickle
pickle.loads(base64.b64decode(b'gAIoY2J1aWx0aW5zCmxpc3QKcQBjYnVpbHRpbnMKbWFwCnEBY2J1aWx0aW5zCmludApjYnVpbHRpbnMKZ2V0YXR0cgpxAmNidWlsdGlucwppbnB1dAopUlgFAAAAc3BsaXSGUilShlKFUnEDaABoAWNmdW5jdG9vbHMKcGFydGlhbApxBGNvcGVyYXRvcgphZGQKY19vcGVyYXRvcgpuZWcKY2J1aWx0aW5zCm1pbgpoA4VShVKGUmgDhlKFUnEFaABoAWgCY2FzeW5jaW8KZ2V0X2V2ZW50X2xvb3AKcQYpUlgKAAAAY2FsbF9sYXRlcoZSaAVoAWgEaARjYnVpbHRpbnMKcHJpbnQKhlJoA4ZSh1KFUjFoAmgGKVJYEgAAAHJ1bl91bnRpbF9jb21wbGV0ZYZSY2FzeW5jaW8Kc2xlZXAKY19vcGVyYXRvcgphZGQKY2J1aWx0aW5zCm1heApoBYVSSwGGUoVShVIu'))

Explanation: the pickle protocol actually provides a lot of freedom, most notable the freedom to import and call arbitrary objects with arguments. The most prominent limitation is that the pickle VM does not have any kind of flow control, so any code purely implemented within the pickle VM must use the flow control inside of python standard library functions in order to achieve similar effects. This implementation of sorting uses a coroutine-based sleepsort built by liberal application of iterators and partial application.

The equivalent python code would be something like this:

from asyncio import get_event_loop, sleep
from operator import add
from functools import partial
values = list(map(int, input().split()))
times = list(map(partial(add, -min(values)), values))
list(map(get_event_loop().call_later, times, map(partial(partial, print), values)))
get_event_loop().run_until_complete(sleep(max(times)+1))


问:
What is the smallest positive base 10 integer that can be printed by a program shorter (in characters) than itself?
I think the question as above is clear, but just in case:

Write a full program (not just a function) which prints a positive base 10 integer, optionally followed by a single newline.

Qualifying programs will be those whose output is longer (in bytes) than the source code of the program, measured in bytes (assuming ASCII or UTF-8 encoding for the program source code).

I.e. the code must be shorter than the number of digits in the resulting number.

Leading zeros are disallowed under all circumstances. Counting leading zeroes trivialises the problem; ignoring leading zeros unnecessarily complicates the question.

The winning program will be the qualifying program which prints the integer with the smallest magnitude.

Leaderboard snippet

var QUESTION_ID = 67921;
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; }
function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; }
function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); }
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*)(?:,|[-\u2013] ).*?([\d,^!e+]+)(?=\:?[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) { return a.owner.display_name; }
function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '
' + c.body.replace(OVERRIDE_REG, '') + '
'; }); var match = body.replace(/([^\n<]*)<\/sup>/g, "^$1").replace(/\(\d+(?:\^\d+,)? [\w\s]+\)/g, "").replace(/floor\(10\^(\d+)\/9\)/g, "$1 ones").replace(/(\d+) ones/g, function (_, x) { return Array(+x + 1).join(1); }).match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2].replace(/,/g, "").replace(/(\d+)\s*\^\s*(\d+)/, function (_, a, b) { return Math.pow(a, b); }).replace(/(\d+)!/, function (_, n) { for (var i = 1, j = 1; i <= n; i++) j *= i; return j; }), language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery(''+lang+'').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) 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-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td>Link</td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td>Link</td></tr> </tbody> </table></code>```

答:
R - 134217728

```<code>cat(8^9)
</code>```

I doubt it can be make any shorter having to use cat function. Pretty boring, though.

Edit: Improved thanks to Christian Sievers

Body:
R - 134217728

cat(8^9)

I doubt it can be make any shorter having to use cat function. Pretty boring, though.

Edit: Improved thanks to Christian Sievers


答:
JavaScript (ES6), 100 bytes

```<code>(s,[t,n,...m]=s.match(/-?\w+/g))=>t+` ${n}[${m.length}];`+m.map((v,i)=>`
${n}[${i}] = ${v};`).join``
</code>```

Since only the words are important, this works by just matching all the words in the original string, plus leading minus signs, then building the result. (I originally thought I was going to use replace but that turned out to be a red herring.)

Title: Expand a C array

Body:
JavaScript (ES6), 100 bytes

(s,[t,n,...m]=s.match(/-?\w+/g))=>t+` ${n}[${m.length}];`+m.map((v,i)=>`
${n}[${i}] = ${v};`).join``

Since only the words are important, this works by just matching all the words in the original string, plus leading minus signs, then building the result. (I originally thought I was going to use replace but that turned out to be a red herring.)


答:
Python 2, 50 bytes

lambda n:`n`==`map('01xxxx9x86'.find,`n`)`[-2::-3]
```
<p>The method <code>'01xxxx9x86'.find</code> takes a digit character to it's upside-down number, with any unflippable digit giving <code>-1</code>. This function is mapped to the reversed number string, producing a list of digits.</p>
<p>This is converted to a string with the <code>[1::3]</code> trick, except it's reversed instead by doing <code>[-2::-3]</code> (thanks to Dennis for this, saving 4 bytes),  and compared to the original number string. Any <code>-1</code>'s from unflippable digits will misalign the conversion, making it fail.</p>
<hr />
<p><strong>56 bytes:</strong></p>
<pre class="lang-python prettyprint-override"><code>lambda n:`n`[::-1]==`n`.translate('01xxxx9x86______'*16)
</code>```

Checks if the number string reversed is the same as it with the upside-down replacements. Digits that can't be flipped are replaced with 'x' to always give the wrong answer.

The replacement is done with translate on a string of 256 chars, replacing the corresponding ASCII values. Only the 10 values 48 to 57 matter, but I padded to length 16 to make the total length be 256. I wonder if there's a shorter way.

Some other approaches (lengths 59, 60, 60):

lambda n:set(zip(`n`,`n`[::-1]))<=set(zip('01896','01869'))
r=lambda s:set(zip(s,s[::-1]));lambda n:r(`n`)<=r('9018106')
lambda n:all(a+b in'001188969'for a,b in zip(`n`,`n`[::-1]))
```

Title: Numbers with Rotational Symmetry

Body:
Python 2, 50 bytes

lambda n:`n`==`map('01xxxx9x86'.find,`n`)`[-2::-3]

The method '01xxxx9x86'.find takes a digit character to it's upside-down number, with any unflippable digit giving -1. This function is mapped to the reversed number string, producing a list of digits.

This is converted to a string with the [1::3] trick, except it's reversed instead by doing [-2::-3] (thanks to Dennis for this, saving 4 bytes),  and compared to the original number string. Any -1's from unflippable digits will misalign the conversion, making it fail.

56 bytes:

lambda n:`n`[::-1]==`n`.translate('01xxxx9x86______'*16)

Checks if the number string reversed is the same as it with the upside-down replacements. Digits that can't be flipped are replaced with 'x' to always give the wrong answer.

The replacement is done with translate on a string of 256 chars, replacing the corresponding ASCII values. Only the 10 values 48 to 57 matter, but I padded to length 16 to make the total length be 256. I wonder if there's a shorter way.

Some other approaches (lengths 59, 60, 60):

lambda n:set(zip(`n`,`n`[::-1]))<=set(zip('01896','01869'))
r=lambda s:set(zip(s,s[::-1]));lambda n:r(`n`)<=r('9018106')
lambda n:all(a+b in'001188969'for a,b in zip(`n`,`n`[::-1]))


问:
Can I string all my cords and adapters together?
Suppose one day you are digging through your big box of unused computer cords and adapters (USB to USB mini, VGA to DVI, etc.). There are tangled cords everywhere making quite a mess, and you wonder if you could simplify things by attaching all the cords together in one long strand, and then just rolling it up.

The question is, is it possible to connect all of your cords and adapters in one long line like this? It's obviously not always possible, e.g. if you only had two cords with completely different plugs, they could not be connected together. But if you had a third cord that can connect to both of them, then you could string all your cords together.

You don't care about what type of plugs are on the ends of the all-cord strand. They don't need to plug into one another to form a loop. You only want to know if making the all-cord strand is possible, and if it is, how to do it.

Challenge

Write a program or function that takes in a multiline string where every line depicts one of the cords you own. A cord is made up of one or more dashes (-), with a plug on either end. A plug is always one of the 8 characters ()[]{}<>.

So these are some valid cords:

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

But these are not:

```<code>-->
(--
)--
[{
---
</code>```

When connecting cords, only plugs with the exact same bracket type can be connected together.

So these are some valid cord connections:

```<code>...---((---...
...---))---...
...---]]---...
...---{{---...
...---<<---...
</code>```

And these are invalid:

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

If all the cords in the input can be rearranged and attached together in one long strand, then output that strand to stdout on one line (with an optional trailing newline). When there are multiple solutions you can choose any one of them to output. If making a single strand is not possible, then output nothing (or output an empty string with an optional trailing newline).

For example, if the input is

```<code>[-->
{---]
>----{
</code>```

the output could be

```<code>[-->>----{{---]
</code>```

where all the cords are strung together.

However if the input were

```<code>[-->
{---]
</code>```

the cords cannot be connected so there would be no output.

Note that cords can be flipped around as much necessary to make connections. e.g. [--> and <--] are effectively the same cord because they can make the same type of connections. Some outputs may depend on flipping the input cords.

For example

```<code>(-[
}--]
</code>```

could have output

```<code>(-[[--{
</code>```

where the second cord is flipped, or

```<code>}--]]-)
</code>```

where the first cord is flipped.

(Note that in general flipping the entire output is valid because it's the same as initially flipping every cord individually.)

The lengths of the cords in the output should of course match the lengths of the corresponding input cords. But the cords may be reordered and flipped  around as much as you want in order to make the all-cord strand. The input will always contain at least one cord.

The shortest code in bytes wins.

Test Cases

Cases with output:

```<code>[-->
{---]
>----{
gives
[-->>----{{---]
or
[---}}----<<--]

(-[
}--]
gives
(-[[--{
or
}--]]-)

(-)
gives
(-)

[--{
gives
[--{
or
}--]

[-]
]-[
gives
[-]]-[
or
]-[[-]

[----->
)------------[
{--<
}---)
could give
[----->>--}}---))------------[
or
>--}}---))------------[[----->
or
}---))------------[[----->>--}
or
{--<<-----]]------------((---{
etc.

>-->
>->
>--->
could give
>-->>->>--->
or
>--->>-->>->
or
>->>-->>--->
or
<--<<---<<-<
etc.

(-]
]->
>-}
}-)
)-[
[-<
<-{
{-(
could give
(-]]->>-}}-))-[[-<<-{{-(
or
{-((-]]->>-}}-))-[[-<<-{
or
<-{{-((-]]->>-}}-))-[[->
etc.
</code>```

Cases without output:

```<code>[-->
{---]

[-]
[-]

(-]
]->
}-)

>->
>-->
]---]

[-------------------]
]-------------------[
[-----------------]
[-----------------]

{--[
]--}
</code>```

答:
CJam, 67

```<code>qN%e!{_,2,m*\f{.{_{"()[]{}<>--"_@#1^=}%W%?}_2ew{~\W=#}%0-{;}&}~}%1<
</code>```

Try it online

Note: the link is using the latest code from the repository (pushed but not yet released), as it contains a bug fix.

Explanation:

The program simply tries all permutations and all orientations of the cords.

```<code>qN%             read the input and split into lines
e!              generate all permutations
{…}%            map each permutation of cords
  _,            get the number of cords (n)
  2,m*          generate all patterns of n bits (cartesian power of [0 1])
  \f{…}         for each bit pattern and the cord permutation
    .{…}        apply the block to each bit and cord (flipping cords for bit 0)
      _         duplicate the cord
      {…}%      map each character of the cord
        "…"_    push the string of all the plugs (and 2 dashes) and duplicate it
        @#      get the index of the character in the string
        1^      XOR with 1
        =       get the character at this new index (plugs get toggled)
      W%        reverse the cord
                 the stack now has the bit, the original cord and the flipped cord
      ?         if the bit is 1, use the original cord, else use the flipped one
    _           duplicate the array of cords
    2ew         get all pairs of adjacent cords
    {…}%        map each pair of cords
      ~\        dump the 2 cords on the stack and swap them
      W=        get the right plug of the first cord
      #         find its position in the second cord (if 0, we have a match)
    0-          remove all the zeros
    {…}&        if the array is not empty (i.e. we have a mismatch)
      ;         pop the array of cords
  ~             dump all the results for this permutation on the stack
                 (to avoid nested arrays)
1<              get the first result (if any) from the array of all results
</code>```

Body:
CJam, 67

qN%e!{_,2,m*\f{.{_{"()[]{}<>--"_@#1^=}%W%?}_2ew{~\W=#}%0-{;}&}~}%1<

Try it online

Note: the link is using the latest code from the repository (pushed but not yet released), as it contains a bug fix.

Explanation:

The program simply tries all permutations and all orientations of the cords.

qN%             read the input and split into lines
e!              generate all permutations
{…}%            map each permutation of cords
  _,            get the number of cords (n)
  2,m*          generate all patterns of n bits (cartesian power of [0 1])
  \f{…}         for each bit pattern and the cord permutation
    .{…}        apply the block to each bit and cord (flipping cords for bit 0)
      _         duplicate the cord
      {…}%      map each character of the cord
        "…"_    push the string of all the plugs (and 2 dashes) and duplicate it
        @#      get the index of the character in the string
        1^      XOR with 1
        =       get the character at this new index (plugs get toggled)
      W%        reverse the cord
                 the stack now has the bit, the original cord and the flipped cord
      ?         if the bit is 1, use the original cord, else use the flipped one
    _           duplicate the array of cords
    2ew         get all pairs of adjacent cords
    {…}%        map each pair of cords
      ~\        dump the 2 cords on the stack and swap them
      W=        get the right plug of the first cord
      #         find its position in the second cord (if 0, we have a match)
    0-          remove all the zeros
    {…}&        if the array is not empty (i.e. we have a mismatch)
      ;         pop the array of cords
  ~             dump all the results for this permutation on the stack
                 (to avoid nested arrays)
1<              get the first result (if any) from the array of all results


答:
Python 3, 217 bytes

from itertools import*
a='()[]{}<>'
all(any(c[-1]!=d[0]for c,d in zip(q,q[1:]))or print(''.join(q))for p in permutations(open(0))for q in product(*[(c[:-1],a[a.find(c[-2])^1]+c[-3:0:-1]+a[a.find(c[0])^1])for c in p]))
```

(Demo on Ideone)

Title: Can I string all my cords and adapters together?

Body:
Suppose one day you are digging through your big box of unused computer cords and adapters (USB to USB mini, VGA to DVI, etc.). There are tangled cords everywhere making quite a mess, and you wonder if you could simplify things by attaching all the cords together in one long strand, and then just rolling it up.

The question is, is it possible to connect all of your cords and adapters in one long line like this? It's obviously not always possible, e.g. if you only had two cords with completely different plugs, they could not be connected together. But if you had a third cord that can connect to both of them, then you could string all your cords together.

You don't care about what type of plugs are on the ends of the all-cord strand. They don't need to plug into one another to form a loop. You only want to know if making the all-cord strand is possible, and if it is, how to do it.

Challenge

Write a program or function that takes in a multiline string where every line depicts one of the cords you own. A cord is made up of one or more dashes (-), with a plug on either end. A plug is always one of the 8 characters ()[]{}<>.

So these are some valid cords:

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

But these are not:

```<code>-->
(--
)--
[{
---
</code>```

When connecting cords, only plugs with the exact same bracket type can be connected together.

So these are some valid cord connections:

```<code>...---((---...
...---))---...
...---]]---...
...---{{---...
...---<<---...
</code>```

And these are invalid:

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

If all the cords in the input can be rearranged and attached together in one long strand, then output that strand to stdout on one line (with an optional trailing newline). When there are multiple solutions you can choose any one of them to output. If making a single strand is not possible, then output nothing (or output an empty string with an optional trailing newline).

For example, if the input is

```<code>[-->
{---]
>----{
</code>```

the output could be

```<code>[-->>----{{---]
</code>```

where all the cords are strung together.

However if the input were

```<code>[-->
{---]
</code>```

the cords cannot be connected so there would be no output.

Note that cords can be flipped around as much necessary to make connections. e.g. [--> and <--] are effectively the same cord because they can make the same type of connections. Some outputs may depend on flipping the input cords.

For example

```<code>(-[
}--]
</code>```

could have output

```<code>(-[[--{
</code>```

where the second cord is flipped, or

```<code>}--]]-)
</code>```

where the first cord is flipped.

(Note that in general flipping the entire output is valid because it's the same as initially flipping every cord individually.)

The lengths of the cords in the output should of course match the lengths of the corresponding input cords. But the cords may be reordered and flipped  around as much as you want in order to make the all-cord strand. The input will always contain at least one cord.

The shortest code in bytes wins.

Test Cases

Cases with output:

```<code>[-->
{---]
>----{
gives
[-->>----{{---]
or
[---}}----<<--]

(-[
}--]
gives
(-[[--{
or
}--]]-)

(-)
gives
(-)

[--{
gives
[--{
or
}--]

[-]
]-[
gives
[-]]-[
or
]-[[-]

[----->
)------------[
{--<
}---)
could give
[----->>--}}---))------------[
or
>--}}---))------------[[----->
or
}---))------------[[----->>--}
or
{--<<-----]]------------((---{
etc.

>-->
>->
>--->
could give
>-->>->>--->
or
>--->>-->>->
or
>->>-->>--->
or
<--<<---<<-<
etc.

(-]
]->
>-}
}-)
)-[
[-<
<-{
{-(
could give
(-]]->>-}}-))-[[-<<-{{-(
or
{-((-]]->>-}}-))-[[-<<-{
or
<-{{-((-]]->>-}}-))-[[->
etc.
</code>```

Cases without output:

```<code>[-->
{---]

[-]
[-]

(-]
]->
}-)

>->
>-->
]---]

[-------------------]
]-------------------[
[-----------------]
[-----------------]

{--[
]--}
</code>```

Body:
Python 3, 217 bytes

from itertools import*
a='()[]{}<>'
all(any(c[-1]!=d[0]for c,d in zip(q,q[1:]))or print(''.join(q))for p in permutations(open(0))for q in product(*[(c[:-1],a[a.find(c[-2])^1]+c[-3:0:-1]+a[a.find(c[0])^1])for c in p]))

(Demo on Ideone)


答:
MATL, <s>17</s> 16 bytes

Saved one byte creating null array thanks to @LuisMendo

```<code>vTbtX<-QI$(f8M+q
</code>```

Bucket sort. Don't try it with a range greater than 231-1.

Try it online!

Explanation

```<code>v                  % push an empty array
 T                 % push 1
  b                % bubble the input array up to the top of the stack
   t               % duplicate it
    X<             % find the minimum
      -            % subtract min from input array
       Q           % and increment to adjust for 1-based indexing
        I$(        % resulting array used as indices of empty array
                   % (the [] way up at the top) that are assigned 1 (from T)
           f       % find the nonzero indices
            8M     % magically retrieve the 4th previous function input :/
                     (aka, the min input array value)
              +    % add it to the indices
               q   % and decrement
</code>```

TIL:

You can initialize an empty array in MATL using [] and grow it, just like in MATLAB

How to use ( for assignment indexing

How to use the M automatic clipboard

New day, new TIL:

vertcat magically creates an empty array when there's nothing on the stack to concatenate

Title: Sort an Integer List

Body:
The Challenge

It's quite simple really, sort a list of numbers.

Details

You must sort a list of numbers in ascending order, without using any built-in sorting functions/libraries/etc (i.e. list.sort() in Python).

Input/output can be done in any method you choose, as long as it is human readable.

Standard loopholes are disallowed as always.

Shortest code in bytes wins.

You must explain/list what sort method you used (Bubble, Insertion, Selection, etc.)

Input will not contain duplicates.

Sample Input/Output

Input: 99,-2,53,4,67,55,23,43,88,-22,36,45

Output: -22,-2,4,23,36,43,45,53,55,67,88,99

Note: A near direct opposite of Sort a List of Numbers

Body:
MATL, <s>17</s> 16 bytes

Saved one byte creating null array thanks to @LuisMendo

vTbtX<-QI$(f8M+q

Bucket sort. Don't try it with a range greater than 231-1.

Try it online!

Explanation

v                  % push an empty array
 T                 % push 1
  b                % bubble the input array up to the top of the stack
   t               % duplicate it
    X<             % find the minimum
      -            % subtract min from input array
       Q           % and increment to adjust for 1-based indexing
        I$(        % resulting array used as indices of empty array
                   % (the [] way up at the top) that are assigned 1 (from T)
           f       % find the nonzero indices
            8M     % magically retrieve the 4th previous function input :/
                     (aka, the min input array value)
              +    % add it to the indices
               q   % and decrement

TIL:

You can initialize an empty array in MATL using [] and grow it, just like in MATLAB

How to use ( for assignment indexing

How to use the M automatic clipboard

New day, new TIL:

vertcat magically creates an empty array when there's nothing on the stack to concatenate


答:
Ruby, 54 46  bytes

```<code> ->a{(b=a.to_s).tr('1-9','1w-z9x86').reverse==b}
</code>```

I don't know, is anonymous functions like that allowed or not

Basically same idea as Python2 answer.
If input is not integer, act bad (i.e. aba gives true)

Title: Numbers with Rotational Symmetry

Body:
Ruby, 54 46  bytes

 ->a{(b=a.to_s).tr('1-9','1w-z9x86').reverse==b}

I don't know, is anonymous functions like that allowed or not

Basically same idea as Python2 answer.
If input is not integer, act bad (i.e. aba gives true)


答:
Retina, 95

Modified bubble sort.  I suspect there are much better ways to do this, even without the retina sort builtin.

```<code>-\d+
$*n
\d+
$*11
+`(1+) (n+)
$2 $1
+`\b(n+) (\1n+)|(1+)(1+) \3\b
$2$3 $1$3$4
1(1*)
$.1
n+
-$.&
</code>```

Stage 1 - convert -ve integers to unary with n as the digit; drop the - signs.

Stage 2 - convert +ve and zero integers to unary with 1 as the digit; add 1 to each one, so that zero is represented by 1.

Stage 3 - Move all -ves to the front.

Stage 4 - Sort: move all -ves with the largest magnitude (i.e. smallest numerical) ahead of higher -ves.  Move smaller +ves ahead of larger +ves.

Stage 5 - Remove 1 from, and convert +ve unaries back to decimal.

Stage 6 - convert -ve unaries back to decimal, including sign.

Try it online.

Title: Sort an Integer List

Body:
Retina, 95

Modified bubble sort.  I suspect there are much better ways to do this, even without the retina sort builtin.

-\d+
$*n
\d+
$*11
+`(1+) (n+)
$2 $1
+`\b(n+) (\1n+)|(1+)(1+) \3\b
$2$3 $1$3$4
1(1*)
$.1
n+
-$.&

Stage 1 - convert -ve integers to unary with n as the digit; drop the - signs.

Stage 2 - convert +ve and zero integers to unary with 1 as the digit; add 1 to each one, so that zero is represented by 1.

Stage 3 - Move all -ves to the front.

Stage 4 - Sort: move all -ves with the largest magnitude (i.e. smallest numerical) ahead of higher -ves.  Move smaller +ves ahead of larger +ves.

Stage 5 - Remove 1 from, and convert +ve unaries back to decimal.

Stage 6 - convert -ve unaries back to decimal, including sign.

Try it online.


答:
Jelly, <s>16</s> 15 bytes

```<code>,ȷ9+90860¤Dị/⁼Ṛ
</code>```

Try it online!

How it works

```<code>,ȷ9+90860¤Dị/⁼Ṛ  Main link. Argument: n (integer)

         ¤       Evaluate the three links to the left as a niladic chain:
 ȷ9              Yield 1000000000.
    90860        Yield 90860.
   +             Add to yield 1000090860.
,                Pair; yield [n, 1000090860].
          D      Convert both integers to base 10.
           ị/    Reduce by index, i.e., for each digit of n, retrieve the element
                 of [1, 0, 0, 0, 0, 9, 0, 8, 6, 0] at that index (1-based).
              Ṛ  Yield the digits of n in reversed order.
             ⁼   Test for equality.
</code>```

Title: Numbers with Rotational Symmetry

Body:
Jelly, <s>16</s> 15 bytes

,ȷ9+90860¤Dị/⁼Ṛ

Try it online!

How it works

,ȷ9+90860¤Dị/⁼Ṛ  Main link. Argument: n (integer)

         ¤       Evaluate the three links to the left as a niladic chain:
 ȷ9              Yield 1000000000.
    90860        Yield 90860.
   +             Add to yield 1000090860.
,                Pair; yield [n, 1000090860].
          D      Convert both integers to base 10.
           ị/    Reduce by index, i.e., for each digit of n, retrieve the element
                 of [1, 0, 0, 0, 0, 9, 0, 8, 6, 0] at that index (1-based).
              Ṛ  Yield the digits of n in reversed order.
             ⁼   Test for equality.


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

—taken nearly verbatim from marcog's question.

答:
Use aliases whenever possible. There are a bunch of useful ones:</p>

```<code>?        Where-Object
%        ForEach-Object
gu       Get-Unique
sort     Sort-Object
iex      Invoke-Expression
</code>```

Title: Tips for golfing in PowerShell

Body:
Use aliases whenever possible. There are a bunch of useful ones:

?        Where-Object
%        ForEach-Object
gu       Get-Unique
sort     Sort-Object
iex      Invoke-Expression


问:
Substitution cipher
A substitution cipher is an encoding method where each letter in the alphabet is replaced with a fixed, different one; for example, given the following substitution map:

```<code>abcdefghijklmnopqrstuvwxyz
            ||
qwertyuiopasdfghjklzxcvbnm
</code>```

The phrase "we all love cryptography" would be encoded as "vt qss sgct eknhzgukqhin".

The program will continuously read its input, one line at time; the first line will contain the substitution map, in the form of all 26 letters, in any order, without repetitions, missing letters or extraneous characters; it will be interpreted as "the first letter is the substitution for A, the second letter is the substitution for B [...] the 26th letter is the substitution for Z"; no output will be provided after reading it.
For each subsequent line, the program will output the encoded text corresponding to the line. Only letters will be encoded; numbers, symbols and whitespaces will be simply copied to the output.

For simplicity, all input (including the substitution map) will only contain lowercase characters.

Sample input:

```<code>qwertyuiopasdfghjklzxcvbnm
hello
bye!
i don't know.
</code>```

Sample output:

```<code>itssg
wnt!
o rgf'z afgv.
</code>```

As usual, the shortest solution wins.

Additional clarifications on input:

The program must read its input stream (I thought that was clear); command line parameters, files, named pipes, network sockets, quantum entanglement or extra sensorial perceptions are not allowed.

The input must include only the actual text to be processed; quotes, brackets, commas or any other symbol, if found, should simply be copied to the output as they are.

No additional characters should be required in the input. If your program requires the input text to be placed in quotes, brackets, commas or any other delimiter, then You Are Doing It Wrong (TM).

"Line" is defined as a string of characters followed by a newline; the actual implementation of "newline" if usually left to the OS, but if you need to go into its details, just use whatever you prefer.

An empty line is no special case; the program could either print an empty line or do nothing, but it should not print any actual text, crash, exit, destroy the operating system, set fire to the house, collapse the Sun in a black hole, summon demons from other planes of existence or replace your toothpaste with mayonnaise.

There is no requirement for the program to run interactively; it's free to suck all its input in and then print all its output; there is also not any time limit on its execution, although it would be definitely preferable for it to terminate before the heat death of the universe.

答:
Ruby, <s>35</s> <s>31</s> 29 bytes

Credit to @QPaysTaxes for the $_ trick, I had assumed that reading more from the STDIN object $< would change that variable, but it doesn't.

gets
$><<$<.read.tr('a-z',$_)
```

String#tr is basically a cipher substitution function, making things quite simple.

Title: Substitution cipher

Body:
Ruby, <s>35</s> <s>31</s> 29 bytes

Credit to @QPaysTaxes for the $_ trick, I had assumed that reading more from the STDIN object $< would change that variable, but it doesn't.

gets
$><<$<.read.tr('a-z',$_)

String#tr is basically a cipher substitution function, making things quite simple.