答:
Perl, 40 bytes

$a.=/(.*)(.)\1$/^$2for($a)x$_;$_=$a%5+1
```

The code is 39 bytes long and requires the -p switch (+1 byte).

The loop is inspired by the Perl solution on the relevant OEIS page, although I did come up independently with the regular expression.

Test it on Ideone.

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:
Perl, 40 bytes

$a.=/(.*)(.)\1$/^$2for($a)x$_;$_=$a%5+1

The code is 39 bytes long and requires the -p switch (+1 byte).

The loop is inspired by the Perl solution on the relevant OEIS page, although I did come up independently with the regular expression.

Test it on Ideone.


问:
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...)

答:
LuckyBot, Python

Pairbot invited his buddy Luckybot, who sprang for the chance. Luckybot had watched a lot of fictional poker, and reckoned he'd figured out the secret to poker: luck. Everyone knows the real pros (James Bond, for example) really rely and getting good hands, not skill. Hence, he doesn't look at his cards, and tries to pack as much good luck into them as possible

```<code>lucky_number=24 #IMPORTANT

from random import randint as roll

def lucky_shuffle(i):
    return sorted(i, key=lucky_dice)

def lucky_dice(seed):
    return sum(roll(1,6)for i in range(roll(1,6)))

hand=lucky_shuffle(input().split())

throw=lucky_dice(lucky_number)%5
print("true\n"+" ".join(hand[throw:]))

hand=hand[:throw]+lucky_shuffle(input().split())

hand=lucky_shuffle(hand)
hand=lucky_shuffle(hand)
#One more for good luck
hand=lucky_shuffle(hand)
#maybe one more
hand=lucky_shuffle(hand)
#I got a good feeling about this one
hand=lucky_shuffle(hand)

hand=lucky_shuffle(hand)
#I think I'm done
hand=lucky_shuffle(hand)
#for real this time

hand=lucky_shuffle(hand)

print("3")
hand=hand+lucky_shuffle(input().split())
#All right, I got a real good feeling about this,
#let me shuffle some more luck into them cards!

def extra_super_lucky_shuffle(item):
 return lucky_shuffle(lucky_shuffle(lucky_shuffle(\
    lucky_shuffle(lucky_shuffle(lucky_shuffle(\
        lucky_shuffle(lucky_shuffle(lucky_shuffle(item)))))))))

def super_duper_extra_ultra_uber_luckyshuffle(item):
    return extra_super_lucky_shuffle(extra_super_lucky_shuffle(\
        extra_super_lucky_shuffle(extra_super_lucky_shuffle(item))))

hand=super_duper_extra_ultra_uber_luckyshuffle(super_duper_extra_ultra_uber_luckyshuffle(hand))
#cmoooooooooooooooon
print(hand[:5])
</code>```

ContentLicense: CC BY-SA 3.0

Title: Leo's Pokerface

Body:
LuckyBot, Python

Pairbot invited his buddy Luckybot, who sprang for the chance. Luckybot had watched a lot of fictional poker, and reckoned he'd figured out the secret to poker: luck. Everyone knows the real pros (James Bond, for example) really rely and getting good hands, not skill. Hence, he doesn't look at his cards, and tries to pack as much good luck into them as possible

lucky_number=24 #IMPORTANT

from random import randint as roll

def lucky_shuffle(i):
    return sorted(i, key=lucky_dice)

def lucky_dice(seed):
    return sum(roll(1,6)for i in range(roll(1,6)))

hand=lucky_shuffle(input().split())

throw=lucky_dice(lucky_number)%5
print("true\n"+" ".join(hand[throw:]))

hand=hand[:throw]+lucky_shuffle(input().split())

hand=lucky_shuffle(hand)
hand=lucky_shuffle(hand)
#One more for good luck
hand=lucky_shuffle(hand)
#maybe one more
hand=lucky_shuffle(hand)
#I got a good feeling about this one
hand=lucky_shuffle(hand)

hand=lucky_shuffle(hand)
#I think I'm done
hand=lucky_shuffle(hand)
#for real this time

hand=lucky_shuffle(hand)

print("3")
hand=hand+lucky_shuffle(input().split())
#All right, I got a real good feeling about this,
#let me shuffle some more luck into them cards!

def extra_super_lucky_shuffle(item):
 return lucky_shuffle(lucky_shuffle(lucky_shuffle(\
    lucky_shuffle(lucky_shuffle(lucky_shuffle(\
        lucky_shuffle(lucky_shuffle(lucky_shuffle(item)))))))))

def super_duper_extra_ultra_uber_luckyshuffle(item):
    return extra_super_lucky_shuffle(extra_super_lucky_shuffle(\
        extra_super_lucky_shuffle(extra_super_lucky_shuffle(item))))

hand=super_duper_extra_ultra_uber_luckyshuffle(super_duper_extra_ultra_uber_luckyshuffle(hand))
#cmoooooooooooooooon
print(hand[:5])


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

答:
Retina, <s>51</s> 42 bytes

9 bytes thanks to Martin Ender.

```<code>.+
$*x
+`((.*)(^|2|(?<3>1))\2)x
$1$#3
!`.$
</code>```

Try it online!

A port of this answer.

Title: Generate Linus Sequence

Body:
Retina, <s>51</s> 42 bytes

9 bytes thanks to Martin Ender.

.+
$*x
+`((.*)(^|2|(?<3>1))\2)x
$1$#3
!`.$

Try it online!

A port of this answer.


问:
Hofstadter H-sequence

Definition

\$a(0) = 0\$

\$a(n) = n-a(a(a(n-1)))\$ for integer \$n > 0\$

Task

Given non-negative integer \$n\$, output \$a(n)\$.

Testcases

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

References

WolframMathWorld

OEIS A005374

答:
Python 3, 72 bytes

def f(n):
    a=[0];i=0
    while n:i+=1;a+=[i-a[a[a[i-i]]]];n-=1
    return a[i]
```

Ideone it!

ContentLicense: CC BY-SA 4.0

Title: Hofstadter H-sequence

Body:
Python 3, 72 bytes

def f(n):
    a=[0];i=0
    while n:i+=1;a+=[i-a[a[a[i-i]]]];n-=1
    return a[i]

Ideone it!


答:
Python, 31 bytes

a=lambda n:n and n-a(a(a(n-1)))
```

Recursion limit and time constraints make above function impractical, but in theory it should work (and does work for small n).

Title: Hofstadter H-sequence

Body:
Definition

\$a(0) = 0\$

\$a(n) = n-a(a(a(n-1)))\$ for integer \$n > 0\$

Task

Given non-negative integer \$n\$, output \$a(n)\$.

Testcases

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

References

WolframMathWorld

OEIS A005374

Body:
Python, 31 bytes

a=lambda n:n and n-a(a(a(n-1)))

Recursion limit and time constraints make above function impractical, but in theory it should work (and does work for small n).


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

```

答:
F#, 70 bytes

```<code>for i in 'A'..'Z'do(for j in 'A'..'Z'do printf"%c"(max i j));printfn""
</code>```

Pretty straightforward.

Title: Print/Output the L-phabet

Body:
F#, 70 bytes

for i in 'A'..'Z'do(for j in 'A'..'Z'do printf"%c"(max i j));printfn""

Pretty straightforward.


答:
Jelly, 8 bytes

```<code>’ßßßạµṠ¡
</code>```

Try it online! or verify the smaller test cases.

How it works

```<code>’ßßßạµṠ¡  Main link. Argument: n

     µṠ¡  Execute the preceding chain sign(n) times.
’         Decrement n, yielding n - 1.
 ßßß      Recursively call the main link thrice.
    ạ     Take the absolute difference of n and the result.
</code>```

Title: Hofstadter H-sequence

Body:
Jelly, 8 bytes

’ßßßạµṠ¡

Try it online! or verify the smaller test cases.

How it works

’ßßßạµṠ¡  Main link. Argument: n

     µṠ¡  Execute the preceding chain sign(n) times.
’         Decrement n, yielding n - 1.
 ßßß      Recursively call the main link thrice.
    ạ     Take the absolute difference of n and the result.


问:
Score a game of Bowling
Your task is to sum up and output one player's score in a game of 10-pin bowling after up to 21 rolls.

The rolls are represented as a sequence of integers in your preferred method of input.
Each integer corresponds to the number of pins that were knocked down in that roll.

Scoring

After each round the number of pins knocked down in that round is counted into the final score.
If a player knocks down all ten pins in the first roll of a round, this is a strike, and the round is over.
Otherwise, the round lasts for one more roll. If the second roll of a round knocks down all the remaining pins, this is a spare.

For each strike there is a bonus equal to the sum of pins knocked down in the two next rolls.
For each spare there is a bonus equal to the number of pins knocked down in the next roll.

The 10th and final round, the player may be granted extra rolls:
In case of a strike, the player gets two more rolls to make up his strike bonus.
In case of a spare, the player gets one more roll.

Examples

```<code>Input: 4 3 8 2 7 1 10 7 3 0 10 2 2 10 10 5 4
Output: 131

Input: 10 10 9 1 7 3 2 7 10 1 9 10 7 1 10 10 10
Output: 183
</code>```

Rules

You may assumed that the input is valid.

As per Mego's comment I have loosened the requirements for the input/output methods to meet our current standard.

Answers in languages that are newer than the challenge are allowed

Shortest code wins!

答:
Ruby, 252 bytes

Accepts input into an array add all elements first, then searches for spare and strike bonus

```<code>s,p,t,r=0,0,1,1
o=ARGV
o.each_with_index do |m,n|
y=m.to_i
s+=y
if r<10
p+=y
if p==10&&t==1
r,p=(r+1),0
s+=o[n+1].to_i+o[n+2].to_i
elsif p<10&&t==1
t=2
elsif p<10&&t==2
t,p,r=1,0,(r+1)
elsif p==10&&t==2
t,p,r=1,0,(r+1)
s+=o[n+1].to_i
end end end
puts s
</code>```

Title: Score a game of Bowling

Body:
Ruby, 252 bytes

Accepts input into an array add all elements first, then searches for spare and strike bonus

s,p,t,r=0,0,1,1
o=ARGV
o.each_with_index do |m,n|
y=m.to_i
s+=y
if r<10
p+=y
if p==10&&t==1
r,p=(r+1),0
s+=o[n+1].to_i+o[n+2].to_i
elsif p<10&&t==1
t=2
elsif p<10&&t==2
t,p,r=1,0,(r+1)
elsif p==10&&t==2
t,p,r=1,0,(r+1)
s+=o[n+1].to_i
end end end
puts s


问:
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.

答:
JavaScript, <s>99</s> 98 bytes

This solution assumes the array and its values are zero-indexed (e.g. [2, 1, 0]).

f=a=>{h={},i=c=0;while(i<a.length){s=i;while(!h[i]){h[i]=1;i=a[i]}c++;i=s;while(h[++i]);}return c}
```
<p><strong>Explanation</strong></p>
<pre class="lang-js prettyprint-override"><code>// assumes the array is valid and zero-indexed
var findCycles = (array) => {
    var hash = {};  // remembers visited nodes
    var index = 0;  // current node
    var count = 0;  // number of cycles
    var start;      // starting node of cycle

    // loop until all nodes visited
    while(index < array.length) {
        start = index;  // cache starting node

        // loop until found previously visited node
        while(!hash[index]) {
            hash[index] = 1;    // mark node as visited
            index = array[index];   // get next node
        }
        count++;    // increment number of cycles

        index = start + 1;  // assume next node is right after

        // loop until found unvisited node
        while(hash[index]) {
            index++;    // get next node
        }
    }

    return count;   // return number of cycles
};
</code>```

Title: Number of cycles of a permutation

Body:
JavaScript, <s>99</s> 98 bytes

This solution assumes the array and its values are zero-indexed (e.g. [2, 1, 0]).

f=a=>{h={},i=c=0;while(i<a.length){s=i;while(!h[i]){h[i]=1;i=a[i]}c++;i=s;while(h[++i]);}return c}

Explanation

// assumes the array is valid and zero-indexed
var findCycles = (array) => {
    var hash = {};  // remembers visited nodes
    var index = 0;  // current node
    var count = 0;  // number of cycles
    var start;      // starting node of cycle

    // loop until all nodes visited
    while(index < array.length) {
        start = index;  // cache starting node

        // loop until found previously visited node
        while(!hash[index]) {
            hash[index] = 1;    // mark node as visited
            index = array[index];   // get next node
        }
        count++;    // increment number of cycles

        index = start + 1;  // assume next node is right after

        // loop until found unvisited node
        while(hash[index]) {
            index++;    // get next node
        }
    }

    return count;   // return number of cycles
};


答:
Julia, 16 bytes

!n=n>0&&n-!!!~-n
```

Try it online!

How it works

We redefine the unary operator ! for our purposes.

If n = 0, the comparison n>0 returns false and so does !.

Otherwise, the code after && gets executed. ~-n is equivalent to (n-1) in two's complement, !!! recursively calls ! thrice on n - 1, and the resulting value is subtracted from n.

Title: Hofstadter H-sequence

Body:
Julia, 16 bytes

!n=n>0&&n-!!!~-n

Try it online!

How it works

We redefine the unary operator ! for our purposes.

If n = 0, the comparison n>0 returns false and so does !.

Otherwise, the code after && gets executed. ~-n is equivalent to (n-1) in two's complement, !!! recursively calls ! thrice on n - 1, and the resulting value is subtracted from n.


问:
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.

答:
J, 14 bytes

```<code>'(:)-',~'='#~]
</code>```

Very simple. This is a five train:

```<code>'(:)-' ,~ '=' #~ ]
</code>```

Both strings, in this case, become constant verbs. #~ essentially repeats its left argument the amount of times as its right argument. ,~ then appends its left argument to the end of its right argument.

Test cases:

```<code>   f 2
==(:)-
   f 7
=======(:)-
   f 10
==========(:)-
   f 0
(:)-
</code>```

I think that it would look more snake-like with a tilde at the end, but eh.

Title: Snakes all around

Body:
J, 14 bytes

'(:)-',~'='#~]

Very simple. This is a five train:

'(:)-' ,~ '=' #~ ]

Both strings, in this case, become constant verbs. #~ essentially repeats its left argument the amount of times as its right argument. ,~ then appends its left argument to the end of its right argument.

Test cases:

   f 2
==(:)-
   f 7
=======(:)-
   f 10
==========(:)-
   f 0
(:)-

I think that it would look more snake-like with a tilde at the end, but eh.


答:
Haskell, <s>23</s> 22 bytes

f 0=0
f n=n-f(f$f$n-1)
```

<p>Simply uses the definition of the sequence. <code>f(f$f$n-1)</code> is equivalent to <code>f (f (f (n-1)))</code>.</p>

<p>Test:</p>

<pre class="lang-hs prettyprint-override"><code>main = putStrLn . show $ map f [0..20]
-- => [0,1,1,2,3,4,4,5,5,6,7,7,8,9,10,10,11,12,13,13,14]
</code>```

Thanks to Anders Kaseorg for a byte!

Title: Hofstadter H-sequence

Body:
Haskell, <s>23</s> 22 bytes

f 0=0
f n=n-f(f$f$n-1)

Simply uses the definition of the sequence. f(f$f$n-1) is equivalent to f (f (f (n-1))).

Test:

main = putStrLn . show $ map f [0..20]
-- => [0,1,1,2,3,4,4,5,5,6,7,7,8,9,10,10,11,12,13,13,14]

Thanks to Anders Kaseorg for a byte!


答:
J, <s>14</s> 12 bytes

```<code>-$:^:3@<:^:*
</code>```

Saved 2 bytes thanks to @Leaky Nun.

Computes the result by calling itself recursively when n > 0 three times on n-1 and subtracting that result from n. There is a different situation for the base case when n = 0. There it computes n-n which equals 0.

```<code>a(n) = n - n = 0           if n = 0
       n - a(a(a(n-1)))    if n > 0
</code>```

Try it here.

Explanation

```<code>-$:^:3@<:^:*  Input: n
           *  Get the sign of n (n = 0 => 0, n > 0 => 1)
         ^:   Execute that many times
                (0 times means it will just be an identity function)
       <:       Decrement n
 $:             Call itself recursively
   ^:3          three times
      @         on n-1
-             Subtract that result from n and return
</code>```

Title: Hofstadter H-sequence

Body:
J, <s>14</s> 12 bytes

-$:^:3@<:^:*

Saved 2 bytes thanks to @Leaky Nun.

Computes the result by calling itself recursively when n > 0 three times on n-1 and subtracting that result from n. There is a different situation for the base case when n = 0. There it computes n-n which equals 0.

a(n) = n - n = 0           if n = 0
       n - a(a(a(n-1)))    if n > 0

Try it here.

Explanation

-$:^:3@<:^:*  Input: n
           *  Get the sign of n (n = 0 => 0, n > 0 => 1)
         ^:   Execute that many times
                (0 times means it will just be an identity function)
       <:       Decrement n
 $:             Call itself recursively
   ^:3          three times
      @         on n-1
-             Subtract that result from n and return


问:
How Many Rectangles in the Grid?

Well, although this challenge turned out to be a huge success, it also turned out to be very trivial to solve. Therefore, for those of looking for more of a challenge, I created a sequel to this challenge in which you must now count the number of unique rectangles. Check it out!

Now, for those of you looking to solve this challenge, here it comes.

Well, we don't really have a challenge like this yet, so here we go.

Consider this 3 x 3 grid of rectangles:

How many rectangles are there? Well, counting visually, we can see that there are actually 36 rectangles, including the entire plane itself, which are all shown in the animated GIF below:

The Task

The counting of rectangles as shown above is the task. In other words, given 2 integers greater than or equal to 0, m and n, where m represents the width and n represents the height, output the total number of rectangles in that m x n grid of rectangles.

Rules

The use of any built-ins that directly solve this problem is explicitly disallowed.

This challenge is not about finding the shortest answer, but finding the shortest answer in every language. Therefore, no answer will be accepted.

Standard loopholes are prohibited.

Test Cases

Presented in the format Array of Integers Input -> Integer Output:

```<code>[0,0] -> 0
[1,1] -> 1
[3,3] -> 36 (Visualized above)
[4,4] -> 100
[6,7] -> 588
</code>```

References

http://oeis.org/A096948

Remember, this is code-golf, so shortest code wins!

答:
Ruby, 22 bytes

Stealing @xnor's trick and making a stabby-lambda:

```<code>r=->(m,n){m*n*~m*~n/4}
</code>```

Example call:

```<code>r[6,7]     # => 588
</code>```

Or as a proc, also 22 bytes:

```<code>proc{|m,n|m*n*~m*~n/4}
</code>```

Which we could then call:

```<code>proc{|m,n|m*n*~m*~n/4}.call(6,7)     # => 588
</code>```

Title: How Many Rectangles in the Grid?

Body:
Ruby, 22 bytes

Stealing @xnor's trick and making a stabby-lambda:

r=->(m,n){m*n*~m*~n/4}

Example call:

r[6,7]     # => 588

Or as a proc, also 22 bytes:

proc{|m,n|m*n*~m*~n/4}

Which we could then call:

proc{|m,n|m*n*~m*~n/4}.call(6,7)     # => 588


答:
Mathematica, 20 bytes

Byte count assumes ISO 8859-1 (or compatible) encoding and $CharacterEncoding set to a matching value, like the Windows default WindowsANSI.

```<code>±0=0
±n_:=n-±±±(n-1)
</code>```

This defines a unary operator ±.

Title: Hofstadter H-sequence

Body:
Mathematica, 20 bytes

Byte count assumes ISO 8859-1 (or compatible) encoding and $CharacterEncoding set to a matching value, like the Windows default WindowsANSI.

±0=0
±n_:=n-±±±(n-1)

This defines a unary operator ±.


答:
CJam, <s>13</s> 12 bytes

Thanks to Dennis for saving 1 byte.

```<code>ri0{_(jjj-}j
</code>```

Test it here.

Title: Hofstadter H-sequence

Body:
CJam, <s>13</s> 12 bytes

Thanks to Dennis for saving 1 byte.

ri0{_(jjj-}j

Test it here.


问:
Print a Tabula Recta!
The Tabula Recta (sometimes called a 'Vigenere Table'), was created by Johannes Trithemius, and has been used in several ciphers, including all variants of Bellaso's Vigenere cipher and the Trithemius cipher. It looks like this:

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
BCDEFGHIJKLMNOPQRSTUVWXYZA
CDEFGHIJKLMNOPQRSTUVWXYZAB
DEFGHIJKLMNOPQRSTUVWXYZABC
EFGHIJKLMNOPQRSTUVWXYZABCD
FGHIJKLMNOPQRSTUVWXYZABCDE
GHIJKLMNOPQRSTUVWXYZABCDEF
HIJKLMNOPQRSTUVWXYZABCDEFG
IJKLMNOPQRSTUVWXYZABCDEFGH
JKLMNOPQRSTUVWXYZABCDEFGHI
KLMNOPQRSTUVWXYZABCDEFGHIJ
LMNOPQRSTUVWXYZABCDEFGHIJK
MNOPQRSTUVWXYZABCDEFGHIJKL
NOPQRSTUVWXYZABCDEFGHIJKLM
OPQRSTUVWXYZABCDEFGHIJKLMN
PQRSTUVWXYZABCDEFGHIJKLMNO
QRSTUVWXYZABCDEFGHIJKLMNOP
RSTUVWXYZABCDEFGHIJKLMNOPQ
STUVWXYZABCDEFGHIJKLMNOPQR
TUVWXYZABCDEFGHIJKLMNOPQRS
UVWXYZABCDEFGHIJKLMNOPQRST
VWXYZABCDEFGHIJKLMNOPQRSTU
WXYZABCDEFGHIJKLMNOPQRSTUV
XYZABCDEFGHIJKLMNOPQRSTUVW
YZABCDEFGHIJKLMNOPQRSTUVWX
ZABCDEFGHIJKLMNOPQRSTUVWXY
</code>```

I frequently need this, but can't find it anywhere on the internet to copy and paste from. Because the square table is so long, and takes frigging ages to type, your code must be as short as possible.

Rules/Requirements

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

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Javascript 98 bytes

```<code>s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";for (var i = 0; i < 26; i++) {console.log(s);s=s+s[0];s.substr(1);}
</code>```

try it yourself at: https://jsfiddle.net/dL0vg3cL/1/

sorry i don't know how to do the character count

Title: Print a Tabula Recta!

Body:
Javascript 98 bytes

s="ABCDEFGHIJKLMNOPQRSTUVWXYZ";for (var i = 0; i < 26; i++) {console.log(s);s=s+s[0];s.substr(1);}

try it yourself at: https://jsfiddle.net/dL0vg3cL/1/

sorry i don't know how to do the character count


问:
Advanced Calculator
You must write a program that evaluates a string that would be entered into an advanced calculator.

The program must accept input using stdin and output the correct answer.  For languages that do no have functions to accept stdin, you may assume the functions readLine and print to handle these tasks.

Requirements:

Does not use any kind of "eval" functions

Can handle floating point and negative numbers

Supports at least the +, -, *, /, and ^ operators

Supports brackets and parenthesis for overriding the normal order

Can handle input containing one or more spaces between the operators and numbers

Evaluates the input using the standard order of operations

Test Cases

Input

```<code>10 - 3 + 2
</code>```

Output

```<code>9
</code>```

Input

```<code>8 + 6 / 3 - 7 + -5 / 2.5
</code>```

Output

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

Input

```<code>4 + [ ( -3 + 5 ) * 3.5 ] ^ 2 - 12
</code>```

Output

```<code>41
</code>```

答:
Postscript, 446

This uses the shunting yard algorithm.

```<code>[/*[/p
2/e{mul}>>/d[/p
2/e{div}>>/+[/p
1/e{add}>>/-[/p
1/e{sub}>>/o[/p
9/e{}>>/c[/p
-1/e{}>>/^[/p
3/e{exp}>>/p
0>>begin/s(%stdin)(r)file 999 string readline pop def
0 1 s length 1 sub{s exch[0 1 255{}for]dup[(\(o)([o)(\)c)(]c)(/d)]{{}forall
put dup}forall
pop
3 copy pop
get
get
put}for{s token not{exit}if
exch/s exch store{cvr}stopped{load
dup/p get
p
le{currentdict end
exch begin/e get exec}{begin}ifelse}if}loop{{e end}stopped{exit}if}loop
=
</code>```

Un-golfed and commented:

```<code>% We associate the operators with their precedence /p and the executed commend /e
[
  (*)[/p  2 /e{mul}>>
  (d)[/p  2 /e{div}>> % This is division
  (+)[/p  1 /e{add}>>
  (-)[/p  1 /e{sub}>>
  (o)[/p  9 /e{   }>> % This is open bracket
  (c)[/p -1 /e{   }>> % This is close bracket
  (^)[/p  3 /e{exp}>>
  /p 0
>>begin

% Let's read the input string
/s(%stdin)(r)file 999 string readline pop def

% If we want to use the token operator, we have to replace (, [, ), ] and / to get meaningful results
% We use kind of an encoding array (familiar to PostScripters) to map those codes to o, c, and d.
0 1 s length 1 sub{        % index
  s exch                   % string index
  [0 1 255{}for] dup       % string index translationArray translationArray
  [(\(o)  ([o)  (\)c)  (]c)  (/d)] % string index translationArray translationArray reencodeArray
  {                        % string index translationArray translationArray translationString
    {}forall               % string index translationArray translationArray charCode newCharCode
    put dup                % string index translationArray translationArray
  }forall                  % string index translationArray translationArray
  pop                      % string index translationArray
  3 copy pop               % string index translationArray string index
  get                      % string index translationArray charCode
  get                      % string index translatedCharCode
  put                      % -/-
}for

% Now we can actually start interpreting the string
% We use the stack for storing numbers we read and the dictionary stack for operators that are "waiting"
{                          % number*
  s token not{exit}if      % number* string token
  exch /s exch store       % number* token
  % We try to interpret the token as a number
  {cvr}stopped{            % number* token
    % If interpretation as number fails, we have an operator
    load                   % number* opDict
    % Compare operator precedence with last operator on dictstack
    dup /p get             % number* opDict opPrec
    p                      % number* opDict opPrec prevOpPrec
    le {                   % number* opDict
      % If the last operator on the stack has at least the same precedence, execute it
      currentdict end      % number* opDict prevOpDict
      exch begin           % number* prevOpDict
      /e get exec          % number*
    }{                     % number* opDict
      % If last operator doesn't have higher precedence, put the new operator on the dictstack as well
      begin
    }ifelse
  }if
}loop
% If we're finished with interpreting the string, execute all operators that are left on the dictstack
{{e end}stopped{exit}if}loop
=
</code>```

TODO: Right-associativity of exponentation

ContentLicense: CC BY-SA 2.5

Title: Advanced Calculator

Body:
Postscript, 446

This uses the shunting yard algorithm.

[/*[/p
2/e{mul}>>/d[/p
2/e{div}>>/+[/p
1/e{add}>>/-[/p
1/e{sub}>>/o[/p
9/e{}>>/c[/p
-1/e{}>>/^[/p
3/e{exp}>>/p
0>>begin/s(%stdin)(r)file 999 string readline pop def
0 1 s length 1 sub{s exch[0 1 255{}for]dup[(\(o)([o)(\)c)(]c)(/d)]{{}forall
put dup}forall
pop
3 copy pop
get
get
put}for{s token not{exit}if
exch/s exch store{cvr}stopped{load
dup/p get
p
le{currentdict end
exch begin/e get exec}{begin}ifelse}if}loop{{e end}stopped{exit}if}loop
=

Un-golfed and commented:

% We associate the operators with their precedence /p and the executed commend /e
[
  (*)[/p  2 /e{mul}>>
  (d)[/p  2 /e{div}>> % This is division
  (+)[/p  1 /e{add}>>
  (-)[/p  1 /e{sub}>>
  (o)[/p  9 /e{   }>> % This is open bracket
  (c)[/p -1 /e{   }>> % This is close bracket
  (^)[/p  3 /e{exp}>>
  /p 0
>>begin

% Let's read the input string
/s(%stdin)(r)file 999 string readline pop def

% If we want to use the token operator, we have to replace (, [, ), ] and / to get meaningful results
% We use kind of an encoding array (familiar to PostScripters) to map those codes to o, c, and d.
0 1 s length 1 sub{        % index
  s exch                   % string index
  [0 1 255{}for] dup       % string index translationArray translationArray
  [(\(o)  ([o)  (\)c)  (]c)  (/d)] % string index translationArray translationArray reencodeArray
  {                        % string index translationArray translationArray translationString
    {}forall               % string index translationArray translationArray charCode newCharCode
    put dup                % string index translationArray translationArray
  }forall                  % string index translationArray translationArray
  pop                      % string index translationArray
  3 copy pop               % string index translationArray string index
  get                      % string index translationArray charCode
  get                      % string index translatedCharCode
  put                      % -/-
}for

% Now we can actually start interpreting the string
% We use the stack for storing numbers we read and the dictionary stack for operators that are "waiting"
{                          % number*
  s token not{exit}if      % number* string token
  exch /s exch store       % number* token
  % We try to interpret the token as a number
  {cvr}stopped{            % number* token
    % If interpretation as number fails, we have an operator
    load                   % number* opDict
    % Compare operator precedence with last operator on dictstack
    dup /p get             % number* opDict opPrec
    p                      % number* opDict opPrec prevOpPrec
    le {                   % number* opDict
      % If the last operator on the stack has at least the same precedence, execute it
      currentdict end      % number* opDict prevOpDict
      exch begin           % number* prevOpDict
      /e get exec          % number*
    }{                     % number* opDict
      % If last operator doesn't have higher precedence, put the new operator on the dictstack as well
      begin
    }ifelse
  }if
}loop
% If we're finished with interpreting the string, execute all operators that are left on the dictstack
{{e end}stopped{exit}if}loop
=

TODO: Right-associativity of exponentation


问:
Tips for golfing in Cheddar

Cheddar is a high-level, functional + object-oriented programming language created by our user Downgoat designed to make programming easier, faster, and more intuitive.

What general tips do you have for golfing in Cheddar? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Cheddar (e.g. "Remove unnecessary whitespace." is not an answer).

答:
Use the String Operator for string sequences

I'm talking about the @" operator which does different things, all of which deal with strings. This has quite a bit of uses but this is one of my favorite uses:

Take a look at this:

```<code>@" [103, 111, 97, 116, 115] === "goats"
</code>```

not that useful but the opposite is:

```<code>@"'goats' === [103, 111, 97, 116, 115]
'goats'.bytes // compare the above too
</code>```

This is especially useful to generate the alphabet:

```<code>65@"90    // Uppercase Alphabet
97@"122   // Lowercase Alphabet
65@"90+97@"122 // Both cases
String.letters // Compare 97@"122 to this
</code>```

Title: Tips for golfing in Cheddar

Body:
Use the String Operator for string sequences

I'm talking about the @" operator which does different things, all of which deal with strings. This has quite a bit of uses but this is one of my favorite uses:

Take a look at this:

@" [103, 111, 97, 116, 115] === "goats"

not that useful but the opposite is:

@"'goats' === [103, 111, 97, 116, 115]
'goats'.bytes // compare the above too

This is especially useful to generate the alphabet:

65@"90    // Uppercase Alphabet
97@"122   // Lowercase Alphabet
65@"90+97@"122 // Both cases
String.letters // Compare 97@"122 to this


答:
C, 35 32 bytes

Saved 3 bytes thanks to @PeterTaylor!

a(n){return n?n-a(a(a(n-1))):0;}
```

Try it on Ideone!

Title: Hofstadter H-sequence

Body:
C, 35 32 bytes

Saved 3 bytes thanks to @PeterTaylor!

a(n){return n?n-a(a(a(n-1))):0;}

Try it on Ideone!


答:
Java 1.8, <s>96</s> 91 bytes

I managed to flatten everything into one for-loop with a single print statement. Nothing Java 1.8 specific - just happens to be the version I compiled the code with.

<s>

```<code>void f(){for(int i=-1,j=0,k=i;++i<702;k=(i+1)%27)System.out.write(k>25?++j-j+10:65+(k>j?k:j));}
</code>```

</s>

Surprisingly, removing variable k and introducing Math.max() skimmed off 5 bytes:

```<code>void f(){for(int i=-1,j=0;++i<702;)System.out.write(i%27>25?++j-j+10:65+Math.max(i%27,j));}
</code>```

Or ungolf'ed:

```<code>interface C {
    static void main(String[] a) {
        f();
    }

    static void f() {
        for (int i = -1, j = 0; ++i < 702;) {
            System.out.write(i%27 > 25 ? ++j - j + 10 : 65 + Math.max(i%27,j));
        }
    }
}
</code>```

Try it here.

Approach is based on my Tabula Recta answer. This leverages the fact that the System.out stream is line-buffered, causing an auto-flush whenever a line feed character (10) is written.

I have a feeling this can be golf'ed down further, mainly because of the way the values of certain variable are juggled with (i.e. j). Note to self: I was right!.

Title: Print/Output the L-phabet

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

```

Body:
Java 1.8, <s>96</s> 91 bytes

I managed to flatten everything into one for-loop with a single print statement. Nothing Java 1.8 specific - just happens to be the version I compiled the code with.

<s>

void f(){for(int i=-1,j=0,k=i;++i<702;k=(i+1)%27)System.out.write(k>25?++j-j+10:65+(k>j?k:j));}

</s>

Surprisingly, removing variable k and introducing Math.max() skimmed off 5 bytes:

void f(){for(int i=-1,j=0;++i<702;)System.out.write(i%27>25?++j-j+10:65+Math.max(i%27,j));}

Or ungolf'ed:

interface C {
    static void main(String[] a) {
        f();
    }

    static void f() {
        for (int i = -1, j = 0; ++i < 702;) {
            System.out.write(i%27 > 25 ? ++j - j + 10 : 65 + Math.max(i%27,j));
        }
    }
}

Try it here.

Approach is based on my Tabula Recta answer. This leverages the fact that the System.out stream is line-buffered, causing an auto-flush whenever a line feed character (10) is written.

I have a feeling this can be golf'ed down further, mainly because of the way the values of certain variable are juggled with (i.e. j). Note to self: I was right!.


Title: Hofstadter H-sequence

Body:
Definition

\$a(0) = 0\$

\$a(n) = n-a(a(a(n-1)))\$ for integer \$n > 0\$

Task

Given non-negative integer \$n\$, output \$a(n)\$.

Testcases

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

References

WolframMathWorld

OEIS A005374

Body:
Java 7, 42 bytes

int c(int n){return n>0?n-c(c(c(n-1))):0;}

Ungolfed & test cases:

Try it here.

class Main{
  static int c(int n){
    return n > 0
              ? n - c(c(c(n-1)))
              : 0;
  }

  public static void main(String[] a){
    for(int i = 0; i < 21; i++){
      System.out.println(i + ": " + c(i));
    }
    System.out.println("1000: " + c(1000));
  }
}

Output:

0: 0
1: 1
2: 1
3: 2
4: 3
5: 4
6: 4
7: 5
8: 5
9: 6
10: 7
11: 7
12: 8
13: 9
14: 10
15: 10
16: 11
17: 12
18: 13
19: 13
20: 14
 (last case takes too long..)


答:
///, 128 bytes

```<code>/:/fABCDEFGHIJKLMNOPQRSTUVWXYZ
fbfbAfxf
xbA_xf_x
xfbbbAfbb//x/bff//f/\///b/\\:B:C:D:E:F:G:H:I:J:K:L:M:N:O:P:Q:R:S:T:U:V:W:X:Y:Z:
</code>```

Try it online!

Inspired by Jakube's amazing answer to the L-phabet challenge, I thought I'd try my hand as well at actual programming in /// as opposed to just using it for compression. This was pretty tricky and I needed four attempts, but in the end it came out much shorter than my compression-based solution.

Explanation

A quick primer on ///: basically the interpreter just reads the code character by character and does the following:

If it's neither a \ nor a /, print it.

If it's a \, print the next character.

If it's a /, parse a /x/y/ instruction (with the same escaping rules) and repeatedly substitute all x in the remaining code with y.

Taking some more inspiration from Jakube, for simplicity I'll just explain a 4x4 version of this:

```<code>/:/fABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbb//x/bff//f/\///b/\\:B:C:D:
</code>```

We start by replacing those : with the stuff between the second and third /. This will end up being the code the rotates the subsequent rows. We get this:

```<code>/x/bff//f/\///b/\\fABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbbBfABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbbCfABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbbDfABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbb
</code>```

The f, b and x are just shorthands for common strings, which we'll expand now. The f is for slashes, the b is for backslashes and the x is for \// which happens to come up quite a lot. The reason I'm using aliases for the single-character substrings / and \ is that they'd have to be escaped in the first substitution instruction, so I'm actually saving quite a lot of bytes by not needing all those backslashes. Here's what we get after x, f and b have been filled in:

```<code>ABCD
/\/\A/\///
\//\A_\///_\//
\///\\\A/\\B/ABCD
/\/\A/\///
\//\A_\///_\//
\///\\\A/\\C/ABCD
/\/\A/\///
\//\A_\///_\//
\///\\\A/\\D/ABCD
/\/\A/\///
\//\A_\///_\//
\///\\\A/\\
</code>```

Very readable.

So the first line is just printed verbatim. Then we get to the funky part that rotates all further rows. It actually consists of four different instructions. One thing to notice is that I've escaped all occurrences of A within these instructions. The reason for this is that it allows me to distinguish As within the instructions from As in the remaining rows, which need to be processed differently.

```<code>/\/\A/\//
</code>```

This matches /A and replaces it with /, removing the A. Note that this substring only appears at the front of each ABCD, so this drops the first character of all subsequent lines:

```<code>/
\//\A_\//
</code>```

This matches a linefeed followed by a slash and replaces it with A_/. So this inserts an A at the end of each line, completing the rotation and also turns the linefeed into an underscore.

```<code>/_\//
\//
</code>```

This matches _/ and replaces it with a linefeed followed by a slash. The reason I need to make this detour via the underscore is the fact that /// applies each instruction repeatedly until the string no longer matches. That means you can never use an instruction of the form /x/axb/ where x, a and b are arbitrary strings, because after the substitution x will always still match. In particular, this means we can't just insert something in front of a linefeed. We need to replace the linefeed in the process and the undo this replacement.

```<code>/\\\A/\\B/
</code>```

This matches \A and replaces it with \B, so that the instructions after the remaining rows process the next character. After all four instructions have been processed the remaining string looks like this:

```<code>BCDA
/\/\B/\///
\//\B_\///_\//
\///\\\B/\\C/BCDA
/\/\B/\///
\//\B_\///_\//
\///\\\B/\\D/BCDA
/\/\B/\///
\//\B_\///_\//
\///\\\B/\\
</code>```

So now the first rotated row gets printed, and then the next set of instructions rotates the remaining rows by another cell and so on. After the last rotation, we have a few more instructions that we can ignore and then we end with the incomplete instruction:

```<code>/\\\B/\\
</code>```

Incomplete instructions at the end are simply ignored and the program terminates.

Title: Print a Tabula Recta!

Body:
The Tabula Recta (sometimes called a 'Vigenere Table'), was created by Johannes Trithemius, and has been used in several ciphers, including all variants of Bellaso's Vigenere cipher and the Trithemius cipher. It looks like this:

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
BCDEFGHIJKLMNOPQRSTUVWXYZA
CDEFGHIJKLMNOPQRSTUVWXYZAB
DEFGHIJKLMNOPQRSTUVWXYZABC
EFGHIJKLMNOPQRSTUVWXYZABCD
FGHIJKLMNOPQRSTUVWXYZABCDE
GHIJKLMNOPQRSTUVWXYZABCDEF
HIJKLMNOPQRSTUVWXYZABCDEFG
IJKLMNOPQRSTUVWXYZABCDEFGH
JKLMNOPQRSTUVWXYZABCDEFGHI
KLMNOPQRSTUVWXYZABCDEFGHIJ
LMNOPQRSTUVWXYZABCDEFGHIJK
MNOPQRSTUVWXYZABCDEFGHIJKL
NOPQRSTUVWXYZABCDEFGHIJKLM
OPQRSTUVWXYZABCDEFGHIJKLMN
PQRSTUVWXYZABCDEFGHIJKLMNO
QRSTUVWXYZABCDEFGHIJKLMNOP
RSTUVWXYZABCDEFGHIJKLMNOPQ
STUVWXYZABCDEFGHIJKLMNOPQR
TUVWXYZABCDEFGHIJKLMNOPQRS
UVWXYZABCDEFGHIJKLMNOPQRST
VWXYZABCDEFGHIJKLMNOPQRSTU
WXYZABCDEFGHIJKLMNOPQRSTUV
XYZABCDEFGHIJKLMNOPQRSTUVW
YZABCDEFGHIJKLMNOPQRSTUVWX
ZABCDEFGHIJKLMNOPQRSTUVWXY
</code>```

I frequently need this, but can't find it anywhere on the internet to copy and paste from. Because the square table is so long, and takes frigging ages to type, your code must be as short as possible.

Rules/Requirements

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

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
///, 128 bytes

/:/fABCDEFGHIJKLMNOPQRSTUVWXYZ
fbfbAfxf
xbA_xf_x
xfbbbAfbb//x/bff//f/\///b/\\:B:C:D:E:F:G:H:I:J:K:L:M:N:O:P:Q:R:S:T:U:V:W:X:Y:Z:

Try it online!

Inspired by Jakube's amazing answer to the L-phabet challenge, I thought I'd try my hand as well at actual programming in /// as opposed to just using it for compression. This was pretty tricky and I needed four attempts, but in the end it came out much shorter than my compression-based solution.

Explanation

A quick primer on ///: basically the interpreter just reads the code character by character and does the following:

If it's neither a \ nor a /, print it.

If it's a \, print the next character.

If it's a /, parse a /x/y/ instruction (with the same escaping rules) and repeatedly substitute all x in the remaining code with y.

Taking some more inspiration from Jakube, for simplicity I'll just explain a 4x4 version of this:

/:/fABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbb//x/bff//f/\///b/\\:B:C:D:

We start by replacing those : with the stuff between the second and third /. This will end up being the code the rotates the subsequent rows. We get this:

/x/bff//f/\///b/\\fABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbbBfABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbbCfABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbbDfABCD
fbfbAfxf
xbA_xf_x
xfbbbAfbb

The f, b and x are just shorthands for common strings, which we'll expand now. The f is for slashes, the b is for backslashes and the x is for \// which happens to come up quite a lot. The reason I'm using aliases for the single-character substrings / and \ is that they'd have to be escaped in the first substitution instruction, so I'm actually saving quite a lot of bytes by not needing all those backslashes. Here's what we get after x, f and b have been filled in:

ABCD
/\/\A/\///
\//\A_\///_\//
\///\\\A/\\B/ABCD
/\/\A/\///
\//\A_\///_\//
\///\\\A/\\C/ABCD
/\/\A/\///
\//\A_\///_\//
\///\\\A/\\D/ABCD
/\/\A/\///
\//\A_\///_\//
\///\\\A/\\

Very readable.

So the first line is just printed verbatim. Then we get to the funky part that rotates all further rows. It actually consists of four different instructions. One thing to notice is that I've escaped all occurrences of A within these instructions. The reason for this is that it allows me to distinguish As within the instructions from As in the remaining rows, which need to be processed differently.

/\/\A/\//

This matches /A and replaces it with /, removing the A. Note that this substring only appears at the front of each ABCD, so this drops the first character of all subsequent lines:

/
\//\A_\//

This matches a linefeed followed by a slash and replaces it with A_/. So this inserts an A at the end of each line, completing the rotation and also turns the linefeed into an underscore.

/_\//
\//

This matches _/ and replaces it with a linefeed followed by a slash. The reason I need to make this detour via the underscore is the fact that /// applies each instruction repeatedly until the string no longer matches. That means you can never use an instruction of the form /x/axb/ where x, a and b are arbitrary strings, because after the substitution x will always still match. In particular, this means we can't just insert something in front of a linefeed. We need to replace the linefeed in the process and the undo this replacement.

/\\\A/\\B/

This matches \A and replaces it with \B, so that the instructions after the remaining rows process the next character. After all four instructions have been processed the remaining string looks like this:

BCDA
/\/\B/\///
\//\B_\///_\//
\///\\\B/\\C/BCDA
/\/\B/\///
\//\B_\///_\//
\///\\\B/\\D/BCDA
/\/\B/\///
\//\B_\///_\//
\///\\\B/\\

So now the first rotated row gets printed, and then the next set of instructions rotates the remaining rows by another cell and so on. After the last rotation, we have a few more instructions that we can ignore and then we end with the incomplete instruction:

/\\\B/\\

Incomplete instructions at the end are simply ignored and the program terminates.


答:
Ruby, <s>49</s> 47 Bytes

Shaved off two bytes thanks to a simple () removal as per @manatwork, though his answer is even better at 45 bytes (see comment)

```<code>a=?A..?Z;a.map{|x|a.map{|y|$><<[x,y].max};puts}
</code>```

Ungolfed:

```<code>('A'..'Z').map{|x|
  ('A'..'Z').map{|y|
    print [x,y].max
  }
  puts
}
</code>```

Or using a stabby lambda to print out character by it's index, 76 bytes:

```<code>l=->i,j{$><<(i+65).chr*j};26.times{|i|l[i,i];(26-i).times{|j|l[i+j,1]};puts}
</code>```

Ungolfed:

```<code>def printChar(char,num)
  print (char+65).chr*num
end

26.times { |i|
  printChar(i,i)
  (26-i).times{|j| printChar(i+j,1)}
  puts
}
</code>```

A less complicated version (that doesn't use the string * op) at 77 bytes:

```<code>l=->i{$><<(i+65).chr};26.times{|i|i.times{l[i]};(26-i).times{|j|l[i+j]};puts}
</code>```

Title: Print/Output the L-phabet

Body:
Ruby, <s>49</s> 47 Bytes

Shaved off two bytes thanks to a simple () removal as per @manatwork, though his answer is even better at 45 bytes (see comment)

a=?A..?Z;a.map{|x|a.map{|y|$><<[x,y].max};puts}

Ungolfed:

('A'..'Z').map{|x|
  ('A'..'Z').map{|y|
    print [x,y].max
  }
  puts
}

Or using a stabby lambda to print out character by it's index, 76 bytes:

l=->i,j{$><<(i+65).chr*j};26.times{|i|l[i,i];(26-i).times{|j|l[i+j,1]};puts}

Ungolfed:

def printChar(char,num)
  print (char+65).chr*num
end

26.times { |i|
  printChar(i,i)
  (26-i).times{|j| printChar(i+j,1)}
  puts
}

A less complicated version (that doesn't use the string * op) at 77 bytes:

l=->i{$><<(i+65).chr};26.times{|i|i.times{l[i]};(26-i).times{|j|l[i+j]};puts}


答:
JavaScript (ES6), 52 bytes

```<code>n=>[0,...Array(n)].reduce((p,_,i,a)=>a[i]=i-a[a[p]])
</code>```

I could have been boring and written the recursive version but this version is much faster (easily coping with the last test case) and also uses reduce so that's a plus!

Title: Hofstadter H-sequence

Body:
JavaScript (ES6), 52 bytes

n=>[0,...Array(n)].reduce((p,_,i,a)=>a[i]=i-a[a[p]])

I could have been boring and written the recursive version but this version is much faster (easily coping with the last test case) and also uses reduce so that's a plus!


问:
Integer goes back and forth through time
Input:

An integer.

Output:

First convert the integer to it's equivalent Roman Numeral.

Then convert each capital letter of that Roman Numeral to their ASCII/UNICODE decimal value.

And output the sum of those.

Example:

```<code>1991 -> MCMXCI -> 77+67+77+88+67+73 -> 449
^ input                                ^ output
</code>```

Roman Numerals:

Here is a perhaps useful Roman Numeral Converter.

Challenge rules:

Standard Roman Numeral rules are applied, so no alternative forms like IIII or VIIII instead of IV and IX.*

The Macron lines above the Roman Numerals past 1,000 are ¯ (UNICODE nr. 175). So one line counts as +175 and two as +350.

You are allowed to use any kind of input and output type, as long as it represents the integers.

The test cases will be in the range of 1 - 2,147,483,647.

* Roman Numeral rules (quote from Wikipedia):

Numbers are formed by combining symbols and adding the values, so II is two (two ones) and XIII is thirteen (a ten and three ones). Because each numeral has a fixed value rather than representing multiples of ten, one hundred and so on, according to position, there is no need for "place keeping" zeros, as in numbers like 207 or 1066; those numbers are written as CCVII (two hundreds, a five and two ones) and MLXVI (a thousand, a fifty, a ten, a five and a one).

Symbols are placed from left to right in order of value, starting with the largest. However, in a few specific cases, to avoid four characters being repeated in succession (such as IIII or XXXX), subtractive notation is often used as follows:

I placed before V or X indicates one less, so four is IV (one less than five) and nine is IX (one less than ten)

X placed before L or C indicates ten less, so forty is XL (ten less than fifty) and ninety is XC (ten less than a hundred)

C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand)

  For example, MCMIV is one thousand nine hundred and four, 1904 (M is a thousand, CM is nine hundred and IV is four).

Some examples of the modern use of Roman numerals include:

  1954 as MCMLIV; 1990 as MCMXC; 2014 as MMXIV

  SOURCE

General rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases:

```<code>100          ->   67
1            ->   73
4            ->   159
22           ->   322
5000         ->   261
2016         ->   401
1000000000   ->   427
1991         ->   449
9999         ->   800
1111111111   ->   2344
2147483647   ->   5362
</code>```

Body:
Python, 263 bytes

def g(m):x=0;r=[73,86,88,76,67,68,77,261,263,251,242,243,252,436,438,426,417,418,427,0,0];return sum([b%5%4*r[i+(i*1)]+((b==9)*(r[i+(i*1)]+r[(i+1)*2]))+((b==4)*(r[i+(i*1)]+r[i+1+(i*1)]))+((b in [5,6,7,8])*r[i+1+(i*1)])for i,b in enumerate(map(int,str(m)[::-1]))])


问:
My Squiggly Lamp
While moving, I broke my lamp. Now, I need a new one. It's your job to make me a lamp! I'm not sure what size I want, though I know I want a squiggly one.

Your program/function must take in a number input, and print out a lamp with that many squiggles/bumps.

Examples:

Input:2

Output:

```
/--\
 ()
 ()
/__\
```

Input:3

Output:

```
/--\
 ()
 ()
 ()
/__\
```

Input:5

Output:

```
/--\
 ()
 ()
 ()
 ()
 ()
/__\
```

Rules:

0 & negative numbers don't matter

To give the lamps (an this challenge) more of a variety, you must change the lamp shade.

They must be 4 characters wide and 1 character high.

They can be in any shape, including non-lamp-shade shapes.

They must not contain whitespace.

The base must stay the same.

You must show an example input & output with your lamp shade.

Shortest code wins!

答:
Java <s>7</s> 11, <s>84</s> <s>83</s> 37 bytes

n->"i!!i\n"+" ()\n".repeat(n)+"/__\\"
```
<p>Try it online. (NOTE: Java 11 isn't supported on TIO yet, so <code>String.repeat(int)</code> has been emulated with <code>repeat(String,int)</code> for the same byte-count.)</p>
<p>Uses <code>i!!i</code> as cap. <code>¡!!¡</code> looks better, but is two bytes more.</p>
<p><strong>Explanation:</strong></p>
<pre class="lang-java prettyprint-override"><code>n->                    // Method with integer parameter and String return-type
  "i!!i\n"             //  Return the cap + new-line
  " ()\n".repeat(n)    //   appended with " ()" and a new-line `n` amount of times
  "/__\\"              //   append with "/__\"
</code>```

Title: My Squiggly Lamp

Body:
Java <s>7</s> 11, <s>84</s> <s>83</s> 37 bytes

n->"i!!i\n"+" ()\n".repeat(n)+"/__\\"

Try it online. (NOTE: Java 11 isn't supported on TIO yet, so String.repeat(int) has been emulated with repeat(String,int) for the same byte-count.)

Uses i!!i as cap. ¡!!¡ looks better, but is two bytes more.

Explanation:

n->                    // Method with integer parameter and String return-type
  "i!!i\n"             //  Return the cap + new-line
  " ()\n".repeat(n)    //   appended with " ()" and a new-line `n` amount of times
  "/__\\"              //   append with "/__\"


答:
Python, 64 bytes

l=input()
for _ in l:l=[min(x,l[x])for x in l]
print len(set(l))
```

<p>This golfed code happens to be idiomatic and readable. Uses 0-indexing. </p>

<p>Each value looks at what it points to and what the pointed value points to, and points to the smaller of the two. After enough repetitions, each element points to the smallest element of its cycle. The number of distinct elements pointed to is then the number of cycles. </p>

<p>It suffices to do <code>n</code> iterations. Alternatively, we could iterate until the list no longer changes. This strategy gave me a recursive function of the same length, 64 bytes:</p>

<pre class="lang-python prettyprint-override"><code>f=lambda l,p=0:len(set(l*(l==p)))or f([min(x,l[x])for x in l],l)
</code>```

Reducing was 65 bytes

lambda l:len(set(reduce(lambda l,_:[min(x,l[x])for x in l],l,l)))
```

The set(_) conversions can be shortened to {*_} in Python 3.5, saving 2 bytes.

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, 64 bytes

l=input()
for _ in l:l=[min(x,l[x])for x in l]
print len(set(l))

This golfed code happens to be idiomatic and readable. Uses 0-indexing.

Each value looks at what it points to and what the pointed value points to, and points to the smaller of the two. After enough repetitions, each element points to the smallest element of its cycle. The number of distinct elements pointed to is then the number of cycles.

It suffices to do n iterations. Alternatively, we could iterate until the list no longer changes. This strategy gave me a recursive function of the same length, 64 bytes:

f=lambda l,p=0:len(set(l*(l==p)))or f([min(x,l[x])for x in l],l)

Reducing was 65 bytes

lambda l:len(set(reduce(lambda l,_:[min(x,l[x])for x in l],l,l)))

The set(_) conversions can be shortened to {*_} in Python 3.5, saving 2 bytes.


问:
Print this diamond
This question has been spreading like a virus in my office. There are quite a variety of approaches:

Print the following:

```<code>        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321
 123456787654321
  1234567654321
   12345654321
    123454321
     1234321
      12321
       121
        1
</code>```

Answers are scored in characters with fewer characters being better.

答:
VBA, 197

```<code>for i=1 to 9:?string(27-i*3,32)l;:for j=1 to i:?j;:next:for j=i-1 to 1 step -1:?j;:next:?:next:for i=8 to 1 step -1:?string(27-i*3,32)l;:for j=1 to i:?j;:next:for j=i-1 to 1 step -1:?j;:next:?:next
</code>```

if vba didn't automatically add a space for the + sign it doesn't print, perhaps I could avoid the 27-i*3 construct for making it look right

Title: Print this diamond

Body:
VBA, 197

for i=1 to 9:?string(27-i*3,32)l;:for j=1 to i:?j;:next:for j=i-1 to 1 step -1:?j;:next:?:next:for i=8 to 1 step -1:?string(27-i*3,32)l;:for j=1 to i:?j;:next:for j=i-1 to 1 step -1:?j;:next:?:next

if vba didn't automatically add a space for the + sign it doesn't print, perhaps I could avoid the 27-i*3 construct for making it look right


问:
Ordering a list

Summary

Given a list of integers, return the index each integer would end up at when sorted.

For example, if the list was [0,8,-1,5,8], you should return [1,3,0,2,4].  Note that the two 8s maintain their order relative to each other (the sort is stable).

Put another way:  For each element in the list, return the number of elements in the list that are: Smaller than the chosen element OR (equal to the element AND appears before the chosen element)

Indexes must start with 0 (not 1)EDIT: given the large pushback, I'll allow 1-based indicies.

Test cases:

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

答:
Mathematica, 15 bytes

```<code>(o=Ordering)@*o
</code>```

Title: Ordering a list

Body:
Mathematica, 15 bytes

(o=Ordering)@*o