答:
Factor, 58 bytes

```<code>[ [ [ 43 ] ""replicate-as ".>"append ] { } map-as ""join ]
</code>```

Works like:

```<code>[
  [
    [ 43 ] "" replicate-as  ! ``+'' * code point, clone-like a string ""
    ".>" append             ! append ".>"
  ]
  { } map-as                ! for each char in string and clone-like an array { }
  "" join                   ! join array of str into str by ""
]
</code>```

Since Factor comes with a Brainfuck interpreter, it's simple to test.

bfcat.factor

```<code>USING: sequences ;
IN: bfcat

: string>brainfuck ( s -- bf )
  [ [ 43 ] "" replicate-as ".>" append ]
  { } map-as "" join ;
</code>```

bfcat-tests.factor

```<code>USING: tools.test bfcat brainfuck ;
IN: bfcat.tests

{ "a"  } [ "a"  string>brainfuck get-brainfuck ] unit-test
{ "ab" } [ "ab" string>brainfuck get-brainfuck ] unit-test
{ "+++++++++++++" } [ "+++++++++++++" string>brainfuck get-brainfuck ] unit-test
{ "Code Golf" } [ "Code Golf" string>brainfuck get-brainfuck ] unit-test
</code>```

output

```<code>Unit Test: { { "a" } [ "a" string>brainfuck get-brainfuck ] }
Unit Test: { { "ab" } [ "ab" string>brainfuck get-brainfuck ] }
Unit Test: {
    { "+++++++++++++" }
    [ "+++++++++++++" string>brainfuck get-brainfuck ]
}
Unit Test: {
    { "Code Golf" }
    [ "Code Golf" string>brainfuck get-brainfuck ]
}
</code>```

Yay! they all pass.

Body:
Challenge

Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..

Assume all inputs are encoded as ASCII.

Assume the outputted BF program will execute in an environment with an infinite tape.

Assume the pointer starts at cell 0 with every cell initialized to a value of zero.

Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.

The tape is doubly infinite.

All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.

Examples

Space string

Given the input  , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
++ .
</code>```

Exclamation point

Given the input ! , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++
.
</code>```

Two letters

Given the input hi , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

++++
.
+
.
</code>```

This is code-golf, so the code with the smallest number of bytes wins. Good luck.

Body:
Factor, 58 bytes

[ [ [ 43 ] ""replicate-as ".>"append ] { } map-as ""join ]

Works like:

[
  [
    [ 43 ] "" replicate-as  ! ``+'' * code point, clone-like a string ""
    ".>" append             ! append ".>"
  ]
  { } map-as                ! for each char in string and clone-like an array { }
  "" join                   ! join array of str into str by ""
]

Since Factor comes with a Brainfuck interpreter, it's simple to test.

bfcat.factor

USING: sequences ;
IN: bfcat

: string>brainfuck ( s -- bf )
  [ [ 43 ] "" replicate-as ".>" append ]
  { } map-as "" join ;

bfcat-tests.factor

USING: tools.test bfcat brainfuck ;
IN: bfcat.tests

{ "a"  } [ "a"  string>brainfuck get-brainfuck ] unit-test
{ "ab" } [ "ab" string>brainfuck get-brainfuck ] unit-test
{ "+++++++++++++" } [ "+++++++++++++" string>brainfuck get-brainfuck ] unit-test
{ "Code Golf" } [ "Code Golf" string>brainfuck get-brainfuck ] unit-test

output

Unit Test: { { "a" } [ "a" string>brainfuck get-brainfuck ] }
Unit Test: { { "ab" } [ "ab" string>brainfuck get-brainfuck ] }
Unit Test: {
    { "+++++++++++++" }
    [ "+++++++++++++" string>brainfuck get-brainfuck ]
}
Unit Test: {
    { "Code Golf" }
    [ "Code Golf" string>brainfuck get-brainfuck ]
}

Yay! they all pass.


问:
Is string X a subsequence of string Y?
Given strings X and Y, determine whether X is a subsequence of Y. The empty string is regarded as a subsequence of every string. (E.g., '' and 'anna' are subsequences of 'banana'.)

Input

X, a possibly-empty case-sensitive alphanumeric string

Y, a possibly-empty case-sensitive alphanumeric string

Output

True or False (or equivalents), correctly indicating whether X is a subsequence of Y.

I/O examples

```<code>X      Y        output

''     'z00'    True
'z00'  'z00'    True
'z00'  '00z0'   False
'aa'   'anna'   True
'anna' 'banana' True
'Anna' 'banana' False
</code>```

Criteria

The shortest program wins, as determined by the number of bytes of source code.

Example programs

Several programs that could be adapted are in this related posting.

答:
Mathematica 19 17 27

LongestCommonSequence returns the longest non-contiguous subsequence of two strings.  (Not to be confused with LongestCommonSubsequence, which returns the longest contiguous subsequence.

The following checks whether the longest contiguous subsequence is the first of the two strings. (So you must enter the shorter string followed by the larger string.)

```<code>LongestCommonSequence@##==#&
</code>```

Examples

```<code>LongestCommonSequence@## == # &["", "z00"]
LongestCommonSequence@## == # &["z00", "z00"]
LongestCommonSequence@## == # &["anna", "banana"]
LongestCommonSequence@## == # &["Anna", "banana"]
</code>```

True True True False

The critical test is the third one, because "anna" is contained non contiguously in  "banana".

ContentLicense: CC BY-SA 4.0

Title: Is string X a subsequence of string Y?

Body:
Mathematica 19 17 27

LongestCommonSequence returns the longest non-contiguous subsequence of two strings.  (Not to be confused with LongestCommonSubsequence, which returns the longest contiguous subsequence.

The following checks whether the longest contiguous subsequence is the first of the two strings. (So you must enter the shorter string followed by the larger string.)

LongestCommonSequence@##==#&

Examples

LongestCommonSequence@## == # &["", "z00"]
LongestCommonSequence@## == # &["z00", "z00"]
LongestCommonSequence@## == # &["anna", "banana"]
LongestCommonSequence@## == # &["Anna", "banana"]

True True True False

The critical test is the third one, because "anna" is contained non contiguously in  "banana".

ContentLicense: CC BY-SA 3.0


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

```

答:
BruhScript, 28 bytes

I take the bytecount of the encoded version.

Source:

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

Encoded:

```<code>0000000: 007e 002f 0008 0018 0018 000e 0056 0005  .~./.........V..
0000010: 0021 000e 0009 0018 0012 0044            .!.........D
</code>```

This insane count of NUL bytes is because the encoding of BruhScript is a 16-bit encoding.

This code is really simple. A block (string literal, lambda, etc...) don't need to be terminated at the end of file.

EDIT: BruhScript print every thing on the stack at the end of the program, so the print function is not needed

Title: "Hello, World!"

Body:
BruhScript, 28 bytes

I take the bytecount of the encoded version.

Source:

«Hello, World!

Encoded:

0000000: 007e 002f 0008 0018 0018 000e 0056 0005  .~./.........V..
0000010: 0021 000e 0009 0018 0012 0044            .!.........D

This insane count of NUL bytes is because the encoding of BruhScript is a 16-bit encoding.

This code is really simple. A block (string literal, lambda, etc...) don't need to be terminated at the end of file.

EDIT: BruhScript print every thing on the stack at the end of the program, so the print function is not needed


问:
Simple cat program
One of the most common standard tasks (especially when showcasing esoteric programming languages) is to implement a "cat program": read all of STDIN and print it to STDOUT. While this is named after the Unix shell utility cat it is of course much less powerful than the real thing, which is normally used to print (and concatenate) several files read from disc.

Task

You should write a full program which reads the contents of the standard input stream and writes them verbatim to the standard output stream. If and only if your language does not support standard input and/or output streams (as understood in most languages), you may instead take these terms to mean their closest equivalent in your language (e.g. JavaScript's prompt and alert). These are the only admissible forms of I/O, as any other interface would largely change the nature of the task and make answers much less comparable.

The output should contain exactly the input and nothing else. The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation. This also applies to trailing newlines. If the input does not contain a trailing newline, the output shouldn't include one either! (The only exception being if your language absolutely always prints a trailing newline after execution.)

Output to the standard error stream is ignored, so long as the standard output stream contains the expected output. In particular, this means your program can terminate with an error upon hitting the end of the stream (EOF), provided that doesn't pollute the standard output stream. If you do this, I encourage you to add an error-free version to your answer as well (for reference).

As this is intended as a challenge within each language and not between languages, there are a few language specific rules:

If it is at all possible in your language to distinguish null bytes in the standard input stream from the EOF, your program must support null bytes like any other bytes (that is, they have to be written to the standard output stream as well).

If it is at all possible in your language to support an arbitrary infinite input stream (i.e. if you can start printing bytes to the output before you hit EOF in the input), your program has to work correctly in this case. As an example yes | tr -d \\n | ./my_cat should print an infinite stream of ys. It is up to you how often you print and flush the standard output stream, but it must be guaranteed to happen after a finite amount of time, regardless of the stream (this means, in particular, that you cannot wait for a specific character like a linefeed before printing).

Please add a note to your answer about the exact behaviour regarding null-bytes, infinite streams, and extraneous output.

Additional rules

This is not about finding the language with the shortest solution for this (there are some where the empty program does the trick) - this is about finding the shortest solution in every language. Therefore, no answer will be marked as accepted.

Submissions in most languages will be scored in bytes in an appropriate preexisting encoding, usually (but not necessarily) UTF-8.

Some languages, like Folders, are a bit tricky to score. If in doubt, please ask on Meta.

Feel free to use a language (or language version) even if it's newer than this challenge. Languages specifically written to submit a 0-byte answer to this challenge are fair game but not particularly interesting.

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.

Also note that languages do have to fulfil our usual criteria for programming languages.

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 Headsecks or Unary), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

Unless they have been overruled earlier, all standard code-golf rules apply, including the http://meta.codegolf.stackexchange.com/q/1061.

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 author actually had to put effort into golfing the code.

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>## [><>](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

```

答:
BruhScript, 22 bytes

Source:

```<code>↺₀1Λ₀⍈+⍰'
∇
</code>```

Encoded version hexdump:

```<code>0000000: 0099 009a 003a 0087 009a 008f 0051 008e  .....:.......Q..
0000010: 0061 0000 0069                           .a...i
</code>```

Explanation:

```<code>↺                While loop. Take two niladic functions as arguments.
 ₀1Λ             A function that always return 1
    ₀⍈+⍰'<LF>∇   `'<c>` is a shorthand for «<c>», so this code print (⍈) the input (⍰) + a newline ('<LF>), and return None (∇)
</code>```

Title: Simple cat program

Body:
BruhScript, 22 bytes

Source:

↺₀1Λ₀⍈+⍰'
∇

Encoded version hexdump:

0000000: 0099 009a 003a 0087 009a 008f 0051 008e  .....:.......Q..
0000010: 0061 0000 0069                           .a...i

Explanation:

↺                While loop. Take two niladic functions as arguments.
 ₀1Λ             A function that always return 1
    ₀⍈+⍰'<LF>∇   `'<c>` is a shorthand for «<c>», so this code print (⍈) the input (⍰) + a newline ('<LF>), and return None (∇)


问:
Autonest an array
Everybody loves nested lists! However, sometimes it's hard to make a nested list. You have to decide if you want to nest it deeper, or if you need to nest it shallower. So for your challenge, you must "Autonest" a list. To autonest a list, compare every pair of items in the list.

If the second item is smaller, separate the two elements by inserting closing and opening brackets between them, like this:

```<code>  } {
{2 , 1}
</code>```

For example, {2, 1} becomes {2}, {1}, and {3, 2, 1} becomes {3}, {2}, {1}

If the second item is the same, then change nothing. For example, {1, 1, 1} stays the same, and {2, 1, 1, 1} would become {2}, {1, 1, 1}.

If the second item is larger, then nest every following item one level deeper. For example, {1, 2} would become {1, {2}} and {1, 2, 3} would become {1, {2, {3}}}

The Challenge

You must write a program or function that takes in a list of numbers, and returns the same list after being autonested. Take this input in your languages native list format (or the closest alternative) or as a string. You do not have to use curly braces like I did in my examples. You can use whichever type of brackets are most natural in your language, as long as this is consistent. You can safely assume the list will only contain integers. You can also assume the list will have at least 2 numbers in it. Here is some sample IO:

```<code>{1, 3, 2}                         -->   {1, {3}, {2}}
{1, 2, 3, 4, 5, 6}                -->   {1, {2, {3, {4, {5, {6}}}}}}
{6, 5, 4, 3, 2, 1}                -->   {6}, {5}, {4}, {3}, {2}, {1}
{7, 3, 3, 2, 6, 4}                -->   {7}, {3, 3}, {2, {6}, {4}}
{7, 3, 1, -8, 4, 8, 2, -9, 2, 8}  -->   {7}, {3}, {1}, {-8, {4, {8}, {2}, {-9, {2, {8}}}}}
</code>```

Standard loopholes apply, and the shortest answer in bytes wins!

答:
Haskell, 96 bytes

```<code>a#b|a<b=",{"|a>b="},{"|1<2=","
f(a:b:c)=show a++a#b++f(b:c)++['}'|a<b]
f[x]=show x++"}"
('{':).f
</code>```

Usage example: ('{':).f $ [7,3,3,2,6,4] -> "{7},{3,3},{2,{6},{4}}".

As Haskell doesn't have nested lists, I return the result as a string. The nesting algorithm is easy: a) print number, b) if the next number is greater (less, equal), print ,{ ( },{, ,), c) make a recursive call with the rest of the list, d) print } if the number is less than the next one, e) enclose everything in { and }.

Title: Autonest an array

Body:
Haskell, 96 bytes

a#b|a<b=",{"|a>b="},{"|1<2=","
f(a:b:c)=show a++a#b++f(b:c)++['}'|a<b]
f[x]=show x++"}"
('{':).f

Usage example: ('{':).f $ [7,3,3,2,6,4] -> "{7},{3,3},{2,{6},{4}}".

As Haskell doesn't have nested lists, I return the result as a string. The nesting algorithm is easy: a) print number, b) if the next number is greater (less, equal), print ,{ ( },{, ,), c) make a recursive call with the rest of the list, d) print } if the number is less than the next one, e) enclose everything in { and }.


问:
How many squares are guarded by chess queens?
Today marks the 15th anniversary of Garry Kasparov's defeat against Deep Blue. Speaking of chess...

Input is a string that represents an 8x8 chess board containing only empty squares (.) and queens (Q). Output the number of squares that any queen can move to the next move. Queens can move any number of squares vertically, horizontally or diagonally.

Write either a program or a function. Shortest code wins, but most inventive solution gets the most upvotes.

Examples

Input:

```<code>Q.......
........
.Q......
........
........
........
........
........
</code>```

Output:

```<code>37
</code>```

Input:

```<code>QQQQQQQQ
QQQQQQQQ
QQQQQQQQ
QQQQ.QQQ
QQQQQQQQ
QQQQQQQQ
QQQQQQQQ
QQQQQQQQ
</code>```

Output:

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

答:
APL, 50 chars

```<code>{≢(b~x)∩,(x←(,'Q'=⍵)/b←,⍳8 8)∘.+(⍳8)∘.×∘.,⍨1 0 ¯1}
</code>```

In English:

∘.,⍨1 0 ¯1: computes all the pairs composed by -1, 0 or 1, i.e.: (0 0)(0 1)(0 -1)(1 0) and so on;

(⍳8)∘.×∘.,⍨1 0 ¯1: multiply all the pairs computed by all the number from 1 to 8, obtaining all the possible offsets of movement of the queen;

(x←(,'Q'=⍵)/b←,⍳8 8): puts is x the coordinates of the given queens;

∘.+: compute yet another outer sum, combining the position of the given queens with all the possible displacement offsets. This gives a multidimensional array of coordinate pairs of all the possible place where each of the queens might end up, including outside the board (whose valid coordinate pairs is in b)

(b~x)∩,: removes from the list b all the coordinates taken by the queens in the given (x) and intersects it with flattened array of pairs of all the possible positions of the queens

≢: count the remaining pairs

Try online sample 1.

Try online sample 2

ContentLicense: CC BY-SA 2.5

Body:
APL, 50 chars

{≢(b~x)∩,(x←(,'Q'=⍵)/b←,⍳8 8)∘.+(⍳8)∘.×∘.,⍨1 0 ¯1}

In English:

∘.,⍨1 0 ¯1: computes all the pairs composed by -1, 0 or 1, i.e.: (0 0)(0 1)(0 -1)(1 0) and so on;

(⍳8)∘.×∘.,⍨1 0 ¯1: multiply all the pairs computed by all the number from 1 to 8, obtaining all the possible offsets of movement of the queen;

(x←(,'Q'=⍵)/b←,⍳8 8): puts is x the coordinates of the given queens;

∘.+: compute yet another outer sum, combining the position of the given queens with all the possible displacement offsets. This gives a multidimensional array of coordinate pairs of all the possible place where each of the queens might end up, including outside the board (whose valid coordinate pairs is in b)

(b~x)∩,: removes from the list b all the coordinates taken by the queens in the given (x) and intersects it with flattened array of pairs of all the possible positions of the queens

≢: count the remaining pairs

Try online sample 1.

Try online sample 2


问:
Type uniqchars!
Given a string consisting of printable ASCII chars, produce an output consisting of its unique chars in the original order. In other words, the output is the same as the input except that a char is removed if it has appeared previously.

No built-ins for finding unique elements in an array can be used (for example, MATLAB has a unique function that does that). The idea is to do it manually.

Further details:

Either functions or programs are allowed.

Input and output can be in the form of function arguments, stdin/stdout (even for functions), or a mix of those.

If stdin or stdout are used, a string is understood as just the sequence of chars. If function arguments are used, the sequence of chars may need to be enclosed in quotation marks or equivalent symbols that the programming language of choice uses for defining strings.

The output should be a string containing only the unique characters of the input. So no extra linebreaks, spaces etc. The only exception is: if the output is displayed in stdout, most displaying functions add a trailing \n (to separate the string from what will come next). So one trailing \n is acceptable in stdout.

If possible, post a link to an online interpreter/compiler so that others can try your code.

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

Some examples, assuming stdin and stdout:

Input string:

```<code>Type unique chars!
</code>```

Output string:

```<code>Type uniqchars!
</code>```

Input string

```<code>"I think it's dark and it looks like rain", you said
</code>```

Output string

```<code>"I think'sdarloe,yu
</code>```

Input string

```<code>3.1415926535897932384626433832795
</code>```

Output string

```<code>3.14592687
</code>```

答:
Javascript (ES6), 47 bytes

```<code>a=>[...a].filter((b,c)=>a.indexOf(b)==c).join``
</code>```

Test it here

Some code is added to have a better input and to write to the console the result.

d=document,g=d.getElementById.bind(d);g("s").onclick=e=>console.log((a=>[...a].filter((b,c)=>a.indexOf(b)==c).join``)(g("t").value))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="t"><button id="s">Convert</button></code>```

Title: Type uniqchars!

Body:
Javascript (ES6), 47 bytes

a=>[...a].filter((b,c)=>a.indexOf(b)==c).join``

Test it here

Some code is added to have a better input and to write to the console the result.

d=document,g=d.getElementById.bind(d);g("s").onclick=e=>console.log((a=>[...a].filter((b,c)=>a.indexOf(b)==c).join``)(g("t").value))

<input id="t"><button id="s">Convert</button>


问:
Hello World 0.0!

 source: Dilbert, September 8, 1992

I'm hoping to add a new twist on the classic "Hello World!" program.

Code a program that outputs Hello World! without:

String/Character literals

Numbers (any base)

Pre-built functions that return "Hello World!"

RegEx literals

With the exceptions of "O"† and 0.

†"O" is capitalized, "o" is not acceptable.

Title: Hello World 0.0!

Body:
Emacs Lisp, 281 bytes

(defalias'O'string-to-char)
(setq O(1+(O"O"))O0(-(1+ O)(O"O"))OO(* O0 O0 O0 O0 O0 O0)O1(+ O(- O OO))OOO(+ O1 (* O0 O0 O0) O0 O0)OO1(1+ (+ OOO O0)))
(princ(string(-O(* O0 O0 O0))(1+(+ O1 O0 O0))OOO OOO OO1 (/ OO O0)(1+ (+ O O0 O0 O0))OO1(1+ (+ OO1 O0))OOO(+ O1 O0 O0)(1+(/ OO O0))))

1+ is not a number, but a function, that returns 1 + NUMBER with NUMBER as its argument.

Ungolfed:

(defalias'O'string-to-char)
(setq O (1+ (O"O"))                 ; 80 => "P"
      O0 (-(1+ O)(O"O"))            ; 2
      OO (* O0 O0 O0 O0 O0 O0)      ; 64
      O1 (+ O(- O OO))              ; 96
      OOO (+ O1 (* O0 O0 O0) O0 O0) ; 108 => "l"
      OO1 (1+ (+ OOO O0)))          ; 111 => "o"
(princ
 (string
  (- O (* O0 O0 O0))   ; "H"
  (1+(+ O1 O0 O0))     ; "e"
  OOO                  ; "l"
  OOO                  ; "l"
  OO1                  ; "o"
  (/ OO O0)            ; " "
  (1+ (+ O O0 O0 O0))  ; "W"
  OO1                  ; "o"
  (1+ (+ OO1 O0))      ; "r"
  OOO                  ; "l"
  (+ O1 O0 O0)         ; "d"
  (1+ (/ OO O0))))     ; "!"


答:
C, <s>145</s> 138 bytes

Thanks to Giacomo for 7 bytes!

```<code>#define P printf(
n;main(c,v,p,t)char**v;{p=-101;for(v++;*v;v++){t=atoi(*v);if(t<p)P"}{");if(t>p)P"{",n++);P"%d ",p=t);}for(;n--;)P"}");}
</code>```

Input is taken through command line arguments and output is given though
stdout.

sample run:

```<code>$ ./autonest 7 3 1 -8 4 8 2 -9 2 8
{7 }{3 }{1 }{-8 {4 {8 }{2 }{-9 {2 {8 }}}}}
</code>```

Title: Autonest an array

Body:
Everybody loves nested lists! However, sometimes it's hard to make a nested list. You have to decide if you want to nest it deeper, or if you need to nest it shallower. So for your challenge, you must "Autonest" a list. To autonest a list, compare every pair of items in the list.

If the second item is smaller, separate the two elements by inserting closing and opening brackets between them, like this:

```<code>  } {
{2 , 1}
</code>```

For example, {2, 1} becomes {2}, {1}, and {3, 2, 1} becomes {3}, {2}, {1}

If the second item is the same, then change nothing. For example, {1, 1, 1} stays the same, and {2, 1, 1, 1} would become {2}, {1, 1, 1}.

If the second item is larger, then nest every following item one level deeper. For example, {1, 2} would become {1, {2}} and {1, 2, 3} would become {1, {2, {3}}}

The Challenge

You must write a program or function that takes in a list of numbers, and returns the same list after being autonested. Take this input in your languages native list format (or the closest alternative) or as a string. You do not have to use curly braces like I did in my examples. You can use whichever type of brackets are most natural in your language, as long as this is consistent. You can safely assume the list will only contain integers. You can also assume the list will have at least 2 numbers in it. Here is some sample IO:

```<code>{1, 3, 2}                         -->   {1, {3}, {2}}
{1, 2, 3, 4, 5, 6}                -->   {1, {2, {3, {4, {5, {6}}}}}}
{6, 5, 4, 3, 2, 1}                -->   {6}, {5}, {4}, {3}, {2}, {1}
{7, 3, 3, 2, 6, 4}                -->   {7}, {3, 3}, {2, {6}, {4}}
{7, 3, 1, -8, 4, 8, 2, -9, 2, 8}  -->   {7}, {3}, {1}, {-8, {4, {8}, {2}, {-9, {2, {8}}}}}
</code>```

Standard loopholes apply, and the shortest answer in bytes wins!

Body:
C, <s>145</s> 138 bytes

Thanks to Giacomo for 7 bytes!

#define P printf(
n;main(c,v,p,t)char**v;{p=-101;for(v++;*v;v++){t=atoi(*v);if(t<p)P"}{");if(t>p)P"{",n++);P"%d ",p=t);}for(;n--;)P"}");}

Input is taken through command line arguments and output is given though
stdout.

sample run:

$ ./autonest 7 3 1 -8 4 8 2 -9 2 8
{7 }{3 }{1 }{-8 {4 {8 }{2 }{-9 {2 {8 }}}}}


问:
Obfuscated Hello World
Create the shortest possible obfuscated program that displays the text "Hello World".

In order to be considered an obfuscated program, it must meet at least two of the following requirements:

Does not contain the characters: h, l, w and d in any case

Does not contain the characters: e, o, r, 0, and 1 in any case

Does not contain the characters: 2 or 7

Input:

none

Output:

Hello World

Leaderboard

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

/* Configuration */

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

```

答:
Python 2, 39 chars

```<code>print'\x48e\x6c\x6co %cor\x6c\x64'%-~86
</code>```

Breaks rule 3-1.

Ungolfed versions

```<code>print '%ce%c%co %cor%c%c' % (0x48, 0x6c, 0x6c, 0x56 + 0x1, 0x6c, 0x64)
</code>```
```print '%ce%c%co %cor%c%c' % (68 + 4, 108, 108, 86 + 1, 108, 100)```

Normal version (-2) (18 chars)

```<code>print'Hello World'
</code>```

Ungolfed

```<code>print 'Hello World'
</code>```

Title: Obfuscated Hello World

Body:
Python 2, 39 chars

print'\x48e\x6c\x6co %cor\x6c\x64'%-~86

Breaks rule 3-1.

Ungolfed versions

print '%ce%c%co %cor%c%c' % (0x48, 0x6c, 0x6c, 0x56 + 0x1, 0x6c, 0x64)

print '%ce%c%co %cor%c%c' % (68 + 4, 108, 108, 86 + 1, 108, 100)

Normal version (-2) (18 chars)

print'Hello World'

Ungolfed

print 'Hello World'


答:
DOG, 20 bytes

```<code>bark "Hello, World!"
</code>```

Title: "Hello, World!"

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

```

Body:
DOG, 20 bytes

bark "Hello, World!"


问:
Recursion bracketed; or Dyck words generation
We already have challenges to check if a string of brackets is fully matched and to count the number of balanced strings. It remains for us to generate these strings, but it will not be so easy…

A Dyck word is a string, of length 2n, consisting of n opening and n closing parentheses (( and )) fully matched (that is to say: for all prefixes of the string, the number of opening parentheses is greater than or equal to the number of closing ones).

It is interesting to note that the number of different Dyck words of length 2n is equal to the (n + 1)-th Catalan number.

It’s pretty straightforward to write a program that generates these words with a recursive function. But the goal here is to do the same thing without.

Challenge

Write a full program or function that takes a positive integer, n, using stdin or an acceptable alternative, and outputs all the different Dyck words of length 2n. The words can appear in any order and each must be separated from each other by a line break. Moreover, your program should not use recursive functions (see details below).

Rules

The output of your program should only contain Dyck words of length 2n, separated by line breaks. Each word must appear only once.

Your program must work at minimum for inputs 0 to 15.

You may not write recursive functions, neither direct (a function that calls itself) nor indirect (e.g. a function f that calls another function g that calls function f). That being said, you can still use the standard functions of your language without worry of how they work internally.

Similarly, your program should not call itself.

You may not use non-standard librairies.

Your program may not read or write files.

Your program must be able to run in a reasonable time for 0 ≤ n ≤ 15 (hence, naively generate all arrangements is probably not a good idea). Let’s say less than 20 minutes with a memory limit of 4 GB (my reference implementation in C manages n = 15 in less than 5 seconds).

All standard loopholes are forbidden.

As usual in code-golf, the shortest code in bytes wins. But if you have found an interesting way to achieve this challenge in your language, please do not hesitate.

Test I/O

For this input:

```<code>3
</code>```

The output could be (any other order is correct too):

```<code>((()))
()()()
(()())
(())()
()(())
</code>```

答:
CJam (48 bytes)

```<code>ri"()"*${_p_,{1$>_)-,\(-,<},_{W=/(\s$1m>+}{&}?}h
</code>```

Online demo. This effectively takes one obvious recursive solution and makes it iterative. Instead of actually simulating the steps back up the stack, it applies a successor rule:

Find the last ( which starts a suffix with strictly more ) than (; sort that suffix, and rotate once.

Note that this is deliberately designed to avoid keeping the full list of solutions in memory, because I don't think it fits (at least, not if run on a 64-bit machine. It might on a 32-bit machine). There are 9694845 Dyck paths for n=15, so that's 30*9694845 characters, and 92*9694845 = 891925740 bytes of memory just for the (Java) String objects. But then the List holding the objects probably wraps an array with space for 16777216 elements, which is a further 256MB, and the CJam interpreter itself seems to add quite a bit of overhead.

(42 bytes)

```<code>Ma{{_'(+\')+}%{"()"\f{\-,}I+_$=},}ri:I2**,
</code>```

This builds the strings up one character at a time, filtering to ensure that no string has more than n opening parentheses or more closing than opening parentheses. However, it runs out of memory with 3GB for n=15.

The same idea at 39 bytes, but this runs out of memory earlier.

```<code>Ma{"()":Sm*::+{S\f{\-,}I+_$=},}ri:I2**`
</code>```

Online demo

(24 bytes)

My original answer, now disqualified by rule changes.

```<code>{"()"*e!{0\+{~_}*]1&!},}
</code>```

This is an anonymous function which takes input on the stack. Online demo.

It works by the obvious approach of taking all permutations of n pairs of parentheses and filtering for those which are balanced.

Body:
CJam (48 bytes)

ri"()"*${_p_,{1$>_)-,\(-,<},_{W=/(\s$1m>+}{&}?}h

Online demo. This effectively takes one obvious recursive solution and makes it iterative. Instead of actually simulating the steps back up the stack, it applies a successor rule:

Find the last ( which starts a suffix with strictly more ) than (; sort that suffix, and rotate once.

Note that this is deliberately designed to avoid keeping the full list of solutions in memory, because I don't think it fits (at least, not if run on a 64-bit machine. It might on a 32-bit machine). There are 9694845 Dyck paths for n=15, so that's 30*9694845 characters, and 92*9694845 = 891925740 bytes of memory just for the (Java) String objects. But then the List holding the objects probably wraps an array with space for 16777216 elements, which is a further 256MB, and the CJam interpreter itself seems to add quite a bit of overhead.

(42 bytes)

Ma{{_'(+\')+}%{"()"\f{\-,}I+_$=},}ri:I2**,

This builds the strings up one character at a time, filtering to ensure that no string has more than n opening parentheses or more closing than opening parentheses. However, it runs out of memory with 3GB for n=15.

The same idea at 39 bytes, but this runs out of memory earlier.

Ma{"()":Sm*::+{S\f{\-,}I+_$=},}ri:I2**`

Online demo

(24 bytes)

My original answer, now disqualified by rule changes.

{"()"*e!{0\+{~_}*]1&!},}

This is an anonymous function which takes input on the stack. Online demo.

It works by the obvious approach of taking all permutations of n pairs of parentheses and filtering for those which are balanced.


Title: Autonest an array

Body:
Python 3, 98 bytes

p,*i=eval(input())
c=[p]
a=b=[c]
for x in i:
 if x>p:b=c
 if x!=p:c=[];b+=[c]
 c+=[x];p=x
print(a)

Example:

$ python3 autonest.py <<< "[7, 3, 1, -8, 4, 8, 2, -9, 2, 8]"
[[7], [3], [1], [-8, [4, [8], [2], [-9, [2, [8]]]]]]


问:
bfcat - encode a file as a brainf*** program

Challenge

Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..

Assume all inputs are encoded as ASCII.

Assume the outputted BF program will execute in an environment with an infinite tape.

Assume the pointer starts at cell 0 with every cell initialized to a value of zero.

Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.

The tape is doubly infinite.

All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.

Examples

Space string

Given the input  , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
++ .
</code>```

Exclamation point

Given the input ! , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++
.
</code>```

Two letters

Given the input hi , your program/function could return:

```<code>+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

++++
.
+
.
</code>```

This is code-golf, so the code with the smallest number of bytes wins. Good luck.

答:
GNU Bash, <s>100</s> 85 bytes

```<code>while IFS= read -rn1 c;do printf '+%.0s' $(seq 1 $(printf %d \'$c));echo '.>';done<$1
</code>```

Thanks @cat for saving me 15 bytes!

Postramble

Assumes input string is represented as-is in a file passed as first argument.

Usage: bash bfcat.sh <path to file containing string>

Usage (with named pipe): bash bfcat.sh <(echo -n '<string>')

Ungolfed

```<code>while IFS= read -r -n1 c # Read file byte by byte [1]
do
    n=$(printf "%d" \'"$c") # `ord` of a char in bash [2]
    printf '+%.0s' $(seq 1 $n) # emit character $n times [3]
    echo '.>' # Emit output and shift command for bf. I love infinite memory.
done <"$1"
</code>```

References in Ungolfed version

Read file byte by byte

ord of a char in bash

emit character $n times

Body:
GNU Bash, <s>100</s> 85 bytes

while IFS= read -rn1 c;do printf '+%.0s' $(seq 1 $(printf %d \'$c));echo '.>';done<$1

Thanks @cat for saving me 15 bytes!

Postramble

Assumes input string is represented as-is in a file passed as first argument.

Usage: bash bfcat.sh <path to file containing string>

Usage (with named pipe): bash bfcat.sh <(echo -n '<string>')

Ungolfed

while IFS= read -r -n1 c # Read file byte by byte [1]
do
    n=$(printf "%d" \'"$c") # `ord` of a char in bash [2]
    printf '+%.0s' $(seq 1 $n) # emit character $n times [3]
    echo '.>' # Emit output and shift command for bf. I love infinite memory.
done <"$1"

References in Ungolfed version

Read file byte by byte

ord of a char in bash

emit character $n times


答:
Retina, <s>71</s> 70 bytes

Lists are space separated, with curly braces: {1 2 3}. Negative numbers are not supported, so if that's a problem, I'll just delete my answer. Retina + negative numbers = not worth it.

```<code>\d+
$*
+`\b(1+) (1+\1\b.*)
$1 {$2}
+`\b(1(1+)1*) (\2)\b
$1} {$2
1+
$.0
</code>```

Try it online

Title: Autonest an array

Body:
Retina, <s>71</s> 70 bytes

Lists are space separated, with curly braces: {1 2 3}. Negative numbers are not supported, so if that's a problem, I'll just delete my answer. Retina + negative numbers = not worth it.

\d+
$*
+`\b(1+) (1+\1\b.*)
$1 {$2}
+`\b(1(1+)1*) (\2)\b
$1} {$2
1+
$.0

Try it online


问:
Create a hash from an array of arrays of key|value pairs
Starting from an array of sub-arrays, each sub-array is a 2 elements key|value pair. Example

```<code>input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]
</code>```

Convert this into a hash that has distinct keys from above, with values summed up, so the above would be:

```<code>output = {"A" => 17, "B" => 0, "C" => 7}
</code>```

答:
TXR

```<code>@(do (let ((h (hash :equal-based)))
       (each ((entry '(("A" 5) ("B" 2) ("A" 12) ("B" -2) ("C" 7))))
         (inc [h (first entry) 0] (second entry)))
       (format t "~a\n" h)))
</code>```

Run:

```<code>$ txr sumhash.txr
#H((:equal-based) ("A" 17) ("B" 0) ("C" 7))
</code>```

What if we take the question literally? The question says that the input is this:

```<code>input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]
</code>```

and that the output looks like this:

```<code>output = {"A" => 17, "B" => 0, "C" => 7}
</code>```

Fair enough. We can make a program to transform that exact input to  that exact output, rather than massaging the data to fit the syntax of our programming language.

```<code>input = [@(coll :vars (key value))["@key", @{value /[+\-]?[0-9]+/}]@(last)]@(end)
@(bind (keyout valout) @(let ((h (hash :equal-based)))
                          (each* ((k key)
                                  (v [mapcar (op int-str @1 10) value]))
                             (inc [h k 0] v))
                          '(,(hash-keys h) ,(hash-values h))))
@(output)
output = {@(rep)"@keyout" => @valout, @(last)"@keyout" => @valout@(end)}
@(end)
</code>```

Run:

```<code>$ txr sumhash2.txr -   # input read from stdin
input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]
<user types Ctrl-D>
output = {"A" => 17, "B" => 0, "C" => 7}
</code>```

Empty case:

```<code>$ txr sumhash2.txr -
input = []
<Ctrl-D>
output = []
</code>```

Invalid input:

```<code>$ txr sumhash2.txr
foo
<Ctrl-D>
false
</code>```

Word false is output, termination status is failed.

Simplified version in which hashing is worked into data acquisition (side effects during pattern matching):

```<code>@(bind h @(hash :equal-based))
input = [@(coll)["@key", @{value /[+\-]?[0-9]+/}]@\
                @(do (inc [h key 0] (int-str value 10)))@\
                @(last)]@(end)
@(bind (keyout valout) (@(hash-keys h) @(hash-values h)))
@(output)
output = {@(rep)"@keyout" => @valout, @(last)"@keyout" => @valout@(end)}
@(end)
</code>```

Body:
TXR

@(do (let ((h (hash :equal-based)))
       (each ((entry '(("A" 5) ("B" 2) ("A" 12) ("B" -2) ("C" 7))))
         (inc [h (first entry) 0] (second entry)))
       (format t "~a\n" h)))

Run:

$ txr sumhash.txr
#H((:equal-based) ("A" 17) ("B" 0) ("C" 7))

What if we take the question literally? The question says that the input is this:

input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]

and that the output looks like this:

output = {"A" => 17, "B" => 0, "C" => 7}

Fair enough. We can make a program to transform that exact input to  that exact output, rather than massaging the data to fit the syntax of our programming language.

input = [@(coll :vars (key value))["@key", @{value /[+\-]?[0-9]+/}]@(last)]@(end)
@(bind (keyout valout) @(let ((h (hash :equal-based)))
                          (each* ((k key)
                                  (v [mapcar (op int-str @1 10) value]))
                             (inc [h k 0] v))
                          '(,(hash-keys h) ,(hash-values h))))
@(output)
output = {@(rep)"@keyout" => @valout, @(last)"@keyout" => @valout@(end)}
@(end)

Run:

$ txr sumhash2.txr -   # input read from stdin
input = [["A", 5], ["B", 2], ["A", 12], ["B", -2], ["C", 7]]
<user types Ctrl-D>
output = {"A" => 17, "B" => 0, "C" => 7}

Empty case:

$ txr sumhash2.txr -
input = []
<Ctrl-D>
output = []

Invalid input:

$ txr sumhash2.txr
foo
<Ctrl-D>
false

Word false is output, termination status is failed.

Simplified version in which hashing is worked into data acquisition (side effects during pattern matching):

@(bind h @(hash :equal-based))
input = [@(coll)["@key", @{value /[+\-]?[0-9]+/}]@\
                @(do (inc [h key 0] (int-str value 10)))@\
                @(last)]@(end)
@(bind (keyout valout) (@(hash-keys h) @(hash-values h)))
@(output)
output = {@(rep)"@keyout" => @valout, @(last)"@keyout" => @valout@(end)}
@(end)


问:
Write a AZERTY to QWERTY converter
Your task is to create a program will transform each letter of a text typed on a AZERTY keyboard to the equivalent on a QWERTY keyboard, using the same keystrokes.

Example: Hello; Zorld1 => Hello, World!

List of character to convert:

A <=> Q

Z <=> W

, => m

? => M

M => :

1 => !

9 => (

; => ,

§ => ?

0 => )

) => -

ù => '

QWERTY keyboard:

AZERTY keyboard:

Test cases:

```<code>Input: This is q text zritten zith q QWERTY keyboqrd:
Output: This is a text written with a AZERTY keyboard.

Input: Hello zorld in PythonM print9ùHello; Zorld1ù0
Output: Hello world in Python: print('Hello, World!')

Input: Zikipediq is q free online enciclopediq
Output: Wikipedia is a free online enciclopedia

Input: Progrq,,ing puwwles qnd code)golf
Output: Programming puzzles and code-golf

Input: Zhy ,y lqyout hqve szitched to QWERTY §
Output: Why my layout have switched to AZERTY ?
</code>```

This is code golf, so the answer with the shortest byte count win.

答:
Python 3, 70 132 bytes

My first try in code-golfing, so please be kind :):

print(input().translate(str.maketrans('azqwAZQW&é"\'(-è_çà)^$Mù,?;:!§1234567890','qwazQWAZ1234567890-[]:\'mM,./?!@#$%^&*()')))
```

Try it online!

Title: Write a AZERTY to QWERTY converter

Body:
Python 3, 70 132 bytes

My first try in code-golfing, so please be kind :):

print(input().translate(str.maketrans('azqwAZQW&é"\'(-è_çà)^$Mù,?;:!§1234567890','qwazQWAZ1234567890-[]:\'mM,./?!@#$%^&*()')))

Try it online!


问:
Difference of the square of the sum
Find the difference between the square of the sums and sum of the squares.

This is the mathematical representation:

\$\left(\sum n\right)^2-\sum n^2\$

Your program/method should take two inputs, these are your lower and upper limits of the range, and are inclusive.
Limits will be whole integers above 0.

Your program/method should return the answer.

You may use whichever base you would like to, but please state in your answer which base you have used.

Test case (Base 10)

```<code>5,9      970
91,123   12087152
1,10     2640
</code>```

This is usual code-golf, so the shorter the answer the better.

答:
CoffeeScript, 49 Bytes

f=(n,m,s=0)->if n>m then 0else 2*n*s+f(n+1,m,n+s)

Translation of Neil's answer

Output:

f 91, 123 == 12087152
 => true

Title: Difference of the square of the sum


答:
JavaScript (ES6), 203

Implementing this algorithm (point 3, totally iterative)

Within the limits of script executing in Firefox, I managed to have the 200K console output for input 12 in about 1.5 minutes

n=>{
for(b=[...Array(n)].map((_,i)=>1+2*i),z=0;!z;)
for(c=[...'('.repeat(n+n)],b.map(n=>c[n]=')'),console.log(c.join``),z=i=n;i--&&z;)
if(b[i]<n+i)for(z=0,b[j=i]++;++j<n-1;)b[j]=Math.max(b[j-1],2*j)+1
}
```
<p><em>Less golfed</em></p>
<pre class="lang-js prettyprint-override"><code>n=>{
  b=[...Array(n)].map((_,i)=>1+2*i)
  q=0
  for(z=0;!z;)
  {
    c=[...'('.repeat(n+n)],
    b.map(n=>c[n]=')'),
    console.log(++q,c.join``)
    for(z=i=n;i--&&z;)
      if(b[i]<n+i)
        for(z=0,b[j=i]++;++j<n-1;)
          b[j]=Math.max(b[j-1],2*j)+1
  }
}
</code>```

Ported to C just for fun, run in 5 secs for input 15 (it compiles and works without #includes)

f(n){int i,j,z,b[49];char c[99];
for(i=n;i--;)b[i]=2*i+1;
for(z=0;!z;){memset(c,40,n+n);c[n+n]=0;
for(i=n;i--;)c[b[i]]=41;puts(c);
for(z=i=n;i--&&z;)if(b[i]<n+i)for(z=0,b[j=i]++;++j<n;)b[j]=(b[j-1]>2*j?b[j-1]:2*j)+1;
}}
```
<p><strong>Test</strong> generating all output but do not display it, just counting output rows</p>
<p>I got 90 sec for input 15
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>F=n=>{
for(b=[...Array(n)].map((_,i)=>1+2*i),z=0;!z;)
for(c=[...'('.repeat(n+n)],b.map(n=>c[n]=')'),console.log(c.join``),z=i=n;i--&&z;)
if(b[i]<n+i)for(z=0,b[j=i]++;++j<n-1;)b[j]=Math.max(b[j-1],2*j)+1
}

console.log=x=>o++ // console.log display no output, just count rows

function test() {
  n=+I.value,o=0,t=+new Date
  O.textContent='...wait...'
  setTimeout(_=>(F(n),O.textContent=['rows='+o,'time sec '+(new Date-t)/1000]), 10)

}

test()</code>```

N:<input id=I value=12 type=number max=20><button onclick='test()'>go</button>

```</code>```

Title: Recursion bracketed; or Dyck words generation

Body:
We already have challenges to check if a string of brackets is fully matched and to count the number of balanced strings. It remains for us to generate these strings, but it will not be so easy…

A Dyck word is a string, of length 2n, consisting of n opening and n closing parentheses (( and )) fully matched (that is to say: for all prefixes of the string, the number of opening parentheses is greater than or equal to the number of closing ones).

It is interesting to note that the number of different Dyck words of length 2n is equal to the (n + 1)-th Catalan number.

It’s pretty straightforward to write a program that generates these words with a recursive function. But the goal here is to do the same thing without.

Challenge

Write a full program or function that takes a positive integer, n, using stdin or an acceptable alternative, and outputs all the different Dyck words of length 2n. The words can appear in any order and each must be separated from each other by a line break. Moreover, your program should not use recursive functions (see details below).

Rules

The output of your program should only contain Dyck words of length 2n, separated by line breaks. Each word must appear only once.

Your program must work at minimum for inputs 0 to 15.

You may not write recursive functions, neither direct (a function that calls itself) nor indirect (e.g. a function f that calls another function g that calls function f). That being said, you can still use the standard functions of your language without worry of how they work internally.

Similarly, your program should not call itself.

You may not use non-standard librairies.

Your program may not read or write files.

Your program must be able to run in a reasonable time for 0 ≤ n ≤ 15 (hence, naively generate all arrangements is probably not a good idea). Let’s say less than 20 minutes with a memory limit of 4 GB (my reference implementation in C manages n = 15 in less than 5 seconds).

All standard loopholes are forbidden.

As usual in code-golf, the shortest code in bytes wins. But if you have found an interesting way to achieve this challenge in your language, please do not hesitate.

Test I/O

For this input:

```<code>3
</code>```

The output could be (any other order is correct too):

```<code>((()))
()()()
(()())
(())()
()(())
</code>```

Body:
JavaScript (ES6), 203

Implementing this algorithm (point 3, totally iterative)

Within the limits of script executing in Firefox, I managed to have the 200K console output for input 12 in about 1.5 minutes

n=>{
for(b=[...Array(n)].map((_,i)=>1+2*i),z=0;!z;)
for(c=[...'('.repeat(n+n)],b.map(n=>c[n]=')'),console.log(c.join``),z=i=n;i--&&z;)
if(b[i]<n+i)for(z=0,b[j=i]++;++j<n-1;)b[j]=Math.max(b[j-1],2*j)+1
}

Less golfed

n=>{
  b=[...Array(n)].map((_,i)=>1+2*i)
  q=0
  for(z=0;!z;)
  {
    c=[...'('.repeat(n+n)],
    b.map(n=>c[n]=')'),
    console.log(++q,c.join``)
    for(z=i=n;i--&&z;)
      if(b[i]<n+i)
        for(z=0,b[j=i]++;++j<n-1;)
          b[j]=Math.max(b[j-1],2*j)+1
  }
}

Ported to C just for fun, run in 5 secs for input 15 (it compiles and works without #includes)

f(n){int i,j,z,b[49];char c[99];
for(i=n;i--;)b[i]=2*i+1;
for(z=0;!z;){memset(c,40,n+n);c[n+n]=0;
for(i=n;i--;)c[b[i]]=41;puts(c);
for(z=i=n;i--&&z;)if(b[i]<n+i)for(z=0,b[j=i]++;++j<n;)b[j]=(b[j-1]>2*j?b[j-1]:2*j)+1;
}}

Test generating all output but do not display it, just counting output rows

I got 90 sec for input 15

F=n=>{
for(b=[...Array(n)].map((_,i)=>1+2*i),z=0;!z;)
for(c=[...'('.repeat(n+n)],b.map(n=>c[n]=')'),console.log(c.join``),z=i=n;i--&&z;)
if(b[i]<n+i)for(z=0,b[j=i]++;++j<n-1;)b[j]=Math.max(b[j-1],2*j)+1
}

console.log=x=>o++ // console.log display no output, just count rows

function test() {
  n=+I.value,o=0,t=+new Date
  O.textContent='...wait...'
  setTimeout(_=>(F(n),O.textContent=['rows='+o,'time sec '+(new Date-t)/1000]), 10)

}

test()

N:<input id=I value=12 type=number max=20><button onclick='test()'>go</button>
<pre id=O></pre>


问:
Theoretically output Graham's number
Graham's number G is defined in this way:

```<code>u(3,n,1) = 3^n
u(3,1,m) = 3
u(3,n,m) = u(3,u(3,n-1,m),m-1)
[Knuth's up-arrow notation]
[Conway chained arrow notation]

THEN

g1 = u(3,3,4)
g2 = u(3,3,g1)
g3 = u(3,3,g2)
...
G = u(3,3,g63)
</code>```

You are given that u(3,3,2)=7625597484987 to check your code.

Your task is to write a program/function that will output the value of G deterministically, given enough integer size and enough time.

References

Graham's number

Knuth's up-arrow notation

Conway chained arrow notation

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
J, 107 bytes

```<code>u=:4 :0
if.y=1 do.3^x
elseif.x=1 do.3
elseif.1 do.x:(y u~<:x)u<:y
end.
)
(g=:(3 u 4[[)`(3 u$:@<:)@.(1&<))64
</code>```

I'm working on converting u to an agenda, but for now it'll do.

Title: Theoretically output Graham's number

Body:
J, 107 bytes

u=:4 :0
if.y=1 do.3^x
elseif.x=1 do.3
elseif.1 do.x:(y u~<:x)u<:y
end.
)
(g=:(3 u 4[[)`(3 u$:@<:)@.(1&<))64

I'm working on converting u to an agenda, but for now it'll do.


答:
C99, 105 bytes

i,j,s;f(n){for(char a[31]={};++i%(1<<2*n);s||puts(a))for(j=s=0;~s&&j<2*n;)s+=1-(a[j]=40+(i>>j++)%2)%2*2;}
```

Iterates over all strings of 2n parentheses.

With piped output and compiler flag -O3, input n = 15 takes roughly 15.5 seconds on my machine. Memory consumption is 1.2 MB.

Test it on Ideone.

Body:
C99, 105 bytes

i,j,s;f(n){for(char a[31]={};++i%(1<<2*n);s||puts(a))for(j=s=0;~s&&j<2*n;)s+=1-(a[j]=40+(i>>j++)%2)%2*2;}

Iterates over all strings of 2n parentheses.

With piped output and compiler flag -O3, input n = 15 takes roughly 15.5 seconds on my machine. Memory consumption is 1.2 MB.

Test it on Ideone.


答:
Pyth, 47 bytes

```<code>                                                               <-empty line
Musm?<J/d\(Q?>-J/d\)0,+d\(+d\)]+d\(]+d\)G*2Q]k
</code>```

Took 18 minutes on my machine, and over 2GB RAM.

In pythonic pseudocode:

```<code>// newline means "print"
M                                              map(print,
 u                                               reduce(lambda G,H:
  sm                                               sum(map(lambda d:
                     ,+d\(+d\)                       ([d+"(",d+")"] if
            ?>-J/d\)0                                   J-d.count(")") > 0
                              ]+d\(                     else [d+"("]) if
    ?<J/d\(Q                                           (J=d.count("(") < Q
                                   ]+d\)               else [d+")"],
                                        G              G)),
                                         *2Q]k     2*input(),[""]))
</code>```

In words:

create a function that maps any string to a list of strings that can be formed by adding "(" or ")"

if the parentheses are already matched, only "(" can be added; if there are already n "(", only ")" can be added; otherwise a pair is returned

create a new function that maps the old function over its param, and then sum up the map, so that it takes a list of strings, maps to a list of lists of strings, and then de-nests it back into a list of strings

each call essentially "grows" its params by one ( or )

reduce this new function over range(2*input()), with [""] as base case

essentially just passing [""] through the new function 2n times

map print over the return value of reduce to print each string in new lines

Body:
Pyth, 47 bytes

                                                               <-empty line
Musm?<J/d\(Q?>-J/d\)0,+d\(+d\)]+d\(]+d\)G*2Q]k

Took 18 minutes on my machine, and over 2GB RAM.

In pythonic pseudocode:

// newline means "print"
M                                              map(print,
 u                                               reduce(lambda G,H:
  sm                                               sum(map(lambda d:
                     ,+d\(+d\)                       ([d+"(",d+")"] if
            ?>-J/d\)0                                   J-d.count(")") > 0
                              ]+d\(                     else [d+"("]) if
    ?<J/d\(Q                                           (J=d.count("(") < Q
                                   ]+d\)               else [d+")"],
                                        G              G)),
                                         *2Q]k     2*input(),[""]))

In words:

create a function that maps any string to a list of strings that can be formed by adding "(" or ")"

if the parentheses are already matched, only "(" can be added; if there are already n "(", only ")" can be added; otherwise a pair is returned

create a new function that maps the old function over its param, and then sum up the map, so that it takes a list of strings, maps to a list of lists of strings, and then de-nests it back into a list of strings

each call essentially "grows" its params by one ( or )

reduce this new function over range(2*input()), with [""] as base case

essentially just passing [""] through the new function 2n times

map print over the return value of reduce to print each string in new lines


问:
Fred's water bill
Fred is a quasi-friendly guy, but in reality he is mean.

Because of this, Fred lives alone in a small apartment in Los Altos, CA. Fred is so mean because he is very particular about water. He, therefore, needs your help with figuring out what his water bill is.

Your job is to write a function or program that returns his water bill given the amount of water used as input (which is always an integer).

Water consumption comes in tiers. This means that there are ranges of prices depending on the amount of water.

These are the tiers, their prices, and the amounts of water they correspond to:

```<code>Tier I
   First 10 Ccf: $3.8476/Ccf
Tier II
   Next 17 Ccf: $4.0932/Ccf
Tier III
   All subsequent water: $4.9118/Ccf
</code>```

For n hundreds of cubic feet (Ccf), there are the following additional charges as well:

```<code>CPUC fee: 1.5% of above charges
LIRA quantity surcharge: $0.047*n
PBOP amoritization surcharge: $0.004*n
</code>```

The sum of the Tier I, Tier II, Tier III, CPUC, LIRA, and PBOP fees is the total water bill. This sum you should either return or print to the console rounded to two decimal places.

Here are two examples:

```<code>Input: 15
... Calculations which you do not need to output but here to help explain:
Tier I: 10*3.8476 = 38.476
Tier II: (15-10)*4.0932 = 20.466
Tier III: 0*4.9118 = 0
Tiers sum: 58.942
CPUC: 1.5% of 58.942 = 0.88413
LIRA: 0.047*15 = 0.705
PBOP: 0.004*15 = 0.06
Total sum: 58.942 + 0.88413 + 0.705 + 0.06 = 60.59113
...
Output: 60.59

Input: 100
... Calculations which you do not need to output but here to help explain:
Tier I: 10*3.8476 = 38.476
Tier II: 17*4.0932 = 69.5844
Tier III: (100-10-17)*4.9118 = 358.5614
Tiers sum: 466.6218
CPUC: 1.5% of  = 6.999327
LIRA: 0.047*100 = 4.7
PBOP: 0.004*100 = 0.4
Total sum: 478.721127
...
Output: 478.72
</code>```

This is code golf so shortest code in bytes wins!

答:
VBA, 88 bytes

```<code>Function W(V):W=Round(.051*V+.203*(V*19.238-(V-10)*(V>10)*1.228-(V-27)*(V>27)*4.093),2)

</code>```

The base rate and higher use differential rates have been multiplied by 5, and the CPUC fee multiplier divided by 5 (0.203).

The VB editor will add an End Function line, which is why the terminal line feed is included.

Title: Fred's water bill

Body:
VBA, 88 bytes

Function W(V):W=Round(.051*V+.203*(V*19.238-(V-10)*(V>10)*1.228-(V-27)*(V>27)*4.093),2)

The base rate and higher use differential rates have been multiplied by 5, and the CPUC fee multiplier divided by 5 (0.203).

The VB editor will add an End Function line, which is why the terminal line feed is included.


答:
JavaScript (ES6), 125 bytes

```<code>n=>{for(i=m=1<<n+n-1;i&m;i++){for(j=m,z=o=0;o>=z;j>>=1)i&j?o++:z++;o-n||console.log(i.toString(2).replace(/./g,d=>")("[d]))}}
</code>```

Actually printing the results slows things down horribly, but with console.log set to ()=>{} this takes my machine about 7 seconds for n=12, which presumably translates to 7 minutes for n=15. If that's not fast enough, you can replace i++ with i+=2 or even i+=j||2 but that made only a few percent difference in my testing. Works by generating all 2n-digit binary numbers and checking whether they represent a Dyck word. Ungolfed:

```<code>function dyck(n) {
    // Don't bother generating words that begin with ),
    // so start half-way though 4 ** n.
    for (var i = 4 ** n / 2; i < 4 ** n; i += 2) {
        // Convert to the string of ()s.
        var word = i.toString(2);
        word = word.replace(/1/g, "(");
        word = word.replace(/0/g, ")");
        // Count the (s and )s separately.
        var left = 0;
        var right = 0;
        for (var j = 0; j < n + n; j++) {
            if (word[j] == "(") left++;
            else right++;
            // Abort if there are too many )s
            if (right > left) break;
        }
        // If we got exactly n (s then it's a Dyck word.
        if (left == n) console.log(word);
    }
}
</code>```

Body:
JavaScript (ES6), 125 bytes

n=>{for(i=m=1<<n+n-1;i&m;i++){for(j=m,z=o=0;o>=z;j>>=1)i&j?o++:z++;o-n||console.log(i.toString(2).replace(/./g,d=>")("[d]))}}

Actually printing the results slows things down horribly, but with console.log set to ()=>{} this takes my machine about 7 seconds for n=12, which presumably translates to 7 minutes for n=15. If that's not fast enough, you can replace i++ with i+=2 or even i+=j||2 but that made only a few percent difference in my testing. Works by generating all 2n-digit binary numbers and checking whether they represent a Dyck word. Ungolfed:

function dyck(n) {
    // Don't bother generating words that begin with ),
    // so start half-way though 4 ** n.
    for (var i = 4 ** n / 2; i < 4 ** n; i += 2) {
        // Convert to the string of ()s.
        var word = i.toString(2);
        word = word.replace(/1/g, "(");
        word = word.replace(/0/g, ")");
        // Count the (s and )s separately.
        var left = 0;
        var right = 0;
        for (var j = 0; j < n + n; j++) {
            if (word[j] == "(") left++;
            else right++;
            // Abort if there are too many )s
            if (right > left) break;
        }
        // If we got exactly n (s then it's a Dyck word.
        if (left == n) console.log(word);
    }
}


问:
It's Life, Jim, but not as we know it
You probably know Conway's Game of Life, the famous cellular automaton invented by mathematician John Conway. Life is a set of rules that, together, allow you to simulate a two-dimensional board of cells. The rules decide which cells on the board live and  which ones die. With some imagination, you could say that Life is a zero-player game: a game with the objective to find patterns with interesting behavior, like the famous glider.

A zero-player game... Until today. You are to write a program that plays the Game of Life - and plays it to win, King of the Hill-style. Your opponent (singular) of course tries to do the same. The winner is either the last bot with any live cells, or the player with the most live cells after 10000 generations.

Game rules

The rules are almost the same as normal (B3/S23) Life:

A live cell with fewer than two friendly neighbors dies from starvation.

A live cell with two or three friendly neighbors survives.

A live cell with more than three friendly neighbors dies from overpopulation.

A dead cell with exactly three neighbors of the same player comes alive to fight for that player provided there are no enemy neighbors.

...but after each generation, both you and your opponent get the opportunity to intervene. You can awake up to a maximum of 30 cells to fight for you. (Who goes first is decided by the server.)

The board is a (x,y) cells square. All squares are initially dead. The borders do not wrap around (this is not a torus-shaped world) and are permanently dead.

This is is a contest in the spirit of Battlebots and Core Wars. There is a central server that will run bots and it can be found here

Protocol

The arena server speaks a simple JSON protocol communicated through argv

Where Values is a JSON encoded string

y_size: the maximum y coords of tiles before they vanish

x_size: the maximum x coords of tiles before they vanish

tick_id: the current tick number

board: a dictionary with keys in the form '(y,x)' and values in the form bot_id (int)

bot_id: tiles in the board with this id are yours

Example:

```<code> {"y_size":2000,"x_size":2000,"board":{},"bot_id":1,"tick_id":1}

</code>```

Telling the server your choice:

Send the server a list of tiles to turn to your colour.

Only those that are empty will be changed

Nested coords list format

[[0,0], [0,1], [100,22]...]

NOTE: Your bot doesn't have to update the tiles at all - the server does the updating itself

Competition rules

If your implementation fails to follow the protocol, the turn it does will be forfeited; The server will assume no change in state

You are not allowed to willfully take advantage of a fault in the arena server.

Have your AI decide on moves in a sane time. Please send your next move as  fast as reasonably possible.

Finally, please be nice to the server. It's there for your enjoyment.

Not following these rules can lead to disqualification.

In the event of a tie, both players have 1 win added to their total

Running the controller yourself

The source for the controller can be found here. There are 2 ways of running the controller:

Competition mode (terminal)

Setup with python3 get_answers.py

Run an all v all competition with each bot pitting it against every other.

Testing mode (GUI)

Run python3 nice_gui.py

Click Pull Answers

If you want to add your own answer to try it before posting, click File -> Add manual answer and find the file and choose the language it's written in.

If your language isn't present ping me and I'll try to get it installed on the server I will run it on (installation and running instructions would be nice too!)

Choose 2 bots to pit against each other

Click Run

Watch the game...

Installation

Requires python3

get_answers requires bs4 and html5lib

controller requires a way of running .sh files (MinGW on windows)

Scoring

The bot with the most wins starting from <s>12/07/2016 (12th July)</s>   14/07/2016 (14th July, couldn't work out how to run a bot) wins.

Help with the controller/gui can be asked in this chat room

This question has been in development since 2014 and was the most upvoted question in the sandbox. Special Thanks goes to Wander Nauta (original author and concept), PPCG Chat (comments and help) and anyone who commented in the sandbox post (more comments).

答:
Python 2, TrainingBot

Because everyone needs one of these!

```<code>import random, copy
import sys, json

args = json.loads(sys.argv[1])
bot_id = args["bot_id"]
x_size = args["x_size"]
y_size = args["y_size"]
cur_tick = args["tick_id"]
board = args["board"]

glider = [[1,2],[2,1],[0,0],[0,1],[0,2]]

x_add = random.randrange(x_size)
y_add = random.randrange(y_size)
new_glider = copy.deepcopy(glider)
for coord in new_glider:
    coord[0]+=y_add
    coord[1]+=x_add
move = new_glider
print json.dumps(move)
</code>```

Title: It's Life, Jim, but not as we know it

Body:
Python 2, TrainingBot

Because everyone needs one of these!

import random, copy
import sys, json

args = json.loads(sys.argv[1])
bot_id = args["bot_id"]
x_size = args["x_size"]
y_size = args["y_size"]
cur_tick = args["tick_id"]
board = args["board"]

glider = [[1,2],[2,1],[0,0],[0,1],[0,2]]

x_add = random.randrange(x_size)
y_add = random.randrange(y_size)
new_glider = copy.deepcopy(glider)
for coord in new_glider:
    coord[0]+=y_add
    coord[1]+=x_add
move = new_glider
print json.dumps(move)


问:
Tips for golfing in GolfScript
What, this post doesn't exist yet?

Of course, GolfScript is made for golfing, so you might think that no specific tips are really needed.  But to make full use of GolfScript's features, you need to learn some non-obvious tricks.  This post is for collecting such helpful tips and tricks.

To start with, here are the official GolfScript reference pages.  You should really familiarize yourself with these first:

Tutorial

Syntax

Built-ins

Quick reference

In particular, I would very much suggest reading the pages in this order — the quick reference is of little use until you're already reasonably familiar with the built-ins, and the tutorial includes some important details that are not explained on the other pages.

Ps. For the sake of inspiration and personal interest, here are some questions I'd like to see nice answers to:

How to do limited transliteration in GolfScript?  {FROM?TO=}% works if you can be sure all the inputs are found in FROM (or don't mind them all being mapped to the last element of TO), but all the ways I've seen for leaving unmapped values unchanged have been more or less klugey.

How to best convert a string into an array of ASCII codes and back?  Which operations do this as a side effect?  What's the best way to dump the characters in a string onto the stack (like ~ does for arrays)?

答:
To address a specific subquestion:

How to best convert a string into an array of ASCII codes and back? Which operations do this as a side effect? What's the best way to dump the characters in a string onto the stack (like ~ does for arrays)?

For those who don't understand the problem, GolfScript's type system gives priority to the types in the order integer, array, string, block. This means that ordinary array operations applied to a string almost always give you a string. E.g.

```<code>'ABC123'{)}%
</code>```

will leave 'BCD234' on the stack.

As a result, the best way to convert a string into an array of ASCII codes is almost certainly to dump the characters on the stack and then gather them into an array.

What's the best way to dump the characters in a string onto the stack? {}/

What's the best way to convert a string into an array of ASCII codes? [{}/] (with the usual caveat that if there's nothing else on the stack you can skip the [)

What's the best way to convert an array of ASCII codes into a string? ''+ (Note that this also flattens the array, so e.g. [65 [66 67] [[[49] 50] 51]]''+ gives 'ABC123')

Title: Tips for golfing in GolfScript

Body:
To address a specific subquestion:

How to best convert a string into an array of ASCII codes and back? Which operations do this as a side effect? What's the best way to dump the characters in a string onto the stack (like ~ does for arrays)?

For those who don't understand the problem, GolfScript's type system gives priority to the types in the order integer, array, string, block. This means that ordinary array operations applied to a string almost always give you a string. E.g.

'ABC123'{)}%

will leave 'BCD234' on the stack.

As a result, the best way to convert a string into an array of ASCII codes is almost certainly to dump the characters on the stack and then gather them into an array.

What's the best way to dump the characters in a string onto the stack? {}/

What's the best way to convert a string into an array of ASCII codes? [{}/] (with the usual caveat that if there's nothing else on the stack you can skip the [)

What's the best way to convert an array of ASCII codes into a string? ''+ (Note that this also flattens the array, so e.g. [65 [66 67] [[[49] 50] 51]]''+ gives 'ABC123')