问:
Code Golf Golf Golf

Golf Challenge

Given the below ASCII "Green".

```<code>|          |
|  |>      |
|  |       |
|  O       |
|          |
|          |
|          |
|          |
|          |
|          |
</code>```

Let | Denote a wall

Let | Denote half the flag pole

Let > Denote the flag on the pole

Let O Denote the hole

Let o Denote the ball

The dimensions of the "Green" is 10x10. There are ten spaces between the two walls |.

There are also ten spaces, empty or not between the top and the bottom of the green.

Challenge

Input an x and y value or
generate two random numbers to "shoot" a golf ball onto the green.

If the x, y generated does not touch the hole or the flag pole/flag output "Try Again!"

If the x, y generated hits the hole output "Hole in One!"

if the x, y generated hits the pole output "Lucky Shot!"

if the x, y generated hits the flag output "Close One!"

After the shot, output the location of the ball on the green with a o, replacing any character it hit. Also output the respective saying above.

Examples:

```<code>//Hole in one example, the O was replaced with a o
Randomed x = 3
Randomed y = 4

"Hole in One!"

|          |
|  |>      |
|  |       |
|  o       |
|          |
|          |
|          |
|          |
|          |
|          |

//Clone example, the top half of the pole was replaced with a o
Randomed x = 3
Randomed y = 2

"Lucky Shot!"

|          |
|  o>      |
|  |       |
|  O       |
|          |
|          |
|          |
|          |
|          |
|          |

//Lucky Shot example, the > was replaced with a o
Randomed x = 4
Randomed y = 2

"Close One!"

|          |
|  |o      |
|  |       |
|  O       |
|          |
|          |
|          |
|          |
|          |
|          |

//Try Again example, the <space> was replaced with a o
Randomed x = 5
Randomed y = 1

"Try Again!"

|     o    |
|  |>      |
|  |       |
|  O       |
|          |
|          |
|          |
|          |
|          |
|          |
</code>```

Have fun and good luck and as this is code-golf the shortest code wins!

Title: Code Golf Golf Golf


问:
Convert Chinese numbers
In Chinese, numbers are written as follows:

1 一 2 二 3 三 4 四 5 五 6 六 7 七 8 八 9 九 10 十

For numbers above 10, it is expressed as the number of tens and the number of ones. If there is only one ten, you do not need to explicitly say one, and if there are no ones, you don't need to put anything after:

11 十一

24 二十四

83 八十三

90 九十

For numbers above 100, you use the same logic, but with the character 百. This time though, if there is only one hundred, you still need to write it out, and if there are no tens, you need to say 零.

100 一百 231 二百三十一 803 八百零三 999 九百九十九

Your task is to convert these Chinese numerals into Arabic numerals. Given a number N in Chinese (一 (1) <= N <= 九百九十九 (999)), convert it into an Arabic number.

Remember, this is code-golf, so the code with the smallest number of bytes wins.

答:
JavaScript (ES6), 112 bytes

```<code>s=>[...s].map(c=>d=(i="零一二三四五六七八九十百".search(c))>9?(n+=(d||1)*(i*90-890),0):i,n=d=0)&&n+d
</code>```

Digits 一-九 are converted to decimal and saved in d, while 十 and 百 multiply the last digit by 10 or 100 respectively and accumulate it in n. 零 is effectively ignored, since d is already zero when it is encountered.

ContentLicense: CC BY-SA 3.0

Title: Convert Chinese numbers

Body:
JavaScript (ES6), 112 bytes

s=>[...s].map(c=>d=(i="零一二三四五六七八九十百".search(c))>9?(n+=(d||1)*(i*90-890),0):i,n=d=0)&&n+d

Digits 一-九 are converted to decimal and saved in d, while 十 and 百 multiply the last digit by 10 or 100 respectively and accumulate it in n. 零 is effectively ignored, since d is already zero when it is encountered.


问:
Trick or Treat polyglot
Since Halloween is coming up I thought I might start a fun little code golf challenge!

The challenge is quite simple. You have to write a program that outputs either trick or treat.

"The twist?" you may ask. Well let me explain:

Your program has to do the following:

Be compilable/runnable in two different languages. Different versions of the same language don't count.

When you run the program in one language it should output trick and the other should output treat. The case is irrelevant and padding the string with whitespace characters are allowed (see examples).

This is code-golf,  so the solution with the fewest bytes wins.

A few explanations:

Valid outputs (Just for the words not for running the code in the two languages. Also adding quotes to signalize the beginning or end of the output. Do not include them in your solution!):

```<code>"trick"

"Treat"

"    TReAt"

"
     tRICk          "
</code>```

Invalid outputs:

```<code>"tri ck"

"tr
eat"

"trck"
</code>```

I'm interested to see what you can come up with! Happy Golfing!

I'd like to note that this is my first challenge so if you have suggestions on this question please leave them in the form of a comment.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code># Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code># Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code># Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the leaderboard snippet:

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

var QUESTION_ID=97472,OVERRIDE_USER=23417;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,TAGS_REG = /(<([^>]+)>)/ig;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;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

```

答:
/// / FEU, 24 bytes

```<code>/ /
p/trick/
end
a/treat
</code>```

Try it online! Slashes | FEU

Explanation

///

```<code>/ /       Replace space with "\n...
p/trick/  ...p". Print "trick". Replace "\n...
end       ...end\n...
a/treat   ...a", third slash is missing so it doesn't do anything.
</code>```

FEU

```<code>/ /       Execute the next block for each strings matched by " "
p/trick/  Prepend "trick"
end       End block
a/treat   Append "treat"
</code>```

Title: Trick or Treat polyglot

Body:
/// / FEU, 24 bytes

/ /
p/trick/
end
a/treat

Try it online! Slashes | FEU

Explanation

///

/ /       Replace space with "\n...
p/trick/  ...p". Print "trick". Replace "\n...
end       ...end\n...
a/treat   ...a", third slash is missing so it doesn't do anything.

FEU

/ /       Execute the next block for each strings matched by " "
p/trick/  Prepend "trick"
end       End block
a/treat   Append "treat"


问:
Simplificate an array

Input

An array that can contain arrays or positive, consecutive, ascending integers. The arrays can have any number of arrays inside of them, and so on and so forth. No arrays will be empty.

Output

This array simplificated

How to simplificate an array

We will use the array, [1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]] as our example.

First, we check how deep the values are nested. Here are the depths and the numbers at those depths:

```<code>0  1
1  2 3 9
2  4 7
3  5 6
5  8
</code>```

We construct the output array by taking the numbers in the original array, grouping them by how deep they are nested, and then nesting the groups at depths of the original depths of their  elements. Arrange the numbers in ascending order and ascending depth.

So, our output is [1, [2, 3, 9], [[4, 7]], [[[5, 6]]], [[[[[8]]]]]]

Examples

```<code>[1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]] -> [1, [2, 3, 9], [[4, 7]], [[[5, 6]]], [[[[[8]]]]]]
[[[1]], [2, [3]], 4, [5, [6, [7, [8], [9, [[10]]]]]]] -> [4, [2, 5], [[1, 3, 6]], [[[7]]], [[[[8, 9]]]], [[[[[[10]]]]]]]
[1] -> [1]
[1, [2], [[3]], [[[4]]], [[[[5]]]]] -> [1, [2], [[3]], [[[4]]], [[[[5]]]]]
[1, [[[[2], 3]]], [[4]]] -> [1, [[4]], [[[3]]], [[[[2]]]]]
</code>```

答:
PHP, 145 Bytes

```<code><?function c($r){$n=[];foreach($r as$k=>$v)if(is_array($v)){$n=array_merge($n,$v);unset($r[$k]);}if($n)$r[]=c($n);return$r;}print_r(c($_GET[a]));
</code>```

Breakdown

```<code>function c($r){
  #usort($r,function($x,$y){return is_array($x)<=>is_array($y)?:$x<=>$y;});
#no need to sort and a simple sort($r); do it sort array after scalar
  $n=[];
  foreach($r as$k=>$v)if(is_array($v)){$n=array_merge($n,$v);unset($r[$k]);} # put arrays on the same depth together
  if($n)$r[]=c($n); # recursive if an array exists
  return$r; #return changes
}
print_r(c($_GET[a])); #Output and Input
</code>```

ContentLicense: CC BY-SA 4.0

Title: Simplificate an array

Body:
PHP, 145 Bytes

<?function c($r){$n=[];foreach($r as$k=>$v)if(is_array($v)){$n=array_merge($n,$v);unset($r[$k]);}if($n)$r[]=c($n);return$r;}print_r(c($_GET[a]));

Breakdown

function c($r){
  #usort($r,function($x,$y){return is_array($x)<=>is_array($y)?:$x<=>$y;});
#no need to sort and a simple sort($r); do it sort array after scalar
  $n=[];
  foreach($r as$k=>$v)if(is_array($v)){$n=array_merge($n,$v);unset($r[$k]);} # put arrays on the same depth together
  if($n)$r[]=c($n); # recursive if an array exists
  return$r; #return changes
}
print_r(c($_GET[a])); #Output and Input


问:
Alphabet Diamond
You've seen the amazing alphabet triangle, the revenge of the alphabet triangle and now it's time for the revenge of the revenge of the alphabet triangle!

Introducing...

THE ALPHABET DIAMOND!

Your task is to output this exact text, lowercase/uppercase does not matter, though newlines do:

```<code>bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb
cdefghijklmnopqrstuvwxyzabazyxwvutsrqponmlkjihgfedc
defghijklmnopqrstuvwxyzabcbazyxwvutsrqponmlkjihgfed
efghijklmnopqrstuvwxyzabcdcbazyxwvutsrqponmlkjihgfe
fghijklmnopqrstuvwxyzabcdedcbazyxwvutsrqponmlkjihgf
ghijklmnopqrstuvwxyzabcdefedcbazyxwvutsrqponmlkjihg
hijklmnopqrstuvwxyzabcdefgfedcbazyxwvutsrqponmlkjih
ijklmnopqrstuvwxyzabcdefghgfedcbazyxwvutsrqponmlkji
jklmnopqrstuvwxyzabcdefghihgfedcbazyxwvutsrqponmlkj
klmnopqrstuvwxyzabcdefghijihgfedcbazyxwvutsrqponmlk
lmnopqrstuvwxyzabcdefghijkjihgfedcbazyxwvutsrqponml
mnopqrstuvwxyzabcdefghijklkjihgfedcbazyxwvutsrqponm
nopqrstuvwxyzabcdefghijklmlkjihgfedcbazyxwvutsrqpon
opqrstuvwxyzabcdefghijklmnmlkjihgfedcbazyxwvutsrqpo
pqrstuvwxyzabcdefghijklmnonmlkjihgfedcbazyxwvutsrqp
qrstuvwxyzabcdefghijklmnoponmlkjihgfedcbazyxwvutsrq
rstuvwxyzabcdefghijklmnopqponmlkjihgfedcbazyxwvutsr
stuvwxyzabcdefghijklmnopqrqponmlkjihgfedcbazyxwvuts
tuvwxyzabcdefghijklmnopqrsrqponmlkjihgfedcbazyxwvut
uvwxyzabcdefghijklmnopqrstsrqponmlkjihgfedcbazyxwvu
vwxyzabcdefghijklmnopqrstutsrqponmlkjihgfedcbazyxwv
wxyzabcdefghijklmnopqrstuvutsrqponmlkjihgfedcbazyxw
xyzabcdefghijklmnopqrstuvwvutsrqponmlkjihgfedcbazyx
yzabcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcbazy
zabcdefghijklmnopqrstuvwxyxwvutsrqponmlkjihgfedcbaz
abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba
bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb
abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba
zabcdefghijklmnopqrstuvwxyxwvutsrqponmlkjihgfedcbaz
yzabcdefghijklmnopqrstuvwxwvutsrqponmlkjihgfedcbazy
xyzabcdefghijklmnopqrstuvwvutsrqponmlkjihgfedcbazyx
wxyzabcdefghijklmnopqrstuvutsrqponmlkjihgfedcbazyxw
vwxyzabcdefghijklmnopqrstutsrqponmlkjihgfedcbazyxwv
uvwxyzabcdefghijklmnopqrstsrqponmlkjihgfedcbazyxwvu
tuvwxyzabcdefghijklmnopqrsrqponmlkjihgfedcbazyxwvut
stuvwxyzabcdefghijklmnopqrqponmlkjihgfedcbazyxwvuts
rstuvwxyzabcdefghijklmnopqponmlkjihgfedcbazyxwvutsr
qrstuvwxyzabcdefghijklmnoponmlkjihgfedcbazyxwvutsrq
pqrstuvwxyzabcdefghijklmnonmlkjihgfedcbazyxwvutsrqp
opqrstuvwxyzabcdefghijklmnmlkjihgfedcbazyxwvutsrqpo
nopqrstuvwxyzabcdefghijklmlkjihgfedcbazyxwvutsrqpon
mnopqrstuvwxyzabcdefghijklkjihgfedcbazyxwvutsrqponm
lmnopqrstuvwxyzabcdefghijkjihgfedcbazyxwvutsrqponml
klmnopqrstuvwxyzabcdefghijihgfedcbazyxwvutsrqponmlk
jklmnopqrstuvwxyzabcdefghihgfedcbazyxwvutsrqponmlkj
ijklmnopqrstuvwxyzabcdefghgfedcbazyxwvutsrqponmlkji
hijklmnopqrstuvwxyzabcdefgfedcbazyxwvutsrqponmlkjih
ghijklmnopqrstuvwxyzabcdefedcbazyxwvutsrqponmlkjihg
fghijklmnopqrstuvwxyzabcdedcbazyxwvutsrqponmlkjihgf
efghijklmnopqrstuvwxyzabcdcbazyxwvutsrqponmlkjihgfe
defghijklmnopqrstuvwxyzabcbazyxwvutsrqponmlkjihgfed
cdefghijklmnopqrstuvwxyzabazyxwvutsrqponmlkjihgfedc
bcdefghijklmnopqrstuvwxyzazyxwvutsrqponmlkjihgfedcb
</code>```

This is code-golf, lowest bytecount wins.

Rules:

Standard loopholes are disallowed.

a must be the center of the alphabet diamond.

答:
Groovy - 103 97 bytes

I realise there are cleverer ways of doing this but...

```{t=('a'..'z').join();q={it[-2..0]};c=[];27.times{t=t[1..-1]+t[0];c<<t+q(t)};(c+q(c)).join('\n')}```

When run the result of the script is the requested answer.

(Thanks to carusocomputing for the tip on saving 7 bytes).

Updated example accordingly on:

See http://ideone.com/MkQeoW

Title: Alphabet Diamond

Body:
Groovy - 103 97 bytes

I realise there are cleverer ways of doing this but...

{t=('a'..'z').join();q={it[-2..0]};c=[];27.times{t=t[1..-1]+t[0];c<<t+q(t)};(c+q(c)).join('\n')}

When run the result of the script is the requested answer.

(Thanks to carusocomputing for the tip on saving 7 bytes).

Updated example accordingly on:

See http://ideone.com/MkQeoW


问:
Alphabet wings!
Your task is to print this exact text:

```<code>az                                               za
abyz                                           zyba
abcxyz                                       zyxcba
abcdwxyz                                   zyxwdcba
abcdevwxyz                               zyxwvedcba
abcdefuvwxyz                           zyxwvufedcba
abcdefgtuvwxyz                       zyxwvutgfedcba
abcdefghstuvwxyz                   zyxwvutshgfedcba
abcdefghirstuvwxyz               zyxwvutsrihgfedcba
abcdefghijqrstuvwxyz           zyxwvutsrqjihgfedcba
abcdefghijkpqrstuvwxyz       zyxwvutsrqpkjihgfedcba
abcdefghijklopqrstuvwxyz   zyxwvutsrqpolkjihgfedcba
abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba
  abcdefghijklopqrstuvwxyzyxwvutsrqpolkjihgfedcba
    abcdefghijkpqrstuvwxyzyxwvutsrqpkjihgfedcba
      abcdefghijqrstuvwxyzyxwvutsrqjihgfedcba
        abcdefghirstuvwxyzyxwvutsrihgfedcba
          abcdefghstuvwxyzyxwvutshgfedcba
            abcdefgtuvwxyzyxwvutgfedcba
              abcdefuvwxyzyxwvufedcba
                abcdevwxyzyxwvedcba
                  abcdwxyzyxwdcba
                    abcxyzyxcba
                      abyzyba
                        aza
</code>```

The following are allowed:

Leaving out trailing spaces at the end of lines

Doing everything in uppercase instead of lowercase

Trailing newlines

Remember, this is code-golf, so the code with the smallest number of bytes wins.

答:
Ruby, 109 bytes

Full program that prints a string as required by the question. One byte could be saved by changing to a lambda function that returns an array of strings.

```<code>s=[*(?a..?z)]*""
puts (-12..12).map{|i|(t="%#{(i<=>0)*26}s"%(s[0,13-i.abs]+s[13+i.abs..26]))+t[0,25].reverse}
</code>```

Ungolfed

```<code>s=[*(?a..?z)]*""                     #Convert range 'a'..'z' into an array, then a string.
puts (-12..12).map{|i|               #Iterate over -12..12, make an array of lines then print them.
  (t=                                #t= left side of pattern.
    "%#{(i<=>0)*26}s"%               #Compose format string %-26s or %26s to pad to 26 chars and left/right justify depending on sign.
     (s[0,13-i.abs]+s[13+i.abs..26]) #In this format, print the appropriate number of beginning and ending letters of the alphabet.
   )+
     t[0,25].reverse                 #Righthand side of pattern. Remove the rightmost column from t, reverse it, and concatenate to left side.
}
</code>```

Title: Alphabet wings!

Body:
Ruby, 109 bytes

Full program that prints a string as required by the question. One byte could be saved by changing to a lambda function that returns an array of strings.

s=[*(?a..?z)]*""
puts (-12..12).map{|i|(t="%#{(i<=>0)*26}s"%(s[0,13-i.abs]+s[13+i.abs..26]))+t[0,25].reverse}

Ungolfed

s=[*(?a..?z)]*""                     #Convert range 'a'..'z' into an array, then a string.
puts (-12..12).map{|i|               #Iterate over -12..12, make an array of lines then print them.
  (t=                                #t= left side of pattern.
    "%#{(i<=>0)*26}s"%               #Compose format string %-26s or %26s to pad to 26 chars and left/right justify depending on sign.
     (s[0,13-i.abs]+s[13+i.abs..26]) #In this format, print the appropriate number of beginning and ending letters of the alphabet.
   )+
     t[0,25].reverse                 #Righthand side of pattern. Remove the rightmost column from t, reverse it, and concatenate to left side.
}


问:
Next Friday the 13th
What is the shortest program that can predict the next time Friday will fall on the 13th day of the month?

Must be an complete functioning program (not just a function/subroutine)

Must print out date in the following format: YYYY-MM-DD

Allow user to provide a start date either as a command line argument or through STDIN

If user provides no start date, use today as the start date.

If the start date is a Friday the 13th, the program should find the next Friday the 13th.

If I were to run the program today (Feb 16 2011) I should get the following output.

```<code>$ ./fr13th 2013-05-09
2013-09-13
$ ./fr13th 2007-06-29
2007-07-13
$ ./fr13th 2007-07-13
2008-06-13
$ ./fr13th
2011-05-13
</code>```

答:
Perl (and others), 114

```<code>for(($y,$m,$d)=(shift//`date +%F`)=~/\d+/g,$d>12&&$m++;$m
>12&&($y++,$m=1),`cal $m $y`!~/14$/m;$m++){}say"$y-$m-13"
</code>```

Perl 5.10 or later, run with -E 'code here' or -M5.010 file.  Needs date (from coreutils for Linux) and cal (from util-linux)

Sample run:

```<code>$ perl -M5.010 fr13.pl 2013-05-09
2013-9-13
$ perl -M5.010 fr13.pl 2007-06-29
2007-07-13
$ perl -M5.010 fr13.pl 2007-07-13
2008-6-13
$ perl -M5.010 fr13.pl
2011-5-13
</code>```

I'm not sure when the leading zero for months before October is kept.  It's obviously lost when the year rolls over; it seems to be kept when the answer is just next month.  Let's call that undefined behavior--hey, this is golfing!

ContentLicense: CC BY-SA 2.5

Title: Next Friday the 13th

Body:
Perl (and others), 114

for(($y,$m,$d)=(shift//`date +%F`)=~/\d+/g,$d>12&&$m++;$m
>12&&($y++,$m=1),`cal $m $y`!~/14$/m;$m++){}say"$y-$m-13"

Perl 5.10 or later, run with -E 'code here' or -M5.010 file.  Needs date (from coreutils for Linux) and cal (from util-linux)

Sample run:

$ perl -M5.010 fr13.pl 2013-05-09
2013-9-13
$ perl -M5.010 fr13.pl 2007-06-29
2007-07-13
$ perl -M5.010 fr13.pl 2007-07-13
2008-6-13
$ perl -M5.010 fr13.pl
2011-5-13

I'm not sure when the leading zero for months before October is kept.  It's obviously lost when the year rolls over; it seems to be kept when the answer is just next month.  Let's call that undefined behavior--hey, this is golfing!


问:
Print the digital root
This is different from My Word can beat up your Word as it is less complex and only requires you to calculate it, and not compare them.

To find the digital root, take all of the digits of a number, add them, and repeat until you get a one-digit number. For example, if the number was 12345, you would add 1, 2, 3, 4, and 5, getting 15. You would then add 1 and 5, giving you 6.

Your task

Given an integer N (0 <= N <= 10000) through STDIN, print the digital root of N.

Test cases

```<code>1 -> 1
45 -> 9
341 -> 8
6801 -> 6
59613 -> 6
495106 -> 7
</code>```

Remember, this is code-golf, so the code with the smallest number of bytes wins.

答:
Element, 32 bytes

```<code>_2:1-+9/3:0<!{1-+2:0<!}1+-+9-*+`
</code>```

Try it online!

This is using the typical closed-form formula, although it is noticeably more painful since Element lacks any rounding functionality.

```<code>_2:1-+9/3:0<!{1-+2:0<!}1+-+9-*+`
_2:                               make two copies of input
   1-+9/                          for one copy, subtract 1 and divide by 9
        3:0<!{1-+2:0<!}1+-+       floor it
                           9-*    multiply by -9
                              +`  add to the original input value, then output
</code>```

Title: Print the digital root

Body:
Element, 32 bytes

_2:1-+9/3:0<!{1-+2:0<!}1+-+9-*+`

Try it online!

This is using the typical closed-form formula, although it is noticeably more painful since Element lacks any rounding functionality.

_2:1-+9/3:0<!{1-+2:0<!}1+-+9-*+`
_2:                               make two copies of input
   1-+9/                          for one copy, subtract 1 and divide by 9
        3:0<!{1-+2:0<!}1+-+       floor it
                           9-*    multiply by -9
                              +`  add to the original input value, then output


答:
Perl 6, 29 bytes

{($_,*.comb.sum...10>*)[*-1]}
```

<h1>Expanded:</h1>

<pre class="lang-perl6 prettyprint-override"><code>{ # bare block lambda with implicit parameter ｢$_｣
  ( # generate a sequence

    $_,         # starting with the input
    *.comb.sum  # Whatever lambda that splits into digits, and finds sum
    ...         # keep doing that
    10 > *      # until it is less than 10

  )[ * - 1 ] # get the last value
}
</code>```

Title: Print the digital root

Body:
This is different from My Word can beat up your Word as it is less complex and only requires you to calculate it, and not compare them.

To find the digital root, take all of the digits of a number, add them, and repeat until you get a one-digit number. For example, if the number was 12345, you would add 1, 2, 3, 4, and 5, getting 15. You would then add 1 and 5, giving you 6.

Your task

Given an integer N (0 <= N <= 10000) through STDIN, print the digital root of N.

Test cases

```<code>1 -> 1
45 -> 9
341 -> 8
6801 -> 6
59613 -> 6
495106 -> 7
</code>```

Remember, this is code-golf, so the code with the smallest number of bytes wins.

Body:
Perl 6, 29 bytes

{($_,*.comb.sum...10>*)[*-1]}

Expanded:

{ # bare block lambda with implicit parameter ｢$_｣
  ( # generate a sequence

    $_,         # starting with the input
    *.comb.sum  # Whatever lambda that splits into digits, and finds sum
    ...         # keep doing that
    10 > *      # until it is less than 10

  )[ * - 1 ] # get the last value
}


答:
PHP, Lua 41 Bytes

PHP print trick an Lua treat

```<code>--$a;echo"trick";/*
print("treat")
--*/
</code>```

Title: Trick or Treat polyglot

Body:
Since Halloween is coming up I thought I might start a fun little code golf challenge!

The challenge is quite simple. You have to write a program that outputs either trick or treat.

"The twist?" you may ask. Well let me explain:

Your program has to do the following:

Be compilable/runnable in two different languages. Different versions of the same language don't count.

When you run the program in one language it should output trick and the other should output treat. The case is irrelevant and padding the string with whitespace characters are allowed (see examples).

This is code-golf,  so the solution with the fewest bytes wins.

A few explanations:

Valid outputs (Just for the words not for running the code in the two languages. Also adding quotes to signalize the beginning or end of the output. Do not include them in your solution!):

```<code>"trick"

"Treat"

"    TReAt"

"
     tRICk          "
</code>```

Invalid outputs:

```<code>"tri ck"

"tr
eat"

"trck"
</code>```

I'm interested to see what you can come up with! Happy Golfing!

I'd like to note that this is my first challenge so if you have suggestions on this question please leave them in the form of a comment.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code># Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code># Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code># Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the leaderboard snippet:

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

var QUESTION_ID=97472,OVERRIDE_USER=23417;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,TAGS_REG = /(<([^>]+)>)/ig;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;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:
PHP, Lua 41 Bytes

PHP print trick an Lua treat

--$a;echo"trick";/*
print("treat")
--*/


问:
Display an xkcd
xkcd is everyone's favorite webcomic, and you will be writing a program that will bring a little bit more humor to us all.

Your objective in this challenge is to write a program which will take a number as input and display that xkcd and its title-text (mousover text).

Input

Your program will take a positive integer as input (not necessarily one for which there exists a valid comic) and display that xkcd: for example, an input of 1500 should display the comic "Upside-Down Map" at xkcd.com/1500, and then either print its title-text to the console or display it with the image.

Due to their proximity across the channel, there's long been tension between North Korea and the United Kingdom of Great Britain and Southern Ireland.

Test case 2, for n=859:

<img src="https://i.stack.imgur.com/ItL7a.png" alt="Brains aside, I wonder how many poorly-written xkcd.com-parsing scripts will break on this title (or ;;"''{<<[' this mouseover text."">

Brains aside, I wonder how many poorly-written xkcd.com-parsing scripts will break on this title (or ;;"''{<<[' this mouseover text."

Your program should also be able to function without any input, and perform the same task for the most recent xkcd found at xkcd.com, and it should always display the most recent one even when a new one goes up.

You do not have to get the image directly from xkcd.com, you can use another database as long as it is up-to-date and already existed before this challenge went up. URL shortners, that is, urls with no purpose other than redirecting to somewhere else, are not allowed.

You may display the image in any way you chose, including in a browser. You may not, however, directly display part of another page in an iframe or similar. CLARIFICATION: you cannot open a preexisting webpage, if you wish to use the browser you have to create a new page. You must also actually display an image - outputting an image file is not allowed.

You can handle the case that there isn't an image for a particular comic (e.g. it is interactive or the program was passed a number greater than the amount of comics that have been released) in any reasonable way you wish, including throwing an exception, or printing out an at least single-character string, as long as it somehow signifies to the user that there isn't an image for that input.

You can only display an image and output its title-text, or output an error message for an invalid comic. Other output is not allowed.

This is a code-golf challenge, so the fewest bytes wins.

答:
Python 2.7, <s>309</s> <s>299</s> <s>295</s> 274 bytes

Full program. Definitely more golfable, but having read xkcd comics for so long I couldn't let this pass (who knows if this will be helpful in a future for easily browsing xkcd).

If no input is passed, gets current comic. If a valid comic number is passed as input then gets that comic. If an invalid input (not a number comic in the valid range) is passed, throws an error.

Any suggestions on how to reduce byte count are welcome! Will revisit (and add explanation) when I have more time.

-10 bytes thanks to @Dopapp

-21 bytes thanks to @Shebang

```<code>import urllib as u,re
from PIL import Image
h='http://';x='xkcd.com/'
o=u.URLopener()
t=u.urlopen(h+x+raw_input()).read()
c=sum([re.findall(r,t)for r in[h+'imgs.'+x+'c.*s/.*\.\w{1,3}','\.\w{1,3}" t.*e="(.*)" a']],[])
Image.open(o.retrieve(c[0],'1.png')[0]).show();print c[1]
</code>```

Title: Display an xkcd

Body:
Python 2.7, <s>309</s> <s>299</s> <s>295</s> 274 bytes

Full program. Definitely more golfable, but having read xkcd comics for so long I couldn't let this pass (who knows if this will be helpful in a future for easily browsing xkcd).

If no input is passed, gets current comic. If a valid comic number is passed as input then gets that comic. If an invalid input (not a number comic in the valid range) is passed, throws an error.

Any suggestions on how to reduce byte count are welcome! Will revisit (and add explanation) when I have more time.

-10 bytes thanks to @Dopapp

-21 bytes thanks to @Shebang

import urllib as u,re
from PIL import Image
h='http://';x='xkcd.com/'
o=u.URLopener()
t=u.urlopen(h+x+raw_input()).read()
c=sum([re.findall(r,t)for r in[h+'imgs.'+x+'c.*s/.*\.\w{1,3}','\.\w{1,3}" t.*e="(.*)" a']],[])
Image.open(o.retrieve(c[0],'1.png')[0]).show();print c[1]


答:
Pyth and SMBF, 28 bytes

```<code>"trick"<.q<.q<.q<.q<.q"taert
</code>```

"trick" explanation:

 Pyth has a quit-type operation with .q, which I use at <.q to end the program. Everything afterwards is uninterpreted, but in order for me to fix arity I need to add arity 0 data after each arity-2 <.  Otherwise, the program requires user input (although what Python datum the input wouldn't matter, since it's not used).  Pyth will implicitly print the "trick" at the beginning of the program.

"treat" explanation:

 The only characters that SMBF uses are as follows (the others are no-ops or not examined in memory): "<.<.<.<.<.taert.  The <. sets print out the last five characters of the program in reverse order (hence treat is reversed into taert to have it print as treat).

Title: Trick or Treat polyglot

Body:
Pyth and SMBF, 28 bytes

"trick"<.q<.q<.q<.q<.q"taert

"trick" explanation:

 Pyth has a quit-type operation with .q, which I use at <.q to end the program. Everything afterwards is uninterpreted, but in order for me to fix arity I need to add arity 0 data after each arity-2 <.  Otherwise, the program requires user input (although what Python datum the input wouldn't matter, since it's not used).  Pyth will implicitly print the "trick" at the beginning of the program.

"treat" explanation:

 The only characters that SMBF uses are as follows (the others are no-ops or not examined in memory): "<.<.<.<.<.taert.  The <. sets print out the last five characters of the program in reverse order (hence treat is reversed into taert to have it print as treat).


答:
Forth/Perl, 53 bytes

```<code>1 ?dup : print"trick" ." treat" ; print"trick" or bye
</code>```

Needs a case-insensitive Forth (e.g: GNU Forth).

When run in Forth, it defines a print"trick" word that outputs "treat", then calls it.

When run in Perl, it uses the colon of Forth's word definition as part of a conditional statement. In ?dup, the question mark forms part of the aforementioned conditional statement, and dup gets treated as a bareword (a string without quotes). The dot in Forth's ." primitive gets interpreted as Perl's concatenation operator, and bye gets treated as another bareword.

Title: Trick or Treat polyglot

Body:
Forth/Perl, 53 bytes

1 ?dup : print"trick" ." treat" ; print"trick" or bye

Needs a case-insensitive Forth (e.g: GNU Forth).

When run in Forth, it defines a print"trick" word that outputs "treat", then calls it.

When run in Perl, it uses the colon of Forth's word definition as part of a conditional statement. In ?dup, the question mark forms part of the aforementioned conditional statement, and dup gets treated as a bareword (a string without quotes). The dot in Forth's ." primitive gets interpreted as Perl's concatenation operator, and bye gets treated as another bareword.


答:
JavaScript (ES6), <s>139</s> 109 bytes

```<code>f=(a,v=b=>a.filter(a=>b^!a[0]))=>a[0]?v().concat((a=f([].concat(...v(1))),b=v())[0]?[b]:[],v(1).map(a=>[a])):[]
</code>```

Explanation using the example input: v is a helper method which returns the arrays (with parameter 1) or values (with no parameter). We start with a = [1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]], which is nonempty. We filter out the arrays, giving [1]. We then recursively call ourselves on the arrays concatenated together, which is [2, 3, [4], [[5, 6], 7, [[[8]]]], 9], the result being [2, 3, 9, [4, 7], [[5, 6]], [[[[8]]]]]. We again filter out the arrays, which gives us the second term of our output, [2, 3, 9], however we have to be careful not to insert an empty array here. It them remains to wrap the arrays [4, 7], [[5, 6]], [[[[8]]]] inside arrays and append them to the output, resulting in [1, [2, 3, 9], [[4, 7]], [[[5, 6]]], [[[[[8]]]]]].

Title: Simplificate an array

Body:
Input

An array that can contain arrays or positive, consecutive, ascending integers. The arrays can have any number of arrays inside of them, and so on and so forth. No arrays will be empty.

Output

This array simplificated

How to simplificate an array

We will use the array, [1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]] as our example.

First, we check how deep the values are nested. Here are the depths and the numbers at those depths:

```<code>0  1
1  2 3 9
2  4 7
3  5 6
5  8
</code>```

We construct the output array by taking the numbers in the original array, grouping them by how deep they are nested, and then nesting the groups at depths of the original depths of their  elements. Arrange the numbers in ascending order and ascending depth.

So, our output is [1, [2, 3, 9], [[4, 7]], [[[5, 6]]], [[[[[8]]]]]]

Examples

```<code>[1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]] -> [1, [2, 3, 9], [[4, 7]], [[[5, 6]]], [[[[[8]]]]]]
[[[1]], [2, [3]], 4, [5, [6, [7, [8], [9, [[10]]]]]]] -> [4, [2, 5], [[1, 3, 6]], [[[7]]], [[[[8, 9]]]], [[[[[[10]]]]]]]
[1] -> [1]
[1, [2], [[3]], [[[4]]], [[[[5]]]]] -> [1, [2], [[3]], [[[4]]], [[[[5]]]]]
[1, [[[[2], 3]]], [[4]]] -> [1, [[4]], [[[3]]], [[[[2]]]]]
</code>```

Body:
JavaScript (ES6), <s>139</s> 109 bytes

f=(a,v=b=>a.filter(a=>b^!a[0]))=>a[0]?v().concat((a=f([].concat(...v(1))),b=v())[0]?[b]:[],v(1).map(a=>[a])):[]

Explanation using the example input: v is a helper method which returns the arrays (with parameter 1) or values (with no parameter). We start with a = [1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]], which is nonempty. We filter out the arrays, giving [1]. We then recursively call ourselves on the arrays concatenated together, which is [2, 3, [4], [[5, 6], 7, [[[8]]]], 9], the result being [2, 3, 9, [4, 7], [[5, 6]], [[[[8]]]]]. We again filter out the arrays, which gives us the second term of our output, [2, 3, 9], however we have to be careful not to insert an empty array here. It them remains to wrap the arrays [4, 7], [[5, 6]], [[[[8]]]] inside arrays and append them to the output, resulting in [1, [2, 3, 9], [[4, 7]], [[[5, 6]]], [[[[[8]]]]]].


问:
Randomly Misspell a Word
Inspired by this CR question (please don't kill me for browsing CR)

Spec

The probabilities of misspelling a word are:

1/3 of the time don't change the output

1/3 of the time remove a random character

1/3 of the time duplicate a random character

The chance for removing/duplicating a given character in the input should be the same for all chars.

If two consecutive characters are the same (case-sensitive), the probability of one of them being modified should be the same as if they are one character. I.e. the outputs for AA (which are AA or A or AAA) should all have the same probability.

The input will only contain of letters for simplicity.

Examples

First line is input, following lines are all possible misspellings. Each line should have the same probability of being output, the input is excluded in the examples but it should still have a 1/3 probability of output.

```<code>foo

fo
oo
ffoo
fooo
</code>```

```<code>PPCG

PPC
PPG
PCG
PPPCG
PPCCG
PPCGG
</code>```

答:
Python 2, 123 bytes

from random import*
R=randint
s=input()
m=n=R(0,len(s)-1)
c=R(0,2)
m=[m,1+[-len(s),m][m>0]][c==1]
n+=c==2
print s[:m]+s[n:]
```

Title: Randomly Misspell a Word


问:
Monte Carlo estimator of Pi
Happy Pi Day everyone! For no reason at all, I'm trying to construct a Monte Carlo estimator of Pi that is as short as possible. Can we construct one that can fit in a tweet?

To clarify, what I have in mind is the typical approach of drawing random points from the unit square and calculating the ratio that fall within the unit circle. The number of samples can be hard coded or not. If you hardcode them, you must use at least 1000 samples. The result may be returned or printed as a floating point, fixed point or rational number.

No trig functions or Pi constants, must be a Monte Carlo approach.

This is code golf, so the shortest submission (in bytes) wins.

答:
Python 3, 69 bytes

Apparently shorter than the other python entries, save one that uses <s>sympy</s> numpy (misremembered)

```<code>from random import*
print(eval(('+(1>('+2*'+random()**2)')*2000)/500)
</code>```

Try it online!

Wow, it's been a while since I posted a multiline answer on this site... I've been using Turtlèd too much for that

Explanation:

```<code>from random import*    We can use random.random now as random
print(                 Print the result of the following
      eval(            evaluate the value of the expression in the string
           ('+(1>('+2*'+random()**2)')*2000    the string construction
                                           )/500) divide by 500 and print
</code>```

Explanation of the string expression:

```<code>                             *2000  repeat this 2000 times
    '+(1>('                         have each section joined by a +,
                                    and the first item have the unary +. (nop, essentially)
                                    check if the section is less than 1, if so,
                                    evaluate to 1, else 0
           +2*'+random()**2)'        sum two random numbers squared, close both parens.

                                   [Evaluate the sum]
</code>```

This is about the max accuracy, because 3000 samples gives a recursion error.

(I'll improve this explanation real soon actually.)

Title: Monte Carlo estimator of Pi

Body:
Python 3, 69 bytes

Apparently shorter than the other python entries, save one that uses <s>sympy</s> numpy (misremembered)

from random import*
print(eval(('+(1>('+2*'+random()**2)')*2000)/500)

Try it online!

Wow, it's been a while since I posted a multiline answer on this site... I've been using Turtlèd too much for that

Explanation:

from random import*    We can use random.random now as random
print(                 Print the result of the following
      eval(            evaluate the value of the expression in the string
           ('+(1>('+2*'+random()**2)')*2000    the string construction
                                           )/500) divide by 500 and print

Explanation of the string expression:

                             *2000  repeat this 2000 times
    '+(1>('                         have each section joined by a +,
                                    and the first item have the unary +. (nop, essentially)
                                    check if the section is less than 1, if so,
                                    evaluate to 1, else 0
           +2*'+random()**2)'        sum two random numbers squared, close both parens.

                                   [Evaluate the sum]

This is about the max accuracy, because 3000 samples gives a recursion error.

(I'll improve this explanation real soon actually.)


答:
C / C++, 73 bytes

```<code>#include<stdio.h>
int main(){puts("treat\0trick"+sizeof'1'/sizeof 1*6);}
</code>```

This could fail (printing trick in both C and C++) on an implementation with sizeof (int) == 1, which implies CHAR_BIT >= 16. As far as I know there are no such implementations in the real world.

Changing int main() to int main(void) would make it theoretically more conforming in C, but in practice all C and C++ compilers accept int main().

Title: Trick or Treat polyglot

Body:
C / C++, 73 bytes

#include<stdio.h>
int main(){puts("treat\0trick"+sizeof'1'/sizeof 1*6);}

This could fail (printing trick in both C and C++) on an implementation with sizeof (int) == 1, which implies CHAR_BIT >= 16. As far as I know there are no such implementations in the real world.

Changing int main() to int main(void) would make it theoretically more conforming in C, but in practice all C and C++ compilers accept int main().


答:
Racket 152 bytes

```<code>(let p((ol'())(n n))(let*-values(((q r)(quotient/remainder n 10))((l)(cons r ol)))
(if(= q 0)(begin(let((s(apply + l)))(if(< s 10)s(p'()s))))(p l q)))))
</code>```

Ungolfed:

```<code>(define (f n)
  (let loop ((ol '())
             (n n))
    (let*-values (((q r) (quotient/remainder n 10))
                 ((l) (cons r ol)))
      (if (= q 0)
          (begin
            (let ((s (apply + l)))
              (if (< s 10)
                  s
                  (loop '() s))))
          (loop l q))
      )))
</code>```

Simpler version:

```<code>(define (f1 N)
  (define (getDigitList n)                   ; sub-fn  to get digits
    (let loop ((ol '())
               (n n))
      (let-values (((q r) (quotient/remainder n 10)))
        (if (= q 0) (cons r ol)
            (loop (cons r ol) q)))))

    (let loop2 ((n N))                       ; actual fn
      (define s (apply + (getDigitList n)))  ; get sum of digits
      (if (< s 10)
          s
          (loop2 s))))
</code>```

Testing:

```<code>(f 1)
(f 45)
(f 341)
(f 6801)
(f 59613)
(f 495106)
</code>```

Output:

```<code>1
9
8
6
6
7
</code>```

Title: Print the digital root

Body:
Racket 152 bytes

(let p((ol'())(n n))(let*-values(((q r)(quotient/remainder n 10))((l)(cons r ol)))
(if(= q 0)(begin(let((s(apply + l)))(if(< s 10)s(p'()s))))(p l q)))))

Ungolfed:

(define (f n)
  (let loop ((ol '())
             (n n))
    (let*-values (((q r) (quotient/remainder n 10))
                 ((l) (cons r ol)))
      (if (= q 0)
          (begin
            (let ((s (apply + l)))
              (if (< s 10)
                  s
                  (loop '() s))))
          (loop l q))
      )))

Simpler version:

(define (f1 N)
  (define (getDigitList n)                   ; sub-fn  to get digits
    (let loop ((ol '())
               (n n))
      (let-values (((q r) (quotient/remainder n 10)))
        (if (= q 0) (cons r ol)
            (loop (cons r ol) q)))))

    (let loop2 ((n N))                       ; actual fn
      (define s (apply + (getDigitList n)))  ; get sum of digits
      (if (< s 10)
          s
          (loop2 s))))

Testing:

(f 1)
(f 45)
(f 341)
(f 6801)
(f 59613)
(f 495106)

Output:

1
9
8
6
6
7


Title: Monte Carlo estimator of Pi

Body:
Happy Pi Day everyone! For no reason at all, I'm trying to construct a Monte Carlo estimator of Pi that is as short as possible. Can we construct one that can fit in a tweet?

To clarify, what I have in mind is the typical approach of drawing random points from the unit square and calculating the ratio that fall within the unit circle. The number of samples can be hard coded or not. If you hardcode them, you must use at least 1000 samples. The result may be returned or printed as a floating point, fixed point or rational number.

No trig functions or Pi constants, must be a Monte Carlo approach.

This is code golf, so the shortest submission (in bytes) wins.

Body:
Racket 63 bytes

Using method of R language answer by @Matt :

(/(for/sum((i n))(define a(/(random 11)10))(/ 4(+ 1(* a a))))n)

Ungolfed:

(define(f n)
   (/
    (for/sum ((i n))
      (define a (/(random 11)10))
      (/ 4(+ 1(* a a))))
    n))

Testing:

(f 10000)

Output (fraction):

3 31491308966059784/243801776017028125

As decimal:

(exact->inexact(f 10000))

3.13583200307849


答:
Python and Lua, 29 bytes

This solution is posted separately from but in addition to my other solution due to the use of a different set of languages and a much more competitive byte count.

The 29th byte is the newline at the end. In Python, the empty string '' is considered a falsey value, while in Lua, it's considered true. In Lua, the or is short-circuited by ''and'trick' evaluating to a true value and printing, while in Python the and short-circuits due to '' and prints the true value on the other side of the or.

```<code>print(''and'trick'or'treat')
</code>```

Title: Trick or Treat polyglot

Body:
Python and Lua, 29 bytes

This solution is posted separately from but in addition to my other solution due to the use of a different set of languages and a much more competitive byte count.

The 29th byte is the newline at the end. In Python, the empty string '' is considered a falsey value, while in Lua, it's considered true. In Lua, the or is short-circuited by ''and'trick' evaluating to a true value and printing, while in Python the and short-circuits due to '' and prints the true value on the other side of the or.

print(''and'trick'or'treat')


问:
Shortest code to produce infinite output
Write the shortest code you can that produces an infinite output.

That's all. You code will only be disqualified if it stops producing output at some point. As always in code golf, the shortest code wins.

Here's a list of answers that I think are really clever, so they can get credit:

The comma is both code and data

Infinite errors (that counts)

Infinite warnings (that also counts)

What's Marbelous?

Leaderboard

var QUESTION_ID=13152,OVERRIDE_USER=8611;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

```

答:
Ruby, 10 bytes

loop{puts}
```

This program prints out an infinite stream of newlines.

Body:
Ruby, 10 bytes

loop{puts}

This program prints out an infinite stream of newlines.


答:
JavaScript (ES6), 103

```<code>w=>{w=w.split(''),r=Math.random,x=r(),i=r()*w.length|0;w.splice(i,x<.6,x>.3?w[i]:'');alert(w.join(''))}
</code>```

Title: Randomly Misspell a Word

Body:
Inspired by this CR question (please don't kill me for browsing CR)

Spec

The probabilities of misspelling a word are:

1/3 of the time don't change the output

1/3 of the time remove a random character

1/3 of the time duplicate a random character

The chance for removing/duplicating a given character in the input should be the same for all chars.

If two consecutive characters are the same (case-sensitive), the probability of one of them being modified should be the same as if they are one character. I.e. the outputs for AA (which are AA or A or AAA) should all have the same probability.

The input will only contain of letters for simplicity.

Examples

First line is input, following lines are all possible misspellings. Each line should have the same probability of being output, the input is excluded in the examples but it should still have a 1/3 probability of output.

```<code>foo

fo
oo
ffoo
fooo
</code>```

```<code>PPCG

PPC
PPG
PCG
PPPCG
PPCCG
PPCGG
</code>```

Body:
JavaScript (ES6), 103

w=>{w=w.split(''),r=Math.random,x=r(),i=r()*w.length|0;w.splice(i,x<.6,x>.3?w[i]:'');alert(w.join(''))}


答:
APL, 27 bytes

```<code>{⍵/⍨(?3)⌷1⍪2 0∘.|1+(⍳=?)⍴⍵}
</code>```

Explanation:

```<code>                        ⍴⍵  ⍝ length of ⍵
                   (⍳=?)    ⍝ bit vector with one random bit on
                 1+         ⍝ add one to each value (duplicate one character)
           2 0∘.|           ⍝ mod by 2 and 0 (remove instead of duplicate)
         1⍪                 ⍝ add a line of just ones (do nothing)
    (?3)⌷                   ⍝ select a random line from that matrix
 ⍵/⍨                        ⍝ replicate characters in ⍵
</code>```

Test:

```<code>      {⍵/⍨(?3)⌷1⍪2 0∘.|1+(⍳=?)⍴⍵} ¨ 10/⊂'foo'
 fooo  foo  oo  foo  fo  fo  oo  fo  oo  fooo
</code>```

Title: Randomly Misspell a Word

Body:
APL, 27 bytes

{⍵/⍨(?3)⌷1⍪2 0∘.|1+(⍳=?)⍴⍵}

Explanation:

                        ⍴⍵  ⍝ length of ⍵
                   (⍳=?)    ⍝ bit vector with one random bit on
                 1+         ⍝ add one to each value (duplicate one character)
           2 0∘.|           ⍝ mod by 2 and 0 (remove instead of duplicate)
         1⍪                 ⍝ add a line of just ones (do nothing)
    (?3)⌷                   ⍝ select a random line from that matrix
 ⍵/⍨                        ⍝ replicate characters in ⍵

Test:

      {⍵/⍨(?3)⌷1⍪2 0∘.|1+(⍳=?)⍴⍵} ¨ 10/⊂'foo'
 fooo  foo  oo  foo  fo  fo  oo  fo  oo  fooo


答:
Perl, 110 bytes

98 bytes code + 12 for -plC -Mutf8.

Perl does hate unicode. Hopefully I haven't missed any edge cases, I had an issue with numbers like 二百十 but I've addressed that now!

s/十/*10+/;s/百/*100+/;y/一二三四五六七八九零/123456789 /;s/^\*|\+\*/+/g;$_=eval"$_-0"
```

<h3>Usage</h3>

<pre class="lang-sh prettyprint-override"><code>perl -plC -Mutf8 -e 's/十/*10+/;s/百/*100+/;y/一二三四五六七八九零/123456789 /;s/^\*|\+\*/+/g;$_=eval"$_-0"' <<< '一
二
三
四
五
六
七
八
九
十
十一
二十四
八十三
九十
一百
二百三十一
八百零三
九百九十九'
1
2
3
4
5
6
7
8
9
10
11
24
83
90
100
231
803
999
</code>```

Title: Convert Chinese numbers

Body:
In Chinese, numbers are written as follows:

1 一 2 二 3 三 4 四 5 五 6 六 7 七 8 八 9 九 10 十

For numbers above 10, it is expressed as the number of tens and the number of ones. If there is only one ten, you do not need to explicitly say one, and if there are no ones, you don't need to put anything after:

11 十一

24 二十四

83 八十三

90 九十

For numbers above 100, you use the same logic, but with the character 百. This time though, if there is only one hundred, you still need to write it out, and if there are no tens, you need to say 零.

100 一百 231 二百三十一 803 八百零三 999 九百九十九

Your task is to convert these Chinese numerals into Arabic numerals. Given a number N in Chinese (一 (1) <= N <= 九百九十九 (999)), convert it into an Arabic number.

Remember, this is code-golf, so the code with the smallest number of bytes wins.

Body:
Perl, 110 bytes

98 bytes code + 12 for -plC -Mutf8.

Perl does hate unicode. Hopefully I haven't missed any edge cases, I had an issue with numbers like 二百十 but I've addressed that now!

s/十/*10+/;s/百/*100+/;y/一二三四五六七八九零/123456789 /;s/^\*|\+\*/+/g;$_=eval"$_-0"

Usage

perl -plC -Mutf8 -e 's/十/*10+/;s/百/*100+/;y/一二三四五六七八九零/123456789 /;s/^\*|\+\*/+/g;$_=eval"$_-0"' <<< '一
二
三
四
五
六
七
八
九
十
十一
二十四
八十三
九十
一百
二百三十一
八百零三
九百九十九'
1
2
3
4
5
6
7
8
9
10
11
24
83
90
100
231
803
999


答:
Java 7, <s>236</s> <s>233</s> 229 bytes

```<code>int c(String s){String x=" 一二三四五六七八九十百";int l=s.length(),i=x.indexOf(s.charAt(l-1)),j=x.indexOf(s.charAt(0)),q=j*100;return l<2?i:l<3?i==10?j*10:i>10?q:10+i:l<4?j*10+i:l<5?q+i:q+i+x.indexOf(s.charAt(2))*10;}
</code>```

Ungolfed & test code:

Try it here.

```<code>class M{
  static int c(String s){
    String x = " 一二三四五六七八九十百";
    int l = s.length(),
        i = x.indexOf(s.charAt(l-1)),
        j = x.indexOf(s.charAt(0));
    if(l<2) return i; // 1-10
    if(l<3){
      if(i==10) return j*10; // 20,30,40,50,60,70,80,90
      if(i>10) return j*100; // 100,200,300,400,500,600,700,800,900
      return 10+i; // 11-19
    }
    if(l<4) return j*10+i; // 21-29,31-39,41-49,51-59,61-69,71-79,81-89,91-99
    if(l<5) return j*100+i; // 101-109,201-209,301-309,401-409,501-509,601-609,701-709,801-809,901-909
    return j*100+i+x.indexOf(s.charAt(2))*10; // 111-119,121-129,131-139,...,971-979,981-989,991-999
  }

  public static void main(String[] a){
    System.out.println(c("一"));
    System.out.println(c("二"));
    System.out.println(c("三"));
    System.out.println(c("四"));
    System.out.println(c("五"));
    System.out.println(c("六"));
    System.out.println(c("七"));
    System.out.println(c("八"));
    System.out.println(c("九"));
    System.out.println(c("十"));
    System.out.println(c("十一"));
    System.out.println(c("二十四"));
    System.out.println(c("八十三"));
    System.out.println(c("九十"));
    System.out.println(c("一百"));
    System.out.println(c("二百三十一"));
    System.out.println(c("八百零三"));
    System.out.println(c("九百九十九"));
  }
}
</code>```

Output:

```<code>1
2
3
4
5
6
7
8
9
10
11
24
83
90
100
231
803
999
</code>```

Title: Convert Chinese numbers

Body:
Java 7, <s>236</s> <s>233</s> 229 bytes

int c(String s){String x=" 一二三四五六七八九十百";int l=s.length(),i=x.indexOf(s.charAt(l-1)),j=x.indexOf(s.charAt(0)),q=j*100;return l<2?i:l<3?i==10?j*10:i>10?q:10+i:l<4?j*10+i:l<5?q+i:q+i+x.indexOf(s.charAt(2))*10;}

Ungolfed & test code:

Try it here.

class M{
  static int c(String s){
    String x = " 一二三四五六七八九十百";
    int l = s.length(),
        i = x.indexOf(s.charAt(l-1)),
        j = x.indexOf(s.charAt(0));
    if(l<2) return i; // 1-10
    if(l<3){
      if(i==10) return j*10; // 20,30,40,50,60,70,80,90
      if(i>10) return j*100; // 100,200,300,400,500,600,700,800,900
      return 10+i; // 11-19
    }
    if(l<4) return j*10+i; // 21-29,31-39,41-49,51-59,61-69,71-79,81-89,91-99
    if(l<5) return j*100+i; // 101-109,201-209,301-309,401-409,501-509,601-609,701-709,801-809,901-909
    return j*100+i+x.indexOf(s.charAt(2))*10; // 111-119,121-129,131-139,...,971-979,981-989,991-999
  }

  public static void main(String[] a){
    System.out.println(c("一"));
    System.out.println(c("二"));
    System.out.println(c("三"));
    System.out.println(c("四"));
    System.out.println(c("五"));
    System.out.println(c("六"));
    System.out.println(c("七"));
    System.out.println(c("八"));
    System.out.println(c("九"));
    System.out.println(c("十"));
    System.out.println(c("十一"));
    System.out.println(c("二十四"));
    System.out.println(c("八十三"));
    System.out.println(c("九十"));
    System.out.println(c("一百"));
    System.out.println(c("二百三十一"));
    System.out.println(c("八百零三"));
    System.out.println(c("九百九十九"));
  }
}

Output:

1
2
3
4
5
6
7
8
9
10
11
24
83
90
100
231
803
999


问:
Minify Brainfuck
Your challenge is to minify Brainfuck code, according to these rules:

Remove anything that is not one of +-><[].,.

For any group of consecutive + or - characters, if the amount of +s and -s is the same, remove them.

Do the same as above, but with > and <.

Remove sequences of the +->< characters if they do nothing. For example, you should remove +>-<->+<. (This may be the trickiest and hardest one to implement.) Make sure you don't get any false positives, like +>-<+>-<, which should not be removed.

Test cases:

Input

```<code>++++++[->++++++<]>.   prints a $
[-]<                  resets tape
>,[>,]<[.<]           reverses NUL terminated input string
++-->><<              does nothing
</code>```

Output

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

Input

```<code>Should disappear: ++>>+<+++<->-->-<<->-<
Should disappear: +++>-<--->+<
Should stay: +++>-<+>---<
</code>```

Output

```<code>+++>-<+>---<
</code>```

You may accept input and output however you would like - stdin/stdout, a function, etc., but input may not be hardcoded.

This is code-golf, so the shortest code in character count will win.

Title: Minify Brainfuck

Body:
Brainfuck, 579 bytes

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

With formatting and some comments:

,
[
  <<+>> >>+<<
  [
    [<+> >+<-]
    ++++++[>-------<-]
    >-
    [
      not plus
      -
      [
        not comma
        -
        [
          not minus
          -
          [
            not period
            --------------
            [
              not less than
              --
              [
                not greater than
                <+++++[>------<-]>+
                [
                  not open bracket
                  --
                  [
                    not close bracket
                    <<[-]>>-
                  ]
                ]
                <
              ]
              >
              [
                greater than
                >>-<<
                <<<[-]<[<]<<<[<]
                >>>>>>>>[<]
                <-[+>]
                +[->+]
                >>>>+>[<-]
                <[>+<-<]
                >
              ]
              <
            ]
            >
            [
              less than
              <<<[-]-[<]
              >>>> >>>>>>>[<]
              <<<<<<[<]
              <-[+>]
              +[-<+]
              <<<+<[>-<<<]
              >[-<+<]
            ]
          ]
          <
        ]
        >
        [
          minus
          +>[-<]
          <[<<]
          <[-]>>
        ]
      ]
      <
    ]
    +>
    [
      plus
      -[<-]
      <[>+>+<<-<]
      <[-]>+>
    ]
    <<
    [
      comma or period or bracket
      >-
    ]
    >[,>]
    <
  ]
  comma or period or bracket or eof
  <+<
  [
    start and end same cell
    >
  ]
  >
  [
    >>>
    [
      <<<<[-<]<<<
    ]
    >>>+>>>>
    [
      start right of end
      <<<<->>>>
      [>>>[-<]>>>>]
    ]
  ]
  >
  [
    <<<
    [
      <+[-->>]
    ]
    >[-[.[-]]]
    >[<]
    >
    [
      <<++++++[>+++++++<-]>+>>
      [<<.>>-]
      <<++>-[<.>-]
      +++[<+++++>-]
      +<<<<< <+>
      [
        <<
        [
          go left
          >->>>>>.
          [[-]<<<<]
          <<<+>>>
        ]
        >
        [
          toggle left right
          ->->>>>[-]
        ]
      ]
      <
      [
        toggle right left
        ->+[>>>>>]>>[<]
        <<<<<<<<
        [
          [-]<
        ]
        >
        [
          go right
          ++.[-]
          >>>>>>>
        ]
        <
      ]
    ]
    >>
  ]
  <[>>>>>>>]
  +[-<<<<<[-]<<]
  ,
]

This uses the same approach as Keith Randall's solution, minifying all contiguous sequences of +-<> optimally by simulation. For example, +++>-<+>---< becomes ++++>----< and >+<+<<+>+<->>>> becomes +<+>>+>.

<a href="http://brainfuck.tryitonline.net/#code=LFs8PCs-Pj4-Kzw8W1s8Kz4-KzwtXSsrKysrK1s-LS0tLS0tLTwtXT4tWy1bLVstWy0tLS0tLS0tLS0tLS0tWy0tWzwrKysrK1s-LS0tLS0tPC1dPitbLS1bPDxbLV0-Pi1dXTxdPls-Pi08PDw8PFstXTxbPF08PDxbPF0-Pj4-Pj4-Pls8XTwtWys-XStbLT4rXT4-Pj4rPls8LV08Wz4rPC08XT5dPF0-Wzw8PFstXS1bPF0-Pj4-Pj4-Pj4-Pls8XTw8PDw8PFs8XTwtWys-XStbLTwrXTw8PCs8Wz4tPDw8XT5bLTwrPF1dXTxdPlsrPlstPF08Wzw8XTxbLV0-Pl1dPF0rPlstWzwtXTxbPis-Kzw8LTxdPFstXT4rPl08PFs-LV0-Wyw-XTxdPCs8Wz5dPls-Pj5bPDw8PFstPF08PDxdPj4-Kz4-Pj5bPDw8PC0-Pj4-Wz4-PlstPF0-Pj4-XV1dPls8PDxbPCtbLS0-Pl1dPlstWy5bLV1dXT5bPF0-Wzw8KysrKysrWz4rKysrKysrPC1dPis-Pls8PC4-Pi1dPDwrKz4tWzwuPi1dKysrWzwrKysrKz4tXSs8PDw8PDwrPls8PFs-LT4-Pj4-LltbLV08PDw8XTw8PCs-Pj5dPlstPi0-Pj4-Wy1dXV08Wy0-K1s-Pj4-Pl0-Pls8XTw8PDw8PDw8W1stXTxdPlsrKy5bLV0-Pj4-Pj4-XTxdXT4-XTxbPj4-Pj4-Pl0rWy08PDw8PFstXTw8XSxd&input=KysrKysrWy0-KysrKysrPF0-LiAgIHByaW50cyBhICQKWy1dPCAgICAgICAgICAgICAgICAgIHJlc2V0cyB0YXBlCj4sWz4sXTxbLjxdICAgICAgICAgICByZXZlcnNlcyBOVUwgdGVybWluYXRlZCBpbnB1dCBzdHJpbmcKKystLT4-PDwgICAgICAgICAgICAgIGRvZXMgbm90aGluZw">Try it online.
(If a simulated cell's absolute value gets close to 256, there will be overflow issues.)

The overall structure is

while not EOF:
  while not EOF and next char not in ",.[]":
    process char
  print minified sequence (followed by the char in ",.[]" if applicable)

The tape is divided into 7-cell nodes; at the beginning of the inner loop, the memory layout is

0 s 0 c 0 a b

where s is a boolean flag for start cell, c is the current character, a is the negative part of the simulated cell value (plus one), and b is the positive part of the simulated cell value.

When the minified sequence is being printed, the memory layout is

d n e 0 0 a b

where d is a boolean flag for direction, a and b are as before (but become one/zero when printed), and n and e are only nonzero for the end node; n is related to how many times the node has been seen, and e is the value of the char that halted the inner loop (plus one).

Originally I considered keeping track of more information per node: leftmost and rightmost node as boolean flags, and node's position in relation to the start and end nodes. But we can avoid that by looking at neighboring cells when needed, and by doing left and right scans in order to find the start node.

When printing the minified sequence and deciding how to move the simulated pointer, we can take a general approach: start by moving away from the end node (in an arbitrary direction if start and end nodes are the same), turn around at leftmost and rightmost nodes, and stop based on the number of times the end node has been seen: 3 times if the start and end nodes are the same, otherwise 2.


答:
R, <s>358</s> <s>328</s> <s>310</s> 298 bytes

```<code>f=function(x){H="http:";p=paste0;library(XML);a=xpathSApply(htmlParse(p(H,'//xkcd.com/',x)),'//div/img',xmlAttrs)[[1]];download.file(p(H,a[1]),'a');I=`if`(grepl('png',a[1]),png::readPNG,jpeg::readJPEG)('a');d=dim(I)/100;quartz(,d[2],d[1]);par(mar=rep(0,4));frame();rasterImage(I,0,0,1,1);cat(a[2])}
</code>```

With new lines and comments:

f=function(x){
H="http:"
p=paste0
library(XML) #Needed for xpathSApply, htmlParse and xmlAttrs
# The following line find the first img element and extract its attributes
a=xpathSApply(htmlParse(p(H,'//xkcd.com/',x)),'//div/img',xmlAttrs)[[1]]
download.file(p(H,a[1]),'a') #Download to a file called 'a'
I=`if`(grepl('png',a[1]),png::readPNG,jpeg::readJPEG)('a') #Check if png or jpeg and load the file accordingly
d=dim(I)/100 #convert dimension from pixel to inches (100 ppi).
quartz(,d[2],d[1]) #open a window of the correct dimension
par(mar=rep(0,4)) #Get rid of margins
frame() #Create empty plot
rasterImage(I,0,0,1,1) #Add png/jpeg to the plot
cat(a[2]) #Print title text to stdout
}
```

Screenshots of test cases:

for x=1500:

for x empty:

case when picture is a jpeg:

x=859:

Title: Display an xkcd

Body:
xkcd is everyone's favorite webcomic, and you will be writing a program that will bring a little bit more humor to us all.

Your objective in this challenge is to write a program which will take a number as input and display that xkcd and its title-text (mousover text).

Input

Your program will take a positive integer as input (not necessarily one for which there exists a valid comic) and display that xkcd: for example, an input of 1500 should display the comic "Upside-Down Map" at xkcd.com/1500, and then either print its title-text to the console or display it with the image.

Due to their proximity across the channel, there's long been tension between North Korea and the United Kingdom of Great Britain and Southern Ireland.

Test case 2, for n=859:

<img src="https://i.stack.imgur.com/ItL7a.png" alt="Brains aside, I wonder how many poorly-written xkcd.com-parsing scripts will break on this title (or ;;"''{<<[' this mouseover text."">

Brains aside, I wonder how many poorly-written xkcd.com-parsing scripts will break on this title (or ;;"''{<<[' this mouseover text."

Your program should also be able to function without any input, and perform the same task for the most recent xkcd found at xkcd.com, and it should always display the most recent one even when a new one goes up.

You do not have to get the image directly from xkcd.com, you can use another database as long as it is up-to-date and already existed before this challenge went up. URL shortners, that is, urls with no purpose other than redirecting to somewhere else, are not allowed.

You may display the image in any way you chose, including in a browser. You may not, however, directly display part of another page in an iframe or similar. CLARIFICATION: you cannot open a preexisting webpage, if you wish to use the browser you have to create a new page. You must also actually display an image - outputting an image file is not allowed.

You can handle the case that there isn't an image for a particular comic (e.g. it is interactive or the program was passed a number greater than the amount of comics that have been released) in any reasonable way you wish, including throwing an exception, or printing out an at least single-character string, as long as it somehow signifies to the user that there isn't an image for that input.

You can only display an image and output its title-text, or output an error message for an invalid comic. Other output is not allowed.

This is a code-golf challenge, so the fewest bytes wins.

Body:
R, <s>358</s> <s>328</s> <s>310</s> 298 bytes

f=function(x){H="http:";p=paste0;library(XML);a=xpathSApply(htmlParse(p(H,'//xkcd.com/',x)),'//div/img',xmlAttrs)[[1]];download.file(p(H,a[1]),'a');I=`if`(grepl('png',a[1]),png::readPNG,jpeg::readJPEG)('a');d=dim(I)/100;quartz(,d[2],d[1]);par(mar=rep(0,4));frame();rasterImage(I,0,0,1,1);cat(a[2])}

With new lines and comments:

f=function(x){
H="http:"
p=paste0
library(XML) #Needed for xpathSApply, htmlParse and xmlAttrs
# The following line find the first img element and extract its attributes
a=xpathSApply(htmlParse(p(H,'//xkcd.com/',x)),'//div/img',xmlAttrs)[[1]]
download.file(p(H,a[1]),'a') #Download to a file called 'a'
I=`if`(grepl('png',a[1]),png::readPNG,jpeg::readJPEG)('a') #Check if png or jpeg and load the file accordingly
d=dim(I)/100 #convert dimension from pixel to inches (100 ppi).
quartz(,d[2],d[1]) #open a window of the correct dimension
par(mar=rep(0,4)) #Get rid of margins
frame() #Create empty plot
rasterImage(I,0,0,1,1) #Add png/jpeg to the plot
cat(a[2]) #Print title text to stdout
}

Screenshots of test cases:

for x=1500:

for x empty:

case when picture is a jpeg:

x=859:


问:
Draw an hourglass
Again inspired by a task for Programming 101 here's another challenge.

Input:

A positive integer n >= 3. (has to be odd)

Output:

n lines of asterisks, where the first line has n asterisks and every new line has two asterisks less than the line before. Until hitting 1 asterisk. From there every new line has two asterisks more than the line before until getting back to n asterisks. Spaces or something like spaces have to used to align the asterisks so that it really will look like an hourglass.

General rules:

Trailing newlines are allowed but do not have to be used.

indentation is a must.

This is code-golf, so shortest answer in bytes wins.

Since the course is taught in C++, I'm eager to see solutions in C++.

Test case (n=5):

```<code>*****
 ***
  *
 ***
*****
</code>```

答:
Batch, <s>191</s> 154 bytes

```<code>@echo off
set s=*
set l=for /l %%i in (2,1,%1)do call:
%l%s
%l%s
%l%u
%l%l
:l
echo %s%
:s
set s=%s:~1%**
exit/b
:u
echo %s%
set s= %s:~0,-2%
</code>```

The u subroutine generates the top half of the hourglass by prepending a space and removing two trailing stars each time. The l subroutine generates the bottom half of the hourglass by removing a space and appending two trailing stars each time. The code falls through into the l subroutine at the end to save bytes. The second half of the l subroutine is also used to build up the initial string, although it has to be called twice as many times as the string doesn't have its spaces yet.

Edit: Saved 37 bytes by using an idea by @ConorO'Brien.

Title: Draw an hourglass

Body:
Batch, <s>191</s> 154 bytes

@echo off
set s=*
set l=for /l %%i in (2,1,%1)do call:
%l%s
%l%s
%l%u
%l%l
:l
echo %s%
:s
set s=%s:~1%**
exit/b
:u
echo %s%
set s= %s:~0,-2%

The u subroutine generates the top half of the hourglass by prepending a space and removing two trailing stars each time. The l subroutine generates the bottom half of the hourglass by removing a space and appending two trailing stars each time. The code falls through into the l subroutine at the end to save bytes. The second half of the l subroutine is also used to build up the initial string, although it has to be called twice as many times as the string doesn't have its spaces yet.

Edit: Saved 37 bytes by using an idea by @ConorO'Brien.


答:
Perl, 15 bytes

Includes +2 for -lp

Give input on STDIN

```<code>root.pl <<< 123
</code>```

root.pl

```<code>#!/usr/bin/perl -lp
$_&&=~-$_%9+1
</code>```

This is the boring solution that has already been given in many languages, but at least this version supports 0 too

More interesting doing real repeated additions (though in another order) is in fact only 1 byte longer:

```<code>#!/usr/bin/perl -p
s%%$_+=chop%reg
</code>```

Title: Print the digital root

Body:
This is different from My Word can beat up your Word as it is less complex and only requires you to calculate it, and not compare them.

To find the digital root, take all of the digits of a number, add them, and repeat until you get a one-digit number. For example, if the number was 12345, you would add 1, 2, 3, 4, and 5, getting 15. You would then add 1 and 5, giving you 6.

Your task

Given an integer N (0 <= N <= 10000) through STDIN, print the digital root of N.

Test cases

```<code>1 -> 1
45 -> 9
341 -> 8
6801 -> 6
59613 -> 6
495106 -> 7
</code>```

Remember, this is code-golf, so the code with the smallest number of bytes wins.

Body:
Perl, 15 bytes

Includes +2 for -lp

Give input on STDIN

root.pl <<< 123

root.pl

#!/usr/bin/perl -lp
$_&&=~-$_%9+1

This is the boring solution that has already been given in many languages, but at least this version supports 0 too

More interesting doing real repeated additions (though in another order) is in fact only 1 byte longer:

#!/usr/bin/perl -p
s%%$_+=chop%reg


答:
Powershell, 93 Bytes

93 Byte version to use local image viewer.

```<code>$n=(iwr xkcd.com/$args).images|?{$_.title};$n.title;iwr ("http:"+$n.src) -OutF x.jpg;ii x.*
</code>```

Saved 2 bytes by removing needless doublequotes, then another lot by using ("http:"+$n.src) instead of "https://"+$n.src.trim("/") - since the img src comes with // already on it, and xkcd doesn't require https.

```<code>$n=(iwr xkcd.com/$args).images|?{$_.title};$n.title;saps ("http:"+$n.src)
</code>```

$n=(iwr "xkcd.com/$args").images|?{$_.title};$n.title;saps ("https://"+$n.src.trim("/"))

extremely similar to Matts powershell answer, (should probably be a comment but low reputation)

Instead this opens a new tab/window in the default browser, and other things, saving some bytes.

iwr is an alias for Invoke-WebRequest

saps is an alias for Start-Process which opens 'it' in the default context.

Title: Display an xkcd

Body:
Powershell, 93 Bytes

93 Byte version to use local image viewer.

$n=(iwr xkcd.com/$args).images|?{$_.title};$n.title;iwr ("http:"+$n.src) -OutF x.jpg;ii x.*

Saved 2 bytes by removing needless doublequotes, then another lot by using ("http:"+$n.src) instead of "https://"+$n.src.trim("/") - since the img src comes with // already on it, and xkcd doesn't require https.

$n=(iwr xkcd.com/$args).images|?{$_.title};$n.title;saps ("http:"+$n.src)

$n=(iwr "xkcd.com/$args").images|?{$_.title};$n.title;saps ("https://"+$n.src.trim("/"))

extremely similar to Matts powershell answer, (should probably be a comment but low reputation)

Instead this opens a new tab/window in the default browser, and other things, saving some bytes.

iwr is an alias for Invoke-WebRequest

saps is an alias for Start-Process which opens 'it' in the default context.


问:
This isn't rocket science
Write a program or function that takes in a single-line string. You can assume it only contains printable ASCII. Print or return a string of an ASCII art rocket such as

```<code>  |
 /_\
 |E|
 |a|
 |r|
 |t|
 |h|
 |_|
/___\
 VvV
</code>```

with the input string written from top to bottom on the fuselage. In this case the input was Earth. The height of the rocket (including flames) is always the length of the string plus five.

Each line in the output may have up to two trailing spaces and there may be a single optional trailing newline. The shortest code in bytes wins.

More Examples:

```<code>[empty string]

  |
 /_\
 |_|
/___\
 VvV

a

  |
 /_\
 |a|
 |_|
/___\
 VvV

|0

  |
 /_\
 |||
 |0|
 |_|
/___\
 VvV

\/\

  |
 /_\
 |\|
 |/|
 |\|
 |_|
/___\
 VvV

 _ _ [note trailing space]

  |
 /_\
 | |
 |_|
 | |
 |_|
 | |
 |_|
/___\
 VvV

    [4 spaces]

  |
 /_\
 | |
 | |
 | |
 | |
 |_|
/___\
 VvV

SPACEY

  |
 /_\
 |S|
 |P|
 |A|
 |C|
 |E|
 |Y|
 |_|
/___\
 VvV
</code>```

Leaderboard

var QUESTION_ID=91182,OVERRIDE_USER=26997;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

```

Title: This isn't rocket science

Body:
Perl, 51 bytes

50 bytes code + 1 for -p.

s/./$&|
 |/g;s~^~  |
 /_\\
 |~;s~$~_|
/___\\
 VvV~

Usage

perl -pe 's/./$&|
 |/g;s~^~  |
 /_\\
 |~;s~$~_|
/___\\
 VvV~' <<< earth
  |
 /_\
 |e|
 |a|
 |r|
 |t|
 |h|
 |_|
/___\
 VvV

perl -pe 's/./$&|
 |/g;s~^~  |
 /_\\
 |~;s~$~_|
/___\\
 VvV~' <<< ''
  |
 /_\
 |_|
/___\
 VvV

perl -pe 's/./$&|
 |/g;s~^~  |
 /_\\
 |~;s~$~_|
/___\\
 VvV~' <<< '0|'
  |
 /_\
 |0|
 |||
 |_|
/___\
 VvV


答:
Japt / GolfScript, 15 bytes

```<code>"trick""treat";
</code>```

Japt implicitly prints the last string literal, "treat", the first string "trick" is basically ignored.

GolfScript pushes both strings to the stack and then the semicolon ; pops "treat" and thus only "trick" remains on the stack which is printed at the end.

Title: Trick or Treat polyglot

Body:
Since Halloween is coming up I thought I might start a fun little code golf challenge!

The challenge is quite simple. You have to write a program that outputs either trick or treat.

"The twist?" you may ask. Well let me explain:

Your program has to do the following:

Be compilable/runnable in two different languages. Different versions of the same language don't count.

When you run the program in one language it should output trick and the other should output treat. The case is irrelevant and padding the string with whitespace characters are allowed (see examples).

This is code-golf,  so the solution with the fewest bytes wins.

A few explanations:

Valid outputs (Just for the words not for running the code in the two languages. Also adding quotes to signalize the beginning or end of the output. Do not include them in your solution!):

```<code>"trick"

"Treat"

"    TReAt"

"
     tRICk          "
</code>```

Invalid outputs:

```<code>"tri ck"

"tr
eat"

"trck"
</code>```

I'm interested to see what you can come up with! Happy Golfing!

I'd like to note that this is my first challenge so if you have suggestions on this question please leave them in the form of a comment.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code># Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code># Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code># Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the leaderboard snippet:

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

var QUESTION_ID=97472,OVERRIDE_USER=23417;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,TAGS_REG = /(<([^>]+)>)/ig;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;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:
Japt / GolfScript, 15 bytes

"trick""treat";

Japt implicitly prints the last string literal, "treat", the first string "trick" is basically ignored.

GolfScript pushes both strings to the stack and then the semicolon ; pops "treat" and thus only "trick" remains on the stack which is printed at the end.


问:
Tips for golfing in R
I'm looking for tips for golfing in the R statistical language.  R is perhaps an unconventional choice for Golf.  However, it does certain things very compactly (sequences, randomness, vectors, and lists), many of the built-in functions have very short names, and it has an optional line terminator (;).  What tips and tricks can you give to help solve code golf problems in R?</p>

答:
Using if, ifelse, and `if`

There are several ways to do if-statements in R. Golf-optimal solutions can vary a lot.

The basics

if is for control flow. It is not vectorized, i.e. can only evaluate conditions of length 1. It requires else to (optionally) return an else value.

ifelse is a function. It is vectorized, and can return values of arbitrary length. Its third argument (the else value) is obligatory.*

`if` is a function, with the same syntax as ifelse. It is not vectorized, nor are any of the return arguments obligatory.

* It's not technically obligatory; ifelse(TRUE,x) works just fine, but it throws an error if the third argument is empty and the condition evaluates to FALSE. So it's only safe to use if you are sure that the condition is always TRUE, and if that's the case, why are you even bothering with an if-statement?

Examples

These are all equivalent:

```<code>if(x)y else z # 13 bytes
ifelse(x,y,z) # 13 bytes
`if`(x,y,z)   # 11 bytes
</code>```

Note that the spaces around else are not required if you are using strings directly in the code:

```<code>if(x)"foo"else"bar"   # 19 bytes
ifelse(x,"foo","bar") # 21 bytes
`if`(x,"foo","bar")   # 19 bytes
</code>```

So far, `if` looks to be the winner, as long as we don't have vectorized input. But what about cases where we don't care about the else condition? Say we only want to execute some code if the condition is TRUE. For one line of code alone, if is usually best:

```<code>if(x)z=f(y)         # 11 bytes
ifelse(x,z<-f(y),0) # 19 bytes
`if`(x,z<-f(y))     # 15 bytes
</code>```

For multiple lines of code, if is still the winner:

```<code>if(x){z=f(y);a=g(y)}        # 20 bytes
ifelse(x,{z=f(y);a=g(y)},0) # 27 bytes
`if`(x,{z=f(y);a=g(y)})     # 23 bytes
</code>```

There's also the possibility where we do care about the else condition, and where we want to execute arbitrary code rather than return a value. In these cases, if and `if` are equivalent in byte count.

```<code>if(x)a=b else z=b   # 17 bytes
ifelse(x,a<-b,z<-b) # 19 bytes
`if`(x,a<-b,z<-b)   # 17 bytes

if(x){z=y;a=b}else z=b   # 22 bytes
ifelse(x,{z=y;a=b},z<-b) # 24 bytes
`if`(x,{z=y;a=b},z<-b)   # 22 bytes

if(x)a=b else{z=b;a=y}   # 22 bytes
ifelse(x,a<-b,{z=b;a=y}) # 24 bytes
`if`(x,a<-b,{z=b;a=y})   # 22 bytes

if(x){z=y;a=b}else{z=b;a=y}   # 27 bytes
ifelse(x,{z=y;a=b},{z=b;a=y}) # 29 bytes
`if`(x,{z=y;a=b},{z=b;a=y})   # 27 bytes
</code>```

Summary

Use ifelse when you have input of length > 1.

If you're returning a simple value rather than executing many lines of code, using the `if` function is probably shorter than a full if...else statement.

If you just want a single value when TRUE, use if.

For executing arbitrary code, `if` and if are usually the same in terms of byte count; I recommend if mainly because it's easier to read.

Title: Tips for golfing in R

Body:
Using if, ifelse, and `if`

There are several ways to do if-statements in R. Golf-optimal solutions can vary a lot.

The basics

if is for control flow. It is not vectorized, i.e. can only evaluate conditions of length 1. It requires else to (optionally) return an else value.

ifelse is a function. It is vectorized, and can return values of arbitrary length. Its third argument (the else value) is obligatory.*

`if` is a function, with the same syntax as ifelse. It is not vectorized, nor are any of the return arguments obligatory.

* It's not technically obligatory; ifelse(TRUE,x) works just fine, but it throws an error if the third argument is empty and the condition evaluates to FALSE. So it's only safe to use if you are sure that the condition is always TRUE, and if that's the case, why are you even bothering with an if-statement?

Examples

These are all equivalent:

if(x)y else z # 13 bytes
ifelse(x,y,z) # 13 bytes
`if`(x,y,z)   # 11 bytes

Note that the spaces around else are not required if you are using strings directly in the code:

if(x)"foo"else"bar"   # 19 bytes
ifelse(x,"foo","bar") # 21 bytes
`if`(x,"foo","bar")   # 19 bytes

So far, `if` looks to be the winner, as long as we don't have vectorized input. But what about cases where we don't care about the else condition? Say we only want to execute some code if the condition is TRUE. For one line of code alone, if is usually best:

if(x)z=f(y)         # 11 bytes
ifelse(x,z<-f(y),0) # 19 bytes
`if`(x,z<-f(y))     # 15 bytes

For multiple lines of code, if is still the winner:

if(x){z=f(y);a=g(y)}        # 20 bytes
ifelse(x,{z=f(y);a=g(y)},0) # 27 bytes
`if`(x,{z=f(y);a=g(y)})     # 23 bytes

There's also the possibility where we do care about the else condition, and where we want to execute arbitrary code rather than return a value. In these cases, if and `if` are equivalent in byte count.

if(x)a=b else z=b   # 17 bytes
ifelse(x,a<-b,z<-b) # 19 bytes
`if`(x,a<-b,z<-b)   # 17 bytes

if(x){z=y;a=b}else z=b   # 22 bytes
ifelse(x,{z=y;a=b},z<-b) # 24 bytes
`if`(x,{z=y;a=b},z<-b)   # 22 bytes

if(x)a=b else{z=b;a=y}   # 22 bytes
ifelse(x,a<-b,{z=b;a=y}) # 24 bytes
`if`(x,a<-b,{z=b;a=y})   # 22 bytes

if(x){z=y;a=b}else{z=b;a=y}   # 27 bytes
ifelse(x,{z=y;a=b},{z=b;a=y}) # 29 bytes
`if`(x,{z=y;a=b},{z=b;a=y})   # 27 bytes

Summary

Use ifelse when you have input of length > 1.

If you're returning a simple value rather than executing many lines of code, using the `if` function is probably shorter than a full if...else statement.

If you just want a single value when TRUE, use if.

For executing arbitrary code, `if` and if are usually the same in terms of byte count; I recommend if mainly because it's easier to read.