问:
Count the words in a text and display them
The code should take input a text (not mandatory can be anything file, stdin, string for JavaScript, etc):

```<code>This is a text and a number: 31.
</code>```

The output should contain the words with their number of occurrence, sorted by the number of occurrences in descending order:

```<code>a:2
and:1
is:1
number:1
This:1
text:1
31:1
</code>```

Notice that 31 is a word, so a word is anything alpha-numeric, number are not acting as separators so for example 0xAF qualifies as a word. Separators will be anything that is not alpha-numeric including .(dot) and -(hyphen) thus i.e. or pick-me-up would result in 2 respectively 3 words. Should be case sensitive, This and this would be two different words,  ' would also be separator so wouldnand t will be 2 different words from wouldn't.

Write the shortest code in your language of choice.

Shortest correct answer so far:

grep and coreutils - 42 bytes

答:
Perl 6, <s>53</s> 39 bytes

```<code>{.comb(/<-[_\W]>+/).Bag.sort:{-.value}}
</code>```

I use .comb to find every word matching the regexp <-[_\W]>+. In Perl 6, character classes are written <[]> instead of [], and negative character classes <-[]> instead of [^].

We then transform the list of words to a Bag (a set that keeps the number of occurences), and we sort said bag by their value.

Body:
Perl 6, <s>53</s> 39 bytes

{.comb(/<-[_\W]>+/).Bag.sort:{-.value}}

I use .comb to find every word matching the regexp <-[_\W]>+. In Perl 6, character classes are written <[]> instead of [], and negative character classes <-[]> instead of [^].

We then transform the list of words to a Bag (a set that keeps the number of occurences), and we sort said bag by their value.


问:
Counting in bijective base 62
The task is to generate all the strings from 'a' to '999' including upper case characters like so:

```<code>'a', 'b', 'c' ... 'y', 'z', 'A', 'B', 'C' ... 'Y', 'Z', '0', '1', 2' ...
'8', '9', 'aa', 'ab', 'ac' ... 'az', 'aA', 'aB' ... 'aZ', 'a0' ... 'a9', 'ba'
</code>```

and so on (filling in the gaps), optionally starting with the empty string.

Input:

The amount of consecutive characters the program has to print up to.

Output:

An array containing each string OR one string per line

Clarifications:

The order doesn't matter, you can print uppercase or lowercase letters first if you want.

The output can return any type of enumerable, doesn't have to be an array specifically, although I doubt printing all the combinations won't be the easiest way to go.

An input of 3 would print all the string from 'a' (or '') to '999'‚ an input of 5 up to '99999' and so on.

答:
Perl, 113 bytes + whitespace

@r="";
for (1..shift) {
  @r = sub {
    map { $c=$_; map $c.$_, @{$_[1]} } @{$_[0]}
  }->(\@r, [0..9, "a".."z", "A".."Z"])
}
map say($_), @r
```

Use "perl -E" on the above, with an argument that's a number. I could probably decently have not counted the last "map say" in the chars count.

ContentLicense: CC BY-SA 3.0

Title: Counting in bijective base 62

Body:
Perl, 113 bytes + whitespace

@r="";
for (1..shift) {
  @r = sub {
    map { $c=$_; map $c.$_, @{$_[1]} } @{$_[0]}
  }->(\@r, [0..9, "a".."z", "A".."Z"])
}
map say($_), @r

Use "perl -E" on the above, with an argument that's a number. I could probably decently have not counted the last "map say" in the chars count.


问:
What is the most frequent word?

What is the most frequent word?

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

Rules/Requirements

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

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

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

Your program must not write anything to STDERR.

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

Standard loopholes are forbidden.

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

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

Definition of a 'word':

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

Test Cases

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

-----

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

-----

This sentence has no most frequent word.
==>

-----

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

-----

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

-----

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

-----

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

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

Scoring

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

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

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
R, 115 bytes

function(s)if(sum(z<-(y=table(tolower((x=strsplit(s,"[^\\w']",,T)[[1]])[x>""])))==max(y))<2)names(which(z))else NULL
```

<p>This is a function that accepts a string and returns a string if a single word appears more often than others and <code>NULL</code> otherwise. To call it, assign it to a variable.</p>

<p>Ungolfed:</p>

<pre class="lang-r prettyprint-override"><code>f <- function(s) {
    # Create a vector of words by splitting the input on characters other
    # than word characters and apostrophes
    v <- (x <- strsplit(s, "[^\\w']", perl = TRUE))[x > ""]

    # Count the occurrences of each lowercased word
    y <- table(tolower(v))

    # Create a logical vector such that elements of `y` which occur most
    # often are `TRUE` and the rest are fase
    z <- y == max(y)

    # If a single word occurs most often, return it, otherwise `NULL`
    if (sum(z) < 2) {
        names(which(z))
    } else {
        NULL
    }
}
</code>```

Title: What is the most frequent word?

Body:
R, 115 bytes

function(s)if(sum(z<-(y=table(tolower((x=strsplit(s,"[^\\w']",,T)[[1]])[x>""])))==max(y))<2)names(which(z))else NULL

This is a function that accepts a string and returns a string if a single word appears more often than others and NULL otherwise. To call it, assign it to a variable.

Ungolfed:

f <- function(s) {
    # Create a vector of words by splitting the input on characters other
    # than word characters and apostrophes
    v <- (x <- strsplit(s, "[^\\w']", perl = TRUE))[x > ""]

    # Count the occurrences of each lowercased word
    y <- table(tolower(v))

    # Create a logical vector such that elements of `y` which occur most
    # often are `TRUE` and the rest are fase
    z <- y == max(y)

    # If a single word occurs most often, return it, otherwise `NULL`
    if (sum(z) < 2) {
        names(which(z))
    } else {
        NULL
    }
}


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

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

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

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

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

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

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

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

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

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

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

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

The challenge

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

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

Test IO

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

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

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

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

答:
Python, 85 bytes

```<code>lambda a,b:sum(b[i]*eval('*'.join(str(n)for n in a[i+1:])or'1')for i in range(len(a)))
</code>```

I'll probably get my butt kicked by the better python golfers out there.

Title: Index of a multidimensional array

Body:
Python, 85 bytes

lambda a,b:sum(b[i]*eval('*'.join(str(n)for n in a[i+1:])or'1')for i in range(len(a)))

I'll probably get my butt kicked by the better python golfers out there.


答:
Mathematica, 47 bytes

```<code>Fold[Last@#2#+First@#2&,First@#,Rest/@{##}]&
</code>```

(Unicode is U+F3C7, or \[Transpose].) For this, I rewrote the expression as Dn(Dn-1( ⋯ (D3(D2S1 + S2) + S3) ⋯ ) + Sn-1) + Sn. Just Folds the function over both lists.

Title: Index of a multidimensional array

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

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

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

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

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

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

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

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

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

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

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

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

The challenge

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

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

Test IO

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

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

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

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

Body:
Mathematica, 47 bytes

Fold[Last@#2#+First@#2&,First@#,Rest/@{##}]&

(Unicode is U+F3C7, or \[Transpose].) For this, I rewrote the expression as Dn(Dn-1( ⋯ (D3(D2S1 + S2) + S3) ⋯ ) + Sn-1) + Sn. Just Folds the function over both lists.


答:
JavaScript (ES6), 34 bytes

```<code>(d,a)=>a.reduce((r,i,j)=>r*d[j]+i)
</code>```

Surely reduce must be better than map.

Title: Index of a multidimensional array

Body:
JavaScript (ES6), 34 bytes

(d,a)=>a.reduce((r,i,j)=>r*d[j]+i)

Surely reduce must be better than map.


答:
MATL, 11 bytes

```<code>4L)1hPYpP*s
</code>```

This uses 0-based indexing, as in the original challenge.

Try it online!

Explanation

The code explicitly does the required multiplications and additions.

```<code>4L)    % Take first input array implicitly. Remove its first entry
1h     % Append a 1
PYpP   % Cumulative product from right to left
*      % Take second input array implicitly. Multiply the two arrays element-wise
s      % Sum of resulting array. Implicitly display
</code>```

Title: Index of a multidimensional array

Body:
MATL, 11 bytes

4L)1hPYpP*s

This uses 0-based indexing, as in the original challenge.

Try it online!

Explanation

The code explicitly does the required multiplications and additions.

4L)    % Take first input array implicitly. Remove its first entry
1h     % Append a 1
PYpP   % Cumulative product from right to left
*      % Take second input array implicitly. Multiply the two arrays element-wise
s      % Sum of resulting array. Implicitly display


答:
Pyth, 10 bytes

```<code>e.b=+*ZNYC
</code>```

Try it online: Demonstration or Test Suite

Using Horner's method to calculate the index.

Title: Index of a multidimensional array

Body:
Pyth, 10 bytes

e.b=+*ZNYC

Try it online: Demonstration or Test Suite

Using Horner's method to calculate the index.


答:
Jelly, <s>7</s> 6 bytes

```<code>Ṇ;żḅ@/
</code>```

Try it online! or verify all test cases.

How it works

```<code>Ṇ;żḅ@/  Main link. Arguments: D (list of dimensions), I (list of indices)

Ṇ       Yield 0, the logical NOT of D.
  ż     Zip D with I.
        If D = [10, 10, 4, 62, 7] and I = [1, 2, 3, 4, 5], this yields
        [[10, 1], [10, 2], [4, 3], [62, 4], [7, 5]].
 ;      Concatenate, yielding [0, [10, 1], [10, 2], [4, 3], [62, 4], [7, 5]].
   ḅ@/  Reduce by swapped base conversion to integer.
        [10, 1] in base    0 is    0 × 10 + 1 = 1.
        [10, 2] in base    1 is    1 × 10 + 2 = 12.
        [ 4, 3] in base   12 is   12 ×  4 + 3 = 51.
        [62, 4] in base   51 is   51 × 62 + 4 = 3166.
        [ 7, 5] in base 3166 is 3166 ×  7 + 5 = 22167.
</code>```

Title: Index of a multidimensional array

Body:
Jelly, <s>7</s> 6 bytes

Ṇ;żḅ@/

Try it online! or verify all test cases.

How it works

Ṇ;żḅ@/  Main link. Arguments: D (list of dimensions), I (list of indices)

Ṇ       Yield 0, the logical NOT of D.
  ż     Zip D with I.
        If D = [10, 10, 4, 62, 7] and I = [1, 2, 3, 4, 5], this yields
        [[10, 1], [10, 2], [4, 3], [62, 4], [7, 5]].
 ;      Concatenate, yielding [0, [10, 1], [10, 2], [4, 3], [62, 4], [7, 5]].
   ḅ@/  Reduce by swapped base conversion to integer.
        [10, 1] in base    0 is    0 × 10 + 1 = 1.
        [10, 2] in base    1 is    1 × 10 + 2 = 12.
        [ 4, 3] in base   12 is   12 ×  4 + 3 = 51.
        [62, 4] in base   51 is   51 × 62 + 4 = 3166.
        [ 7, 5] in base 3166 is 3166 ×  7 + 5 = 22167.


答:
Octave, <s>58</s> 54 bytes

Thanks to @AlexA. for his suggestion, which removed 4 bytes

```<code>@(d,i)reshape(1:prod(d),flip(d))(num2cell(flip(i)){:})
</code>```

Input and output are 1-based. To compare with the test cases, add 1 ot each entry in the input and subtract 1 from the output.

This is an anonymous function. To call it, assign it to a variable.

Try it here.

Explanation

This works by actually building the multidimensional array (reshape(...)), filled with values 1, 2, ... in linear order (1:prod(d)), and then indexing with the multidimensional index to get the corrresponding value.

The indexing is done by converting the input multidimensional index i into a cell array (num2cell(...)) and then to a comma-separated list ({:}).

The two flip operations are needed to adapt the order of dimensions from C to Octave.

Title: Index of a multidimensional array

Body:
Octave, <s>58</s> 54 bytes

Thanks to @AlexA. for his suggestion, which removed 4 bytes

@(d,i)reshape(1:prod(d),flip(d))(num2cell(flip(i)){:})

Input and output are 1-based. To compare with the test cases, add 1 ot each entry in the input and subtract 1 from the output.

This is an anonymous function. To call it, assign it to a variable.

Try it here.

Explanation

This works by actually building the multidimensional array (reshape(...)), filled with values 1, 2, ... in linear order (1:prod(d)), and then indexing with the multidimensional index to get the corrresponding value.

The indexing is done by converting the input multidimensional index i into a cell array (num2cell(...)) and then to a comma-separated list ({:}).

The two flip operations are needed to adapt the order of dimensions from C to Octave.


答:
APL, 1 byte

```<code>⊥
</code>```

Test it on TryAPL.

Title: Index of a multidimensional array

Body:
APL, 1 byte

⊥

Test it on TryAPL.


答:
MATL, 9 bytes

```<code>PiPZ}N$X]
</code>```

This uses 1-based indexing (now allowed by the challenge), which is the natural choice in MATL.

To compare with the test cases in the challenge, add 1 to each entry in the input index vector, and subtract 1 from the output.

Try it online!

Explanation

The code is based on the builtin X] function, which converts multidimensional indices to a single, linear index (like Matlab or Octave's sub2ind function).

```<code>P      % Take dimension vector implicitly. Reverse
iP     % Take vector of indices. Reverse
Z}     % Split vector into its elements
N$X]   % Convert indices to linear index (`sub2ind` function). Implicitly display
</code>```

Title: Index of a multidimensional array

Body:
MATL, 9 bytes

PiPZ}N$X]

This uses 1-based indexing (now allowed by the challenge), which is the natural choice in MATL.

To compare with the test cases in the challenge, add 1 to each entry in the input index vector, and subtract 1 from the output.

Try it online!

Explanation

The code is based on the builtin X] function, which converts multidimensional indices to a single, linear index (like Matlab or Octave's sub2ind function).

P      % Take dimension vector implicitly. Reverse
iP     % Take vector of indices. Reverse
Z}     % Split vector into its elements
N$X]   % Convert indices to linear index (`sub2ind` function). Implicitly display


答:
Python 3.5, 69

```<code>lambda d,i:sum(eval("*".join(map(str,[z,*d])))for z in i if d.pop(0))
</code>```

Test here

Title: Index of a multidimensional array

Body:
Python 3.5, 69

lambda d,i:sum(eval("*".join(map(str,[z,*d])))for z in i if d.pop(0))

Test here


答:
Python, 43 bytes

```<code>f=lambda x,y:x>[]and y.pop()+x.pop()*f(x,y)
</code>```

Test it on Ideone.

Title: Index of a multidimensional array

Body:
Python, 43 bytes

f=lambda x,y:x>[]and y.pop()+x.pop()*f(x,y)

Test it on Ideone.


答:
Haskell, 47 bytes

Two equal length solutions:

```<code>s(a:b)(x:y)=a*product y:s b y
s _ _=[]
(sum.).s
</code>```

Called like: ((sum.).s)[4,2][5,10].

Here's an infix version:

```<code>(a:b)&(x:y)=a*product y:b&y
_ & _=[]
(sum.).(&)
</code>```

Title: Index of a multidimensional array

Body:
Haskell, 47 bytes

Two equal length solutions:

s(a:b)(x:y)=a*product y:s b y
s _ _=[]
(sum.).s

Called like: ((sum.).s)[4,2][5,10].

Here's an infix version:

(a:b)&(x:y)=a*product y:b&y
_ & _=[]
(sum.).(&)


问:
Simpson diversity index
The Simpson index is a measure of diversity of a collection of items with duplicates. It is simply the probability of drawing two different items when picking without replacement uniformly at random.

With n items in groups of n_1, ..., n_k identical items, the probability of two different items is

For example, if you have 3 apples, 2 bananas, and 1 carrot, the diversity index is

D = 1 - (6 + 2 + 0)/30 = 0.7333

Alternatively, the number of unordered pairs of different items is 3*2 + 3*1 + 2*1 = 11 out of 15 pairs overall, and 11/15 = 0.7333.

Input:

A string of characters A to Z. Or, a list of such characters. Its length will be at least 2. You may not assume it to be sorted.

Output:

The Simpson diversity index of characters in that string, i.e., the probability that two characters taken randomly with replacement are different. This is a number between 0 and 1 inclusive.

When outputting a float, display at least 4 digits, though terminating exact outputs like 1 or 1.0 or 0.375 are OK.

You may not use built-ins that specifically compute diversity indices or entropy measures. Actual random sampling is fine, as long as you get sufficient accuracy on the test cases.

Test cases

```<code>AAABBC 0.73333
ACBABA 0.73333
WWW 0.0
CODE 1.0
PROGRAMMING 0.94545
</code>```

Leaderboard

Here's a by-language leaderboard, courtesy of Martin Büttner.

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

function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/53455/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){$.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(e){answers.push.apply(answers,e.items);if(e.has_more)getAnswers();else process()}})}function shouldHaveHeading(e){var t=false;var n=e.body_markdown.split("\n");try{t|=/^#/.test(e.body_markdown);t|=["-","="].indexOf(n[1][0])>-1;t&=LANGUAGE_REG.test(e.body_markdown)}catch(r){}return t}function shouldHaveScore(e){var t=false;try{t|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(n){}return t}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading);answers.sort(function(e,t){var n=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0],r=+(t.body_markdown.split("\n")[0].match(SIZE_REG)||[Infinity])[0];return n-r});var e={};var t=1;answers.forEach(function(n){var r=n.body_markdown.split("\n")[0];var i=$("#answer-template").html();var s=r.match(NUMBER_REG)[0];var o=(r.match(SIZE_REG)||[0])[0];var u=r.match(LANGUAGE_REG)[1];var a=getAuthorName(n);i=i.replace("{{PLACE}}",t++ +".").replace("{{NAME}}",a).replace("{{LANGUAGE}}",u).replace("{{SIZE}}",o).replace("{{LINK}}",n.share_link);i=$(i);$("#answers").append(i);e[u]=e[u]||{lang:u,user:a,size:o,link:n.share_link}});var n=[];for(var r in e)if(e.hasOwnProperty(r))n.push(e[r]);n.sort(function(e,t){if(e.lang>t.lang)return 1;if(e.lang<t.lang)return-1;return 0});for(var i=0;i<n.length;++i){var s=$("#language-template").html();var r=n[i];s=s.replace("{{LANGUAGE}}",r.lang).replace("{{NAME}}",r.user).replace("{{SIZE}}",r.size).replace("{{LINK}}",r.link);s=$(s);$("#languages").append(s)}}var QUESTION_ID=45497;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/;var NUMBER_REG=/\d+/;var LANGUAGE_REG=/^#*\s*((?:[^,\s]|\s+[^-,\s])*)/```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

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

Leaderboard

	AuthorLanguageSize

Winners by Language

LanguageUserScore

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

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

答:
APL, 26 bytes

```<code>{1-+/÷/{⍵×⍵-1}({⍴⍵}⌸⍵),≢⍵}
</code>```

Explanation:

≢⍵: get the length of the first dimension of ⍵. Given that ⍵ is supposed to be a string, this means the length of the string.

{⍴⍵}⌸⍵: for each unique element in ⍵, get the lengths of each dimension of the list of occurrences. This gives the amount of times an item occurs for each item, as a 1×≢⍵ matrix.

,: concatenate the two along the horizontal axis. Since ≢⍵ is a scalar, and the other value is a column, we get a 2×≢⍵ matrix where the first column has the amount of times an item occurs for each item, and the second column has the total amount of items.

{⍵×⍵-1}: for each cell in the matrix, calculate N(N-1).

÷/: reduce rows by division. This divides the value for each item by the value for the total.

+/: sum the result for each row.

1-: subtract it from 1

Title: Simpson diversity index

Body:
APL, 26 bytes

{1-+/÷/{⍵×⍵-1}({⍴⍵}⌸⍵),≢⍵}

Explanation:

≢⍵: get the length of the first dimension of ⍵. Given that ⍵ is supposed to be a string, this means the length of the string.

{⍴⍵}⌸⍵: for each unique element in ⍵, get the lengths of each dimension of the list of occurrences. This gives the amount of times an item occurs for each item, as a 1×≢⍵ matrix.

,: concatenate the two along the horizontal axis. Since ≢⍵ is a scalar, and the other value is a column, we get a 2×≢⍵ matrix where the first column has the amount of times an item occurs for each item, and the second column has the total amount of items.

{⍵×⍵-1}: for each cell in the matrix, calculate N(N-1).

÷/: reduce rows by division. This divides the value for each item by the value for the total.

+/: sum the result for each row.

1-: subtract it from 1


问:
Laver table computations and an algorithm that is not known to terminate in ZFC
The Laver tables provide examples of programs which have not been shown to terminate in the standard axiomatic system of mathematics ZFC but which do terminate when one assumes very large cardinal axioms.

Introduction

The classical Laver tables An are the unique finite algebras with underlying set {1,...,2n} and an operation * that satisfies the identity x * (y * z)=(x * y) * (x * z) and where x*1=x+1 for x<2n and where 2n*1=1.

More information about the classical Laver tables can be found in the book Braids and Self-Distributivity by Patrick Dehornoy.

Challenge

What is the shortest code (in bytes) that calculates 1*32 in the classical Laver tables and terminates precisely when it finds an n with 1*32<2n? In other words, the program terminates if and only if it finds an n with 1*32<2n but otherwise it runs forever.

Motivation

A rank-into-rank cardinal (also called an I3-cardinal) is an extremely large level of infinity and if one assumes the existence of a rank-into-rank cardinal, then one is able to prove more theorems than if one does not assume the existence of a rank-into-rank cardinal. If there exists a rank-into-rank cardinal, then there is some classical Laver table An where 1*32<2n. However, there is no known proof that 1*32<2n in ZFC. Furthermore, it is known that the least n where 1*32<2n is greater than Ack(9,Ack(8,Ack(8,254)))(which is an extremely large number since the Ackermann function Ack is a fast growing function). Therefore, any such program will last for an extremely long amount of time.

I want to see how short of a program can be written so that we do not know if the program terminates using the standard axiomatic system ZFC but where we do know that the program eventually terminates in a much stronger axiomatic system, namely ZFC+I3. This question was inspired by Scott Aaronson's recent post in which Aaronson and Adam Yedidia have constructed a Turing machine with under 8000 states such that ZFC cannot prove that the Turing machine does not terminate but is known not to terminate when one assumes large cardinal hypotheses.

How the classical Laver tables are computed

When computing Laver tables it is usually convenient to use the fact that in the algebra An, we have 2n * x=x for all x in An.

The following code calculates the classical Laver table An

```
# table(n,x,y) returns x*y in A<sub>n</sub>
table:=function(n,x,y)
if x=2^n then return y;
elif y=1 then return x+1;
else return table(n,table(n,x,y-1),x+1); fi; end;
```

For example, the input table(4,1,2) will return 12.

The code for table(n,x,y) is rather inefficient and it can only compute in the Laver table A4 in a reasonable amount of time. Fortunately, there are much faster algorithms for computing the classical Laver tables than the ones given above.

Body:
Binary Lambda Calculus, 215 bits (27 bytes)

\io. let
  zero = \f\x. x;
  one = \x. x;
  two = \f\x. f (f x);
  sixteen = (\x. x x x) two;
  pred = \n\f\x. n (\g\h. h (g f)) (\h. x) (\x. x);
  laver = \mx.
    let laver = \b\a. a (\_. mx (b (laver (pred a))) zero) b
    in laver;
  sweet = sixteen;
  dblp1 = \n\f\x. n f (n f (f x)); -- map n to 2*n+1
  go2 = \mx. laver mx sweet mx (\_. mx) (go2 (dblp1 mx));
in go2 one

compiles to (using software at https://github.com/tromp/AIT)

000101000110100000010101010100011010000000010110000101111110011110010111
110111100000010101111100000011001110111100011000100000101100100010110101
00000011100111010100011001011101100000010111101100101111011001110100010

This solution is mostly due to https://github.com/int-e

ContentLicense: CC BY-SA 4.0


答:
Julia, <s>29</s> 27 bytes

```<code>x%y=prod(x)÷cumprod(x)⋅y
</code>```

Try it online!

Title: Index of a multidimensional array

Body:
Julia, <s>29</s> 27 bytes

x%y=prod(x)÷cumprod(x)⋅y

Try it online!


答:
Actually, 13 bytes

```<code>;pX╗lr`╜tπ`M*
</code>```

Try it online!

This program takes the list of indices as the first input and the list of dimensions as the second input.

Explanation:

```<code>;pX╗lr`╜tπ`M*
;pX╗            push dims[1:] to reg0
    lr`   `M    map: for n in range(len(dims)):
       ╜tπ        push product of last n values in reg0
            *   dot product of indices and map result
</code>```

Title: Index of a multidimensional array

Body:
Actually, 13 bytes

;pX╗lr`╜tπ`M*

Try it online!

This program takes the list of indices as the first input and the list of dimensions as the second input.

Explanation:

;pX╗lr`╜tπ`M*
;pX╗            push dims[1:] to reg0
    lr`   `M    map: for n in range(len(dims)):
       ╜tπ        push product of last n values in reg0
            *   dot product of indices and map result


问:
Read n random lines from a potentially huge file
This challenge is about reading random lines from a potentially huge file without reading the whole file into memory.

Input

An integer n and the name of a text file.

Output

n lines of the text file chosen uniformly at random without replacement.

You can assume that n is in the range 1 to the number of lines in the file.

Be careful when sampling n numbers at random from the range that the answer you get is uniform. rand()%n in C is not uniform for example. Every outcome must be equally likely.

Rules and restrictions

Each line of the text file will have the same number of characters and that will be no more than 80.

Your code must not read any of the contents of text file except:

Those lines it outputs.

The first line to work out how many characters per line there are in the text file.

We can assume each character in the text file takes exactly one byte.

Line separators are assumed to be 1 byte long. Solutions may use 2 bytes long line separators only if they specify this need. You may also assume the last line is terminated by a line separator.

Your answer should be a complete program but you can specify the input in any way that is convenient.

Languages and libraries

You can use any language or library you like.

Notes

There was a concern about calculating the number of lines in the file. As nimi points out in the comments, you can infer this from the file size and the number of chars per line.

Motivation

In chat some people asked if this is really a "Do X without Y" question. I interpret this to ask if the restrictions are unusually artificial.

The task of randomly sampling lines from huge files is not uncommon and is in fact one I sometimes have to do. One way to do this is in bash:

shuf -n <num-lines>

This is however very slow for large files as it reads in the whole file.

答:
Python 3, <s>146</s> 139 bytes

```<code>from random import*
i=input
f=open(i())
l=len(f.readline())
[(f.seek(v*l),print(f.read(l)))for v in sample(range(f.seek(0,2)//l),int(i()))]
#print is here^
</code>```

Input: [filename]\n[lines]\n

This solution heavily stole from @pppery but <s>is python3.5 only and</s> is a complete program.

Edit: Thanks to @Mego for the inline range and python3.x compatibility.
Edit2: Clarification where the print is because i got two comments about it. (Comment is obviously not part of the code or the byte count.)

Body:
Python 3, <s>146</s> 139 bytes

from random import*
i=input
f=open(i())
l=len(f.readline())
[(f.seek(v*l),print(f.read(l)))for v in sample(range(f.seek(0,2)//l),int(i()))]
#print is here^

Input: [filename]\n[lines]\n

This solution heavily stole from @pppery but <s>is python3.5 only and</s> is a complete program.

Edit: Thanks to @Mego for the inline range and python3.x compatibility.
Edit2: Clarification where the print is because i got two comments about it. (Comment is obviously not part of the code or the byte count.)


问:
Print every character your program doesn't have
Your task is to build a program (using only printable ASCII characters and/or tabs and newlines) that prints out exactly the characters in the printable ASCII space (0x20 to 0x7e) that don't appear in your program's source code (in any order, however many times you want).

The shortest code to do this in any language wins.

答:
Pyke, 34 bytes, noncompeting

```<code>"!$%&'()*+[,.]/:<=>?@^_`{|}";~J\J-
</code>```

I'm going the no-op, print chars route

Try it here!

Body:
Pyke, 34 bytes, noncompeting

"!$%&'()*+[,.]/:<=>?@^_`{|}";~J\J-

I'm going the no-op, print chars route

Try it here!


答:
Sqlserver 2008, 250 bytes

```<code>DECLARE @ varchar(max) = 'That''s... that''s... that is just terrible!" he said.';

WITH c as(SELECT
@ p,@ x
UNION ALL
SELECT LEFT(x,k-1),STUFF(x,1,k,'')FROM
c CROSS APPLY(SELECT patindex('%[^a-z''-]%',x+'!')k)k
WHERE''<x)SELECT max(p)FROM(SELECT top 1with ties p
FROM c WHERE p>''GROUP BY p
ORDER BY count(*)DESC
)j HAVING count(*)=1
</code>```

Try it online!

Sqlserver 2016, 174 bytes

Unable to handle data like this example(counting the equals as 3 words):

```<code>DECLARE @ varchar(max) = 'That''s... that''s... that is just terrible!" he said. = = ='

SELECT max(v)FROM(SELECT TOP 1WITH TIES value v
FROM STRING_SPLIT(REPLACE(REPLACE(REPLACE(@,'"',''),',',''),'.',''),' ')GROUP
BY value ORDER BY count(*)DESC)x HAVING count(*)=1
</code>```

Title: What is the most frequent word?

Body:
What is the most frequent word?

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

Rules/Requirements

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

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

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

Your program must not write anything to STDERR.

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

Standard loopholes are forbidden.

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

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

Definition of a 'word':

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

Test Cases

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

-----

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

-----

This sentence has no most frequent word.
==>

-----

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

-----

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

-----

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

-----

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

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

Scoring

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

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

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Sqlserver 2008, 250 bytes

DECLARE @ varchar(max) = 'That''s... that''s... that is just terrible!" he said.';

WITH c as(SELECT
@ p,@ x
UNION ALL
SELECT LEFT(x,k-1),STUFF(x,1,k,'')FROM
c CROSS APPLY(SELECT patindex('%[^a-z''-]%',x+'!')k)k
WHERE''<x)SELECT max(p)FROM(SELECT top 1with ties p
FROM c WHERE p>''GROUP BY p
ORDER BY count(*)DESC
)j HAVING count(*)=1

Try it online!

Sqlserver 2016, 174 bytes

Unable to handle data like this example(counting the equals as 3 words):

DECLARE @ varchar(max) = 'That''s... that''s... that is just terrible!" he said. = = ='

SELECT max(v)FROM(SELECT TOP 1WITH TIES value v
FROM STRING_SPLIT(REPLACE(REPLACE(REPLACE(@,'"',''),',',''),'.',''),' ')GROUP
BY value ORDER BY count(*)DESC)x HAVING count(*)=1


问:
Draw an ASCII Checkerboard

Summary

Inspired by the recent popularity of ASCII art challenges, this challenge's purpose is to draw an ASCII checkerboard, like one on which Chess can be played.

Write a program that takes a positive integer n as an argument, in stdin, or as user input, and output an checkerboard with nxn squares, along with a border that is 1 character thick.

Each square should be 2x2 characters. The squares should follow the normal alternating white-black (white first, as in top-left corner) pattern of a checkerboard. White squares should be made out of space () characters, and black squares should be made out of pound (#) characters.

The border should be made out of dashes (-) with a plus (+) on the border or perpendicular point of a square.

Input

Positive integer in representing the number of squares (dimensions in squares) to draw in the checkerboard, with each square being 2x2 characters.

Example Results

n=2

```<code>+--+--+
|  |##|
|  |##|
+--+--+
|##|  |
|##|  |
+--+--+
</code>```

n=3

```<code>+--+--+--+
|  |##|  |
|  |##|  |
+--+--+--+
|##|  |##|
|##|  |##|
+--+--+--+
|  |##|  |
|  |##|  |
+--+--+--+
</code>```

n=4

```<code>+--+--+--+--+
|  |##|  |##|
|  |##|  |##|
+--+--+--+--+
|##|  |##|  |
|##|  |##|  |
+--+--+--+--+
|  |##|  |##|
|  |##|  |##|
+--+--+--+--+
|##|  |##|  |
|##|  |##|  |
+--+--+--+--+
</code>```

... and so on.

Notes

Trailing spaces and new lines are acceptable.

You may write either an entire program or a function.

No leading spaces.

Your program should display correct results for n=15.

For less-known esoteric languages and similar, provide a link to the language.

n=0 should produce +. (optional, but highly recommended and encouraged.)

Shortest code in bytes wins, as this is code golf.

答:
Pyke, 47 bytes

```<code>"+--"Q*\+j+i
QQ]Uas 2%" #"@2*)F\|JjR+"+
"+2*pi
<Newline needed>
</code>```

Try it here!

Title: Draw an ASCII Checkerboard

Body:
Pyke, 47 bytes

"+--"Q*\+j+i
QQ]Uas 2%" #"@2*)F\|JjR+"+
"+2*pi
<Newline needed>

Try it here!


问:
Distance between two points in n-dimensional space
Here is another simple one:

The Challenge

Given two points in an n-dimensional space, output the distance between them, also called the Euclidean distance.

The coordinates will be rational numbers; the only limits are the restrictions of your language.

Lowest dimension is 1, highest is whatever your language can handle

You may assume that the two points are of the same dimension and that there will be no empty input.

The distance has to be correct to at least 3 decimal places. If your language does not support floating point numbers, output the nearest whole number.

Rules

As usual, function or full program allowed.

Input may be taken from STDIN, command line- or function arguments.

Input format is up to you, specify which one you used in your answer.

Output may be provided by printing to stdout or return value.

This is code-golf so lowest byte-count wins! In case of a tie, the earlier answer wins.

Test cases

Each point is represented by a list of length n.

```<code>[1], [3] -> 2
[1,1], [1,1] -> 0
[1,2], [3,4] -> 2.82842712475
[1,2,3,4], [5,6,7,8] -> 8
[1.5,2,-5], [-3.45,-13,145] -> 150.829382085
[13.37,2,6,-7], [1.2,3.4,-5.6,7.89] -> 22.5020221314
</code>```

Happy Coding!

答:
Pyke, 7 bytes

```<code>,A-MXs,
</code>```

Try it here!

Transpose, apply subtract, map square, sum, sqrt.

Body:
Pyke, 7 bytes

,A-MXs,

Try it here!

Transpose, apply subtract, map square, sum, sqrt.


答:
PostgreSQL, 246, 245 bytes

```<code>WITH z AS(SELECT DISTINCT*,COUNT(*)OVER(PARTITION BY t,m)c FROM i,regexp_split_to_table(translate(lower(t),'.,"''',''),E'\\s+')m)
SELECT t,CASE WHEN COUNT(*)>1 THEN '' ELSE MAX(m)END
FROM z WHERE(t,c)IN(SELECT t,MAX(c)FROM z GROUP BY t)
GROUP BY t
</code>```

Output:

Input if anyone is interested:

```<code>CREATE TABLE i(t TEXT);

INSERT INTO i(t)
VALUES ('The man walked down the road.'), ('Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.'),
       ('This sentence has no most frequent word.'), ('"That''s... that''s... that is just terrible!" he said. '), ('The old-fashioned man ate an old-fashioned cake.'),
       ('IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.'), ('a   a            a b b b c');
</code>```

Normally I would use MODE() WITHIN GROUP(...) and it will be much shorter, but it will violate:

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

EDIT:

Handling ':

```<code>WITH z AS(SELECT DISTINCT*,COUNT(*)OVER(PARTITION BY t,m)c FROM i,regexp_split_to_table(translate(lower(t),'.,"!',''),E'\\s+')m)
SELECT t,CASE WHEN COUNT(*)>1 THEN '' ELSE MAX(m)END
FROM z WHERE(t,c)IN(SELECT t,MAX(c)FROM z GROUP BY t)
GROUP BY t
</code>```

SqlFiddleDemo

Output:

```<code>╔═══════════════════════════════════════════════════════════════════════════════════════════════╦═══════════════╗
║                                              t                                                ║      max      ║
╠═══════════════════════════════════════════════════════════════════════════════════════════════╬═══════════════╣
║ a a a b b b c                                                                                ║               ║
║ The old-fashioned man ate an old-fashioned cake.                                              ║ old-fashioned ║
║ IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.  ║ ipv6          ║
║ This sentence has no most frequent word.                                                      ║               ║
║ "That's... that's... that is just terrible!" he said.                                         ║ that's        ║
║ The man walked down the road.                                                                 ║ the           ║
║ Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.        ║ he            ║
╚═══════════════════════════════════════════════════════════════════════════════════════════════╩═══════════════╝
</code>```

Title: What is the most frequent word?

Body:
PostgreSQL, 246, 245 bytes

WITH z AS(SELECT DISTINCT*,COUNT(*)OVER(PARTITION BY t,m)c FROM i,regexp_split_to_table(translate(lower(t),'.,"''',''),E'\\s+')m)
SELECT t,CASE WHEN COUNT(*)>1 THEN '' ELSE MAX(m)END
FROM z WHERE(t,c)IN(SELECT t,MAX(c)FROM z GROUP BY t)
GROUP BY t

Output:

Input if anyone is interested:

CREATE TABLE i(t TEXT);

INSERT INTO i(t)
VALUES ('The man walked down the road.'), ('Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.'),
       ('This sentence has no most frequent word.'), ('"That''s... that''s... that is just terrible!" he said. '), ('The old-fashioned man ate an old-fashioned cake.'),
       ('IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.'), ('a   a            a b b b c');

Normally I would use MODE() WITHIN GROUP(...) and it will be much shorter, but it will violate:

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

EDIT:

Handling ':

WITH z AS(SELECT DISTINCT*,COUNT(*)OVER(PARTITION BY t,m)c FROM i,regexp_split_to_table(translate(lower(t),'.,"!',''),E'\\s+')m)
SELECT t,CASE WHEN COUNT(*)>1 THEN '' ELSE MAX(m)END
FROM z WHERE(t,c)IN(SELECT t,MAX(c)FROM z GROUP BY t)
GROUP BY t

SqlFiddleDemo

Output:

╔═══════════════════════════════════════════════════════════════════════════════════════════════╦═══════════════╗
║                                              t                                                ║      max      ║
╠═══════════════════════════════════════════════════════════════════════════════════════════════╬═══════════════╣
║ a a a b b b c                                                                                ║               ║
║ The old-fashioned man ate an old-fashioned cake.                                              ║ old-fashioned ║
║ IPv6 looks great, much better than IPv4, except for the fact that IPv6 has longer addresses.  ║ ipv6          ║
║ This sentence has no most frequent word.                                                      ║               ║
║ "That's... that's... that is just terrible!" he said.                                         ║ that's        ║
║ The man walked down the road.                                                                 ║ the           ║
║ Slowly, he ate the pie, savoring each delicious bite. He felt like he was truly happy.        ║ he            ║
╚═══════════════════════════════════════════════════════════════════════════════════════════════╩═══════════════╝


Title: Print every character your program doesn't have

Body:
Your task is to build a program (using only printable ASCII characters and/or tabs and newlines) that prints out exactly the characters in the printable ASCII space (0x20 to 0x7e) that don't appear in your program's source code (in any order, however many times you want).

The shortest code to do this in any language wins.

Body:
BitShift, 1038 bytes

BitShift is a language which only supports 0 and 1 as syntax. I figured it would be easy to print all other characters, but since it doesn't really support looping it still ended up a massive 1038 bytes.

However, I believe it's not really possible to go any smaller than this..

101001100101011011010100110111010100100101011001101111010100100101011001000101011011010100101100110110101001001010110010001010110110101000001101010010010101100100010101101101010000010000011001010110110101000010000101011011010100110111010100100101011111100101011011010100110111010100100101011001101111010100100101011001000101011011010100000000011010100100101011001000101011011010100110010000101011011010100110111010100100101011001101001101010010010101100100010101101101010011001000010101101101010011011101010010010101111011111110010101101101010011011101010010010101100101100101011011010100010001010110110101001000010101101101010011011101010010010101110111110010101101101010011011101010010010101111111100101011011010100110111010100100101011111011110101001001010110010001010110110101001000100000101011011010100110111010100100101011111010011010100100101011001000101011011010100100000101011011010100110111010100100101011001101111010100100101011001000101011011010100010000010101101101010011011101010010010101101001101101010010010101101001101010

Prints

 !"#$%&'()*+,-./23456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

Try it here


答:
JavaScript (ES6), 99 bytes

F=s=>(f={},w=c='',s.toLowerCase().replace(/[\w-']+/g,m=>(f[m]=o=++f[m]||1)-c?o>c?(w=m,c=o):0:w=''),w)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#input { width: 100%; }</code>```

<textarea id="input" oninput="output.innerHTML=F(this.value)"></textarea>

```

Title: What is the most frequent word?

Body:
JavaScript (ES6), 99 bytes

F=s=>(f={},w=c='',s.toLowerCase().replace(/[\w-']+/g,m=>(f[m]=o=++f[m]||1)-c?o>c?(w=m,c=o):0:w=''),w)

#input { width: 100%; }

<textarea id="input" oninput="output.innerHTML=F(this.value)"></textarea>
<div id="output"></div>


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

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

Rules

Each submission must be a full program.

You must create the shortest infinite loop.

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

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

The program must not write anything to STDERR.

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

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

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

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

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

Standard loopholes are not allowed.

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

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

Catalogue

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
ACIDIC, 1 byte

```<br/><br/>```

A single newline character. In the C# interpreter, the empty program (i.e., the second line) just loops forever.

Body:
ACIDIC, 1 byte

A single newline character. In the C# interpreter, the empty program (i.e., the second line) just loops forever.


问:
Find the n-th perfect power!
A perfect power is a number of the form \$a^b\$, where \$a>0\$ and \$b>1\$.

For example, \$125\$ is a perfect power because it can be expressed as \$5^3\$.

Goal

Your task is to write  a program/function that finds the \$n\$-th perfect power, given a positive integer \$n\$.

Specs

The first perfect power is \$1\$ (which is \$1^2\$).

Input/output in any reasonable format.

Built-ins are allowed.

Further information

OEIS A001597

Scoring

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

Testcases

```<code>input  output
1      1
2      4
3      8
4      9
5      16
6      25
7      27
8      32
9      36
10     49
</code>```

答:
><>, 108 bytes

```<code>:1)?v  >n;
$:@@\&31+2>2$:@@:@
:1=?\@$:@*@@1-
:~$~<.1b+1v!?(}:{:~~v?(}:{:v?=}:{
1-:&1=?v~~>~61.     >~1+b1.>&
</code>```

This program requires the input number to be present on the stack before running.

It took quite a lot to reduce the number of wasted bytes down to 7!

After a check to see if the input is 1, the program checks each number, n, from 4 in turn to see if it's a perfect power. It does this by starting with a=b=2. If a^b == n, we've found a perfect power, so decrement the number of perfect powers left to find - if we've already found the right number, output.

If a^b < n, b is incremented. If a^b > n, a is incremented. Then, if a == n, we've found that n isn't a perfect power, so increment n, resetting a and b.

Title: Find the n-th perfect power!

Body:
><>, 108 bytes

:1)?v  >n;
$:@@\&31+2>2$:@@:@
:1=?\@$:@*@@1-
:~$~<.1b+1v!?(}:{:~~v?(}:{:v?=}:{
1-:&1=?v~~>~61.     >~1+b1.>&

This program requires the input number to be present on the stack before running.

It took quite a lot to reduce the number of wasted bytes down to 7!

After a check to see if the input is 1, the program checks each number, n, from 4 in turn to see if it's a perfect power. It does this by starting with a=b=2. If a^b == n, we've found a perfect power, so decrement the number of perfect powers left to find - if we've already found the right number, output.

If a^b < n, b is incremented. If a^b > n, a is incremented. Then, if a == n, we've found that n isn't a perfect power, so increment n, resetting a and b.


答:
CJam (36 32 bytes)

```<code>1{2*31TW$,(+a{0X$j@(@jj}2j)W$=}g
</code>```

In practice, this errors out quite quickly because it overflows the call stack, but on a theoretical unlimited machine it is correct, and I understand that to be the assumption of this question.

The code for table(n,x,y) is rather inefficient and it can only compute in the Laver table A4 in a reasonable amount of time.

is not actually correct if we cache computed values to avoid recomputing them. That's the approach I've taken, using the j (memoisation) operator. It tests A6 in milliseconds and overflows the stack testing A7 - and I've actually deoptimised table in the interests of golfing.

Dissection

If we assume that n is understood from the context, instead of

```<code>f(x,y) =
    x==2^n ? y :
    y==1 ? x+1 :
    f(f(x,y-1),x+1)
</code>```

we can remove the first special case, giving

```<code>f(x,y) =
    y==1 ? x+1 :
    f(f(x,y-1),x+1)
</code>```

and it still works because

```<code>f(2^n, 1) = 2^n + 1 = 1
</code>```

and for any other y,

```<code>f(2^n, y) = f(f(2^n, y-1), 1) = f(2^n, y-1) + 1
</code>```

so by induction we get f(2^n, y) = y.

For CJam it turns out to be more convenient to reverse the order of the parameters. And rather than using the range 1 .. 2^n I'm using the range 0 .. 2^n - 1 by decrementing each value, so the recursive function I'm implementing is

```<code>g(y,x) =
    y==0 ? x+1
         : g(x+1, g(y-1, x))
</code>```

```<code>1           e# Initial value of 2^n
{           e# do-while loop
  2*        e#   Double 2^n (i.e. increment n)
  31T       e#   table(n,1,32) is g(31,0) so push 31 0
  W$,(+a    e#   Set up a lookup table for g(0,x) = x+1 % 2^n
  {         e#   Memoisation function body: stack is 2^n ... y x
    0X$j    e#     Compute g(0,x) = x+1 % 2^n
            e#     Stack is 2^n ... y x (x+1%2^n)
    @(      e#     Bring y to top, decrement (guaranteed not to underflow)
            e#     Stack is 2^n ... x (x+1%2^n) (y-1%2^n)
    @jj     e#     Rotate and apply memoised function twice: g(x+1,g(y-1,x))
  }
  2j        e#   Memoise two-parameter function
            e#   Stack: 2^n g(31,0)
  )W$=      e#   Test whether g(31,0)+1 is 2^n
}g          e# Loop while true
</code>```

Title: Laver table computations and an algorithm that is not known to terminate in ZFC

Body:
The Laver tables provide examples of programs which have not been shown to terminate in the standard axiomatic system of mathematics ZFC but which do terminate when one assumes very large cardinal axioms.

Introduction

The classical Laver tables An are the unique finite algebras with underlying set {1,...,2n} and an operation * that satisfies the identity x * (y * z)=(x * y) * (x * z) and where x*1=x+1 for x<2n and where 2n*1=1.

More information about the classical Laver tables can be found in the book Braids and Self-Distributivity by Patrick Dehornoy.

Challenge

What is the shortest code (in bytes) that calculates 1*32 in the classical Laver tables and terminates precisely when it finds an n with 1*32<2n? In other words, the program terminates if and only if it finds an n with 1*32<2n but otherwise it runs forever.

Motivation

A rank-into-rank cardinal (also called an I3-cardinal) is an extremely large level of infinity and if one assumes the existence of a rank-into-rank cardinal, then one is able to prove more theorems than if one does not assume the existence of a rank-into-rank cardinal. If there exists a rank-into-rank cardinal, then there is some classical Laver table An where 1*32<2n. However, there is no known proof that 1*32<2n in ZFC. Furthermore, it is known that the least n where 1*32<2n is greater than Ack(9,Ack(8,Ack(8,254)))(which is an extremely large number since the Ackermann function Ack is a fast growing function). Therefore, any such program will last for an extremely long amount of time.

I want to see how short of a program can be written so that we do not know if the program terminates using the standard axiomatic system ZFC but where we do know that the program eventually terminates in a much stronger axiomatic system, namely ZFC+I3. This question was inspired by Scott Aaronson's recent post in which Aaronson and Adam Yedidia have constructed a Turing machine with under 8000 states such that ZFC cannot prove that the Turing machine does not terminate but is known not to terminate when one assumes large cardinal hypotheses.

How the classical Laver tables are computed

When computing Laver tables it is usually convenient to use the fact that in the algebra An, we have 2n * x=x for all x in An.

The following code calculates the classical Laver table An

```
# table(n,x,y) returns x*y in A<sub>n</sub>
table:=function(n,x,y)
if x=2^n then return y;
elif y=1 then return x+1;
else return table(n,table(n,x,y-1),x+1); fi; end;
```

For example, the input table(4,1,2) will return 12.

The code for table(n,x,y) is rather inefficient and it can only compute in the Laver table A4 in a reasonable amount of time. Fortunately, there are much faster algorithms for computing the classical Laver tables than the ones given above.

Body:
CJam (36 32 bytes)

1{2*31TW$,(+a{0X$j@(@jj}2j)W$=}g

In practice, this errors out quite quickly because it overflows the call stack, but on a theoretical unlimited machine it is correct, and I understand that to be the assumption of this question.

The code for table(n,x,y) is rather inefficient and it can only compute in the Laver table A4 in a reasonable amount of time.

is not actually correct if we cache computed values to avoid recomputing them. That's the approach I've taken, using the j (memoisation) operator. It tests A6 in milliseconds and overflows the stack testing A7 - and I've actually deoptimised table in the interests of golfing.

Dissection

If we assume that n is understood from the context, instead of

f(x,y) =
    x==2^n ? y :
    y==1 ? x+1 :
    f(f(x,y-1),x+1)

we can remove the first special case, giving

f(x,y) =
    y==1 ? x+1 :
    f(f(x,y-1),x+1)

and it still works because

f(2^n, 1) = 2^n + 1 = 1

and for any other y,

f(2^n, y) = f(f(2^n, y-1), 1) = f(2^n, y-1) + 1

so by induction we get f(2^n, y) = y.

For CJam it turns out to be more convenient to reverse the order of the parameters. And rather than using the range 1 .. 2^n I'm using the range 0 .. 2^n - 1 by decrementing each value, so the recursive function I'm implementing is

g(y,x) =
    y==0 ? x+1
         : g(x+1, g(y-1, x))

1           e# Initial value of 2^n
{           e# do-while loop
  2*        e#   Double 2^n (i.e. increment n)
  31T       e#   table(n,1,32) is g(31,0) so push 31 0
  W$,(+a    e#   Set up a lookup table for g(0,x) = x+1 % 2^n
  {         e#   Memoisation function body: stack is 2^n ... y x
    0X$j    e#     Compute g(0,x) = x+1 % 2^n
            e#     Stack is 2^n ... y x (x+1%2^n)
    @(      e#     Bring y to top, decrement (guaranteed not to underflow)
            e#     Stack is 2^n ... x (x+1%2^n) (y-1%2^n)
    @jj     e#     Rotate and apply memoised function twice: g(x+1,g(y-1,x))
  }
  2j        e#   Memoise two-parameter function
            e#   Stack: 2^n g(31,0)
  )W$=      e#   Test whether g(31,0)+1 is 2^n
}g          e# Loop while true


答:
Pyth, 33 bytes

```<code>.N?qT^2NY?tY:N:NTtYhThT<:T1 32^2T
</code>```

Try it online! (Obviously the testing part is not included here.)

Body:
Pyth, 33 bytes

.N?qT^2NY?tY:N:NTtYhThT<:T1 32^2T

Try it online! (Obviously the testing part is not included here.)


答:
Python, 158 bytes

```<code>def g(s):import collections as c,re;l=c.Counter(re.sub('[^\w\s-]',"",s.lower()).split());w,f=l.most_common(1)[0];return[w,""][all(f==i[1]for i in l.items())]
</code>```

Takes its input like this:

```<code>g("Bird is the word")
</code>```

Should match all the requirements, although it does fail on empty strings, is it necessary to check for those? Sorry for the delay.

Advice / feedback / black magic tips for saving bytes are always welcome

Title: What is the most frequent word?

Body:
Python, 158 bytes

def g(s):import collections as c,re;l=c.Counter(re.sub('[^\w\s-]',"",s.lower()).split());w,f=l.most_common(1)[0];return[w,""][all(f==i[1]for i in l.items())]

Takes its input like this:

g("Bird is the word")

Should match all the requirements, although it does fail on empty strings, is it necessary to check for those? Sorry for the delay.

Advice / feedback / black magic tips for saving bytes are always welcome


答:
PHP, 223 bytes

```<code>$a=array_count_values(array_map(function($s){return preg_replace('/[^A-Za-z0-9]/','',$s);},explode(' ',strtolower($argv[1]))));arsort($a);$c=count($a);$k=array_keys($a);echo($c>0?($c==1?$k[0]:($a[$k[0]]!=$a[$k[1]]?$k[0]:'')):'');
</code>```

Title: What is the most frequent word?

Body:
PHP, 223 bytes

$a=array_count_values(array_map(function($s){return preg_replace('/[^A-Za-z0-9]/','',$s);},explode(' ',strtolower($argv[1]))));arsort($a);$c=count($a);$k=array_keys($a);echo($c>0?($c==1?$k[0]:($a[$k[0]]!=$a[$k[1]]?$k[0]:'')):'');


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

The Problem

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

The Question

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

Detailed Example

Let n = 30.

The greatest divisor of:

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

It takes 6 steps to reach 1.

Input

Input is an integer n, where n ≥ 2.

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

Output

Simply output the number of steps, like 6.

Leading/trailing whitespaces or newlines are fine.

Examples

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

Requirements

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

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

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

Standard loopholes are disallowed.

This series can be found on OEIS as well: A064097

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

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

```<code>L?tbhy-b*F+1tPb0
</code>```

Try it online! (The y.v at the end is for function calling)

Original 17 bytes:

```<code>L?tb+1y-b*F+1tPb0
</code>```

Try it online! (The y.v at the end is for function calling)

(I actually answered that question with this Pyth program.)

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

L?tbhy-b*F+1tPb0

Try it online! (The y.v at the end is for function calling)

Original 17 bytes:

L?tb+1y-b*F+1tPb0

Try it online! (The y.v at the end is for function calling)

(I actually answered that question with this Pyth program.)


答:
Mathematica, 27 bytes

```<code>#~FromDigits~MixedRadix@#2&
</code>```

An unnamed function which takes the list of indices as the first argument and the list of dimensions second. Based on the same observation as Dennis's APL answer that computing the index is really just a mixed-base conversion.

Title: Index of a multidimensional array

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

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

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

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

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

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

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

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

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

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

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

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

The challenge

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

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

Test IO

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

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

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

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

Body:
Mathematica, 27 bytes

#~FromDigits~MixedRadix@#2&

An unnamed function which takes the list of indices as the first argument and the list of dimensions second. Based on the same observation as Dennis's APL answer that computing the index is really just a mixed-base conversion.


答:
Pyth - <s>15</s> <s>14</s> 13 bytes

Special casing 1 is really killing me.

```<code>tl.u-N/Nh+PN2
</code>```

Try it online here.

```<code>tl                One minus the length of
 .u               Cumulative fixed point operator implicitly on input
  -N              N -
   /N             N /
    h             Smallest prime factor
     +PN2         Prime factorization of lambda var, with two added to work with 1
</code>```

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

Body:
Inspired by this question over at Mathematics.

The Problem

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

The Question

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

Detailed Example

Let n = 30.

The greatest divisor of:

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

It takes 6 steps to reach 1.

Input

Input is an integer n, where n ≥ 2.

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

Output

Simply output the number of steps, like 6.

Leading/trailing whitespaces or newlines are fine.

Examples

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

Requirements

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

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

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

Standard loopholes are disallowed.

This series can be found on OEIS as well: A064097

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

Body:
Pyth - <s>15</s> <s>14</s> 13 bytes

Special casing 1 is really killing me.

tl.u-N/Nh+PN2

Try it online here.

tl                One minus the length of
 .u               Cumulative fixed point operator implicitly on input
  -N              N -
   /N             N /
    h             Smallest prime factor
     +PN2         Prime factorization of lambda var, with two added to work with 1


答:
05AB1E, <s>13</s> 11 bytes

Code:

```<code>[DÒ¦P-¼D#]¾
</code>```

Explanation:

```<code>[        ]   # An infinite loop and...
       D#        break out of the loop when the value is equal to 1.
 D           # Duplicate top of the stack (or in the beginning: duplicate input).
  Ò          # Get the prime factors, in the form [2, 3, 5]
   ¦         # Remove the first prime factor (the smallest one), in order to get
               the largest product.
    P        # Take the product, [3, 5] -> 15, [] -> 1.
     -       # Substract from the current value.
      ¼      # Add one to the counting variable.
          ¾  # Push the counting variable and implicitly print that value.
</code>```

Uses CP-1252 encoding. Try it online!.

Body:
05AB1E, <s>13</s> 11 bytes

Code:

[DÒ¦P-¼D#]¾

Explanation:

[        ]   # An infinite loop and...
       D#        break out of the loop when the value is equal to 1.
 D           # Duplicate top of the stack (or in the beginning: duplicate input).
  Ò          # Get the prime factors, in the form [2, 3, 5]
   ¦         # Remove the first prime factor (the smallest one), in order to get
               the largest product.
    P        # Take the product, [3, 5] -> 15, [] -> 1.
     -       # Substract from the current value.
      ¼      # Add one to the counting variable.
          ¾  # Push the counting variable and implicitly print that value.

Uses CP-1252 encoding. Try it online!.


答:
Mathematica, 36 bytes

```<code>f@1=0;f@n_:=f[n-Divisors[n][[-2]]]+1
</code>```

An unnamed function takes the same bytes:

```<code>If[#<2,0,#0[#-Divisors[#][[-2]]]+1]&
</code>```

This is a very straightforward implementation of the definition as a recursive function.

Body:
Mathematica, 36 bytes

f@1=0;f@n_:=f[n-Divisors[n][[-2]]]+1

An unnamed function takes the same bytes:

If[#<2,0,#0[#-Divisors[#][[-2]]]+1]&

This is a very straightforward implementation of the definition as a recursive function.


答:
Python 3, <s>75, 70</s>, 67 bytes.

```<code>g=lambda x,y=0:y*(x<2)or[g(x-z,y+1)for z in range(1,x)if x%z<1][-1]
</code>```

This is a pretty straight forward recursive solution. It takes a VERY long time for the high number test cases.

Body:
Python 3, <s>75, 70</s>, 67 bytes.

g=lambda x,y=0:y*(x<2)or[g(x-z,y+1)for z in range(1,x)if x%z<1][-1]

This is a pretty straight forward recursive solution. It takes a VERY long time for the high number test cases.


答:
PowerShell v2+, 81 bytes

```<code>param($a)for(;$a-gt1){for($i=$a-1;$i-gt0;$i--){if(!($a%$i)){$j++;$a-=$i;$i=0}}}$j
</code>```

Brutest of brute force.

Takes input $a, enters a for loop until $a is less than or equal to 1. Each loop we go through another for loop that counts down from $a until we find a divisor (!($a%$i). At worst, we'll find $i=1 as a divisor. When we do, increment our counter $j, subtract our divisor $a-=$i and set $i=0 to break out of the inner loop. Eventually, we'll reach a condition where the outer loop is false (i.e., $a has reached 1), so output $j and exit.

Caution: This will take a long time on larger numbers, especially primes. Input of 100,000,000 takes ~35 seconds on my Core i5 laptop. Edit -- just tested with [int]::MaxValue (2^32-1), and it took ~27 minutes. Not too bad, I suppose.

Body:
PowerShell v2+, 81 bytes

param($a)for(;$a-gt1){for($i=$a-1;$i-gt0;$i--){if(!($a%$i)){$j++;$a-=$i;$i=0}}}$j

Brutest of brute force.

Takes input $a, enters a for loop until $a is less than or equal to 1. Each loop we go through another for loop that counts down from $a until we find a divisor (!($a%$i). At worst, we'll find $i=1 as a divisor. When we do, increment our counter $j, subtract our divisor $a-=$i and set $i=0 to break out of the inner loop. Eventually, we'll reach a condition where the outer loop is false (i.e., $a has reached 1), so output $j and exit.

Caution: This will take a long time on larger numbers, especially primes. Input of 100,000,000 takes ~35 seconds on my Core i5 laptop. Edit -- just tested with [int]::MaxValue (2^32-1), and it took ~27 minutes. Not too bad, I suppose.


答:
J, 2 bytes

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

Where there's an APL, there's a J! Kind of. Takes dimensions as left arg and index as right arg. "Indexing a multidimensional array is essentially mixed base conversion."

Title: Index of a multidimensional array

Body:
J, 2 bytes

#.

Where there's an APL, there's a J! Kind of. Takes dimensions as left arg and index as right arg. "Indexing a multidimensional array is essentially mixed base conversion."


答:
Python 2, <s>50</s> 49 bytes

f=lambda n,k=1:2/n or n%(n-k)and f(n,k+1)or-~f(k)
```

<p>This isn't going to finish that last test case any time soon...</p>

<p>Alternatively, here's a 48-byte which returns <code>True</code> instead of <code>1</code> for <code>n=2</code>:</p>

```f=lambda n,k=1:n<3or n%(n-k)and f(n,k+1)or-~f(k)
```

Body:
Python 2, <s>50</s> 49 bytes

f=lambda n,k=1:2/n or n%(n-k)and f(n,k+1)or-~f(k)

This isn't going to finish that last test case any time soon...

Alternatively, here's a 48-byte which returns True instead of 1 for n=2:

f=lambda n,k=1:n<3or n%(n-k)and f(n,k+1)or-~f(k)


答:
Haskell, 34 bytes

```<code>a#b=sum$zipWith(*)(0:b)$scanr(*)1a
</code>```

Usage example: [10,10,4,62,7] # [1,2,3,4,5] -> 22167.

How it works:

```<code>      scanr(*)1a  -- build partial products of the first parameter from the right,
                  -- starting with 1, e.g. [173600,17360,1736,434,7,1]
    (0:b)         -- prepend 0 to second parameter, e.g. [0,1,2,3,4,5]
  zipWith(*)      -- multiply both lists elementwise, e.g. [0,17360,3472,1302,28,5]
sum               -- calculate sum
</code>```

Title: Index of a multidimensional array

Body:
Haskell, 34 bytes

a#b=sum$zipWith(*)(0:b)$scanr(*)1a

Usage example: [10,10,4,62,7] # [1,2,3,4,5] -> 22167.

How it works:

      scanr(*)1a  -- build partial products of the first parameter from the right,
                  -- starting with 1, e.g. [173600,17360,1736,434,7,1]
    (0:b)         -- prepend 0 to second parameter, e.g. [0,1,2,3,4,5]
  zipWith(*)      -- multiply both lists elementwise, e.g. [0,17360,3472,1302,28,5]
sum               -- calculate sum


答:
><>, 32 bytes

```<code><\?=2:-$@:$/:
1-$:@@:@%?!\
;/ln
</code>```

Expects the input number, n, on the stack.

This program builds the complete sequence on the stack. As the only number that can lead to 1 is 2, building the sequence stops when 2 is reached. This also causes the size of the stack to equal the number of steps, rather than the number of steps +1.

Body:
><>, 32 bytes

<\?=2:-$@:$/:
1-$:@@:@%?!\
;/ln

Expects the input number, n, on the stack.

This program builds the complete sequence on the stack. As the only number that can lead to 1 is 2, building the sequence stops when 2 is reached. This also causes the size of the stack to equal the number of steps, rather than the number of steps +1.


答:
Pyth, 11 bytes

```<code>fq1=-Q/QhPQ
</code>```

Test suite

A straightforward repeat-until-true loop.

Explanation:

```<code>fq1=-Q/QhPQ
               Implicit: Q = eval(input())
f              Apply the following function until it is truthy,
               incrementing T each time starting at 1:
         PQ    Take the prime factorization of Q
        h      Take its first element, the smallest factor of Q
      /Q       Divide Q by that, giving Q's largest factor
    -Q         Subtract the result from Q
   =           Assign Q to that value
 q1            Check if Q is now 1.
</code>```

Body:
Pyth, 11 bytes

fq1=-Q/QhPQ

Test suite

A straightforward repeat-until-true loop.

Explanation:

fq1=-Q/QhPQ
               Implicit: Q = eval(input())
f              Apply the following function until it is truthy,
               incrementing T each time starting at 1:
         PQ    Take the prime factorization of Q
        h      Take its first element, the smallest factor of Q
      /Q       Divide Q by that, giving Q's largest factor
    -Q         Subtract the result from Q
   =           Assign Q to that value
 q1            Check if Q is now 1.


问:
Morse code translator
Write the shortest program to transform the standard input into Morse code. Characters not in the table should be printed as they are.

答:
Python 2, <s>283</s> 274 Bytes

I created a string of alphanumerics such that their placement in the string describes their Morse code representation. Originally I was going to use binary, but 01 would be the same as 1. So I used ternary with - = 1 and . = 2. Thus is character c is at index 1121 in this string, its Morse code representation is --.-.

To save bytes, I created variables for space, dash and dot.

Then I hard coded the 'decoder' string using a couple replace statements to reduce whitespace.

The part of the function converts an index into an array of the ternary digits

The other part function takes an string and converts each character into Morse code with 3 spaces after letters and 7 (4 extra) between words

q,d,D=" .-"
s=" TE MN AI.OG KD.WR US-.QZ.YC XB- JP  L. F VH---.09  8..7--  6---.1--  2..3  45".replace(D,d*3).replace(d,q*4)
lambda n:''.join(''.join([0,D,d][i]for i in [s.index(c)//3**i%3 for i in range(5)if s.index(c)//3**i!=0][::-1])+q*3 if c!=q else q*4for c in n.upper())
```

<p><strong>Test Harness</strong></p>

<pre class="lang-py prettyprint-override"><code>print(f("Hi")=="....   ..   ")
print(f("Hello")=="....   .   .-..   .-..   ---   ")
print(f("Hello World")=="....   .   .-..   .-..   ---       .--   ---   .-.   .-..   -..   ")
print(f("To be or not to be")=="-   ---       -...   .       ---   .-.       -.   ---   -       -   ---       -...   .   ")
print(f("3 14 15")=="...--       .----   ....-       .----   .....   ")
</code>```

Update

-9 [16-05-09] Incorporated the ternary calculating function into the main function

[NOTE: There is always trailing white space but white space represents a pause, so I guest that is ok ]

Title: Morse code translator

Body:
Python 2, <s>283</s> 274 Bytes

I created a string of alphanumerics such that their placement in the string describes their Morse code representation. Originally I was going to use binary, but 01 would be the same as 1. So I used ternary with - = 1 and . = 2. Thus is character c is at index 1121 in this string, its Morse code representation is --.-.

To save bytes, I created variables for space, dash and dot.

Then I hard coded the 'decoder' string using a couple replace statements to reduce whitespace.

The part of the function converts an index into an array of the ternary digits

The other part function takes an string and converts each character into Morse code with 3 spaces after letters and 7 (4 extra) between words

q,d,D=" .-"
s=" TE MN AI.OG KD.WR US-.QZ.YC XB- JP  L. F VH---.09  8..7--  6---.1--  2..3  45".replace(D,d*3).replace(d,q*4)
lambda n:''.join(''.join([0,D,d][i]for i in [s.index(c)//3**i%3 for i in range(5)if s.index(c)//3**i!=0][::-1])+q*3 if c!=q else q*4for c in n.upper())

Test Harness

print(f("Hi")=="....   ..   ")
print(f("Hello")=="....   .   .-..   .-..   ---   ")
print(f("Hello World")=="....   .   .-..   .-..   ---       .--   ---   .-.   .-..   -..   ")
print(f("To be or not to be")=="-   ---       -...   .       ---   .-.       -.   ---   -       -   ---       -...   .   ")
print(f("3 14 15")=="...--       .----   ....-       .----   .....   ")

Update

-9 [16-05-09] Incorporated the ternary calculating function into the main function

[NOTE: There is always trailing white space but white space represents a pause, so I guest that is ok ]


问:
Finite Cantor's Diagonal
Given a list of N integers, each with N digits, output a number which differs from the first number because of the first digit, the second number because of the second digit, etc.

Example

Given this list:

```<code>1234
4815
1623
4211
</code>```

The number 2932's first digit is different from the first number's first digit, its second digit is different from the second number's second digit, etc. Therefore it would be a valid output.

Inputs

You may take both the list and N as input, or only the list if you wish.

Each integer in the list will necessarily have as many digits as the length of the list (N)

Numbers will not have any leading zeroes

The input list must contain numbers and not strings.

You may take inputs as function arguments, through STDIN, or anything similar.

You may assume that the list will not be longer than 10 elements (and no number in the list will be bigger than 2147483647)

Outputs

It is not sufficient that the output is not in the list. The digits must differ as explained above.

You can use any digit selection strategy that respects the constraint of different digits.

The number cannot have leading zeroes

You may output the number through STDOUT, return it from a function, etc.

Test cases

```<code>Input:
12345678
23456789
34567890
45678901
56789012
67890123
78901234
89012345

Possible output: 24680246

Input:
1

Possible output: 2
</code>```

Scoring

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

答:
Perl, 18 bytes

Includes +1 for -p

Run with the input lines on STDIN. Output is 1 except 2 when the diagonal is 1

cantor.pl

```<code>#!/usr/bin/perl -p
pos=$.;$_=/1\G/+1
</code>```

Title: Finite Cantor's Diagonal

Body:
Perl, 18 bytes

Includes +1 for -p

Run with the input lines on STDIN. Output is 1 except 2 when the diagonal is 1

cantor.pl

#!/usr/bin/perl -p
pos=$.;$_=/1\G/+1


答:
Matlab, 58 bytes

```<code>function p=l(a),p=0;if(a-1),p=1+l(a-a/min(factor(a)));end
</code>```

Body:
Matlab, 58 bytes

function p=l(a),p=0;if(a-1),p=1+l(a-a/min(factor(a)));end