问:
Convert a Forsyth-Edwards Notation string to ASCII art
In chess, Forsyth-Edwards Notation, more commonly called "FEN", is a textual way of transcribing boards. It describes each of the board's eight rows (called "ranks" in chess) from top to bottom from White's perspective. The pieces are written as K (king), Q (queen), R (rook), B (bishop), N (knight), and P (pawn). Black pieces use these letters in lowercase, and white pieces use these letters in uppercase. Empty spaces are indicated by a number from 1 to 8 indicating how many consecutive empty spaces there are. A completely empty rank would be 8, a single black rook in the rightmost column (called "files" in chess) would be 7r, and two white pawns on each end of a row would be PP4PP. Ranks are separated by a /. There is normally other information added, indicating which side is to move, castling and en passant rights, move number, and halfmove clock, but we will ignore them for the purposes of this challenge.

Input

A FEN string, from the command line or STDIN, as you please. You may assume that this string is always valid.

Output

Write to STDOUT a simple ASCII art representation of the board as it would actually appear:

Pieces are represented by their character in FEN

Empty squares are represented by spaces

Pieces and squares are separated by a pipe | and there are pipes on each side of the board

So an empty board, written as 8/8/8/8/8/8/8/8 in FEN, would appear as

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

The starting position of a chess game is written as rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR, and would appear as

```<code>|r|n|b|q|k|b|n|r|
|p|p|p|p|p|p|p|p|
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
| | | | | | | | |
|P|P|P|P|P|P|P|P|
|R|N|B|Q|K|B|N|R|
</code>```

The final position of Anderssen-Kieseritzky 1851, called "The Immortal Game" in the chess community, is written as r1bk3r/p2pBpNp/n4n2/1p1NP2P/6P1/3P4/P1P1K3/q5b1, and your program when fed that input would output:

```<code>|r| |b|k| | | |r|
|p| | |p|B|p|N|p|
|n| | | | |n| | |
| |p| |N|P| | |P|
| | | | | | |P| |
| | | |P| | | | |
|P| |P| |K| | | |
|q| | | | | |b| |
</code>```

答:
><>, 64 bytes

```<code><v?(0:i
r\
"<o-*=@"%/":   v?*(@)@":/"::;?(0:o"|
 ^~?="0":-1o" "<
</code>```

4 wasted bytes due to alignment issues, not sure how to golf them out though. ¯\_(ツ)_/¯

Body:
><>, 64 bytes

<v?(0:i
r\
"<o-*=@"%/":   v?*(@)@":/"::;?(0:o"|
 ^~?="0":-1o" "<

4 wasted bytes due to alignment issues, not sure how to golf them out though. ¯\_(ツ)_/¯


问:
Sᴍᴀʟʟ Cᴀᴘꜱ Cᴏɴᴠᴇʀᴛᴇʀ
Portable Spec.

Iɴꜱᴘɪʀᴇᴅ ʙʏ @ConorO'Brien's ᴜꜱᴇʀɴᴀᴍᴇ.

Aʟꜱᴏ ᴛʜᴀɴᴋꜱ ᴛᴏ @Dᴏᴏʀᴋɴᴏʙ ꜰᴏʀ ꜱʜᴏᴡɪɴɢ ᴍᴇ ᴛʜᴇ ᴇxɪꜱᴛᴇɴᴄᴇ ᴏꜰ ǫ ᴀɴᴅ x.

Sᴍᴀʟʟ Cᴀᴘꜱ ᴀʀᴇ ᴘʀᴇᴛᴛʏ ᴄᴏᴏʟ. Tʜᴇʏ ᴀʀᴇ ᴜɴɪᴄᴏᴅᴇ ᴄʜᴀʀᴀᴄᴛᴇʀꜱ ᴛʜᴀᴛ ʀᴇᴘʟᴀᴄᴇ ꜱᴍᴀʟʟ ʟᴇᴛᴛᴇʀꜱ. Tʜᴇʏ ʟᴏᴏᴋ ᴊᴜꜱᴛ ʟɪᴋᴇ ᴛʜᴇ ᴄᴀᴘɪᴛᴀʟ ᴏɴᴇꜱ, ʙᴜᴛ ꜱᴍᴀʟʟᴇʀ, ᴀɴᴅ ʟᴏᴏᴋ ʀᴇᴀʟʟʏ ᴏꜰꜰɪᴄɪᴀʟ. Yᴏᴜʀ ᴛᴀꜱᴋ ɪꜱ ᴛᴏ ᴡʀɪᴛᴇ ᴀ ᴘʀᴏɢʀᴀᴍ ᴛʜᴀᴛ ᴄᴏɴᴠᴇʀᴛꜱ ʀᴇɢᴜʟᴀʀ ᴛᴇxᴛ ɪɴᴛᴏ ꜱᴍᴀʟʟ ᴄᴀᴘꜱ.

Hᴇʀᴇ ɪꜱ ᴀ ʟɪꜱᴛ ᴏꜰ ᴛʜᴇ ᴜɴɪᴄᴏᴅᴇ ᴄʜᴀʀᴀᴄᴛᴇʀꜱ ꜰᴏʀ ꜱᴍᴀʟʟ ᴄᴀᴘꜱ:

```<code>ᴀ ʙ ᴄ ᴅ ᴇ ꜰ ɢ ʜ ɪ ᴊ ᴋ ʟ ᴍ ɴ ᴏ ᴘ ǫ ʀ ꜱ ᴛ ᴜ ᴠ ᴡ x ʏ ᴢ
</code>```

Cʟᴀʀɪꜰɪᴄᴀᴛɪᴏɴꜱ

Rᴇɢᴜʟᴀʀ ᴄᴀᴘꜱ ʀᴇᴍᴀɪɴ ʀᴇɢᴜʟᴀʀ ᴄᴀᴘꜱ ᴀɴᴅ ꜱᴏ ᴅᴏ ᴘᴜɴᴄᴛᴜᴀᴛɪᴏɴꜱ, ꜱᴘᴀᴄᴇꜱ, ᴇᴛᴄ.

Iɴᴘᴜᴛ ᴄᴀɴ ʙᴇ ᴍᴜʟᴛɪᴘʟᴇ ʟɪɴᴇꜱ.

Tʜɪꜱ ɪꜱ code-golf, ꜱᴏ ꜱʜᴏʀᴛᴇꜱᴛ ᴄᴏᴅᴇ ɪɴ ʙʏᴛᴇꜱ ᴡɪɴꜱ!

Tᴇꜱᴛ Cᴀꜱᴇꜱ

```<code>Hello World -> Hᴇʟʟᴏ Wᴏʀʟᴅ

abcdefghijklmnopqrstuvwxyz -> ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ

Welcome to Programming Puzzles and Code Golf Stackexchange!
It is a website ->
Wᴇʟᴄᴏᴍᴇ ᴛᴏ Pʀᴏɢʀᴀᴍᴍɪɴɢ Pᴜᴢᴢʟᴇꜱ ᴀɴᴅ Cᴏᴅᴇ Gᴏʟꜰ Sᴛᴀᴄᴋᴇxᴄʜᴀɴɢᴇ!
Iᴛ ɪꜱ ᴀ ᴡᴇʙꜱɪᴛᴇ.
</code>```

答:
05AB1E, 73 bytes (non-competing)

Yet again, I wish Adnan had published this language earlier.

```<code>A"ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ"‡
</code>```

Try it online!

Explanation:

```<code>A                              - Push a-z
 "ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ"   - Push "ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ"
                             ‡ - Pop a, b, c Push a.transliterate(b -> c)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Sᴍᴀʟʟ Cᴀᴘꜱ Cᴏɴᴠᴇʀᴛᴇʀ

Body:
05AB1E, 73 bytes (non-competing)

Yet again, I wish Adnan had published this language earlier.

A"ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ"‡

Try it online!

Explanation:

A                              - Push a-z
 "ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ"   - Push "ᴀʙᴄᴅᴇꜰɢʜɪᴊᴋʟᴍɴᴏᴘǫʀꜱᴛᴜᴠᴡxʏᴢ"
                             ‡ - Pop a, b, c Push a.transliterate(b -> c)


问:
How many steps does it take from n to 1 by subtracting the greatest divisor?
Inspired by this question over at Mathematics.

The Problem

Let n be a natural number ≥ 2. Take the biggest divisor of n – which is different from n itself – and subtract it from n. Repeat until you get 1.

The Question

How many steps does it take to reach 1 for a given number n ≥ 2.

Detailed Example

Let n = 30.

The greatest divisor of:

```<code>1.   30 is 15  -->  30 - 15 = 15
2.   15 is  5  -->  15 -  5 = 10
3.   10 is  5  -->  10 -  5 =  5
4.    5 is  1  -->   5 -  1 =  4
5.    4 is  2  -->   4 -  2 =  2
6.    2 is  1  -->   2 -  1 =  1
</code>```

It takes 6 steps to reach 1.

Input

Input is an integer n, where n ≥ 2.

Your program should support input up to the language's maximum integer value.

Output

Simply output the number of steps, like 6.

Leading/trailing whitespaces or newlines are fine.

Examples

```<code>f(5)        --> 3
f(30)       --> 6
f(31)       --> 7
f(32)       --> 5
f(100)      --> 8
f(200)      --> 9
f(2016^155) --> 2015
</code>```

Requirements

You can get input from STDIN, command line arguments, as function parameters or from the closest equivalent.

You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it.

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

Standard loopholes are disallowed.

This series can be found on OEIS as well: A064097

A quasi-logarithm defined inductively by a(1) = 0 and a(p) = 1 + a(p-1) if p is prime and a(n*m) = a(n) + a(m) if m,n > 1.

答:
C99, <s>62</s> 61 bytes

1 byte golfed off by @Alchymist.

```<code>f(a,c,b)long*c,a,b;{for(*c=0,b=a;a^1;a%--b||(++*c,b=a-=b));}
</code>```

Call as f(x,&y), where x is the input and y is the output.

Body:
C99, <s>62</s> 61 bytes

1 byte golfed off by @Alchymist.

f(a,c,b)long*c,a,b;{for(*c=0,b=a;a^1;a%--b||(++*c,b=a-=b));}

Call as f(x,&y), where x is the input and y is the output.


Title: How many steps does it take from n to 1 by subtracting the greatest divisor?

Body:
Inspired by this question over at Mathematics.

The Problem

Let n be a natural number ≥ 2. Take the biggest divisor of n – which is different from n itself – and subtract it from n. Repeat until you get 1.

The Question

How many steps does it take to reach 1 for a given number n ≥ 2.

Detailed Example

Let n = 30.

The greatest divisor of:

```<code>1.   30 is 15  -->  30 - 15 = 15
2.   15 is  5  -->  15 -  5 = 10
3.   10 is  5  -->  10 -  5 =  5
4.    5 is  1  -->   5 -  1 =  4
5.    4 is  2  -->   4 -  2 =  2
6.    2 is  1  -->   2 -  1 =  1
</code>```

It takes 6 steps to reach 1.

Input

Input is an integer n, where n ≥ 2.

Your program should support input up to the language's maximum integer value.

Output

Simply output the number of steps, like 6.

Leading/trailing whitespaces or newlines are fine.

Examples

```<code>f(5)        --> 3
f(30)       --> 6
f(31)       --> 7
f(32)       --> 5
f(100)      --> 8
f(200)      --> 9
f(2016^155) --> 2015
</code>```

Requirements

You can get input from STDIN, command line arguments, as function parameters or from the closest equivalent.

You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it.

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

Standard loopholes are disallowed.

This series can be found on OEIS as well: A064097

A quasi-logarithm defined inductively by a(1) = 0 and a(p) = 1 + a(p-1) if p is prime and a(n*m) = a(n) + a(m) if m,n > 1.

Body:
Haskell, 67 bytes

Here's the code:

a&b|b<2=0|a==b=1+2&(b-1)|mod b a<1=1+2&(b-div b a)|1<2=(a+1)&b
(2&)

And here's one reason why Haskell is awesome:

f = (2&)

(-->) :: Eq a => a -> a -> Bool
(-->) = (==)

h=[f(5)        --> 3
  ,f(30)       --> 6
  ,f(31)       --> 7
  ,f(32)       --> 5
  ,f(100)      --> 8
  ,f(200)      --> 9
  ,f(2016^155) --> 2015
  ]

Yes, in Haskell you can define --> to be equivalent to ==.


答:
Matlab, 107 bytes

```<code>a=input('');b=factor(a-isprime(a));c=log2(a);while(max(b)>1),b=max(factor(max(b)-1));c=c+1;end,disp(fix(c))
</code>```

Non-competing, this is not the iterative translation of my last submission, just another direct algerbraic method, it sums up all binary-logs of all prime factors, kinda ambiguous to illustrate.

I will golf this more when i have time.

Body:
Matlab, 107 bytes

a=input('');b=factor(a-isprime(a));c=log2(a);while(max(b)>1),b=max(factor(max(b)-1));c=c+1;end,disp(fix(c))

Non-competing, this is not the iterative translation of my last submission, just another direct algerbraic method, it sums up all binary-logs of all prime factors, kinda ambiguous to illustrate.

I will golf this more when i have time.


答:
Retina, 12

14 bytes saved thanks to @MartinBüttner

```
(1+)(?=\1+$)
```

This assumes input given in unary and output given in decimal.  If this is not acceptable then we can do this for 6 bytes more:

Retina, 18

8 bytes saved thanks to @MartinBüttner

```
.+
$*
(1+)(?=\1+$)
```

Try it online - 1st line added to run all testcases in one go.

Sadly this uses unary for the calculations, so input of 2016155 is not practical.

The first stage (2 lines) simply converts the decimal input to unary as a string of 1s

The second stage (1 line) calculates the largest factor of n using regex matching groups and lookbehinds to and effectively subtracts it from n.  This regex will match as many times as is necessary to reduce the number as far as possible.  The number of regex matches will be the number of steps, and is output by this stage.

Body:
Retina, 12

14 bytes saved thanks to @MartinBüttner

(1+)(?=\1+$)

This assumes input given in unary and output given in decimal.  If this is not acceptable then we can do this for 6 bytes more:

Retina, 18

8 bytes saved thanks to @MartinBüttner

.+
$*
(1+)(?=\1+$)

Try it online - 1st line added to run all testcases in one go.

Sadly this uses unary for the calculations, so input of 2016155 is not practical.

The first stage (2 lines) simply converts the decimal input to unary as a string of 1s

The second stage (1 line) calculates the largest factor of n using regex matching groups and lookbehinds to and effectively subtracts it from n.  This regex will match as many times as is necessary to reduce the number as far as possible.  The number of regex matches will be the number of steps, and is output by this stage.


问:
What is the most frequent word?

What is the most frequent word?

Given a sentence, your program must make its way through it, counting the frequencies of each word, then output the most used word. Because a sentence has no fixed length, and so can get very long, your code must be as short as possible.

Rules/Requirements

Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.

There must be a free interpreter/compiler available for your language.

If it is possible, provide a link to a site where your program can be tested.

Your program must not write anything to STDERR.

Your program should take input from STDIN (or the closest alternative in your language).

Standard loopholes are forbidden.

Your program must be case-insensitive (tHe, The and the all contribute to the count of the).

If there is no most frequent word (see test case #3), your program should output nothing.

Definition of a 'word':

You get the list of words by splitting the input text on spaces. The input will never contain any other type of whitespace than plain spaces (in particular no newlines). However, the final words should only contain alphanumerics (a-z, A-Z, 0-9), hyphens (-) and apostrophes ('). You can make that so by removing all other characters or by replacing them by space before doing the word splitting. To remain compatible with previous versions of the rules, apostrophes are not required to be included.

Test Cases

```<code>The man walked down the road.
==> the

-----

Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.
==> he

-----

This sentence has no most frequent word.
==>

-----

"That's... that's... that is just terrible!" he said.
==> that's / thats

-----

The old-fashioned man ate an old-fashioned cake.
==> old-fashioned

-----

IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.
==> IPv6

-----

This sentence with words has at most two equal most frequent words.
==>
</code>```

Note: The third and seventh test cases have no output, you may choose either on the fourth.

Scoring

Programs are scored according to bytes. The usual character set is UTF-8, if you are using another please specify.

When the challenge finishes, the program with the least bytes (it's called code-golf), will win.

Submissions

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

Leaderboard

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

/* Configuration */

var QUESTION_ID = 79576; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

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

```

答:
Lua, <s>232</s> <s>199</s> 175 bytes

```<code>w,m,o={},0;io.read():lower():gsub("[^-%w%s]",""):gsub("[%w-]+",function(x)w[x]=(w[x]or 0)+1 end)for k,v in pairs(w)do if m==v then o=''end if(v>m)then m,o=v,k end end print(o)
</code>```

Title: What is the most frequent word?

Body:
Lua, <s>232</s> <s>199</s> 175 bytes

w,m,o={},0;io.read():lower():gsub("[^-%w%s]",""):gsub("[%w-]+",function(x)w[x]=(w[x]or 0)+1 end)for k,v in pairs(w)do if m==v then o=''end if(v>m)then m,o=v,k end end print(o)


答:
Ruby, 43 bytes

```<code>f=->x{x<2?0:1+f[(1..x).find{|i|x%(x-i)<1}]}
</code>```

Find the smallest number i such that x divides x-i and recurse until we reach 1.

Body:
Ruby, 43 bytes

f=->x{x<2?0:1+f[(1..x).find{|i|x%(x-i)<1}]}

Find the smallest number i such that x divides x-i and recurse until we reach 1.


答:
Octave, <s>59</s> <s>58</s> 55 bytes

```<code>function r=f(x)r=0;while(x-=x/factor(x)(1));r++;end;end
</code>```

Updated thanks to Stewie Griffin, saving 1 byte

Further update, saving three more bytes by using result of factorization in while-check.

Sample runs:

```<code>octave:41> f(5)
ans =  3
octave:42> f(30)
ans =  6
octave:43> f(31)
ans =  7
octave:44> f(32)
ans =  5
octave:45> f(100)
ans =  8
octave:46> f(200)
ans =  9
</code>```

Body:
Octave, <s>59</s> <s>58</s> 55 bytes

function r=f(x)r=0;while(x-=x/factor(x)(1));r++;end;end

Updated thanks to Stewie Griffin, saving 1 byte

Further update, saving three more bytes by using result of factorization in while-check.

Sample runs:

octave:41> f(5)
ans =  3
octave:42> f(30)
ans =  6
octave:43> f(31)
ans =  7
octave:44> f(32)
ans =  5
octave:45> f(100)
ans =  8
octave:46> f(200)
ans =  9


答:
Julia, <s>56</s> <s>50</s> <s>45</s> 39 bytes

f(n)=n>1&&f(n-n÷first(factor(n))[1])+1
```

<p>This is a recursive function that accepts an integer and returns an integer.</p>

<p>Ungolfed:</p>

<pre class="lang-default prettyprint-override"><code>function f(n)
    if n < 2
        # No decrementing necessary
        return 0
    else
        # As Dennis showed in his Jelly answer, we don't need to
        # divide by the smallest prime factor; any prime factor
        # will do. Since `factor` returns a `Dict` which isn't
        # sorted, `first` doesn't always get the smallest, and
        # that's okay.
        return f(n - n ÷ first(factor(n))[1]) + 1
    end
end
</code>```

Try it online! (includes all test cases)

Saved 6 bytes thanks to Martin Büttner and 11 thanks to Dennis!

Body:
Julia, <s>56</s> <s>50</s> <s>45</s> 39 bytes

f(n)=n>1&&f(n-n÷first(factor(n))[1])+1

This is a recursive function that accepts an integer and returns an integer.

Ungolfed:

function f(n)
    if n < 2
        # No decrementing necessary
        return 0
    else
        # As Dennis showed in his Jelly answer, we don't need to
        # divide by the smallest prime factor; any prime factor
        # will do. Since `factor` returns a `Dict` which isn't
        # sorted, `first` doesn't always get the smallest, and
        # that's okay.
        return f(n - n ÷ first(factor(n))[1]) + 1
    end
end

Try it online! (includes all test cases)

Saved 6 bytes thanks to Martin Büttner and 11 thanks to Dennis!


问:
Write a brain-flak classic interpreter!
Brain-Flak (a cross between Brainf**k and Flak-Overstow) is a stack-based esoteric language. Since this challenge was posted, the language has evolved and updated, but this first revision of the language is known as "brain-flak classic".

You must write a program or function that takes a string of Brain-Flak classic code, and evaluates it. It will also take a (possible empty) list of integers. There are the inputs to the Brain-Flak classic program.

The Language

Brain-Flak has two stacks, known as 'left' and 'right'. The active stack starts at left. If an empty stack is popped or peeked, it will return 0. There are no variables. When the program starts, each input is pushed on to the active stack in order (so that the last input is on top of the stack).

The only valid characters in a Brain-Flak program are ()[]{}<>, and they must always be balanced. If there are invalid characters, or the brackets are unmatched, you get undefined behaviour. Anything is valid.

There are two types of functions: Nilads and Monads. A nilad is a function that takes 0 arguments. Here are all of the nilads:

() +1.

[] -1.

{} Pop the active stack.

<> Toggle the active stack.

These are concatenated together when they are evaluated. So if we had a '3' on top of the active stack, this snippet:

```<code>()(){}
</code>```

would evaluate to 1 + 1 + active.pop() which would evaluate to 5. <> evaluates to 0.

The monads take one argument, a chunk of Brain-Flak code. Here are all of the monads:

(n) Push 'n' on the active stack.

[n] Print 'n' as an int and a newline.

{foo} While active.peek() != 0, do foo. Evaluates to 0¹.

<foo> Execute foo, but evaluate it as 0.

These functions will also return the value inside of them, so

```<code>(()()())
</code>```

Will push 3 and

```<code>[()()()]
</code>```

Will print 3 but

```<code>[(()()())]
</code>```

Will print and push 3.

When the program is done executing, each value left on the active stack is printed as an integer, with a newline between. Values on the other stack are ignored.

Rules:

Your program must support numbers in the (-128, 127) range, and a stack size of at least 255. If you support larger, great.

Underflow/overflow is undefined.

Sample IO:

The empty program:

Input: None

Output: None

Addition. Source:

```<code>({}{})
</code>```

Input:

```<code>2, 3
</code>```

Output:

```<code>5
</code>```

Subtraction. Source:

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

Input:

```<code>2, 3
</code>```

Output:

```<code>-1
</code>```

Multiplication. Source:

```<code>(()()())
</code>```0

Input:

```<code>(()()())
</code>```1

Output:

```<code>(()()())
</code>```2

Fibonacci. Source:

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

Input:

```<code>5
</code>```

Output:

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

Truth machine

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

Standard loopholes apply, and the shortest answer in bytes wins.

¹: This was actually a mistake on my part. {...} should evaluate to the sum of all of it's runs, which is IMO one of the coolest features of brain-flak. However, for the purposes of this challenge, assume that {...} evaluates as 0.

答:
Perl 5.6, <s>419</s> 414 bytes

I've golfed it a bit but there's probably scope for improvement. Newlines and tabs added here for the sake of a bit of readability:

```<code>use Text::Balanced extract_bracketed;
$s=shift;
@a=reverse@ARGV;
sub p
{
    my($c)=@_;
    my$s=0;
    while(my$n=extract_bracketed($c)){
        $s+='()'eq$n||'{}'eq$n&&shift@a;
        $s-='[]'eq$n;
        @t=@a,@a=@i,@i=@t if'<>'eq$n;
        my$m=chop($n);
        $n=substr($n,1);
        if($n){
            p($n)while'}'eq$m&&$a[0];
            p($n)if'}'ne$m;
            $s+=$v,unshift@a,$v if')'eq$m;
            $s+=$v,print"n=$n m=$m v=$v\n"if']'eq$m;
        }
    }
    $v=$s;
}
p($s);
foreach(@a){
    print"$_\n";
}
</code>```

Title: Write a brain-flak classic interpreter!

Body:
Perl 5.6, <s>419</s> 414 bytes

I've golfed it a bit but there's probably scope for improvement. Newlines and tabs added here for the sake of a bit of readability:

use Text::Balanced extract_bracketed;
$s=shift;
@a=reverse@ARGV;
sub p
{
    my($c)=@_;
    my$s=0;
    while(my$n=extract_bracketed($c)){
        $s+='()'eq$n||'{}'eq$n&&shift@a;
        $s-='[]'eq$n;
        @t=@a,@a=@i,@i=@t if'<>'eq$n;
        my$m=chop($n);
        $n=substr($n,1);
        if($n){
            p($n)while'}'eq$m&&$a[0];
            p($n)if'}'ne$m;
            $s+=$v,unshift@a,$v if')'eq$m;
            $s+=$v,print"n=$n m=$m v=$v\n"if']'eq$m;
        }
    }
    $v=$s;
}
p($s);
foreach(@a){
    print"$_\n";
}


答:
JavaScript (ES6), <s>70</s> 54 bytes

```<code>f=(n,i=2)=>n<i?0:n%i?f(n,i+1):n>i?f(i)+f(n/i):1+f(n-1)
</code>```

Implementation of the provided recursive formula, but now updated to use recursion to find the divisor too.

Body:
JavaScript (ES6), <s>70</s> 54 bytes

f=(n,i=2)=>n<i?0:n%i?f(n,i+1):n>i?f(i)+f(n/i):1+f(n-1)

Implementation of the provided recursive formula, but now updated to use recursion to find the divisor too.


Title: Write a brain-flak classic interpreter!

Body:
Brain-Flak (a cross between Brainf**k and Flak-Overstow) is a stack-based esoteric language. Since this challenge was posted, the language has evolved and updated, but this first revision of the language is known as "brain-flak classic".

You must write a program or function that takes a string of Brain-Flak classic code, and evaluates it. It will also take a (possible empty) list of integers. There are the inputs to the Brain-Flak classic program.

The Language

Brain-Flak has two stacks, known as 'left' and 'right'. The active stack starts at left. If an empty stack is popped or peeked, it will return 0. There are no variables. When the program starts, each input is pushed on to the active stack in order (so that the last input is on top of the stack).

The only valid characters in a Brain-Flak program are ()[]{}<>, and they must always be balanced. If there are invalid characters, or the brackets are unmatched, you get undefined behaviour. Anything is valid.

There are two types of functions: Nilads and Monads. A nilad is a function that takes 0 arguments. Here are all of the nilads:

() +1.

[] -1.

{} Pop the active stack.

<> Toggle the active stack.

These are concatenated together when they are evaluated. So if we had a '3' on top of the active stack, this snippet:

```<code>()(){}
</code>```

would evaluate to 1 + 1 + active.pop() which would evaluate to 5. <> evaluates to 0.

The monads take one argument, a chunk of Brain-Flak code. Here are all of the monads:

(n) Push 'n' on the active stack.

[n] Print 'n' as an int and a newline.

{foo} While active.peek() != 0, do foo. Evaluates to 0¹.

<foo> Execute foo, but evaluate it as 0.

These functions will also return the value inside of them, so

```<code>(()()())
</code>```

Will push 3 and

```<code>[()()()]
</code>```

Will print 3 but

```<code>[(()()())]
</code>```

Will print and push 3.

When the program is done executing, each value left on the active stack is printed as an integer, with a newline between. Values on the other stack are ignored.

Rules:

Your program must support numbers in the (-128, 127) range, and a stack size of at least 255. If you support larger, great.

Underflow/overflow is undefined.

Sample IO:

The empty program:

Input: None

Output: None

Addition. Source:

```<code>({}{})
</code>```

Input:

```<code>2, 3
</code>```

Output:

```<code>5
</code>```

Subtraction. Source:

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

Input:

```<code>2, 3
</code>```

Output:

```<code>-1
</code>```

Multiplication. Source:

```<code>(()()())
</code>```0

Input:

```<code>(()()())
</code>```1

Output:

```<code>(()()())
</code>```2

Fibonacci. Source:

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

Input:

```<code>5
</code>```

Output:

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

Truth machine

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

Standard loopholes apply, and the shortest answer in bytes wins.

¹: This was actually a mistake on my part. {...} should evaluate to the sum of all of it's runs, which is IMO one of the coolest features of brain-flak. However, for the purposes of this challenge, assume that {...} evaluates as 0.

Body:
APL, <s>255</s> 257 bytes

b←{S←(⌽⍺)⍬
e←{0=⍴⍵:0
v+∇⊃_ v←∇{r←⊂2↓⍵
'()'≡n←2↑⍵:r,1
'[]'≡n:r,¯1
'{}'≡n:r,{i←⊃⊃⊃S⋄S[1]↓⍨←1⋄i}⍬
'<>'≡n:r,0⊣S⌽⍨←1
r←⊂⍵↓⍨i←0⍳⍨(+\c=⍵)-+\')]>}'['([<{'⍳c←⊃⍵]=⍵
i←1↓¯1↓c←i↑⍵
'('=c←⊃c:r,S[1],⍨←⍺⍺i
'['=c:r,+⎕←⍺⍺i
'{'=c:r,{0≠⊃⊃⊃S:∇e i⋄0}⍬
'<'=c:r,0⊣⍺⍺i}⍵}
⎕←⍪⊃S⊣e⍵}

This takes the program as its right argument, and the program input as its left argument, i.e:

      2 3 b '({}{})'
5
      2 3 b '({}<>){({}[])<>({}[])<>}<>'
¯1
      7 8 b '({}<>)<>({}[]){({}[])<>(({}))<>}<>{({}<>{})<>}<>'
56
      5 b '<>((()))<>{({}[])<>({}<>)<>(({})<>({}<>))<>}<>'
13
 8
 5
 3
 2
 1
 1

Ungolfed version: here.


答:
Rexx, <s>109</s> <s>128</s> 122 bytes

```<code>pull s;g.=0;m=0;do i=1 to words(s);w=word(s,i);g.w=g.w+1;if g.w>=m then do;m=g.w;g.m=g.m+1;r=w;end;end;if g.m=1 then say r
</code>```

Pretty printed...

```<code>pull s
g.=0
m=0
do i=1 to words(s)
  w=word(s,i)
  g.w=g.w+1
  if g.w>=m
  then do
    m=g.w
    g.m=g.m+1
    r=w
  end
end
if g.m=1 then say r
</code>```

Title: What is the most frequent word?

Body:
What is the most frequent word?

Given a sentence, your program must make its way through it, counting the frequencies of each word, then output the most used word. Because a sentence has no fixed length, and so can get very long, your code must be as short as possible.

Rules/Requirements

Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.

There must be a free interpreter/compiler available for your language.

If it is possible, provide a link to a site where your program can be tested.

Your program must not write anything to STDERR.

Your program should take input from STDIN (or the closest alternative in your language).

Standard loopholes are forbidden.

Your program must be case-insensitive (tHe, The and the all contribute to the count of the).

If there is no most frequent word (see test case #3), your program should output nothing.

Definition of a 'word':

You get the list of words by splitting the input text on spaces. The input will never contain any other type of whitespace than plain spaces (in particular no newlines). However, the final words should only contain alphanumerics (a-z, A-Z, 0-9), hyphens (-) and apostrophes ('). You can make that so by removing all other characters or by replacing them by space before doing the word splitting. To remain compatible with previous versions of the rules, apostrophes are not required to be included.

Test Cases

```<code>The man walked down the road.
==> the

-----

Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.
==> he

-----

This sentence has no most frequent word.
==>

-----

"That's... that's... that is just terrible!" he said.
==> that's / thats

-----

The old-fashioned man ate an old-fashioned cake.
==> old-fashioned

-----

IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.
==> IPv6

-----

This sentence with words has at most two equal most frequent words.
==>
</code>```

Note: The third and seventh test cases have no output, you may choose either on the fourth.

Scoring

Programs are scored according to bytes. The usual character set is UTF-8, if you are using another please specify.

When the challenge finishes, the program with the least bytes (it's called code-golf), will win.

Submissions

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

Leaderboard

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

/* Configuration */

var QUESTION_ID = 79576; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

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:
Rexx, <s>109</s> <s>128</s> 122 bytes

pull s;g.=0;m=0;do i=1 to words(s);w=word(s,i);g.w=g.w+1;if g.w>=m then do;m=g.w;g.m=g.m+1;r=w;end;end;if g.m=1 then say r

Pretty printed...

pull s
g.=0
m=0
do i=1 to words(s)
  w=word(s,i)
  g.w=g.w+1
  if g.w>=m
  then do
    m=g.w
    g.m=g.m+1
    r=w
  end
end
if g.m=1 then say r


问:
Rotation-safe Latin squares
A Latin square is a square that has no repeated symbols in either the X or Y columns.  For example:

```<code>ABCD
DABC
CDAB
BCDA
</code>```

is one such square.  Notice how every column and row contains a permutation of the same 4 letters.

However, our Latin square has a problem:  If I were to rotate the second row (DABC) 1 to the left, I'd end up with ABCD, which is identical to the permutation above it.  If it is impossible to rotate any 1 column/row and obtain another column/row, then we consider the square to be rotation safe.

For example:

```<code>ABCD
BDAC
CADB
DCBA
</code>```

is rotation safe.  The grid has the following properties:

Point [0,N] uses the Nth symbol

Point [0,N] and [N,0] are always the same symbol.  (I'd like to also say that [x,y] and [y,x] are also always the same letter, but I can't prove it)

Your task is to print out 1 rotation-safe Latin square, when passed N.  I don't care if you output letters, numbers, a list, or a 2D array.  If you use numbers, the top column and row must be 0,1,2,3,... (in that order).  If you use letters, then it must be A,B,C,D,....

For example, if your input was 4, you should either print:

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

There are no rotation-safe Latin squares of size less than 4.  I don't care what your program does if N is less than 4.  For the curious, the number of rotation-safe squares is (starting at 4):  2,5,5906,(too long to calculate)

This is a code-golf, so try to make answers as short as possible in your favorite language!

答:
Pyth - 29 bytes

Brute force.

```<code>hf&!@JsCBTsm.>RdJStQ.A{IMJ^.p
</code>```

Does not finish online even for n=4, but you can try it out locally, or run this modified version online for one more byte.

Title: Rotation-safe Latin squares

Body:
Pyth - 29 bytes

Brute force.

hf&!@JsCBTsm.>RdJStQ.A{IMJ^.p

Does not finish online even for n=4, but you can try it out locally, or run this modified version online for one more byte.


问:
Is the electric garage door open?
My electric garage door works like this:

There is just one push button to control the door

If the door is fully closed and I hit the button, the door starts to open.  It takes 10 seconds to open fully

If the door is fully open and I hit the button, the door starts to close.  It takes 10 seconds to close fully

If the door is part way through opening or closing and I hit the button, then the door stops and is left partially open.

Whenever the door stops moving, either from automatic completion of an open or close action, or from manual interruption by pushing the button partway through an action, then the mechanism will reverse and remember its direction for the next action.

If the button is pushed when the door is stopped but partially open, then the amount of time for it to complete its action will be a fraction of 10 seconds in proportion to the amount it needs to move to complete the action.

Assume the door is fully closed at the start.

An input list of integers will be given.  These integers are the number of seconds I wait between successive pushes of the control button.

Output two things:

a percentage indicating the state of the door once all button pushes are completed and the door has reached a steady state.  Output of % symbol is optional.

an unambiguous indication of what direction the door will travel on the next button push.  This may be up/down, U/D, +/-, 1/0 or whatever you choose.

You may assume the door takes infinitesimally less than 10 seconds to complete an open or close action.

Example inputs:

```<code><empty list>  # button was pushed just once
20            # button was pushed twice with 20 seconds between
10
5
20 20
10 10
5 5
1 2 3
8 9 10 11
11 10 9 8 7
</code>```

Expected outputs corresponding to above inputs

```<code>100% D
0% U
0% U
50% D
100% D
100% D
0% U
100% D
0% U
20% U
</code>```

Worked example of the last test

Door starts off closed.  Button is pushed

Wait 11 seconds.  Door ends up fully opened.  Button is pushed.

Wait 10 seconds.  Door ends up fully closed.  Button is pushed.

Wait 9 seconds.  Button is pushed.  Door stops at 90% open.

Wait 8 seconds.  Button is pushed.  Door starts to close.

Wait 7 seconds.  Button is pushed.  Door stops at 20% open.  Next direction will be up.

答:
Lua, <s>258</s> <s>248</s> 242 bytes

```<code>u,s,p=1>0,0>1,0;io.read():gsub("%d+",function(a)if(not s)then p=u and p+a or p-a;if(p>=10 or p<=0)then s,p=1>0,p>0 and 10 or 0;end;u,s=not u,not s else s=0>1;end end)if(not s)then p=u and 10 or 0;u=not u;end;print(10*p.."% "..(u and"U"or"D"))
</code>```

Ungolfed

```<code>u,s,p=true,false,0;                          -- Up direction, Stopped, Position
io.read():gsub("%d+",function(t)             -- For each number in input
    if(not s)then                            -- If door wasn't stopped
        p=u and p+t or p-t;                  -- Position = Moving up ? +t : -t
        if(p>=10 or p<=0)then                -- If door fully opened or closed
            s,p=true,p>0 and 10 or 0;        -- Then door stopped at 0 or 10
        end
        u,s=not u,not s;                     -- Toggle direction and toggle stopped
    else
        s=false;                             -- If stopped, nothing happened, un-stop.
    end
end)
-------------------- Done pressing the button --------------------
if(not s)then                                -- If left off moving
    p=u and 10 or 0;                         -- Finish movement
    u=not u;                                 -- Toggle direction
end
print(10*p.."% "..(u and"U"or"D"))           -- Output answer
</code>```

<s>I don't see how your test cases can be right...

```<code>20 20 -- Initial push, after 20, garage is at 100, push to start it down, after 20, garage is at 0, push to start it up, garage finishes up.
10 10 -- Same as above
1 2 3 -- 0 U Moving, wait 1, 1 D Stopped, wait 2, 0 U stopped, wait 3, 100 D stopped
</code>```

</s> OP Fixed

Title: Is the electric garage door open?

Body:
Lua, <s>258</s> <s>248</s> 242 bytes

u,s,p=1>0,0>1,0;io.read():gsub("%d+",function(a)if(not s)then p=u and p+a or p-a;if(p>=10 or p<=0)then s,p=1>0,p>0 and 10 or 0;end;u,s=not u,not s else s=0>1;end end)if(not s)then p=u and 10 or 0;u=not u;end;print(10*p.."% "..(u and"U"or"D"))

Ungolfed

u,s,p=true,false,0;                          -- Up direction, Stopped, Position
io.read():gsub("%d+",function(t)             -- For each number in input
    if(not s)then                            -- If door wasn't stopped
        p=u and p+t or p-t;                  -- Position = Moving up ? +t : -t
        if(p>=10 or p<=0)then                -- If door fully opened or closed
            s,p=true,p>0 and 10 or 0;        -- Then door stopped at 0 or 10
        end
        u,s=not u,not s;                     -- Toggle direction and toggle stopped
    else
        s=false;                             -- If stopped, nothing happened, un-stop.
    end
end)
-------------------- Done pressing the button --------------------
if(not s)then                                -- If left off moving
    p=u and 10 or 0;                         -- Finish movement
    u=not u;                                 -- Toggle direction
end
print(10*p.."% "..(u and"U"or"D"))           -- Output answer

<s>I don't see how your test cases can be right...

20 20 -- Initial push, after 20, garage is at 100, push to start it down, after 20, garage is at 0, push to start it up, garage finishes up.
10 10 -- Same as above
1 2 3 -- 0 U Moving, wait 1, 1 D Stopped, wait 2, 0 U stopped, wait 3, 100 D stopped

</s> OP Fixed


Title: Is the electric garage door open?

Body:
My electric garage door works like this:

There is just one push button to control the door

If the door is fully closed and I hit the button, the door starts to open.  It takes 10 seconds to open fully

If the door is fully open and I hit the button, the door starts to close.  It takes 10 seconds to close fully

If the door is part way through opening or closing and I hit the button, then the door stops and is left partially open.

Whenever the door stops moving, either from automatic completion of an open or close action, or from manual interruption by pushing the button partway through an action, then the mechanism will reverse and remember its direction for the next action.

If the button is pushed when the door is stopped but partially open, then the amount of time for it to complete its action will be a fraction of 10 seconds in proportion to the amount it needs to move to complete the action.

Assume the door is fully closed at the start.

An input list of integers will be given.  These integers are the number of seconds I wait between successive pushes of the control button.

Output two things:

a percentage indicating the state of the door once all button pushes are completed and the door has reached a steady state.  Output of % symbol is optional.

an unambiguous indication of what direction the door will travel on the next button push.  This may be up/down, U/D, +/-, 1/0 or whatever you choose.

You may assume the door takes infinitesimally less than 10 seconds to complete an open or close action.

Example inputs:

```<code><empty list>  # button was pushed just once
20            # button was pushed twice with 20 seconds between
10
5
20 20
10 10
5 5
1 2 3
8 9 10 11
11 10 9 8 7
</code>```

Expected outputs corresponding to above inputs

```<code>100% D
0% U
0% U
50% D
100% D
100% D
0% U
100% D
0% U
20% U
</code>```

Worked example of the last test

Door starts off closed.  Button is pushed

Wait 11 seconds.  Door ends up fully opened.  Button is pushed.

Wait 10 seconds.  Door ends up fully closed.  Button is pushed.

Wait 9 seconds.  Button is pushed.  Door stops at 90% open.

Wait 8 seconds.  Button is pushed.  Door starts to close.

Wait 7 seconds.  Button is pushed.  Door stops at 20% open.  Next direction will be up.

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

a=>a.map(e=>(s^=1)?(r-=e*(d=-d))>9?(s=0,r=10):r<1?(r=s=0):r:r,r=s=0,d=1)&&(s?r:5*++d)*10+(d-s?"% D":"% U")


答:
Python, 616 bytes

Instructions:

Run with python

Input list in [1,2,...] format, then press enter

Paste/write program, then press enter again

Done

Basically, what this program does is recursively "compile" the Brain-flak code into nested lists, and recursively interpret that list. There probably is a way to combine the two...

I'll try and rework the logic later.

```<code>y="([{<)]}>"
w,z,g=print,len,input
def c(s):
 if z(s)<1:return[]
 t,i,o=[],1,0
 t.append(y.index(s[0]))
 while z(t)>0:
  x=y.index(s[i])
  if x<4:t.append(x)
  else:o=t.pop()
  i+=1
 r=[[o,c(s[1:i-1])]]
 r.extend(c(s[i:]))
 return r
p=lambda t:t.pop()if z(t)>0 else 0
k=lambda t:t[z(t)-1]if z(t)>0 else 0
r,l=[],eval(g())
a=l
def i(u):
 v=0
 global a
 for t,n in u:
  if t<1:
   if n:o=i(n);v+=o;a.append(o)
   else:v+=1
  if t==1:
   if n:o=i(n);v+=o;w(o)
   else:v-=1
  if t==2:
   if n:
    while k(a)!=0:i(n)
   else:v+=p(a)
  if t>2:
   if n:i(n)
   elif a==l:a=r
   else:a=l
 return v
i(c(g()))
for n in a:w(n)
</code>```

Title: Write a brain-flak classic interpreter!

Body:
Python, 616 bytes

Instructions:

Run with python

Input list in [1,2,...] format, then press enter

Paste/write program, then press enter again

Done

Basically, what this program does is recursively "compile" the Brain-flak code into nested lists, and recursively interpret that list. There probably is a way to combine the two...

I'll try and rework the logic later.

y="([{<)]}>"
w,z,g=print,len,input
def c(s):
 if z(s)<1:return[]
 t,i,o=[],1,0
 t.append(y.index(s[0]))
 while z(t)>0:
  x=y.index(s[i])
  if x<4:t.append(x)
  else:o=t.pop()
  i+=1
 r=[[o,c(s[1:i-1])]]
 r.extend(c(s[i:]))
 return r
p=lambda t:t.pop()if z(t)>0 else 0
k=lambda t:t[z(t)-1]if z(t)>0 else 0
r,l=[],eval(g())
a=l
def i(u):
 v=0
 global a
 for t,n in u:
  if t<1:
   if n:o=i(n);v+=o;a.append(o)
   else:v+=1
  if t==1:
   if n:o=i(n);v+=o;w(o)
   else:v-=1
  if t==2:
   if n:
    while k(a)!=0:i(n)
   else:v+=p(a)
  if t>2:
   if n:i(n)
   elif a==l:a=r
   else:a=l
 return v
i(c(g()))
for n in a:w(n)


答:
Pyth, <s>50</s> <s>45</s> 39 bytes

6 bytes thanks to Sp3000.

```<code>J1,*Tu@S[0T+?|!%GTZ+=Z0*H~_J~Z1G)1+QT0J
</code>```

Test suite.

Title: Is the electric garage door open?

Body:
Pyth, <s>50</s> <s>45</s> 39 bytes

6 bytes thanks to Sp3000.

J1,*Tu@S[0T+?|!%GTZ+=Z0*H~_J~Z1G)1+QT0J

Test suite.


答:
Jelly, 10 bytes

```<code>ÆfḊPạµÐĿi2
</code>```

Try it online! or verify most test cases. The last test cases finishes quickly locally.

How it works

```<code>ÆfḊPạµÐĿi2  Main link. Argument: n (integer)

Æf          Factorize n, yielding a list of primes, [] for 1, or [0] for 0.
  Ḋ         Dequeue; remove the first (smallest) element.
   P        Take the product.
            This yields the largest proper divisor if n > 1, 1 if n < 2.
    ạ       Yield the abs. value of the difference of the divisor (or 1) and n.
     µ      Convert the chain to the left into a link.
      ÐĿ    Repeatedly execute the link until the results are no longer unique.
            Collect all intermediate results in a list.
            For each starting value of n, the last results are 2 -> 1 -> 0 (-> 1).
        i2  Compute the 1-based index of 2.
</code>```

Body:
Inspired by this question over at Mathematics.

The Problem

Let n be a natural number ≥ 2. Take the biggest divisor of n – which is different from n itself – and subtract it from n. Repeat until you get 1.

The Question

How many steps does it take to reach 1 for a given number n ≥ 2.

Detailed Example

Let n = 30.

The greatest divisor of:

```<code>1.   30 is 15  -->  30 - 15 = 15
2.   15 is  5  -->  15 -  5 = 10
3.   10 is  5  -->  10 -  5 =  5
4.    5 is  1  -->   5 -  1 =  4
5.    4 is  2  -->   4 -  2 =  2
6.    2 is  1  -->   2 -  1 =  1
</code>```

It takes 6 steps to reach 1.

Input

Input is an integer n, where n ≥ 2.

Your program should support input up to the language's maximum integer value.

Output

Simply output the number of steps, like 6.

Leading/trailing whitespaces or newlines are fine.

Examples

```<code>f(5)        --> 3
f(30)       --> 6
f(31)       --> 7
f(32)       --> 5
f(100)      --> 8
f(200)      --> 9
f(2016^155) --> 2015
</code>```

Requirements

You can get input from STDIN, command line arguments, as function parameters or from the closest equivalent.

You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it.

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

Standard loopholes are disallowed.

This series can be found on OEIS as well: A064097

A quasi-logarithm defined inductively by a(1) = 0 and a(p) = 1 + a(p-1) if p is prime and a(n*m) = a(n) + a(m) if m,n > 1.

Body:
Jelly, 10 bytes

ÆfḊPạµÐĿi2

Try it online! or verify most test cases. The last test cases finishes quickly locally.

How it works

ÆfḊPạµÐĿi2  Main link. Argument: n (integer)

Æf          Factorize n, yielding a list of primes, [] for 1, or [0] for 0.
  Ḋ         Dequeue; remove the first (smallest) element.
   P        Take the product.
            This yields the largest proper divisor if n > 1, 1 if n < 2.
    ạ       Yield the abs. value of the difference of the divisor (or 1) and n.
     µ      Convert the chain to the left into a link.
      ÐĿ    Repeatedly execute the link until the results are no longer unique.
            Collect all intermediate results in a list.
            For each starting value of n, the last results are 2 -> 1 -> 0 (-> 1).
        i2  Compute the 1-based index of 2.


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

```<code>`tttYfl)/-tq]vnq
</code>```

Try it Online

Explanation

```<code>        % Implicitly grab input
`       % Do while loop
    ttt % Make three copies of top stack element
    Yf  % Compute all prime factors
    l)  % Grab the smallest one
    /   % Divide by this to get the biggest divisor
    -   % Subtract the biggest divisor
    t   % Duplicate the result
    q   % Subtract one (causes loop to terminate when the value is 1). This
        % is functionally equivalent to doing 1> (since the input will always be positive)
        % with fewer bytes
]       % End do...while loop
v       % Vertically concatenate stack contents (consumes entire stack)
n       % Determine length of the result
q       % Subtract 1 from the length
        % Implicitly display result
</code>```

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

`tttYfl)/-tq]vnq

Try it Online

Explanation

        % Implicitly grab input
`       % Do while loop
    ttt % Make three copies of top stack element
    Yf  % Compute all prime factors
    l)  % Grab the smallest one
    /   % Divide by this to get the biggest divisor
    -   % Subtract the biggest divisor
    t   % Duplicate the result
    q   % Subtract one (causes loop to terminate when the value is 1). This
        % is functionally equivalent to doing 1> (since the input will always be positive)
        % with fewer bytes
]       % End do...while loop
v       % Vertically concatenate stack contents (consumes entire stack)
n       % Determine length of the result
q       % Subtract 1 from the length
        % Implicitly display result


答:
PowerShell (v4), 117 bytes

$y,$z=@($input-replace'[^a-z0-9 \n-]'-split'\s'|group|sort Count)[-2,-1]
($y,($z,'')[$y.Count-eq$z.Count])[!!$z].Name
```
<p>The first part is easy enough:</p>
<ul>
<li><code>$input</code> is ~= stdin</li>
<li>Regex replace irrelevant characters with nothing, keep newlines so we don't mash two words from the end of a line and the beginning of the next line into one by mistake. (Nobody else has discussed multiple lines, could golf -2 if the input is always a single line).</li>
<li>Regex split, <code>Group</code> by frequency (~= Python's collections.Counter), <code>Sort</code> to put most frequent words at the end.</li>
<li>PowerShell is case insensitive by default for everything.</li>
</ul>
<p>Handling if there isn't a most frequent word:</p>
<ul>
<li>Take the last two items [-2,-1] into $y and $z;</li>
<li>an N-item list, where N>=2,  makes  $y and $z the last two items</li>
<li>a 1-item list makes $y the last item and $z null</li>
<li>an Empty list makes them both null</li>
</ul>
<p>Use the bool-as-array-index fake-ternary-operator golf <code>(0,1)[truthyvalue]</code>, nested, to choose "", $z or $y as output, then take .Name.</p>
<pre class="lang-powershell prettyprint-override"><code>PS D:\> "The man walked down the road."|.\test.ps1
The

PS D:\> "Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy."|.\test.ps1
he

PS D:\> "`"That's... that's... that is just terrible!`" he said."|.\test.ps1
Thats

PS D:\> "The old-fashioned man ate an old-fashioned cake."|.\test.ps1
old-fashioned

PS D:\> "IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses."|.\test.ps1
IPv6
</code>```

Title: What is the most frequent word?

Body:
PowerShell (v4), 117 bytes

$y,$z=@($input-replace'[^a-z0-9 \n-]'-split'\s'|group|sort Count)[-2,-1]
($y,($z,'')[$y.Count-eq$z.Count])[!!$z].Name

The first part is easy enough:

$input is ~= stdin

Regex replace irrelevant characters with nothing, keep newlines so we don't mash two words from the end of a line and the beginning of the next line into one by mistake. (Nobody else has discussed multiple lines, could golf -2 if the input is always a single line).

Regex split, Group by frequency (~= Python's collections.Counter), Sort to put most frequent words at the end.

PowerShell is case insensitive by default for everything.

Handling if there isn't a most frequent word:

Take the last two items [-2,-1] into $y and $z;

an N-item list, where N>=2,  makes  $y and $z the last two items

a 1-item list makes $y the last item and $z null

an Empty list makes them both null

Use the bool-as-array-index fake-ternary-operator golf (0,1)[truthyvalue], nested, to choose "", $z or $y as output, then take .Name.

PS D:\> "The man walked down the road."|.\test.ps1
The

PS D:\> "Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy."|.\test.ps1
he

PS D:\> "`"That's... that's... that is just terrible!`" he said."|.\test.ps1
Thats

PS D:\> "The old-fashioned man ate an old-fashioned cake."|.\test.ps1
old-fashioned

PS D:\> "IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses."|.\test.ps1
IPv6


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

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

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

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

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

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

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

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

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

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

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

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

The challenge

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

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

Test IO

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

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

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

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

Title: Index of a multidimensional array

Body:
CJam, 7 bytes

0q~z+:b

Try it online!

How it works

0        e# Push 0 on the stack.
 q       e# Read and push all input, e.g., "[[10 10 4 62 7] [1 2 3 4 5]]".
  ~      e# Eval, pushing [[10 10 4 62 7] [1 2 3 4 5]].
   z     e# Zip, pushing [[10 1] [10 2] [4 3] [62 4] [7 5]].
    +    e# Concatenate, pushing [0 [10 1] [10 2] [4 3] [62 4] [7 5]]
     :b  e# Reduce by base conversion.
         e# [10 1] in base    0 is    0 * 10 + 1 = 1.
         e# [10 2] in base    1 is    1 * 10 + 2 = 12.
         e# [ 4 3] in base   12 is   12 *  4 + 3 = 51.
         e# [62 4] in base   51 is   51 * 62 + 4 = 3166.
         e# [ 7 5] in base 3166 is 3166 *  7 + 5 = 22167.


问:
Largest Number Printable
Your goal is to write a program that prints a number. The bigger the number, the more points you'll get. But be careful! Code length is both limited and heavily weighted in the scoring function. Your printed number will be divided by the cube of the number of bytes you used for your solution.

So, let's say you printed 10000000 and your code is 100 bytes long. Your final score will be \$\frac {10000000} {100^3} = 10\$.

There are other rules to follow, in order to make this challenge a bit harder.

You cannot use digits in your code (0123456789);

You can use mathematical/physical/etc. constants, but only if they are less than 10. (e.g. You can use \$\pi \approx 3.14\$ but you can't use the Avogadro constant \$= 6\times 10^{23}\$)

Recursion is allowed but the generated number needs to be finite (so infinite is not accepted as a solution. Your program needs to terminate correctly, assuming unbounded time and memory, and generate the requested output);

You cannot use the operations * (multiply), / (divide), ^ (power) nor any other way to indicate them (e.g. 2 div 2 is not allowed);

Your program can output more than one number, if you need it to do that. Only the highest one will count for scoring;

However, you can concatenate strings: this means that any sequence of adjacent digits will be considered as a single number;

Your code will be run as-is. This means that the end-user cannot edit any line of code, nor he can input a number or anything else;

Maximum code length is 100 bytes.

Leaderboard

Steven H., Pyth \$\approx f_{\varphi(1,0,0)+7}(256^{26})\$

Simply Beautiful Art, Ruby \$\approx f_{\varphi(1,0,0)}(3)\$

Peter Taylor, GolfScript \$\approx f_{\varepsilon_0+\omega+1}(17)\$

r.e.s., GolfScript \$\approx f_{\epsilon_0}^9(126)\approx f_{\epsilon_0+1}(9)\$ [1]

Simply Beautiful Art, Ruby \$\approx f_{\omega^{\omega2}+1}(126^22^{126})\$

eaglgenes101, Julia \$\approx f_{\omega^3}(127)\$

col6y, Python 3, \$\approx 127\to126\to\dots\to2\to1\approx f_{\omega^2}(127)\$ [1][3]

Toeofdoom, Haskell, \$\approx a_{20}(1)\approx f_{\omega+1}(18)\$ [1]

Fraxtil, dc, \$\approx 15\uparrow^{166665}15\$ [3]

Magenta, Python, \$\approx\mathrm{ack}(126,126)\approx10\uparrow^{124}129\$

Kendall Frey, ECMAScript 6, \$\approx1000\uparrow^43\$ [1]

Ilmari Karonen, GolfScript, \$\approx10\uparrow^310^{377}\$ [1]

Aiden4, Rust, \$\approx10\uparrow^3127\$

BlackCap, Haskell, \$\approx10\uparrow\uparrow65503\$

recursive, Python, \$\approx2\uparrow\uparrow11\approx10\uparrow\uparrow8.63297\$ [1][3]

n.m., Haskell, \$\approx2\uparrow\uparrow7\approx10\uparrow\uparrow4.63297\$ [1]

David Yaw, C, \$\approx10^{10^{4\times10^{22}}}\approx10\uparrow\uparrow4.11821\$ [2]

primo, Perl, \$\approx10^{(12750684161!)^{5\times2^{27}}}\approx10\uparrow\uparrow4.11369\$

Art, C, \$\approx10^{10^{2\times10^6}}\approx10\uparrow\uparrow3.80587\$

Robert Sørlie, x86, \$\approx10^{2^{2^{19}+32}}\approx10\uparrow\uparrow3.71585\$

Tobia, APL, \$\approx10^{10^{353}}\approx10\uparrow\uparrow3.40616\$

Darren Stone, C, \$\approx10^{10^{97.61735}}\approx10\uparrow\uparrow3.29875\$

ecksemmess, C, \$\approx10^{2^{320}}\approx10\uparrow\uparrow3.29749\$

Adam Speight, vb.net, \$\approx10^{5000\times2^{256}}\approx10\uparrow\uparrow3.28039\$

Joshua, bash, \$\approx10^{10^{15}}\approx10\uparrow\uparrow3.07282\$

Footnotes

If every electron in the universe were a qubit, and every superposition thereof could be gainfully used to store information (which, as long as you don't actually need to know what's being stored is theoretically possible), this program requires more memory than could possibly exist, and therefore cannot be run - now, or at any conceiveable point in the future. If the author intended to print a value larger than ≈10↑↑3.26 all at once, this condition applies.

This program requires more memory than currently exists, but not so much that it couldn't theoretically be stored on a meager number of qubits, and therefore a computer may one day exist which could run this program.

All interpreters currently available issue a runtime error, or the program otherwise fails to execute as the author intended.

Running this program will cause irreparable damage to your system.

Edit @primo: I've updated a portion of the scoreboard using a hopefully easier to compare notation, with decimals to denote the logarithmic distance to the next higher power. For example \$10↑↑2.5 = 10^{10^{\sqrt {10}}}\$. I've also changed some scores if I believed to user's analysis to be faulty, feel free to dispute any of these.

Explanation of this notation:

If \$0 \le b \lt 1\$, then \$a \uparrow\uparrow b = a^b\$.

If \$b \ge 1\$, then \$a \uparrow\uparrow b = a^{a \uparrow\uparrow (b-1)}\$.

If \$b \lt 0\$, then \$a \uparrow\uparrow b = \log_a(a \uparrow\uparrow (b+1))\$

An implementation of this notation is provided in Python that let's you test reasonably sized values.

答:
Python 3, score = ack(126,126)/100^3

```<code>g=len('"');i=ord('~');f=lambda m,n:(f(m-g,f(m,n-g))if n else f(m-g,g))if m else n+g
print(f(i,i))
</code>```

The f function is the ackermann function, which i have just enough space to invoke.

Edit: previously "else n+1", which was in violation of challenge rules- kudos to Simply Beautiful Art.

ContentLicense: CC BY-SA 4.0

Title: Largest Number Printable

Body:
Python 3, score = ack(126,126)/100^3

g=len('"');i=ord('~');f=lambda m,n:(f(m-g,f(m,n-g))if n else f(m-g,g))if m else n+g
print(f(i,i))

The f function is the ackermann function, which i have just enough space to invoke.

Edit: previously "else n+1", which was in violation of challenge rules- kudos to Simply Beautiful Art.


Body:
Julia, <s>39</s> 36 bytes

\(n,k=2)=n%k>0?n>1&&n\-~k:\(n-n/k)+1

Try it online!


问:
Convert header levels to numbers

Introduction

Nodes in tree structures (e.g. headings in a long document, law paragraphs, etc.) are often created by assigning a specific header level (h1, h2, etc.) to each item, but outputted with additional node numbers for each level (1., 1.1., etc.), e.g.:

```<code>1. Intro (h1)
1.1. About this (h2)
1.2. Target audience (h2)
2. Actual stuff (h1)
3. More stuff (h1)
3.1. Details (h2)
3.1.1. Special points (h3)
3.2. Specifics (h2)
3.2.1. Minutiae (h3)
3.2.2. Petitesses (h3)
3.3. Specifications (h2)
4. Index (h1)
5. Appendices (h1)
</code>```

Input

Given (by any means) a list of header levels (the X's in hX above) like:

```<code>[1,2,2,1,1,2,3,2,3,3,2,1,1]
</code>```

Input will always begin with a 1, and Inputn+1 is in the range [1,1+Inputn].

Input will only contain numbers in the range [1,256].

Output

Return (by any means) the list of lists (or matrix - see below) of node numbers (dot-separated above):

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

You may return scalars instead of one-element sub-lists:

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

You may return a matrix (or list of lists) which is padded with zeros so that all rows (sub-lists) have the same length:

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

Additional rules

The reverse process of all this is just the length of each sub-list. You must also include a reverse program in the same language. Your score is the total byte count of your two programs. If you return zero-padded results on the first prgram, your reverse code must handle such input.

Please explain your code so we all can learn from it.

This is code golf, because I'll need to read it on a phone screen and type it into a computer. - No, really, this is not meme-ness!

答:
JavaScript (ES6), 47 + 21 = 68 bytes

```<code>a=>a.map(l=>b=[...b.slice(0,--l),-~b[l]],b=[])
</code>```

Explanation:

```<code>a=>a.map(l=>            Loop over each header level
 b=[                    Make a new sublist using
  ...b.slice(0,--l),    First l-1 elements from the previous sublist
  -~b[l]],              Plus increment the lth element or default to 1
 b=[])                  Start with an empty sublist
</code>```

The bitwise not operator is used because it will coerce its operand to a signed 32-bit integer, which will be zero if this is a new level. Negating the result conveniently returns one more than the original number, or 1 in the case of a new level. Reverse process:

```<code>a=>a.map(b=>b.length)
</code>```

Title: Convert header levels to numbers

Body:
JavaScript (ES6), 47 + 21 = 68 bytes

a=>a.map(l=>b=[...b.slice(0,--l),-~b[l]],b=[])

Explanation:

a=>a.map(l=>            Loop over each header level
 b=[                    Make a new sublist using
  ...b.slice(0,--l),    First l-1 elements from the previous sublist
  -~b[l]],              Plus increment the lth element or default to 1
 b=[])                  Start with an empty sublist

The bitwise not operator is used because it will coerce its operand to a signed 32-bit integer, which will be zero if this is a new level. Negating the result conveniently returns one more than the original number, or 1 in the case of a new level. Reverse process:

a=>a.map(b=>b.length)


答:
Pyth, <s>27</s> 22 + 2 = 24 bytes

This is embarrassingly <s>more than</s> 1 less than half of the bytes that javascript used.

```<code>JylQjRJ.uhs*N^JY-VtQQ1
</code>```

Try it online!

Reverse, 2 bytes

```<code>lM
</code>```

Try it online!

Title: Convert header levels to numbers

Body:
Introduction

Nodes in tree structures (e.g. headings in a long document, law paragraphs, etc.) are often created by assigning a specific header level (h1, h2, etc.) to each item, but outputted with additional node numbers for each level (1., 1.1., etc.), e.g.:

```<code>1. Intro (h1)
1.1. About this (h2)
1.2. Target audience (h2)
2. Actual stuff (h1)
3. More stuff (h1)
3.1. Details (h2)
3.1.1. Special points (h3)
3.2. Specifics (h2)
3.2.1. Minutiae (h3)
3.2.2. Petitesses (h3)
3.3. Specifications (h2)
4. Index (h1)
5. Appendices (h1)
</code>```

Input

Given (by any means) a list of header levels (the X's in hX above) like:

```<code>[1,2,2,1,1,2,3,2,3,3,2,1,1]
</code>```

Input will always begin with a 1, and Inputn+1 is in the range [1,1+Inputn].

Input will only contain numbers in the range [1,256].

Output

Return (by any means) the list of lists (or matrix - see below) of node numbers (dot-separated above):

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

You may return scalars instead of one-element sub-lists:

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

You may return a matrix (or list of lists) which is padded with zeros so that all rows (sub-lists) have the same length:

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

Additional rules

The reverse process of all this is just the length of each sub-list. You must also include a reverse program in the same language. Your score is the total byte count of your two programs. If you return zero-padded results on the first prgram, your reverse code must handle such input.

Please explain your code so we all can learn from it.

This is code golf, because I'll need to read it on a phone screen and type it into a computer. - No, really, this is not meme-ness!

Body:
Pyth, <s>27</s> 22 + 2 = 24 bytes

This is embarrassingly <s>more than</s> 1 less than half of the bytes that javascript used.

JylQjRJ.uhs*N^JY-VtQQ1

Try it online!

Reverse, 2 bytes

lM

Try it online!


Title: What is the most frequent word?

Body:
What is the most frequent word?

Given a sentence, your program must make its way through it, counting the frequencies of each word, then output the most used word. Because a sentence has no fixed length, and so can get very long, your code must be as short as possible.

Rules/Requirements

Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.

There must be a free interpreter/compiler available for your language.

If it is possible, provide a link to a site where your program can be tested.

Your program must not write anything to STDERR.

Your program should take input from STDIN (or the closest alternative in your language).

Standard loopholes are forbidden.

Your program must be case-insensitive (tHe, The and the all contribute to the count of the).

If there is no most frequent word (see test case #3), your program should output nothing.

Definition of a 'word':

You get the list of words by splitting the input text on spaces. The input will never contain any other type of whitespace than plain spaces (in particular no newlines). However, the final words should only contain alphanumerics (a-z, A-Z, 0-9), hyphens (-) and apostrophes ('). You can make that so by removing all other characters or by replacing them by space before doing the word splitting. To remain compatible with previous versions of the rules, apostrophes are not required to be included.

Test Cases

```<code>The man walked down the road.
==> the

-----

Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.
==> he

-----

This sentence has no most frequent word.
==>

-----

"That's... that's... that is just terrible!" he said.
==> that's / thats

-----

The old-fashioned man ate an old-fashioned cake.
==> old-fashioned

-----

IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.
==> IPv6

-----

This sentence with words has at most two equal most frequent words.
==>
</code>```

Note: The third and seventh test cases have no output, you may choose either on the fourth.

Scoring

Programs are scored according to bytes. The usual character set is UTF-8, if you are using another please specify.

When the challenge finishes, the program with the least bytes (it's called code-golf), will win.

Submissions

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

Leaderboard

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

/* Configuration */

var QUESTION_ID = 79576; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Perl 5, <s>96</s> <s>92</s> 84 + 2 (-p flag) = 86 bytes

++$h{+lc}for/\w(?:\S*\w)?/g}{$m>$e[1]||$e[1]>$m&&(($_,$m)=@e)||($_="")while@e=each%h

Using:

> echo "The man walked down the road." | perl -p script.pl


答:
Perl, <s>60</s> <s>56</s> <s>55</s> 54 bytes

Includes +3 for -p

```<code>#!/usr/bin/perl -p
s/[\pL\d'-]+/$;[$a{lc$&}++]++or$\=$&/eg}{$\x=2>pop@
</code>```

If a word cannot be just a number you can also drop the a for a score of 53.

Title: What is the most frequent word?

Body:
Perl, <s>60</s> <s>56</s> <s>55</s> 54 bytes

Includes +3 for -p

#!/usr/bin/perl -p
s/[\pL\d'-]+/$;[$a{lc$&}++]++or$\=$&/eg}{$\x=2>pop@

If a word cannot be just a number you can also drop the a for a score of 53.


问:
Mode (most common element) of a list
Write a snippet to calculate the mode (most common number) of a list of positive integers.

For example, the mode of

```<code>d = [4,3,1,0,6,1,6,4,4,0,3,1,7,7,3,4,1,1,2,8]
</code>```

is 1, because it occurs the maximum of 5 times.

You may assume that the list is stored in a variable such as d and has a unique mode.

e.g.: Python, 49

```<code>max(((i,d.count(i))for i in set(d)), key=lambda x:x[1])
</code>```

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

答:
Perl, 27 bytes

```<code>$Q[$a{$_}++]=$_ for@F;pop@Q
</code>```

Returns the last most common value in case of a tie.

Title: Mode (most common element) of a list

Body:
Perl, 27 bytes

$Q[$a{$_}++]=$_ for@F;pop@Q

Returns the last most common value in case of a tie.


问:
Detect rotated strings
Read two strings from stdin.

Output Yes if one string is a rotated version of the other.

Otherwise output No

Testcases

Input

```<code>CodeGolf GolfCode
</code>```

Output

```<code>Yes
</code>```

Input

```<code>stackexchange changestackex
</code>```

Output

```<code>Yes
</code>```

Input

```<code>stackexchange changestack
</code>```

Output

```<code>No
</code>```

Input

```<code>Hello World
</code>```

Output

```<code>No
</code>```

答:
05AB1E, 20 bytes

Code:

```<code>DgFÀD²Qi"Yes",q}}"No
</code>```

Uses CP-1252 encoding. Try it online!

ContentLicense: CC BY-SA 2.5

Title: Detect rotated strings

Body:
05AB1E, 20 bytes

Code:

DgFÀD²Qi"Yes",q}}"No

Uses CP-1252 encoding. Try it online!


问:
Decompose a number!
Your task is to decompose a number using the format below.

This is similar to base conversion, except that instead of listing the digits in the base, you list the values, such that the list adds up to the input.

If the given base is \$n\$, then each number in the list must be in the form of \$k\times n^m\$, where \$0\le k<n\$ and \$m\$ is unique throughout the list.

Specs

Any reasonable input/output format. Your program/function takes 2 inputs and outputs a list.

Output list can be in any order.

0 can be excluded or included.

Leading 0s are allowed.

Built-ins are allowed.

Testcases

```<code>number base   converted list
input1 input2 output
123456 10     [100000,20000,3000,400,50,6] or [6,50,400,3000,20000,100000]
11     2      [8,2,1] or [0,0,0,0,8,0,2,1]
727    20     [400,320,7]
101    10     [100,1] or [100,0,1]
</code>```

Scoring

This is code-golf. Shortest solution in bytes wins.

答:
><>, 28 bytes

```<code>:&\
&*>:{:}$%:n$}-:0=?;ao$&:
</code>```

Expects the input values to be present on the stack at program start.

As ><> doesn't have list objects, the output is presented as a newline-separated list of values, with the 'units' on the first line. An example run:

```<code>Input:
11 2

Ouput:
1
2
0
8
</code>```

@OP, if this isn't an acceptable output format, let me know and I'll edit the answer accordingly.

Title: Decompose a number!

Body:
><>, 28 bytes

:&\
&*>:{:}$%:n$}-:0=?;ao$&:

Expects the input values to be present on the stack at program start.

As ><> doesn't have list objects, the output is presented as a newline-separated list of values, with the 'units' on the first line. An example run:

Input:
11 2

Ouput:
1
2
0
8

@OP, if this isn't an acceptable output format, let me know and I'll edit the answer accordingly.


答:
JavaScript (ES6), <s>*44</s> 38

Edit 6 bytes saved thanks @l4m2

(* 4 striked is still 4)

Recursive function

f=(n,d=n)=>n>1?n%--d?f(n,d):f(n-d)+1:0
```
<p>Less golfed</p>
<pre class="lang-js prettyprint-override"><code>f=(n, d=n-1)=>{
  if (n>1)
    if(n % d != 0)
      return f(n, d-1) // same number, try a smaller divisor
    else
      return f(n-d)+1  // reduce number, increment step, repeat
  else
    return 0
}
</code>```

Test

f=(n,d=n)=>n>1?n%--d?f(n,d):f(n-d)+1:0

console.log=x=>O.textContent+=x+'\n';

[5,30,31,32,100,200].forEach(x=>console.log(x+' -> '+f(x)))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id=O>``````

Body:
JavaScript (ES6), <s>*44</s> 38

Edit 6 bytes saved thanks @l4m2

(* 4 striked is still 4)

Recursive function

f=(n,d=n)=>n>1?n%--d?f(n,d):f(n-d)+1:0

Less golfed

f=(n, d=n-1)=>{
  if (n>1)
    if(n % d != 0)
      return f(n, d-1) // same number, try a smaller divisor
    else
      return f(n-d)+1  // reduce number, increment step, repeat
  else
    return 0
}

Test

f=(n,d=n)=>n>1?n%--d?f(n,d):f(n-d)+1:0

console.log=x=>O.textContent+=x+'\n';

[5,30,31,32,100,200].forEach(x=>console.log(x+' -> '+f(x)))

<pre id=O></pre>


答:
Java (JDK 10), 60 bytes

n->{int c=0,d;for(;n>1;c++,n-=d)for(d=n;n%--d>0;);return c;}
```

Try it online!

Body:
Inspired by this question over at Mathematics.

The Problem

Let n be a natural number ≥ 2. Take the biggest divisor of n – which is different from n itself – and subtract it from n. Repeat until you get 1.

The Question

How many steps does it take to reach 1 for a given number n ≥ 2.

Detailed Example

Let n = 30.

The greatest divisor of:

```<code>1.   30 is 15  -->  30 - 15 = 15
2.   15 is  5  -->  15 -  5 = 10
3.   10 is  5  -->  10 -  5 =  5
4.    5 is  1  -->   5 -  1 =  4
5.    4 is  2  -->   4 -  2 =  2
6.    2 is  1  -->   2 -  1 =  1
</code>```

It takes 6 steps to reach 1.

Input

Input is an integer n, where n ≥ 2.

Your program should support input up to the language's maximum integer value.

Output

Simply output the number of steps, like 6.

Leading/trailing whitespaces or newlines are fine.

Examples

```<code>f(5)        --> 3
f(30)       --> 6
f(31)       --> 7
f(32)       --> 5
f(100)      --> 8
f(200)      --> 9
f(2016^155) --> 2015
</code>```

Requirements

You can get input from STDIN, command line arguments, as function parameters or from the closest equivalent.

You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it.

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

Standard loopholes are disallowed.

This series can be found on OEIS as well: A064097

A quasi-logarithm defined inductively by a(1) = 0 and a(p) = 1 + a(p-1) if p is prime and a(n*m) = a(n) + a(m) if m,n > 1.

Body:
Java (JDK 10), 60 bytes

n->{int c=0,d;for(;n>1;c++,n-=d)for(d=n;n%--d>0;);return c;}

Try it online!


答:
PHP, 55 bytes

Uses Windows-1252 encoding.

```<code>for($n=$argv[1];$d+$n-=$d=$n%$argv[2]**++$i;)echo$d,~Ó;
</code>```

Run like this (-d added for aesthetics only):

```<code>php -d error_reporting=30709 -r 'for($n=$argv[1];$d+$n-=$d=$n%$argv[2]**++$i;)echo$d,~Ó; echo"\n";' 123056 10
</code>```

Title: Decompose a number!

Body:
Your task is to decompose a number using the format below.

This is similar to base conversion, except that instead of listing the digits in the base, you list the values, such that the list adds up to the input.

If the given base is \$n\$, then each number in the list must be in the form of \$k\times n^m\$, where \$0\le k<n\$ and \$m\$ is unique throughout the list.

Specs

Any reasonable input/output format. Your program/function takes 2 inputs and outputs a list.

Output list can be in any order.

0 can be excluded or included.

Leading 0s are allowed.

Built-ins are allowed.

Testcases

```<code>number base   converted list
input1 input2 output
123456 10     [100000,20000,3000,400,50,6] or [6,50,400,3000,20000,100000]
11     2      [8,2,1] or [0,0,0,0,8,0,2,1]
727    20     [400,320,7]
101    10     [100,1] or [100,0,1]
</code>```

Scoring

This is code-golf. Shortest solution in bytes wins.

Body:
PHP, 55 bytes

Uses Windows-1252 encoding.

for($n=$argv[1];$d+$n-=$d=$n%$argv[2]**++$i;)echo$d,~Ó;

Run like this (-d added for aesthetics only):

php -d error_reporting=30709 -r 'for($n=$argv[1];$d+$n-=$d=$n%$argv[2]**++$i;)echo$d,~Ó; echo"\n";' 123056 10


问:
Calculate the Fermat Point of a Triangle
This is somewhat similar to The centers of a triangle, but with a different point. The Fermat Point is the point P in triangle ABC such that the value of AP + BP + CP is minimized. There are two cases:

If there is an angle greater than 120 degrees, that vertex is the fermat point. Otherwise, draw equilateral triangles on each of the sides of ABC. Connect the far vertex of each equilateral triangle to the opposite vertex of triangle ABC. Doing this for each of the three equilateral triangles results in a single common point of intersection for all three lines, which is the Fermat Point.

It should run within 5 seconds on a reasonable machine.

Input: A set of 3 points, not necessarily integers. This can be taken as a nested array, string, list of tuples, etc. (whatever suits your language).

Output: The coordinates of the Fermat point, again, however your language best handles points. Floating point inaccuracies will not be counted against you.

Test Cases:

```<code>[[1, 1], [2, 2], [1, 2]] --> [1.2113248654051871, 1.788675134594813]
[[-1, -1], [-2, -1], [0, 0]] --> [-1, -1]
[[-1, -1], [1, -1], [0, 1]] --> [0, -0.42264973081037427]
[[0, 0], [0.5, 0.8660254037844386], [-5, 0]] --> [0, 0]
[[0, 0], [0, -5], [-0.8660254037844386, 0.5]] --> [0, 0]
</code>```

This is code golf so shortest code wins!

答:
Haskell, <s>346</s> <s>291</s> 295 bytes

infixl 5£
z=zipWith
(?)=z(-)
t[a,b]=[-b,a]
a¤b=sum$z(*)a b
a%b=t a¤b
r a b c=[c%b/a%b,c%a/a%b]
x£y=2*x¤y<= -sqrt(x¤x*y¤y)
f[a,b,c]|a?b£c?b=b|a?c£b?c=c|b?a£c?a=a|[n,m,p,o]<-c?k a b c++a?k b c a=r[m,o][n,p][c%[n,m],a%[p,o]]
k a b c=map(/2)$z(+)a b?map(signum((b?a)%(c?a))*sqrt 3*)(t$b?a)
```
<p>The same code with some explanations</p>
<pre class="lang-haskell prettyprint-override"><code>infixl 5£
z=zipWith

-- operator ? : difference of two vectors
(?)=z(-)

-- function t : rotate a vector by +90 degrees
t[a,b]=[-b,a]

-- operator ¤ : scalar product of two vectors ( a¤b = a0 * b0 + a1 * b1 )
a¤b=sum$z(*)a b

-- operator % : "cross product" of two vectors ( a%b = a0 * b1 - a1 * b0 )
--      this returns actually the z coordinate of the 3d cross vector
--      other coordinates are nul since a and b are in the xy plan
a%b=t a¤b

-- function r : solves the system of two linear equations with two variables x0,x1 :
--      a0*x0 - b0*x1 = c0
--      a1*x0 - b1*x1 = c1
r a b c=[c%b/a%b,c%a/a%b]

-- operator £ : returns true if the angle between two vectors is >= 120 degrees
--      x¤y = ||x|| * ||y|| * cos(xyAngle)
--      so xyAngle>=120° is equivalent to : x¤y / (||x|| * ||y||) <= -0.5
x£y=2*x¤y<= -sqrt(x¤x*y¤y)

-- function k : takes 3 points A B C of a triangle and constructs the point C'
--              of the equilateral triangle ABC' which is opposite to C:
--              C' = (A+B)/2 - ((+/-) sqrt(3)/2 * t(AB))
--
--      the sign +/- is given by the sign of the cross vector of AB an AC ((b?a)%(c?a))
--      which is >0 if the angle between AB and AC is positive
--      and <0 otherwise.
k a b c=map(/2)$z(+)a b?map(signum((b?a)%(c?a))*sqrt 3*)(t$b?a)

-- function f : returns the fermat point of a triangle
f[a,b,c]
    |a?b£c?b=b  -- return B if angle ABC >= 120°
    |a?c£b?c=c  -- return C if angle BCA >= 120°
    |b?a£c?a=a  -- return A if angle CAB >= 120°
    |[n,m,p,o]<-c?k a b c++a?k b c a= -- calculate the two segments C'C and A'A
        r[m,o][n,p][c%[n,m],a%[p,o]]  -- return their intersection
</code>```

Tests:

main = do
    print $ f [[1, 1], [2, 2], [1, 2]]
    print $ f [[-1, -1], [-2, -1], [0, 0]]
    print $ f [[-1, -1], [1, -1], [0, 1]]
    print $ f [[0, 0], [0.5, 0.8660254037844386], [-5, 0]]
    print $ f [[0, 0], [0, -5], [-0.8660254037844386, 0.5]]
```
<p>Output:</p>

<pre class="lang-haskell prettyprint-override"><code>[1.2113248654051871,1.7886751345948126]
[-1.0,-1.0]
[0.0,-0.42264973081037427]
[0.0,0.0]
[0.0,0.0]
</code>```

Body:
Haskell, <s>346</s> <s>291</s> 295 bytes

infixl 5£
z=zipWith
(?)=z(-)
t[a,b]=[-b,a]
a¤b=sum$z(*)a b
a%b=t a¤b
r a b c=[c%b/a%b,c%a/a%b]
x£y=2*x¤y<= -sqrt(x¤x*y¤y)
f[a,b,c]|a?b£c?b=b|a?c£b?c=c|b?a£c?a=a|[n,m,p,o]<-c?k a b c++a?k b c a=r[m,o][n,p][c%[n,m],a%[p,o]]
k a b c=map(/2)$z(+)a b?map(signum((b?a)%(c?a))*sqrt 3*)(t$b?a)

The same code with some explanations

infixl 5£
z=zipWith

-- operator ? : difference of two vectors
(?)=z(-)

-- function t : rotate a vector by +90 degrees
t[a,b]=[-b,a]

-- operator ¤ : scalar product of two vectors ( a¤b = a0 * b0 + a1 * b1 )
a¤b=sum$z(*)a b

-- operator % : "cross product" of two vectors ( a%b = a0 * b1 - a1 * b0 )
--      this returns actually the z coordinate of the 3d cross vector
--      other coordinates are nul since a and b are in the xy plan
a%b=t a¤b

-- function r : solves the system of two linear equations with two variables x0,x1 :
--      a0*x0 - b0*x1 = c0
--      a1*x0 - b1*x1 = c1
r a b c=[c%b/a%b,c%a/a%b]

-- operator £ : returns true if the angle between two vectors is >= 120 degrees
--      x¤y = ||x|| * ||y|| * cos(xyAngle)
--      so xyAngle>=120° is equivalent to : x¤y / (||x|| * ||y||) <= -0.5
x£y=2*x¤y<= -sqrt(x¤x*y¤y)

-- function k : takes 3 points A B C of a triangle and constructs the point C'
--              of the equilateral triangle ABC' which is opposite to C:
--              C' = (A+B)/2 - ((+/-) sqrt(3)/2 * t(AB))
--
--      the sign +/- is given by the sign of the cross vector of AB an AC ((b?a)%(c?a))
--      which is >0 if the angle between AB and AC is positive
--      and <0 otherwise.
k a b c=map(/2)$z(+)a b?map(signum((b?a)%(c?a))*sqrt 3*)(t$b?a)

-- function f : returns the fermat point of a triangle
f[a,b,c]
    |a?b£c?b=b  -- return B if angle ABC >= 120°
    |a?c£b?c=c  -- return C if angle BCA >= 120°
    |b?a£c?a=a  -- return A if angle CAB >= 120°
    |[n,m,p,o]<-c?k a b c++a?k b c a= -- calculate the two segments C'C and A'A
        r[m,o][n,p][c%[n,m],a%[p,o]]  -- return their intersection

Tests:

main = do
    print $ f [[1, 1], [2, 2], [1, 2]]
    print $ f [[-1, -1], [-2, -1], [0, 0]]
    print $ f [[-1, -1], [1, -1], [0, 1]]
    print $ f [[0, 0], [0.5, 0.8660254037844386], [-5, 0]]
    print $ f [[0, 0], [0, -5], [-0.8660254037844386, 0.5]]

Output:

[1.2113248654051871,1.7886751345948126]
[-1.0,-1.0]
[0.0,-0.42264973081037427]
[0.0,0.0]
[0.0,0.0]


问:
Toilet Paper Mysteries
Today you need to solve a very practical problem: How many loops do you need to have a certain number of sheets on your toilet paper roll? Let's look at some facts:

The diameter of a bare toilet paper cylinder is 3.8cm

The length of one sheet of toilet paper is 10cm.

The thickness of one sheet of toilet paper is 1mm.

Before you wrap around the cylinder the first time, it has a circumference in cm of 3.8*pi. Every time you wrap a sheet around the cylinder its radius increases by .1, therefore its circumference increases by .2*PI. Use this information to find out how many loops it takes to fit n sheets of toilet paper. (Note: Use an approximation of Pi that is at least as accurate as 3.14159).

Test Cases:

n=1:

10/(3.8*pi) = .838 loops

n=2:

(How many full loops can we make?) 1 full loop = 3.8*pi = 11.938.

(How much do we have left after the 1st loop?) 20 - 11.938 = 8.062

(How much of a 2nd loop does the remaining piece make?) 8.062/(4*pi) = .642 loops

Answer: 1.642 loops

n=3:

1st full loop = 3.8*pi = 11.938, 2nd full loop = 4*pi = 12.566

30 - 11.938 - 12.566 = 5.496

5.496/(4.2*pi) = .417

Answer: 2.417 loops

n=100 => 40.874

答:
><>, 46 44 bytes

```<code>a*0"Gq",:&a9+*\
?\:{$-{1+{&:&+>:{:})
;>{$,+n
</code>```

Expects the number of sheets to be present on the stack at program start.

This uses an approximation of pi of 355/113 = 3.14159292..., storing pi/5 in the register. The current iteration's circumference lives on the stack, and pi/5 is added on each iteration.

Edit: Refactored to store the circumference directly - previous version stored pi/10 and started the diameter as 38, which was 2 bytes longer.

Title: Toilet Paper Mysteries

Body:
><>, 46 44 bytes

a*0"Gq",:&a9+*\
?\:{$-{1+{&:&+>:{:})
;>{$,+n

Expects the number of sheets to be present on the stack at program start.

This uses an approximation of pi of 355/113 = 3.14159292..., storing pi/5 in the register. The current iteration's circumference lives on the stack, and pi/5 is added on each iteration.

Edit: Refactored to store the circumference directly - previous version stored pi/10 and started the diameter as 38, which was 2 bytes longer.


Title: Detect rotated strings

Body:
Read two strings from stdin.

Output Yes if one string is a rotated version of the other.

Otherwise output No

Testcases

Input

```<code>CodeGolf GolfCode
</code>```

Output

```<code>Yes
</code>```

Input

```<code>stackexchange changestackex
</code>```

Output

```<code>Yes
</code>```

Input

```<code>stackexchange changestack
</code>```

Output

```<code>No
</code>```

Input

```<code>Hello World
</code>```

Output

```<code>No
</code>```

Body:
CJam, 21 bytes

r]r_,,\f{\{(+}*}_@+^!

Try it online!