答:
Retina, 12 bytes

Credits to FryAmTheEggman who found this solution independently.

```<code>+`a;?b
;
^;$
</code>```

Prints 1 for valid input and 0 otherwise.

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

Balancing groups require expensive syntax, so instead I'm trying to reduce a valid input to a simple form.

Stage 1

```<code>+`a;?b
;
</code>```

The + tells Retina to repeat this stage in a loop until the output stops changing. It matches either ab or a;b and replaces it with ;. Let's consider a few cases:

If the as and the bs in the string aren't balanced in the same way that ( and ) normally need to be, some a or b will remain in the string, since ba, or b;a can't be resolved and a single a or b on its own can't either. To get rid of all the as and the bs there has to be one corresponding b to the right of each a.

If the a and the b aren't all nested (e.g. if we have something like abab or aabaabbb) then we'll end up with multiple ; (and potentially some as and bs) because the first iteration will find multiple abs to insert them and further iterations will preserve the number of ; in the string.

Hence, if and only if the input is of the form anbn, we'll end up with a single ; in the string.

Stage 2:

```<code>^;$
</code>```

Check whether the resulting string contains nothing but a single semicolon. (When I say "check" I actually mean, "count the number of matches of the given regex, but since that regex can match at most once due to the anchors, this gives either 0 or 1.)

Body:
Retina, 12 bytes

Credits to FryAmTheEggman who found this solution independently.

+`a;?b
;
^;$

Prints 1 for valid input and 0 otherwise.

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

Balancing groups require expensive syntax, so instead I'm trying to reduce a valid input to a simple form.

Stage 1

+`a;?b
;

The + tells Retina to repeat this stage in a loop until the output stops changing. It matches either ab or a;b and replaces it with ;. Let's consider a few cases:

If the as and the bs in the string aren't balanced in the same way that ( and ) normally need to be, some a or b will remain in the string, since ba, or b;a can't be resolved and a single a or b on its own can't either. To get rid of all the as and the bs there has to be one corresponding b to the right of each a.

If the a and the b aren't all nested (e.g. if we have something like abab or aabaabbb) then we'll end up with multiple ; (and potentially some as and bs) because the first iteration will find multiple abs to insert them and further iterations will preserve the number of ; in the string.

Hence, if and only if the input is of the form anbn, we'll end up with a single ; in the string.

Stage 2:

^;$

Check whether the resulting string contains nothing but a single semicolon. (When I say "check" I actually mean, "count the number of matches of the given regex, but since that regex can match at most once due to the anchors, this gives either 0 or 1.)


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

```

答:
Retina, 22 bytes

Another shorter answer in the same language just came...

```<code>^(a)+(?<-1>b)+(?(1)c)$
</code>```

Try it online!

This is a showcase of the balancing groups in regex, which is explained fully by Martin Ender.

As my explanation would not come close to half of it, I'll just link to it and not attempt to explain, as that would be detrimental to the glory of his explanation.

ContentLicense: CC BY-SA 4.0

Body:
Retina, 22 bytes

Another shorter answer in the same language just came...

^(a)+(?<-1>b)+(?(1)c)$

Try it online!

This is a showcase of the balancing groups in regex, which is explained fully by Martin Ender.

As my explanation would not come close to half of it, I'll just link to it and not attempt to explain, as that would be detrimental to the glory of his explanation.

ContentLicense: CC BY-SA 3.0


答:
05AB1E, 9 bytes

Code:

```<code>.M{J¹ÔQ0r
</code>```

Explanation:

```<code>.M         # Get the most frequent element from the input. If the count is equal, this
           results into ['a', 'b'] or ['b', 'a'].
  {        # Sort this list, which should result into ['a', 'b'].
   J       # Join this list.
    Ô      # Connected uniquified. E.g. "aaabbb" -> "ab" and "aabbaa" -> "aba".
     Q     # Check if both strings are equal.
      0r   # (Print 0 if the input is empty).
</code>```

The last two bytes can be discarded if the input is guaranteed to be non-empty.

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

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:
05AB1E, 9 bytes

Code:

.M{J¹ÔQ0r

Explanation:

.M         # Get the most frequent element from the input. If the count is equal, this
           results into ['a', 'b'] or ['b', 'a'].
  {        # Sort this list, which should result into ['a', 'b'].
   J       # Join this list.
    Ô      # Connected uniquified. E.g. "aaabbb" -> "ab" and "aabbaa" -> "aba".
     Q     # Check if both strings are equal.
      0r   # (Print 0 if the input is empty).

The last two bytes can be discarded if the input is guaranteed to be non-empty.

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


答:
Python 2, <s>43</s> 40 Bytes

```<code>lambda s:''<s==len(s)/2*"a"+len(s)/2*"b"
</code>```

Try it online! - considered the obvious solution thanks to Leaky Nun

other idea, 45 bytes:

```<code>lambda s:s and list(s)==sorted(len(s)/2*"ab")
</code>```

Try it online!

-4 bytes by using len/2 (i get an error when the half comes last)

now gives false for the empty string

-3 bytes thanks to xnor

Body:
Python 2, <s>43</s> 40 Bytes

lambda s:''<s==len(s)/2*"a"+len(s)/2*"b"

Try it online! - considered the obvious solution thanks to Leaky Nun

other idea, 45 bytes:

lambda s:s and list(s)==sorted(len(s)/2*"ab")

Try it online!

-4 bytes by using len/2 (i get an error when the half comes last)

now gives false for the empty string

-3 bytes thanks to xnor


答:
JavaScript, <s>54</s> <s>55</s> 44

```<code>s=>s&&s.match(`^a{${l=s.length/2}}b{${l}}$`)
</code>```

Builds a simple regex based on the length of the string and tests it. For a length 4 string (aabb) the regex looks like: ^a{2}b{2}$

Returns a truthy or falsey value.

11 bytes saved thanks to Neil.

f=s=>s&&s.match(`^a{${l=s.length/2}}b{${l}}$`)
// true
console.log(f('ab'), !!f('ab'))
console.log(f('aabb'), !!f('aabb'))
console.log(f('aaaaabbbbb'), !!f('aaaaabbbbb'))
// false
console.log(f('a'), !!f('a'))
console.log(f('b'), !!f('b'))
console.log(f('ba'), !!f('ba'))
console.log(f('aaab'), !!f('aaab'))
console.log(f('ababab'), !!f('ababab'))
console.log(f('c'), !!f('c'))
console.log(f('abc'), !!f('abc'))
console.log(f(''), !!f(''))```

Body:
JavaScript, <s>54</s> <s>55</s> 44

s=>s&&s.match(`^a{${l=s.length/2}}b{${l}}$`)

Builds a simple regex based on the length of the string and tests it. For a length 4 string (aabb) the regex looks like: ^a{2}b{2}$

Returns a truthy or falsey value.

11 bytes saved thanks to Neil.

f=s=>s&&s.match(`^a{${l=s.length/2}}b{${l}}$`)
// true
console.log(f('ab'), !!f('ab'))
console.log(f('aabb'), !!f('aabb'))
console.log(f('aaaaabbbbb'), !!f('aaaaabbbbb'))
// false
console.log(f('a'), !!f('a'))
console.log(f('b'), !!f('b'))
console.log(f('ba'), !!f('ba'))
console.log(f('aaab'), !!f('aaab'))
console.log(f('ababab'), !!f('ababab'))
console.log(f('c'), !!f('c'))
console.log(f('abc'), !!f('abc'))
console.log(f(''), !!f(''))


答:
Perl 5.10, <s>35</s> 17 bytes (with -n flag)

```<code>say/^(a(?1)?b)$/
</code>```

Ensures that the string starts with as and then recurses on bs. It matches only if both lengths are equal.

Thanks to Martin Ender for halving the byte count and teaching me a little about recursion in regexes :D

It returns the whole string if it matches, and nothing if not.

Try it here!

Body:
Perl 5.10, <s>35</s> 17 bytes (with -n flag)

say/^(a(?1)?b)$/

Ensures that the string starts with as and then recurses on bs. It matches only if both lengths are equal.

Thanks to Martin Ender for halving the byte count and teaching me a little about recursion in regexes :D

It returns the whole string if it matches, and nothing if not.

Try it here!


答:
Brachylog, <s>23</s> 19 bytes

```<code>@2L,?lye:"ab"rz:jaL
</code>```

Try it online!

Explanation

```<code>@2L,                  Split the input in two, the list containing the two halves is L
    ?lye              Take a number I between 0 and the length of the input
        :"ab"rz       Zip the string "ab" with that number, resulting in [["a":I]:["b":I]]
               :jaL   Apply juxtapose with that zip as input and L as output
                        i.e. "a" concatenated I times to itself makes the first string of L
                        and "b" concatenated I times to itself makes the second string of L
</code>```

Body:
Brachylog, <s>23</s> 19 bytes

@2L,?lye:"ab"rz:jaL

Try it online!

Explanation

@2L,                  Split the input in two, the list containing the two halves is L
    ?lye              Take a number I between 0 and the length of the input
        :"ab"rz       Zip the string "ab" with that number, resulting in [["a":I]:["b":I]]
               :jaL   Apply juxtapose with that zip as input and L as output
                        i.e. "a" concatenated I times to itself makes the first string of L
                        and "b" concatenated I times to itself makes the second string of L


答:
Batch, 133 bytes

```<code>@if ""=="%1" exit/b1        Fail if the input is empty
@set a=%1                   Grab the input into a variable for processing
@set b=%a:ab=%              Remove all `ab` substrings
@if "%a%"=="%b%" exit/b1    Fail if we didn't remove anything
@if not %a%==a%b%b exit/b1  Fail if we removed more than one `ab`
@if ""=="%b%" exit/b0       Success if there's nothing left to check
@%0 %b%                     Rinse and repeat
</code>```

Returns an ERRORLEVEL of 0 on success, 1 on failure. Batch doesn't like to do substring replacement on empty strings, so we have to check that up front; if an empty parameter was legal, line 6 wouldn't be necessary.

Body:
Batch, 133 bytes

@if ""=="%1" exit/b1        Fail if the input is empty
@set a=%1                   Grab the input into a variable for processing
@set b=%a:ab=%              Remove all `ab` substrings
@if "%a%"=="%b%" exit/b1    Fail if we didn't remove anything
@if not %a%==a%b%b exit/b1  Fail if we removed more than one `ab`
@if ""=="%b%" exit/b0       Success if there's nothing left to check
@%0 %b%                     Rinse and repeat

Returns an ERRORLEVEL of 0 on success, 1 on failure. Batch doesn't like to do substring replacement on empty strings, so we have to check that up front; if an empty parameter was legal, line 6 wouldn't be necessary.


问:
Return each number from a group of numbers

The challenge

The program must return all numbers included into a group (comma and hyphen separated sequence) of numbers.

Rules

s is the sequence string;

all numbers included in s are positive;

numbers will always increase;

numbers will never repeat

when you answer, show the output for s="1,3-5,9,16,18-23"

Examples

```<code>input(s)    outputs
-----------------
1           1
1,2         1,2
1-4         1,2,3,4
1-4,6       1,2,3,4,6
1-4,8-11    1,2,3,4,8,9,10,11
</code>```

Good luck. =)

答:
GolfScript (24 chars)

```<code>','/{~.,!{~)),>~}*}%','*
</code>```

E.g.

```<code>$ golfscript.rb expand.gs <<<"1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23
</code>```

I actually have four 24-char solutions, but I chose this one because it doesn't have any alphanumeric characters.

How it works

```<code># On the stack: a string such as "1,3-5,9,16,18-23"
','/
# Split on commas to get ["1" "3-5" "9" "16" "18-23"]
{
    # This is executed for each of those strings in a map
    # So stack holds e.g. "1" or "3-5"

    # Evaluate the string.
    # If it's a single number, this puts the number on the stack.
    # Otherwise it's parsed as a positive number followed by a negative number.
    ~
    # Stack holds e.g. 1 or 3 -5
    # Duplicate the last element on the stack and make a list of that length.
    # If it's negative or zero, the list will be empty
    .,
    # Negate. An empty list => 1; a non-empty list => 0
    !
    # If the string was a single number "n", the stack now holds n 0
    # If the string was a range "m-n", the stack now holds m -n 1
    # The following block will be executed 0 times for "n" and once for "m-n"
    {
        # Here we rely on twos-complement numbers satisfying ~n = -n -1
        # Stack: m -n
        ~))
        # Stack: m -(-n)-1+2  =  m n+1
        ,
        # Stack: m [0 1 2 ... n]
        >
        # Stack: [m m+1 ... n]
        ~
        # Stack: m m+1 ... n
    }*
}%
# On the stack: e.g. [1 3 4 5 9 16 18 19 20 21 22 23]
','*
# Joined by , to give the desired output
</code>```

Body:
GolfScript (24 chars)

','/{~.,!{~)),>~}*}%','*

E.g.

$ golfscript.rb expand.gs <<<"1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23

I actually have four 24-char solutions, but I chose this one because it doesn't have any alphanumeric characters.

How it works

# On the stack: a string such as "1,3-5,9,16,18-23"
','/
# Split on commas to get ["1" "3-5" "9" "16" "18-23"]
{
    # This is executed for each of those strings in a map
    # So stack holds e.g. "1" or "3-5"

    # Evaluate the string.
    # If it's a single number, this puts the number on the stack.
    # Otherwise it's parsed as a positive number followed by a negative number.
    ~
    # Stack holds e.g. 1 or 3 -5
    # Duplicate the last element on the stack and make a list of that length.
    # If it's negative or zero, the list will be empty
    .,
    # Negate. An empty list => 1; a non-empty list => 0
    !
    # If the string was a single number "n", the stack now holds n 0
    # If the string was a range "m-n", the stack now holds m -n 1
    # The following block will be executed 0 times for "n" and once for "m-n"
    {
        # Here we rely on twos-complement numbers satisfying ~n = -n -1
        # Stack: m -n
        ~))
        # Stack: m -(-n)-1+2  =  m n+1
        ,
        # Stack: m [0 1 2 ... n]
        >
        # Stack: [m m+1 ... n]
        ~
        # Stack: m m+1 ... n
    }*
}%
# On the stack: e.g. [1 3 4 5 9 16 18 19 20 21 22 23]
','*
# Joined by , to give the desired output


答:
J, <s>17</s> 15 bytes

-2 bytes thanks to Jonah!

```<code>#<.2&#-:'ab'#~#
</code>```

This works correctly for giving falsey for the empty string. Error is falsey.

Other versions:

```<code><e.'ab'<@#"{~#\       NB. alternate 15 bytes, thanks to Jonah
#<.(-:'ab'#~-:@#)

NB. the following do not handle the empty string correctly
-:'ab'#~-:@#
2&#-:'ab'#~#          NB. thanks to miles
</code>```

Proof and explanation

Outdated, but applicable to the old 17 byte version.

The main verb is a fork consisting of these three verbs:

```<code># <. (-:'ab'#~-:@#)
</code>```

This means, "The lesser of (<.) the length (#) and the result of the right tine ((-:'ab'#~-:@#))".

The right tine is a 4-train, consisting of:

```<code>(-:) ('ab') (#~) (-:@#)
</code>```

Let k represent our input. Then, this is equivalent to:

```<code>k -: ('ab' #~ -:@#) k
</code>```

-: is the match operator, so the leading -: tests for invariance under the monadic fork 'ab' #~ -:@#.

Since the left tine of the fork is a verb, it becomes a constant function. So, the fork is equivalent to:

```<code>'ab' #~ (-:@# k)
</code>```

The right tine of the fork halves (-:) the length (#) of k. Observe #:

```<code>   1 # 'ab'
'ab'
   2 # 'ab'
'aabb'
   3 # 'ab'
'aaabbb'
   'ab' #~ 3
'aaabbb'
</code>```

Now, this is k only on valid inputs, so we are done here. # errors for odd-length strings, which never satisfies the language, so there we are also done.

Combined with the lesser of the length and this, the empty string, which is not a part of our language, yields its length, 0, and we are done with it all.

Body:
J, <s>17</s> 15 bytes

-2 bytes thanks to Jonah!

#<.2&#-:'ab'#~#

This works correctly for giving falsey for the empty string. Error is falsey.

Other versions:

<e.'ab'<@#"{~#\       NB. alternate 15 bytes, thanks to Jonah
#<.(-:'ab'#~-:@#)

NB. the following do not handle the empty string correctly
-:'ab'#~-:@#
2&#-:'ab'#~#          NB. thanks to miles

Proof and explanation

Outdated, but applicable to the old 17 byte version.

The main verb is a fork consisting of these three verbs:

# <. (-:'ab'#~-:@#)

This means, "The lesser of (<.) the length (#) and the result of the right tine ((-:'ab'#~-:@#))".

The right tine is a 4-train, consisting of:

(-:) ('ab') (#~) (-:@#)

Let k represent our input. Then, this is equivalent to:

k -: ('ab' #~ -:@#) k

-: is the match operator, so the leading -: tests for invariance under the monadic fork 'ab' #~ -:@#.

Since the left tine of the fork is a verb, it becomes a constant function. So, the fork is equivalent to:

'ab' #~ (-:@# k)

The right tine of the fork halves (-:) the length (#) of k. Observe #:

   1 # 'ab'
'ab'
   2 # 'ab'
'aabb'
   3 # 'ab'
'aaabbb'
   'ab' #~ 3
'aaabbb'

Now, this is k only on valid inputs, so we are done here. # errors for odd-length strings, which never satisfies the language, so there we are also done.

Combined with the lesser of the length and this, the empty string, which is not a part of our language, yields its length, 0, and we are done with it all.


答:
PowerShell v2+, <s>61</s> 52 bytes

```<code>param($n)$x=$n.length/2;$n-and$n-match"^a{$x}b{$x}$"
</code>```

Takes input $n as a string, creates $x as half the length. Constructions an -and Boolean comparison between $n and a -match regex operator against the regex of an equal number of a's and b's. Outputs Boolean $TRUE or $FALSE. The $n-and is there to account for ""=$FALSE.

Alternate, 35 bytes

```<code>$args-match'^(a)+(?<-1>b)+(?(1)c)$'
</code>```

This uses the regex from Leaky's answer, based on .NET balancing groups, just encapsulated in the PowerShell -match operator. Returns the string for truthy, or empty string for falsey.

Body:
PowerShell v2+, <s>61</s> 52 bytes

param($n)$x=$n.length/2;$n-and$n-match"^a{$x}b{$x}$"

Takes input $n as a string, creates $x as half the length. Constructions an -and Boolean comparison between $n and a -match regex operator against the regex of an equal number of a's and b's. Outputs Boolean $TRUE or $FALSE. The $n-and is there to account for ""=$FALSE.

Alternate, 35 bytes

$args-match'^(a)+(?<-1>b)+(?(1)c)$'

This uses the regex from Leaky's answer, based on .NET balancing groups, just encapsulated in the PowerShell -match operator. Returns the string for truthy, or empty string for falsey.


答:
Pyth - 13 bytes

```<code>&zqzS*/lz2"ab
</code>```

Explained:

```<code>  qz          #is input equal to
          "ab #the string "ab"
     *        #multiplied by
      /lz2    #length of input / 2
    S         #and sorted?
&z            #(implicitly) print if the above is true and z is not empty
</code>```

Body:
Pyth - 13 bytes

&zqzS*/lz2"ab

Explained:

  qz          #is input equal to
          "ab #the string "ab"
     *        #multiplied by
      /lz2    #length of input / 2
    S         #and sorted?
&z            #(implicitly) print if the above is true and z is not empty


答:
C, 69 bytes

69 bytes:

#define f(s)strlen(s)==2*strcspn(s,"b")&strrchr(s,97)+1==strchr(s,98)

For those unfamiliar:

strlen determines the length of the string

strcspn returns the first index in string where the other string is found

strchr returns a pointer to the first occurrence of a character

strrchr returns a pointer to the last occurrence of a character

A big thanks to Titus!


答:
Pyke, 10 bytes

```<code>le"ab"*Sq&
</code>```

Try it here!

Or 9 bytes if null input isn't valid

```<code>le"ab"*Sq
</code>```

Body:
Pyke, 10 bytes

le"ab"*Sq&

Try it here!

Or 9 bytes if null input isn't valid

le"ab"*Sq


问:
Generate Pascal's Braid
This is Pascal's Braid:

```<code> 1 4  15  56   209   780    2911    10864     40545      151316      564719
1 3 11  41  153   571   2131    7953     29681     110771      413403      1542841
 1 4  15  56   209   780    2911    10864     40545      151316      564719
</code>```

I totally made that up. Blaise Pascal didn't have a braid as far as I can tell, and if he did it was probably made of hair instead of numbers.

It's defined like this:

The first column has a single 1 in the middle.

The second column has a 1 at the top and at the bottom.

Now we alternate between putting a number in the middle or two copies of a number at the top and bottom.

If the number goes on the top or the bottom, it will be the sum of the two adjacent numbers (e.g. 56 = 15 + 41). If you tilt your head a little, this is like a step in Pascal's triangle.

If the number goes in the middle, it will be the sum of all three adjacent numbers (e.g. 41 = 15 + 11 + 15).

Your task will be to print (some part of) this braid.

Input

You should write a program or function, which receives a single integer n, giving the index of the last column to be output.

You may choose whether the first column (printing only a single 1 on the middle line) corresponds to n = 0 or n = 1. This has to be a consistent choice across all possible inputs.

Output

Output Pascal's Braid up to the nth column. The whitespace has to match exactly the example layout above, except that you may pad the shorter line(s) to the length of the longer line(s) with spaces and you may optionally output a single trailing linefeed.

In other words, every column should be exactly as wide as the number (or pair of equal numbers) in that column, numbers in successive columns should not overlap and there should be no spaces between columns.

You may either print the result to STDOUT (or the closest alternative), or if you write a function you may return either a string with the same contents or a list of three strings (one for each line).

Further Details

You may assume that n won't be less than the index of the first column (so not less than 0 or 1 depending on your indexing). You may also assume that the last number in the braid is less than 256 or the largest number representable by your language's native integer type, whichever is greater. So if your native integer type can only store bytes, you can assume that the largest n is 9 or 10 (depending on whether you use 0- or 1-based n) and if it can store signed 32-bit integers, n will be at most 33 or 34.

Standard code-golf rules apply. The shortest code wins.

OEIS

Here are a few relevant OEIS links. Of course, these contain spoilers for different ways to generate the numbers in the braid:

Top/bottom: A001353 or A010905 or A106707 or A195503

Middle: A001835 or A079935

Both: A002530

Test Cases

These test cases use 1-base indexing. Each test case is four lines, with the first being the input and the remaining three being the output.

```<code>1

1

---
2
 1
1
 1
---
3
 1
1 3
 1
---
5
 1 4
1 3 11
 1 4
---
10
 1 4  15  56   209
1 3 11  41  153
 1 4  15  56   209
---
15
 1 4  15  56   209   780    2911
1 3 11  41  153   571   2131    7953
 1 4  15  56   209   780    2911
---
24
 1 4  15  56   209   780    2911    10864     40545      151316      564719       2107560
1 3 11  41  153   571   2131    7953     29681     110771      413403      1542841
 1 4  15  56   209   780    2911    10864     40545      151316      564719       2107560
</code>```

Title: Generate Pascal's Braid

Body:
PHP 265 bytes

<?php $i=$argv[1];$i=$i?$i:1;$a=[[],[]];$s=['',''];$p='';for($j=0;$j<$i;$j++){$y=($j+1)%2;$x=floor($j/2);$v=$x?$y?2*$a[0][$x-1]+$a[1][$x-1]:$a[0][$x-1]+$a[1][$x]:1;$s[$y].=$p.$v;$a[$y][$x]=$v;$p=str_pad('',strlen($v),' ');}printf("%s\n%s\n%s\n",$s[0],$s[1],$s[0]);

Un-golfed:

$a = [[],[]];
$s = ['',''];

$p = '';

$i=$argv[1];
$i=$i?$i:1;
for($j=0; $j<$i; $j++) {
    $y = ($j+1) % 2;
    $x = floor($j/2);

    if( $x == 0 ) {
        $v = 1;
    } else {
        if( $y ) {
            $v = 2 * $a[0][$x-1] + $a[1][$x-1];
        } else {
            $v = $a[0][$x-1] + $a[1][$x];
        }
    }
    $s[$y] .= $p . $v;
    $a[$y][$x] = $v;
    $p = str_pad('', strlen($v), ' ');
}

printf("%s\n%s\n%s\n", $s[0], $s[1], $s[0]);

Python 278 bytes

import sys,math;a=[[],[]];s=['',''];p='';i=int(sys.argv[1]);i=1 if i<1 else i;j=0
while j<i:y=(j+1)%2;x=int(math.floor(j/2));v=(2*a[0][x-1]+a[1][x-1] if y else a[0][x-1]+a[1][x]) if x else 1;s[y]+=p+str(v);a[y].append(v);p=' '*len(str(v));j+=1
print ("%s\n"*3)%(s[0],s[1],s[0])


问:
Validating a CPR number

Validating a CPR number

A Danish CPR number (Person Identification Number) is date of birth followed by 4 digits (the last one being a control digit): DDMMYY-XXXX

The final digit validates the CPR number using Modulo 11 by satisfying the following equation:

where the  are the ten digits of the complete ID number, and the coefficients (4, 3, 2, 7, …) are all nonzero in the finite field of order 11.

Input

A CPR number formatted like this DDMMYY-XXXX where YY indicates a year within the last 100 years (between 1917 and 2016).

Output

Indication whether CPR number is valid (1 or true) or invalid (0 or false)

Examples

```<code>  290215-2353 --> false
  140585-2981 --> true
  311217-6852 --> true
  121200-0004 --> false
  140322-5166 --> false
  111111-1118 --> true
</code>```

Scoring

This is code-golf - fewest bytes win!

Date validation

All years refer to a period within the last 100 years. A valid date is a date that exists within it's calendar year.

290215 is not a valid date because 29/2 wasn't a date in 2015.

301216 is a valid date because 30/12 is a date in 2016.

答:
Python (2), <s>167</s> <s>156</s> <s>155</s> <s>142</s> 141 bytes

from time import*
def f(s):
 try:return 1>sum(int(i)*(ord(j)-48)for i,j in zip("43276504321",s))%11;strptime(s[:6],"%d%m%y")
 except:return 0
```

<p>tried to do the date validation without the library, but it's 168 bytes:</p>

<pre class="lang-python prettyprint-override"><code>lambda s:sum(int(i)*(ord(j)-48)for i,j in zip("43276504321",s))%11==0 and int(s[0:2])<([0,32,(29,30)[int(s[4:6])%4==0],32]+[31,32]*2+[32,31]*2+[32]+[0]*99)[int(s[2:4])]
</code>```

-12 bytes thanks to @GáborFekete

-14 bytes thanks to @RootTwo

Title: Validating a CPR number

Body:
Python (2), <s>167</s> <s>156</s> <s>155</s> <s>142</s> 141 bytes

from time import*
def f(s):
 try:return 1>sum(int(i)*(ord(j)-48)for i,j in zip("43276504321",s))%11;strptime(s[:6],"%d%m%y")
 except:return 0

tried to do the date validation without the library, but it's 168 bytes:

lambda s:sum(int(i)*(ord(j)-48)for i,j in zip("43276504321",s))%11==0 and int(s[0:2])<([0,32,(29,30)[int(s[4:6])%4==0],32]+[31,32]*2+[32,31]*2+[32]+[0]*99)[int(s[2:4])]

-12 bytes thanks to @GáborFekete

-14 bytes thanks to @RootTwo


答:
MATL, 9 bytes

```<code>vHI$e!d1=
</code>```

Try it online!

The output array is truthy if it is non-empty and all its entries are nonzero. Otherwise it's falsy. Here are some examples.

```<code>v     % concatenate the stack. Since it's empty, pushes the empty array, []
H     % push 2
I$    % specify three inputs for next function
e     % reshape(input, [], 2): this takes the input implicitly and reshapes it in 2
      % columns in column major order. If the input has odd length a zero is padded at
      % the end. For input 'aaabbb' this gives the 2D char array ['ab;'ab';'ab']
!     % transpose. This gives ['aaa;'bbb']
d     % difference along each column
1=    % test if all elements are 1. If so, that means the first tow contains 'a' and
      % the second 'b'. Implicitly display
</code>```

Body:
MATL, 9 bytes

vHI$e!d1=

Try it online!

The output array is truthy if it is non-empty and all its entries are nonzero. Otherwise it's falsy. Here are some examples.

v     % concatenate the stack. Since it's empty, pushes the empty array, []
H     % push 2
I$    % specify three inputs for next function
e     % reshape(input, [], 2): this takes the input implicitly and reshapes it in 2
      % columns in column major order. If the input has odd length a zero is padded at
      % the end. For input 'aaabbb' this gives the 2D char array ['ab;'ab';'ab']
!     % transpose. This gives ['aaa;'bbb']
d     % difference along each column
1=    % test if all elements are 1. If so, that means the first tow contains 'a' and
      % the second 'b'. Implicitly display


答:
Haskell, 39 bytes

```<code>p x=elem x$scanl(\s _->'a':s++"b")"ab"x
</code>```

Usage example: p "aabb" -> True.

scanl(\s _->'a':s++"b")"ab"x build a list of all ["ab", "aabb", "aaabbb", ...] with a total of (length x) elements. elem checks if x is in this list.

Body:
Haskell, 39 bytes

p x=elem x$scanl(\s _->'a':s++"b")"ab"x

Usage example: p "aabb" -> True.

scanl(\s _->'a':s++"b")"ab"x build a list of all ["ab", "aabb", "aaabbb", ...] with a total of (length x) elements. elem checks if x is in this list.


问:
m3ph1st0s's programming puzzle 4 (C/C++): “3-way swap”
My last puzzle has generated some confusion and controversy so I decided to give up, for now, on those "replace one character"-type puzzles.

Hope this 4th puzzle will redeem myself after all the edits in puzzle 3 and will put your brains at work once more.

I've really put up all the effort to make this one as clear as possible and hope you will enjoy it!

So here it goes:

We start from a very short C program:

```<code>int main() {
   int a = 93;
   int b = 11;
   int c = 22528;

   // insert your code here

}
</code>```

Your job will be to swap the values of the variables a,b,c like this: a <= b, b <= c, c <= a. To make it even more clear: new a = old b, new b = old c, new c = old a.

You are required to do this by inserting one single instruction in the line indicated by the comment in the code. To be clear once again, this line will contain only one semicolon (;) indicating the end of the lone instruction. After the execution of this program, a will contain 11, b will contain 22528, c will contain 93.
However, there are some conditions that need to be met. So we'll have 4 different puzzles with different cryteria.

4.1. Do it by using whatever you want. Just one statement. -> most creative solution wins this one.

4.2. Do it without using any comma (,). -> most creative wins

4.3. Do it without any comma and with no more than 4 letters (+any other characters). -> shortest code wins

4.4. Do it without any comma and with no more than 4 letters and no more than 4 digits (+any other characters). -> shortest code wins

To make sure you understood, here's some code that is valid under the condition required but does not solve the problem:

4.1:

```<code>I_hereby_call_my_beautiful_function(nice_argument), int q=w, who_the_hell_is(w)+1;
</code>```

4.2:

```<code>one = single + assignment;
</code>```

4.3:

```<code>int w=12345678;
</code>```

4.4:

```<code>int w=1234;
</code>```

P.S. In case you haven't already noticed, 4.4 is the tough one here (I hope :D).

答:
For 4.4 (14 characters, 1 digit and 4 letters):

```<code>int main()
{
  int a = 93;
  int b = 11;
  int c = 22528;

  b<<=a=(c=a)/8;
}
</code>```

VS2010 with /Wall didn't show any warnings, but I'm still a bit suspicious about using a twice in there (even though it's only modified once).

Body:
For 4.4 (14 characters, 1 digit and 4 letters):

int main()
{
  int a = 93;
  int b = 11;
  int c = 22528;

  b<<=a=(c=a)/8;
}

VS2010 with /Wall didn't show any warnings, but I'm still a bit suspicious about using a twice in there (even though it's only modified once).


答:
Befunge-93, 67 bytes

```<code>0v@.<  0<@.!-$<  >0\v
+>~:0`!#^_:"a" -#^_$ 1
~+1_^#!-"b" _ ^#`0: <
</code>```

Try it here! Might explain how it works later. Might also try to golf it just a tad bit more, just for kicks.

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:
Befunge-93, 67 bytes

0v@.<  0<@.!-$<  >0\v
+>~:0`!#^_:"a" -#^_$ 1
~+1_^#!-"b" _ ^#`0: <

Try it here! Might explain how it works later. Might also try to golf it just a tad bit more, just for kicks.


答:
C, 183 177 176 bytes

```<code>#define F for(i=0;i<c;i++)
int i,c,a[35],t[9];p(r){F printf("%*s",sprintf(t,"%d",a[i]),r-i&1?t:" ");putchar(10);}b(n){c=n;F a[i]=i<2?1:a[i-2]+a[i-1]*(i&1?1:2);p(0);p(1);p(0);}
</code>```

Explanation

C is never going to win any prizes for brevity against a higher level language, but the exercise is interesting and good practice.

The macro F shaves off six bytes at the cost of readability. Variables are declared globally to avoid multiple declarations. I needed a character buffer for sprintf, but since K&R is loose with type checking, sprintf and printf can interpret t[9] as a pointer to a 36-byte buffer. This saves a separate declaration.

```<code>#define F for(i=0;i<c;i++)
int i,c,a[35],t[9];
</code>```

Pretty printing function, where r is the row number. Sprintf formats the number and computes the column width. To save space we just call this three times, one for each row of output; the expression r-i&1 filters what gets printed.

```<code>p(r) {
    F
        printf("%*s", sprintf(t, "%d", a[i]), r-i&1 ? t
                                                    : " ");
    putchar(10);
}
</code>```

Entry point function, argument is number of columns. Computes array a of column values a[], then calls printing function p once for each row of output.

```<code>b(n) {
    c=n;
    F
        a[i] = i<2 ? 1
                   : a[i-2] + a[i-1]*(i&1 ? 1
                                          : 2);
    p(0);
    p(1);
    p(0);
}
</code>```

Sample invocation (not included in answer and byte count):

```<code>main(c,v) char**v;
{
    b(atoi(v[1]));
}
</code>```

Updated

Incorporated the inline sprintf suggestion from tomsmeding. That reduced the count from 183 to 177 characters. This also allows removing the the braces around the printf(sprintf()) block since it's only one statement now, but that only saved one character because it still needs a space as a delimiter. So down to 176.

Title: Generate Pascal's Braid

Body:
This is Pascal's Braid:

```<code> 1 4  15  56   209   780    2911    10864     40545      151316      564719
1 3 11  41  153   571   2131    7953     29681     110771      413403      1542841
 1 4  15  56   209   780    2911    10864     40545      151316      564719
</code>```

I totally made that up. Blaise Pascal didn't have a braid as far as I can tell, and if he did it was probably made of hair instead of numbers.

It's defined like this:

The first column has a single 1 in the middle.

The second column has a 1 at the top and at the bottom.

Now we alternate between putting a number in the middle or two copies of a number at the top and bottom.

If the number goes on the top or the bottom, it will be the sum of the two adjacent numbers (e.g. 56 = 15 + 41). If you tilt your head a little, this is like a step in Pascal's triangle.

If the number goes in the middle, it will be the sum of all three adjacent numbers (e.g. 41 = 15 + 11 + 15).

Your task will be to print (some part of) this braid.

Input

You should write a program or function, which receives a single integer n, giving the index of the last column to be output.

You may choose whether the first column (printing only a single 1 on the middle line) corresponds to n = 0 or n = 1. This has to be a consistent choice across all possible inputs.

Output

Output Pascal's Braid up to the nth column. The whitespace has to match exactly the example layout above, except that you may pad the shorter line(s) to the length of the longer line(s) with spaces and you may optionally output a single trailing linefeed.

In other words, every column should be exactly as wide as the number (or pair of equal numbers) in that column, numbers in successive columns should not overlap and there should be no spaces between columns.

You may either print the result to STDOUT (or the closest alternative), or if you write a function you may return either a string with the same contents or a list of three strings (one for each line).

Further Details

You may assume that n won't be less than the index of the first column (so not less than 0 or 1 depending on your indexing). You may also assume that the last number in the braid is less than 256 or the largest number representable by your language's native integer type, whichever is greater. So if your native integer type can only store bytes, you can assume that the largest n is 9 or 10 (depending on whether you use 0- or 1-based n) and if it can store signed 32-bit integers, n will be at most 33 or 34.

Standard code-golf rules apply. The shortest code wins.

OEIS

Here are a few relevant OEIS links. Of course, these contain spoilers for different ways to generate the numbers in the braid:

Top/bottom: A001353 or A010905 or A106707 or A195503

Middle: A001835 or A079935

Both: A002530

Test Cases

These test cases use 1-base indexing. Each test case is four lines, with the first being the input and the remaining three being the output.

```<code>1

1

---
2
 1
1
 1
---
3
 1
1 3
 1
---
5
 1 4
1 3 11
 1 4
---
10
 1 4  15  56   209
1 3 11  41  153
 1 4  15  56   209
---
15
 1 4  15  56   209   780    2911
1 3 11  41  153   571   2131    7953
 1 4  15  56   209   780    2911
---
24
 1 4  15  56   209   780    2911    10864     40545      151316      564719       2107560
1 3 11  41  153   571   2131    7953     29681     110771      413403      1542841
 1 4  15  56   209   780    2911    10864     40545      151316      564719       2107560
</code>```

Body:
C, 183 177 176 bytes

#define F for(i=0;i<c;i++)
int i,c,a[35],t[9];p(r){F printf("%*s",sprintf(t,"%d",a[i]),r-i&1?t:" ");putchar(10);}b(n){c=n;F a[i]=i<2?1:a[i-2]+a[i-1]*(i&1?1:2);p(0);p(1);p(0);}

Explanation

C is never going to win any prizes for brevity against a higher level language, but the exercise is interesting and good practice.

The macro F shaves off six bytes at the cost of readability. Variables are declared globally to avoid multiple declarations. I needed a character buffer for sprintf, but since K&R is loose with type checking, sprintf and printf can interpret t[9] as a pointer to a 36-byte buffer. This saves a separate declaration.

#define F for(i=0;i<c;i++)
int i,c,a[35],t[9];

Pretty printing function, where r is the row number. Sprintf formats the number and computes the column width. To save space we just call this three times, one for each row of output; the expression r-i&1 filters what gets printed.

p(r) {
    F
        printf("%*s", sprintf(t, "%d", a[i]), r-i&1 ? t
                                                    : " ");
    putchar(10);
}

Entry point function, argument is number of columns. Computes array a of column values a[], then calls printing function p once for each row of output.

b(n) {
    c=n;
    F
        a[i] = i<2 ? 1
                   : a[i-2] + a[i-1]*(i&1 ? 1
                                          : 2);
    p(0);
    p(1);
    p(0);
}

Sample invocation (not included in answer and byte count):

main(c,v) char**v;
{
    b(atoi(v[1]));
}

Updated

Incorporated the inline sprintf suggestion from tomsmeding. That reduced the count from 183 to 177 characters. This also allows removing the the braces around the printf(sprintf()) block since it's only one statement now, but that only saved one character because it still needs a space as a delimiter. So down to 176.


问:
Draw a ladder and slide
Your task is to create a program or function that takes, as input, a natural number (n) between 1 and 25 (inclusive) and prints an isometric representation of a slide and ladder with n number of rungs.

Ladder and slide specifications

The ladder is always oriented on the left and the slide on the right. We're viewing it from the ladder side, so part of the slide is obscured at the top three levels. The rungs are represented by four dashes (----) and the sides of the ladder and slide by slashes (/ and \). The following is a diagram to represent the patterns of spaces needed for a slide with five rungs.

```<code>Slide              Blank space count
    /----/\        1234/----/\
   /----/  \       123/----/12\
  /----/    \      12/----/1234\
 /----/ \    \     1/----/1\1234\
/----/   \    \    /----/123\1234\
</code>```

Examples

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

>>3
  /----/\
 /----/  \
/----/    \

>>4
   /----/\
  /----/  \
 /----/    \
/----/ \    \

>>10
         /----/\
        /----/  \
       /----/    \
      /----/ \    \
     /----/   \    \
    /----/     \    \
   /----/       \    \
  /----/         \    \
 /----/           \    \
/----/             \    \
</code>```

This is code-golf, so the answer with the lowest byte count wins.

Note: trailing white space is acceptable in the output, as long as it doesn't exceed the length of the line.

答:
Java, 116 bytes

```<code>c->{for(int i=0;i<c;i++)System.out.format("%"+(5+c-i)+"s%"+(i<3?i*2+1:2*(i-2))+"s%5s\n","/----/","\\",i<3?"":"\\");};
</code>```

Unfortunately, you can't [easily] duplicate strings in Java, so I end up abusing the format function.

Title: Draw a ladder and slide

Body:
Java, 116 bytes

c->{for(int i=0;i<c;i++)System.out.format("%"+(5+c-i)+"s%"+(i<3?i*2+1:2*(i-2))+"s%5s\n","/----/","\\",i<3?"":"\\");};

Unfortunately, you can't [easily] duplicate strings in Java, so I end up abusing the format function.


Body:
C, 65 bytes

m,t;C(char*c){for(m=1,t=0;*c;)m>0&*c++-97&&(m-=2),t+=m;return!t;}


答:
Haskell, 31 bytes

f s=s==[c|c<-"ab",'a'<-s]&&s>""
```

The list comprehension [c|c<-"ab",'a'<-s] makes a string of one 'a' for each 'a' in s, followed by one 'b' for each 'a' in s. It avoids counting by matching on a constant and producing an output for each match.

This string is checked to be equal to the original string, and the original string is checked to be non-empty.

Body:
Haskell, 31 bytes

f s=s==[c|c<-"ab",'a'<-s]&&s>""

The list comprehension [c|c<-"ab",'a'<-s] makes a string of one 'a' for each 'a' in s, followed by one 'b' for each 'a' in s. It avoids counting by matching on a constant and producing an output for each match.

This string is checked to be equal to the original string, and the original string is checked to be non-empty.


答:
eacal, noncompeting, 386 bytes

```<code>init .
define @ curry push .
define ~ curry exec .--func
alias $ strap
alias ' string
set n set m cast number arg number 0
set s empty string
label l
@ get n
set n ~ dec
@ space
@ get n
$ ~ repeat
$ ' /----/
@ space
@ get m
@ get n
@ ~ sub
@ ~ dec
@ number 2
@ ~ mul
$ ~ repeat
$ ' \
$ newline
@ get n
@ number 0
if ~ more
goto l
@ $
@ regex gm '   ( {4})(?=.$)
@ '  \$1
print ~ replace
</code>```

<s>I have officially made the most verbose language possible.</s> I made the comment in jest and in sarcasm. Please calm down. Instructions on how to run in the github repo linked in the header.

Ungolfed

```<code>init .
set n set m cast number arg number 0
set s empty string
label loop
    push . get n
    set n exec .--func dec
    push . space
    push . get n
    strap exec .--func repeat
    strap string /----/
    push . space
    push . get m
    push . get n
    push . exec .--func sub
    push . exec .--func dec
    push . number 2
    push . exec .--func mul
    strap exec .--func repeat
    strap string \
    strap newline
    push . get n
    push . number 0
    if exec .--func more
        goto loop

push . strap
push . regex gm string   ( {4})(?=.$)
push . string  \$1
print exec .--func replace
</code>```

Title: Draw a ladder and slide

Body:
Your task is to create a program or function that takes, as input, a natural number (n) between 1 and 25 (inclusive) and prints an isometric representation of a slide and ladder with n number of rungs.

Ladder and slide specifications

The ladder is always oriented on the left and the slide on the right. We're viewing it from the ladder side, so part of the slide is obscured at the top three levels. The rungs are represented by four dashes (----) and the sides of the ladder and slide by slashes (/ and \). The following is a diagram to represent the patterns of spaces needed for a slide with five rungs.

```<code>Slide              Blank space count
    /----/\        1234/----/\
   /----/  \       123/----/12\
  /----/    \      12/----/1234\
 /----/ \    \     1/----/1\1234\
/----/   \    \    /----/123\1234\
</code>```

Examples

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

>>3
  /----/\
 /----/  \
/----/    \

>>4
   /----/\
  /----/  \
 /----/    \
/----/ \    \

>>10
         /----/\
        /----/  \
       /----/    \
      /----/ \    \
     /----/   \    \
    /----/     \    \
   /----/       \    \
  /----/         \    \
 /----/           \    \
/----/             \    \
</code>```

This is code-golf, so the answer with the lowest byte count wins.

Note: trailing white space is acceptable in the output, as long as it doesn't exceed the length of the line.

Body:
eacal, noncompeting, 386 bytes

init .
define @ curry push .
define ~ curry exec .--func
alias $ strap
alias ' string
set n set m cast number arg number 0
set s empty string
label l
@ get n
set n ~ dec
@ space
@ get n
$ ~ repeat
$ ' /----/
@ space
@ get m
@ get n
@ ~ sub
@ ~ dec
@ number 2
@ ~ mul
$ ~ repeat
$ ' \
$ newline
@ get n
@ number 0
if ~ more
goto l
@ $
@ regex gm '   ( {4})(?=.$)
@ '  \$1
print ~ replace

<s>I have officially made the most verbose language possible.</s> I made the comment in jest and in sarcasm. Please calm down. Instructions on how to run in the github repo linked in the header.

Ungolfed

init .
set n set m cast number arg number 0
set s empty string
label loop
    push . get n
    set n exec .--func dec
    push . space
    push . get n
    strap exec .--func repeat
    strap string /----/
    push . space
    push . get m
    push . get n
    push . exec .--func sub
    push . exec .--func dec
    push . number 2
    push . exec .--func mul
    strap exec .--func repeat
    strap string \
    strap newline
    push . get n
    push . number 0
    if exec .--func more
        goto loop

push . strap
push . regex gm string   ( {4})(?=.$)
push . string  \$1
print exec .--func replace


问:
"Hello, World!"
So... uh... this is a bit embarrassing. But we don't have a plain "Hello, World!" challenge yet (despite having 35 variants tagged with hello-world, and counting). While this is not the most interesting code golf in the common languages, finding the shortest solution in certain esolangs can be a serious challenge. For instance, to my knowledge it is not known whether the shortest possible Brainfuck solution has been found yet.

Furthermore, while all of <s>Wikipedia</s> (the Wikipedia entry has been deleted but there is a copy at archive.org
), esolangs and Rosetta Code have lists of "Hello, World!" programs, none of these are interested in having the shortest for each language (there is also this GitHub repository). If we want to be a significant site in the code golf community, I think we should try and create the ultimate catalogue of shortest "Hello, World!" programs (similar to how our basic quine challenge contains some of the shortest known quines in various languages). So let's do this!

The Rules

Each submission must be a full program.

The program must take no input, and print Hello, World! to STDOUT (this exact byte stream, including capitalization and punctuation) plus an optional trailing newline, and nothing else.

The program must not write anything to STDERR.

If anyone wants to abuse this by creating a language where the empty program prints Hello, World!, then congrats, they just paved the way for a very boring answer.

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

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

This is not about finding the language with the shortest "Hello, World!" program. This is about finding the shortest "Hello, World!" program in every language. Therefore, I will not mark any answer as "accepted".

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

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf - these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the authors actually had to put effort into golfing the code.

For inspiration, check the Hello World Collection.

The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue 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 + 2 (-p flag) = 45 bytes
</code>```

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

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

/* Configuration */

var QUESTION_ID = 55422; // 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 = 8478; // 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,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

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

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

function process() {
  var valid = [];

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

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

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

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

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

    var lang = a.language;
    lang = jQuery(''+lang+'').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

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

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

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

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

table thead {
  font-weight: bold;
}

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

<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
eacal, 24 bytes

```<code>put string Hello, World!
</code>```

Simple enough. put prints its argument, string turns its arguments into a string entity.

Title: "Hello, World!"

Body:
eacal, 24 bytes

put string Hello, World!

Simple enough. put prints its argument, string turns its arguments into a string entity.


Title: Draw a ladder and slide

Body:
Scala, 95 bytes

def l(n:Int)=for(i<- 0 to n-1){println(" "*(n-i-1)+"/----/"+("  "*i+"\\    \\").substring(5))}


问:
Implement a Truth-Machine
A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

Gets a number (either 0 or 1) from STDIN.

If that number is 0, print out 0 and terminate.

If that number is 1, print out 1 forever.

Challenge

Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

take input from STDIN or an acceptable alternative

If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program

must output to STDOUT or an acceptable alternative

If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.

when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory

the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of code-golf must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

The Stack Snippet at the bottom of this post generates the catalog 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 + 2 (-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

```

答:
eacal, 58 bytes

```<code>label l
put set n cast number arg number 0
if get n
goto l
</code>```

put outputs n, which is cast to the first argument. Call like:

```<code>node eacal.js tm.eaa <input>
</code>```

Title: Implement a Truth-Machine

Body:
eacal, 58 bytes

label l
put set n cast number arg number 0
if get n
goto l

put outputs n, which is cast to the first argument. Call like:

node eacal.js tm.eaa <input>


问:
Dice from Changing Random Generator

Introduction

You are given a random integer generator with the following implementation

The first invocation always returns 1.

The second invocation returns a random integer between 1 and 2.

The third invocation returns a random integer between 1 and 3.

The nth invocation returns a random integer between 1 and n, inclusive.

Based on the above function, write a random dice generator that is perfectly random, returning a value between 1 and 6 (inclusive) with equal probability.

Rules

Your program/function should result in a random integer between 1 and 6, inclusive, in some usable form, i.e., to standard output or as a function return value.

The ascending random number generator above can be defined as a "free" function in your program (i.e., doesn't count toward your character count), or a separate script/program that is executed as needed, assuming the state (n) is persistent between calls.

Assume that no more than 1000 dice rolls will ever be requested in a single use case of your program, and the initial random number generator can be reset to 1 at the end of 1000 dice rolls to avoid overflow of n.

Your program may not use any other source of random numbers except the ascending random generator defined above.  You may of course request multiple random numbers from the random number generator for each single dice roll output.

This is code-golf, so winner is shortest answer or most votes in the event of a tie.  If you can generate 1000 dice rolls using less than 1000 generated random numbers, give yourself a 10-point efficiency bonus.

Example

```<code>./asc-rand
1 # random integer between 1 and 1
./asc-rand
1 # random integer between 1 and 2
./asc-rand
3 # random integer between 1 and 3
./asc-rand
4 # random integer between 1 and 4

# dice-gen generates random dice based on output of asc-rand program.
./dice-gen
3
./dice-gen
6
./dice-gen
5
./dice-gen
1
</code>```

答:
Scala 23

```<code>def s={r;r;r;r;r;r%6+1}
</code>```

The method r can be (approx.) implemented like this:

```<code>var cnt = 0
val rnd = new util.Random

def r = {
  cnt %= 1000
  cnt += 1
  rnd.nextInt (cnt)
}
</code>```

a rough test:

```<code>scala> (1 to 6).map (i => ((1 to 600) map (_=>s)).filter (_ == i).size)
res26: scala.collection.immutable.IndexedSeq[Int] = Vector(110, 105, 91, 96, 106, 102)
</code>```

Every 6th call should produce an equal distribution over the 6 values, so I throw away 5.

Title: Dice from Changing Random Generator

Body:
Scala 23

def s={r;r;r;r;r;r%6+1}

The method r can be (approx.) implemented like this:

var cnt = 0
val rnd = new util.Random

def r = {
  cnt %= 1000
  cnt += 1
  rnd.nextInt (cnt)
}

a rough test:

scala> (1 to 6).map (i => ((1 to 600) map (_=>s)).filter (_ == i).size)
res26: scala.collection.immutable.IndexedSeq[Int] = Vector(110, 105, 91, 96, 106, 102)

Every 6th call should produce an equal distribution over the 6 values, so I throw away 5.


问:
Showcase of Languages

Notes

This thread is open and unlocked only because the community decided to make an exception. Please do not use this question as evidence that you can ask similar questions here. Please do not create additional showcase questions.

This is no longer a popularity-contest, nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes.

This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible.

How this works

All answers should include the name of the programming language at the top of the post, prefixed by a #.

Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language.

Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions.

The snippets do not need to be related. In fact, snippets that are too related may be redundant.

Since this is not a contest, all programming languages are welcome, whenever they were created.

Answers that contain more than a handful of code snippets should use a Stack Snippet to collapse everything except the factoid and one of the snippets.

Whenever possible, there should be only one answer per programming language. This is a community wiki, so feel free to add snippets to any answer, even if you haven't created it yourself. There is a Stack Snippet for compressing posts, which should mitigate the effect of the 30,000 character limit.

Answers that predate these guidelines should be edited. Please help updating them as needed.

Current answers, sorted alphabetically by language name

$.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/44680/answers?site=codegolf&filter=withbody",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('
' + temp.innerText || temp.textContent + '');}}})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="http://codegolf.stackexchange.com"><ul id="list"></ul></code>```

答:
eacal

0-vote

eacal is a language made by me in 2016. It's very extremely verbose, but, as I hope, is capable. There is one command per line, and each data entry is separated by spaces. It is meant to be classified under a lot of programming paradigms, which includes right now, imperative, structured, stack-based, object oriented, event-driven, and a tad of functional.

Fun fact: the empty program errors.

1-vote

```<code>v
</code>```

This prints:

```<code>eacal is currently running.
</code>```

This tells you if eacal is still alive. Helpful!

2-vote

```<code>on
</code>```

This is the event-driven portion of eacal. It's syntax is:

```<code>on <event> <code evaluating to a function>
</code>```

Here is an example:

```<code>on end eval print string Done!

print string Running...
</code>```

This prints:

```<code>Running...
Done!
</code>```

3-vote

```<code>arg
</code>```

This returns all of the command-line arguments passed to the program. Like so:

```<code>node eacal.js <file> 3 4 Hello
</code>```

File:

```<code>print arg
</code>```

Output:

```<code>[ '3', '4', 'Hello' ]
</code>```

4-vote

```<code>eacal is currently running.
</code>```0

This is used to initialize stacks, like so:

```<code>eacal is currently running.
</code>```1

Otherwise, the stack does not exist.

5-vote

```<code>eacal is currently running.
</code>```2

This sets creates a command that function the same as another command. Example:

```<code>alias define_stack init
define_stack main
</code>```

is the same as

```<code>init main
</code>```

This is very helpful in golfing.

6-vote

```<code>string
</code>```

Represents a string, where it's arguments are joined by spaces. So, Hello, World! is this:

```<code>string Hello, World!
</code>```

7-vote

```<code>numlist
</code>```

This returns an array of numbers representative of its arguments. For the first few Fibonacci numbers in a list:

```<code>numlist 0 1 1 2 3 5 8 13 21
</code>```

8-vote

```<code>func add
</code>```

This shows some of eacal's function programming. You can execute it on a stack named k using exec k--func add. For example:

```<code>on
</code>```0

Title: Showcase of Languages

Body:
eacal

0-vote

eacal is a language made by me in 2016. It's very extremely verbose, but, as I hope, is capable. There is one command per line, and each data entry is separated by spaces. It is meant to be classified under a lot of programming paradigms, which includes right now, imperative, structured, stack-based, object oriented, event-driven, and a tad of functional.

Fun fact: the empty program errors.

1-vote

v

This prints:

eacal is currently running.

This tells you if eacal is still alive. Helpful!

2-vote

on

This is the event-driven portion of eacal. It's syntax is:

on <event> <code evaluating to a function>

Here is an example:

on end eval print string Done!

print string Running...

This prints:

Running...
Done!

3-vote

arg

This returns all of the command-line arguments passed to the program. Like so:

node eacal.js <file> 3 4 Hello

File:

print arg

Output:

[ '3', '4', 'Hello' ]

4-vote

init

This is used to initialize stacks, like so:

init main

Otherwise, the stack does not exist.

5-vote

alias

This sets creates a command that function the same as another command. Example:

alias define_stack init
define_stack main

is the same as

init main

This is very helpful in golfing.

6-vote

string

Represents a string, where it's arguments are joined by spaces. So, Hello, World! is this:

string Hello, World!

7-vote

numlist

This returns an array of numbers representative of its arguments. For the first few Fibonacci numbers in a list:

numlist 0 1 1 2 3 5 8 13 21

8-vote

func add

This shows some of eacal's function programming. You can execute it on a stack named k using exec k--func add. For example:

init main
push main number 5
push main number 8
print exec main--func add
; outputs 13


答:
Octave, 28 bytes

```<code>@(m)diff(+m)>=0&~sum(m-97.5)
</code>```

This defines an anonymous function. It works also for empty input. Falsy and truthy are as described in my MATL answer.

Try it at ideone.

Explanation

diff(+m)>0 checks if the input string (consisting of 'a' and 'b') is sorted, that is, all characters 'a' come before all 'b'.

The other condition that needs to be checked is whether the numbers of characters 'a' and 'b' are the same. Since their ASCII codes are 97 ansd 98, this is done subtracting 97.5 and chacking if the the sum is zero.

For empty input the result is empty, which is falsy.

Body:
Octave, 28 bytes

@(m)diff(+m)>=0&~sum(m-97.5)

This defines an anonymous function. It works also for empty input. Falsy and truthy are as described in my MATL answer.

Try it at ideone.

Explanation

diff(+m)>0 checks if the input string (consisting of 'a' and 'b') is sorted, that is, all characters 'a' come before all 'b'.

The other condition that needs to be checked is whether the numbers of characters 'a' and 'b' are the same. Since their ASCII codes are 97 ansd 98, this is done subtracting 97.5 and chacking if the the sum is zero.

For empty input the result is empty, which is falsy.


答:
Python 3, 32 bytes

eval(input().translate(")("*50))
```
<p>Try it online!</p>
<p>Outputs via exit code: Error for false, no error for True.</p>
<p>The string is evaluated as Python code, replacing parens <code>(</code> for <code>a</code> and <code>)</code> for <code>b</code>. Only expressions of the form <code>a^n b^n</code> become well-formed expressions of parentheses like <code>((()))</code>, evaluating to the tuple <code>()</code>.</p>
<p>Any mismatched parens give an error, as will multiple groups like <code>(()())</code>, since there's no separator. The empty string also fails (it would succeed on <code>exec</code>).</p>
<p>The conversion <code>( -> a</code>, <code>) -> b</code> is done using <code>str.translate</code>, which replaces characters as indicated by a string that serves as a conversion table. Given  the 100-length string ")("*50, the tables maps the first 100 ASCII values as</p>
```... Z[\]^_`abc
... )()()()()(
```

which takes ( -> a, ) -> b.

In Python 2, conversions for all 256 ASCII values must be provided, requiring "ab"*128, one byte longer; thanks to isaacg for pointing this out.

Try it online! (Python 2, 33 bytes)

Body:
Python 3, 32 bytes

eval(input().translate(")("*50))

<a href="https://tio.run/##ZVFNbusgEN5zihEbzEtqJarexlaWPUVaWfBCWiQXEEyapgfoumfsRVJmcLp5yGL@vu@bGZwu@BLD/dW/ppgRfFyXS1m3aPZWHNwRJh/SCTs9wPMcrZkBXcERssNTDhyIabInP6MPZZp6hsNu4Y0QkwudJFzp00Wu5Vnq/pw9ui5LKa/uzczd0qPHbEKZTa1J3ck/fzdaXytovx3utk96hDpenwy@1C7FZew2a1Cq5j92G3GMGeoOgUEFDz4MAurxR/gYbsl4wqW5egxK3wC4r/q7HeUGoOlxTx25TKNTZgRXjdqols2XJk8n0b5Te7dpWraV@rfeRvh91z67OZpDlxrCvf9zCeGBjY8BTAGX89D6bdV4G74mb8NLtcKVkgMoWNV/kXJXi7r6vNbIuv@t7KgO359fIImGFMr2fNurscIYS1e92ZBtDnuL23wrhBGUEbZ@XCK6MDUkFcuVarncqCxNKIIYvojQGEwhDpEIYlmGdZpQU7I/" rel="nofollow noreferrer" title="Python 3 – Try It Online">Try it online!

Outputs via exit code: Error for false, no error for True.

The string is evaluated as Python code, replacing parens ( for a and ) for b. Only expressions of the form a^n b^n become well-formed expressions of parentheses like ((())), evaluating to the tuple ().

Any mismatched parens give an error, as will multiple groups like (()()), since there's no separator. The empty string also fails (it would succeed on exec).

The conversion ( -> a, ) -> b is done using str.translate, which replaces characters as indicated by a string that serves as a conversion table. Given  the 100-length string ")("*50, the tables maps the first 100 ASCII values as

... Z[\]^_`abc
... )()()()()(

which takes ( -> a, ) -> b.

In Python 2, conversions for all 256 ASCII values must be provided, requiring "ab"*128, one byte longer; thanks to isaacg for pointing this out.

<a href="https://tio.run/##ZVBBjtswDLzrFYR6kNWkRrynwoaPfUVaGNJG2RXgSoJEd5t9QM99Yz@SkpLTSwVDpGY4Q9Lphq8xPN0/PMeLDy/zhlfhv6eYEXw8lls50ktc3BUWH9KGnR7hZY3WrICu4ATZ4ZYDuB9m7RjRYlns5lf0oSxLX0Uw7@oJYnKhk1xY@nSTR/kmdf@WPbouSynv1Wfv1GM2oayGOKk7@XF4@qz1narOw/hp@KYnoPn6ZPCV2hSXsTsdQSnC3@eTuMYMtESoRQVpu1EAHX@F9/EBxg337uprUPpRgGfyn2fGRuDx8cwdK82zE6KkOuCB7gkcP0@qsfnW2vBJvPjSfuey7GtL/Y9voxDfZ7dGc@lS49zPZ5cQvtTgYwBTwOU8tk6Dmh7jE7iPX6c6AI2rKGSXckekZogXm6rvf0s75uHPr98gWVYdZPuBw91YYYzli@4aOLakZnvaciuEEYwIS1@lWC4MPdnFVoZipZu0WnMVl5h6saApqoQ1LOISW22qTzNqTvYv" rel="nofollow noreferrer" title="Python 2 – Try It Online">Try it online! (Python 2, 33 bytes)


答:
Jelly, <s>31</s> <s>30</s> 29 bytes

```<code>Q;S⁹o_
3ḶḂç@⁸Ð¡Iµa"Ṿ€o⁶z⁶Zµ€Z
</code>```

This is a monadic link; it accepts a 0-based column index as argument and returns a list of strings.

Try it online!

How it works

```<code>Q;S⁹o_                  Helper link.
                        Arguments: [k, 0, k] and [0, m, 0] (any order)

Q                       Unique; deduplicate the left argument.
 ;                      Concatenate the result with the right argument.
  S                     Take the sum of the resulting array.
   ⁹o                   Logical OR with the right argument; replaces zeroes in the
                        right argument with the sum.
     _                  Subtract; take the difference with the right argument to
                        remove its values.
                        This maps [k, 0, k], [0, m, 0] to [0, k + m, 0] and
                        [0, m, 0], [k, 0, k] to [m + 2k, 0, m + 2k].

3ḶḂç@⁸Ð¡Iµa"Ṿ€o⁶z⁶Zµ€Z  Monadic link. Argument: A (array of column indices)

3Ḷ                      Yield [0, 1, 2].
  Ḃ                     Bit; yield [0, 1, 0].
        I               Increments of n; yield [].
      Ð¡                Apply...
   ç@                       the helper link with swapped arguments...
     ⁸                      n times, updating the left argument with the return
                            value, and the right argument with the previous value
                            of the left one. Collect all intermediate values of
                            the left argument in an array.
         µ         µ€   Map the chain in between over the intermediate values.
            Ṿ€          Uneval each; turn all integers into strings.
          a"            Vectorized logical AND; replace non-zero integers with
                        their string representation.
              o⁶        Logical OR with space; replace zeroes with spaces.
                z⁶      Zip with fill value space; transpose the resulting 2D
                        array after inserting spaces to make it rectangular.
                  Z     Zip; transpose the result to restore the original shape.
                     Z  Zip; transpose the resulting 3D array.
</code>```

Title: Generate Pascal's Braid

Body:
Jelly, <s>31</s> <s>30</s> 29 bytes

Q;S⁹o_
3ḶḂç@⁸Ð¡Iµa"Ṿ€o⁶z⁶Zµ€Z

This is a monadic link; it accepts a 0-based column index as argument and returns a list of strings.

Try it online!

How it works

Q;S⁹o_                  Helper link.
                        Arguments: [k, 0, k] and [0, m, 0] (any order)

Q                       Unique; deduplicate the left argument.
 ;                      Concatenate the result with the right argument.
  S                     Take the sum of the resulting array.
   ⁹o                   Logical OR with the right argument; replaces zeroes in the
                        right argument with the sum.
     _                  Subtract; take the difference with the right argument to
                        remove its values.
                        This maps [k, 0, k], [0, m, 0] to [0, k + m, 0] and
                        [0, m, 0], [k, 0, k] to [m + 2k, 0, m + 2k].

3ḶḂç@⁸Ð¡Iµa"Ṿ€o⁶z⁶Zµ€Z  Monadic link. Argument: A (array of column indices)

3Ḷ                      Yield [0, 1, 2].
  Ḃ                     Bit; yield [0, 1, 0].
        I               Increments of n; yield [].
      Ð¡                Apply...
   ç@                       the helper link with swapped arguments...
     ⁸                      n times, updating the left argument with the return
                            value, and the right argument with the previous value
                            of the left one. Collect all intermediate values of
                            the left argument in an array.
         µ         µ€   Map the chain in between over the intermediate values.
            Ṿ€          Uneval each; turn all integers into strings.
          a"            Vectorized logical AND; replace non-zero integers with
                        their string representation.
              o⁶        Logical OR with space; replace zeroes with spaces.
                z⁶      Zip with fill value space; transpose the resulting 2D
                        array after inserting spaces to make it rectangular.
                  Z     Zip; transpose the result to restore the original shape.
                     Z  Zip; transpose the resulting 3D array.