问:
Count of "a"s and "b"s must be equal. Did you get it computer?
In the popular (and essential) computer science book, An Introduction to Formal Languages and Automata by Peter Linz, the following formal language is frequently stated:

$$\large{L=\{a^n b^n:n\in\mathbb{Z}^+\}}$$

mainly because this language can not be processed with finite-state automata.
This expression mean "Language L consists all strings of 'a's followed by 'b's, in which the number of 'a's and 'b's are equal and non-zero".

Challenge

Write a working program/function which gets a string, containing "a"s and "b"s only, as input and returns/outputs a truth value, saying if this string is valid the formal language L.

Your program cannot use any external computation tools, including network, external programs, etc. Shells are an exception to this rule; Bash, e.g., can use command line utilities.

Your program must return/output the result in a "logical" way, for example: returning 10 instead of 0, "beep" sound, outputting to stdout etc. More info here.

Standard code golf rules apply.

This is a code-golf. Shortest code in bytes wins. Good luck!

Truthy test cases

```<code>"ab"
"aabb"
"aaabbb"
"aaaabbbb"
"aaaaabbbbb"
"aaaaaabbbbbb"
</code>```

Falsy test cases

```<code>""
"a"
"b"
"aa"
"ba"
"bb"
"aaa"
"aab"
"aba"
"abb"
"baa"
"bab"
"bba"
"bbb"
"aaaa"
"aaab"
"aaba"
"abaa"
"abab"
"abba"
"abbb"
"baaa"
"baab"
"baba"
"babb"
"bbaa"
"bbab"
"bbba"
"bbbb"
</code>```

Leaderboard

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

/* Configuration */

var QUESTION_ID = 85994; // 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 = 48934; // 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

```

答:
Thue, 39 bytes

```<code>$::=:::
ab::=x
axb::=x
-x-::=~1
::=
-$-
</code>```

Outputs a "1" for true and nothing for false.

Body:
Thue, 39 bytes

$::=:::
ab::=x
axb::=x
-x-::=~1
::=
-$-

Outputs a "1" for true and nothing for false.


问:
Use 16 colors while writing Hey! 4 times
i.e each byte appears in a different ANSI shell colour.

Rules

Resetting the color of the shell after output is not required

Must be output in STDOUT or the primary colour text output of your language.

Must be done programmatically (iterating through each color and letter of the string induvidually) instead of just writing a fixed string to shell like the reference command.

Must output the same as the reference command:
echo -e '\e[30mH\e[31me\e[32my\e[33m!\e[34mH\e[35me\e[36my\e[37m!\e[90mH\e[91me\e[92my\e[93m!\e[94mH\e[95me\e[96my\e[97m!'
on a recent version of bash (I am using 4.3 installed via Homebrew on OS X) i.e like this:

Obviously colours will vary based on terminal colour scheme.

Scoring

This is code-golf, so lowest bytes wins.

ContentLicense: CC BY-SA 3.0

Body:
JavaScript 134 bytes

<script>
  var a=0;
  var c=["H","e","y","!"];
  for(;a<3;){
    var b=-1;
    for(;++b<4;){
      document.write(<b style='color:rgb(0,0,"+(a*4+b)+"'>"+c[b]);
    }
  }
</script>

Golfed

<script>a=0;c=["H","e","y","!"];for(;a++<3;){b=-1;for(;++b<4;){document.write(<b style='color:rgb(0,0,"+(a*4+b)+"'>"+c[b]);}}</script>


答:
C, 126 bytes

#define a"\x1B[%d;%dm"
#define b j,i++
i,j;main(){for(;i=30,j<2;j++)printf(a"H"a"e"a"y"a"!"a"H"a"e"a"y"a"!",b,b,b,b,b,b,b,b);}
```

output may vary depending on your compiler, linker, operating system, and processor

Ideone doesn't have colour output, so have a screenshot from my phone:

Title: Use 16 colors while writing Hey! 4 times

Body:
i.e each byte appears in a different ANSI shell colour.

Rules

Resetting the color of the shell after output is not required

Must be output in STDOUT or the primary colour text output of your language.

Must be done programmatically (iterating through each color and letter of the string induvidually) instead of just writing a fixed string to shell like the reference command.

Must output the same as the reference command:
echo -e '\e[30mH\e[31me\e[32my\e[33m!\e[34mH\e[35me\e[36my\e[37m!\e[90mH\e[91me\e[92my\e[93m!\e[94mH\e[95me\e[96my\e[97m!'
on a recent version of bash (I am using 4.3 installed via Homebrew on OS X) i.e like this:

Obviously colours will vary based on terminal colour scheme.

Scoring

This is code-golf, so lowest bytes wins.

Body:
C, 126 bytes

#define a"\x1B[%d;%dm"
#define b j,i++
i,j;main(){for(;i=30,j<2;j++)printf(a"H"a"e"a"y"a"!"a"H"a"e"a"y"a"!",b,b,b,b,b,b,b,b);}

output may vary depending on your compiler, linker, operating system, and processor

Ideone doesn't have colour output, so have a screenshot from my phone:


问:
Compounding english
A compound word is a word that contains 2 or more words in it.  We can do better than that, though.  We need you to create 1 (nonsensical) word that contains every word.

However, we want this word to be as short as possible.  We can use overlapping letters to achieve this.

For example, if your word list was ["cat", "atom", "a"], you would want to return "catom".

Input/Output

Your program will need to take a list of words as input, and return a compound word as output.

The word list you will be using is the top 10000 words in English, according to Google  (If this list turns out to be too easy, I may change it to a longer one).   For reference, simply appending each word gives you a score of 65888.

Your score is the number of letters in your final word, lower is better.  Tie breaker goes to the first poster.

答:
C++, final word length: 38272

(optimised version took about 20 minutes)

#include <iostream>
#include <string>
#include <vector>

std::size_t calcOverlap(const std::string &a, const std::string &b, std::size_t limit, std::size_t minimal) {
    std::size_t la = a.size();
    for(std::size_t p = std::min(std::min(la, b.size()), limit + 1); -- p > minimal; ) {
        if(a.compare(la - p, p, b, 0, p) == 0) {
            return p;
        }
    }
    return 0;
}

int main() {
    std::vector<std::string> words;

    // Load all words from input
    while(true) {
        std::string word;
        std::getline(std::cin, word);
        if(word.empty()) {
            break;
        }
        words.push_back(word);
    }

    std::cerr
        << "Input word count: " << words.size() << std::endl;

    // Remove all fully subsumed words

    for(auto p = words.begin(); p != words.end(); ) {
        bool subsumed = false;
        for(auto i = words.begin(); i != words.end(); ++ i) {
            if(i == p) {
                continue;
            }
            if(i->find(*p) != std::string::npos) {
                subsumed = true;
                break;
            }
        }
        if(subsumed) {
            p = words.erase(p);
        } else {
            ++ p;
        }
    }

    std::cerr
        << "After subsuming checks: " << words.size()
        << std::endl;

    // Sort words longest-to-shortest (not necessary but doesn't hurt. Makes finding maxlen a tiny bit easier)
    std::sort(words.begin(), words.end(), [](const std::string &a, const std::string &b) {
        return a.size() > b.size();
    });

    std::size_t maxlen = words.front().size();

    // Repeatedly combine most-compatible words until there is only one left
    std::size_t bestPossible = maxlen - 1;
    while(words.size() > 1) {
        auto bestA = words.begin();
        auto bestB = -- words.end();
        std::size_t bestOverlap = 0;
        for(auto p = ++ words.begin(), e = words.end(); p != e; ++ p) {
            if(p->size() - 1 <= bestOverlap) {
                continue;
            }
            for(auto q = words.begin(); q != p; ++ q) {
                std::size_t overlap = calcOverlap(*p, *q, bestPossible, bestOverlap);
                if(overlap > bestOverlap) {
                    bestA = p;
                    bestB = q;
                    bestOverlap = overlap;
                }
                overlap = calcOverlap(*q, *p, bestPossible, bestOverlap);
                if(overlap > bestOverlap) {
                    bestA = q;
                    bestB = p;
                    bestOverlap = overlap;
                }
            }
            if(bestOverlap == bestPossible) {
                break;
            }
        }
        std::string newStr = std::move(*bestA);
        newStr.append(*bestB, bestOverlap, std::string::npos);

        if(bestA == -- words.end()) {
            words.pop_back();
            *bestB = std::move(words.back());
            words.pop_back();
        } else {
            *bestB = std::move(words.back());
            words.pop_back();
            *bestA = std::move(words.back());
            words.pop_back();
        }

        // Remove any words which are now in the result
        for(auto p = words.begin(); p != words.end(); ) {
            if(newStr.find(*p) != std::string::npos) {
                std::cerr << "Now subsumes: " << *p << std::endl;
                p = words.erase(p);
            } else {
                ++ p;
            }
        }

        std::cerr
            << "Words remaining: " << (words.size() + 1)
            << " Latest combination: (" << bestOverlap << ") " << newStr
            << std::endl;

        words.push_back(std::move(newStr));
        bestPossible = bestOverlap; // Merging existing words will never make longer merges possible
    }

    std::string result = words.front();

    std::cout
        << result
        << std::endl;
    std::cerr
        << "Word size: " << result.size()
        << std::endl;
    return 0;
}
```

<p>Verification bash one-liner:</p>

<pre class="lang-sh prettyprint-override"><code>cat commonwords.txt | while read p; do grep "$p" merged.txt >/dev/null || echo "Not found: $p"; done
</code>```

It also produced some pretty cool in-progress words. Here are some of my favourites:

polyesterday (synthetic nostalgia)

afghanistanbul (something [insert politician you dislike] would say)

togethernet (the friendly internet)

elephantom (a large ghost)

thundergroundwaterproof (as in "I don't know why they felt the need to make it thundergroundwaterproof, but it's making me nervous")

And:

codescribingo (maybe an upcoming challenge on this site?)

The final output is on pastebin here: http://pastebin.com/j3qYb65b

Title: Compounding english

Body:
C++, final word length: 38272

(optimised version took about 20 minutes)

#include <iostream>
#include <string>
#include <vector>

std::size_t calcOverlap(const std::string &a, const std::string &b, std::size_t limit, std::size_t minimal) {
    std::size_t la = a.size();
    for(std::size_t p = std::min(std::min(la, b.size()), limit + 1); -- p > minimal; ) {
        if(a.compare(la - p, p, b, 0, p) == 0) {
            return p;
        }
    }
    return 0;
}

int main() {
    std::vector<std::string> words;

    // Load all words from input
    while(true) {
        std::string word;
        std::getline(std::cin, word);
        if(word.empty()) {
            break;
        }
        words.push_back(word);
    }

    std::cerr
        << "Input word count: " << words.size() << std::endl;

    // Remove all fully subsumed words

    for(auto p = words.begin(); p != words.end(); ) {
        bool subsumed = false;
        for(auto i = words.begin(); i != words.end(); ++ i) {
            if(i == p) {
                continue;
            }
            if(i->find(*p) != std::string::npos) {
                subsumed = true;
                break;
            }
        }
        if(subsumed) {
            p = words.erase(p);
        } else {
            ++ p;
        }
    }

    std::cerr
        << "After subsuming checks: " << words.size()
        << std::endl;

    // Sort words longest-to-shortest (not necessary but doesn't hurt. Makes finding maxlen a tiny bit easier)
    std::sort(words.begin(), words.end(), [](const std::string &a, const std::string &b) {
        return a.size() > b.size();
    });

    std::size_t maxlen = words.front().size();

    // Repeatedly combine most-compatible words until there is only one left
    std::size_t bestPossible = maxlen - 1;
    while(words.size() > 1) {
        auto bestA = words.begin();
        auto bestB = -- words.end();
        std::size_t bestOverlap = 0;
        for(auto p = ++ words.begin(), e = words.end(); p != e; ++ p) {
            if(p->size() - 1 <= bestOverlap) {
                continue;
            }
            for(auto q = words.begin(); q != p; ++ q) {
                std::size_t overlap = calcOverlap(*p, *q, bestPossible, bestOverlap);
                if(overlap > bestOverlap) {
                    bestA = p;
                    bestB = q;
                    bestOverlap = overlap;
                }
                overlap = calcOverlap(*q, *p, bestPossible, bestOverlap);
                if(overlap > bestOverlap) {
                    bestA = q;
                    bestB = p;
                    bestOverlap = overlap;
                }
            }
            if(bestOverlap == bestPossible) {
                break;
            }
        }
        std::string newStr = std::move(*bestA);
        newStr.append(*bestB, bestOverlap, std::string::npos);

        if(bestA == -- words.end()) {
            words.pop_back();
            *bestB = std::move(words.back());
            words.pop_back();
        } else {
            *bestB = std::move(words.back());
            words.pop_back();
            *bestA = std::move(words.back());
            words.pop_back();
        }

        // Remove any words which are now in the result
        for(auto p = words.begin(); p != words.end(); ) {
            if(newStr.find(*p) != std::string::npos) {
                std::cerr << "Now subsumes: " << *p << std::endl;
                p = words.erase(p);
            } else {
                ++ p;
            }
        }

        std::cerr
            << "Words remaining: " << (words.size() + 1)
            << " Latest combination: (" << bestOverlap << ") " << newStr
            << std::endl;

        words.push_back(std::move(newStr));
        bestPossible = bestOverlap; // Merging existing words will never make longer merges possible
    }

    std::string result = words.front();

    std::cout
        << result
        << std::endl;
    std::cerr
        << "Word size: " << result.size()
        << std::endl;
    return 0;
}

Verification bash one-liner:

cat commonwords.txt | while read p; do grep "$p" merged.txt >/dev/null || echo "Not found: $p"; done

It also produced some pretty cool in-progress words. Here are some of my favourites:

polyesterday (synthetic nostalgia)

afghanistanbul (something [insert politician you dislike] would say)

togethernet (the friendly internet)

elephantom (a large ghost)

thundergroundwaterproof (as in "I don't know why they felt the need to make it thundergroundwaterproof, but it's making me nervous")

And:

codescribingo (maybe an upcoming challenge on this site?)

The final output is on pastebin here: http://pastebin.com/j3qYb65b


答:
Ruby, 39222 characters

Uses a similar approach to @KarlKastor in his Python answer, but the starting string is one of the smallest words instead of the largest. Another optimization (I don't know how much it helps) is that in between each addition, it prunes any words that may have already been included in the string due to overlapping words.

Runs in a little over 4 minutes on my machine, not counting the web request to retrieve the list of words, but not quite 4:20.

The word on Pastebin.

```<code>require 'net/http'

puts "Obtaining word list..."
data = Net::HTTP.get(URI'https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt')
puts "Word list obtained!"

puts "Starting calculation..."
time = Time.now

words = data.split.sort_by(&:size)
words.reject!{|w| words.find{|x| w!=x && x.include?(w)}}

string = words.shift

def merge_dist(prefix, suffix)
    [prefix.size,suffix.size].min.downto(0).find{|i| prefix.end_with?(suffix[0,i])}
end

while words.length > 0
    suffix = words.max_by{|w| merge_dist string, w}
    string += suffix[merge_dist(string, suffix)..-1]
    words.reject!{|w| string.include? w}
end

delta = Time.now - time

puts "Calculation completed in #{delta} seconds!"
puts "Word is #{string.size} chars long."

open("word.txt", 'w') << string

puts "Word saved to word.txt"
</code>```

Title: Compounding english

Body:
A compound word is a word that contains 2 or more words in it.  We can do better than that, though.  We need you to create 1 (nonsensical) word that contains every word.

However, we want this word to be as short as possible.  We can use overlapping letters to achieve this.

For example, if your word list was ["cat", "atom", "a"], you would want to return "catom".

Input/Output

Your program will need to take a list of words as input, and return a compound word as output.

The word list you will be using is the top 10000 words in English, according to Google  (If this list turns out to be too easy, I may change it to a longer one).   For reference, simply appending each word gives you a score of 65888.

Your score is the number of letters in your final word, lower is better.  Tie breaker goes to the first poster.

Body:
Ruby, 39222 characters

Uses a similar approach to @KarlKastor in his Python answer, but the starting string is one of the smallest words instead of the largest. Another optimization (I don't know how much it helps) is that in between each addition, it prunes any words that may have already been included in the string due to overlapping words.

Runs in a little over 4 minutes on my machine, not counting the web request to retrieve the list of words, but not quite 4:20.

The word on Pastebin.

require 'net/http'

puts "Obtaining word list..."
data = Net::HTTP.get(URI'https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt')
puts "Word list obtained!"

puts "Starting calculation..."
time = Time.now

words = data.split.sort_by(&:size)
words.reject!{|w| words.find{|x| w!=x && x.include?(w)}}

string = words.shift

def merge_dist(prefix, suffix)
    [prefix.size,suffix.size].min.downto(0).find{|i| prefix.end_with?(suffix[0,i])}
end

while words.length > 0
    suffix = words.max_by{|w| merge_dist string, w}
    string += suffix[merge_dist(string, suffix)..-1]
    words.reject!{|w| string.include? w}
end

delta = Time.now - time

puts "Calculation completed in #{delta} seconds!"
puts "Word is #{string.size} chars long."

open("word.txt", 'w') << string

puts "Word saved to word.txt"


问:
Cooke and Wheatstone telegraph, five-needle

Definition

According to Wikipedia:

The Cooke and Wheatstone telegraph was an early electrical telegraph system dating from the 1830s invented by English inventor William Fothergill Cooke and English scientist Charles Wheatstone. It was the first telegraph system to be put into commercial service. The receiver consisted of a number of needles which could be moved by electromagnetic coils to point to letters on a board. This feature was liked by early users who were unwilling to learn codes, and employers who did not want to invest in staff training.

It works like this:

In the middle are five needles, which can be deflected clockwise (as is the case of the middle needle) or anti-clockwise (as is the case of the last needle).

In the picture above, the two deflected needles point to the letter G, which means that the letter being transmitted/received is the letter G.

Note that the letters C, J, Q, V, X, Z are missing and thus have to be substituted with other letters.

Task

You will receive a character in ABDEFGHIKLMNOPRSTUWY as input, and you will output the corresponding configuration of the five needles, with undeflected as |, deflected clockwise as /, and deflected anti-clockwise as \.

Testcases

This covers all the possible inputs

```<code>input output
A     /|||\
B     /||\|
D     |/||\
E     /|\||
F     |/|\|
G     ||/|\  (explanation: see above)
H     /\|||
I     |/\||
K     ||/\|
L     |||/\
M     \/|||
N     |\/||
O     ||\/|
P     |||\/
R     \|/||
S     |\|/|
T     ||\|/
U     \||/|
W     |\||/
Y     \|||/
</code>```

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.

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

Your program must not write anything to STDERR.

Standard Loopholes are forbidden.

Your program can output in any case, but it must be printed (not an array or similar).

Scoring

Programs are scored according to bytes, in UTF-8 by default or a different character set of your choice.

Eventually, the answer with the least bytes 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 = 87104; // 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 = 48934; // 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

```

答:
C, 78 bytes

```<code>i;f(x){for(i=5;i--;)putchar("|/\\|"["^\\ NXLFPH DBow{} gsyc q a"[x-65]>>i&3]);}
</code>```

version shown is all printable ASCII, 79 bytes. The second \\ can be replaced by any single byte that has the same last 6 bits as the \ character 0x5C : 0x1C (if your compiler allows it), 0x9C or 0xDC.

The input character is looked up in the magic string which contains values for A to Y (including spaces for the unsupported characters CJQVX.) The character from the lookup table is interpreted as five overlapping 2-bit codes where:

```<code>01 = /   10 = \    00 or 11 = |
</code>```

Commented code in test program

```<code>/*
magic string codes: bytes are 01XXXXXX
A     /|||\ 011110 ^
B     /||\| 011100 \\
D     |/||\ 001110 N
E     /|\|| 011000 X
F     |/|\| 001100 L
G     ||/|\ 000110 F
H     /\||| 010000 P
I     |/\|| 001000 H
K     ||/\| 000100 D
L     |||/\ 000010 B
M     \/||| 101111 o
N     |\/|| 110111 w
O     ||\/| 111011 {
P     |||\/ 111101 }
R     \|/|| 100111 g
S     |\|/| 110011 s
T     ||\|/ 111001 y
U     \||/| 100011 c
W     |\||/ 110001 q
Y     \|||/ 100001 a

                                     ABBCDEFGHIJKLMNOPQRSTUVWXY*/
i;f(x){for(i=5;i--;)putchar("|/\\|"["^\\ NXLFPH DBow{} gsyc q a"[x-65]>>i&3]);}

j;
main(){
  j=getchar();
  f(j);
}
</code>```

Body:
C, 78 bytes

i;f(x){for(i=5;i--;)putchar("|/\\|"["^\\ NXLFPH DBow{} gsyc q a"[x-65]>>i&3]);}

version shown is all printable ASCII, 79 bytes. The second \\ can be replaced by any single byte that has the same last 6 bits as the \ character 0x5C : 0x1C (if your compiler allows it), 0x9C or 0xDC.

The input character is looked up in the magic string which contains values for A to Y (including spaces for the unsupported characters CJQVX.) The character from the lookup table is interpreted as five overlapping 2-bit codes where:

01 = /   10 = \    00 or 11 = |

Commented code in test program

/*
magic string codes: bytes are 01XXXXXX
A     /|||\ 011110 ^
B     /||\| 011100 \\
D     |/||\ 001110 N
E     /|\|| 011000 X
F     |/|\| 001100 L
G     ||/|\ 000110 F
H     /\||| 010000 P
I     |/\|| 001000 H
K     ||/\| 000100 D
L     |||/\ 000010 B
M     \/||| 101111 o
N     |\/|| 110111 w
O     ||\/| 111011 {
P     |||\/ 111101 }
R     \|/|| 100111 g
S     |\|/| 110011 s
T     ||\|/ 111001 y
U     \||/| 100011 c
W     |\||/ 110001 q
Y     \|||/ 100001 a

                                     ABBCDEFGHIJKLMNOPQRSTUVWXY*/
i;f(x){for(i=5;i--;)putchar("|/\\|"["^\\ NXLFPH DBow{} gsyc q a"[x-65]>>i&3]);}

j;
main(){
  j=getchar();
  f(j);
}


问:
RPN calculator without pointers
Me and some other students were at a bar discussing programming languages, in particular the C programming language. At some point a first year student said he didn't need no damn pointers. Another student said that he couldn't use arrays either since "they're basically pointers".

This led to a programming challenge:

Implement a reverse polish notation calculator in C without using arrays and pointers.

Description

You must implement a RPN calculator that

operates on integers,

supports addition (+),

supports multiplication (*).

Your implementation

must not use pointers or arrays

you may use structs

the input is read from stdin

your lexer may use pointers and arrays (but it shouldn't be needed)

when EOF is read then print the top of the stack

the behavior can be as undefined as you want for malformed input

should be in a language sufficiently c-like that the "no-pointers and no-arrays" restriction has a sensible interpretation (please elaborate if you think people may not get it)

The lexer could have a signature a la thisNote: this is not taken from my own code. Please tell me if there's an error or it looks unreasonable

```<code>typedef enum {
  val,
  op,
  eof
} TYPE;

typedef enum {
  add,
  mul
} OPERATION;

typedef struct {
  TYPE type;
  union {
    int val;
    OPERATION op;
  } dat;
} token;

token next();
</code>```

A solution using a stack with push() and pop() could look something like this:

```<code>token t;
while ((t = next()).type != eof) {
  switch (t.type) {
    case val:
      push(t.dat.val);
    case op:
      switch (t.dat.op) {
        case add:
          int v1 = pop();
          int v2 = pop();
          push(v1+v2);
        case mult:
          int v1 = pop();
          int v2 = pop();
          push(v1*v2);
      }
    case eof:
      printf("Result: %d\n", pop());
  }
}
</code>```

Other languages than C are also accepted, but the constraints should be comparable. It is hard to state the constraints in a way that fits all languages, but something like »all used data structures must have fixed size and fixed "depth"«. If there's any doubt please ask in the comments.

I have a solution that I can post. After cleaning up the code a bit. I wrote it the morning after while hungover.

答:
2 uses of pointers are collected at the top, and are permitted by the rules as these are a necessary part of I/O at the level of file descriptors. Uses C99 compound literals and POSIX low-level file operations, reading and writing one byte at a time. There is also one implicit FILE * returned by tmpfile() which is immediately converted by fileno() to an integer.

This code implements the RPN calculator as a Semi-Thue system that works like a queue. ("Thue" is pronounced /too-ay/, like "2 A".) It uses iteration and a tempfile to evaluate the formula left-to-right, examining up to 3 tokens, possibly reducing, and writing into a new temp file for the next iteration.

It waits for enter before each pass. Terminate with an interrupt signal (ctrl-C). A simple extension would allow it to detect when a string is no longer reducing from one pass to the next, and terminate.

```<code>#define Read(f,x) read(f,&x,1)
#define Write(f,x) write(f,&x,1),write(1,&x,1)

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

typedef union {
    enum tag {number, oper, eof} tag;
    struct {
        enum tag tag;
        int val;
    } num;
    struct {
        enum tag tag;
        char val;
    } op;
} token;

token input(int in){
    char b;
    int a;
    char o;
    a=0;
    o=0;
    do {
        if (!Read(in,b)) {
            return (token){.tag=eof};
        }
        if (b=='\n') {
            return (token){.tag=eof};
        }
        if (b>='0'&&b<='9') {
            a*=10;
            a+=b-'0';
        } else if (b=='+'||b=='*') {
            o=b;
        }
    } while(b!=32);

    if (o)
        return (token){.op.tag=oper, .op.val=o};
    else
        return (token){.num.tag=number, .num.val=a};
}

output(int out, token t){
    char b;
    int c;
    switch(t.tag){
    case number:
        c=t.num.val>9?(int)floor(log10((double)t.num.val)):0;
        //b = c + '0'; Write(out,b);
        for( ; c>=0; c--) {
            b = '0' + (t.num.val/(int)pow(10.0, c)) % 10;
            Write(out,b);
        }
        break;
    case oper:
        b = t.op.val;
        Write(out,b);
        break;
    case eof:
        b = '\n';
        Write(out,b);
        return;
    }
    b = 32;
    Write(out,b);
}

int rpn(int in, int out) {
    token x,y,z;
    char b;
read_x:
    //b='X';write(1,&b,1);
    x = input(in);
    //b='A'+x.tag;write(1,&b,1);
    switch (x.tag){
    case eof:
        output(out, x);
        return EOF;
    case oper:
        output(out, x);
        goto read_x;
    }
read_y:
    //b='Y';write(1,&b,1);
    y = input(in);
    //b='A'+y.tag;write(1,&b,1);
    switch (y.tag){
    case eof:
        output(out, x);
        output(out, y);
        return EOF;
    case oper:
        output(out, x);
        output(out, y);
        goto read_x;
    }
read_z:
    //b='Z';write(1,&b,1);
    z = input(in);
    //b='A'+z.tag;write(1,&b,1);
    switch(z.tag){
    case eof:
        output(out, x);
        output(out, y);
        output(out, z);
        return EOF;
    case number:
        output(out, x);
        x.num.val = y.num.val;
        y.num.val = z.num.val;
        goto read_z;
    case oper:
        switch(z.op.val){
        case '+':
            x.num.val = x.num.val + y.num.val;
            break;
        case '*':
            x.num.val = x.num.val * y.num.val;
            break;
        }
        output(out, x);
        goto read_x;
    }
    return 0;
}

main(){
    int i=0,o;
    char b;
    token t;
    do {
        o = fileno(tmpfile());
        rpn(i,o);
        i = o;
        lseek(i, 0, SEEK_SET);
    } while(Read(0,b));
}
</code>```

In action:

```<code>./2A
1 2 3 4 5 6 7 8 9 10 + + + + + + + + +
1 2 3 4 5 6 7 8 19 + + + + + + + +

1 2 3 4 5 6 7 27 + + + + + + +

1 2 3 4 5 6 34 + + + + + +

1 2 3 4 5 40 + + + + +

1 2 3 4 45 + + + +

1 2 3 49 + + +

1 2 52 + +

1 54 +

55

55

55
</code>```

Title: RPN calculator without pointers

Body:
2 uses of pointers are collected at the top, and are permitted by the rules as these are a necessary part of I/O at the level of file descriptors. Uses C99 compound literals and POSIX low-level file operations, reading and writing one byte at a time. There is also one implicit FILE * returned by tmpfile() which is immediately converted by fileno() to an integer.

This code implements the RPN calculator as a Semi-Thue system that works like a queue. ("Thue" is pronounced /too-ay/, like "2 A".) It uses iteration and a tempfile to evaluate the formula left-to-right, examining up to 3 tokens, possibly reducing, and writing into a new temp file for the next iteration.

It waits for enter before each pass. Terminate with an interrupt signal (ctrl-C). A simple extension would allow it to detect when a string is no longer reducing from one pass to the next, and terminate.

#define Read(f,x) read(f,&x,1)
#define Write(f,x) write(f,&x,1),write(1,&x,1)

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

typedef union {
    enum tag {number, oper, eof} tag;
    struct {
        enum tag tag;
        int val;
    } num;
    struct {
        enum tag tag;
        char val;
    } op;
} token;

token input(int in){
    char b;
    int a;
    char o;
    a=0;
    o=0;
    do {
        if (!Read(in,b)) {
            return (token){.tag=eof};
        }
        if (b=='\n') {
            return (token){.tag=eof};
        }
        if (b>='0'&&b<='9') {
            a*=10;
            a+=b-'0';
        } else if (b=='+'||b=='*') {
            o=b;
        }
    } while(b!=32);

    if (o)
        return (token){.op.tag=oper, .op.val=o};
    else
        return (token){.num.tag=number, .num.val=a};
}

output(int out, token t){
    char b;
    int c;
    switch(t.tag){
    case number:
        c=t.num.val>9?(int)floor(log10((double)t.num.val)):0;
        //b = c + '0'; Write(out,b);
        for( ; c>=0; c--) {
            b = '0' + (t.num.val/(int)pow(10.0, c)) % 10;
            Write(out,b);
        }
        break;
    case oper:
        b = t.op.val;
        Write(out,b);
        break;
    case eof:
        b = '\n';
        Write(out,b);
        return;
    }
    b = 32;
    Write(out,b);
}

int rpn(int in, int out) {
    token x,y,z;
    char b;
read_x:
    //b='X';write(1,&b,1);
    x = input(in);
    //b='A'+x.tag;write(1,&b,1);
    switch (x.tag){
    case eof:
        output(out, x);
        return EOF;
    case oper:
        output(out, x);
        goto read_x;
    }
read_y:
    //b='Y';write(1,&b,1);
    y = input(in);
    //b='A'+y.tag;write(1,&b,1);
    switch (y.tag){
    case eof:
        output(out, x);
        output(out, y);
        return EOF;
    case oper:
        output(out, x);
        output(out, y);
        goto read_x;
    }
read_z:
    //b='Z';write(1,&b,1);
    z = input(in);
    //b='A'+z.tag;write(1,&b,1);
    switch(z.tag){
    case eof:
        output(out, x);
        output(out, y);
        output(out, z);
        return EOF;
    case number:
        output(out, x);
        x.num.val = y.num.val;
        y.num.val = z.num.val;
        goto read_z;
    case oper:
        switch(z.op.val){
        case '+':
            x.num.val = x.num.val + y.num.val;
            break;
        case '*':
            x.num.val = x.num.val * y.num.val;
            break;
        }
        output(out, x);
        goto read_x;
    }
    return 0;
}

main(){
    int i=0,o;
    char b;
    token t;
    do {
        o = fileno(tmpfile());
        rpn(i,o);
        i = o;
        lseek(i, 0, SEEK_SET);
    } while(Read(0,b));
}

In action:

./2A
1 2 3 4 5 6 7 8 9 10 + + + + + + + + +
1 2 3 4 5 6 7 8 19 + + + + + + + +

1 2 3 4 5 6 7 27 + + + + + + +

1 2 3 4 5 6 34 + + + + + +

1 2 3 4 5 40 + + + + +

1 2 3 4 45 + + + +

1 2 3 49 + + +

1 2 52 + +

1 54 +

55

55

55


问:
Number of cycles of a permutation
Consider a permutation of the integers 1, ..., n, such as this one for n = 6:

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

If you view the permutation as a mapping from [1,2,3,4,5,6] to [5,2,4,3,6,1], the permutation can be decomponsed into disjoint cycles. A cycle is a subset of elements that map to each other. For example, 1 gets mapped to 5, which gets mapped to 6, which gets mapped back to 1. So one cycle is [1,5,6]. The other cycles are [2] and [3,4]. Thus the number of cycles for this permutation is 3.

In general, the cycles of a permutation are unique (up to order), and the number of cycles for a permutation of size n varies from 1 to n.

The challenge

Given a non-empty permutation, output its number of cycles.

Input is an array formed by the n integers 1, 2, ..., n, where n > 0. Each integer occurs exactly once. The order in which they appear defines the permutation, as in the example above.

Instead of an array you can use a list, a string with a separator between the numbers, a separate input for each number, or anything that's reasonable.

For a permutation of size n, instead of the 1-based set of integers 1, ..., n you can consistently use the 0-based set 0, ..., n-1. If so, please indicate it in your answer.

The code should work for n up to 20 in a reasonable time, say less than one minute.

Code golf. All builtins allowed.

Test cases

This assumes 1-based, array input.

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

Related

This related challenge asks for the actual cycles of the permutation, not the number of them. Requiring only the number of cycles can lead to shorter algorithms that sidestep generating the actual cycles.

答:
J, 4 bytes

```<code>#@C.
</code>```

This assumes that the permutation is 0-based. It uses the builtin C. which given a list representing a direct permutation outputs a list of cycles. Then # composed @ on that returns the number of cycles in that list.

Try it here.

Title: Number of cycles of a permutation

Body:
J, 4 bytes

#@C.

This assumes that the permutation is 0-based. It uses the builtin C. which given a list representing a direct permutation outputs a list of cycles. Then # composed @ on that returns the number of cycles in that list.

Try it here.


Title: Number of cycles of a permutation

Body:
Consider a permutation of the integers 1, ..., n, such as this one for n = 6:

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

If you view the permutation as a mapping from [1,2,3,4,5,6] to [5,2,4,3,6,1], the permutation can be decomponsed into disjoint cycles. A cycle is a subset of elements that map to each other. For example, 1 gets mapped to 5, which gets mapped to 6, which gets mapped back to 1. So one cycle is [1,5,6]. The other cycles are [2] and [3,4]. Thus the number of cycles for this permutation is 3.

In general, the cycles of a permutation are unique (up to order), and the number of cycles for a permutation of size n varies from 1 to n.

The challenge

Given a non-empty permutation, output its number of cycles.

Input is an array formed by the n integers 1, 2, ..., n, where n > 0. Each integer occurs exactly once. The order in which they appear defines the permutation, as in the example above.

Instead of an array you can use a list, a string with a separator between the numbers, a separate input for each number, or anything that's reasonable.

For a permutation of size n, instead of the 1-based set of integers 1, ..., n you can consistently use the 0-based set 0, ..., n-1. If so, please indicate it in your answer.

The code should work for n up to 20 in a reasonable time, say less than one minute.

Code golf. All builtins allowed.

Test cases

This assumes 1-based, array input.

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

Related

This related challenge asks for the actual cycles of the permutation, not the number of them. Requiring only the number of cycles can lead to shorter algorithms that sidestep generating the actual cycles.

Body:
Python, 77 69 67 bytes

f=lambda p,i=1:i and0 **p[i-1]+f(p[:i-1]+[0]+p[i:],p[i-1]or max(p))


问:
Generate Linus Sequence

Definition

From the description on OEIS A006345:

To find a(n), consider either a 1 or a 2. For each, find the longest repeated suffix, that is, for each of a(n)=1,2, find the longest sequence s with the property that the sequence a(1),...,a(n) ends with ss. Use the digit that results in the shorter such suffix. a(1) = 1.

Worked-out Example

a(1)=1.

If a(2)=1, we will have the sequence 1 1 where the longest doubled substring from the end is 1. If a(2)=2 instead, then it would be the empty substring. Therefore a(2)=2.

When n=6, we choose between 1 2 1 1 2 1 and 1 2 1 1 2 2. In the first choice, 1 2 1 is doubled consecutively from the end. In the second choice, it is 2 instead. Therefore, a(6)=2.

When n=9, we choose between 1 2 1 1 2 2 1 2 1  and 1 2 1 1 2 2 1 2 2. In the first choice, the longest doubled consecutive substring is 2 1, while in the second choice 1 2 2 is doubled consecutively at the end. Therefore a(9)=1.

Task

Given n, return a(n).

Specs

n will be positive.

You can use 0-indexed instead of 1-indexed. In that case, please state so in your answer. Also, in that case, n can be 0 also.

Testcases

The testcases are 1-indexed. However, you can use 0-indexed.

```<code>n  a(n)
1  1
2  2
3  1
4  1
5  2
6  2
7  1
8  2
9  1
10 1
11 2
12 1
13 2
14 2
15 1
16 1
17 2
18 1
19 1
20 1
</code>```

References

WolframMathWorld

Obligatory OEIS A006345

答:
Jelly, <s>30</s> <s>29</s> <s>28</s> <s>27</s> 24 bytes

```<code>;€¬;\€Z;/f;`€$ṪḢ;
1Ç¡o2Ḣ
</code>```

Try it online! or verify all test cases.

Title: Generate Linus Sequence

Body:
Jelly, <s>30</s> <s>29</s> <s>28</s> <s>27</s> 24 bytes

;€¬;\€Z;/f;`€$ṪḢ;
1Ç¡o2Ḣ

Try it online! or verify all test cases.


答:
MATL, 34 bytes

```<code>vXKi:"2:"K@h'(.+)\1$'XXgn]>QhXK]0)
</code>```

Try it online! or verify all test cases.

Explanation

```<code>v             % Concatenate stack vertically: produces empty array
XK            % Copy to clipboard K. This clipboard holds the current sequence
i:            % Take input n. Generate vector [1 2 ... n]
"             % For each k in [1 2 ... n]
  2:          %   Push [1 2]. These are the possible digits for extending the sequence
  "           %     For each j in [1 2]
    K         %       Push contents of clipboard K (current sequence)
    @         %       Push j (1 or 2)
    h         %       Concatenate horizontally: gives a possible extension of sequence
    '(.+)\1$' %       String to be used as regex pattern: maximal-length repeated suffix
    XX        %       Regex match
    gn        %       Convert to vector and push its length: gives length of match
  ]           %    End. We now have the suffix lengths of the two possible extensions
  >           %    Push 1 if extension with "1" has longer suffix than with "2"; else 0
  Q           %    Add 1: gives 2 if extension with "1" produced a longer suffix, or 1
              %    otherwise. This is the digit to be appended to the sequence
  h           %    Concatenate horizontally
  XK          %    Update clipboard with extended sequence, for the next iteration
]             % End
0)            % Get last entry (1-based modular indexing). Implicitly display
</code>```

Title: Generate Linus Sequence

Body:
Definition

From the description on OEIS A006345:

To find a(n), consider either a 1 or a 2. For each, find the longest repeated suffix, that is, for each of a(n)=1,2, find the longest sequence s with the property that the sequence a(1),...,a(n) ends with ss. Use the digit that results in the shorter such suffix. a(1) = 1.

Worked-out Example

a(1)=1.

If a(2)=1, we will have the sequence 1 1 where the longest doubled substring from the end is 1. If a(2)=2 instead, then it would be the empty substring. Therefore a(2)=2.

When n=6, we choose between 1 2 1 1 2 1 and 1 2 1 1 2 2. In the first choice, 1 2 1 is doubled consecutively from the end. In the second choice, it is 2 instead. Therefore, a(6)=2.

When n=9, we choose between 1 2 1 1 2 2 1 2 1  and 1 2 1 1 2 2 1 2 2. In the first choice, the longest doubled consecutive substring is 2 1, while in the second choice 1 2 2 is doubled consecutively at the end. Therefore a(9)=1.

Task

Given n, return a(n).

Specs

n will be positive.

You can use 0-indexed instead of 1-indexed. In that case, please state so in your answer. Also, in that case, n can be 0 also.

Testcases

The testcases are 1-indexed. However, you can use 0-indexed.

```<code>n  a(n)
1  1
2  2
3  1
4  1
5  2
6  2
7  1
8  2
9  1
10 1
11 2
12 1
13 2
14 2
15 1
16 1
17 2
18 1
19 1
20 1
</code>```

References

WolframMathWorld

Obligatory OEIS A006345

Body:
MATL, 34 bytes

vXKi:"2:"K@h'(.+)\1$'XXgn]>QhXK]0)

Try it online! or verify all test cases.

Explanation

v             % Concatenate stack vertically: produces empty array
XK            % Copy to clipboard K. This clipboard holds the current sequence
i:            % Take input n. Generate vector [1 2 ... n]
"             % For each k in [1 2 ... n]
  2:          %   Push [1 2]. These are the possible digits for extending the sequence
  "           %     For each j in [1 2]
    K         %       Push contents of clipboard K (current sequence)
    @         %       Push j (1 or 2)
    h         %       Concatenate horizontally: gives a possible extension of sequence
    '(.+)\1$' %       String to be used as regex pattern: maximal-length repeated suffix
    XX        %       Regex match
    gn        %       Convert to vector and push its length: gives length of match
  ]           %    End. We now have the suffix lengths of the two possible extensions
  >           %    Push 1 if extension with "1" has longer suffix than with "2"; else 0
  Q           %    Add 1: gives 2 if extension with "1" produced a longer suffix, or 1
              %    otherwise. This is the digit to be appended to the sequence
  h           %    Concatenate horizontally
  XK          %    Update clipboard with extended sequence, for the next iteration
]             % End
0)            % Get last entry (1-based modular indexing). Implicitly display


Title: Number of cycles of a permutation

Body:
Haskell, 111 bytes

l!i|l!!i<0=l|1<2=(take i l++[-1]++drop(i+1)l)!(l!!i)
f(x:y)|x>=0=0|1<2=1+f y
c l|l==[-1|x<-l]=0|1<2=1+c(l!f l)

Uses 0-based indexing


答:
Pyth, 9 bytes

```<code>l{mS.u@QN
</code>```

Uses 0-based indexes.
Try it online.

How it works

```<code>  m         map for d in input:
    .u        cumulative fixed-point: starting at N=d, repeatedly replace N with
      @QN       input[N]
              until a duplicate is found, and return all intermediate results
   S          sort
 {          deduplicate
l           length
</code>```

Title: Number of cycles of a permutation

Body:
Pyth, 9 bytes

l{mS.u@QN

Uses 0-based indexes.
<a href="https://pyth.herokuapp.com/?code=l%7BmS.u%40QN&test_suite=1&test_suite_input=%5B0%5D%0A%5B2%2C+1%2C+0%5D%0A%5B1%2C+2%2C+3%2C+4%2C+0%5D%0A%5B4%2C+1%2C+3%2C+2%2C+5%2C+0%5D%0A%5B7%2C+5%2C+3%2C+4%2C+1%2C+0%2C+6%2C+2%5D%0A%5B3%2C+4%2C+10%2C+11%2C+6%2C+0%2C+2%2C+8%2C+9%2C+5%2C+7%2C+1%5D%0A%5B3%2C+1%2C+4%2C+10%2C+11%2C+6%2C+0%2C+2%2C+8%2C+9%2C+5%2C+7%5D%0A%5B4%2C+7%2C+5%2C+17%2C+15%2C+8%2C+13%2C+9%2C+10%2C+11%2C+3%2C+19%2C+14%2C+18%2C+1%2C+16%2C+0%2C+12%2C+6%2C+2%5D%0A%5B13%2C+4%2C+16%2C+14%2C+9%2C+17%2C+0%2C+2%2C+3%2C+12%2C+10%2C+15%2C+1%2C+11%2C+8%2C+6%2C+19%2C+5%2C+18%2C+7%5D" rel="nofollow">Try it online.

How it works

  m         map for d in input:
    .u        cumulative fixed-point: starting at N=d, repeatedly replace N with
      @QN       input[N]
              until a duplicate is found, and return all intermediate results
   S          sort
 {          deduplicate
l           length


问:
Leo's Pokerface

Pokerface

Introduction

Leo enjoys playing poker, but his job at Tech Inc. is too demanding for him to learn how to play well. Leo, being a computer scientist, is not discouraged. He decides to take more time than it would have taken to just learn poker, and use it to write a poker bot to help him play better. But now Leo has a problem: in order to understand how to play a bit better, Leo needs to observe multiple games of multiple "people," but the "people" need different play styles to improve the quality and reality of the game.

The Challenge

Leo recalls that there is actually a website dedicated to programming challenges, and is enlisting your help! Your job is to write a program which plays "Pokerface" a modified version of 5-card poker. The program will take input as a 5-card hand in whatever format you wish, after which the program will output:

Exactly (case-sensitive) "true" "1" or "t" if the player wishes to exchange cards, any other non-empty output otherwise.

If true, list of indices of cards and/or card names the player wishes to exchange.

A single number between 0 and 3, which specifies how many additional cards the player wants.

Print out the hand the player wishes to use.

(See formatting below)

Pokerface rules

Since pokerface is a text-based adventure game, cards must be presented in a consistent way. Cards are represented by two character codes, the first character is the suit, and the second is the name of the card.

Cards:

2-9 = 2-9

10 = T

Jack = J

Queen = Q

King = K

Ace = A

Suits:

Spades = S

Clubs = C

Hearts = H

Diamond = D

So the ace of spades would be SA, the 10 of hearts is HT, the 4th of diamonds is D4, etc.

A single round of Pokerface consists of four steps:

The deck is reshuffled and a five card hand is dealt to each player.

Each player is given the chance to exchange as many cards as they want.

Each player is given the chance to gain up to three more cards.

Each player must reveal their best hand.

The best hand wins, and gains that player a point. In the event of a tie, both players get a point.

In a single game, ten rounds are played and the player with the most points wins and gains a single "win point." In the event of a tie, both players gain a win point.

Leo doesn't really have a large amount of money, so your bot can assume that this is a perfect world with no betting.

Hands

Hands are exactly 5 cards in length (initial input and final output).

Hands are ranked consistent with the rules described here.

Input / Output

Leo only knows Java, so your program must be executable via the Process API (command line), and use STDIN and STDOUT for input and output, respectively.

For each step of input and output detailed above, the input and output must each exist on one line.

There must be at least one trailing new line after the final output. (This is due to the way input is read from STDIN)

No extraneous input/output is allowed, other than trailing and leading spaces. The parser simply does not understand things like final_hand=... or draw 0.

When drawing, output is a single integer, when exchanging output is a list of integers and/or cards defined below, and when being dealt the original hand, output is a list of cards defined below.

All input/output numbers must be positive integers in base 10.

You may define the format for card input (see post format below).

True is defined as exactly "true," "1" or "t" and false is any other non-empty value.

During the exchange step:

Card indices must be output with at least one space between them (e.g. 3  4    0)

Card names must be output with at least one space between them (e.g. H4 S8)

Card names and indices may be mixed in the output (e.g. 0 H7 3 D3)

Trailing and leading spaces are allowed.

The input as a result of the player outputting the above will be formatted as specified by the bot.jlsc file, in the same order as requested

The number of cards a player wants to add to their hand can have leading and trailing spaces.

Hands must be output with at least one space between them (e.g. H4 D5  CA), trailing spaces and leading spaces are allowed.

Hands do not need to be output in proper order (e.g. H4 D4 C4 DA SA and H4 DA D4 SA C4 both represent 4, 4, 4, Ace, Ace, which is a full house).

If you wish to build a strategy by analyzing opponents hands, you may store data in a <botname>/data directory.

After competing bots have displayed their hands, they will be written to every bots data directory, in hands.txt, with each hand on a new line (separated by \n). The file will be encoded in US_ASCII.

After your bot requests new cards or exchange cards, the cards will be input depending on what format you specify in the bot.jlsc file.

Post Format

Every post must include two things:

The source code of your bot, or a link to a public facing repository.

A zip file containing:

The compiled/executable version of your bot (If the file is a .exe or other non-de-compilable file, please just include compilation instructions in your post).

A bot.jlsc file, see below (side note: the .jlsc extension is just because of a side project of mine, a configuration format. The file below matches the proper syntax, so don't worry).

The .zip file must be named the same as your bot.

If you don't have access to windows or some other zipping utility, or can't make a .zip for whatever reason, just include the text of the bot.jlsc file in your post

bot.jlsc file:

```<code>name= "Botty"
link= "example.com"
cmd= "java -jar Botty.jar"
input_hand= "${0} ${1} ${2} ${3} ${4}"
input_1= "${0}"
input_2= "${0} ${1}"
input_3= "${0} ${1} ${2}"
input_4= "${0} ${1} ${2} ${3}"
</code>```

Where:

"cmd" is the windows command line command to run your bot. Note that your bot will be in directory <botname>, so adjust the command accordingly.

"name" is the name of your bot.

"link" is the link to your answer, you'll have to edit this in after posting.

"input_hand" is how you want the original dealing to be formatted (with ${#} representing cards 0-4).

"input_1" is how you want the input of one additional card to be formatted.

"input_2" is how you want the input of two additional cards to be formatted.

"input_3" is how you want the input of three additional cards to be formatted.

"input_4" is how you want the input of four additional cards to be formatted.

Specifics

These loopholes are disallowed (see 'common pitfalls')

You may not write a bot the will always output the best hand possible, every time, within the rule set. (i.e. no long-running brute-force bots, nothing should be quite as 'good' as LeoBot)

Your bot should run in ~100 ms or less (Lenient on this point, max of ~1 second)

Any output of the bot after its chosen hand will be ignored.

Standard loopholes are disallowed.

Yes, I know linux is better, but I have a windows PC, so be sure the compiled/executable version of your program can be run from the windows command line.

I already have python and java installed on my computer, but I'm willing to update to new versions and install other environments, so please specify what type of environment your program requires.

You may not write a bot which does the same thing as another bot in every case. Spam bots are allowed, but discouraged.

Your bot may only use cards it has. Cards lost through exchange or not dealt to begin with are invalid output in the final hand.

Input and output may only contain ASCII characters.

Tournaments

Tournaments will be run when I get the time (my schedule is nearly as packed as Leo's, so this my be a little infrequent. Sorry for the inconvenience.).

Bots will be pit against eachother in 4 person games, and there will be one game for each possible subset of bots (i.e. lots of games).

This process will be repeated five times.

Due to the way the tournament handler makes the groups of bots, up to three filler bots will be added to make the number of bots divisible by 4. These bots will simply return the hand they were originally dealt.

After every round and game is run, the scores of the bots will be computed based on the number games they won.

Multiple bots can share a position (ties for first won by first posted).

After a tournament finishes, the scores will be appended to the bottom of this post.

Scoring

Normal KoTH rules. The bot(s) that win the most games win the challenge.

LeoBot

Leo's bot is pretty smart. It doesn't exchange any cards, that's too hard, but it does request the maximum number of additional cards, and it determines the best possible hand it can make, and plays that hand. The main logic of leobot is below.

```<code>package com.gmail.socraticphoenix.pokerface.leobot;

import com.gmail.socraticphoenix.pokerface.lib.card.Card;
import com.gmail.socraticphoenix.pokerface.lib.card.Deck;
import com.gmail.socraticphoenix.pokerface.lib.rule.HandRegistry;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class LeoBot {

    public static void main(String[] args) {
        List<Card> hand = new ArrayList<>();

        Scanner scanner = new Scanner(System.in);
        hand.addAll(Card.parseHand(scanner.nextLine()));
        System.out.println(false);

        System.out.println(3);
        hand.addAll(Card.parseHand(scanner.nextLine()));

        List<List<Card>> possibleHands = LeoBot.getSubsets(hand, 5);
        System.out.println(Deck.toString(possibleHands.stream().sorted((a, b) -> HandRegistry.determineWinner(b, a).comparable()).findFirst().get()));
    }

    private static <T> void getSubsets(List<T> superSet, int k, int idx, List<T> current, List<List<T>> solution) {
        if (current.size() == k) {
            solution.add(new ArrayList<>(current));
            return;
        }
        if (idx == superSet.size()) return;
        T x = superSet.get(idx);
        if (!current.contains(x)) {
            current.add(x);
        }
        getSubsets(superSet, k, idx + 1, current, solution);
        current.remove(x);
        getSubsets(superSet, k, idx + 1, current, solution);
    }

    public static <T> List<List<T>> getSubsets(List<T> superSet, int k) {
        List<List<T>> res = new ArrayList<>();
        getSubsets(superSet, k, 0, new ArrayList<T>(), res);
        return res;
    }

}
</code>```

Note that if LeoBot consistently wins the tournaments, and there are a good amount of entries, I'll stop including him in the running.

Important Links

Tournament bot and library

Leo's bot

Disclaimer

Leo and Tech Inc. are story elements and any resemblance to real-life companies or people is purely unintentional. (However, when Leo's 'situation' adds or subtracts conditions from the question, those are actually part of the question...)

答:
(Python), Pairbot, not quite competing (I don't know how to make cmd commands and stuff)

Pairbot will compete as soon as someone assists with the bot.jlsc, and zip files etc.

Pairbot knows that you don't always get good hands. He knows good hands are rare. Pairbot knows pairs and other duplicates are some of the best hands. Pairbot also knows the lowest hand you can get is a seven high, so he knows if he has 6 high, that's actually a straight (pairbot doesn't know why he knows that). He also knows if his lowest card is 10, (with no pairs), that's also a straight (pairbot knows he can get royal flush this way). Pairbot checks mainly for same number dupes, but also checks for two types of straights in special cases.

```<code>card_values={"2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8,
             "9":9, "T":10, "J":11, "Q":12, "K":13, "A":14,}
straight=False
def card_valuing(item):
    return card_values[item[1]]

input_list=input().split()
pairs_to_keep=[]
for item in input_list:
    if sum(item[1]==card[1] for card in input_list)>1:
        pairs_to_keep+=[item]
cards_to_remove=input_list
for item in pairs_to_keep:cards_to_remove.remove(item)#we want to remove all non pairs
hand=pairs_to_keep
if pairs_to_keep==[]:
    input_list.sort(key=card_valuing, reverse=True)
    if card_values[input_list[0][1]]==6:
        straight=True
        hand=input_list
    elif card_values[input_list[-1][1]]==10:
        straight=True
        hand=input_list
    else:
        print("true\n"+" ".join(input_list[1:]))
        hand+=input_list[0]+input().split()
elif input_list!=[]:
    print("true\n"+" ".join(input_list))
    hand+=input().split()
else:print(0, end=', ')
if straight:print("0\n0\n"+" ".join(hand))
else:
    print("3")
    hand+=input().split()
    same_number_dict={} #holds the amount of each type (A, 2, 3, etc.)

    def dict_value(item):
        return int(same_number_dict[item[1]])*100+card_values[item[1]]

    for card in hand:
        same_number_dict[card[1]]=sum(card[1] == item[1] for item in hand)

    hand=list(sorted(hand, key=dict_value, reverse=True))
    final_hand =[]
    last_number=hand[0][1]
    hand_taken=0
    while hand_taken < 5:
        if last_number==hand[0][1]:
            final_hand+=[hand[0]]
            hand=hand[1:]
            hand_taken+=1
        else:
            for card in hand:
                if same_number_dict[card[1]]>5-hand_taken:
                    same_number_dict[card[1]]=5-hand_taken
            hand=list(sorted(hand, key=dict_value, reverse=True))
            last_number=hand[0][1]
    print(" ".join(final_hand))
</code>```

Format for input is the same as in the example: separated by spaces

If Socratic Phoenix could assist with the file stuffs, that would be good

Title: Leo's Pokerface

Body:
(Python), Pairbot, not quite competing (I don't know how to make cmd commands and stuff)

Pairbot will compete as soon as someone assists with the bot.jlsc, and zip files etc.

Pairbot knows that you don't always get good hands. He knows good hands are rare. Pairbot knows pairs and other duplicates are some of the best hands. Pairbot also knows the lowest hand you can get is a seven high, so he knows if he has 6 high, that's actually a straight (pairbot doesn't know why he knows that). He also knows if his lowest card is 10, (with no pairs), that's also a straight (pairbot knows he can get royal flush this way). Pairbot checks mainly for same number dupes, but also checks for two types of straights in special cases.

card_values={"2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8,
             "9":9, "T":10, "J":11, "Q":12, "K":13, "A":14,}
straight=False
def card_valuing(item):
    return card_values[item[1]]

input_list=input().split()
pairs_to_keep=[]
for item in input_list:
    if sum(item[1]==card[1] for card in input_list)>1:
        pairs_to_keep+=[item]
cards_to_remove=input_list
for item in pairs_to_keep:cards_to_remove.remove(item)#we want to remove all non pairs
hand=pairs_to_keep
if pairs_to_keep==[]:
    input_list.sort(key=card_valuing, reverse=True)
    if card_values[input_list[0][1]]==6:
        straight=True
        hand=input_list
    elif card_values[input_list[-1][1]]==10:
        straight=True
        hand=input_list
    else:
        print("true\n"+" ".join(input_list[1:]))
        hand+=input_list[0]+input().split()
elif input_list!=[]:
    print("true\n"+" ".join(input_list))
    hand+=input().split()
else:print(0, end=', ')
if straight:print("0\n0\n"+" ".join(hand))
else:
    print("3")
    hand+=input().split()
    same_number_dict={} #holds the amount of each type (A, 2, 3, etc.)

    def dict_value(item):
        return int(same_number_dict[item[1]])*100+card_values[item[1]]

    for card in hand:
        same_number_dict[card[1]]=sum(card[1] == item[1] for item in hand)

    hand=list(sorted(hand, key=dict_value, reverse=True))
    final_hand =[]
    last_number=hand[0][1]
    hand_taken=0
    while hand_taken < 5:
        if last_number==hand[0][1]:
            final_hand+=[hand[0]]
            hand=hand[1:]
            hand_taken+=1
        else:
            for card in hand:
                if same_number_dict[card[1]]>5-hand_taken:
                    same_number_dict[card[1]]=5-hand_taken
            hand=list(sorted(hand, key=dict_value, reverse=True))
            last_number=hand[0][1]
    print(" ".join(final_hand))

Format for input is the same as in the example: separated by spaces

If Socratic Phoenix could assist with the file stuffs, that would be good


问:
Print/Output the L-phabet
Inspired by George Gibson's Print a Tabula Recta.

You are to print/output this exact text:

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
BBCDEFGHIJKLMNOPQRSTUVWXYZ
CCCDEFGHIJKLMNOPQRSTUVWXYZ
DDDDEFGHIJKLMNOPQRSTUVWXYZ
EEEEEFGHIJKLMNOPQRSTUVWXYZ
FFFFFFGHIJKLMNOPQRSTUVWXYZ
GGGGGGGHIJKLMNOPQRSTUVWXYZ
HHHHHHHHIJKLMNOPQRSTUVWXYZ
IIIIIIIIIJKLMNOPQRSTUVWXYZ
JJJJJJJJJJKLMNOPQRSTUVWXYZ
KKKKKKKKKKKLMNOPQRSTUVWXYZ
LLLLLLLLLLLLMNOPQRSTUVWXYZ
MMMMMMMMMMMMMNOPQRSTUVWXYZ
NNNNNNNNNNNNNNOPQRSTUVWXYZ
OOOOOOOOOOOOOOOPQRSTUVWXYZ
PPPPPPPPPPPPPPPPQRSTUVWXYZ
QQQQQQQQQQQQQQQQQRSTUVWXYZ
RRRRRRRRRRRRRRRRRRSTUVWXYZ
SSSSSSSSSSSSSSSSSSSTUVWXYZ
TTTTTTTTTTTTTTTTTTTTUVWXYZ
UUUUUUUUUUUUUUUUUUUUUVWXYZ
VVVVVVVVVVVVVVVVVVVVVVWXYZ
WWWWWWWWWWWWWWWWWWWWWWWXYZ
XXXXXXXXXXXXXXXXXXXXXXXXYZ
YYYYYYYYYYYYYYYYYYYYYYYYYZ
ZZZZZZZZZZZZZZZZZZZZZZZZZZ
</code>```

(Yes, I typed that by hand)

You are allowed to use all lowercase instead of all uppercase.

However, your choice of case must be consistent throughout the whole text.

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.

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

Your program must not write anything to STDERR.

Standard Loopholes are forbidden.

Your program can output in any case, but it must be printed (not an array or similar).

Scoring

Programs are scored according to bytes, in UTF-8 by default or a different character set of your choice.

Eventually, the answer with the least bytes 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 = 87064; // 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 = 48934; // 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

```

Title: Print/Output the L-phabet

Body:
Ruby, 60 bytes

a=("A".."Z").to_a.join;(0..25).map{|i|puts(a[i]*i+a[i..-1])}


答:
Jelly, <s>12</s> <s>10</s> 9 bytes

```<code>ị³$ÐĿ«/QL
</code>```

Saved 1 byte thanks to @Dennis.

This uses 1-based permutations. It works by applying the permutation repeatedly until it reaches a previous permutation while also keeping its previous values. By keeping track of the changes, it will create the orbit for every value along the columns of that table. Then, by finding either the minimum or maximum of each column, a label for that cycle can be created. Then deduplicate that list of labels and get the length of it which will be the number of disjoint cycles.

Try it here.

Explanation

```<code>ị³$ÐĿ«/QL  Input: permutation p
  $        Chain (ị³) as a monad
 ³           The input p
ị            For each value x, get the value at index x in p
   ÐĿ      Invoke it on p initially, and repeat it on its next value until it returns
           to a previous value and keep track of the results
           This will create a table where each column is the orbit of each value
     «/    Get the minimum value along each column of that table
       Q   Deduplicate
        L  Get the length and return
</code>```

Title: Number of cycles of a permutation

Body:
Jelly, <s>12</s> <s>10</s> 9 bytes

ị³$ÐĿ«/QL

Saved 1 byte thanks to @Dennis.

This uses 1-based permutations. It works by applying the permutation repeatedly until it reaches a previous permutation while also keeping its previous values. By keeping track of the changes, it will create the orbit for every value along the columns of that table. Then, by finding either the minimum or maximum of each column, a label for that cycle can be created. Then deduplicate that list of labels and get the length of it which will be the number of disjoint cycles.

Try it here.

Explanation

ị³$ÐĿ«/QL  Input: permutation p
  $        Chain (ị³) as a monad
 ³           The input p
ị            For each value x, get the value at index x in p
   ÐĿ      Invoke it on p initially, and repeat it on its next value until it returns
           to a previous value and keep track of the results
           This will create a table where each column is the orbit of each value
     «/    Get the minimum value along each column of that table
       Q   Deduplicate
        L  Get the length and return


答:
Mathematica, 45 bytes

```<code>Length@ConnectedComponents@Thread[Sort@#->#]&
</code>```

It generates a graph and counts its connected components.

Title: Number of cycles of a permutation

Body:
Mathematica, 45 bytes

Length@ConnectedComponents@Thread[Sort@#->#]&

It generates a graph and counts its connected components.


问:
Snakes all around

Challenge

The challenge is simple: print a snake.

You will get the length of the snake as input.

A snake of length 2 looks like this:

```<code>==(:)-
</code>```

A snake of length 7 looks like this:

```<code>=======(:)-
</code>```

In other words, the length of a snake is how many equal signs are before the head.

Usage

Let's say I made a C++ implementation and compiled it to ./getsnake.

I could run it like so:

```<code>$ ./getsnake 10
==========(:)-
</code>```

Clarifications

Standard loopholes are disallowed.

You can get input and output in any acceptable way.

You can assume all inputs given are positive integers.

You may write a function instead of a regular program.

Title: Snakes all around

Body:
Ruby, 27 bytes

puts"="*($*[0].to_i)+"(:)-"


答:
Python 2, 94 bytes

import re
s='1'
exec"s+=`3-int(re.search(r'(.*)(.)\\1$',s).groups()[1])`;"*input()
print s[-1]
```

Uses 0-based indexing. Test it on Ideone.

Title: Generate Linus Sequence

Body:
Python 2, 94 bytes

import re
s='1'
exec"s+=`3-int(re.search(r'(.*)(.)\\1$',s).groups()[1])`;"*input()
print s[-1]

Uses 0-based indexing. Test it on Ideone.


答:
Mathematica, 84 bytes

```<code>a@n_:=a@n=First@MinimalBy[{1,2},Array[a,n-1]~Append~#/.{___,b___,b___}:>Length@{b}&]
</code>```

Title: Generate Linus Sequence

Body:
Mathematica, 84 bytes

a@n_:=a@n=First@MinimalBy[{1,2},Array[a,n-1]~Append~#/.{___,b___,b___}:>Length@{b}&]


答:
Pyth, <s>46</s> 29 bytes

Took some inspiration from @Leaky Nun's excellent Pyth answer. Tried to see if there was a shorter way using strings. Still 3 bytes short!

```<code>huh.melM+kf!x>blTT._bm+dGS2Qk
</code>```

You can try it out here.

Title: Generate Linus Sequence

Body:
Pyth, <s>46</s> 29 bytes

Took some inspiration from @Leaky Nun's excellent Pyth answer. Tried to see if there was a shorter way using strings. Still 3 bytes short!

huh.melM+kf!x>blTT._bm+dGS2Qk

You can try it out here.


问:
Draw a Fibonacci Network!

What are Fibonacci networks?

In 1202, an Italian mathematician known as Fibonacci posed the following problem:

"A male and a female rabbit are born at the beginning of the year. We assume the following conditions:

1.After reaching the age of two months, each pair produces a mixed pair, (one male, one female), and then another mixed pair each month thereafter.

2.No deaths occur during the year."

How many rabbits will there be at the end of the year?

Sources for graph and problem statement

Challenge

Your challenge is to write a program/function to draw an ASCII art to output or a text file, or a graphical picture to a file/screen of a graph with following settings:

At 0th tick, there is one newly-born node.

Every newly born node creates a normal node after one tick after being born and gets deactivated.

A normal node creates a normal node and a newly-born node one tick after its birth and gets deactivated.

Your program will get the non-negative value n as input, and will draw the graph at the nth tick. Note that your program can draw newly-born nodes and normal nodes differently, but this is not necessary.

Rules

You must not use any built-in Fibonacci sequence function or mathematical constants or similar.

If your program outputs to a file, it must be either a text file in a suitable and viewable format and encoding, or an image file in a suitable and viewable format with recognizable colors (for example, an image format that can be uploaded to SE).

Your program can draw graph in any size, any shape and any alignment but the nodes and connections must be recognizable. Tree-shaped graphs (like the graph in "What are Fibonacci networks?" section) are recommended, but not necessary.

Common code golf rules apply to this challenge.

Examples

```<code>Input: 2
Possible Output:
*
|
*
| \
* *

Input: 0
Possible Output:
*
</code>```

Input: 5

Possible Graphical Output:

This is a codegolf. Shortest code wins. Good luck!

Title: Draw a Fibonacci Network!

Body:
Pyth, 31 bytes

Ms+0m+Wd+J+G"| "+G1+\-gJtd_UHgb

Try it online

How it works

M                                  def g(G, H):
    m                     _UH        map for d in [H - 1, …, 0]:
         J+G"| "                       assign J = G + "| "
        +       +G1                    J + G + 1
     +Wd                               conditional +, if d is truthy (nonzero):
                   +\-gJtd               "-" + g(J, d - 1)
  +0                                 prepend 0
 s                                   concatenate
                             gbQ   g("\n", input)

Output for 6

0
|
1-0
| |
| 1-0
| | |
| | 1-0
| | |
| | 1
| |
| 1-0
| | |
| | 1
| |
| 1-0
| |
| 1
|
1-0
| |
| 1-0
| | |
| | 1
| |
| 1-0
| |
| 1
|
1-0
| |
| 1-0
| |
| 1
|
1-0
| |
| 1
|
1-0
|
1

Pyth, 43 bytes

Mc+WH`G++WG\-+j"
| "g0tH"
`-"j"
  "g1tHbjg0

Try it online

Output for 6

0-1-0-1-0-1-0
  |   |   `-1
  |   `-1-0-1
  |     `-1-0
  |       `-1
  `-1-0-1-0-1
    |   `-1-0
    |     `-1
    `-1-0-1-0
      |   `-1
      `-1-0-1
        `-1-0
          `-1


答:
Pyth, 26 bytes

```<code>huh.mleq#.<T/lT2._b+RGS2QY
</code>```

Test suite.

Explanation

When n = 6, we choose between 1 2 1 1 2 1 and 1 2 1 1 2 2.

We generate these two possibilities, and then look at their suffixes.

For the first one, the suffixes are: 1, 2 1, 1 2 1, 1 1 2 1, 2 1 1 2 1, 1 2 1 1 2 1.

We filter for doubled suffixes by checking if they are the same after rotating them for their length divided by 2 (it turns out that this check is not perfect, because it confirms 1 and 2 also).

We take the last doubled suffix and then take its length.

We then choose the possibility that corresponds to a minimum length generated above.

Then we proceed to the next value of n.

For the purpose of this program, it was golfier to generate the reversed array instead.

```<code>huh.mleq#.<T/lT2._b+RGS2QY
 u                      QY   repeat Q (input) times,
                             start with Y (empty array),
                             storing the temporary result in G:
                   +RGS2         prepend 1 and 2 to G,
                                 creating two possibilities
   .m             b              find the one that
                                 makes the following minimal:
                ._                   generate all prefixes
       q#                            filter for prefixes as T
                                     that equals:
         .<T/lT2                         T left-rotated
                                         by its length halved
      e                              take the last one
     l                               generate its length
  h                              take the first minimal one
h                                take the first one from the generated
                                 array and implicitly print it out
</code>```

Title: Generate Linus Sequence

Body:
Pyth, 26 bytes

huh.mleq#.<T/lT2._b+RGS2QY

Test suite.

Explanation

When n = 6, we choose between 1 2 1 1 2 1 and 1 2 1 1 2 2.

We generate these two possibilities, and then look at their suffixes.

For the first one, the suffixes are: 1, 2 1, 1 2 1, 1 1 2 1, 2 1 1 2 1, 1 2 1 1 2 1.

We filter for doubled suffixes by checking if they are the same after rotating them for their length divided by 2 (it turns out that this check is not perfect, because it confirms 1 and 2 also).

We take the last doubled suffix and then take its length.

We then choose the possibility that corresponds to a minimum length generated above.

Then we proceed to the next value of n.

For the purpose of this program, it was golfier to generate the reversed array instead.

huh.mleq#.<T/lT2._b+RGS2QY
 u                      QY   repeat Q (input) times,
                             start with Y (empty array),
                             storing the temporary result in G:
                   +RGS2         prepend 1 and 2 to G,
                                 creating two possibilities
   .m             b              find the one that
                                 makes the following minimal:
                ._                   generate all prefixes
       q#                            filter for prefixes as T
                                     that equals:
         .<T/lT2                         T left-rotated
                                         by its length halved
      e                              take the last one
     l                               generate its length
  h                              take the first minimal one
h                                take the first one from the generated
                                 array and implicitly print it out


答:
Mathematica, 56 bytes

```<code>1##&@@@Tuples@Reverse[#^Range[0,#2]&@@@FactorInteger@#]&
</code>```

ContentLicense: CC BY-SA 4.0

Title: Sort a number's divisors by prime factorization

Body:
Given an input of an integer \$n ≥ 2\$, output a list of its divisors sorted by the
exponents in their prime factorizations, in ascending order, ordering first by
the largest prime, then by the second largest, and so on.

As an example, take the integer \$72\$, which is \$2^3\cdot3^2\$. It has
the divisors

```<code>1     3^0 · 2^0
2     3^0 · 2^1
3     3^1 · 2^0
4     3^0 · 2^2
6     3^1 · 2^1
8     3^0 · 2^3
9     3^2 · 2^0
12    3^1 · 2^2
18    3^2 · 2^1
24    3^1 · 2^3
36    3^2 · 2^2
72    3^2 · 2^3
</code>```

When sorted in ascending order by the exponents on the prime factors, with
larger primes taking priority, this becomes

```<code>1     3^0 · 2^0
2     3^0 · 2^1
4     3^0 · 2^2
8     3^0 · 2^3
3     3^1 · 2^0
6     3^1 · 2^1
12    3^1 · 2^2
24    3^1 · 2^3
9     3^2 · 2^0
18    3^2 · 2^1
36    3^2 · 2^2
72    3^2 · 2^3
</code>```

Note that the list is sorted first by the order of the exponent of 3, and then
by the exponent of 2. You can also think of this as reading from left to right
and top to bottom across the following grid:

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

3^0     1    2    4    8
3^1     3    6    12   24
3^2     9    18   36   72
</code>```

Test cases:

```<code>2 => 1 2
72 => 1 2 4 8 3 6 12 24 9 18 36 72
101 => 1 101
360 => 1 2 4 8 3 6 12 24 9 18 36 72 5 10 20 40 15 30 60 120 45 90 180 360
3780 => 1 2 4 3 6 12 9 18 36 27 54 108 5 10 20 15 30 60 45 90 180 135 270 540 7 14 28 21 42 84 63 126 252 189 378 756 35 70 140 105 210 420 315 630 1260 945 1890 3780
30030 => 1 2 3 6 5 10 15 30 7 14 21 42 35 70 105 210 11 22 33 66 55 110 165 330 77 154 231 462 385 770 1155 2310 13 26 39 78 65 130 195 390 91 182 273 546 455 910 1365 2730 143 286 429 858 715 1430 2145 4290 1001 2002 3003 6006 5005 10010 15015 30030
65536 => 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536
74088 => 1 2 4 8 3 6 12 24 9 18 36 72 27 54 108 216 7 14 28 56 21 42 84 168 63 126 252 504 189 378 756 1512 49 98 196 392 147 294 588 1176 441 882 1764 3528 1323 2646 5292 10584 343 686 1372 2744 1029 2058 4116 8232 3087 6174 12348 24696 9261 18522 37044 74088
</code>```

Since this is code-golf, the shortest code in bytes wins.

Body:
Mathematica, 56 bytes

1##&@@@Tuples@Reverse[#^Range[0,#2]&@@@FactorInteger@#]&


答:
Jelly, <s>25</s> <s>24</s> <s>22</s> 20 bytes

2 bytes thanks to Dennis.

```<code>2;€µḣJf;`€$ṪLµÞḢ
Ç¡Ḣ
</code>```

Try it online!

A port of my answer in Pyth.

```<code>Ç¡Ḣ   Main chain

 ¡    Repeat for (input) times:
Ç         the helper chain
  Ḣ   Then take the first element

2;€µḣJf;`€$ṪLµÞḢ  Helper chain, argument: z

2;€               append z to 1 and 2, creating two possibilities
   µ         µÞ   sort the possibilities by the following:
    ḣJ                generate all prefixes from shortest to longest
       ;`€            append the prefixes to themselves
      f   $           intersect with the original set of prefixes
           Ṫ          take the last prefix in the intersection
            L         find its length
                 Ḣ   take the first (minimum)
</code>```

Title: Generate Linus Sequence

Body:
Jelly, <s>25</s> <s>24</s> <s>22</s> 20 bytes

2 bytes thanks to Dennis.

2;€µḣJf;`€$ṪLµÞḢ
Ç¡Ḣ

Try it online!

A port of my answer in Pyth.

Ç¡Ḣ   Main chain

 ¡    Repeat for (input) times:
Ç         the helper chain
  Ḣ   Then take the first element

2;€µḣJf;`€$ṪLµÞḢ  Helper chain, argument: z

2;€               append z to 1 and 2, creating two possibilities
   µ         µÞ   sort the possibilities by the following:
    ḣJ                generate all prefixes from shortest to longest
       ;`€            append the prefixes to themselves
      f   $           intersect with the original set of prefixes
           Ṫ          take the last prefix in the intersection
            L         find its length
                 Ḣ   take the first (minimum)


问:
Create and write to a file

Challenge

Create a new file and write the string Hello World to it.

Restrictions

Your challenge must write to a file on disk, in the file system.

The file may not be a log file generated during normal operation of the interpreter.

The file must contain only the string Hello World. It is allowed to contain a trailing newline or minimal whitespace. No other content.

No command-line flags/pipes (etc) allowed, except when necessary to run the program. (e.g. perl -p)

Notes

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

Follow the spirit, not the letter, of the rules.

答:
PHP, 27 bytes

```<code>exec('echo Hello World>o');
</code>```

PHP, 20 bytes

```<code>`echo Hello World>o`
</code>```

Title: Create and write to a file

Body:
PHP, 27 bytes

exec('echo Hello World>o');

PHP, 20 bytes

`echo Hello World>o`


问:
Code Golf: 6174 - Kaprekar's mythical constant
Why is the number 6174 so interesting? As defined by Wikipedia

Take any four-digit number, using at
  least two different digits. (Leading
  zeros are allowed.)

Arrange the digits in ascending and
  then in descending order to get two
  four-digit numbers, adding leading
  zeros if necessary.

Subtract the smaller number from the
  bigger number.

Go back to step 2.

The above process, known as Kaprekar's
  routine, will always reach 6174 in at
  most 7 iterations. Once 6174 is
  reached, the process will continue
  yielding it.

Write a program which runs the Kaprekar's routine against a given four-digit number (see definition above) printing out each step of the routine.

Rules:

Submissions must be complete
programs.

Input must be read from standard
input. Piping from echo is OK.

Input should be in numeric form.

Printing out leading zeros is
required. (See examples below.)

Last line should say how many
iterations were needed. Punctuation is required.

Examples:

```<code>> 2607
7620 - 0267 = 7353
7533 - 3357 = 4176
7641 - 1467 = 6174
Iterations: 3.

> 1211
2111 - 1112 = 0999
9990 - 0999 = 8991
9981 - 1899 = 8082
8820 - 0288 = 8532
8532 - 2358 = 6174
Iterations: 5.

> 6174
7641 - 1467 = 6174
Iterations: 1.
</code>```

Any programming language is welcome. Extra points for esoteric ones + a small bounty.

Update 1: There is already a similar question.

Update 2: Added example for 6174 as input. Thanks to Peter Taylor for the notice.

OwnerDisplayName: lunohodov

Body:
K, 104

{b::();{b,:,k," = ",r:"0"^(-:4)$$. k:(x@>x)," - ",x@<x;r}\[$x];-1'c,,"Iterations: ",$#c:$[1=#b;b;-1_b];}

Test cases

k){b::();{b,:,k," = ",r:"0"^(-:4)$$. k:(x@>x)," - ",x@<x;r}\[$x];-1'c,,"Iterations: ",$#c:$[1=#b;b;-1_b];}'2607 1211 6174;
7620 - 0267 = 7353
7533 - 3357 = 4176
7641 - 1467 = 6174
Iterations: 3
2111 - 1112 = 0999
9990 - 0999 = 8991
9981 - 1899 = 8082
8820 - 0288 = 8532
8532 - 2358 = 6174
Iterations: 5
7641 - 1467 = 6174
Iterations: 1


答:
Mathematica, <s>37</s> <s>28</s> 27 bytes

```<code>#~PermutationCycles~Length&
</code>```

Thanks @alephalpha for saving 9 bytes, and @miles for 1 more byte.

Title: Number of cycles of a permutation

Body:
Consider a permutation of the integers 1, ..., n, such as this one for n = 6:

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

If you view the permutation as a mapping from [1,2,3,4,5,6] to [5,2,4,3,6,1], the permutation can be decomponsed into disjoint cycles. A cycle is a subset of elements that map to each other. For example, 1 gets mapped to 5, which gets mapped to 6, which gets mapped back to 1. So one cycle is [1,5,6]. The other cycles are [2] and [3,4]. Thus the number of cycles for this permutation is 3.

In general, the cycles of a permutation are unique (up to order), and the number of cycles for a permutation of size n varies from 1 to n.

The challenge

Given a non-empty permutation, output its number of cycles.

Input is an array formed by the n integers 1, 2, ..., n, where n > 0. Each integer occurs exactly once. The order in which they appear defines the permutation, as in the example above.

Instead of an array you can use a list, a string with a separator between the numbers, a separate input for each number, or anything that's reasonable.

For a permutation of size n, instead of the 1-based set of integers 1, ..., n you can consistently use the 0-based set 0, ..., n-1. If so, please indicate it in your answer.

The code should work for n up to 20 in a reasonable time, say less than one minute.

Code golf. All builtins allowed.

Test cases

This assumes 1-based, array input.

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

Related

This related challenge asks for the actual cycles of the permutation, not the number of them. Requiring only the number of cycles can lead to shorter algorithms that sidestep generating the actual cycles.

Body:
Mathematica, <s>37</s> <s>28</s> 27 bytes

#~PermutationCycles~Length&

Thanks @alephalpha for saving 9 bytes, and @miles for 1 more byte.