答:
JavaScript (ES6), <s>48</s> <s>47</s> 45 bytes

```<code>a=>[h=l=0,...a.map(c=>c?--l:++h)].map(e=>e-l)
</code>```

This turned out to be similar to @ETHproductions' method, except I had started by directly calculating the first element and then using the binary vector to determine whether each digit is a new high or a new low. Edit: Saved 1 byte thanks to @ETHproductions. Saved 2 bytes by starting with zero and adjusting afterwards. My previous method turned out to be similar to @Dennis's method, but took 54 bytes:

```<code>a=>a.reduce((r,b)=>[...r.map(e=>b+e),r.length*!b],[0])
</code>```

Title: Generate antsy permutations

Body:
Introduction

I defined the class of antsy permutations in an earlier challenge.
As a reminder, a permutation p of the numbers from 0 to r-1 is antsy, if for every entry p[i] except the first, there is some earlier entry p[i-k] such that p[i] == p[i-k] ± 1.
As a fun fact, I also stated that for r ≥ 1, there are exactly 2r-1 antsy permutations of length r.
This means that there is a one-to-one correspondence between the antsy permutations of length r and the binary vectors of length r-1.
In this challenge, your task is to implement such a correspondence.

The task

Your task is to write a program or function that takes in a binary vector of length 1 ≤ n ≤ 99, and outputs an antsy permutation of length n + 1.
The permutation can be either 0-based of 1-based (but this must be consistent), and the input and output can be in any reasonable format.
Furthermore, different inputs must always give different outputs; other than that, you are free to return whichever antsy permutation you want.

The lowest byte count wins.

Example

The (0-based) antsy permutations of length 4 are

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

and your program should return one of them for each of the eight bit vectors of length 3:

```<code>0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
</code>```

Body:
JavaScript (ES6), <s>48</s> <s>47</s> 45 bytes

a=>[h=l=0,...a.map(c=>c?--l:++h)].map(e=>e-l)

This turned out to be similar to @ETHproductions' method, except I had started by directly calculating the first element and then using the binary vector to determine whether each digit is a new high or a new low. Edit: Saved 1 byte thanks to @ETHproductions. Saved 2 bytes by starting with zero and adjusting afterwards. My previous method turned out to be similar to @Dennis's method, but took 54 bytes:

a=>a.reduce((r,b)=>[...r.map(e=>b+e),r.length*!b],[0])


问:
Animate Adve the Adventurer

The challenge

Your task is to animate Adve the Adventurer moving through a creepy (i.e. Halloween) maze. Adve is a •; he's character fluid, though, so he does not mind being represented by a different character.

To animate Adve, you print out each frame; a frame is the map with his current location in it. Adve moves one space forward every turn and never backtracks. He starts in the first row and ends in the last.

Input

Any reasonable format like a string with a delimiter or string array. You can assume the input will be a map greater than 3*3, containing only one possible path. The only characters present will be # and .

Output

The frames.

Example maze (ok... labyrinth)

Here is a map without Adve in it; the first and last frames are this empty map (this map is 9x15):

```<code>### #####
##  #####
## ######
##      #
####### #
#   ### #
# # #   #
# #   ###
# #######
#    ####
#### ####
####  ###
##### ###
##### ###
##### ###
</code>```

This is code-golf, so shortest code in bytes wins!

The exact output for this can be found here (37 frames).

This is code-golf, so shortest code in bytes wins!

答:
JavaScript (ES6), 137

(1 byte saved thx @ETHproductions)

m=>(o=>{for(p=m.search` `-o,r=[m];[d,o/d,-o/d].some(q=>1/m[d=q,q+=p]?p=q:0);r.push(q.join``))(q=[...m])[p]=0})(d=1+m.search`
`)||[...r,m]
```
<p><em>Less golfed</em></p>
<pre class="lang-js prettyprint-override"><code>m=>{
  d = o = 1+m.search`\n`; // offset to next row and starting direction
  p = m.search` `-o; // starting position, 1 row above the first
  for( r=[m]; // r is the output array, start with empty maze
       // try moving in 3 directions (no back)
       // if no empty cell found, we have exit the maze
       [d,o/d,-o/d].some(q => 1/m[d=q,q+=p]? p=q : 0);
       r.push(q.join``) // add current frame
     )
     q=[...m], q[p] = 0; // build frame, '0' used to mark Adve position
  return [...r,m] // add last frame with maze empty again
}
</code>```

Test

F=
m=>(o=>{for(p=m.search` `-o,r=[m];[d,o/d,-o/d].some(q=>1/m[d=q,q+=p]?p=q:0);r.push(q.join``))(q=[...m])[p]=0})(d=1+m.search`\n`)||[...r,m]

function go() {
  var i=I.value,r=F(i),
      frame=x=>(x=r.shift())&&(O.textContent=x,setTimeout(frame,100))
  frame()
}

go()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#I { width:10em; height: 19em; font-size:10px}
#O { white-space:pre; font-family: monospace; font-size:10px; vertical-align: top; padding: 4px}</code>```

<textarea id=I>### #####
##  #####
## ######
##      #
####### #
#   ### #
# # #   #
# #   ###
# #######
#    ####
#### ####
####  ###
##### ###
##### ###
##### ###
</textarea><button onclick='go()'>go</button>

```

ContentLicense: CC BY-SA 3.0

Title: Animate Adve the Adventurer

Body:
JavaScript (ES6), 137

(1 byte saved thx @ETHproductions)

m=>(o=>{for(p=m.search` `-o,r=[m];[d,o/d,-o/d].some(q=>1/m[d=q,q+=p]?p=q:0);r.push(q.join``))(q=[...m])[p]=0})(d=1+m.search`
`)||[...r,m]

Less golfed

m=>{
  d = o = 1+m.search`\n`; // offset to next row and starting direction
  p = m.search` `-o; // starting position, 1 row above the first
  for( r=[m]; // r is the output array, start with empty maze
       // try moving in 3 directions (no back)
       // if no empty cell found, we have exit the maze
       [d,o/d,-o/d].some(q => 1/m[d=q,q+=p]? p=q : 0);
       r.push(q.join``) // add current frame
     )
     q=[...m], q[p] = 0; // build frame, '0' used to mark Adve position
  return [...r,m] // add last frame with maze empty again
}

Test

F=
m=>(o=>{for(p=m.search` `-o,r=[m];[d,o/d,-o/d].some(q=>1/m[d=q,q+=p]?p=q:0);r.push(q.join``))(q=[...m])[p]=0})(d=1+m.search`\n`)||[...r,m]

function go() {
  var i=I.value,r=F(i),
      frame=x=>(x=r.shift())&&(O.textContent=x,setTimeout(frame,100))
  frame()
}

go()

#I { width:10em; height: 19em; font-size:10px}
#O { white-space:pre; font-family: monospace; font-size:10px; vertical-align: top; padding: 4px}

<table><tr><td>
<textarea id=I>### #####
##  #####
## ######
##      #
####### #
#   ### #
# # #   #
# #   ###
# #######
#    ####
#### ####
####  ###
##### ###
##### ###
##### ###
</textarea><button onclick='go()'>go</button></td><td id=O></td></tr></table>


问:
Markov Chain Quine
A simple Markov Model will be used in this question. For more information about Markov Chains, see http://setosa.io/ev/markov-chains/.

Take a string. For this example, we will use the word:

```<code>reader
</code>```

Now, for each character, take the characters that appear after each occurence of the character in the string. (`^` represents the start of the string and `$` represents the end)

```<code>`^` -> {'r'}       # After the start of the string, there is an `r`.
'r' -> {'e', `$`}  # After the first `r` (*r*eader), there is an `e`
                   # after the second (reade*r*), there is the end of the string.
'e' -> {'a', 'r'}
'a' -> {'d'}
'd' -> {'e'}
</code>```

Now, starting from the start of the string, pick randomly from one of the characters in the next set. Append this character and then pick from the characters in its next set, and so on until you get to the end. Here are some example words:

```<code>r
rereader
rer
readereader
</code>```

If a character appears after another character multiple times, it is more likely to be chosen. For example, in cocoa can, after a c, there is a two thirds of a chance of getting an o and a one thirds chance of getting an a.

```<code>'c' -> {'o', 'o', 'a'}
</code>```

Challenge

Create a program that takes no input and outputs a random string generated using a Markov Chain, like above, where the input to the chain is the program's source.

The program must have at least two characters, two of which must be the same (To prevent "boring" chains that only have one output)

You can modify the model to use bytes instead of characters if you wish, but change "characters" to "bytes" in rule 1

The program should output strings randomly with the expected frequency in theory

This is code-golf, so the shortest program wins!

答:
Ruby, 152 bytes

0;s="0;s=%p<<33
0until putc($/=Hash[[*(s%%s).chars.each_cons(2)].shuffle][$/])==?"<<33
0until putc($/=Hash[[*(s%s).chars.each_cons(2)].shuffle][$/])==?!
```

<p>Sample output:</p>

<pre class="lang-rb prettyprint-override"><code>0;s.c($/=Has(s).ears(2).ch[*(2)=Hacontc(2).ears.eas=Has==Hars%putc($/]).ears%sh_chuffl puns=Hachach[$/==?!
</code>```

or

0;s.ch[*($/=%pufl puns($/=%s.shas($/=Harsh_chutilears)])].e]).s)=Hac($/=="<<33\ntile].chufffle][[$/=Hars%sh_c(2)=%p<<<<<33
0;s)].ears)=Hars).c(s).eacon0un0;sh_c($/][*(s.s=Hacons=?!
```

Quines using string formatting via "s%s", and does the Markov chaining by taking all two-character slices, shuffling them, and turning them into a Hash dictionary, where for duplicate keys the last appearance defines the value. To avoid adding extra logic for the beginning, I track the most recently output character using $/, which is automatically initialized to a newline, and ensure that newlines are always followed in the code by 0, the same character the code starts with. For the end, I manipulate the source code so that there's only one ! so we always end after the bang, using <<33 to add it without the literal. This could be golfed further using an unprintable single-digit character instead of ASCII 33, but that seemed too annoying.

Title: Markov Chain Quine

Body:
Ruby, 152 bytes

0;s="0;s=%p<<33
0until putc($/=Hash[[*(s%%s).chars.each_cons(2)].shuffle][$/])==?"<<33
0until putc($/=Hash[[*(s%s).chars.each_cons(2)].shuffle][$/])==?!

Sample output:

0;s.c($/=Has(s).ears(2).ch[*(2)=Hacontc(2).ears.eas=Has==Hars%putc($/]).ears%sh_chuffl puns=Hachach[$/==?!

or

0;s.ch[*($/=%pufl puns($/=%s.shas($/=Harsh_chutilears)])].e]).s)=Hac($/=="<<33\ntile].chufffle][[$/=Hars%sh_c(2)=%p<<<<<33
0;s)].ears)=Hars).c(s).eacon0un0;sh_c($/][*(s.s=Hacons=?!

Quines using string formatting via "s%s", and does the Markov chaining by taking all two-character slices, shuffling them, and turning them into a Hash dictionary, where for duplicate keys the last appearance defines the value. To avoid adding extra logic for the beginning, I track the most recently output character using $/, which is automatically initialized to a newline, and ensure that newlines are always followed in the code by 0, the same character the code starts with. For the end, I manipulate the source code so that there's only one ! so we always end after the bang, using <<33 to add it without the literal. This could be golfed further using an unprintable single-digit character instead of ASCII 33, but that seemed too annoying.


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

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

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

Your program has to do the following:

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

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

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

A few explanations:

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

```<code>"trick"

"Treat"

"    TReAt"

"
     tRICk          "
</code>```

Invalid outputs:

```<code>"tri ck"

"tr
eat"

"trck"
</code>```

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

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

Leaderboards

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Python, Lua 31 or 32 bytes

```<code>s="trick"
--0;s="treat"
print s
</code>```

The one above has to be run using python 2.

```<code>s="trick"
--0;s="treat"
print(s)
</code>```

The -- designates a comment in Lua, while it is two negatives in Python.
Prints "trick" in Lua, but prints "treat" in Python.

Title: Trick or Treat polyglot

Body:
Python, Lua 31 or 32 bytes

s="trick"
--0;s="treat"
print s

The one above has to be run using python 2.

s="trick"
--0;s="treat"
print(s)

The -- designates a comment in Lua, while it is two negatives in Python.
Prints "trick" in Lua, but prints "treat" in Python.


问:
Generate antsy permutations

Introduction

I defined the class of antsy permutations in an earlier challenge.
As a reminder, a permutation p of the numbers from 0 to r-1 is antsy, if for every entry p[i] except the first, there is some earlier entry p[i-k] such that p[i] == p[i-k] ± 1.
As a fun fact, I also stated that for r ≥ 1, there are exactly 2r-1 antsy permutations of length r.
This means that there is a one-to-one correspondence between the antsy permutations of length r and the binary vectors of length r-1.
In this challenge, your task is to implement such a correspondence.

The task

Your task is to write a program or function that takes in a binary vector of length 1 ≤ n ≤ 99, and outputs an antsy permutation of length n + 1.
The permutation can be either 0-based of 1-based (but this must be consistent), and the input and output can be in any reasonable format.
Furthermore, different inputs must always give different outputs; other than that, you are free to return whichever antsy permutation you want.

The lowest byte count wins.

Example

The (0-based) antsy permutations of length 4 are

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

and your program should return one of them for each of the eight bit vectors of length 3:

```<code>0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
</code>```

答:
Python, 54 bytes

lambda l:[i-i*x+sum(l[i:])for i,x in enumerate([1]+l)]
```

<p>Uses the following procedure:</p>

<ol>
<li>Prepend a 1 to the list.</li>
<li>For each 0 entry, write its position in the 0-indexed list.</li>
<li>For each entry, write the number of 1's to its right, not counting itself.</li>
<li>Add the results of steps 2 and 3 entrywise.</li>
</ol>

<p>For example, <code>l=[1,0,1,0]</code> gives <code>f(l) == [2,1,3,0,4]</code></p>

```List with prepended 1         1 1 0 1 0

0-indexed position for 0's        2   4
Number of 1's to right        2 1 1 0 0
Sum of above two              2 1 3 0 4
```

Prepending a 0 would also give the same result. The enumerate is clunky, I'll see if it can done better recursively.

Title: Generate antsy permutations

Body:
Python, 54 bytes

lambda l:[i-i*x+sum(l[i:])for i,x in enumerate([1]+l)]

Uses the following procedure:

Prepend a 1 to the list.

For each 0 entry, write its position in the 0-indexed list.

For each entry, write the number of 1's to its right, not counting itself.

Add the results of steps 2 and 3 entrywise.

For example, l=[1,0,1,0] gives f(l) == [2,1,3,0,4]

List with prepended 1         1 1 0 1 0

0-indexed position for 0's        2   4
Number of 1's to right        2 1 1 0 0
Sum of above two              2 1 3 0 4

Prepending a 0 would also give the same result. The enumerate is clunky, I'll see if it can done better recursively.


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

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

Your task

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

Test cases

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

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

答:
Labyrinth, 8 bytes

```<code>?(_9%)!@
</code>```

using the equation (n-1)%9+1:

? reads the input as decimal and pushes it to the stack

( decrements the top of the stack

_ pushes a zero onto the top of the stack

9 push the top of the stack popped times 10 the digit (in this case, 9)

% pops y, pops x, pushes x%y

) increments the top of the stack

! pops the top of the stack and out puts it as a decimal string

@ terminates the program

Title: Print the digital root

Body:
Labyrinth, 8 bytes

?(_9%)!@

using the equation (n-1)%9+1:

? reads the input as decimal and pushes it to the stack

( decrements the top of the stack

_ pushes a zero onto the top of the stack

9 push the top of the stack popped times 10 the digit (in this case, 9)

% pops y, pops x, pushes x%y

) increments the top of the stack

! pops the top of the stack and out puts it as a decimal string

@ terminates the program


Title: Visualize an Array

Body:
Given an array of any depth, draw its contents with borders of +-| around each subarray. Those are the ASCII characters for plus, minus, and vertical pipe.

For example, if the array is [1, 2, 3], draw

```<code>+-----+
|1 2 3|
+-----+
</code>```

For a nested array such as [[1, 2, 3], [4, 5], [6, 7, 8]], draw

```<code>+-----------------+
|+-----+---+-----+|
||1 2 3|4 5|6 7 8||
|+-----+---+-----+|
+-----------------+
</code>```

For a ragged array such as [[[1, 2, 3], [4, 5]], [6, 7, 8]], draw

```<code>+-------------------+
|+-----------+-----+|
||+-----+---+|6 7 8||
|||1 2 3|4 5||     ||
||+-----+---+|     ||
|+-----------+-----+|
+-------------------+
</code>```

Notice that there is more space after drawing [6, 7, 8]. You may either draw the contents on the top-most, center, or bottom-most line, but whichever you choose, you must remain consistent.

This challenge was inspired by the box verb < from J.

Rules

This is code-golf so the shortest code wins.

Builtins that solve this are not allowed.

The input array will contain only nonnegative integer values or arrays. Each array will be homogenous, meaning that its elements will either by only arrays or only integers, but never a mix of both.

Each subarray may be nested to any depth.

The output may either by as a string or as an array of strings where each string is a line of output.

Test Cases

```<code>[]
++
||
++

[[], []]
+---+
|+++|
|||||
|+++|
+---+

[[], [1], [], [2], [], [3], []]
+-----------+
|++-++-++-++|
|||1||2||3|||
|++-++-++-++|
+-----------+

[[[[[0]]]]]
+---------+
|+-------+|
||+-----+||
|||+---+|||
||||+-+||||
|||||0|||||
||||+-+||||
|||+---+|||
||+-----+||
|+-------+|
+---------+

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

Body:
Ruby, 104 bytes

->s{r=s=s.gsub'}{',?|
r=[s,r,s]*$/while s=s.tr('!-9',' ').gsub!(/{[ |]*}/){$&.tr' -}','-+'}
r.tr'{}',?|}

Anonymous function that expects a string. For example, {{{{{4 3 2 1}}}}{{{3 2 1}}}{{2 1}}{1}} produces

+---------------------------------+
|+-------------+---------+-----+-+|
||+-----------+|         |     | ||
|||+---------+||+-------+|     | ||
||||+-------+||||+-----+||+---+| ||
|||||4 3 2 1||||||3 2 1||||2 1||1||
||||+-------+||||+-----+||+---+| ||
|||+---------+||+-------+|     | ||
||+-----------+|         |     | ||
|+-------------+---------+-----+-+|
+---------------------------------+

You can use this code for testing:

f=->s{r=s=s.gsub'}{',?|
r=[s,r,s]*$/while s=s.tr('!-9',' ').gsub!(/{[ |]*}/){$&.tr' -}','-+'}
r.tr'{}',?|}

a=[]

a<<'[1, 2, 3]'
a<<'[[1, 2, 3], [4, 5], [6, 7, 8]]'
a<<'[[[1, 2, 3], [4, 5]], [6, 7, 8]]'
a<<'[]'
a<<'[[], []]'
a<<'[[], [1], [], [2], [], [3], []]'
a<<'[[[[[0]]]]]'
a<<'[[[[[4, 3, 2, 1]]]], [[[3, 2, 1]]], [[2, 1]], [1]]'

a.map{|s|s.gsub! '], [','}{'
s.tr! '[]','{}'
s.gsub! ',',''
puts s
puts f[s],''}

This starts from the middle row and works outwards. First, instances of }{ are replaced with |. Then, while there are still braces, all innermost {...} strings are transformed into the appropriate +- sequences while characters other than |{} are turned into spaces. At the end, the intermediate braces are turned into pipes.


问:
Division of not so little numbers
Write a program or function that takes in positive integers a, b and c, and prints or returns a/b to c decimal places, using the operations +-*/% [add, subtract, multiply, divide, modulate] on the positive integers: you can use all that your language allows, but not on floating point numbers. The range of a,b,c would be the range allowed for unsigned integers in your language.
The number result will be truncated to the last digit to print (so no round).

This means that if your language does not have an integer type (only float), you can participate by using these float numbers as positive integers only.
The clue of this exercise it would be to write the function that find the
digits in a float point division, using only the operation +-*/%  on
[unsigned] integers.

Examples

print(1,2,1) would print 0.5

print(1,2,2) would print 0.50

print(13,7,27) would print 1.857142857142857142857142857

print(2,3,1) would print 0.6

print(4,5,7) would print 0.8000000

print(4,5,1) would print 0.8

print(9999,23,1) would print 434.7

print(12345613,2321,89) would print if your Language has 32 bit unsigned 5319.09220163722533390779836277466609220163722533390779836277466609220163722533390779836277466

The shortest code in bytes wins. I'm sorry if this appear not clear... I don't know languages too, not remember words well...
It is better to have one link to Ideone.com or some other place for easily try the answer especially for to test some input different from proposed.

答:
Mathematica, 50 bytes

```<code>StringInsert[ToString@Floor[10^# #2/#3],".",-#-1]&
</code>```

Unnamed function of three arguments (which are ordered c, a, b to save a byte somewhere), which returns a string. It multiplies a/b by 10^c, takes the greatest integer function, then converts to a string and inserts a decimal point at the appropriate spot. Too bad the function names aren't shorter.

Title: Division of not so little numbers

Body:
Mathematica, 50 bytes

StringInsert[ToString@Floor[10^# #2/#3],".",-#-1]&

Unnamed function of three arguments (which are ordered c, a, b to save a byte somewhere), which returns a string. It multiplies a/b by 10^c, takes the greatest integer function, then converts to a string and inserts a decimal point at the appropriate spot. Too bad the function names aren't shorter.


答:
Haskell, 40 bytes

foldl(\r a->map(+0^a)r++[a*length r])[0]
```

<p>Dennis's Python solution golfs wonderfully in Haskell with <code>map</code> and <code>fold</code>. It's shorter than my attempts to port my direct entrywise construction:
</p>

<pre class="lang-haskell prettyprint-override"><code>f l=[i*0^x+sum(drop i l)|(i,x)<-zip[0..]$0:l]
f l=[a+c-b*c|(a,c,b)<-zip3(scanr(+)0l)[0..]$0:l]
</code>```

Title: Generate antsy permutations

Body:
Haskell, 40 bytes

foldl(\r a->map(+0^a)r++[a*length r])[0]

Dennis's Python solution golfs wonderfully in Haskell with map and fold. It's shorter than my attempts to port my direct entrywise construction:

f l=[i*0^x+sum(drop i l)|(i,x)<-zip[0..]$0:l]
f l=[a+c-b*c|(a,c,b)<-zip3(scanr(+)0l)[0..]$0:l]


问:
Interlace strings
Your challenge is to write a program or function that, when given two strings of equal length, swaps every other character and outputs/returns the resulting strings in either order.

Examples

```<code>"Hello," "world!" --> "Hollo!" "werld,"
"code" "golf" --> "codf" "gole"
"happy" "angry" --> "hnpry" "aagpy"
"qwerty" "dvorak" --> "qvertk" "dworay"
"1, 2, 3" "a, b, c" --> "1, b, 3" "a, 2, c"
"3.141592653589" "2.718281828459" --> "3.111291623489" "2.748582858559"
"DJMcMayhem" "trichoplax" --> "DrMcMoylex" "tJichapham"
"Doorknob" "Downgoat" --> "Doonkoot" "Dowrgnab"
"Halloween" "Challenge" --> "Hhlloeegn" "Caallwnee"
</code>```

Rules

The strings will only contain ASCII chars (32-126).

The strings will always be the same length, and will never be empty.

You may accept input in any suitable format: separate parameters, items in an array, separated by one or more newlines, even concatenated. The only restriction is that one string must come fully before the other (e.g. a1\nb2\nc3 for "abc", "123" is invalid).

The output may be in either order (i.e. you can start swapping from the first or the second char), and in any valid format mentioned above. (2-item array, separated by newline(s), concatenated, etc.)

Scoring

This is code-golf, so the shortest code in bytes for each language wins.

答:
Lithp, 120 characters (+3 for -v1 flag)

Line split in 2 for readability:

```<code>#P::((invoke P "map" (js-bridge #W,I::(replace W (regex "." "g")
     (js-bridge #C,J::(index (index P (& (+ I J) 1)) J))))))
</code>```

Requires the -v1 flag to run.js as some functions are not yet part of the standard library.

Sample usage:

```<code>(
    (def f #P::((invoke P "map" (js-bridge #W,I::(replace W (regex "." "g")
                (js-bridge #C,J::(index (index P (& (+ I J) 1)) J)))))))
    (print (f (list "Hello," "world!")))
)
</code>```

This sort of highlights that I haven't spent enough time on the standard library. Having to use js-bridge/1 twice and the long regex form, as well as invoking map using invoke/* all contribute to this being much longer than it needs to be.

Time to work on my standard library more I think.

Title: Interlace strings

Body:
Lithp, 120 characters (+3 for -v1 flag)

Line split in 2 for readability:

#P::((invoke P "map" (js-bridge #W,I::(replace W (regex "." "g")
     (js-bridge #C,J::(index (index P (& (+ I J) 1)) J))))))

Requires the -v1 flag to run.js as some functions are not yet part of the standard library.

Sample usage:

(
    (def f #P::((invoke P "map" (js-bridge #W,I::(replace W (regex "." "g")
                (js-bridge #C,J::(index (index P (& (+ I J) 1)) J)))))))
    (print (f (list "Hello," "world!")))
)

This sort of highlights that I haven't spent enough time on the standard library. Having to use js-bridge/1 twice and the long regex form, as well as invoking map using invoke/* all contribute to this being much longer than it needs to be.

Time to work on my standard library more I think.


问:
Pairable strings
A string is pairable if it can be split into subtrings, each of which is a string repeated twice consecutively. For example, aabaaababbbaba is pairable as:

```<code>aaba aaba
b b
ba ba
</code>```

Given a non-empty string of a's and b's, output a Truthy value if it's pairable and a Falsey value if it isn't.

Pairable:

```<code>aa
abaaba
bbababbb
aabaaababbbaba
babababa
bbbbbbbbbbbb
aaababbabbabbbababbaabaabaababaaba
aaaabaab
</code>```

Not pairable:

```<code>a
ba
baab
abaabaaba
bbbbbbbbbbbbbbb
baababbabaaaab
aaaaabbaaaaa
</code>```

I encourage you to come up with non-regex-based solutions even when there's already a shorter regex answer in your language. You can mark them as "no regex". By regex, I mean a built-in string pattern matching subsystem.

Leaderboard:

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

```

答:
Pyth - No Regex - <s>13</s> 12 bytes

Checks if any of the partitions are made up of all string that are  equals to each other when chopped in two.

```<code>sm.AqMcL2d./
</code>```

Test Suite.

Title: Pairable strings

Body:
Pyth - No Regex - <s>13</s> 12 bytes

Checks if any of the partitions are made up of all string that are  equals to each other when chopped in two.

sm.AqMcL2d./

Test Suite.


答:
Retina, 11 bytes

```<code>^((.+)\2)+$
</code>```

Try all the test cases. The first two bytes make it multi-line.

Pretty literal interpretation of the rules, obviously uses regex, like all Retina programs will.

Title: Pairable strings

Body:
A string is pairable if it can be split into subtrings, each of which is a string repeated twice consecutively. For example, aabaaababbbaba is pairable as:

```<code>aaba aaba
b b
ba ba
</code>```

Given a non-empty string of a's and b's, output a Truthy value if it's pairable and a Falsey value if it isn't.

Pairable:

```<code>aa
abaaba
bbababbb
aabaaababbbaba
babababa
bbbbbbbbbbbb
aaababbabbabbbababbaabaabaababaaba
aaaabaab
</code>```

Not pairable:

```<code>a
ba
baab
abaabaaba
bbbbbbbbbbbbbbb
baababbabaaaab
aaaaabbaaaaa
</code>```

I encourage you to come up with non-regex-based solutions even when there's already a shorter regex answer in your language. You can mark them as "no regex". By regex, I mean a built-in string pattern matching subsystem.

Leaderboard:

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

^((.+)\2)+$

Try all the test cases. The first two bytes make it multi-line.

Pretty literal interpretation of the rules, obviously uses regex, like all Retina programs will.


答:
JavaScript (ES6), 24 bytes

```<code>x=>/^((.+)\2)+$/.test(x)
</code>```

Probably doesn't get shorter than this.

Title: Pairable strings

Body:
JavaScript (ES6), 24 bytes

x=>/^((.+)\2)+$/.test(x)

Probably doesn't get shorter than this.


答:
sh / csh, 32 bytes

```<code>echo trick #treat|sed 's/.*#//'
</code>```

For csh, the command must be executed interactively.

Explanation: In interactive mode, sh treats anything starting with # as a comment. csh does so only in batch mode.

ksh and bash behave the same way as sh.  tcsh behaves like csh.  Some of these shells have options to alter this behavior.

zsh behaves like csh for this particular command.

Title: Trick or Treat polyglot

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

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

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

Your program has to do the following:

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

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

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

A few explanations:

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

```<code>"trick"

"Treat"

"    TReAt"

"
     tRICk          "
</code>```

Invalid outputs:

```<code>"tri ck"

"tr
eat"

"trck"
</code>```

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

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

Leaderboards

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
sh / csh, 32 bytes

echo trick #treat|sed 's/.*#//'

For csh, the command must be executed interactively.

Explanation: In interactive mode, sh treats anything starting with # as a comment. csh does so only in batch mode.

ksh and bash behave the same way as sh.  tcsh behaves like csh.  Some of these shells have options to alter this behavior.

zsh behaves like csh for this particular command.


答:
PHP, 40 Bytes

prints 0 for false and 1 for true

```<code><?=preg_match("#^((.+)\\2)+$#",$argv[1]);
</code>```

Title: Pairable strings

Body:
PHP, 40 Bytes

prints 0 for false and 1 for true

<?=preg_match("#^((.+)\\2)+$#",$argv[1]);


答:
Jelly, 10 bytes

```<code>ẆŒPẋ€€2F€ċ
</code>```

Not exactly efficient... Try it online!

How it works

```<code>ẆŒPẋ€€2F€ċ  Main link. Argument: s (string)

Ẇ           Window, generate the array of all substrings of s.
 ŒP         Powerset; generate all subarrays of substrings of s.
   ẋ€€2     Repeat each substring in each subarray twice.
            For example, ["ab", "a", "b"] becomes ["abab", "aa", "bb"].
       F€   Flatten the subarrays by concatenating their strings.
         ċ  Count how many times s appears in the generated strings.
</code>```

Title: Pairable strings

Body:
Jelly, 10 bytes

ẆŒPẋ€€2F€ċ

Not exactly efficient... Try it online!

How it works

ẆŒPẋ€€2F€ċ  Main link. Argument: s (string)

Ẇ           Window, generate the array of all substrings of s.
 ŒP         Powerset; generate all subarrays of substrings of s.
   ẋ€€2     Repeat each substring in each subarray twice.
            For example, ["ab", "a", "b"] becomes ["abab", "aa", "bb"].
       F€   Flatten the subarrays by concatenating their strings.
         ċ  Count how many times s appears in the generated strings.


答:
Python 2, <s>68</s> 63 bytes

f=lambda s,n=1:s==2*s[:n]or''<s[n:]>-f(s,n+1)<f(s[n:])*f(s[:n])
```

Returns True or False. Test it on Ideone.

Title: Pairable strings

Body:
Python 2, <s>68</s> 63 bytes

f=lambda s,n=1:s==2*s[:n]or''<s[n:]>-f(s,n+1)<f(s[n:])*f(s[:n])

Returns True or False. Test it on Ideone.


问:
Decode Baby-talk!
When babies open their mouths, they're not just spewing gibberish. They're actually talking in a highly advanced, adult-proof cipher...

The Baby-talk Cipher

When a baby talks, it could look something like gogooa gagooook aagaaoooy
Each single-space separated section represents a character (so the example above represents 3 characters).

To decipher a section, we must count number of As and Os it contains. However, we only count those which are adjacent to another vowel. For example, the A in 'gag' would not count, but both the A and O in 'gaog' would.

Counting the example above would look like this:

```<code>Section    | Num Os | Num As

gogooa     | 2      | 1
gagooook   | 4      | 0
aagaaoooy  | 3      | 4
</code>```

We then use these values to convert the input into plaintext on a Polybius square. This is a 5x5 representation of the English alphabet, omitting 'J' (please note that, in baby-talk, 0-counting rules apply to the table):

```<code>  0 1 2 3 4
0 A B C D E
1 F G H I K
2 L M N O P
3 Q R S T U
4 V W X Y Z
</code>```

Using the number of Os as the column, and number of As as the row, we find which character each section represents:

```<code>Section    | Num Os | Num As | Character

gogooa     | 2      | 1      | (2,1) -> H
gagooook   | 4      | 0      | (4,0) -> E
aagaaoooy  | 3      | 4      | (3,4) -> Y
</code>```

Which tells us that the baby was just saying "HEY".

Notes:

- If a section representing a character has more than 4 As or Os, ignore the extras, because 4 is the maximum value on the table.
- For this task, Y is not a vowel - only A, E, I, O and U.

The Challenge

Your task is to create a full program which takes one input, a word in baby-speak, and prints it in plaintext.

Your program must be able to take input in uppercase, lowercase, and a mix of both.

The input will only contain ASCII alphabet letters (A-Z and a-z), with single spaces to seperate the baby words.

The output text can be in any case.

You should the take the input from STDIN and print the plaintext on STDOUT. If your language does not have these, use the nearest equivalent.

This is code-golf, so the shortest code in bytes wins - but any solution is welcome.

Test Cases

```<code>'GLOOG KAKAAOOO ARGOOO OOOOOGUGUU' -> CODE
'oaka pooopaa gaau augu' -> GOLF
'Aoao U oOOAoa oaoAoo aoAoAOa' -> NAPPY
'GUG gAGaA gOougOou' -> ALE
'OOaGOG GoGOOoGoU gAA bLAA GOUGoOUgAIGAI' -> HELLO
</code>```

答:
Kotlin, <s>221</s> 209 bytes

Now much more ugly and slow, all in the name of 11 bytes

readLine()!!.toLowerCase().split(" ").map{fun
c(c:Char)=Regex("([aeiou]{2,})").findAll(it).fold(0){a,b->a+b.value.count{it==c}}.let{if(it>4)4 else it}
(('A'..'I')+('K'..'Z'))[c('a')*5+c('o')]}.forEach(::print)
```

<p>Save it to a file (ex. <code>BabyTalk.kts</code>) to run as a script. Or, the above code can be prepended with <code>fun main(z:Array<String>)=</code> and compiled normally for a cost of 26 more bytes.</p>

<p>Try it online!</p>

<p>Indented:</p>

<pre class="lang-kotlin prettyprint-override"><code>readLine()!!
    .toLowerCase()
    .split(" ")
    .map {
        fun c(c: Char) =
            Regex("([aeiou]{2,})")
                .findAll(it)
                .fold(0) {
                    a, b ->
                    a + b.value.count { it == c }
                }
                .let { if (it > 4) 4 else it }
        (('A'..'I') + ('K'..'Z'))[c('a') * 5 + c('o')]
    }
    .forEach(::print)
</code>```

Title: Decode Baby-talk!

Body:
Kotlin, <s>221</s> 209 bytes

Now much more ugly and slow, all in the name of 11 bytes

readLine()!!.toLowerCase().split(" ").map{fun
c(c:Char)=Regex("([aeiou]{2,})").findAll(it).fold(0){a,b->a+b.value.count{it==c}}.let{if(it>4)4 else it}
(('A'..'I')+('K'..'Z'))[c('a')*5+c('o')]}.forEach(::print)

Save it to a file (ex. BabyTalk.kts) to run as a script. Or, the above code can be prepended with fun main(z:Array<String>)= and compiled normally for a cost of 26 more bytes.

Try it online!

Indented:

readLine()!!
    .toLowerCase()
    .split(" ")
    .map {
        fun c(c: Char) =
            Regex("([aeiou]{2,})")
                .findAll(it)
                .fold(0) {
                    a, b ->
                    a + b.value.count { it == c }
                }
                .let { if (it > 4) 4 else it }
        (('A'..'I') + ('K'..'Z'))[c('a') * 5 + c('o')]
    }
    .forEach(::print)


答:
JavaScript (ES6), no regexp, <s>75</s> 74 bytes

```<code>f=s=>!s|[...s].some((_,i)=>i&&s[e='slice'](0,i)==s[e](i,i+=i)&&f(s[e](i)))
</code>```

Returns 1 for pairable otherwise 0. Edit: Saved 1 byte thanks to @edc65.

Title: Pairable strings

Body:
JavaScript (ES6), no regexp, <s>75</s> 74 bytes

f=s=>!s|[...s].some((_,i)=>i&&s[e='slice'](0,i)==s[e](i,i+=i)&&f(s[e](i)))

Returns 1 for pairable otherwise 0. Edit: Saved 1 byte thanks to @edc65.


答:
Python / JavaScript, 32 bytes

```<code>1//2;print"trick"
alert("treat")
</code>```

Python runs 1//2;, which integer divides 1 by 2, then prints "trick". alert("treat") causes a runtime error because alert is not a function, but I believe this is allowed.

JavaScript runs 1 and sees the rest of the line as a comment. The second line alerts "treat".

Note that I can't shorten alert("treat") to alert`treat` because Python will throw a syntax error during compilation.

Title: Trick or Treat polyglot

Body:
Python / JavaScript, 32 bytes

1//2;print"trick"
alert("treat")

Python runs 1//2;, which integer divides 1 by 2, then prints "trick". alert("treat") causes a runtime error because alert is not a function, but I believe this is allowed.

JavaScript runs 1 and sees the rest of the line as a comment. The second line alerts "treat".

Note that I can't shorten alert("treat") to alert`treat` because Python will throw a syntax error during compilation.


答:
Python 3, 262 bytes

import re;f,b,v,n,r,l,t,g,a,o=re.findall,input().lower(),'aeiou',list(range(26)),'[aeiou]','abcdefghiklmnopqrstuvwxyz','',len,'a','o';del n[9],
for w in b.split():
 O,A=g(f(o+r,w))+g(f(r+o,w)),g(f(a+r,w))+g(f(r+a,w))
 if O>4:O=4
 if A>4:A=4
 t+=l[A*5+O]
print(t)
```

<p>Less Golfed (The comments are the variables in the shortened code):</p>

<pre class="lang-python prettyprint-override"><code>import re
findAll = re.findall #f
babyTalk = input('Baby Talk: ').lower() #b
vowels = 'aeiou' #v
numbers = list(range(26)) #n
del numbers[9]
letters = 'abcdefghiklmnopqrstuvwxyz' #l
finalText = '' #t
length = len #g
regex = '[aeiou]' #r
o = 'o' #o
a = 'a' #a
for word in babyTalk.split(): #w in b
 Os = len(findAll('o[aeiou]', word)) + len(findAll('[aeiou]o', word)) #O
 As = len(findAll('a[aeiou]', word)) + len(findAll('[aeiou]a', word)) #A
 if Os > 4: Os = 4
 if As > 4: As = 4
 print(As, Os)
 finalText += letters[As*5+Os]
 print(finalText)
</code>```

Try it online!

Title: Decode Baby-talk!

Body:
When babies open their mouths, they're not just spewing gibberish. They're actually talking in a highly advanced, adult-proof cipher...

The Baby-talk Cipher

When a baby talks, it could look something like gogooa gagooook aagaaoooy
Each single-space separated section represents a character (so the example above represents 3 characters).

To decipher a section, we must count number of As and Os it contains. However, we only count those which are adjacent to another vowel. For example, the A in 'gag' would not count, but both the A and O in 'gaog' would.

Counting the example above would look like this:

```<code>Section    | Num Os | Num As

gogooa     | 2      | 1
gagooook   | 4      | 0
aagaaoooy  | 3      | 4
</code>```

We then use these values to convert the input into plaintext on a Polybius square. This is a 5x5 representation of the English alphabet, omitting 'J' (please note that, in baby-talk, 0-counting rules apply to the table):

```<code>  0 1 2 3 4
0 A B C D E
1 F G H I K
2 L M N O P
3 Q R S T U
4 V W X Y Z
</code>```

Using the number of Os as the column, and number of As as the row, we find which character each section represents:

```<code>Section    | Num Os | Num As | Character

gogooa     | 2      | 1      | (2,1) -> H
gagooook   | 4      | 0      | (4,0) -> E
aagaaoooy  | 3      | 4      | (3,4) -> Y
</code>```

Which tells us that the baby was just saying "HEY".

Notes:

- If a section representing a character has more than 4 As or Os, ignore the extras, because 4 is the maximum value on the table.
- For this task, Y is not a vowel - only A, E, I, O and U.

The Challenge

Your task is to create a full program which takes one input, a word in baby-speak, and prints it in plaintext.

Your program must be able to take input in uppercase, lowercase, and a mix of both.

The input will only contain ASCII alphabet letters (A-Z and a-z), with single spaces to seperate the baby words.

The output text can be in any case.

You should the take the input from STDIN and print the plaintext on STDOUT. If your language does not have these, use the nearest equivalent.

This is code-golf, so the shortest code in bytes wins - but any solution is welcome.

Test Cases

```<code>'GLOOG KAKAAOOO ARGOOO OOOOOGUGUU' -> CODE
'oaka pooopaa gaau augu' -> GOLF
'Aoao U oOOAoa oaoAoo aoAoAOa' -> NAPPY
'GUG gAGaA gOougOou' -> ALE
'OOaGOG GoGOOoGoU gAA bLAA GOUGoOUgAIGAI' -> HELLO
</code>```

Body:
Python 3, 262 bytes

import re;f,b,v,n,r,l,t,g,a,o=re.findall,input().lower(),'aeiou',list(range(26)),'[aeiou]','abcdefghiklmnopqrstuvwxyz','',len,'a','o';del n[9],
for w in b.split():
 O,A=g(f(o+r,w))+g(f(r+o,w)),g(f(a+r,w))+g(f(r+a,w))
 if O>4:O=4
 if A>4:A=4
 t+=l[A*5+O]
print(t)

Less Golfed (The comments are the variables in the shortened code):

import re
findAll = re.findall #f
babyTalk = input('Baby Talk: ').lower() #b
vowels = 'aeiou' #v
numbers = list(range(26)) #n
del numbers[9]
letters = 'abcdefghiklmnopqrstuvwxyz' #l
finalText = '' #t
length = len #g
regex = '[aeiou]' #r
o = 'o' #o
a = 'a' #a
for word in babyTalk.split(): #w in b
 Os = len(findAll('o[aeiou]', word)) + len(findAll('[aeiou]o', word)) #O
 As = len(findAll('a[aeiou]', word)) + len(findAll('[aeiou]a', word)) #A
 if Os > 4: Os = 4
 if As > 4: As = 4
 print(As, Os)
 finalText += letters[As*5+Os]
 print(finalText)

Try it online!


答:
JavaScript (ES6) / Japt, <s>47</s> <s>33</s> 22 bytes

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

JavaScript

This should be fairly obvious: 1 and "treat" do nothing, and alert`trick` alerts trick.

Japt

In Japt, lowercase letters (except those in strings) transpile to method calls, e.g. .a(. However, if it comes after another lowercase letter, it is instead transpiled to "a". All open parentheses are cut off at semicolons ;. This means that the code roughly transpiles to:

```<code>1 .a("l".e("r".t("trick")));"treat"
</code>```

This is then evaluated as JavaScript. "r".t("trick") is "r", "l".e("r") is "l", and 1.a("l") is 1. However, the poor JS engine's work is pointless: only the result of the last expression is sent to STDOUT, so the 1 is discarded and treat is printed.

Title: Trick or Treat polyglot

Body:
JavaScript (ES6) / Japt, <s>47</s> <s>33</s> 22 bytes

1
alert`trick`;"treat"

JavaScript

This should be fairly obvious: 1 and "treat" do nothing, and alert`trick` alerts trick.

Japt

In Japt, lowercase letters (except those in strings) transpile to method calls, e.g. .a(. However, if it comes after another lowercase letter, it is instead transpiled to "a". All open parentheses are cut off at semicolons ;. This means that the code roughly transpiles to:

1 .a("l".e("r".t("trick")));"treat"

This is then evaluated as JavaScript. "r".t("trick") is "r", "l".e("r") is "l", and 1.a("l") is 1. However, the poor JS engine's work is pointless: only the result of the last expression is sent to STDOUT, so the 1 is discarded and treat is printed.


问:
Produce Dürer's magic square

The challenge

Output an array or string representation of Dürer's famous magic square:

that is,

```<code>16  3  2 13
 5 10 11  8
 9  6  7 12
 4 15 14  1
</code>```

Some properties of this square, which can perhaps be exploited, are:

It contains each integer from 1 to 16 exactly once

The sum of each column or row, as well as the the sum of each of the two diagonals, is the same. This is the defining property of a magic square. The sum is the magic constant of the square.

In addition, for this particular square, the sum of each of the four quadrants also equals the magic constant, as do the sum of the center four squares and the sum of the corner four squares.

Rules

Bultins that generate magic squares are not allowed (such as Matlab's magic or Mathematica's MagicSquare). Any other builtin can be used.

The code can be a program or a function.

There is no input.

The numbers must be in base 10. The output format is flexible as usual. Some possibilities are:

A nested array (either function output, or its string representation, with or without separators, any type of matching brackets):

```<code>[[16, 3, 2, 13], [5, 10, 11, 8], [9, 6, 7, 12], [4, 15, 14, 1]]
</code>```

A 2D array:

```<code>{16, 3, 2, 13; 5, 10, 11, 8; 9, 6, 7, 12; 4, 15, 14, 1}
</code>```

An array of four strings, or a string consisting of four lines. The numbers may be right-aligned

```<code>16  3  2 13
 5 10 11  8
 9  6  7 12
 4 15 14  1
</code>```

or left-aligned

```<code>16 3  2  13
5  10 11  8
9  6  7  12
4  15 14  1
</code>```

A string with two different separators for row and column, such as

```<code>16,3,2,13|5,10,11,8|9,6,7,12|4,15,14,1
</code>```

The output format should clearly differentiate rows and columns. For example, it is not allowed to output a flat array, or a string with all numbers separated by spaces.

Code golf. Shortest wins.

答:
Ruby, 49 bytes (shorter than the naive solution!)

It took quite a few attempts to write a snippet for this challenge in a mainstream language that was shorter than what it evaluated to! Per usual rules I've made a program out of it by adding a p  to output it.

```<code>p [15,4,8,3].map{|i|[1+i,1+i^=13,1+i^=3,1+i^=13]}
</code>```

It outputs (the string representation of) an array of arrays. It's longer than wat's Ruby solution that outputs a differently-formatted string, but one byte shorter than the naive program below that simply returns the literal array.

```<code>p [[16,3,2,13],[5,10,11,8],[9,6,7,12],[4,15,14,1]] #naive solution, 50 bytes
p [15,4,8,3].map{|i|[1+i,1+i^=13,1+i^=3,1+i^=13]}  #submission, 49 bytes
</code>```

Explanation: start with numbers 0..15 (38 bytes!)

This is where I started and it´s much easier. If we convert the 0..15 square into binary, we note that each cell contains the value at the bottom of its column XORed with the value at the right hand side of its row:

```<code>15 2  1  12            1111 0010 0001 1100
4  9  10 7             0100 1001 1010 0111
8  5  6  11            1000 0101 0110 1011
3  14 13 0             0011 1110 1101 0000
</code>```

From this we derive the code below. But by using the first column instead of the last column, we save one byte, as shown.

```<code>p [12,7,11,0].map{|i|[i^3,i^14,i^13,i]}            #0..15 square, 39 bytes
p [15,4,8,3].map{|i|[i,i^13,i^14,i^3]}             #0..15 square, 38 bytes
</code>```

The required 1..16 version was more difficult. In the end I realised the way to do it was to add 1 to each cell of the 0..15 square. But as ^ has lower priority than + I needed a lot of parentheses, which ate bytes. Finally I hit on the idea of using ^=. The new value of i is calculated by augmented assignment ^= before the 1 is added to it, so the calculation is done in the correct order.

Title: Produce Dürer's magic square

Body:
Ruby, 49 bytes (shorter than the naive solution!)

It took quite a few attempts to write a snippet for this challenge in a mainstream language that was shorter than what it evaluated to! Per usual rules I've made a program out of it by adding a p  to output it.

p [15,4,8,3].map{|i|[1+i,1+i^=13,1+i^=3,1+i^=13]}

It outputs (the string representation of) an array of arrays. It's longer than wat's Ruby solution that outputs a differently-formatted string, but one byte shorter than the naive program below that simply returns the literal array.

p [[16,3,2,13],[5,10,11,8],[9,6,7,12],[4,15,14,1]] #naive solution, 50 bytes
p [15,4,8,3].map{|i|[1+i,1+i^=13,1+i^=3,1+i^=13]}  #submission, 49 bytes

Explanation: start with numbers 0..15 (38 bytes!)

This is where I started and it´s much easier. If we convert the 0..15 square into binary, we note that each cell contains the value at the bottom of its column XORed with the value at the right hand side of its row:

15 2  1  12            1111 0010 0001 1100
4  9  10 7             0100 1001 1010 0111
8  5  6  11            1000 0101 0110 1011
3  14 13 0             0011 1110 1101 0000

From this we derive the code below. But by using the first column instead of the last column, we save one byte, as shown.

p [12,7,11,0].map{|i|[i^3,i^14,i^13,i]}            #0..15 square, 39 bytes
p [15,4,8,3].map{|i|[i,i^13,i^14,i^3]}             #0..15 square, 38 bytes

The required 1..16 version was more difficult. In the end I realised the way to do it was to add 1 to each cell of the 0..15 square. But as ^ has lower priority than + I needed a lot of parentheses, which ate bytes. Finally I hit on the idea of using ^=. The new value of i is calculated by augmented assignment ^= before the 1 is added to it, so the calculation is done in the correct order.


答:
Jelly, 12 bytes

```<code>ŒṖµœs€2ZEµ€S
</code>```

Two bytes longer than my other answer, but this approach is a lot more efficient and handles all but one of the test cases.

Try it online!

How it works

```<code>ŒṖµœs€2ZEµ€S  Main link. Argument: s (string)

ŒṖ            Generate all partitions of s.
  µ      µ€   Map the monadic chain between the µ's over the partitions.
   œs€2         Split each string in the partition into two chunks of equal length.
       Z        Zip/transpose, collecting the first halves in one array and the
                second halves in another.
        E       Test the arrays of halves for equality.
           S  Return the sum of the results, counting the number of different
              ways s can be paired.
</code>```

Title: Pairable strings

Body:
Jelly, 12 bytes

ŒṖµœs€2ZEµ€S

Two bytes longer than my other answer, but this approach is a lot more efficient and handles all but one of the test cases.

Try it online!

How it works

ŒṖµœs€2ZEµ€S  Main link. Argument: s (string)

ŒṖ            Generate all partitions of s.
  µ      µ€   Map the monadic chain between the µ's over the partitions.
   œs€2         Split each string in the partition into two chunks of equal length.
       Z        Zip/transpose, collecting the first halves in one array and the
                second halves in another.
        E       Test the arrays of halves for equality.
           S  Return the sum of the results, counting the number of different
              ways s can be paired.


Title: Print the digital root

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

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

Your task

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

Test cases

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

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

Body:
J, 8 bytes

**1+9|<:

Uses the formula d(n) = ((n-1) mod 9) + 1 with the case d(0) = 0.

Usage

   f =: **1+9|<:
   (,.f"0) 0 1 45 341 6801 59613 495106
     0 0
     1 1
    45 9
   341 8
  6801 6
 59613 6
495106 7

Explanation

**1+9|<:  Input: integer n
      <:  Decrement n
    9|    Take it modulo 9
  1+      Add 1 to it
*         Sign(n) = 0 if n = 0, else 1
 *        Multiply and return


答:
Haskell, <s>72</s> 69 bytes (no regex)

```<code>g(a:b:c)|a==b=g c
g x=x==[]
any(g.words.concat).mapM(\c->[[c],c:" "])
</code>```

A brute-force approach. Try it on Ideone.

Thanks to BlackCap for -3 bytes.

Explanation

The helper function g takes a list of strings, and checks that it consists of pairs of identical strings, like ["aa","aa","bba","bba","ab","ab"].
The (anonymous) main function splits a string in all possible ways, and checks that at least one splitting results in a list that g accepts.

```<code>g(a:b:c)                                  g on list with elements a, b and tail c,
        |a==b                              in the case that a==b,
             =g c                          recurses to the tail c.
g x=                                      g on any other list x
    x==[]                                  checks that x is empty.
                                           This includes the case where a is not equal
                                           to b, resulting in False.
any(g.words.concat).mapM(\c->[[c],c:" "]) The main function:
                    mapM(\c->[[c],c:" "])  Replace each letter c with either "c" or "c "
                                           in all possible ways, return list of results.
any(              ).                       Check that at least one result satisfies this:
            concat                          Concatenate the 1- or 2-letter strings,
      words.                                split again at each space,
    g.                                      apply g.
</code>```

Title: Pairable strings

Body:
A string is pairable if it can be split into subtrings, each of which is a string repeated twice consecutively. For example, aabaaababbbaba is pairable as:

```<code>aaba aaba
b b
ba ba
</code>```

Given a non-empty string of a's and b's, output a Truthy value if it's pairable and a Falsey value if it isn't.

Pairable:

```<code>aa
abaaba
bbababbb
aabaaababbbaba
babababa
bbbbbbbbbbbb
aaababbabbabbbababbaabaabaababaaba
aaaabaab
</code>```

Not pairable:

```<code>a
ba
baab
abaabaaba
bbbbbbbbbbbbbbb
baababbabaaaab
aaaaabbaaaaa
</code>```

I encourage you to come up with non-regex-based solutions even when there's already a shorter regex answer in your language. You can mark them as "no regex". By regex, I mean a built-in string pattern matching subsystem.

Leaderboard:

var QUESTION_ID=98252,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/98252/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:
Haskell, <s>72</s> 69 bytes (no regex)

g(a:b:c)|a==b=g c
g x=x==[]
any(g.words.concat).mapM(\c->[[c],c:" "])

A brute-force approach. Try it on Ideone.

Thanks to BlackCap for -3 bytes.

Explanation

The helper function g takes a list of strings, and checks that it consists of pairs of identical strings, like ["aa","aa","bba","bba","ab","ab"].
The (anonymous) main function splits a string in all possible ways, and checks that at least one splitting results in a list that g accepts.

g(a:b:c)                                  g on list with elements a, b and tail c,
        |a==b                              in the case that a==b,
             =g c                          recurses to the tail c.
g x=                                      g on any other list x
    x==[]                                  checks that x is empty.
                                           This includes the case where a is not equal
                                           to b, resulting in False.
any(g.words.concat).mapM(\c->[[c],c:" "]) The main function:
                    mapM(\c->[[c],c:" "])  Replace each letter c with either "c" or "c "
                                           in all possible ways, return list of results.
any(              ).                       Check that at least one result satisfies this:
            concat                          Concatenate the 1- or 2-letter strings,
      words.                                split again at each space,
    g.                                      apply g.


答:
Batch, 127 bytes

```<code>@set s=%*
@set/an=h=l=%s: =+%
@for %%b in (%*)do @call:%%b
:0
@echo %n%
@set/an=h+=1
@exit/b
:1
@echo %n%
@set/an=l-=1
</code>```

Takes input as command-line parameters, output is line-separated. (It's possible to input as space-separated on STDIN for no extra cost.)

Title: Generate antsy permutations

Body:
Introduction

I defined the class of antsy permutations in an earlier challenge.
As a reminder, a permutation p of the numbers from 0 to r-1 is antsy, if for every entry p[i] except the first, there is some earlier entry p[i-k] such that p[i] == p[i-k] ± 1.
As a fun fact, I also stated that for r ≥ 1, there are exactly 2r-1 antsy permutations of length r.
This means that there is a one-to-one correspondence between the antsy permutations of length r and the binary vectors of length r-1.
In this challenge, your task is to implement such a correspondence.

The task

Your task is to write a program or function that takes in a binary vector of length 1 ≤ n ≤ 99, and outputs an antsy permutation of length n + 1.
The permutation can be either 0-based of 1-based (but this must be consistent), and the input and output can be in any reasonable format.
Furthermore, different inputs must always give different outputs; other than that, you are free to return whichever antsy permutation you want.

The lowest byte count wins.

Example

The (0-based) antsy permutations of length 4 are

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

and your program should return one of them for each of the eight bit vectors of length 3:

```<code>0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
</code>```

Body:
Batch, 127 bytes

@set s=%*
@set/an=h=l=%s: =+%
@for %%b in (%*)do @call:%%b
:0
@echo %n%
@set/an=h+=1
@exit/b
:1
@echo %n%
@set/an=l-=1

Takes input as command-line parameters, output is line-separated. (It's possible to input as space-separated on STDIN for no extra cost.)


答:
Brachylog, 14 bytes (no regex)

```<code>lye~l:1j@2zcc?
</code>```

Try it online!

This is too slow for some of the test cases

Explanation

```<code>ly                  The list [0, …, length(Input)]
  e~l               A list whose length is an element of the previous list
     :1j            Append itself to this list
        @2zc        Split in half, zip and concatenate so that the list contains pairs of
                      consecutive identical elements
            c?      The concatenation of that list must result in the Input
</code>```

Title: Pairable strings

Body:
Brachylog, 14 bytes (no regex)

lye~l:1j@2zcc?

Try it online!

This is too slow for some of the test cases

Explanation

ly                  The list [0, …, length(Input)]
  e~l               A list whose length is an element of the previous list
     :1j            Append itself to this list
        @2zc        Split in half, zip and concatenate so that the list contains pairs of
                      consecutive identical elements
            c?      The concatenation of that list must result in the Input


问:
Run-Length Encoding
Write a program uses run-length encoding to shorten a list of non-negative integers it has to read in.

You can assume the non-negative integers can fit in 32bit signed integers.

Input Format

The length, n, of the list on the first line.

On the second line, a space-separated list of integers representing the list of integers.

Output Format

A space separated list of integers. The first 2 integers represent the first run, the next 2 integers the second run and so on. For each pair of integers representing a run, the first integer represents the length of the run and the second represents the value of the integer in the run.

Sample Input

1.

```<code>5
1 1 3 2 2
</code>```

2.

```<code>3
1 1 1
</code>```

Sample Output

1.

```<code>2 1 1 3 2 2
</code>```

2.

```<code>3 1
</code>```

Limits

```<code>0<n<10000
</code>```

答:
CJam, 11 bytes

```<code>l;l~]e`e_S*
</code>```

CJam interpreter online (test case provided by this comment).

Explanation:

```<code>l;l~]e`e_S*
l           Get input line
 ;          Remove ToS
  l         Get input line
   ~        Evaluate code
    ]       Wrap the stack in an array (from [-mark)
     e`     Run-length encode
       e_   Flatten
         S  Space (' ')
          * Join
</code>```

ContentLicense: CC BY-SA 2.5

Title: Run-Length Encoding

Body:
CJam, 11 bytes

l;l~]e`e_S*

CJam interpreter online (test case provided by this comment).

Explanation:

l;l~]e`e_S*
l           Get input line
 ;          Remove ToS
  l         Get input line
   ~        Evaluate code
    ]       Wrap the stack in an array (from [-mark)
     e`     Run-length encode
       e_   Flatten
         S  Space (' ')
          * Join

ContentLicense: CC BY-SA 4.0


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

-5 bytes thanks to @Dennis (convert directly from base 256 after ordinal cast)

```<code>Oḅ⁹µBCḄµÐĿ
</code>```

TryItOnline!

How?

```<code>Oḅ⁹µBCḄµÐĿ - Main link: s                     e.g. "Inf"
O          - cast to ordinals                 e.g. [73,110,102]
 ḅ⁹        - convert from base 256 to integer e.g. 4812390
   µ   µ   - monadic chain separations
    B      -     convert to binary
     C     -     complement
      Ḅ    -     convert to integer
        ÐĿ - loop until no longer unique and collect results
</code>```

Title: Count down from "Infinity"

Body:
Seems like an impossible task right? Well, it's actually not that hard. If we write the word Infinity as 8-bit binary ASCII code, we'll get:

```<code>01001001 01101110 01100110 01101001 01101110 01101001 01110100 01111001
</code>```

This can be concatenated, and converted to the decimal value 5291279215216915577. Now that's a number we can work with...

The way you'll count down is:

Output the original string as a decimal number (as shown above)

Remove leading 0s in its binary representation (if any)

Toggle the bits in the binary representation (1->0, 0->1)

Output the number in decimal

Repeat steps 2-4 as until you reach 0.

Challenge:

Create a program or function that takes a string as input, and outputs (on any suitable format) the numbers you'll get when performing the procedure above.

Test case:

I think the challenge will be fairly easy to understand, even though it's only one test case. I'll use Inf instead of Infinity to keep this fairly short.

```<code>Inf
4812390  (10010010110111001100110)
3576217  ( 1101101001000110011001)
618086   (   10010110111001100110)
430489   (    1101001000110011001)
93798    (      10110111001100110)
37273    (       1001000110011001)
28262    (        110111001100110)
4505     (          1000110011001)
3686     (           111001100110)
409      (              110011001)
102      (                1100110)
25       (                  11001)
6        (                    110)
1        (                      1)
0        (                      0)
</code>```

```<code>Input: Inf
Output:
4812390, 3576217, 618086, 430489, 93798, 37273, 28262, 4505, 3686, 409, 102, 25, 6, 1, 0
</code>```

```<code>Input: Infinity
Output:
5291279215216915577, 3932092821637860230, 679593196789527673, 473328307817319302, 103132444486104185, 40982743589751686, 31074850448176249, 4953946570787718, 4053252683953273, 450346943417222, 112603010004089, 28134478351238, 7049893737593, 1746199284614, 452823970937, 96931842950, 40507110521, 28212366214, 6147372153, 2442562438, 1852404857, 295078790, 241792121, 26643334, 6911097, 1477510, 619641, 428934, 95353, 35718, 29817, 2950, 1145, 902, 121, 6, 1, 0
</code>```

Your code must support strings that can be represented as a binary number up to the limit of your language. All strings will only contain printable ASCII-characters from 32-126 (space to tilde).

Leaderboard

var QUESTION_ID=98274,OVERRIDE_USER=31516;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:
Jelly, <s>15</s> 10 bytes

-5 bytes thanks to @Dennis (convert directly from base 256 after ordinal cast)

Oḅ⁹µBCḄµÐĿ

TryItOnline!

How?

Oḅ⁹µBCḄµÐĿ - Main link: s                     e.g. "Inf"
O          - cast to ordinals                 e.g. [73,110,102]
 ḅ⁹        - convert from base 256 to integer e.g. 4812390
   µ   µ   - monadic chain separations
    B      -     convert to binary
     C     -     complement
      Ḅ    -     convert to integer
        ÐĿ - loop until no longer unique and collect results


答:
Actually, 14 bytes

```<code>2@├¿W■├♂≈♂Y2@¿
</code>```

Try it online!

Explanation:

```<code>2@├¿W■├♂≈♂Y2@¿
 @├             encode input in binary
2  ¿            convert from binary to decimal
    W           while the number is not 0:
     ■            print the number without popping
      ├           convert number to binary
       ♂≈         convert each character to an int
         ♂Y       boolean negate each int
           2@¿    convert from binary to decimal
</code>```

Title: Count down from "Infinity"

Body:
Actually, 14 bytes

2@├¿W■├♂≈♂Y2@¿

Try it online!

Explanation:

2@├¿W■├♂≈♂Y2@¿
 @├             encode input in binary
2  ¿            convert from binary to decimal
    W           while the number is not 0:
     ■            print the number without popping
      ├           convert number to binary
       ♂≈         convert each character to an int
         ♂Y       boolean negate each int
           2@¿    convert from binary to decimal


答:
05AB1E, 18 bytes

Uses CP-1252 encoding.

```<code>Çžz+b€¦J[CÐ,_#bS_J
</code>```

Try it online!

Explanation

```<code>Ç                     # convert string to list of ascii codes
 žz+                  # add 256 to each
    b                 # convert to binary
     €¦               # remove the first digit of each list of digits
       J              # join
        [             # start loop
         C            # convert to decimal
          Ð           # triplicate
           ,          # print 1 copy
            _#        # if the 2nd copy is 0, break loop
              b       # convert 3rd copy to binary
               S      # split to list
                _     # negate each in list
                 J    # join
</code>```

Title: Count down from "Infinity"

Body:
05AB1E, 18 bytes

Uses CP-1252 encoding.

Çžz+b€¦J[CÐ,_#bS_J

Try it online!

Explanation

Ç                     # convert string to list of ascii codes
 žz+                  # add 256 to each
    b                 # convert to binary
     €¦               # remove the first digit of each list of digits
       J              # join
        [             # start loop
         C            # convert to decimal
          Ð           # triplicate
           ,          # print 1 copy
            _#        # if the 2nd copy is 0, break loop
              b       # convert 3rd copy to binary
               S      # split to list
                _     # negate each in list
                 J    # join


答:
PHP, <s>132</s> <s>126</s> <s>123</s> <s>120</s> <s>108</s> 107 bytes

```<code>foreach(unpack("C*",$argv[1])as$i)$n=$n*256+$i;for(print$n;$n;)echo _.$n=bindec(strtr(decbin($n),"01",10));
</code>```

printing 0 after loop instead of initial value before loop saves 6 bytes.

unpack instead of str_split renders ord() obsolete -> -3 bytes

underscore _ as separator saves 3.

bindec instead of ltrim to remove leading zeroes: -12

echo in loop body saves 1 byte over print in loop head.

Title: Count down from "Infinity"

Body:
PHP, <s>132</s> <s>126</s> <s>123</s> <s>120</s> <s>108</s> 107 bytes

foreach(unpack("C*",$argv[1])as$i)$n=$n*256+$i;for(print$n;$n;)echo _.$n=bindec(strtr(decbin($n),"01",10));

printing 0 after loop instead of initial value before loop saves 6 bytes.

unpack instead of str_split renders ord() obsolete -> -3 bytes

underscore _ as separator saves 3.

bindec instead of ltrim to remove leading zeroes: -12

echo in loop body saves 1 byte over print in loop head.


答:
MATL, 13 bytes

```<code>8W:qZA`tB~XBt
</code>```

Try it online!

Explanation

```<code>8W:q            % Push array [0 1 ... 255]
    ZA          % Take input string and convert it from the base defined by the
                % alphabet [0 1 ... 255] to decimal
      `         % Do...while
       t        % Duplicate
        B       % Convert to binary
         ~      % Negate
          XB    % Convert to decimal
            t   % Duplicate. Used as loop condition: exit if zero
</code>```

Title: Count down from "Infinity"

Body:
MATL, 13 bytes

8W:qZA`tB~XBt

Try it online!

Explanation

8W:q            % Push array [0 1 ... 255]
    ZA          % Take input string and convert it from the base defined by the
                % alphabet [0 1 ... 255] to decimal
      `         % Do...while
       t        % Duplicate
        B       % Convert to binary
         ~      % Negate
          XB    % Convert to decimal
            t   % Duplicate. Used as loop condition: exit if zero


答:
Mathematica, 99 bytes

```<code>a=FromDigits;b=IntegerDigits;NestWhileList[a[1-#~b~2,2]&,a[Join@@b[ToCharacterCode@#,2,8],2],#>0&]&
</code>```

Anonymous function. Takes a string as input, and returns a list of numbers as output.

Title: Count down from "Infinity"

Body:
Mathematica, 99 bytes

a=FromDigits;b=IntegerDigits;NestWhileList[a[1-#~b~2,2]&,a[Join@@b[ToCharacterCode@#,2,8],2],#>0&]&

Anonymous function. Takes a string as input, and returns a list of numbers as output.


答:
Haskell, <s>109</s> <s>123</s> <s>118</s> <s>102</s> 97 bytes

Thanks to @nimi for saving 5 bytes!

```<code>c 0=0
c n=1-mod n 2+2*c(div n 2)
(++[0]).fst.span(>0).iterate c.foldl((+).(256*))0.map fromEnum
</code>```

Usage: (++[0]).fst.span(>0).iterate c.foldl((+).(256*))0.map fromEnum $ "Infinity"

Guaranteed to work on numbers up to 29 bits by the language, usually works up to 63-bit numbers on 64-bit systems. Use map(fromIntegral.fromEnum) instead (+14 bytes) to support arbitrarily large numbers.

Works for unicode range [0..255]. Recursively flips bits.

Title: Count down from "Infinity"

Body:
Haskell, <s>109</s> <s>123</s> <s>118</s> <s>102</s> 97 bytes

Thanks to @nimi for saving 5 bytes!

c 0=0
c n=1-mod n 2+2*c(div n 2)
(++[0]).fst.span(>0).iterate c.foldl((+).(256*))0.map fromEnum

Usage: (++[0]).fst.span(>0).iterate c.foldl((+).(256*))0.map fromEnum $ "Infinity"

Guaranteed to work on numbers up to 29 bits by the language, usually works up to 63-bit numbers on 64-bit systems. Use map(fromIntegral.fromEnum) instead (+14 bytes) to support arbitrarily large numbers.

Works for unicode range [0..255]. Recursively flips bits.


Title: Count down from "Infinity"

Body:
Python 2, <s>117</s> 115 bytes

Saving 2 bytes thanks to Cyoce.

Assumes input enclosed in quotes, e.g. "Inf"

s=input()
n=sum(ord(s[-i-1])<<i*8for i in range(len(s)))
while n:
 print n;k,m=n,1
 while k:k/=2;m*=2
 n^=m-1
print 0

m counts up to the highest digit, so m-1 is a XOR mask to perform the desired operation. The longest part is converting the input into the initial bit sequence.

Example:

"Inf"
4812390
3576217
618086
430489
93798
37273
28262
4505
3686
409
102
25
6
1
0

"Infinity"
5291279215216915577
3932092821637860230
679593196789527673
473328307817319302
103132444486104185
40982743589751686
31074850448176249
4953946570787718
4053252683953273
450346943417222
112603010004089
28134478351238
7049893737593
1746199284614
452823970937
96931842950
40507110521
28212366214
6147372153
2442562438
1852404857
295078790
241792121
26643334
6911097
1477510
619641
428934
95353
35718
29817
2950
1145
902
121
6
1
0


问:
Implement the divisibility-by-7 rule
To check whether a decimal number is divisible by 7:

Erase the last digit. Multiply it by 2 and subtract from what is left. If the result is divisible by 7, the original number is divisible by 7.

(also described e.g. here)

This rule is good for manual divisibility check. For example:

Is 2016 divisible by 7?

Subtract 6*2 from 201; we get 189. Is this divisible by 7? To check it, let's apply the rule again.

Subtract 9*2 from 18; we get 0. Therefore, 2016 is divisible by 7.

In this challenge, you should apply this rule until the divisibility status is obvious, that is, the number is not greater than 70 (however, see below for details). Make a function or a full program.

Input: a positive integer; your code should support inputs up to 32767 (supporting arbitrary-precision integers is a bonus; see below).

Output: an integer (possibly negative), not greater than 70, that is a result of applying the divisibility-by-7 rule zero or more times.

Test cases:

```<code>Input                   Output      Alternative output

1                       1
10                      10          1
100                     10          1
13                      13          -5
42                      42          0
2016                    0
9                       9
99                      -9
9999                    -3
12345                   3
32767                   28          -14

---------- Values below are only relevant for the bonus

700168844221            70          7
36893488147419103232    32          -1
231584178474632390847141970017375815706539969331281128078915168015826259279872    8
</code>```

Where two possible outputs are specified, either result is correct: the second one corresponds to applying the rule one more time. It's forbidden to apply the rule on a single-digit number: if you erase the digit, nothing (not 0) is left.

Bonus: If your algorithm

Supports arbitrary-precision integers

Performs only one pass on the input

Has space complexity o(n) (i.e. less than O(n)); and

Has time complexity O(n),

where n is the number of decimal digits:

Subtract 50% from your code's byte count.

Real bonus:

In addition, if your algorithm reads the input in normal direction, starting from the most significant digit, subtract 50% once again - your score is 25% of your byte count (it seems possible, but I'm not absolutely sure).

答:
PHP, 50 bytes

```<code>for($n=$argv[1];$n>9;)$n=$n/10|0-2*($n%10);echo$n;
</code>```

uses alternative output; works up to PHP_INT_MAX

string version, works for any (positive) number (64 bytes):

```<code>for($n=$argv[1];$n>9;)$n=substr($n,0,-1)-2*substr($n,-1);echo$n;
</code>```

Title: Implement the divisibility-by-7 rule

Body:
PHP, 50 bytes

for($n=$argv[1];$n>9;)$n=$n/10|0-2*($n%10);echo$n;

uses alternative output; works up to PHP_INT_MAX

string version, works for any (positive) number (64 bytes):

for($n=$argv[1];$n>9;)$n=substr($n,0,-1)-2*substr($n,-1);echo$n;