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

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

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

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

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

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

答:
Random template-string hacks

This function riffles two strings (i.e. turns "abc","de" into "adbec"):

```<code>f=(x,y)=>String.raw({raw:x},...y)
</code>```

Note that this only works when x is longer than y. How does it work, you ask? String.raw is designed to be a template tag, like so:

```<code>String.raw`x: ${x}\ny: ${y}\nx + y: ${x + y}`
</code>```

This basically calls String.raw(["x: ", "\ny: ", "\nx + y: ", ""], x, y, x + y), though it's not that simple. The template array also has a special raw property, which is basically a copy of the array, but with the raw strings. String.raw(x, ...args) basically returns x.raw[0] + args[0] + x.raw[1] + args[1] + x.raw[2] + ... and so on until x runs out of items.

So now that we know how String.raw works, we can use it to our advantage:

```<code>f=(x,y)=>String.raw({raw:x},...y)                   // f("abc", "de") => "adbec"
f=x=>String.raw({raw:x},...[...x].keys())           // f("abc") => "a0b1c"
f=(x,y)=>String.raw({raw:x},...[...x].fill(y))      // f("abc", " ") => "a b c"
</code>```

Of course, for that last one, f=(x,y)=>x.split``.join(y) is way shorter, but you get the idea.

Here are a couple of riffling functions that also work if x and y are of equal length:

```<code>f=(x,y)=>String.raw({raw:x.match(/.?/g)},...y)
f=(x,y)=>String.raw({raw:x},...y)+y.slice(-1)  // Only works if x.length == y.length
</code>```

You can learn more about String.raw on MDN.

Body:
Random template-string hacks

This function riffles two strings (i.e. turns "abc","de" into "adbec"):

f=(x,y)=>String.raw({raw:x},...y)

Note that this only works when x is longer than y. How does it work, you ask? String.raw is designed to be a template tag, like so:

String.raw`x: ${x}\ny: ${y}\nx + y: ${x + y}`

This basically calls String.raw(["x: ", "\ny: ", "\nx + y: ", ""], x, y, x + y), though it's not that simple. The template array also has a special raw property, which is basically a copy of the array, but with the raw strings. String.raw(x, ...args) basically returns x.raw[0] + args[0] + x.raw[1] + args[1] + x.raw[2] + ... and so on until x runs out of items.

So now that we know how String.raw works, we can use it to our advantage:

f=(x,y)=>String.raw({raw:x},...y)                   // f("abc", "de") => "adbec"
f=x=>String.raw({raw:x},...[...x].keys())           // f("abc") => "a0b1c"
f=(x,y)=>String.raw({raw:x},...[...x].fill(y))      // f("abc", " ") => "a b c"

Of course, for that last one, f=(x,y)=>x.split``.join(y) is way shorter, but you get the idea.

Here are a couple of riffling functions that also work if x and y are of equal length:

f=(x,y)=>String.raw({raw:x.match(/.?/g)},...y)
f=(x,y)=>String.raw({raw:x},...y)+y.slice(-1)  // Only works if x.length == y.length

You can learn more about String.raw on MDN.


问:
Let's draw some Atari ST bombs!

Introduction

The Atari ST was a rather popular personal computer from the mid 80's to early 90's era, powered by a Motorola 68000 microprocessor. On this machine, the default behavior of the operating system for uncaught CPU exceptions was to display a row of bombs on the screen, as shown in the following picture:

Source: https://commons.wikimedia.org/wiki/File:Row_of_bombs.png

NB: Depending on the OS version, the bomb graphics may vary slightly. But let's take this one as reference.

The number of bombs depends on the exception vector, the most common ones being:

($008) Bus Error : 2 bombs

($00c) Address Error : 3 bombs

($010) Illegal Instruction : 4 bombs

Goal

Your goal is to write a program or function that prints or outputs an ASCII art of such Atari ST bombs.

Input

An integer representing the number of bombs to display. Your code must support the most common values: 2, 3 and 4. Supporting less and/or more bombs is fine, but it is neither required nor subject to a bonus.

Output

The original bomb consists of a 16x16 pixel tile, represented here in both ASCII and binary:

```<code>....##..........    0000110000000000
.#.#..#.........    0101001000000000
.......#........    0000000100000000
#..#....#.......    1001000010000000
..#...#####.....    0010001111100000
......#####.....    0000001111100000
....#########...    0000111111111000
...###########..    0001111111111100
...###########..    0001111111111100
..#############.    0011111111111110
..########.####.    0011111111011110
...#######.###..    0001111111011100
...######.####..    0001111110111100
....#########...    0000111111111000
.....#######....    0000011111110000
.......###......    0000000111000000
</code>```

In this challenge, each ASCII bomb must be stretched to twice its original width for a better rendering. Therefore, it will consist of 16 rows of 32 characters, using ## for 'ON' pixels and two spaces for 'OFF' pixels. All bomb tiles must be put side by side. Leading spaces are forbidden. Trailing spaces are also forbidden, except the ones that are actually part of the bomb tile (i.e. the 31st and 32nd columns) which must be present. You may include no more than one leading line-break and no more than one trailing line-break.

Example

Below is the reference output for two bombs, where mandatory line-breaks are marked as \n and tolerated extra line-breaks are marked as (\n):

```<code>(\n)
        ####                            ####                    \n
  ##  ##    ##                    ##  ##    ##                  \n
              ##                              ##                \n
##    ##        ##              ##    ##        ##              \n
    ##      ##########              ##      ##########          \n
            ##########                      ##########          \n
        ##################              ##################      \n
      ######################          ######################    \n
      ######################          ######################    \n
    ##########################      ##########################  \n
    ################  ########      ################  ########  \n
      ##############  ######          ##############  ######    \n
      ############  ########          ############  ########    \n
        ##################              ##################      \n
          ##############                  ##############        \n
              ######                          ######            (\n)
</code>```

(Of course, other line-break formats such as \r or \r\n may be used just as well.)

Rules

This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.

答:
Haskell, 155 bytes

As a function with type Int -> String:

```<code>b z=concat$do y<-[0..15];"\n":[if odd$div 0x3800FE01FF03DF83BF87BFC7FFC3FF83FF81FF007C007C401090080004A0030(2^(16*y+x))then"##"else"  "|x<-[1..z]>>[0..15]]
</code>```

Printing to IO directly will cost 5 bytes (or 6 if we prefer to return IO () rather than IO [()]):

```<code>b z=mapM putStr$do y<-[0..15];"\n":[if odd$div 0x3800FE01FF03DF83BF87BFC7FFC3FF83FF81FF007C007C401090080004A0030(2^(16*y+x))then"##"else"  "|x<-[1..z]>>[0..15]]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Let's draw some Atari ST bombs!

Body:
Haskell, 155 bytes

As a function with type Int -> String:

b z=concat$do y<-[0..15];"\n":[if odd$div 0x3800FE01FF03DF83BF87BFC7FFC3FF83FF81FF007C007C401090080004A0030(2^(16*y+x))then"##"else"  "|x<-[1..z]>>[0..15]]

Printing to IO directly will cost 5 bytes (or 6 if we prefer to return IO () rather than IO [()]):

b z=mapM putStr$do y<-[0..15];"\n":[if odd$div 0x3800FE01FF03DF83BF87BFC7FFC3FF83FF81FF007C007C401090080004A0030(2^(16*y+x))then"##"else"  "|x<-[1..z]>>[0..15]]


问:
Index of a multidimensional array
Lower level languages, such as C and C++ actually have no concept of multidimensional arrays. (Other than vectors and dynamic arrays) When you create a multidimensional array with

```<code>int foo[5][10];
</code>```

This is actually just syntactic sugar. What C really does is create a single contiguous array of 5 * 10 elements. This

```<code>foo[4][2]
</code>```

is also syntactic sugar. This really refers to the element at

```<code>4 * 10 + 2
</code>```

or, the 42nd element. In general, the index of element [a][b] in array foo[x][y] is at

```<code>a * y + b
</code>```

The same concept applies to 3d arrays. If we have foo[x][y][z] and we access element [a][b][c] we are really accessing element:

```<code>a * y * z + b * z + c
</code>```

This concept applies to n-dimensional arrays. If we have an array with dimensions D1, D2, D3 ... Dn and we access element S1, S2, S3 ... Sn the formula is

```<code>(S1 * D2 * D3 ... * Dn) + (S2 * D3 * D4 ... * Dn) + (S3 * D4 ... * Dn) ... + (Sn-1 * Dn) + Sn
</code>```

The challenge

You must write a program or function that calculates the index of a multidimensional array according to the formula above. Input will be two arrays. The first array is the dimensions, and the second array is the indices. The length of these two arrays will always be equal and at least 1.

You can safely assume that every number in the arrays will be an non-negative integer. You can also assume that you will not get a 0 in the dimension array, although a 0 might be in the indices. You can also assume that indices will not be larger than the dimensions.

Test IO

```<code>Dimensions: [5, 10]
Indices: [4, 2]
Output: 42

Dimensions: [10, 10, 4, 62, 7]
Indices: [1, 2, 3, 4, 5]
Output: 22167

Dimensions: [5, 1, 10]
Indices: [3, 0, 7]
Output: 37

Dimensions: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
Indices: [3, 1, 5, 5, 3, 0, 5, 2, 5, 4]
Output: 33570178
</code>```

答:
Perl 6, 39 bytes

```<code>->\d,\i{sum i.map:{[×] $_,|d[++$ ..*]}}
</code>```

A rather naive golf here, just squished a anonymous sub.

Perl 6 has an anonymous state variable $ which is useful for creating a counter in a loop (eg, using post-increment $++ or pre-increment ++$).
I pre-increment this state variable to increment the starting index of the dimension array slice inside a map.

Here's a ungolfed function that creates the sub-lists

```<code>sub md-index(@dim, @idx) {
    @idx.map(-> $i { $i, |@dim[++$ .. *] })
}
say md-index([10, 10, 4, 62, 7], [1, 2, 3, 4, 5]);
# OUTPUT: ((1 10 4 62 7) (2 4 62 7) (3 62 7) (4 7) (5))
</code>```

Then it's just a matter of reducing the sub-lists with the multiplication  (×) operator, and suming the results.

```<code>sub md-index(@dim, @idx) {
    @idx.map(-> $i { [×] $i, |@dim[++$ .. *] }).sum
}
say md-index([10, 10, 4, 62, 7], [1, 2, 3, 4, 5]);
# OUTPUT: 22167
</code>```

Title: Index of a multidimensional array

Body:
Perl 6, 39 bytes

->\d,\i{sum i.map:{[×] $_,|d[++$ ..*]}}

A rather naive golf here, just squished a anonymous sub.

Perl 6 has an anonymous state variable $ which is useful for creating a counter in a loop (eg, using post-increment $++ or pre-increment ++$).
I pre-increment this state variable to increment the starting index of the dimension array slice inside a map.

Here's a ungolfed function that creates the sub-lists

sub md-index(@dim, @idx) {
    @idx.map(-> $i { $i, |@dim[++$ .. *] })
}
say md-index([10, 10, 4, 62, 7], [1, 2, 3, 4, 5]);
# OUTPUT: ((1 10 4 62 7) (2 4 62 7) (3 62 7) (4 7) (5))

Then it's just a matter of reducing the sub-lists with the multiplication  (×) operator, and suming the results.

sub md-index(@dim, @idx) {
    @idx.map(-> $i { [×] $i, |@dim[++$ .. *] }).sum
}
say md-index([10, 10, 4, 62, 7], [1, 2, 3, 4, 5]);
# OUTPUT: 22167


问:
Compute minimax of an array
Consider an array x such as [1 5 3 4] and a number n, for example 2. Write all length-n sliding subarrays: [1 5], [5 3], [3 4]. Let the minimax of the array be defined as the minimum of the maxima of the sliding blocks. So in this case it would be the minimum of 5, 5, 4, which is 4.

Challenge

Given an array x and a positive integer n, output the minimax as defined above.

The array x will only contain positive integers. n will always be at least 1 and at most the length of x.

Computation may be done by any procedure, not necessarily as defined above.

Code golf, fewest bytes wins.

Test cases

x, n, result

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

答:
Racket 84 bytes

```<code>(λ(l i)(apply min(for/list((j(-(length l)(- i 1))))(apply max(take(drop l j) i)))))
</code>```

Ungolfed:

```<code>(define f
  (λ (l i)
    (apply min (for/list ((j (- (length l)
                                (- i 1))))
                 (apply max (take (drop l j) i))
                 ))))
</code>```

Testing:

```<code>(f '[1 5 3 4]  2)
(f '[1 2 3 4 5] 3)
(f '[5 42 3 23] 3)
</code>```

Output:

```<code>4
3
42
</code>```

Title: Compute minimax of an array

Body:
Racket 84 bytes

(λ(l i)(apply min(for/list((j(-(length l)(- i 1))))(apply max(take(drop l j) i)))))

Ungolfed:

(define f
  (λ (l i)
    (apply min (for/list ((j (- (length l)
                                (- i 1))))
                 (apply max (take (drop l j) i))
                 ))))

Testing:

(f '[1 5 3 4]  2)
(f '[1 2 3 4 5] 3)
(f '[5 42 3 23] 3)

Output:

4
3
42


问:
Divisibility test

Task

Given two strictly positive integers n and d as input, determine whether n is evenly divisible by d, i.e., if there exists an integer q such that n = qd.

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

The output should be a truthy or a falsy value; truthy if n is divisible by d, and falsy otherwise.

Your code only has to handle integers it can represent natively, as long as it works for all signed 8-bit integers. However, your algorithm has to work for arbitrarily large integers.

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

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

Test cases

```<code> n,  d    output

 1,  1    truthy
 2,  1    truthy
 6,  3    truthy
17, 17    truthy
22,  2    truthy
 1,  2    falsy
 2,  3    falsy
 2,  4    falsy
 3,  9    falsy
15, 16    falsy
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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 + 3 (-p flag) = 45 bytes
</code>```

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Raku, 4 bytes

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

Anonymous function that takes 2 arguments, here represented with *, using the infix "is divisable by" operator %%, which returns a Bool value

Title: Divisibility test

Body:
Raku, 4 bytes

*%%*

Anonymous function that takes 2 arguments, here represented with *, using the infix "is divisable by" operator %%, which returns a Bool value

ContentLicense: CC BY-SA 4.0


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

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

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

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

Points for:

Smallest code (in bytes)

Most obfuscated/obscure solution

Using esoteric/obscure languages

Successfully using languages that are difficult to golf in

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

var QUESTION_ID=69;
var OVERRIDE_USER=98;

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

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

Winners by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

 ```

Title: Golf you a quine for great good!


答:
CJam, 66 bytes

```<code>"^a1{9\b aZ5w7qQAwndIUffO"136b2b1Ser0'#erG/ri*z{:_N}%
</code>```

Try it online! (note that there are some unprintable characters in the code.)

The bomb in encoded in as a number in binary using 1 for spaces (the leading space as 1 ensures we don't have to pad the binary representations), transposed, and then converted to string in base-136 (which produced the shortest string without wide-characters). These steps can be played with here.

This answer then reverses the encoding, the main trick being to repeat the bomb before transposing, effectively concatenating each line of the bomb at once. The characters in each line can be then be doubled up with newlines inserted for the final output.

Title: Let's draw some Atari ST bombs!

Body:
Introduction

The Atari ST was a rather popular personal computer from the mid 80's to early 90's era, powered by a Motorola 68000 microprocessor. On this machine, the default behavior of the operating system for uncaught CPU exceptions was to display a row of bombs on the screen, as shown in the following picture:

Source: https://commons.wikimedia.org/wiki/File:Row_of_bombs.png

NB: Depending on the OS version, the bomb graphics may vary slightly. But let's take this one as reference.

The number of bombs depends on the exception vector, the most common ones being:

($008) Bus Error : 2 bombs

($00c) Address Error : 3 bombs

($010) Illegal Instruction : 4 bombs

Goal

Your goal is to write a program or function that prints or outputs an ASCII art of such Atari ST bombs.

Input

An integer representing the number of bombs to display. Your code must support the most common values: 2, 3 and 4. Supporting less and/or more bombs is fine, but it is neither required nor subject to a bonus.

Output

The original bomb consists of a 16x16 pixel tile, represented here in both ASCII and binary:

```<code>....##..........    0000110000000000
.#.#..#.........    0101001000000000
.......#........    0000000100000000
#..#....#.......    1001000010000000
..#...#####.....    0010001111100000
......#####.....    0000001111100000
....#########...    0000111111111000
...###########..    0001111111111100
...###########..    0001111111111100
..#############.    0011111111111110
..########.####.    0011111111011110
...#######.###..    0001111111011100
...######.####..    0001111110111100
....#########...    0000111111111000
.....#######....    0000011111110000
.......###......    0000000111000000
</code>```

In this challenge, each ASCII bomb must be stretched to twice its original width for a better rendering. Therefore, it will consist of 16 rows of 32 characters, using ## for 'ON' pixels and two spaces for 'OFF' pixels. All bomb tiles must be put side by side. Leading spaces are forbidden. Trailing spaces are also forbidden, except the ones that are actually part of the bomb tile (i.e. the 31st and 32nd columns) which must be present. You may include no more than one leading line-break and no more than one trailing line-break.

Example

Below is the reference output for two bombs, where mandatory line-breaks are marked as \n and tolerated extra line-breaks are marked as (\n):

```<code>(\n)
        ####                            ####                    \n
  ##  ##    ##                    ##  ##    ##                  \n
              ##                              ##                \n
##    ##        ##              ##    ##        ##              \n
    ##      ##########              ##      ##########          \n
            ##########                      ##########          \n
        ##################              ##################      \n
      ######################          ######################    \n
      ######################          ######################    \n
    ##########################      ##########################  \n
    ################  ########      ################  ########  \n
      ##############  ######          ##############  ######    \n
      ############  ########          ############  ########    \n
        ##################              ##################      \n
          ##############                  ##############        \n
              ######                          ######            (\n)
</code>```

(Of course, other line-break formats such as \r or \r\n may be used just as well.)

Rules

This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.

Body:
CJam, 66 bytes

"^a1{9\b aZ5w7qQAwndIUffO"136b2b1Ser0'#erG/ri*z{:_N}%

Try it online! (note that there are some unprintable characters in the code.)

The bomb in encoded in as a number in binary using 1 for spaces (the leading space as 1 ensures we don't have to pad the binary representations), transposed, and then converted to string in base-136 (which produced the shortest string without wide-characters). These steps can be played with <a href="http://cjam.tryitonline.net/#code=IgouLi4uIyMuLi4uLi4uLi4uCi4jLiMuLiMuLi4uLi4uLi4KLi4uLi4uLiMuLi4uLi4uLgojLi4jLi4uLiMuLi4uLi4uCi4uIy4uLiMjIyMjLi4uLi4KLi4uLi4uIyMjIyMuLi4uLgouLi4uIyMjIyMjIyMjLi4uCi4uLiMjIyMjIyMjIyMjLi4KLi4uIyMjIyMjIyMjIyMuLgouLiMjIyMjIyMjIyMjIyMuCi4uIyMjIyMjIyMuIyMjIy4KLi4uIyMjIyMjIy4jIyMuLgouLi4jIyMjIyMuIyMjIy4uCi4uLi4jIyMjIyMjIyMuLi4KLi4uLi4jIyMjIyMjLi4uLgouLi4uLi4uIyMjLi4uLi4uCiIgICAgICAgICAgICAgICAgIGUjIFRIRSBCT01CIQoiLiMiIjEwImVyTiUgICAgICBlIyBlbmNvZGUgdG8gYmluYXJ5IGxpbmVzCnogICAgICAgICAgICAgICAgIGUjIHRyYW5zcG9zZSAoc2F2ZXMgYSBieXRlIHRvLCBidXQgY291bGQgYmUgaW4gY29kZSkKZV97JzAtfSUyYiAgICAgICAgZSMgY29udmVydCBib21iIHRvIG51bWJlcgoxMzZiOmNlX2VkTm8gICAgICBlIyBlbmNvZGluZyAoc3RhY2sgZGlzcGxheSkKICAgICAgICAgICAgICAgICAgZSMgQUNUVUFMIENPREUgQkVMT1cgSEVSRQoxMzZiMmIwJyNlcjFTZXJHLyBlIyBkZWNvZGUgdmlhIGJpbmFyeQpyaSp6ezpfTn0lICAgICAgICBlIyBjb21iaW5lIHZpYSB0cmFuc3Bvc2U&input=Mg&debug=on">here.

This answer then reverses the encoding, the main trick being to repeat the bomb before transposing, effectively concatenating each line of the bomb at once. The characters in each line can be then be doubled up with newlines inserted for the final output.


答:
tinylisp (REPL), 38 bytes

```<code>(d |(q((N D)(i(l N D)(e N 0)(|(s N D)D
</code>```

Defines a function | that takes N and D and returns 1 if divisible, 0 otherwise. The REPL infers closing parentheses as necessary at the end of the code. Call the function like (| 22 2).

Ungolfed/explanation:

```<code>(d |                  Define | to be...
 (q (                 a function, i.e. a list containing...
  (N D)               list of params N and D, and function body:
  (i (l N D)           If N is less than D, then return:
   (e N 0)              1 if N equals 0, 0 otherwise;
   (| (s N D) D)))))    Else, recurse with arguments N - D and D
</code>```

Gets kinda slow for N around D * 10^5 and larger.

Title: Divisibility test

Body:
Task

Given two strictly positive integers n and d as input, determine whether n is evenly divisible by d, i.e., if there exists an integer q such that n = qd.

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

The output should be a truthy or a falsy value; truthy if n is divisible by d, and falsy otherwise.

Your code only has to handle integers it can represent natively, as long as it works for all signed 8-bit integers. However, your algorithm has to work for arbitrarily large integers.

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

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

Test cases

```<code> n,  d    output

 1,  1    truthy
 2,  1    truthy
 6,  3    truthy
17, 17    truthy
22,  2    truthy
 1,  2    falsy
 2,  3    falsy
 2,  4    falsy
 3,  9    falsy
15, 16    falsy
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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 + 3 (-p flag) = 45 bytes
</code>```

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
tinylisp (REPL), 38 bytes

(d |(q((N D)(i(l N D)(e N 0)(|(s N D)D

Defines a function | that takes N and D and returns 1 if divisible, 0 otherwise. The REPL infers closing parentheses as necessary at the end of the code. Call the function like (| 22 2).

Ungolfed/explanation:

(d |                  Define | to be...
 (q (                 a function, i.e. a list containing...
  (N D)               list of params N and D, and function body:
  (i (l N D)           If N is less than D, then return:
   (e N 0)              1 if N equals 0, 0 otherwise;
   (| (s N D) D)))))    Else, recurse with arguments N - D and D

Gets kinda slow for N around D * 10^5 and larger.


问:
Print all integers
Write a program or function which will provably print all integers exactly once given infinite time and memory.

Possible outputs could be:

```<code>0, 1, -1, 2, -2, 3, -3, 4, -4, …

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -2, -3, -4, -5, -6, -7, -8, -9, 10, 11, …
</code>```

This is not a valid output, as this would never enumerate negative numbers:

<s>```0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …```</s>

The output must be in decimal, unless your language does not support decimal integer (in that case use the natural representation of integers your language uses).

Your program has to work up to the numbers with the biggest magnitude of the standard integer type of your language.

Each integer must be separated from the next using any separator (a space, a comma, a linebreak, etc.) that is not a digit nor the negative sign of your language.

The separator must not change at any point.

The separator can consist of multiple characters, as long as none of them is a digit nor the negative sign (e.g. ,  is as valid as just ,).

Any supported integer must eventually be printed after a finite amount of time.

Scoring

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

Leaderboard

var QUESTION_ID=93441,OVERRIDE_USER=41723;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

```

答:
LI, <s>16</s> 7 bytes

New solution:

```<code>R-0P-1P
</code>```

I feel kinda silly for not realizing I could have done this before.   I'm keeping the other one because it shows off more flow control and more functions.

LI is a (very) WIP language that relies primarily on recursion.  Every program in LI must take in user-provided input, so the given program here accepts LI's "null" input of 0.

The current Python interpreter is just barely enough to meet the specifications of this challenge, albeit wordy; I'm working on a Racket interpreter that would be able to meet the specs of this challenge with three bytes, but unfortunately it's not even close to challenge-ready.

Explanation:

```<code>      P    Print input
    -1     (1 - input)
   P       Print that too
 -0        (- (1 - input))
R          Rerun program with new input
</code>```

Old solution:

```<code>R?>0i-0PyPi-0PYP
</code>```

Roughly, this program translates to:

```<code>R                        Recurse program with input:
                 P        print-return (implicit input)
                Y         Increment input
               P          Print incremented
             -0           Invert sign
                          = -(i+1)
 ?>0i                   if i is not negative.
      -0PyPi            If i is negative, do the same but decrement (y) instead of increment.
</code>```

For both solutions, output is of the following format:

```<code>0
1
-1
2
-2
3
-3
...
</code>```

The default interpreter will run out of memory at -3338 (3342 with the new solution), if you're curious.

Title: Print all integers

Body:
LI, <s>16</s> 7 bytes

New solution:

R-0P-1P

I feel kinda silly for not realizing I could have done this before.   I'm keeping the other one because it shows off more flow control and more functions.

LI is a (very) WIP language that relies primarily on recursion.  Every program in LI must take in user-provided input, so the given program here accepts LI's "null" input of 0.

The current Python interpreter is just barely enough to meet the specifications of this challenge, albeit wordy; I'm working on a Racket interpreter that would be able to meet the specs of this challenge with three bytes, but unfortunately it's not even close to challenge-ready.

Explanation:

      P    Print input
    -1     (1 - input)
   P       Print that too
 -0        (- (1 - input))
R          Rerun program with new input

Old solution:

R?>0i-0PyPi-0PYP

Roughly, this program translates to:

R                        Recurse program with input:
                 P        print-return (implicit input)
                Y         Increment input
               P          Print incremented
             -0           Invert sign
                          = -(i+1)
 ?>0i                   if i is not negative.
      -0PyPi            If i is negative, do the same but decrement (y) instead of increment.

For both solutions, output is of the following format:

0
1
-1
2
-2
3
-3
...

The default interpreter will run out of memory at -3338 (3342 with the new solution), if you're curious.


问:
Count even steps of 196 algorithm
In the 196-algorithm one starts from an integer and then adds its reverse to it until a palindrome is reached, like this:

```<code>start -> 5280
5280 + 0825 = 6105
6105 + 5016 = 11121
11121 + 12111 = 23232
-end-
</code>```

Write a function that counts how many even numbers are visited before the algorithm ends. Starting and ending numbers are also counted, so, in the example above, visited are consider the numbers: 5280, 6105, 11121, 23232 but not 825, 5016 and 12111.

Examples:

```<code>f(5280) = 2
f(56) = 1
f(59) = 1
f(89) = 13
</code>```

Extended code golf rules apply: shortest number of instructions and operations (like +,-,mod,print,while,if,...) wins.

答:
Mathematica

5 verbs ... not sure how to count ...

```<code>k = FromDigits@Reverse@IntegerDigits[#] &;
Count[NestWhileList[# + k@# &, #, # != k@# &], _?OddQ] &
</code>```

Title: Count even steps of 196 algorithm

Body:
Mathematica

5 verbs ... not sure how to count ...

k = FromDigits@Reverse@IntegerDigits[#] &;
Count[NestWhileList[# + k@# &, #, # != k@# &], _?OddQ] &

ContentLicense: CC BY-SA 2.5


问:
Tips for golfing in Swift
What are some tips for code-golfing in Swift? Its focus on safety seems to make it difficult to golf in, but that makes little tips and even more useful. Are there any features in Swift that may help it excel in code-golf in certain applications?

Please post one tip per answer.

答:
Enumeration

You can chain forEach from enumerated() on a collection type to get a reference to the object (or value type) in a collection, as well as its index:

[1,2,3,4,5].enumerated().forEach{print($0,$1)}
```

<p>or </p>

<pre class="lang-swift prettyprint-override"><code>for (c,i) in [1,2,3,4,5].enumerated(){print(c,i)}
</code>```

or (even shorter CountableClosedRange syntax)

(1...5).enumerated().forEach{print($0,$1)}
```

<p>Prints:</p>

<pre class="lang-swift prettyprint-override"><code>0 1
1 2
2 3
3 4
4 5
</code>```

Title: Tips for golfing in Swift

Body:
Enumeration

You can chain forEach from enumerated() on a collection type to get a reference to the object (or value type) in a collection, as well as its index:

[1,2,3,4,5].enumerated().forEach{print($0,$1)}

or

for (c,i) in [1,2,3,4,5].enumerated(){print(c,i)}

or (even shorter CountableClosedRange syntax)

(1...5).enumerated().forEach{print($0,$1)}

Prints:

0 1
1 2
2 3
3 4
4 5


答:
Hexagony, <s>22</s> 18 bytes

```<code>!(~2016}Q2;'Oct4!~
</code>```

Try it Online!

Excuse me for keep editing.. After typing the explanations I managed to squeeze.. not so squeeze this into a 3-hexagon and there are still plenty of space to put today's date in.

Old Answer

Try it Online! (old answer)

I have a love at first sight with this language...

```<code>!(._/;'<~.2/~/!}Q/>.$>
</code>```

Expanded

```<code>   ! ( . _        When n<=0, print (-ve number) and n--
  / ; ' < ~       After printing ,
 . 2 / ~ / !      If n<=0, n=-n and print (the +ve number)
} Q / > . $ >     Else n=-n and go into auto-if
 . . . . . .
  . . . . .
   . . . .        When n>0, do nothing as the number is printed at line 3
</code>```

The basic algorithm is,

Loop: print, if(n<=0) n--, n=-n, then print ,

I come into this answer with the thought of using implicit if by going out of the corner:

```<code>   ! ( . .
  . . . . .
 . . . . . .
. ~ } Q 2 ; '
 . . . . . .
  . . . . .
   ! . . .
</code>```

However it is real using a lot of bytes for no-ops in putting the ! there, and in the hope of getting the ! (print) back into the main middle loop, I found it hard to print the 0 since the if(n<=0)n-- is run before the main loop for printing.  So keep drawing on a whiteboard (it is easier to overwrite a byte on a whiteboard than most of other tools) I came up with the above which puts one extra ~ (negation) after branching at line 2 but saves me from using the no-ops at the end.

Anyone who can guide me how to make beautiful Hexagony explanation images?

Title: Print all integers

Body:
Write a program or function which will provably print all integers exactly once given infinite time and memory.

Possible outputs could be:

```<code>0, 1, -1, 2, -2, 3, -3, 4, -4, …

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -2, -3, -4, -5, -6, -7, -8, -9, 10, 11, …
</code>```

This is not a valid output, as this would never enumerate negative numbers:

<s>```0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …```</s>

The output must be in decimal, unless your language does not support decimal integer (in that case use the natural representation of integers your language uses).

Your program has to work up to the numbers with the biggest magnitude of the standard integer type of your language.

Each integer must be separated from the next using any separator (a space, a comma, a linebreak, etc.) that is not a digit nor the negative sign of your language.

The separator must not change at any point.

The separator can consist of multiple characters, as long as none of them is a digit nor the negative sign (e.g. ,  is as valid as just ,).

Any supported integer must eventually be printed after a finite amount of time.

Scoring

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

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Hexagony, <s>22</s> 18 bytes

!(~2016}Q2;'Oct4!~

Try it Online!

Excuse me for keep editing.. After typing the explanations I managed to squeeze.. not so squeeze this into a 3-hexagon and there are still plenty of space to put today's date in.

Old Answer

Try it Online! (old answer)

I have a love at first sight with this language...

!(._/;'<~.2/~/!}Q/>.$>

Expanded

   ! ( . _        When n<=0, print (-ve number) and n--
  / ; ' < ~       After printing ,
 . 2 / ~ / !      If n<=0, n=-n and print (the +ve number)
} Q / > . $ >     Else n=-n and go into auto-if
 . . . . . .
  . . . . .
   . . . .        When n>0, do nothing as the number is printed at line 3

The basic algorithm is,

Loop: print, if(n<=0) n--, n=-n, then print ,

I come into this answer with the thought of using implicit if by going out of the corner:

   ! ( . .
  . . . . .
 . . . . . .
. ~ } Q 2 ; '
 . . . . . .
  . . . . .
   ! . . .

However it is real using a lot of bytes for no-ops in putting the ! there, and in the hope of getting the ! (print) back into the main middle loop, I found it hard to print the 0 since the if(n<=0)n-- is run before the main loop for printing.  So keep drawing on a whiteboard (it is easier to overwrite a byte on a whiteboard than most of other tools) I came up with the above which puts one extra ~ (negation) after branching at line 2 but saves me from using the no-ops at the end.

Anyone who can guide me how to make beautiful Hexagony explanation images?


问:
How many times will a bell tower ring?

Introduction

A bell tower will ring its bells every hour, n times, with n being the the current hour on a 12 hour clock.

For example, a bell will ring 5 times at 5pm, and 10 times at 10am.

Task

Given two times in a suitable format, output the number of times the bell will ring, inclusive of the start and end times

Examples

```<code>"10am-12pm"
10+11+12= 33

[01:00, 05:00]
1+2+3+4+5 = 15

[11, 15]
11+12+1+2+3 = 29

[10:00pm, 10:00am]
10+11+12+1+2+3+4+5+6+7+8+9+10 = 88
</code>```

If the start is the same as the end then the you simply just ouput the number of chimes for that hour:

```<code>[5pm, 5pm]
5 = 5
</code>```

As you can see, you may choose an input method but the output must be an integer on its own (or an acceptable alternative) trailing/ leading newlines and spaces are allowed.

Note:

inputs may span from the afternoon of one day to the morning of the next.

the difference between the two times will never be more than 24 hours.

input is flexible so long as you clearly state what format your input is.

your input must have a clear distinction between AM and PM.

答:
Perl, 36 bytes

Includes +1 for -p

Give start and end time in 24-hour format on a line each on STDIN:

```<code>toll.pl
11
15
^D
</code>```

toll.pl:

```<code>#!/usr/bin/perl -p
$\+=$_%12||12for$_..$_+(<>-$_)%24}{
</code>```

Title: How many times will a bell tower ring?

Body:
Perl, 36 bytes

Includes +1 for -p

Give start and end time in 24-hour format on a line each on STDIN:

toll.pl
11
15
^D

toll.pl:

#!/usr/bin/perl -p
$\+=$_%12||12for$_..$_+(<>-$_)%24}{


问:
Shortest program that throws StackOverflow Error
Write a program that throws a StackOverflow Error or the equivalent in the language used. For example, in java, the program should throw java.lang.StackOverflowError.

You are not allowed to define a function that calls itself or a new class(except the one containing main in java). It should use the classes of the selected programming language.

And it should not throw the error explicitly.

答:
LI, 1 byte

```<code>R
</code>```

Reruns the program with the given input.  Every time this is done, another two functions are added to the interpreter's stack (one interpreting the program string and another interpreting the function R), eventually overflowing the stack.

Body:
LI, 1 byte

R

Reruns the program with the given input.  Every time this is done, another two functions are added to the interpreter's stack (one interpreting the program string and another interpreting the function R), eventually overflowing the stack.


答:
Brachylog, 4 bytes

```<code>$G~l
</code>```

Try it online!

Explanation

$G is 1,000,000,000. $G~l is thus: “Create a list of length 1,000,000,000”, which does not fit the stack.

Title: Shortest program that throws StackOverflow Error

Body:
Write a program that throws a StackOverflow Error or the equivalent in the language used. For example, in java, the program should throw java.lang.StackOverflowError.

You are not allowed to define a function that calls itself or a new class(except the one containing main in java). It should use the classes of the selected programming language.

And it should not throw the error explicitly.

Body:
Brachylog, 4 bytes

$G~l

Try it online!

Explanation

$G is 1,000,000,000. $G~l is thus: “Create a list of length 1,000,000,000”, which does not fit the stack.


问:
Implement a Truth-Machine
A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

Gets a number (either 0 or 1) from STDIN.

If that number is 0, print out 0 and terminate.

If that number is 1, print out 1 forever.

Challenge

Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

take input from STDIN or an acceptable alternative

If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program

must output to STDOUT or an acceptable alternative

If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.

when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory

the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of code-golf must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
LI, 4 bytes

```<code>?iRP
</code>```

Explanation:

```<code>?i       if input is truthy (1):
  RP      Recurse the program with the printed (implied) input
         Else (0 is the only falsy value in LI) return (implied) input,
              which is implicitly printed.
</code>```

Title: Implement a Truth-Machine

Body:
LI, 4 bytes

?iRP

Explanation:

?i       if input is truthy (1):
  RP      Recurse the program with the printed (implied) input
         Else (0 is the only falsy value in LI) return (implied) input,
              which is implicitly printed.


问:
Shortest infinite loop producing no output
Your task is to create the shortest infinite loop!

The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.

Rules

Each submission must be a full program.

You must create the shortest infinite loop.

Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.

The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.

The program must not write anything to STDERR.

Feel free to use a language (or language version) even if it's newer than this challenge.
-Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. :D

Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.

This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainf**k-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like #[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes.

Standard loopholes are not allowed.

(I have taken some of these rules from Martin Büttner's "Hello World" challenge)

Please feel free to post in the comments to tell me how this challenge could be  improved.

Catalogue

This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:

```<code># Language name, X bytes
</code>```

Obviously replacing Language name and X bytes with the proper items. If you want to link to the languages' website, use this template, as posted above:

```<code>#[Language name](http://link.to/the/language), X bytes
</code>```

Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
LI, 2 bytes

```<code>R0
</code>```

Usually, LI programs (under the current interpreter) always take in input.   No input is commonly represented as falsy input, i.e. 0; however, in order to truly accept "no" input, I need to provide my own input to the Recurse function.

Explanation:

```<code>R   Recurse with input:
 0  Literal 0
</code>```

LI, 1 byte

If we're a bit more lax with the input requirements, simply R will work.  It doesn't error if you don't give it an input, but that's simply because, while it interprets the input as invalid (empty), it doesn't try to use its value.

Body:
LI, 2 bytes

R0

Usually, LI programs (under the current interpreter) always take in input.   No input is commonly represented as falsy input, i.e. 0; however, in order to truly accept "no" input, I need to provide my own input to the Recurse function.

Explanation:

R   Recurse with input:
 0  Literal 0

LI, 1 byte

If we're a bit more lax with the input requirements, simply R will work.  It doesn't error if you don't give it an input, but that's simply because, while it interprets the input as invalid (empty), it doesn't try to use its value.


答:
Jelly, <s>43</s> 44 bytes

+1 byte - forgot to double the characters (not that anyone noticed!)

```<code>“¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P"¦ḊƥṾ’b⁴‘ĖŒṙị⁾ #Ḥs⁴ẋ€³Y
</code>```

TryItOnline

How?

Preparation was to compress the data as a run-length encoding of the original image:

Count the length of each run of 1s (space) or 0s (hash) in the image, ignoring new lines - yields a list: [4,2,11,1,1,...];

Subtract one from each number - this gives a range of [0,15];

Treat this as a base-16 number (enumerate the values, v, with index i in reverse and sum up 16**i*v = 19468823747267181273462257760938030726282593096816512166437);

Convert this to base-250: [5,119,249,42,...];

Map into Jelly's code page as indexes: ¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P

Now the code evaluates this number, maps the 1s and 0s to space and hash characters*, doubles each, splits into lines and repeats each the appropriate number of times.

* actually the implementation is performed modulo 2 to save bytes, so spaces are odd and hashes are even:

```<code>“¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P"¦ḊƥṾ’b⁴‘ĖŒṙị⁾ #Ḥs⁴ẋ€³Y - Main link: n
“¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P"¦ḊƥṾ’                  - base 250 number, as above
                           b⁴                - convert to base 16 (the run length - 1 list)
                             ‘               - increment (vectorises) (the run length list)
                              Ė              - enumerate (pairs each with 1,2,3...)
                               Œṙ            - run length decode
                                              ([1,1,1,1,2,2,3,3,3,3,3,3,3,3,3,3,3,4,5,...])
                                  ⁾ #        - string " #"
                                 ị           - index into (1 based and modular)
                                              (makes a bomb without line feeds)
                                     Ḥ       - double (each char becomes a list of 2 chars)
                                      s⁴     - split into slices of length 16
                                        ẋ€³  - repeat each input, n, times
                                           Y - join with line feeds
</code>```

Title: Let's draw some Atari ST bombs!

Body:
Jelly, <s>43</s> 44 bytes

+1 byte - forgot to double the characters (not that anyone noticed!)

“¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P"¦ḊƥṾ’b⁴‘ĖŒṙị⁾ #Ḥs⁴ẋ€³Y

TryItOnline

How?

Preparation was to compress the data as a run-length encoding of the original image:

Count the length of each run of 1s (space) or 0s (hash) in the image, ignoring new lines - yields a list: [4,2,11,1,1,...];

Subtract one from each number - this gives a range of [0,15];

Treat this as a base-16 number (enumerate the values, v, with index i in reverse and sum up 16**i*v = 19468823747267181273462257760938030726282593096816512166437);

Convert this to base-250: [5,119,249,42,...];

Map into Jelly's code page as indexes: ¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P

Now the code evaluates this number, maps the 1s and 0s to space and hash characters*, doubles each, splits into lines and repeats each the appropriate number of times.

* actually the implementation is performed modulo 2 to save bytes, so spaces are odd and hashes are even:

“¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P"¦ḊƥṾ’b⁴‘ĖŒṙị⁾ #Ḥs⁴ẋ€³Y - Main link: n
“¥vẏ)X;ndĊɓ¡ẹ3ċi}Ịɲ¡P"¦ḊƥṾ’                  - base 250 number, as above
                           b⁴                - convert to base 16 (the run length - 1 list)
                             ‘               - increment (vectorises) (the run length list)
                              Ė              - enumerate (pairs each with 1,2,3...)
                               Œṙ            - run length decode
                                              ([1,1,1,1,2,2,3,3,3,3,3,3,3,3,3,3,3,4,5,...])
                                  ⁾ #        - string " #"
                                 ị           - index into (1 based and modular)
                                              (makes a bomb without line feeds)
                                     Ḥ       - double (each char becomes a list of 2 chars)
                                      s⁴     - split into slices of length 16
                                        ẋ€³  - repeat each input, n, times
                                           Y - join with line feeds


答:
C#, 73 bytes

```<code>a=>b=>{int x=0;for(;;){x+=(a%=24)>12?a-12:a<1?12:a;if(a++==b)return x;}};
</code>```

Acceptable input: integers in range [0,23].

This solution does not use LINQ.

Full program with test cases:

```<code>using System;

namespace HowManyTimesABellTowerRings
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,Func<int,int>>f= a=>b=>{int x=0;for(;;){x+=(a%=24)>12?a-12:a<1?12:a;if(a++==b)return x;}};

            Console.WriteLine(f(10)(12));   //33
            Console.WriteLine(f(1)(5));     //15
            Console.WriteLine(f(11)(15));   //29
            Console.WriteLine(f(22)(10));   //88
            Console.WriteLine(f(10)(10));   //10
            Console.WriteLine(f(11)(10));   //156
            Console.WriteLine(f(0)(23));    //156
            Console.WriteLine(f(22)(1));    //34
        }
    }
}
</code>```

Title: How many times will a bell tower ring?

Body:
Introduction

A bell tower will ring its bells every hour, n times, with n being the the current hour on a 12 hour clock.

For example, a bell will ring 5 times at 5pm, and 10 times at 10am.

Task

Given two times in a suitable format, output the number of times the bell will ring, inclusive of the start and end times

Examples

```<code>"10am-12pm"
10+11+12= 33

[01:00, 05:00]
1+2+3+4+5 = 15

[11, 15]
11+12+1+2+3 = 29

[10:00pm, 10:00am]
10+11+12+1+2+3+4+5+6+7+8+9+10 = 88
</code>```

If the start is the same as the end then the you simply just ouput the number of chimes for that hour:

```<code>[5pm, 5pm]
5 = 5
</code>```

As you can see, you may choose an input method but the output must be an integer on its own (or an acceptable alternative) trailing/ leading newlines and spaces are allowed.

Note:

inputs may span from the afternoon of one day to the morning of the next.

the difference between the two times will never be more than 24 hours.

input is flexible so long as you clearly state what format your input is.

your input must have a clear distinction between AM and PM.

Body:
C#, 73 bytes

a=>b=>{int x=0;for(;;){x+=(a%=24)>12?a-12:a<1?12:a;if(a++==b)return x;}};

Acceptable input: integers in range [0,23].

This solution does not use LINQ.

Full program with test cases:

using System;

namespace HowManyTimesABellTowerRings
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<int,Func<int,int>>f= a=>b=>{int x=0;for(;;){x+=(a%=24)>12?a-12:a<1?12:a;if(a++==b)return x;}};

            Console.WriteLine(f(10)(12));   //33
            Console.WriteLine(f(1)(5));     //15
            Console.WriteLine(f(11)(15));   //29
            Console.WriteLine(f(22)(10));   //88
            Console.WriteLine(f(10)(10));   //10
            Console.WriteLine(f(11)(10));   //156
            Console.WriteLine(f(0)(23));    //156
            Console.WriteLine(f(22)(1));    //34
        }
    }
}


答:
><>, 48 + 2 = 50 bytes

```<code><v$&%$-&:$+}:*2c
{>:?!v1-}:1+
v?=1l<++1%c+b$
>n;
</code>```

Input is expected to be present on the stack at program start, so +2 bytes for the -v flag. Input is two integers specifying the hour on the 24 hour clock, so 10am - 10pm would be given as 10 22.

Try it online!

Title: How many times will a bell tower ring?

Body:
><>, 48 + 2 = 50 bytes

<v$&%$-&:$+}:*2c
{>:?!v1-}:1+
v?=1l<++1%c+b$
>n;

Input is expected to be present on the stack at program start, so +2 bytes for the -v flag. Input is two integers specifying the hour on the 24 hour clock, so 10am - 10pm would be given as 10 22.

Try it online!


答:
Batch, <s>168</s> 91 bytes

```<code>@cmd/cset/ax=(%1+23)%%24,y=x+(%2+24-%1)%%24,z=y%%12+1,(y/12-x/12)*78+z*-~z/2-(x%%=12)*-~x/2
</code>```

Edit: Saved 77 byte by switching to a closed form for the answer.

%1 and %2 are the two command-line parameters

@ Disable Batch's default which is to echo the command

cmd/c Fool Batch into immediately printing the result of the calculation

set/a Perform a numeric calculation

x=(%1+23)%%24, Normalise the starting hour to be the number of hours since 1AM (1PM would also work, but 11 is no shorter than 23)

y=x+(%2+24-%1)%%24, Normalise the ending hour to be ahead of the starting hour, advancing to the next day if necessary

z=y%%12+1, Number of bells struck at the ending hour

(y/12-x/12)*78+ Number of bells due to extra half days

z*~-z/2- Number of bells from 1 o'clock to the ending hour inclusive

(x%%=12) One less than the number of bells struck at the starting hour

*-~x/2 Number of bells that would have been struck from 1 o'clock to the starting hour, but not including the starting hour

Title: How many times will a bell tower ring?

Body:
Batch, <s>168</s> 91 bytes

@cmd/cset/ax=(%1+23)%%24,y=x+(%2+24-%1)%%24,z=y%%12+1,(y/12-x/12)*78+z*-~z/2-(x%%=12)*-~x/2

Edit: Saved 77 byte by switching to a closed form for the answer.

%1 and %2 are the two command-line parameters

@ Disable Batch's default which is to echo the command

cmd/c Fool Batch into immediately printing the result of the calculation

set/a Perform a numeric calculation

x=(%1+23)%%24, Normalise the starting hour to be the number of hours since 1AM (1PM would also work, but 11 is no shorter than 23)

y=x+(%2+24-%1)%%24, Normalise the ending hour to be ahead of the starting hour, advancing to the next day if necessary

z=y%%12+1, Number of bells struck at the ending hour

(y/12-x/12)*78+ Number of bells due to extra half days

z*~-z/2- Number of bells from 1 o'clock to the ending hour inclusive

(x%%=12) One less than the number of bells struck at the starting hour

*-~x/2 Number of bells that would have been struck from 1 o'clock to the starting hour, but not including the starting hour


答:
Python 2.7, 68 characters

```<code>def f(s):i=long(s,2);print bin(i^(1,(i&-i)<<1)[s.count('1')&1])[2:]
</code>```

Python 3, 68 characters

```<code>def f(s):i=int(s,2);print(bin(i^(1,(i&-i)<<1)[s.count('1')&1])[2:])
</code>```

This function converts the given binary string to an integer then xor the last bit if the number of set bits in the original string is even, or its swaps the bit to the left of the rightmost set bit if the number of set bits in the original string is odd. Then it converts the result to a binary string and removes the 0b boolean prefix.

Title: Incrementing Gray Codes

Body:
Introduction

A Gray Code is an alternative to binary representation in which a number is incremented by toggling only one bit, rather than a variable amount of bits. Here are some gray codes along with their decimal and binary equivalents:

```<code> decimal | binary | gray
-------------------------
       0 |      0 |    0
-------------------------
       1 |      1 |    1
-------------------------
       2 |     10 |   11
-------------------------
       3 |     11 |   10
-------------------------
       4 |    100 |  110
-------------------------
       5 |    101 |  111
-------------------------
       6 |    110 |  101
-------------------------
       7 |    111 |  100
-------------------------
       8 |   1000 | 1100
-------------------------
       9 |   1001 | 1101
-------------------------
      10 |   1010 | 1111
-------------------------
      11 |   1011 | 1110
-------------------------
      12 |   1100 | 1010
-------------------------
      13 |   1101 | 1011
-------------------------
      14 |   1110 | 1001
-------------------------
      15 |   1111 | 1000
</code>```

Cyclic Bit Pattern of a Gray Code

Sometimes called "reflected binary", the property of changing only one bit at a time is easily achieved with cyclic bit patterns for each column starting from the least significant bit:

```<code>bit 0: 0110011001100110011001100110011001100110011001100110011001100110
bit 1: 0011110000111100001111000011110000111100001111000011110000111100
bit 2: 0000111111110000000011111111000000001111111100000000111111110000
bit 3: 0000000011111111111111110000000000000000111111111111111100000000
bit 4: 0000000000000000111111111111111111111111111111110000000000000000
bit 5: 0000000000000000000000000000000011111111111111111111111111111111
</code>```

...and so on.

Objective

Given a non-padded input string of a gray code, increment the gray code by alternating a single character in the sequence or prepending a 1 (when incrementing to the next power of 2), then output the result as a non-padded gray code.

Caveats

Do not worry about taking 0 or an empty string as input.

The lowest input will be 1, and there is no upper-bound to the string length other than memory limitations imposed by the environment.

By non-padded string, I mean there will be no leading or trailing whitespace (other than an optional trailing newline), and no leading 0s in the input or output.

I/O formats

The following formats are accepted form for input and output, but strings are encouraged over other formats:

most significant "bit" first

non-padded character array or string of ASCII '1's and '0's

non-padded integer array of 1s and 0s

non-padded boolean array

What's not allowed:

least significant "bit" first

decimal, binary or unary integer

fixed-length data-structure

character array or string of non-printable ASCII indices 1 and 0

Tests

```<code>input -> output
1 -> 11
11 -> 10
111 -> 101
1011 -> 1001
1111 -> 1110
10111 -> 10110
101100 -> 100100
100000 -> 1100000
</code>```

More tests can be added by request.

Criteria

This is code-golf, so shortest program in bytes wins! All ties will be broken by favoring earlier submissions; standard loopholes apply. The best submitted answer will be accepted October 9th, 2016, and updated whenever better answers are given.

Body:
Python 2.7, 68 characters

def f(s):i=long(s,2);print bin(i^(1,(i&-i)<<1)[s.count('1')&1])[2:]

Python 3, 68 characters

def f(s):i=int(s,2);print(bin(i^(1,(i&-i)<<1)[s.count('1')&1])[2:])

This function converts the given binary string to an integer then xor the last bit if the number of set bits in the original string is even, or its swaps the bit to the left of the rightmost set bit if the number of set bits in the original string is odd. Then it converts the result to a binary string and removes the 0b boolean prefix.


答:
Java 7, 64 bytes

```<code>int c(int x,int y){return(x%12<1?12:x%12)+(x!=y?c(-~x%24,y):0);}
</code>```

Recursive method based on @ETHproductions's Python 2 answer. Uses a 24-hour clock input.

Ungolfed & test code:

Try it here.

```<code>class M{
  static int c(int x, int y){
    return (x%12 < 1
             ? 12
             : x%12)
         + (x != y
             ? c(-~x % 24, y)
             : 0);
  }

  public static void main(String[] a){
    System.out.println(c(10, 12));
    System.out.println(c(1, 5));
    System.out.println(c(11, 15));
    System.out.println(c(10, 22));
    System.out.println(c(5, 5));
  }
}
</code>```

Output:

```<code>33
15
29
88
5
</code>```

Title: How many times will a bell tower ring?

Body:
Java 7, 64 bytes

int c(int x,int y){return(x%12<1?12:x%12)+(x!=y?c(-~x%24,y):0);}

Recursive method based on @ETHproductions's Python 2 answer. Uses a 24-hour clock input.

Ungolfed & test code:

Try it here.

class M{
  static int c(int x, int y){
    return (x%12 < 1
             ? 12
             : x%12)
         + (x != y
             ? c(-~x % 24, y)
             : 0);
  }

  public static void main(String[] a){
    System.out.println(c(10, 12));
    System.out.println(c(1, 5));
    System.out.println(c(11, 15));
    System.out.println(c(10, 22));
    System.out.println(c(5, 5));
  }
}

Output:

33
15
29
88
5


问:
Find the intersection point of a plane and ray
Given a ray with a point and a vector and a plane with a point and a normal vector to the plane. You have to find the intersection point of the plane and the ray..

So your job if you choose to accept is to write a shortest function that will do the job.

```<code>RULES:
The submission must be a complete program
And that's all

INPUT FORMAT:
x y z rx ry rz //gives the ray point and the ray vectors
x y z px py pz //gives the point on the plane and the vector normal to plane

OUTPUT FORMAT:
(x,y,z) //intersection point

Test Case:
2 3 4 0.577 0.577 0.577
7 1 3 1 0 0
(7,8,9)
</code>```

The shortest codes in bytes win.

References: https://www.siggraph.org/education/materials/HyperGraph/raytrace/rayplane_intersection.htm  thanks orlp for the reference

答:
Haskell, <s>137</s> 157/102 bytes

Follows both input and output pattern. Program reads input from stdin. 157 bytes.

```<code>z=zipWith
main=do
[(p,r),(l,n)]<-map(splitAt 3.map read.words).lines<$>getContents
print$(\[a,b,c]->(a,b,c))$z(+)p$map(*(sum(z(*)n(z(-)l p))/sum(z(*)n r)))r
</code>```

With an input file that has format [[x,y,z],[rx,ry,rz],[x,y,z],[px,py,pz]] and output of format [x,y,z] (102 bytes):

```<code>z=zipWith
main=do
[p,r,l,n]<-read<$>getContents
print$z(+)p$map(*(sum(z(*)n(z(-)l p))/sum(z(*)n r)))r
</code>```

Body:
Haskell, <s>137</s> 157/102 bytes

Follows both input and output pattern. Program reads input from stdin. 157 bytes.

z=zipWith
main=do
[(p,r),(l,n)]<-map(splitAt 3.map read.words).lines<$>getContents
print$(\[a,b,c]->(a,b,c))$z(+)p$map(*(sum(z(*)n(z(-)l p))/sum(z(*)n r)))r

With an input file that has format [[x,y,z],[rx,ry,rz],[x,y,z],[px,py,pz]] and output of format [x,y,z] (102 bytes):

z=zipWith
main=do
[p,r,l,n]<-read<$>getContents
print$z(+)p$map(*(sum(z(*)n(z(-)l p))/sum(z(*)n r)))r


问:
Natural Pi #0 - Rock

Goal

Create a program/function that takes an input N, check if N random pairs of integers are relatively prime, and returns sqrt(6 * N / #coprime).

TL;DR

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

Simulation

What are we simulating? Well, the probability that two random integers are relatively prime (ie coprime or gcd==1) is 6/Pi/Pi, so a natural way to calculate Pi would be to scoop up two buckets (or handfuls) of rocks; count them; see if their gcd is 1; repeat. After doing this a <s>couple</s> lot of times, sqrt(6.0 * total / num_coprimes) will tend towards Pi. If calculating the square-root in post-apocalyptic world makes you nervous, don't worry! There is Newton's Method for that.

How are we simulating this?

Take input N

Do the following N times:

Uniformly generate random positive integers, i and j

With 1 <= i , j <= 10^6

If gcd(i , j) == 1: result = 1

Else: result = 0

Take the sum of the N results, S

Return sqrt(6 * N / S)

Specification

Input

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

Output

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

White space, trailing and leading white space is acceptable

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

Scoring

Shortest code wins!

Test Cases

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

```<code>Input     ->  Output
-----         ------
100       ->  3.????
10000     ->  3.1???
1000000   ->  3.14??
</code>```

答:
Perl, 64 bytes

sub r{1+~~rand 9x6}$_=sqrt$_*6/grep{2>gcd r,r}1..$_
```

<p>Requires the command line option <code>-pMntheory=gcd</code>, counted as 13. Input is taken from stdin.</p>

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

<pre class="lang-perl prettyprint-override"><code>$ echo 1000 | perl -pMntheory=gcd pi-rock.pl
3.14140431218772
</code>```

Title: Natural Pi #0 - Rock

Body:
Perl, 64 bytes

sub r{1+~~rand 9x6}$_=sqrt$_*6/grep{2>gcd r,r}1..$_

Requires the command line option -pMntheory=gcd, counted as 13. Input is taken from stdin.

Sample Usage

$ echo 1000 | perl -pMntheory=gcd pi-rock.pl
3.14140431218772


Title: Natural Pi #0 - Rock

Body:
Goal

Create a program/function that takes an input N, check if N random pairs of integers are relatively prime, and returns sqrt(6 * N / #coprime).

TL;DR

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

Simulation

What are we simulating? Well, the probability that two random integers are relatively prime (ie coprime or gcd==1) is 6/Pi/Pi, so a natural way to calculate Pi would be to scoop up two buckets (or handfuls) of rocks; count them; see if their gcd is 1; repeat. After doing this a <s>couple</s> lot of times, sqrt(6.0 * total / num_coprimes) will tend towards Pi. If calculating the square-root in post-apocalyptic world makes you nervous, don't worry! There is Newton's Method for that.

How are we simulating this?

Take input N

Do the following N times:

Uniformly generate random positive integers, i and j

With 1 <= i , j <= 10^6

If gcd(i , j) == 1: result = 1

Else: result = 0

Take the sum of the N results, S

Return sqrt(6 * N / S)

Specification

Input

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

Output

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

White space, trailing and leading white space is acceptable

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

Scoring

Shortest code wins!

Test Cases

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

```<code>Input     ->  Output
-----         ------
100       ->  3.????
10000     ->  3.1???
1000000   ->  3.14??
</code>```

Body:
Racket 92 bytes

(λ(N)(sqrt(/(* 6 N)(for/sum((c N))(if(= 1(gcd(random 1 1000000)(random 1 1000000)))1 0)))))

Ungolfed:

(define f
  (λ (N)
    (sqrt(/ (* 6 N)
            (for/sum ((c N))
              (if (= 1
                     (gcd (random 1 1000000)
                          (random 1 1000000)))
                  1 0)
              )))))

Testing:

(f 100)
(f 1000)
(f 100000)

Output:

2.970442628930023
3.188964020716403
3.144483068444827


问:
A047841: Autobiographical numbers

Definition

Here is the process to describe a number:

For each number from 0 to 9 that is present in the number:

Write down the frequency of that digit and then the digit.

For example, for the number 10213223:

There is 1 occurrence of 0,

2 occurrences of 1,

3 occurrences of 2,

2 occurrences of 3.

Therefore, the number that describes 10213223 is 10213223 (10 from the first property, 21 from the second, etc.).

Note that the number of occurrences of a digit may be greater than 9.

Task

You are to print/output all numbers that describe themselves.

Specs

Standard loopholes apply, except that you are allowed to hardcode the output or store information related to the output in your program.

The numbers in the output can be in any order.

The numbers in the output are allowed to have duplicates.

You may use any separator, if you choose to print instead of output.

You are allowed to prefix and/or postfix output if you choose to print instead of output.

The separator and the prefix and the postfix may not contain any digits (U+0030 to U+0039).

The solution must compute in one day.

Full list (109 items)

```<code>22
10213223
10311233
10313314
10313315
10313316
10313317
10313318
10313319
21322314
21322315
21322316
21322317
21322318
21322319
31123314
31123315
31123316
31123317
31123318
31123319
31331415
31331416
31331417
31331418
31331419
31331516
31331517
31331518
31331519
31331617
31331618
31331619
31331718
31331719
31331819
1031223314
1031223315
1031223316
1031223317
1031223318
1031223319
3122331415
3122331416
3122331417
3122331418
3122331419
3122331516
3122331517
3122331518
3122331519
3122331617
3122331618
3122331619
3122331718
3122331719
3122331819
10413223241516
10413223241517
10413223241518
10413223241519
10413223241617
10413223241618
10413223241619
10413223241718
10413223241719
10413223241819
41322324151617
41322324151618
41322324151619
41322324151718
41322324151719
41322324151819
41322324161718
41322324161719
41322324161819
41322324171819
1051322314251617
1051322314251618
1051322314251619
1051322314251718
1051322314251719
1051322314251819
1051322325161718
1051322325161719
1051322325161819
1051322325171819
5132231425161718
5132231425161719
5132231425161819
5132231425171819
5132232516171819
106132231415261718
106132231415261719
106132231415261819
106132231426171819
106132231526171819
613223141526171819
1011112131415161718
1011112131415161719
1011112131415161819
1011112131415171819
1011112131416171819
1011112131516171819
1011112141516171819
1011113141516171819
1111213141516171819
10713223141516271819
101112213141516171819
</code>```

References

Autobiographical numbers: OEIS A047841

Biographical number: OEIS A047842

Title: A047841: Autobiographical numbers

Body:
///, 542 bytes

/:/\/\///^/13223:!/31:*/
10:#/!223!:&/4^241:$/1819:(/51617:)/
!3!:%/5^142:@/111:-/*@121!:_/51:+/
!123!:=/41:A/617:B/19:C/*!3!:D/18:E/6^1=52:F/
#:G/
2^:H/*5^2:I/1!=($:J/_6:K/
&:L/*&:M/_7/22*2^*!1233C4C5C6C7C8C9G14G15G16G17GDGB+4+5+6+7+8+9)=5)=6)=7)=8)=9)J)M)_8)_9)A)6D)6B)7D)7B)8B*#4*#5*#6*#7*#8*#9F=5F=6F=7F=8F=9FJF_7F_8F_9FAF6DF6BF7DF7BF8BLJLML_8L_9LAL6DL6BL7DL7BL8BK(KJDKJBKMDKMBK5$KADKABK6$K7$*%(*%JD*%JB*%MD*%MB*%5$H(DH(BHJ$HM$
%(D
%(B
%J$
%M$
5^2($*EAD*EAB*E6$*6^142A$*6^152A$
EA$-=(D-=(B-=J$-=_7$-=617$-($*@121=($*@I
@12I*7^1=_627$*@22I

<a href="http://slashes.tryitonline.net#code=LzovXC9cLy8vXi8xMzIyMzohLzMxOiovCjEwOiMvITIyMyE6Ji80XjI0MTokLzE4MTk6KC81MTYxNzopLwohMyE6JS81XjE0MjpALzExMTotLypAMTIxITpfLzUxOisvCiExMjMhOj0vNDE6QS82MTc6Qi8xOTpDLyohMyE6RC8xODpFLzZeMT01MjpGLwojOkcvCjJeOkgvKjVeMjpJLzEhPSgkOkovXzY6Sy8KJjpMLyomOk0vXzcvMjIqMl4qITEyMzNDNEM1QzZDN0M4QzlHMTRHMTVHMTZHMTdHREdCKzQrNSs2KzcrOCs5KT01KT02KT03KT04KT05KUopTSlfOClfOSlBKTZEKTZCKTdEKTdCKThCKiM0KiM1KiM2KiM3KiM4KiM5Rj01Rj02Rj03Rj04Rj05RkpGXzdGXzhGXzlGQUY2REY2QkY3REY3QkY4QkxKTE1MXzhMXzlMQUw2REw2Qkw3REw3Qkw4QksoS0pES0pCS01ES01CSzUkS0FES0FCSzYkSzckKiUoKiVKRColSkIqJU1EKiVNQiolNSRIKERIKEJISiRITSQKJShECiUoQgolSiQKJU0kCjVeMigkKkVBRCpFQUIqRTYkKjZeMTQyQSQqNl4xNTJBJApFQSQtPShELT0oQi09SiQtPV83JC09NjE3JC0oJCpAMTIxPSgkKkBJCkAxMkkqN14xPV82MjckKkAyMkk" rel="nofollow noreferrer">Try it online!

Definitely less than 1440 bytes for sure!!! Uses 28 constants along with the literal, an unusually high amount for ///.


问:
10 PRINT CHR$(205.5+RND(1)); : GOTO 10 in PHP (or anything else, for that matter)
Just had a 'spirited' conversation with a co-worker about the succinctness of the following BASIC statement:

```<code>10 PRINT CHR$(205.5+RND(1)); : GOTO 10
</code>```

It's the title of this book, and will simply print a sequence of / and \ characters, alternating between the two randomly, resulting in a pattern similar to this:

(Image borrowed from http://www.flickr.com/photos/rndmcnlly/5058442151/sizes/o/in/photostream/)

Being of a PHP proclivity, we wondered what the most compact way of writing the same thing in PHP would be, and came up with this:

```<code>while(1) { echo chr(47 + 45 * rand(0,1)); }
</code>```

chr(47) is a / character, and chr(92) is a \. So the statement echo chr(47 + 45 * rand(0,1)); will randomly alternate between the two, ad nauseam.

In a language of your choosing, write the shortest program or function to output an infinite random sequence of \ and / characters, where each character has an equal probability of being chosen.

答:
Common Lisp, 33

```<code>(loop(princ(elt"/\\"(random 2))))
</code>```

OwnerDisplayName: Judy

Body:
Common Lisp, 33

(loop(princ(elt"/\\"(random 2))))


答:
Java 8, <s>164</s> 151 bytes

n->{int c=n,t=0,x,y;while(c-->0){x=1+(int)(Math.random()*10e6);y=1+(int)(Math.random()*10e6);while(y>0)y=x%(x=y);if(x<2)t++;}return Math.sqrt(6f*n/t);}
```

<h2>Explanation</h2>

<pre class="lang-java prettyprint-override"><code>n->{
    int c=n,t=0,x,y;
    while(c-->0){                          // Repeat n times
        x=1+(int)(Math.random()*10e6);     // Random x
        y=1+(int)(Math.random()*10e6);     // Random y
        while(y>0)y=x%(x=y);               // GCD
        if(x<2)t++;                        // Coprime?
    }
    return Math.sqrt(6f*n/t);              // Pi
}
</code>```

Test Harness

class Main {
    public static interface F{ double f(int n); }
    public static void g(F s){
        System.out.println(s.f(100));
        System.out.println(s.f(1000));
        System.out.println(s.f(10000));
    }
    public static void main(String[] args) {
        g(
            n->{int c=n,t=0,y,x;while(c-->0){x=1+(int)(Math.random()*10e6);y=1+(int)(Math.random()*10e6);while(y>0)y=x%(x=y);if(x<2)t++;}return Math.sqrt(6f*n/t);}
        );
    }
}
```

Update

-13 [16-10-05] Thanks to @TNT and added test harness

Title: Natural Pi #0 - Rock

Body:
Java 8, <s>164</s> 151 bytes

n->{int c=n,t=0,x,y;while(c-->0){x=1+(int)(Math.random()*10e6);y=1+(int)(Math.random()*10e6);while(y>0)y=x%(x=y);if(x<2)t++;}return Math.sqrt(6f*n/t);}

Explanation

n->{
    int c=n,t=0,x,y;
    while(c-->0){                          // Repeat n times
        x=1+(int)(Math.random()*10e6);     // Random x
        y=1+(int)(Math.random()*10e6);     // Random y
        while(y>0)y=x%(x=y);               // GCD
        if(x<2)t++;                        // Coprime?
    }
    return Math.sqrt(6f*n/t);              // Pi
}

Test Harness

class Main {
    public static interface F{ double f(int n); }
    public static void g(F s){
        System.out.println(s.f(100));
        System.out.println(s.f(1000));
        System.out.println(s.f(10000));
    }
    public static void main(String[] args) {
        g(
            n->{int c=n,t=0,y,x;while(c-->0){x=1+(int)(Math.random()*10e6);y=1+(int)(Math.random()*10e6);while(y>0)y=x%(x=y);if(x<2)t++;}return Math.sqrt(6f*n/t);}
        );
    }
}

Update

-13 [16-10-05] Thanks to @TNT and added test harness


问:
Compute the Mertens function
Given a positive integer n, compute the value of the Mertens function \$M(n)\$ where:

$$M(n) = \Sigma_{k=1}^{n}\mu(k)$$

and \$\mu(k)\$ is the Möbius function where \$μ(k) = 1\$ if \$k\$ has an even number of distinct prime factors, \$-1\$ if \$k\$ has an odd number of distinct prime factors, and \$0\$ if the prime factors are not distinct.

This is code-golf so create the shortest code for a function or program that computes the Mertens function for an input integer n > 0.

This is the OEIS sequence A002321.

Test Cases

```<code>n M(n)
1 1
2 0
3 -1
4 -1
5 -2
6 -1
7 -2
8 -2
9 -2
10 -1
117 -5
5525 5
7044 -25
8888 4
10000 -23
</code>```

答:
PARI/GP, 24 bytes

```<code>n->sum(x=1,n,moebius(x))
</code>```

Title: Compute the Mertens function

Body:
PARI/GP, 24 bytes

n->sum(x=1,n,moebius(x))


答:
Java 8, <s>60</s> <s>59</s> <s>54</s> 53 bytes

v->{for(;;)System.out.write(Math.random()<.5?47:92);}
```
<p>-1 byte thanks to <em>@BenjaminUrquhart</em> by replacing <code>print</code> with <code>write</code>, so <code>'/'</code> can be <code>47</code>.</p>
<p><strong>Explanation:</strong></p>
<p>Try it online (times out after 60 sec).</p>
<pre class="lang-java prettyprint-override"><code>v->{                     // Method with empty unused parameter and no return-type
  for(;;)                //  Loop indefinitely
    System.out.write(    //   Print:
      Math.random()<.5?  //    If the random decimal value in range [0,1) is below 0.5:
       47                //     Print forward slash
      :                  //    Else:
       92);}             //     Print backward slash
</code>```

Title: 10 PRINT CHR$(205.5+RND(1)); : GOTO 10 in PHP (or anything else, for that matter)

Body:
Just had a 'spirited' conversation with a co-worker about the succinctness of the following BASIC statement:

```<code>10 PRINT CHR$(205.5+RND(1)); : GOTO 10
</code>```

It's the title of this book, and will simply print a sequence of / and \ characters, alternating between the two randomly, resulting in a pattern similar to this:

(Image borrowed from http://www.flickr.com/photos/rndmcnlly/5058442151/sizes/o/in/photostream/)

Being of a PHP proclivity, we wondered what the most compact way of writing the same thing in PHP would be, and came up with this:

```<code>while(1) { echo chr(47 + 45 * rand(0,1)); }
</code>```

chr(47) is a / character, and chr(92) is a \. So the statement echo chr(47 + 45 * rand(0,1)); will randomly alternate between the two, ad nauseam.

In a language of your choosing, write the shortest program or function to output an infinite random sequence of \ and / characters, where each character has an equal probability of being chosen.

Body:
Java 8, <s>60</s> <s>59</s> <s>54</s> 53 bytes

v->{for(;;)System.out.write(Math.random()<.5?47:92);}

-1 byte thanks to @BenjaminUrquhart by replacing print with write, so '/' can be 47.

Explanation:

Try it online (times out after 60 sec).

v->{                     // Method with empty unused parameter and no return-type
  for(;;)                //  Loop indefinitely
    System.out.write(    //   Print:
      Math.random()<.5?  //    If the random decimal value in range [0,1) is below 0.5:
       47                //     Print forward slash
      :                  //    Else:
       92);}             //     Print backward slash


问:
Greatest Common Divisor
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

```<code>0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101
</code>```

答:
Java 8, <s>44</s> 37 bytes

Here is a straight up, non-recursive (because of the lambda) Euclidean algorithm.

```<code>(x,y)->{while(y>0)y=x%(x=y);return x}
</code>```

Update

-7 [16-10-04] Simplified while condition

Title: Greatest Common Divisor

Body:
Java 8, <s>44</s> 37 bytes

Here is a straight up, non-recursive (because of the lambda) Euclidean algorithm.

(x,y)->{while(y>0)y=x%(x=y);return x}

Update

-7 [16-10-04] Simplified while condition


答:
R, <s>39</s> 33 bytes

Surprised not to see an R answer on here yet. A recursive implementation of the Euclidean algorithm. Saved 2 bytes due to Giuseppe.

```<code>g=pryr::f(`if`(o<-x%%y,g(y,o),y))
</code>```

And here is a vectorized version (35 bytes) which works well for problems like Natural pi calculation.

```<code>g=pryr::f(ifelse(o<-x%%y,g(y,o),y))
</code>```

Title: Greatest Common Divisor

Body:
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

```<code>0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101
</code>```

Body:
R, <s>39</s> 33 bytes

Surprised not to see an R answer on here yet. A recursive implementation of the Euclidean algorithm. Saved 2 bytes due to Giuseppe.

g=pryr::f(`if`(o<-x%%y,g(y,o),y))

And here is a vectorized version (35 bytes) which works well for problems like Natural pi calculation.

g=pryr::f(ifelse(o<-x%%y,g(y,o),y))