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

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

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

Challenge

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

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

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

Standard code golf rules apply.

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

Truthy test cases

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

Falsy test cases

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
ANTLR, 31 bytes

```<code>grammar A;r:'ab'|'a'r'b'|r'\n';
</code>```

Uses the same concept as @dmckee's YACC answer, just slightly more golfed.

To test, follow the steps in ANTLR's Getting Started tutorial. Then, put the above code into a file named A.g4 and run these commands:

```<code>$ antlr A.g4
$ javac A*.java
</code>```

Then test by giving input on STDIN to grun A r like so:

```<code>$ echo "aaabbb" | grun A r
</code>```

If the input is valid, nothing will be output; if it is invalid, grun will give an error (either token recognition error, extraneous input, mismatched input, or no viable alternative).

Example usage:

```<code>$ echo "aabb" | grun A r
$ echo "abbb" | grun A r
line 1:2 mismatched input 'b' expecting {<EOF>, '
'}
</code>```

Body:
ANTLR, 31 bytes

grammar A;r:'ab'|'a'r'b'|r'\n';

Uses the same concept as @dmckee's YACC answer, just slightly more golfed.

To test, follow the steps in ANTLR's Getting Started tutorial. Then, put the above code into a file named A.g4 and run these commands:

$ antlr A.g4
$ javac A*.java

Then test by giving input on STDIN to grun A r like so:

$ echo "aaabbb" | grun A r

If the input is valid, nothing will be output; if it is invalid, grun will give an error (either token recognition error, extraneous input, mismatched input, or no viable alternative).

Example usage:

$ echo "aabb" | grun A r
$ echo "abbb" | grun A r
line 1:2 mismatched input 'b' expecting {<EOF>, '
'}


问:
Big or Little Endian
Write a program or function that outputs an L if run on a little endian architecture or a B if run on a big endian architecture. Lower case output l or b is also acceptable.

There is no input.

Scoring is code golf, so the code with the fewest bytes wins.

Edit: As per the comments below, I am clarifying that the entry must be able to run on either architecture.

I believe that there is only one answer that this affects, and that answer has clearly indicated that this is the case.

答:
Nim, <s>21</s> 20 bytes

```<code>($cpuEndian)[0].echo
</code>```

Takes the cpuEndian builtin (either littleEndian or bigEndian depending on the target CPU), stringifies it with $, takes its 0th character (l or b depending on the target CPU), and uses Nim's uniform function call syntax to echo the result.

ContentLicense: CC BY-SA 3.0

Title: Big or Little Endian

Body:
Nim, <s>21</s> 20 bytes

($cpuEndian)[0].echo

Takes the cpuEndian builtin (either littleEndian or bigEndian depending on the target CPU), stringifies it with $, takes its 0th character (l or b depending on the target CPU), and uses Nim's uniform function call syntax to echo the result.


问:
Detriplicate a string
A lot of languages have built-in ways to get rid of duplicates, or "deduplicate" or "uniquify" a list or string. A less common task is to "detriplicate" a string. That is, for every character that appears, the first two occurrences are kept.

Here is an example where the characters that should be deleted are labelled with ^:

```<code>aaabcbccdbabdcd
  ^    ^ ^^^ ^^
aabcbcdd
</code>```

Your task is to implement exactly this operation.

Rules

Input is a single, possibly empty, string. You may assume that it only contains lowercase letters in the ASCII range.

Output should be a single string with all characters removed which have already appeared at least twice in the string (so the left-most two occurrences are kept).

Instead of strings you may work with lists of characters (or singleton strings), but the format has to be consistent between input and output.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

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

Test Cases

Every pair of lines is one test case, input followed by output.

```<code>

xxxxx
xx
abcabc
abcabc
abcdabcaba
abcdabc
abacbadcba
abacbdc
aaabcbccdbabdcd
aabcbcdd
</code>```

Leaderboard

The Stack Snippet at the bottom of this post generates a leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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 + 3 (-p flag) = 45 bytes
</code>```

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

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</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

```

答:
Retina, 14 bytes

```<code>D`(.)(?<=\1.*)
</code>```

Verify all test cases. (The % enables per-line mode)

Uses the new "Deduplicate" stage to save a couple bytes over Kobi's approach. Deduplicate gathers a list of all matches to the regex and replaces all but the first with the empty string. The regex matches a character that already appears once in the string, meaning that the first two will be kept.

Title: Detriplicate a string

Body:
Retina, 14 bytes

D`(.)(?<=\1.*)

Verify all test cases. (The % enables per-line mode)

Uses the new "Deduplicate" stage to save a couple bytes over Kobi's approach. Deduplicate gathers a list of all matches to the regex and replaces all but the first with the empty string. The regex matches a character that already appears once in the string, meaning that the first two will be kept.


问:
CAPTCHA Modified by Evil Mathematician

CAPTCHA Modified by Evil Mathematician

I accidentally incurred the wrath of an eccentric passive-aggressive mathematician. As part of his demented idea of payback, he modified the CAPTCHA system on my favorite website. Up until now, it would just ask a moderately challenging math question, like 3+2^4, and I would simply type the answer, 19, to verify that I am a human being. But now, thanks to my mathematical nemesis, the CAPTCHA questions are obnoxiously hard to calculate by hand and it keeps me from logging into my profile!

From what I can tell, this is what he has done. The CAPTCHA images seem to still be the same, but the way it calculates the correct answer has changed. It takes the expression displayed in the image and rotates the operations. You wouldn't believe how long it took me to figure this out T__T.

Because of this fiasco, I need a program/function that takes in one of these expressions as a string, evaluates it and returns the result so that I can log onto my website! To make this a game, fewest bytes win.

Ok, you have the idea, lets walk through an example. Suppose that the CAPTCHA displayed an image with 6+5+4-3*2/1. Normally the answer would 9. Instead, we now have to rotate the operations to the right and that gives us 6/5+4+3-2*1. At this point, we evaluate it to be 6.2

Summary

Steps to evaluate the string input:

Rotate the operation to the right

Evaluate the result

Specifications

Full program or function

Standard I/O

Takes an expression

Prints/Returns the evaluated result

After the op rotation

Possible operations are +-/*^

The negatives for negative numbers stays with the number when rotating

Follow the normal order of operations after the rotation is completed

Using integer division is allowed

Possible numbers are positive/negative integers

This does not include 0

Parentheses could be included, but aren't rotated

Test Cases

```<code>Input     -> Output
1+3       -> 4
7+6       -> 13
1+1-2     -> 2
3*4+2     -> 11
-7^4      -> -2401
3*7+1-3   -> -1
-9+4/4    -> 1.75
(4*1)+8   -> 40
1+2-3*4/5 -> -16.5
1+-2*3    -> 1
3*4--2    -> 11
30-2/7    -> 8
120*3-4+10-> 122
(13^-12)+11 -> 1
</code>```

Update

[16-07-28] Fixed typo in last test case. I had posted the expression after rotating it once >___> , so that rotating a second time gave an incorrect answer. It is fixed now! Thanks to @sintax!

[16-08-13] Removed broke test case. Thanks again to @sintax!

答:
Matlab, 114 chars

Okay, so the last test case evaluates to Inf (once rotated, the expression 2^222222 appears...), but otherwise, all test cases hit.

Dealing with negatives, especially non-initial negatives, gave me fits.

```<code>i=input('');d=regexp(i(2:end),'[^\d|\)|\(]');d=d(~[0 d(2:end)-d(1:end-1)==1]);i(d+1)=i(1+d([end,1:end-1]));eval(i)
</code>```

Inputs should be wrapped in single quotes (e.g., '2+3/5-(12*5)'), as per Matlab standard for string inputs.

Ungolfed and commented:

```<code>i=input('');                        # Get input from stdin.
d=regexp(i(2:end),'[^\d|\)|\(]');   # Find the positions of non-digit/paren characters
                                    # in the non-initial portion of the input.
d=d(~[0 d(2:end)-d(1:end-1)==1]);    # If there are consecutive operator-type characters,
                                    # assume the second is a negativity indicator and
                                    # delete its index from our list of operator indices.
i(d+1)=i(1+d([end,1:end-1]));       # Replace each non-initial operator character of the
                                    # input with its own right-rotated operator from our
                                    # list of operator characters
eval(i)                             # Evaluate the string expression we just built.
</code>```

Title: CAPTCHA Modified by Evil Mathematician

Body:
Matlab, 114 chars

Okay, so the last test case evaluates to Inf (once rotated, the expression 2^222222 appears...), but otherwise, all test cases hit.

Dealing with negatives, especially non-initial negatives, gave me fits.

i=input('');d=regexp(i(2:end),'[^\d|\)|\(]');d=d(~[0 d(2:end)-d(1:end-1)==1]);i(d+1)=i(1+d([end,1:end-1]));eval(i)

Inputs should be wrapped in single quotes (e.g., '2+3/5-(12*5)'), as per Matlab standard for string inputs.

Ungolfed and commented:

i=input('');                        # Get input from stdin.
d=regexp(i(2:end),'[^\d|\)|\(]');   # Find the positions of non-digit/paren characters
                                    # in the non-initial portion of the input.
d=d(~[0 d(2:end)-d(1:end-1)==1]);    # If there are consecutive operator-type characters,
                                    # assume the second is a negativity indicator and
                                    # delete its index from our list of operator indices.
i(d+1)=i(1+d([end,1:end-1]));       # Replace each non-initial operator character of the
                                    # input with its own right-rotated operator from our
                                    # list of operator characters
eval(i)                             # Evaluate the string expression we just built.


问:
Removing unique elements from string
I came upon this question, because it seems to be very common use-case to find unique characters in string. But what if we want to get rid of them?

Input contains only lower case alphabets. Only letters from a to z are used. Input length may be from 1 to 1000 characters.

Example:

input: helloworld

output: llool

Objective: Shortest code wins

Language: Any of the top 20 of TIOBE languages

答:
C# – 77 characters

Func<string,string>F=s=>new string(s.Where(c=>s.Count(d=>c==d)>1).ToArray());
```

<p>If you accept the output as an array, it boils down to <strong>65</strong> characters:</p>

<pre class="lang-cs prettyprint-override"><code>Func<string,char[]>F=s=>s.Where(c=>s.Count(d=>c==d)>1).ToArray();
</code>```

Title: Removing unique elements from string

Body:
C# – 77 characters

Func<string,string>F=s=>new string(s.Where(c=>s.Count(d=>c==d)>1).ToArray());

If you accept the output as an array, it boils down to 65 characters:

Func<string,char[]>F=s=>s.Where(c=>s.Count(d=>c==d)>1).ToArray();


答:
Matlab, 67 chars

```<code>s=input('');l=num2str(length(s)/2);regexp(s,['^a{',l,'}b{',l,'}$'])
</code>```

The regular expression searches for exactly half the input's length in as consecutively at the beginning of the input string, followed by exactly half of the input's length in bs consecutively right up to the end of the input string. It returns [] on a non-even-length input, empty strings, and non-Language-L strings and only returns 1 on strings that are part of Language L.

ContentLicense: CC BY-SA 4.0

Title: Count of "a"s and "b"s must be equal. Did you get it computer?

Body:
In the popular (and essential) computer science book, An Introduction to Formal Languages and Automata by Peter Linz, the following formal language is frequently stated:

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

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

Challenge

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

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

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

Standard code golf rules apply.

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

Truthy test cases

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

Falsy test cases

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Matlab, 67 chars

s=input('');l=num2str(length(s)/2);regexp(s,['^a{',l,'}b{',l,'}$'])

The regular expression searches for exactly half the input's length in as consecutively at the beginning of the input string, followed by exactly half of the input's length in bs consecutively right up to the end of the input string. It returns [] on a non-even-length input, empty strings, and non-Language-L strings and only returns 1 on strings that are part of Language L.


问:
Convert exponents into ASCII art

Task

Your task is to convert strings like this:

```<code>abc^d+ef^g + hijk^l - M^NO^P (Ag^+)
</code>```

To strings like this:

```<code>   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )
</code>```

Which is an approximation to abcd+efg + hijkl - MNOP (Ag+)

In words, raise the characters directly next to carets to the upper line, one character for one caret.

Specs

Extra trailing whitespaces in the output are allowed.

No chained carets like m^n^o will be given as input.

A caret will not be followed immediately by a space or by another caret.

A caret will not be preceded immediately by a space.

All carets will be preceded by at least one character and followed by at least one character.

The input string will only contain printable ASCII characters (U+0020 - U+007E)

Instead of two lines of output, you are allowed to output an array of two strings.

To those who speak regex: the input string will match this regex:

```<code>/^(?!.*(\^.\^|\^\^|\^ | \^))(?!\^)[ -~]*(?<!\^)$/
</code>```

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
shell+TeX+catdvi, <s>51</s> 43 bytes

```<code>tex '\empty$'$1'$\end'>n;catdvi *i|head -n2
</code>```

Uses tex to typeset some beautiful mathematics, and then uses catdvi to make a text representation. The head command removes junk (page numbering, trailing newlines) that is otherwise present.

Edit: Why do the long, proper, thing and redirect to /dev/null when you can ignore sideeffects and write to a single letter file?

Example

Input: abc^d+ef^g + hijk^l - M^NO^P (Ag^+)

TeX output (cropped to equation):

Final output:

```<code>   d   g     l  N P   +
abc +ef +hijk -M O (Ag )
</code>```

Assumptions: Start in empty dir (or specifically a dir with no name ending in "i"). Input is a single argument to the shell script. Input is not an empty string.

Someone tell me if this is rule abuse, especially catdvi.

Title: Convert exponents into ASCII art

Body:
shell+TeX+catdvi, <s>51</s> 43 bytes

tex '\empty$'$1'$\end'>n;catdvi *i|head -n2

Uses tex to typeset some beautiful mathematics, and then uses catdvi to make a text representation. The head command removes junk (page numbering, trailing newlines) that is otherwise present.

Edit: Why do the long, proper, thing and redirect to /dev/null when you can ignore sideeffects and write to a single letter file?

Example

Input: abc^d+ef^g + hijk^l - M^NO^P (Ag^+)

TeX output (cropped to equation):

Final output:

   d   g     l  N P   +
abc +ef +hijk -M O (Ag )

Assumptions: Start in empty dir (or specifically a dir with no name ending in "i"). Input is a single argument to the shell script. Input is not an empty string.

Someone tell me if this is rule abuse, especially catdvi.


问:
Verify a Tower of Hanoi solution
If you don't know what the Tower of Hanoi is, I'll explain it briefly: There are three rods and some discs each of which has a different size. In the beginning all discs are on the first tower, in sorted order: The biggest one is at the bottom, the smallest at the top. The goal is to bring all the discs over to the third rod. Sounds easy? Here's the catch: You can't place a disc on top of a disc that is smaller than the other disc; you can only hold one disc in your hand at a time to move them to another rod and you can only place the disc on rods, not on the table, you sneaky bastard.

ascii example solution:

```<code>  A      B      C
  |      |      |
 _|_     |      |
__|__    |      |

  A      B      C
  |      |      |
  |      |      |
__|__   _|_     |

  A      B      C
  |      |      |
  |      |      |
  |     _|_   __|__

  A      B      C
  |      |      |
  |      |     _|_
  |      |    __|__
</code>```

Challenge

There are three rods called A,B and C. (You can also call them 1,2 and 3 respectivly if that helps) In the beginning all n discs are on rod A(1).

Your challenge is to verify a solution for the tower of hanoi. You'll need to make sure that:

In the end all n discs are on rod C(3).

For any given disc at any given state there is no smaller disc below it.

No obvious errors like trying to take discs from an empty rod or moving discs to nonexistant rods.

(the solution does not have to be optimal.)

Input

Your program will receive two inputs:

The number of discs n (an integer)

The moves which are taken, which will consist of a set of tuples of: (tower to take the currently uppermost disc from),(tower to take this disc to) where each tuple refers to a move. You can choose how they are represented. For example something like the following ways of representing the solution for n=2 which I've drawn in ascii above. (I'll use the first one in the test cases, because it's easy on the eyes):

"A->B ; A->C ; B->C"

[("A","B"),("A","C"),("B","C")]

[(1,2),(1,3),(2,3)]

"ABACBC"

[1,2,1,3,2,3]

Output

Truthy, if the conditions that can be found under "challenge" hold.

Falsy, if they don't.

Test cases:

True:

```<code>n=1, "A->C"

n=1, "A->B ; B->C"

n=2, "A->B ; A->C ; B->C"

n=2, "A->C ; C->B ; A->C ; B->C"

n=2, "A->C ; A->B ; C->B ; B->A ; B->C ; A->C"

n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"

n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C ; B->C"
</code>```

False:

3rd one suggested by @MartinEnder, 7th by @Joffan

```<code>n=1, "A->B"

n=1, "C->A"

n=2, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"

n=2, "A->B ; A->C ; C->B"

n=2, "A->C ; A->B ; C->B ; B->A"

n=2, "A->C ; A->C"

n=3, "A->B ; A->D; A->C ; D->C ; A->C"

n=3, "A->C ; A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; A->C"

n=3, "A->C ; A->B ; C->B ; A->B ; B->C ; B->A ; B->C ; A->C"

n=3, "A->C ; A->B ; C->B ; A->C ; B->A ; B->C ; C->B"

n=4, "A->B ; A->C ; B->C ; A->B ; C->A ; C->B ; A->B ; A->C ; B->C ; B->A ; C->A ; B->C ; A->B ; A->C"

n=4, "A->B ; A->B ; A->B ; A->C ; B->C ; B->C ; B->C"
</code>```

This is code-golf, shortest solution wins. Standard rules and loopholes apply. No batteries included.

答:
Retina, <s>84</s> 80 Bytes

-5 bytes thanks to Martin Ender

```<code>~
 ~$'
$
ABC
{`^(.)(.*)( ~+)\1
$3$2$1
}`^(\W+)(\w)(.*)(?<=\1~+|\w)\2
$3$1$2
^AB
</code>```

Try it online! (plus 5 bytes for line-by-line tests)

The code simulates a full game.

Input is given as ACABCBACBABCAC~~~.

~~~ means three discs.

First four lines convert the input to the game format: ACABCBACBABCAC ~~~ ~~ ~ABC.

In the beginning the A rod has all 3 discs, and B and C rods are empty.

Next we have a loop of two steps:

Take the first letter in the line, which indicates the next source rod. Find this rod, and take the last disc on in. Remove the letter and move the disc to the stark (pick it up).

In out example, after the first step, the text will look like:
~CABCBACBABCAC ~~~ ~~ABC.

In the second stage we find the target rod, and move the disc there. We validate the rod is empty, or has a bigger disc at the top: ABCBACBABCAC ~~~ ~~AB ~C.

Finally we confirm the A and B rods are empty - this means all discs are in C (there's an extra space at the last line).

Title: Verify a Tower of Hanoi solution

Body:
Retina, <s>84</s> 80 Bytes

-5 bytes thanks to Martin Ender

~
 ~$'
$
ABC
{`^(.)(.*)( ~+)\1
$3$2$1
}`^(\W+)(\w)(.*)(?<=\1~+|\w)\2
$3$1$2
^AB

<a href="http://retina.tryitonline.net/#code=JShHYAp-CiB-JCcKJApBQkMKe2BeKC4pKC4qKSggfispXDEKJDMkMiQxCn1gXihcVyspKFx3KSguKikoPzw9XDF-K3xcdylcMgokMyQxJDIKXkFCIA&input=QUN-CkFCQkN-CkFCQUNCQ35-CkFDQ0JBQ0JDfn4KQUNBQkNCQkFCQ0FDfn4KQUNBQkNCQUNCQUJDQUN-fn4KQUJBQ0JDQUJDQUNCQUJBQ0JDQkFDQUJDQUJBQ0JDfn5-fgpBQn4KQUNBQ34KQUNCQ34KQ0F-CkFCQUNDQn5-CkFDQUJDQkJBfn4KQUNBQ35-CkFDQUNBQkNCQUNCQUJDQUN-fn4KQUNBQkNCQUJCQ0JBQkNBQ35-fgpBQ0FCQ0JBQ0JBQkNDQn5-fgpBQkFDQkNBQkNBQ0JBQkFDQkNCQUNBQkNBQkFDfn5-fgpBQkFCQUJBQ0JDQkNCQ35-fn4KQUJBQn4KQUNBQkNCQUNCQUJDQUNDQUNBfn5-" rel="nofollow">Try it online! (plus 5 bytes for line-by-line tests)

The code simulates a full game.

Input is given as ACABCBACBABCAC~~~.

~~~ means three discs.

First four lines convert the input to the game format: ACABCBACBABCAC ~~~ ~~ ~ABC.

In the beginning the A rod has all 3 discs, and B and C rods are empty.

Next we have a loop of two steps:

Take the first letter in the line, which indicates the next source rod. Find this rod, and take the last disc on in. Remove the letter and move the disc to the stark (pick it up).

In out example, after the first step, the text will look like:
~CABCBACBABCAC ~~~ ~~ABC.

In the second stage we find the target rod, and move the disc there. We validate the rod is empty, or has a bigger disc at the top: ABCBACBABCAC ~~~ ~~AB ~C.

Finally we confirm the A and B rods are empty - this means all discs are in C (there's an extra space at the last line).


答:
TI-Basic, 35 bytes

Zero is True; anything else is False.

```<code>Input Str1
1+.5length(Str1
inString(Str1,"a",Ans) or Ans≠inString(Str1,"b
</code>```

Explanation

```<code>Input Str1                 Get string into Str1
1+.5length(Str1            Get number that is one more than half. For example, 8 gives 5.
inString(Str1,"a",Ans)     Yields zero if there is no instances of a in the second half
                               (using the number we just calculated as the start point for the search)
 or                        Both conditions need to be zero in order to output zero
Ans≠inString(Str1,"b       Yields zero if the first instance of b is the number we calculated earlier
</code>```

Body:
TI-Basic, 35 bytes

Zero is True; anything else is False.

Input Str1
1+.5length(Str1
inString(Str1,"a",Ans) or Ans≠inString(Str1,"b

Explanation

Input Str1                 Get string into Str1
1+.5length(Str1            Get number that is one more than half. For example, 8 gives 5.
inString(Str1,"a",Ans)     Yields zero if there is no instances of a in the second half
                               (using the number we just calculated as the start point for the search)
 or                        Both conditions need to be zero in order to output zero
Ans≠inString(Str1,"b       Yields zero if the first instance of b is the number we calculated earlier


答:
Ruby, 42 bytes

This is a simple solution, but unfortunately longer than many of the other Ruby solutions.

->s{s=~/^a+b+$/&&s.count(?a)==s.count(?b)}
```

<p><strong>Ungolfed:</strong></p>

<pre class="lang-ruby prettyprint-override"><code>def f(s)
  if s =~ /^a+b+$/ && s.count(?a) == s.count(?b)
    return true
  else
    return nil
  end
end
</code>```

Body:
Ruby, 42 bytes

This is a simple solution, but unfortunately longer than many of the other Ruby solutions.

->s{s=~/^a+b+$/&&s.count(?a)==s.count(?b)}

Ungolfed:

def f(s)
  if s =~ /^a+b+$/ && s.count(?a) == s.count(?b)
    return true
  else
    return nil
  end
end


问:
196 algorithm code golf
Write a short program for 196-algorithm.
The algorithm starts from an integer, then adds its reverse to it until a palindrome is reached.

e.g.

```<code>input = 5280
5280 + 0825 = 6105
6105 + 5016 = 11121
11121 + 12111 = 23232
output = 23232
</code>```

Input

an integer, which is not a lyrchrel number (that is, it does eventually yield a palindrome under this algorithm, rather than continuing infinitely)

Output

the palindrome reached.

答:
Pyke, 13 bytes (noncompeting)

```<code>D`_b]D$XIsr)h
</code>```

Try it here!

```<code> `_b          -     int(reversed(str(num))
D   ]         -    [num, ^]
     D        -   _ = ^
      $       -  delta(^)
       XI     - if ^:
         s    -  num = sum(_)
          r   -  goto_start()
            h - _[0]
</code>```

Title: 196 algorithm code golf

Body:
Pyke, 13 bytes (noncompeting)

D`_b]D$XIsr)h

Try it here!

 `_b          -     int(reversed(str(num))
D   ]         -    [num, ^]
     D        -   _ = ^
      $       -  delta(^)
       XI     - if ^:
         s    -  num = sum(_)
          r   -  goto_start()
            h - _[0]


答:
Julia, <s>24</s> 19 bytes

()->ntoh(5)>>55+'B'
```

This is an anonymous function that takes no input and returns a Char. To call it, assign it to a variable. It assumes that integers are 64-bit.

The ntoh function converts the endianness of the value passed to it from network byte order (big endian) to that used by the host computer. On big endian machines, ntoh is the identity function since there's no conversion to be done. On little endian machines, the bytes are swapped, so ntoh(5) == 360287970189639680. Which is also, perhaps more readably, equal to: 0000010100000000000000000000000000000000000000000000000000000000 in binary.

If we right bit shift the result of ntoh(5) by 55, we'll get 0 on big endian machines and 10 on little endian machines. Adding that to the character constant 'B', we'll get 'B' or 'L' for big or little endian machines, respectively.

Saved 5 bytes thanks to FryAmTheEggman and Dennis!

Title: Big or Little Endian

Body:
Write a program or function that outputs an L if run on a little endian architecture or a B if run on a big endian architecture. Lower case output l or b is also acceptable.

There is no input.

Scoring is code golf, so the code with the fewest bytes wins.

Edit: As per the comments below, I am clarifying that the entry must be able to run on either architecture.

I believe that there is only one answer that this affects, and that answer has clearly indicated that this is the case.

Body:
Julia, <s>24</s> 19 bytes

()->ntoh(5)>>55+'B'

This is an anonymous function that takes no input and returns a Char. To call it, assign it to a variable. It assumes that integers are 64-bit.

The ntoh function converts the endianness of the value passed to it from network byte order (big endian) to that used by the host computer. On big endian machines, ntoh is the identity function since there's no conversion to be done. On little endian machines, the bytes are swapped, so ntoh(5) == 360287970189639680. Which is also, perhaps more readably, equal to: 0000010100000000000000000000000000000000000000000000000000000000 in binary.

If we right bit shift the result of ntoh(5) by 55, we'll get 0 on big endian machines and 10 on little endian machines. Adding that to the character constant 'B', we'll get 'B' or 'L' for big or little endian machines, respectively.

Saved 5 bytes thanks to FryAmTheEggman and Dennis!


答:
05AB1E, 7 bytes

Code:

```<code>[DÂQ#Â+
</code>```

Explanation:

```<code>[        # Infinite loop.
 DÂ      # Duplicate and bifurcate (which duplicates it and reverses the duplicate).
   Q#    # If the number and the number reversed are equal, break.
     Â+  # Add the reversed number to the initial number.
</code>```

Uses the CP-1252 encoding. Try it online!.

Title: 196 algorithm code golf

Body:
Write a short program for 196-algorithm.
The algorithm starts from an integer, then adds its reverse to it until a palindrome is reached.

e.g.

```<code>input = 5280
5280 + 0825 = 6105
6105 + 5016 = 11121
11121 + 12111 = 23232
output = 23232
</code>```

Input

an integer, which is not a lyrchrel number (that is, it does eventually yield a palindrome under this algorithm, rather than continuing infinitely)

Output

the palindrome reached.

Body:
05AB1E, 7 bytes

Code:

[DÂQ#Â+

Explanation:

[        # Infinite loop.
 DÂ      # Duplicate and bifurcate (which duplicates it and reverses the duplicate).
   Q#    # If the number and the number reversed are equal, break.
     Â+  # Add the reversed number to the initial number.

Uses the CP-1252 encoding. Try it online!.


问:
Golf all the 16 logic gates with 2 inputs and 1 output!
For example, the gate A and B is a logic gate with 2 inputs and 1 output.

There are exactly 16 of them, because:

each logic gate takes two inputs, which can be truthy or falsey, giving us 4 possible inputs

of the 4 possible inputs, each can have an output of truthy and falsey

therefore, there are 2^4 possible logic gates, which is 16.

Your task is to write 16 programs/functions which implement all of them separately.

Your functions/programs must be independent.

They are valid as long as they output truthy/falsey values, meaning that you can implement A or B in Python as lambda a,b:a+b, even if 2 is produced for A=True and B=True.

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

0,0,1,0 (A and not B)

0,0,1,1 (A)

0,1,0,0 (not A and B)

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

1,0,1,1 (B implies A)

1,1,0,0 (not A)

1,1,0,1 (A implies B)

1,1,1,0 (nand)

1,1,1,1 (true)

Where the first number is the output for A=false, B=false,
the second number is the output for A=false, B=true,
the third number is the output for A=true, B=false,
the fourth number is the output for A=true, B=true.

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
MarioLANG, <s>176</s> 132 bytes

These solutions were all tested in Ruby interpreter and make substantial use of the implementation-specific feature that > and < can move Mario in mid-air, avoiding the need for ground tiles in many cases.

MarioLANG's only conditional is [ which skips the next command if the current cell is zero. Therefore all non-zero values are truthy and zero is falsy. I'm making use of this to shorten the code substantially by occasionally outputting -1 as truthy.

0000 (1 byte)

```<code>:
</code>```

0001 (7 bytes)

```<code>;[;
==:
</code>```

0010 (12 bytes)

```<code>;
[
>;
:-
 :
</code>```

0011 (3 bytes)

```<code>;
:
</code>```

0100 (9 bytes)

```<code>;-[;
===:
</code>```

0101 (5 bytes)

```<code>;;
=:
</code>```

0110 (12 bytes)

```<code>;
[
>;
;-
::
</code>```

0111 (10 bytes)

```<code>;
[
>:
;
:
</code>```

1000 (13 bytes)

```<code>;
[
>-
;:
-
:
</code>```

1001 (13 bytes)

```<code>;
[
>;
;:
-
:
</code>```

1010 (7 bytes)

```<code>;[;
==:
</code>```0

1011 (12 bytes)

```<code>;[;
==:
</code>```1

1100 (5 bytes)

```<code>;[;
==:
</code>```2

1101 (11 bytes)

```<code>;
[
>;
+:
:
</code>```

1110 (9 bytes)

```<code>;[;-
===:
</code>```

1111 (3 bytes)

```<code>+
:
</code>```

Body:
MarioLANG, <s>176</s> 132 bytes

These solutions were all tested in Ruby interpreter and make substantial use of the implementation-specific feature that > and < can move Mario in mid-air, avoiding the need for ground tiles in many cases.

MarioLANG's only conditional is [ which skips the next command if the current cell is zero. Therefore all non-zero values are truthy and zero is falsy. I'm making use of this to shorten the code substantially by occasionally outputting -1 as truthy.

0000 (1 byte)

:

0001 (7 bytes)

;[;
==:

0010 (12 bytes)

;
[
>;
:-
 :

0011 (3 bytes)

;
:

0100 (9 bytes)

;-[;
===:

0101 (5 bytes)

;;
=:

0110 (12 bytes)

;
[
>;
;-
::

0111 (10 bytes)

;
[
>:
;
:

1000 (13 bytes)

;
[
>-
;:
-
:

1001 (13 bytes)

;
[
>;
;:
-
:

1010 (7 bytes)

;;-
==:

1011 (12 bytes)

;
[
>:
;
-
:

1100 (5 bytes)

;-
=:

1101 (11 bytes)

;
[
>;
+:
:

1110 (9 bytes)

;[;-
===:

1111 (3 bytes)

+
:


答:
PHP - 137

Code

```<code>implode('',array_intersect(str_split($text),array_flip(array_filter(array_count_values(str_split($text)),function($x){return $x>=2;}))));
</code>```

Normal Code

```<code>$text   = 'helloworld';
$filter = array_filter(array_count_values(str_split($text)), function($x){return $x>=2;});
$output = implode('',array_intersect(str_split($text),array_flip($filter)));

echo $output;
</code>```

Title: Removing unique elements from string

Body:
I came upon this question, because it seems to be very common use-case to find unique characters in string. But what if we want to get rid of them?

Input contains only lower case alphabets. Only letters from a to z are used. Input length may be from 1 to 1000 characters.

Example:

input: helloworld

output: llool

Objective: Shortest code wins

Language: Any of the top 20 of TIOBE languages

Body:
PHP - 137

Code

implode('',array_intersect(str_split($text),array_flip(array_filter(array_count_values(str_split($text)),function($x){return $x>=2;}))));

Normal Code

$text   = 'helloworld';
$filter = array_filter(array_count_values(str_split($text)), function($x){return $x>=2;});
$output = implode('',array_intersect(str_split($text),array_flip($filter)));

echo $output;


答:
C, 27

One byte longer, but here it is anyway:

```<code>f(){putchar(htons(19522));}
</code>```

Title: Big or Little Endian

Body:
C, 27

One byte longer, but here it is anyway:

f(){putchar(htons(19522));}


答:
VBA, 151 Bytes

Type x
q As Long
End Type
Type z
w As Integer
End Type
Sub q()
Dim i As x, y As z
y.w=1
LSet i=y
Debug.? IIf(i.q=1,"L","B")
End Sub
```

Title: Big or Little Endian


问:
Prime Wednesdays

Prime Wednesdays

Your task is to count the number of Wednesdays that fall on a prime day of the month in a particular year. For instance, 7-13-16 is a prime Wednesday. For consistency use the Gregorian calendar for all dates.

Input

The input to your program/function will be a year (eg 2016) and is flexible. The year will be an integer between 1912 and 2233 inclusive.

Output

The output is also flexible and should be the number of prime Wednesdays (eg 18).

Scoring

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

Test Cases

input     -> output

  --------------------

  1912  ->   19

  1914  ->   16

  1984  ->   17

  1996  ->   19

  2063  ->   19

  2150  ->   16

  2199  ->   18

  2233  ->   18

答:
Bash + common utilities, 39

ncal $1|grep W|factor|egrep -c ': \S+$'
```
<p>Takes the input year as a command-line parameter.  Typically outputs messages like this to STDERR - I think this is legal as per this meta-answer:</p>
<pre class="lang-bash prettyprint-override"><code>factor: ‘We’ is not a valid positive integer
</code>```

If you want to explicitly suppress the STDERR output then you can do this instead for a score of 43:

ncal $1|grep W|factor 2>-|egrep -c ': \S+$'
```

Title: Prime Wednesdays

Body:
Bash + common utilities, 39

ncal $1|grep W|factor|egrep -c ': \S+$'

Takes the input year as a command-line parameter.  Typically outputs messages like this to STDERR - I think this is legal as per this meta-answer:

factor: ‘We’ is not a valid positive integer

If you want to explicitly suppress the STDERR output then you can do this instead for a score of 43:

ncal $1|grep W|factor 2>-|egrep -c ': \S+$'


问:
Teach me how to add!
Everyone knows how to add numbers by hand, right?––Well, I hope so, but for anyone who needs a quick reminder:

To add 17282 and 1342, you proceed as follows:

place the larger (value wise, not number of digits) number above the smaller number and match up the digits

```<code>17282
 1342
</code>```

draw the plus sign (+) to the left of the equation on the second row. The plus sign must be flush with the left side.

```<code> 17282
+ 1342
</code>```

draw a line of dashes (-) with one dash in each column of the digits of the first line

```<code> 17282
+ 1342
 -----
</code>```

evaluate the expression and write the digits above each column if you need to 'carry' them

```<code>   1
 17282
+ 1342
 -----
 18624
</code>```

Your output is what you get after applying step #4. You may have trailing whitespace, but there may not be any leading zeroes.

You must write a program or a function that prints or returns the output.

The input can be taken as either two separate inputs or an array with two items; the type of the inputs can be either string or integer.

This is code golf so shortest code in bytes wins!

Edit:

The largest number you could expect to receive as output/the sum is the largest integer that your system will display without exponents (thanks to Adám).

More examples:

```<code>Input:
1596, 8404
Output:
1111
 8404
+1596
 ----
10000

Input:
1776, 76
Output:
  11
 1776
+  76
 ----
 1852

Input:
123, 456
Output:
 456
+123
 ---
 579
</code>```

答:
Dyalog APL, 90 bytes

```<code>{⌽↑(⊂⌽s),⍨↓⌽(' + ',⍨' 1'⊃⍨l<⍴s),'-'⍪⍨w⍪⍨' 1'[10|(⍎¨(-l←⍴⍉w)↑s←⍕+/⍵)-(+/0 10⊤⍎)¨⊂[0]w←⍕⍪⍵]}
</code>```

Takes list of two numbers as argument. Needs ⎕IO←0 which is default on many systems.

```<code>      f←{⌽↑(⊂⌽s),⍨↓⌽(' + ',⍨' 1'⊃⍨l<⍴s),'-'⍪⍨w⍪⍨' 1'[10|(⍎¨(-l←≢⍉w)↑s←⍕+/⍵)-(+/0 10⊤⍎)¨⊂[0]w←⍕⍪⍵]}
      f¨(17282 1342)(1596 8404)(1776 76)(123 456)
┌──────┬─────┬─────┬────┐
│   1  │1111 │  11 │    │
│ 17282│ 1596│ 1776│ 123│
│+ 1342│+8404│+  76│+456│
│ -----│ ----│ ----│ ---│
│ 18624│10000│ 1852│ 579│
└──────┴─────┴─────┴────┘
</code>```

TryAPL online! Note that ⎕IO has been set and ⍎ has been emulated with e as ⍎ is banned from TryAPL for security reasons.

Ungolfed and explained

{ An anonymous function

w ← ⍕ ⍪⍵ w gets the textified vertical arrangement of the argument
    (the numbers to be added)

l ← ≢ ⍉w s gets the count of rows in the transposed w (i.e. the
    number of columns in w)

s ← ⍕ +/⍵ s gets the textified sum of the argument

' 1'[... index into the string " 1", so zeros give spaces, and ones
    give character 1s.

⊂[0] w enclose down, gets list of pairs of corresponding digits in
      the numbers

(+/ 0 10 ⊤ ⍎)¨ for each pair; make into digit(s), then sum

(⍎¨ (-l) ↑ s)- chop left-most digit of grand total to the width of
      the longest input, then make each character into separate number and
      subtract the column sums (if the sum does not add up to the total, the
      discrepancies are due to carrys, so this gives us each column's carry)

10| division remainder when divided by 10

] [end of indexing]

w⍪⍨ stack the input numbers below

'-'⍪⍨ stack a minus below each column

(' + ',⍨' 1'⊃⍨l<⍴s), prepend a space to the 2nd line, a
    plus to the 3nd, a space to the 4rd, and a one
    or space to the 1st – depending on if the sum is wider than
    the widest input (meaning we need a carry high over the plus )

⌽ mirror right-left (so left-justification will be to the right)

↓ make table into list of lines (so that differing line lengths are
    allowed

(⊂⌽s),⍨ append the sum

↑ combine list of lines into table (padding the right with spaces as
    needed)

⌽ mirror back to normal

} [end of function]`

Title: Teach me how to add!

Body:
Dyalog APL, 90 bytes

{⌽↑(⊂⌽s),⍨↓⌽(' + ',⍨' 1'⊃⍨l<⍴s),'-'⍪⍨w⍪⍨' 1'[10|(⍎¨(-l←⍴⍉w)↑s←⍕+/⍵)-(+/0 10⊤⍎)¨⊂[0]w←⍕⍪⍵]}

Takes list of two numbers as argument. Needs ⎕IO←0 which is default on many systems.

      f←{⌽↑(⊂⌽s),⍨↓⌽(' + ',⍨' 1'⊃⍨l<⍴s),'-'⍪⍨w⍪⍨' 1'[10|(⍎¨(-l←≢⍉w)↑s←⍕+/⍵)-(+/0 10⊤⍎)¨⊂[0]w←⍕⍪⍵]}
      f¨(17282 1342)(1596 8404)(1776 76)(123 456)
┌──────┬─────┬─────┬────┐
│   1  │1111 │  11 │    │
│ 17282│ 1596│ 1776│ 123│
│+ 1342│+8404│+  76│+456│
│ -----│ ----│ ----│ ---│
│ 18624│10000│ 1852│ 579│
└──────┴─────┴─────┴────┘

<a href="http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20e%u2190%7B%7B1%3D%u2374%u2375%3A%u236C%u2374%u2375%u22C4%u2375%7D%u2283%7B%u237A/%u2375%7D/%u2395VFI%20%u2375%7D%20%u22C4%20%7B%u233D%u2191%28%u2282%u233Ds%29%2C%u2368%u2193%u233D%28%27%20+%20%27%2C%u2368%27%201%27%u2283%u2368l%3C%u2262s%29%2C%27-%27%u236A%u2368w%u236A%u2368%27%201%27%5B10%7C%28e%A8%28-l%u2190%u2262%u2349w%29%u2191s%u2190%u2355+/%u2375%29-%28+/0%2010%u22A4e%29%A8%u2282%5B0%5Dw%u2190%u2355%u236A%u2375%5D%7D%A8%2817282%201342%29%281596%208404%29%281776%2076%29%28123%20456%29&run" rel="nofollow">TryAPL online! Note that ⎕IO has been set and ⍎ has been emulated with e as ⍎ is banned from TryAPL for security reasons.

Ungolfed and explained

{ An anonymous function

w ← ⍕ ⍪⍵ w gets the textified vertical arrangement of the argument
    (the numbers to be added)

l ← ≢ ⍉w s gets the count of rows in the transposed w (i.e. the
    number of columns in w)

s ← ⍕ +/⍵ s gets the textified sum of the argument

' 1'[... index into the string " 1", so zeros give spaces, and ones
    give character 1s.

⊂[0] w enclose down, gets list of pairs of corresponding digits in
      the numbers

(+/ 0 10 ⊤ ⍎)¨ for each pair; make into digit(s), then sum

(⍎¨ (-l) ↑ s)- chop left-most digit of grand total to the width of
      the longest input, then make each character into separate number and
      subtract the column sums (if the sum does not add up to the total, the
      discrepancies are due to carrys, so this gives us each column's carry)

10| division remainder when divided by 10

] [end of indexing]

w⍪⍨ stack the input numbers below

'-'⍪⍨ stack a minus below each column

(' + ',⍨' 1'⊃⍨l<⍴s), prepend a space to the 2nd line, a
    plus to the 3nd, a space to the 4rd, and a one
    or space to the 1st – depending on if the sum is wider than
    the widest input (meaning we need a carry high over the plus )

⌽ mirror right-left (so left-justification will be to the right)

↓ make table into list of lines (so that differing line lengths are
    allowed

(⊂⌽s),⍨ append the sum

↑ combine list of lines into table (padding the right with spaces as
    needed)

⌽ mirror back to normal

} [end of function]`


答:
PHP, 22 bytes

<?=ord(pack(S,1))?L:B;
```

Title: Big or Little Endian

Body:
PHP, 22 bytes

<?=ord(pack(S,1))?L:B;


答:
Ruby, <s>192</s> 191 bytes

Returns a multiline string. Input is an array with two strings.

Try it online!

```<code>->o{x,y=o.sort_by!(&:to_i).map{|e|e.reverse.chars}
a,b=o.map &:to_i
k=' '
y.zip(x).map{|z|i,j=z.map &:to_i
k=i+j+k.to_i<10?' ':1}.reverse*''+"
 %s
+%#{s=y.size}s
 %s
%#{s+1}s"%[b,a,?-*s,a+b]}
</code>```

Title: Teach me how to add!

Body:
Everyone knows how to add numbers by hand, right?––Well, I hope so, but for anyone who needs a quick reminder:

To add 17282 and 1342, you proceed as follows:

place the larger (value wise, not number of digits) number above the smaller number and match up the digits

```<code>17282
 1342
</code>```

draw the plus sign (+) to the left of the equation on the second row. The plus sign must be flush with the left side.

```<code> 17282
+ 1342
</code>```

draw a line of dashes (-) with one dash in each column of the digits of the first line

```<code> 17282
+ 1342
 -----
</code>```

evaluate the expression and write the digits above each column if you need to 'carry' them

```<code>   1
 17282
+ 1342
 -----
 18624
</code>```

Your output is what you get after applying step #4. You may have trailing whitespace, but there may not be any leading zeroes.

You must write a program or a function that prints or returns the output.

The input can be taken as either two separate inputs or an array with two items; the type of the inputs can be either string or integer.

This is code golf so shortest code in bytes wins!

Edit:

The largest number you could expect to receive as output/the sum is the largest integer that your system will display without exponents (thanks to Adám).

More examples:

```<code>Input:
1596, 8404
Output:
1111
 8404
+1596
 ----
10000

Input:
1776, 76
Output:
  11
 1776
+  76
 ----
 1852

Input:
123, 456
Output:
 456
+123
 ---
 579
</code>```

Body:
Ruby, <s>192</s> 191 bytes

Returns a multiline string. Input is an array with two strings.

Try it online!

->o{x,y=o.sort_by!(&:to_i).map{|e|e.reverse.chars}
a,b=o.map &:to_i
k=' '
y.zip(x).map{|z|i,j=z.map &:to_i
k=i+j+k.to_i<10?' ':1}.reverse*''+"
 %s
+%#{s=y.size}s
 %s
%#{s+1}s"%[b,a,?-*s,a+b]}


答:
Python 2.7, <s>201</s> <s>192</s> <s>161</s> <s>155</s> <s>167</s> <s>164</s> 182 bytes:

(Saved 2 bytes (192->190) thanks to TheBikingViking)

```<code>def Q(T,Y):O,D=sorted([T,Y]);E=len(`D`);print'%s\n %s\n+%*s\n %s\n %d'%(''.join([' ',i[0]][len(i)>1]for i in[`sum(map(int,u))`for u in zip(`D`,'%0*d'%(E,O))]),D,E,O,'-'*E,sum([T,Y]))
</code>```

A named function that takes input in any order while outputting the correct answer in order of magnitude from top to bottom.

Try it Online! (Ideone)

Alternatively, if allowed to take input in order of magnitude (i.e. bigger number first, then smallest), then here is a much smaller solution which also uses a named function at 164 bytes:

```<code>def Q(T,Y):E=len(`T`);print'%s\n %d\n+%*d\n %s\n %d'%(''.join([' ',i[0]][len(i)>1]for i in[`sum(map(int,u))`for u in zip(`T`,`Y`.zfill(E))]),T,E,Y,'-'*E,sum([T,Y]))
</code>```

Try this Version Online! (Ideone)

Title: Teach me how to add!

Body:
Python 2.7, <s>201</s> <s>192</s> <s>161</s> <s>155</s> <s>167</s> <s>164</s> 182 bytes:

(Saved 2 bytes (192->190) thanks to TheBikingViking)

def Q(T,Y):O,D=sorted([T,Y]);E=len(`D`);print'%s\n %s\n+%*s\n %s\n %d'%(''.join([' ',i[0]][len(i)>1]for i in[`sum(map(int,u))`for u in zip(`D`,'%0*d'%(E,O))]),D,E,O,'-'*E,sum([T,Y]))

A named function that takes input in any order while outputting the correct answer in order of magnitude from top to bottom.

Try it Online! (Ideone)

Alternatively, if allowed to take input in order of magnitude (i.e. bigger number first, then smallest), then here is a much smaller solution which also uses a named function at 164 bytes:

def Q(T,Y):E=len(`T`);print'%s\n %d\n+%*d\n %s\n %d'%(''.join([' ',i[0]][len(i)>1]for i in[`sum(map(int,u))`for u in zip(`T`,`Y`.zfill(E))]),T,E,Y,'-'*E,sum([T,Y]))

Try this Version Online! (Ideone)


问:
Golf the Subset-Sum Problem

Task

Given a list of space-delimited integers as input, output all unique non-empty subsets of these numbers that each subset sums to 0.

Test Case

Input:  8 −7 5 −3 −2

Output: -3 -2 5

Winning Criterion

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

答:
C# – 384 characters

OK, functional-style programming in C# is not that short, but I love it! (Using just a brute-force enumeration, nothing better.)

using System;using System.Linq;class C{static void Main(){var d=Console.ReadLine().Split(' ').Select(s=>Int32.Parse(s)).ToArray();foreach(var s in Enumerable.Range(1,(1<<d.Length)-1).Select(p=>Enumerable.Range(0,d.Length).Where(i=>(p&1<d.Where((x,i)=>p.Contains(i)).Sum()==0).Select(p=>String.Join(" ",p.Select(i=>d[i].ToString()).ToArray())))Console.WriteLine(s);}}
```

<p>Formatted and commented for more readability:</p>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.Linq;

class C
{
    static void Main()
    {
        // read the data from stdin, split by spaces, and convert to integers, nothing fancy
        var d = Console.ReadLine().Split(' ').Select(s => Int32.Parse(s)).ToArray();
        // loop through all solutions generated by the following LINQ expression
        foreach (var s in
            // first, generate all possible subsets; well, first just their numbers
            Enumerable.Range(1, (1 << d.Length) - 1)
            // convert the numbers to the real subsets of the indices in the original data (using the number as a bit mask)
            .Select(p => Enumerable.Range(0, d.Length).Where(i => (p & 1 << i) != 0))
            // and now filter those subsets only to those which sum to zero
            .Where(p => d.Where((x, i) => p.Contains(i)).Sum() == 0)
            // we have the list of solutions here! just convert them to space-delimited strings
            .Select(p => String.Join(" ", p.Select(i => d[i].ToString()).ToArray()))
        )
            // and print them!
            Console.WriteLine(s);
    }
}
</code>```

Title: Golf the Subset-Sum Problem

Body:
C# – 384 characters

OK, functional-style programming in C# is not that short, but I love it! (Using just a brute-force enumeration, nothing better.)

using System;using System.Linq;class C{static void Main(){var d=Console.ReadLine().Split(' ').Select(s=>Int32.Parse(s)).ToArray();foreach(var s in Enumerable.Range(1,(1<<d.Length)-1).Select(p=>Enumerable.Range(0,d.Length).Where(i=>(p&1<<i)!=0)).Where(p=>d.Where((x,i)=>p.Contains(i)).Sum()==0).Select(p=>String.Join(" ",p.Select(i=>d[i].ToString()).ToArray())))Console.WriteLine(s);}}

Formatted and commented for more readability:

using System;
using System.Linq;

class C
{
    static void Main()
    {
        // read the data from stdin, split by spaces, and convert to integers, nothing fancy
        var d = Console.ReadLine().Split(' ').Select(s => Int32.Parse(s)).ToArray();
        // loop through all solutions generated by the following LINQ expression
        foreach (var s in
            // first, generate all possible subsets; well, first just their numbers
            Enumerable.Range(1, (1 << d.Length) - 1)
            // convert the numbers to the real subsets of the indices in the original data (using the number as a bit mask)
            .Select(p => Enumerable.Range(0, d.Length).Where(i => (p & 1 << i) != 0))
            // and now filter those subsets only to those which sum to zero
            .Where(p => d.Where((x, i) => p.Contains(i)).Sum() == 0)
            // we have the list of solutions here! just convert them to space-delimited strings
            .Select(p => String.Join(" ", p.Select(i => d[i].ToString()).ToArray()))
        )
            // and print them!
            Console.WriteLine(s);
    }
}


答:
PowerShell, 44 bytes

```<code>[char](66+10*[BitConverter]::IsLittleEndian)
</code>```

Character 66 is B, and 10 characters later is number 76, L. A Boolean value of "true" becomes 1 when cast to a number. BitConverter is a standard .NET class.

Title: Big or Little Endian

Body:
PowerShell, 44 bytes

[char](66+10*[BitConverter]::IsLittleEndian)

Character 66 is B, and 10 characters later is number 76, L. A Boolean value of "true" becomes 1 when cast to a number. BitConverter is a standard .NET class.


答:
Lua, 31 bytes

```<code>print(("H"):pack(19522):sub(2))
</code>```

Lua 5.3 is required.

Title: Big or Little Endian

Body:
Lua, 31 bytes

print(("H"):pack(19522):sub(2))

Lua 5.3 is required.


答:
Ruby, 83 + 15 ( -rdate -rprime flags) = 98 bytes

Try it online! (Imported modules are inlined because idk if I can use flags in repl.it)

```<code>->y{k=0;Prime.each(31){|d|k+=(1..12).count{|m|Date.new(y,m,d).wday==3 rescue p}};k}
</code>```

Title: Prime Wednesdays

Body:
Prime Wednesdays

Your task is to count the number of Wednesdays that fall on a prime day of the month in a particular year. For instance, 7-13-16 is a prime Wednesday. For consistency use the Gregorian calendar for all dates.

Input

The input to your program/function will be a year (eg 2016) and is flexible. The year will be an integer between 1912 and 2233 inclusive.

Output

The output is also flexible and should be the number of prime Wednesdays (eg 18).

Scoring

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

Test Cases

input     -> output

  --------------------

  1912  ->   19

  1914  ->   16

  1984  ->   17

  1996  ->   19

  2063  ->   19

  2150  ->   16

  2199  ->   18

  2233  ->   18

Body:
Ruby, 83 + 15 ( -rdate -rprime flags) = 98 bytes

Try it online! (Imported modules are inlined because idk if I can use flags in repl.it)

->y{k=0;Prime.each(31){|d|k+=(1..12).count{|m|Date.new(y,m,d).wday==3 rescue p}};k}


问:
Do X without Y
Usually, it is said that "Doing X without Y" can be a trap to beginners writing challenges (source). However, I am cocky and think that I can definitely make an X without any Ys. Randomly. Oh yes, this will be good.

Challenge: Given an odd integer n greater than or equal to 1, output an ex of side length n made of random printable ascii characters sans "y" and "Y", and the space. All allowed characters must have a nonzero chance of occurring, but not necessarily uniform. This is a code-golf so the shortest code in bytes wins. You should, however, randomize each char--that is, the struts of the ex shouldn't be equal, unless if by chance.

The chars to appear

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

Constructing the ex

Side length 1:

```<code>x
</code>```

Side length 3:

```<code>x x
 x
x x
</code>```

Side length 5:

```<code>x   x
 x x
  x
 x x
x   x
</code>```

etc.

Example outputs

```<code>input
output
empty line

3
h 2
 ^
9 5

1
:

5
D   1
 W z
  W
 q j
W   1
</code>```

Example implementation

You do not need to handle invalid inputs.

function generate(sideLength){
    var result = "";
    var INNER = "@"
    for(var i = 0; i < sideLength; i++){
        var p = i < sideLength / 2 ? i : sideLength - i - 1;
        result += " ".repeat(p) + ((sideLength / 2 | 0) == p ? "" : INNER) + " ".repeat(Math.max(sideLength - p * 2 - 2, 0)) + INNER + "\n";
    }

    return result.replace(RegExp(INNER, "g"), function(e){
        let c = "y";
        while(c === "y" || c === "Y"){
            c = String.fromCharCode((Math.random() * 94) + 33 | 0);
        }
        return c;
    });
}

function print(v){
    output.innerHTML = "";
    output.appendChild(document.createTextNode(v));
}

function update(){
    var n = Number(input.value);
    if(n !== Math.floor(n)) print("error: " + n + " is not an integer.");
    else if(n % 2 === 0)    print("error: " + n + " is not odd.");
    else if(n < 1)          print("error: " + n + "is less than one.");
    else                    print(generate(n));
}

input.onchange = update;

update();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  font-family: Consolas, monospace;
}

#output {
  white-space: pre;
}</code>```

<input id="input" min=1 value=1 type=Number>

```

答:
C, 154 bytes (or 119 without the boiler-plate)

o(w,c){c=rand()%94+33;printf("%*c",w,w?c+!(c&95^89):10);}main(h){scanf("%d",&h);srand(time(0));for(int n=h,p;n--;)p=abs(h/2-n),o(h/2-p+1),p&&o(p*2),o(0);}
```

<p>Or 119 bytes as a function <code>X(h)</code> with <code>srand(time(0))</code> taken care of elsewhere:</p>

```o(w,c){c=rand()%94+33;printf("%*c",w,w?c+!(c&95^89):10);}X(h,n,p){for(n=h;n--;)p=abs(h/2-n),o(h/2-p+1),p&&o(p*2),o(0);}
```

<p>Breakdown:</p>

<pre class="lang-c prettyprint-override"><code>o(w,c){                         // "Output" function, for all printing
    c=rand()%94+33;             // Generate random char, whether we need it or not
    printf("%*c",               // Print a char with some number of leading spaces
           w,                   // Use "w" (width) - 1 leading spaces
           w?                   // Either print the random char...
             c+!(c&95^89)       // (exclude "y" and "Y" by incrementing to "z"/"Z")
                         :10    // ...or print a newline if called with w = 0
    );
}
main(h){                        // Main function; repurpose argc to store grid size
    scanf("%d",&h);             // Get grid size from stdin
    srand(time(0));             // Boiler-plate for random number seeding
    for(int n=h,p;n--;)         // Loop over all lines (count down to save chars)
        p=abs(h/2-n),           // Calculate half-distance between "X" bars
        o(h/2-p+1),             // Output the first half of the "X" (">")
        p&&                     // If we are not in the centre:
           o(p*2),              //   output the second half of the "X" ("<")
        o(0);                   // Output a newline
}
</code>```

Title: Do X without Y

Body:
C, 154 bytes (or 119 without the boiler-plate)

o(w,c){c=rand()%94+33;printf("%*c",w,w?c+!(c&95^89):10);}main(h){scanf("%d",&h);srand(time(0));for(int n=h,p;n--;)p=abs(h/2-n),o(h/2-p+1),p&&o(p*2),o(0);}

Or 119 bytes as a function X(h) with srand(time(0)) taken care of elsewhere:

o(w,c){c=rand()%94+33;printf("%*c",w,w?c+!(c&95^89):10);}X(h,n,p){for(n=h;n--;)p=abs(h/2-n),o(h/2-p+1),p&&o(p*2),o(0);}

Breakdown:

o(w,c){                         // "Output" function, for all printing
    c=rand()%94+33;             // Generate random char, whether we need it or not
    printf("%*c",               // Print a char with some number of leading spaces
           w,                   // Use "w" (width) - 1 leading spaces
           w?                   // Either print the random char...
             c+!(c&95^89)       // (exclude "y" and "Y" by incrementing to "z"/"Z")
                         :10    // ...or print a newline if called with w = 0
    );
}
main(h){                        // Main function; repurpose argc to store grid size
    scanf("%d",&h);             // Get grid size from stdin
    srand(time(0));             // Boiler-plate for random number seeding
    for(int n=h,p;n--;)         // Loop over all lines (count down to save chars)
        p=abs(h/2-n),           // Calculate half-distance between "X" bars
        o(h/2-p+1),             // Output the first half of the "X" (">")
        p&&                     // If we are not in the centre:
           o(p*2),              //   output the second half of the "X" ("<")
        o(0);                   // Output a newline
}


Title: Prime Wednesdays

Body:
R, <s>149</s> 147 bytes

y=function(x){s=strftime;b=ISOdate
a=seq(b(x,1,1),t=b(x,12,31),b='d')
length(a[s(a,'%u')==3&trimws(s(a,'%e'))%in%c(2,3,5,7,11,13,17,19,23,29,31)])}

Test it on Ideone.


答:
C (ansi), <s>392</s> 384 Bytes

Saved 8 thanks to Value Ink (392->384)

Code:

```<code>char c[9],d[9],p[99]=" %s\n%0s\n+%0s\n %s\n%0i",*t,*b;k,r;main(a,i,m,n)char**i;{m=strlen(i[1]);n=strlen(i[2]);m==n?(strcmp(i[1],i[2])<0?t=i[2],b=i[1]:(t=i[1],b=i[2])):m<n?t=i[2],b=i[1]:(t=i[1],b=i[2]);n>m?:(n^=m,m=n^m,n=n^m);p[18]=p[5]=1+(p[10]=48+n);while(k<n)d[k]=45,a=(n-++k>=0)*(t[n-k]-48)+(m-k>=0)*(b[m-k]-48),r+=a*pow(10,k-1),c[n-k-1]=32+(a+c[n-k]%2>9)*17;printf(p,c,t,b,d,r);}
</code>```

With Spacing:

```<code>char c[9],d[9], p[99] = " %s\n%0s\n+%0s\n %s\n%0i", *t,*b;
k,r;
main(a,i,m,n)char**i;{
    m=strlen(i[1]);     //get length of num 1
    n=strlen(i[2]);     //get length of num 2
                        //Set the larger number to the top pointer
    m==n?(strcmp(i[1],i[2])<0?t=i[2],b=i[1]:(t=i[1],b=i[2])):m<n?t=i[2],b=i[1]:(t=i[1],b=i[2]);
    n>m?:(n^=m,m=n^m,n=n^m); //set n to the longer length
    p[18]=p[5]=1+(p[10]=48+n); //set the buffers in the printf string

    while(k<n)     //for every number
        d[k]=45,   //add a dash
        a=(n-++k>=0)*(t[n-k]-48)+(m-k>=0)*(b[m-k]-48), //do the addition
        r+=a*pow(10.,(float)k-1), //add to result
        c[n-k-1]=32+(a+c[n-k]%2>9)*17;  //set 1 if carry or a space otherwise

    printf(p,c,t,b,d,r);    //print to stdio
}
</code>```

Usage:

Compile Params:

```<code>gcc -O3 -ansi -lm -o add add.c
</code>```

Input:

```<code>./add 2834 97829
</code>```

Output:

```<code>  11 1
  97829
 + 2834
  -----
 100663
</code>```

Notes:

Only works on numbers up to 8 in length - formatting is hard or I'm really bad at it

I feel like my approach was suboptimal

Title: Teach me how to add!

Body:
C (ansi), <s>392</s> 384 Bytes

Saved 8 thanks to Value Ink (392->384)

Code:

char c[9],d[9],p[99]=" %s\n%0s\n+%0s\n %s\n%0i",*t,*b;k,r;main(a,i,m,n)char**i;{m=strlen(i[1]);n=strlen(i[2]);m==n?(strcmp(i[1],i[2])<0?t=i[2],b=i[1]:(t=i[1],b=i[2])):m<n?t=i[2],b=i[1]:(t=i[1],b=i[2]);n>m?:(n^=m,m=n^m,n=n^m);p[18]=p[5]=1+(p[10]=48+n);while(k<n)d[k]=45,a=(n-++k>=0)*(t[n-k]-48)+(m-k>=0)*(b[m-k]-48),r+=a*pow(10,k-1),c[n-k-1]=32+(a+c[n-k]%2>9)*17;printf(p,c,t,b,d,r);}

With Spacing:

char c[9],d[9], p[99] = " %s\n%0s\n+%0s\n %s\n%0i", *t,*b;
k,r;
main(a,i,m,n)char**i;{
    m=strlen(i[1]);     //get length of num 1
    n=strlen(i[2]);     //get length of num 2
                        //Set the larger number to the top pointer
    m==n?(strcmp(i[1],i[2])<0?t=i[2],b=i[1]:(t=i[1],b=i[2])):m<n?t=i[2],b=i[1]:(t=i[1],b=i[2]);
    n>m?:(n^=m,m=n^m,n=n^m); //set n to the longer length
    p[18]=p[5]=1+(p[10]=48+n); //set the buffers in the printf string

    while(k<n)     //for every number
        d[k]=45,   //add a dash
        a=(n-++k>=0)*(t[n-k]-48)+(m-k>=0)*(b[m-k]-48), //do the addition
        r+=a*pow(10.,(float)k-1), //add to result
        c[n-k-1]=32+(a+c[n-k]%2>9)*17;  //set 1 if carry or a space otherwise

    printf(p,c,t,b,d,r);    //print to stdio
}

Usage:

Compile Params:

gcc -O3 -ansi -lm -o add add.c

Input:

./add 2834 97829

Output:

  11 1
  97829
 + 2834
  -----
 100663

Notes:

Only works on numbers up to 8 in length - formatting is hard or I'm really bad at it

I feel like my approach was suboptimal


答:
Batch, 248 bytes

```<code>@set/ad=0,l=1,n=20
@for /l %%i in (1913,1,%1)do @set/ad=(d+l+1)%%7,l=!(%%i%%4)-!(%%i%%100)+!(%%i%%400)
@goto %l%%d%
:03
:06
@set/an-=1
:12
:13
:16
@set/an-=1
:01
:04
:14
@set/an-=1
:00
:05
:10
:15
@set/an-=1
:02
:11
@echo %n%
</code>```

Explanation: d is the day of the week, with 0 for Monday, which is conveniently 1st Jan 1912. l is a flag for whether the year is a leap year, 1 for 1912. We then loop through from 1913 to the input year, updating the day of week and recalculating the leap year flag as we go. Finally we use the leap year flag and day of week to index into what is effectively a big switch statement to determine n, the number of prime Wednesdays. Setting n to 20 and decrementing it with fall though is cheaper than using flow control logic, but the upshot is that if the 1st of January of a non-leap year is Thursday or Sunday then there are 16 prime Wednesdays and so on for the other cases.

Title: Prime Wednesdays

Body:
Batch, 248 bytes

@set/ad=0,l=1,n=20
@for /l %%i in (1913,1,%1)do @set/ad=(d+l+1)%%7,l=!(%%i%%4)-!(%%i%%100)+!(%%i%%400)
@goto %l%%d%
:03
:06
@set/an-=1
:12
:13
:16
@set/an-=1
:01
:04
:14
@set/an-=1
:00
:05
:10
:15
@set/an-=1
:02
:11
@echo %n%

Explanation: d is the day of the week, with 0 for Monday, which is conveniently 1st Jan 1912. l is a flag for whether the year is a leap year, 1 for 1912. We then loop through from 1913 to the input year, updating the day of week and recalculating the leap year flag as we go. Finally we use the leap year flag and day of week to index into what is effectively a big switch statement to determine n, the number of prime Wednesdays. Setting n to 20 and decrementing it with fall though is cheaper than using flow control logic, but the upshot is that if the 1st of January of a non-leap year is Thursday or Sunday then there are 16 prime Wednesdays and so on for the other cases.


问:
Output a Magical 8 Trapezium
Your task is to output a Magical 8 Trapezium:

```<code>        1 × 8 + 1 = 9
       12 × 8 + 2 = 98
      123 × 8 + 3 = 987
     1234 × 8 + 4 = 9876
    12345 × 8 + 5 = 98765
   123456 × 8 + 6 = 987654
  1234567 × 8 + 7 = 9876543
 12345678 × 8 + 8 = 98765432
123456789 × 8 + 9 = 987654321
</code>```

Output in your chosen language in the fewest bytes possible.

Note the number of spaces at the start of each line to maintain the trapezium shape.

Trailing spaces are allowed.

You can use × or the letter x - whichever you prefer.

答:
JavaScript ES6 (88)

Taking advantage of the new repeat method, backticks and templating...

```<code>i=10;for(y="";--i;)console.log(`${" ".repeat(i)+(y+=(x=10-i))} x 8 + ${x} = ${y*8+x}\n`)
</code>```

Title: Output a Magical 8 Trapezium

Body:
JavaScript ES6 (88)

Taking advantage of the new repeat method, backticks and templating...

i=10;for(y="";--i;)console.log(`${" ".repeat(i)+(y+=(x=10-i))} x 8 + ${x} = ${y*8+x}\n`)


问:
What exactly was your question?

Introduction

When you are given a boring text, you just want to get it over with as quick as possible. Let's observe the following text:

```<code>Ens colligi timenda etc priorem judicem. De quascunque ii at contingere
repugnaret explicetur intellectu. Adjuvetis hoc fortassis suspicari opportune
obversari vix eam? Dei praemia prudens hominum iii constet requiri haberem. Ima
sane nemo modi fuit lus pro dem haud. Vestro age negare tactum hoc cui lor. Ne et
ut quod id soli soni deus. At constare innumera is occurret ea. Nia calebat seu
acquiro fraudem effingo dicimus.
</code>```

Note: This text has newlines for readability, while the test cases you need to handle don't have newline characters.

One way to skim text is to find questions that the writer has put into the text. For example, there is 1 question in the text above. Namely:

```<code>Adjuvetis hoc fortassis suspicari opportune obversari vix eam?
</code>```

This can be done by splitting the text into sentences. A sentence will always end with one of the following punctuation symbols: .?! (others don't have to be handled). Other symbols than these are part of the sentence.

The Task

Given a line of text consisting of only

letters (A-Za-z)

numbers (0-9)

spaces

punctuation (,.;:?!) (a sentence cannot start with one of these).

Output the questions that are in the text in any reasonable format. You may assume that the text will always have at least 1 question. Outputting trailing and leading spaces before and after a question is allowed.

Important: Next to a punctuation symbol, there will never be another punctuation symbol (e.g. ?? is invalid and will not be required to handle).

Test cases

In the format:

```<code>Input
Output(s)
</code>```

The test cases:

```<code>Huh? I haven't heard what you just said. Could you repeat that please?
Huh?
Could you repeat that please?

plz can i haz cheesburgr? i am cat pls.
plz can i haz cheesburgr?

This is a badly formatted question.Can u please help me,or my friends,with formatting this question    ?thankyou.
Can u please help me,or my friends,with formatting this question    ?

a.b.c.d?
d?

Does this question have a question mark? yes
Does this question have a question mark?

Why example.com resolves to 127.0.0.1 in 99.9 percent of cases?
9 percent of cases?

A? b? c? d!
A?
b?
c?
</code>```

This is code-golf, so the submission with the lowest number of bytes wins!

答:
Python 3, 91 bytes

```<code>def f(x,a=0):
 for n in range(len(x)):
  if x[n]in".!":a=n+1
  if x[n]is"?":print(x[a:n+1])
</code>```

Saves 1 byte in Python 2:

```<code>def f(x,a=0):
 for n in range(len(x)):
  if x[n]in".!":a=n+1
  if x[n]is"?":print x[a:n+1]
</code>```

Title: What exactly was your question?

Body:
Python 3, 91 bytes

def f(x,a=0):
 for n in range(len(x)):
  if x[n]in".!":a=n+1
  if x[n]is"?":print(x[a:n+1])

Saves 1 byte in Python 2:

def f(x,a=0):
 for n in range(len(x)):
  if x[n]in".!":a=n+1
  if x[n]is"?":print x[a:n+1]


答:
JavaScript ES6 <s>206</s> <s>203</s> <s>199</s> <s>197</s> <s>195</s> <s>183</s> <s>182</s> 179

Not the shortest, but best I can do for now... Golfing suggestions welcome...

```<code>p=n=>--d-1?n%d&&p(n):1;v=Date;D=(x,y)=>new v(x.setDate(x.getDate()-y));W=a=>eval('for(Z=0,z=D(w=new v(a,11,31),(w.getDay()+4)%7);z>new v(a,0,1);)Z+=~~p(d=z.getDate()),z=D(z,7);Z')
</code>```

Changes:

altering ternary component from: 3>=x?3-x:10-x to 6-(x+10)%7, saving: 3
Changes to declaration locations;

merged x=w.getDay();z=D(w,6-(x+10)%7) to z=D(w,6-(w.getDay()+10)%7), saving: 4

shifted Z=0 from for loop to Date declaration and pushed z=D(w,6-(x+10)%7) into for loop to tidy up, saving: 2

shifted w=new Date(a,Z=0,1) declaration into for loop, merging with existing w declaration, saving: 2

rewriting the prime finding function to a prime testing function, saving: 12

changing +!! to ~~ to reduce and still convert p(d=1) from NaN to 0, allowing Prime Test function to still work, saving: 1

Moved all extra functions out of main calling function W, redefined for loop - going in reverse from 31st Dec, writing Date object out as a separate variable, then re-wrote for loop into eval call; saving 3.

@PandaCoder, I'm catching up to you, mate!

Title: Prime Wednesdays

Body:
JavaScript ES6 <s>206</s> <s>203</s> <s>199</s> <s>197</s> <s>195</s> <s>183</s> <s>182</s> 179

Not the shortest, but best I can do for now... Golfing suggestions welcome...

p=n=>--d-1?n%d&&p(n):1;v=Date;D=(x,y)=>new v(x.setDate(x.getDate()-y));W=a=>eval('for(Z=0,z=D(w=new v(a,11,31),(w.getDay()+4)%7);z>new v(a,0,1);)Z+=~~p(d=z.getDate()),z=D(z,7);Z')

Changes:

altering ternary component from: 3>=x?3-x:10-x to 6-(x+10)%7, saving: 3
Changes to declaration locations;

merged x=w.getDay();z=D(w,6-(x+10)%7) to z=D(w,6-(w.getDay()+10)%7), saving: 4

shifted Z=0 from for loop to Date declaration and pushed z=D(w,6-(x+10)%7) into for loop to tidy up, saving: 2

shifted w=new Date(a,Z=0,1) declaration into for loop, merging with existing w declaration, saving: 2

rewriting the prime finding function to a prime testing function, saving: 12

changing +!! to ~~ to reduce and still convert p(d=1) from NaN to 0, allowing Prime Test function to still work, saving: 1

Moved all extra functions out of main calling function W, redefined for loop - going in reverse from 31st Dec, writing Date object out as a separate variable, then re-wrote for loop into eval call; saving 3.

@PandaCoder, I'm catching up to you, mate!


问:
Generate Pascal's triangle
Pascal's triangle is generated by starting with a 1 on the first row. On subsequent rows, the number is determined by the sum of the two numbers directly above it to the left and right.

To demonstrate, here are the first 5 rows of Pascal's triangle:

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

The Challenge

Given an input n (provided however is most convenient in your chosen language), generate the first n rows of Pascal's triangle. You may assume that n is an integer inclusively between 1 and 25. There must be a line break between each row and a space between each number, but aside from that, you may format it however you like.

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

Example I/O

```<code>> 1
1
> 9
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
</code>```

Title: Generate Pascal's triangle

Body:
Maple, 46

seq(print(seq(binomial(i,k),k=0..i)),i=0..n-1)

Usage:

> f:=n->seq(print(seq(binomial(i,k),k=0..i)),i=0..n-1);
> f(3)
    1
   1 1
  1 2 1


问:
Make a sprite-sheet from all the Stack Exchange sites' favicons
Your goal in this code golf is to compile all the Stack Exchange sites' favicons.

Getting the Domains

The domains you will be using will be:

*.stackexchange.com

stackexchange.com

stackoverflow.com

superuser.com

serverfault.com

askubuntu.com

mathoverflow.net

stackapps.com

stackauth.com

Everything but stackexchange.com and stackauth.com, as of now, can be gathered from /sites.

All the meta counterparts will also be included. (just prepend meta. to the beginning of any of the domains to get the meta site)

The list above shows the order of the sites. Sites without their own domain (*.stackexchange.com, i.e. codegolf.stackexchange.com) are first in the stylesheet, and are sorted alphabetically. After you've sorted the subdomain sites, the rest of the domains are in the order listed above.

Then, you can append /favicon.ico to each one of the domains you dynamically compiled and get the 32 by 32 pixel image that results from it.

Here's another list for domains that redirect to *.stackexchange.com sites:

askdifferent.com → apple.stackexchange.com

arqade.com → gaming.stackexchange.com

seasonedadvice.com → cooking.stackexchange.com

Output the Images

As soon as you have all of the favicons from the sites and their meta counterparts, your code combines them. Optionally, convert them into .PNG files (you gathered .ICOs, and trying to get favicon.png doesn't work) After that, you can start combining the images into one rectangle.

There will be 10 columns, each 32 pixels in width, making a total of 320 pixels. The number of rows will match those needed to fit all the favicons, and they are 32 pixels in height.

Your code should output an image with all of the favicons you gathered as a transparent .PNG file, which is already , like seen below:

Scoring

This is code-golf and so the least bytes wins!

Leaderboard

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

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

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

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

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

var QUESTION_ID=86753;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\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

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
JavaScript (ES6), <s>691</s> <s>687</s> <s>680</s> <s>663</s> <s>646</s> 657 bytes

fetch(new Request('//crossorigin.me/http://stackexchange.com/sites')).then(r=>r.text(t=(d=document).body.appendChild(c=d.createElement('canvas')).getContext('2d')).then(a=>(d=new DOMParser(c.width=320).parseFromString(a,'text/html'),s=[...d.querySelectorAll('.grid-view-container>a')].map(e=>!~(h=e.href[p='slice'](7))[o='indexOf']('met')?h:h[p](5)),c.height=-~(s.length/5)*32,s.sort((a,b)=>(e=a[o](k='.s'),g=b[o](k),~e&&~g?a[l='localeCompare'](b):!~e&&!~g?a[p](e)[l](b[p](g)):g-e)).concat(s.filter(u=>!~u[o]('ka')).map(u=>'meta.'+u))).map((u,i,x,y)=>(u=`http://${u}favicon.ico`,x=i%10,y=(i-x)/10,i=new Image,i.src=u,i.onload=_=>t.drawImage(i,x*32,y*32)))))```

Oof. Hopefully I can trim down the byte count.

Basically:

CORS request to /sites, parse DOM and scrape the site list from there using a query selector.

Sort first by *.stackexchange.com sites alphabetically, then by independent domain sites alphabetically.

Append the meta sites, filtering out meta.stackexchange.com and stackapps.com since they're both listed on /sites and are without their own meta site.

Asynchronously load each favicon.ico without CORS since we don't care about tainting the canvas.

Use each site's index i from the sorted array to place the loaded image in the correct position on the sprite-sheet.

You can right-click on the image and select "Save Image as", so I don't think I need to write more just to explicitly prompt the image for download, since it's already enough work just displaying it.

Revisions

Inlining global declarations saved 2 bytes. Submission is now one loooong line.

Removing () from new Image() saved another 2 bytes.

Changing Math.ceil(...) to -~(...) saved 7 bytes. Doesn't apply now, but in the event that the amount of sites is a multiple of 10, it's still okay because "There are 10 columns, which is 320 pixels in width, and unlimited rows/height" regardless of the amount of sites.

Saved 17 bytes by moving a global declaration and refactoring an unneeded ternary operator in a .map() function.

Saved another 17 bytes by storing long repeated method names to variables.

Cost 11 bytes to factor in stackexchange.com and its meta... gross.

Body:
JavaScript (ES6), <s>691</s> <s>687</s> <s>680</s> <s>663</s> <s>646</s> 657 bytes

fetch(new Request('//crossorigin.me/http://stackexchange.com/sites')).then(r=>r.text(t=(d=document).body.appendChild(c=d.createElement('canvas')).getContext('2d')).then(a=>(d=new DOMParser(c.width=320).parseFromString(a,'text/html'),s=[...d.querySelectorAll('.grid-view-container>a')].map(e=>!~(h=e.href[p='slice'](7))[o='indexOf']('met')?h:h[p](5)),c.height=-~(s.length/5)*32,s.sort((a,b)=>(e=a[o](k='.s'),g=b[o](k),~e&&~g?a[l='localeCompare'](b):!~e&&!~g?a[p](e)[l](b[p](g)):g-e)).concat(s.filter(u=>!~u[o]('ka')).map(u=>'meta.'+u))).map((u,i,x,y)=>(u=`http://${u}favicon.ico`,x=i%10,y=(i-x)/10,i=new Image,i.src=u,i.onload=_=>t.drawImage(i,x*32,y*32)))))

Oof. Hopefully I can trim down the byte count.

Basically:

CORS request to /sites, parse DOM and scrape the site list from there using a query selector.

Sort first by *.stackexchange.com sites alphabetically, then by independent domain sites alphabetically.

Append the meta sites, filtering out meta.stackexchange.com and stackapps.com since they're both listed on /sites and are without their own meta site.

Asynchronously load each favicon.ico without CORS since we don't care about tainting the canvas.

Use each site's index i from the sorted array to place the loaded image in the correct position on the sprite-sheet.

You can right-click on the image and select "Save Image as", so I don't think I need to write more just to explicitly prompt the image for download, since it's already enough work just displaying it.

Revisions

Inlining global declarations saved 2 bytes. Submission is now one loooong line.

Removing () from new Image() saved another 2 bytes.

Changing Math.ceil(...) to -~(...) saved 7 bytes. Doesn't apply now, but in the event that the amount of sites is a multiple of 10, it's still okay because "There are 10 columns, which is 320 pixels in width, and unlimited rows/height" regardless of the amount of sites.

Saved 17 bytes by moving a global declaration and refactoring an unneeded ternary operator in a .map() function.

Saved another 17 bytes by storing long repeated method names to variables.

Cost 11 bytes to factor in stackexchange.com and its meta... gross.