答:
R, 54 bytes

v=L=LETTERS;for(i in 2:26){L[1:i]=L[i];v=cbind(v,L)};v

This solution uses the R built-in constant LETTERS, that... well... lists the uppercase letters. There is also the constant letters for lowercase letters.

Title: Print/Output the L-phabet

Body:
Inspired by George Gibson's Print a Tabula Recta.

You are to print/output this exact text:

```<code>ABCDEFGHIJKLMNOPQRSTUVWXYZ
BBCDEFGHIJKLMNOPQRSTUVWXYZ
CCCDEFGHIJKLMNOPQRSTUVWXYZ
DDDDEFGHIJKLMNOPQRSTUVWXYZ
EEEEEFGHIJKLMNOPQRSTUVWXYZ
FFFFFFGHIJKLMNOPQRSTUVWXYZ
GGGGGGGHIJKLMNOPQRSTUVWXYZ
HHHHHHHHIJKLMNOPQRSTUVWXYZ
IIIIIIIIIJKLMNOPQRSTUVWXYZ
JJJJJJJJJJKLMNOPQRSTUVWXYZ
KKKKKKKKKKKLMNOPQRSTUVWXYZ
LLLLLLLLLLLLMNOPQRSTUVWXYZ
MMMMMMMMMMMMMNOPQRSTUVWXYZ
NNNNNNNNNNNNNNOPQRSTUVWXYZ
OOOOOOOOOOOOOOOPQRSTUVWXYZ
PPPPPPPPPPPPPPPPQRSTUVWXYZ
QQQQQQQQQQQQQQQQQRSTUVWXYZ
RRRRRRRRRRRRRRRRRRSTUVWXYZ
SSSSSSSSSSSSSSSSSSSTUVWXYZ
TTTTTTTTTTTTTTTTTTTTUVWXYZ
UUUUUUUUUUUUUUUUUUUUUVWXYZ
VVVVVVVVVVVVVVVVVVVVVVWXYZ
WWWWWWWWWWWWWWWWWWWWWWWXYZ
XXXXXXXXXXXXXXXXXXXXXXXXYZ
YYYYYYYYYYYYYYYYYYYYYYYYYZ
ZZZZZZZZZZZZZZZZZZZZZZZZZZ
</code>```

(Yes, I typed that by hand)

You are allowed to use all lowercase instead of all uppercase.

However, your choice of case must be consistent throughout the whole text.

Rules/Requirements

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

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

Your program must not write anything to STDERR.

Standard Loopholes are forbidden.

Your program can output in any case, but it must be printed (not an array or similar).

Scoring

Programs are scored according to bytes, in UTF-8 by default or a different character set of your choice.

Eventually, the answer with the least bytes will win.

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```


答:
Forth, 55 bytes

Uses an iterative approach, built upon my Fibonacci answer in Forth. The results overflow arithmetically for n > 10. The answer is case-insensitive.

```<code>: f >r 1 1 r@ 0 DO 2dup + LOOP 2drop 1 r> 0 DO * LOOP ;
</code>```

Try it online

ContentLicense: CC BY-SA 3.0

Title: Fibonacci-orial

Body:
Definition

Fibonacci sequence F(n), on the positive integers, are defined as such:

```<code>1. F(1) = 1
2. F(2) = 1
3. F(n) = F(n-1) + F(n-2), where n is an integer and n > 2
</code>```

The Fibonacci-orial of a positive integer is the product of [F(1), F(2), ..., F(n)].

Task

Given positive integer n, find the Fibonacci-orial of n.

Specs

The fibonacci-orial of 100 must compute in under 5 seconds on a reasonable computer.

Testcases

```<code>n   Fibonacci-orial of n
1   1
2   1
3   2
4   6
5   30
6   240
7   3120
8   65520
9   2227680
10  122522400
11  10904493600
12  1570247078400
13  365867569267200
14  137932073613734400
15  84138564904377984000
16  83044763560621070208000
17  132622487406311849122176000
18  342696507457909818131702784000
19  1432814097681520949608649339904000
20  9692987370815489224102512784450560000
100 3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000
</code>```

References

Obligatory OEIS A003266

OEIS A000045 - Fibonacci sequence

Body:
Forth, 55 bytes

Uses an iterative approach, built upon my Fibonacci answer in Forth. The results overflow arithmetically for n > 10. The answer is case-insensitive.

: f >r 1 1 r@ 0 DO 2dup + LOOP 2drop 1 r> 0 DO * LOOP ;

Try it online


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

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

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

Rules/Requirements

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

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

Your program must not write anything to STDERR.

Standard Loopholes are forbidden.

Your program can output in any case, but it must be printed (not an array or similar).

Scoring

Programs are scored according to bytes, in UTF-8 by default or a different character set of your choice.

Eventually, the answer with the least bytes will win.

Submissions

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

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

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

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

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

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

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

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

Leaderboard

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

  });

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Groovy, 63

```<code>l='A'..'Z'as Queue;(l+[]).each{println l.join();l<<l.remove()}
</code>```

Found a cool way to copy a list by using (l+[]) instead of l.clone()

ContentLicense: CC BY-SA 4.0

Title: Print a Tabula Recta!

Body:
Groovy, 63

l='A'..'Z'as Queue;(l+[]).each{println l.join();l<<l.remove()}

Found a cool way to copy a list by using (l+[]) instead of l.clone()


问:
Create and write to a file

Challenge

Create a new file and write the string Hello World to it.

Restrictions

Your challenge must write to a file on disk, in the file system.

The file may not be a log file generated during normal operation of the interpreter.

The file must contain only the string Hello World. It is allowed to contain a trailing newline or minimal whitespace. No other content.

No command-line flags/pipes (etc) allowed, except when necessary to run the program. (e.g. perl -p)

Notes

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

Follow the spirit, not the letter, of the rules.

答:
C, 37 bytes

```<code>main(){system("echo Hello World>o");}
</code>```

Title: Create and write to a file

Body:
C, 37 bytes

main(){system("echo Hello World>o");}


答:
Perl, 20 bytes

```<code>`echo Hello World>o`
</code>```

Perl will execute anything in backticks (`) as a system command.

Title: Create and write to a file

Body:
Challenge

Create a new file and write the string Hello World to it.

Restrictions

Your challenge must write to a file on disk, in the file system.

The file may not be a log file generated during normal operation of the interpreter.

The file must contain only the string Hello World. It is allowed to contain a trailing newline or minimal whitespace. No other content.

No command-line flags/pipes (etc) allowed, except when necessary to run the program. (e.g. perl -p)

Notes

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

Follow the spirit, not the letter, of the rules.

Body:
Perl, 20 bytes

`echo Hello World>o`

Perl will execute anything in backticks (`) as a system command.


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

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

Example:

input: helloworld

output: llool

Objective: Shortest code wins

Language: Any of the top 20 of TIOBE languages

答:
sed and coreutils (128)

Granted this is not part of the TIOBE list, but it's fun (-:

```<code><<<$s sed 's/./&\n/g'|head -c -1|sort|uniq -c|sed -n 's/^ *1 (.*)/\1/p'|tr -d '\n'|sed 's:^:s/[:; s:$:]//g\n:'|sed -f - <(<<<$s)
</code>```

De-golfed version:

```<code>s=helloworld
<<< $s sed 's/./&\n/g'        \
| head -c -1                  \
| sort                        \
| uniq -c                     \
| sed -n 's/^ *1 (.*)/\1/p'   \
| tr -d '\n'                  \
| sed 's:^:s/[:; s:$:]//g\n:' \
| sed -f - <(<<< $s)
</code>```

Explanation

The first sed converts input into one character per line. The second sed finds characters that only occur once. Third sed writes a sed script that deletes unique characters. The last sed executes the generated script.

Title: Removing unique elements from string

Body:
sed and coreutils (128)

Granted this is not part of the TIOBE list, but it's fun (-:

<<<$s sed 's/./&\n/g'|head -c -1|sort|uniq -c|sed -n 's/^ *1 (.*)/\1/p'|tr -d '\n'|sed 's:^:s/[:; s:$:]//g\n:'|sed -f - <(<<<$s)

De-golfed version:

s=helloworld
<<< $s sed 's/./&\n/g'        \
| head -c -1                  \
| sort                        \
| uniq -c                     \
| sed -n 's/^ *1 (.*)/\1/p'   \
| tr -d '\n'                  \
| sed 's:^:s/[:; s:$:]//g\n:' \
| sed -f - <(<<< $s)

Explanation

The first sed converts input into one character per line. The second sed finds characters that only occur once. Third sed writes a sed script that deletes unique characters. The last sed executes the generated script.


答:
Perl 6, <s> 27 </s> 23 bytes

<s>'o'.IO.spurt: 'Hello World'</s>
spurt 'o','Hello World'```

Title: Create and write to a file


问:
Generate Linus Sequence

Definition

From the description on OEIS A006345:

To find a(n), consider either a 1 or a 2. For each, find the longest repeated suffix, that is, for each of a(n)=1,2, find the longest sequence s with the property that the sequence a(1),...,a(n) ends with ss. Use the digit that results in the shorter such suffix. a(1) = 1.

Worked-out Example

a(1)=1.

If a(2)=1, we will have the sequence 1 1 where the longest doubled substring from the end is 1. If a(2)=2 instead, then it would be the empty substring. Therefore a(2)=2.

When n=6, we choose between 1 2 1 1 2 1 and 1 2 1 1 2 2. In the first choice, 1 2 1 is doubled consecutively from the end. In the second choice, it is 2 instead. Therefore, a(6)=2.

When n=9, we choose between 1 2 1 1 2 2 1 2 1  and 1 2 1 1 2 2 1 2 2. In the first choice, the longest doubled consecutive substring is 2 1, while in the second choice 1 2 2 is doubled consecutively at the end. Therefore a(9)=1.

Task

Given n, return a(n).

Specs

n will be positive.

You can use 0-indexed instead of 1-indexed. In that case, please state so in your answer. Also, in that case, n can be 0 also.

Testcases

The testcases are 1-indexed. However, you can use 0-indexed.

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

References

WolframMathWorld

Obligatory OEIS A006345

答:
Python, 137 bytes

```<code>def a(n,s=[0],r=lambda l:max([0]+filter(lambda i:l[-i:]==l[-i*2:-i],range(len(l))))):
 for _ in[0]*n:s+=[r(s+[0])>r(s+[1])]
 return-~s[n]
</code>```

This solution is using 0-based indexing.

Title: Generate Linus Sequence

Body:
Python, 137 bytes

def a(n,s=[0],r=lambda l:max([0]+filter(lambda i:l[-i:]==l[-i*2:-i],range(len(l))))):
 for _ in[0]*n:s+=[r(s+[0])>r(s+[1])]
 return-~s[n]

This solution is using 0-based indexing.


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

```

答:
MemeGolf, 570 bytes

Yet another strange esolang from me

```<code>jQuery.Outgolf Dennis by 72 bytes.
jQuery.44
jQuery.Outgolf Dennis by 29 bytes.
jQuery.44
jQuery.Outgolf Dennis by 7 bytes.
jQuery.44
jQuery.44
jQuery.Outgolf Dennis by 3 bytes.
jQuery.44
jQuery.Juice avocado for 67 minutes.
jQuery.44
jQuery.Juice avocado for 12 minutes.
jQuery.44
jQuery.Outgolf Dennis by 55 bytes.
jQuery.44
jQuery.Outgolf Dennis by 24 bytes.
jQuery.44
jQuery.Outgolf Dennis by 3 bytes.
jQuery.44
jQuery.Juice avocado for 6 minutes.
jQuery.44
jQuery.Juice avocado for 8 minutes.
jQuery.44
jQuery.Juice avocado for 67 minutes.
jQuery.44
jQuery.HE COMES
</code>```

Outgolf Dennis by n bytes. add n to the accumulator, Juice avocado for n minutes. substract n from the accumulator, 44 print the value of the accumulator as a character and HE COMES terminate the program.

Title: "Hello, World!"

Body:
MemeGolf, 570 bytes

Yet another strange esolang from me

jQuery.Outgolf Dennis by 72 bytes.
jQuery.44
jQuery.Outgolf Dennis by 29 bytes.
jQuery.44
jQuery.Outgolf Dennis by 7 bytes.
jQuery.44
jQuery.44
jQuery.Outgolf Dennis by 3 bytes.
jQuery.44
jQuery.Juice avocado for 67 minutes.
jQuery.44
jQuery.Juice avocado for 12 minutes.
jQuery.44
jQuery.Outgolf Dennis by 55 bytes.
jQuery.44
jQuery.Outgolf Dennis by 24 bytes.
jQuery.44
jQuery.Outgolf Dennis by 3 bytes.
jQuery.44
jQuery.Juice avocado for 6 minutes.
jQuery.44
jQuery.Juice avocado for 8 minutes.
jQuery.44
jQuery.Juice avocado for 67 minutes.
jQuery.44
jQuery.HE COMES

Outgolf Dennis by n bytes. add n to the accumulator, Juice avocado for n minutes. substract n from the accumulator, 44 print the value of the accumulator as a character and HE COMES terminate the program.


答:
ListSharp, 37 bytes

```<code>OUTP="Hello World" HERE[<here>+"\\a"]
</code>```

simply writes Hello World to a file called "a"(not even a text file) in the script execution environment,

Title: Create and write to a file

Body:
ListSharp, 37 bytes

OUTP="Hello World" HERE[<here>+"\\a"]

simply writes Hello World to a file called "a"(not even a text file) in the script execution environment,


答:
Node.js, 42 bytes

```<code>require("fs").writeFile('o','Hello World')
</code>```

i don't think this needs explanation

Node.js REPL, 31 bytes

```<code>fs.writeFile('o','Hello World')
</code>```

for some reason in repl you dont need to include fs

Title: Create and write to a file

Body:
Node.js, 42 bytes

require("fs").writeFile('o','Hello World')

i don't think this needs explanation

Node.js REPL, 31 bytes

fs.writeFile('o','Hello World')

for some reason in repl you dont need to include fs


问:
Compounding english
A compound word is a word that contains 2 or more words in it.  We can do better than that, though.  We need you to create 1 (nonsensical) word that contains every word.

However, we want this word to be as short as possible.  We can use overlapping letters to achieve this.

For example, if your word list was ["cat", "atom", "a"], you would want to return "catom".

Input/Output

Your program will need to take a list of words as input, and return a compound word as output.

The word list you will be using is the top 10000 words in English, according to Google  (If this list turns out to be too easy, I may change it to a longer one).   For reference, simply appending each word gives you a score of 65888.

Your score is the number of letters in your final word, lower is better.  Tie breaker goes to the first poster.

答:
Java 8, ~5 Minutes, Length of 39,279

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

public class Words {

    public static void main(String[] args) throws Throwable {
        File file = new File("words.txt");
        List<String> wordsList = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        while ((line = reader.readLine()) != null) {
            wordsList.add(line);
        }
        reader.close();

        Set<String> words = new HashSet<>();

        System.out.println("Finished I/O");

        for (int i = 0; i < wordsList.size(); i++) { //Step 1: remove any words that occur in other words
            boolean in = false;
            for (int j = 0; j < wordsList.size(); j++) {
                if (i != j && wordsList.get(j).contains(wordsList.get(i))) {
                    in = true;
                    break;
                }
            }
            if (!in) {
                words.add(wordsList.get(i));
            }
        }

        System.out.println("Removed direct containers");

        List<String> working = words.stream().sorted((c, b) -> Integer.compare(c.length(), b.length())).collect(Collectors.toList()); //Sort by length, shortest first
        StringBuilder result = new StringBuilder();
        result.append(working.get(0));
        while (!working.isEmpty()) {
            Optional<String> target = working.stream().sorted((c, b) -> Integer.compare(firstLastCommonality(result.toString(), b), firstLastCommonality(result.toString(), c))).findFirst(); //Find the string that has the greatest in common with the end of 'result'
            if(target.isPresent()) { //It really should be present, but just in case
                String s = target.get();
                working.remove(s);
                int commonality = firstLastCommonality(result.toString(), s);
                s = s.substring(commonality);
                result.append(s);
            }
        }

        System.out.println("Finished algorithm");

        String r = result.toString();
        System.out.println("The string: \n" + r);
        System.out.println("Length: \n" + r.length());
        System.out.println("Verified: \n" + !wordsList.stream().filter(s -> !r.contains(s)).findFirst().isPresent());
    }

    private static int firstLastCommonality(String a, String b) {
        int count = 0;
        int len = b.length();
        while (!a.endsWith(b) && !b.equals("")) {
            b = cutLastChar(b);
            count++;
        }
        return len - count;
    }

    private static String cutLastChar(String string) {
        if (string.length() - 1 < 0) {
            return string;
        } else {
            return string.substring(0, string.length() - 1);
        }
    }

}
```

<h3>Input:</h3>

<ul>
<li>a file called 'words.txt' in the working directory, in the exact same format as the file in the main post</li>
</ul>

<h3>Output:</h3>

```Finished I/O
Removed direct containers
Finished algorithm
The string:
[Moved to pastebin](http://pastebin.com/iygyR3zL)
Length:
39279
Verified:
true
```

Title: Compounding english

Body:
Java 8, ~5 Minutes, Length of 39,279

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

public class Words {

    public static void main(String[] args) throws Throwable {
        File file = new File("words.txt");
        List<String> wordsList = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new FileReader(file));
        String line;
        while ((line = reader.readLine()) != null) {
            wordsList.add(line);
        }
        reader.close();

        Set<String> words = new HashSet<>();

        System.out.println("Finished I/O");

        for (int i = 0; i < wordsList.size(); i++) { //Step 1: remove any words that occur in other words
            boolean in = false;
            for (int j = 0; j < wordsList.size(); j++) {
                if (i != j && wordsList.get(j).contains(wordsList.get(i))) {
                    in = true;
                    break;
                }
            }
            if (!in) {
                words.add(wordsList.get(i));
            }
        }

        System.out.println("Removed direct containers");

        List<String> working = words.stream().sorted((c, b) -> Integer.compare(c.length(), b.length())).collect(Collectors.toList()); //Sort by length, shortest first
        StringBuilder result = new StringBuilder();
        result.append(working.get(0));
        while (!working.isEmpty()) {
            Optional<String> target = working.stream().sorted((c, b) -> Integer.compare(firstLastCommonality(result.toString(), b), firstLastCommonality(result.toString(), c))).findFirst(); //Find the string that has the greatest in common with the end of 'result'
            if(target.isPresent()) { //It really should be present, but just in case
                String s = target.get();
                working.remove(s);
                int commonality = firstLastCommonality(result.toString(), s);
                s = s.substring(commonality);
                result.append(s);
            }
        }

        System.out.println("Finished algorithm");

        String r = result.toString();
        System.out.println("The string: \n" + r);
        System.out.println("Length: \n" + r.length());
        System.out.println("Verified: \n" + !wordsList.stream().filter(s -> !r.contains(s)).findFirst().isPresent());
    }

    private static int firstLastCommonality(String a, String b) {
        int count = 0;
        int len = b.length();
        while (!a.endsWith(b) && !b.equals("")) {
            b = cutLastChar(b);
            count++;
        }
        return len - count;
    }

    private static String cutLastChar(String string) {
        if (string.length() - 1 < 0) {
            return string;
        } else {
            return string.substring(0, string.length() - 1);
        }
    }

}

Input:

a file called 'words.txt' in the working directory, in the exact same format as the file in the main post

Output:

Finished I/O
Removed direct containers
Finished algorithm
The string:
[Moved to pastebin](http://pastebin.com/iygyR3zL)
Length:
39279
Verified:
true


问:
Draw a Fibonacci Network!

What are Fibonacci networks?

In 1202, an Italian mathematician known as Fibonacci posed the following problem:

"A male and a female rabbit are born at the beginning of the year. We assume the following conditions:

1.After reaching the age of two months, each pair produces a mixed pair, (one male, one female), and then another mixed pair each month thereafter.

2.No deaths occur during the year."

How many rabbits will there be at the end of the year?

Sources for graph and problem statement

Challenge

Your challenge is to write a program/function to draw an ASCII art to output or a text file, or a graphical picture to a file/screen of a graph with following settings:

At 0th tick, there is one newly-born node.

Every newly born node creates a normal node after one tick after being born and gets deactivated.

A normal node creates a normal node and a newly-born node one tick after its birth and gets deactivated.

Your program will get the non-negative value n as input, and will draw the graph at the nth tick. Note that your program can draw newly-born nodes and normal nodes differently, but this is not necessary.

Rules

You must not use any built-in Fibonacci sequence function or mathematical constants or similar.

If your program outputs to a file, it must be either a text file in a suitable and viewable format and encoding, or an image file in a suitable and viewable format with recognizable colors (for example, an image format that can be uploaded to SE).

Your program can draw graph in any size, any shape and any alignment but the nodes and connections must be recognizable. Tree-shaped graphs (like the graph in "What are Fibonacci networks?" section) are recommended, but not necessary.

Common code golf rules apply to this challenge.

Examples

```<code>Input: 2
Possible Output:
*
|
*
| \
* *

Input: 0
Possible Output:
*
</code>```

Input: 5

Possible Graphical Output:

This is a codegolf. Shortest code wins. Good luck!

答:
HTML5/JavaScript, 1262 bytes

This is my code which displays a Fibonacci network. You can just paste it into a file with a name like index.html and run it in your favourite browser (I only tested Chrome and Firefox though). When you launch it, it asks you for the desired number of generations. It uses the HTML5 <canvas> tag to display the image.

```<code><script>let t,p,o,c=[],q=50,r=20,s=25;function d(o){return JSON.parse(JSON.stringify(o));}function e(a,x,y){o.beginPath();o.fillStyle=a?"red":"#000";o.arc(x*q+s,y*q+s,r,0,2*3.14159);o.fill();}function f(a,b,c,d){o.beginPath();o.strokeStyle="blue";o.lineWidth=3;o.moveTo(a*q+s,b*q+s);o.lineTo(c*q+s,d*q+s);o.stroke();}function g(i){return c[i].a+c[i].c;}function h(i){return c[i].b+c[i].d;}function k(j,e,f,b,n,x,y,z){f=j;b=0;while(1){if(!e){f.t=g(t);f.u=0;f.v=f.t;f.w=f.b;}else{n=t-b+1;x=t-b;z=e.b%2?(g(n)+g(x)+1):(-(g(n)+h(x)+1));f.t=e.v+z;f.u=e.w+1;f.v=f.t;f.w=f.u+f.b;}if(!f.a)break;b+=f.b+1;e=f;f=f.z;}return {a:f.b==0,x:f.v,y:f.w};}function l(j,c,b){b=k(j);f(b.x,b.y,c.x,c.y);e(b.a,b.x,b.y);return b;}function m(j){while(j.a)j=j.z;return j;}function n(j,o,p,q,r,s){if(o>t)return;q=l(j,p);r=d(j);m(r).b++;n(r,o+1,q);if(m(j).b>0){r=d(j);s=m(r);s.a=!0;s.z={a:!1,b:0};n(r,o+1,q);}}function b(i,z,y){t=parseInt(prompt());if(isNaN(t)||t<0)t=0;p=document.getElementById("o");c.push({a:0,b:0,c:0,d:0,e:1});for(i=1;i<t+1;i++){z=c[c.length-1];y={a:(i>1?i%2:0)+z.c,b:(i>1?1-i%2:0)+z.d,c:z.a+z.c,d:z.b+z.d};y.e=y.a+y.b+y.c+y.d;c.push(y);}p.width=q*(c[c.length-1].e+1);p.height=q*(t+1);o=p.getContext("2d");n({a:!1,b:0},0,0);}</script><body onload="b()"><canvas id="o">
</code>```

An example for 6 generations would be this one:

As you can see, newly born nodes are colored in red, the others are black.

For reference, this is my ungolfed, development code that does exactly the same:

  <meta charset="utf-8">
  <title>Fibonacci Graph</title>

  <canvas id="output" style="position:absolute; top:10px; left:10px" width="1200" height="600">Canvas not supported...</canvas>

```

Title: Draw a Fibonacci Network!

Body:
HTML5/JavaScript, 1262 bytes

This is my code which displays a Fibonacci network. You can just paste it into a file with a name like index.html and run it in your favourite browser (I only tested Chrome and Firefox though). When you launch it, it asks you for the desired number of generations. It uses the HTML5 <canvas> tag to display the image.

<script>let t,p,o,c=[],q=50,r=20,s=25;function d(o){return JSON.parse(JSON.stringify(o));}function e(a,x,y){o.beginPath();o.fillStyle=a?"red":"#000";o.arc(x*q+s,y*q+s,r,0,2*3.14159);o.fill();}function f(a,b,c,d){o.beginPath();o.strokeStyle="blue";o.lineWidth=3;o.moveTo(a*q+s,b*q+s);o.lineTo(c*q+s,d*q+s);o.stroke();}function g(i){return c[i].a+c[i].c;}function h(i){return c[i].b+c[i].d;}function k(j,e,f,b,n,x,y,z){f=j;b=0;while(1){if(!e){f.t=g(t);f.u=0;f.v=f.t;f.w=f.b;}else{n=t-b+1;x=t-b;z=e.b%2?(g(n)+g(x)+1):(-(g(n)+h(x)+1));f.t=e.v+z;f.u=e.w+1;f.v=f.t;f.w=f.u+f.b;}if(!f.a)break;b+=f.b+1;e=f;f=f.z;}return {a:f.b==0,x:f.v,y:f.w};}function l(j,c,b){b=k(j);f(b.x,b.y,c.x,c.y);e(b.a,b.x,b.y);return b;}function m(j){while(j.a)j=j.z;return j;}function n(j,o,p,q,r,s){if(o>t)return;q=l(j,p);r=d(j);m(r).b++;n(r,o+1,q);if(m(j).b>0){r=d(j);s=m(r);s.a=!0;s.z={a:!1,b:0};n(r,o+1,q);}}function b(i,z,y){t=parseInt(prompt());if(isNaN(t)||t<0)t=0;p=document.getElementById("o");c.push({a:0,b:0,c:0,d:0,e:1});for(i=1;i<t+1;i++){z=c[c.length-1];y={a:(i>1?i%2:0)+z.c,b:(i>1?1-i%2:0)+z.d,c:z.a+z.c,d:z.b+z.d};y.e=y.a+y.b+y.c+y.d;c.push(y);}p.width=q*(c[c.length-1].e+1);p.height=q*(t+1);o=p.getContext("2d");n({a:!1,b:0},0,0);}</script><body onload="b()"><canvas id="o">

An example for 6 generations would be this one:

As you can see, newly born nodes are colored in red, the others are black.

For reference, this is my ungolfed, development code that does exactly the same:

<html>
 <head>
  <meta charset="utf-8">
  <title>Fibonacci Graph</title>
  <script type="text/javascript">
   let totalGenerations;
   let canvas, ctx;
   let individualCount = [];
   let individualDrawSize = 50, individualDrawRadius = 20, individualDrawOffset = 25;

   function generateIndividualCount()
   {
    individualCount.push(
    {
     babiesL: 0,   //number of babies on the left side of the main individual
     babiesR: 0,
     adultsL: 0,
     adultsR: 0,
     total: 1   //total number of individuals (sum of all other members+1, because the main individual counts as well)
    });

    for(let i=1; i<totalGenerations+1; i++)
    {
     let last = individualCount[individualCount.length - 1];
     let next =
     {
      //make an adult alternate between having a baby at the left and the right side (right side first)
      babiesL: (i>1 ? i%2 : 0) + last.adultsL,
      babiesR: (i>1 ? 1-i%2 : 0) + last.adultsR,
      adultsL: last.babiesL + last.adultsL,
      adultsR: last.babiesR + last.adultsR
     };
     next.total = next.babiesL + next.babiesR + next.adultsL + next.adultsR;
     individualCount.push(next);
    }
   }

   function setupContext()
   {
    canvas.width = individualDrawSize * (individualCount[individualCount.length - 1].total + 1);
    canvas.height = individualDrawSize * (totalGenerations + 1);
    ctx = canvas.getContext("2d");
   }

   function deepCopy(obj)
   {
    return JSON.parse(JSON.stringify(obj));
   }

   function drawIndividual(isBaby, x, y)
   {
    ctx.beginPath();
    ctx.fillStyle = isBaby ? "red" : "black";
    ctx.arc(x*individualDrawSize + individualDrawOffset, y*individualDrawSize + individualDrawOffset, individualDrawRadius, 0, 2*Math.PI);
    ctx.fill();
   }

   function drawLine(x1, y1, x2, y2)
   {
    ctx.beginPath();
    ctx.strokeStyle = "blue";
    ctx.lineWidth = 3;
    ctx.moveTo(x1*individualDrawSize + individualDrawOffset, y1*individualDrawSize + individualDrawOffset);
    ctx.lineTo(x2*individualDrawSize + individualDrawOffset, y2*individualDrawSize + individualDrawOffset);
    ctx.stroke();
   }

   function getIndividualCountLeft(i)  //left like in "the opposite of right"
   {
    return individualCount[i].babiesL + individualCount[i].adultsL;
   }

   function getIndividualCountRight(i)
   {
    return individualCount[i].babiesR + individualCount[i].adultsR;
   }

   function getPosition(ancestorInformation)
   {
    let prevInfo;
    let tempInfo = ancestorInformation;
    let currDepth = 0;

    while(1)
    {
     if(prevInfo == undefined)
     {
      tempInfo.birthX = getIndividualCountLeft(totalGenerations);
      tempInfo.birthY = 0;

      tempInfo.givingBirthX = tempInfo.birthX;
      tempInfo.givingBirthY = tempInfo.ageAtGivingBirth;
     }
     else
     {
      let generationsLeftForParent = totalGenerations - (currDepth-1);
      let generationsLeftForChild = totalGenerations - currDepth;    //left like in "to go" or "There are 42 cookies left"
      let isLeftBranch = (prevInfo.ageAtGivingBirth % 2 == 0);
      let distanceToParent;

      if(isLeftBranch)
       distanceToParent = -(getIndividualCountLeft(generationsLeftForParent) + getIndividualCountRight(generationsLeftForChild) + 1);
      else
       //some of these directions may seem odd, but because the parent subtree begins with a left branch (and individualCount only contains data for trees beginning with a right branch), it needs to be inversed
       //if individualCount would have been generated for trees beginning with a left node, all of the getIndividualCountLeft/getIndividualCountRight function would need to be inversed
       //or, when individualCount would have been generated for both cases, functions like getIndividualCountRight_LeftBegin and getIndividualCountLeft_RightBegin could be used
       distanceToParent = getIndividualCountLeft(generationsLeftForParent) + getIndividualCountLeft(generationsLeftForChild) + 1;  //+1, because the previous value of distanceToParent is just the number of empty fields (on the x axis) between the parent and the child

      tempInfo.birthX = prevInfo.givingBirthX + distanceToParent;
      tempInfo.birthY = prevInfo.givingBirthY + 1;

      tempInfo.givingBirthX = tempInfo.birthX;
      tempInfo.givingBirthY = tempInfo.birthY + tempInfo.ageAtGivingBirth;
     }
     if(!tempInfo.isParent)
      break;
     currDepth += tempInfo.ageAtGivingBirth + 1;
     prevInfo = tempInfo;
     tempInfo = tempInfo.child;
    }

    return { isBaby: tempInfo.ageAtGivingBirth==0, x: tempInfo.givingBirthX, y: tempInfo.givingBirthY };
   }

   function draw(ancestorInformation, parentPos)
   {
    let pos = getPosition(ancestorInformation);
    drawLine(pos.x, pos.y, parentPos.x, parentPos.y);
    drawIndividual(pos.isBaby, pos.x, pos.y);
    return pos;
   }

   function getDeepestChild(ancestorInformation)
   {
    while(ancestorInformation.isParent)
     ancestorInformation = ancestorInformation.child;
    return ancestorInformation;
   }

   function drawAll(ancestorInformation, depth, parentPos)
   {
    if(depth > totalGenerations)
     return;

    let pos = draw(ancestorInformation, parentPos);
    let newAncestorInformation = deepCopy(ancestorInformation);
    getDeepestChild(newAncestorInformation).ageAtGivingBirth++;
    drawAll(newAncestorInformation, depth + 1, pos);

    if(getDeepestChild(ancestorInformation).ageAtGivingBirth > 0)
    {
     newAncestorInformation = deepCopy(ancestorInformation);
     let deepestChild = getDeepestChild(newAncestorInformation);
     deepestChild.isParent = true;
     deepestChild.child = { isParent: false, ageAtGivingBirth: 0 };
     drawAll(newAncestorInformation, depth + 1, pos);
    }
   }

   function load()
   {
    totalGenerations = parseInt(prompt("Number of generations?"));
    if(isNaN(totalGenerations)  ||  totalGenerations < 0)
     totalGenerations = 0;
    canvas = document.getElementById("output");
    generateIndividualCount();
    setupContext();
    drawAll({ isParent: false, ageAtGivingBirth: 0 }, 0, 0);     //although this individual does not really give birth after it has been born, it still has an attribute called "ageAtGivingBirth" (like its parents) to achieve a similar effect
   }
  </script>
 </head>
 <body onload="load()">
  <canvas id="output" style="position:absolute; top:10px; left:10px" width="1200" height="600">Canvas not supported...</canvas>
 </body>
</html>


问:
Create a simple 2048 game clone
2048 is an incredibly fun and addictive game in which the goal is to create a tile with 2048 on it.

Here's a short description of the game:

Pressing an arrow key will slide all the blocks in the stage in that direction. For example, if x represents a block, and you pressed the up arrow in this case:

```<code>...x
.x..
..x.
xx..
</code>```

Then the board would become

```<code>xxxx
.x..
....
....
</code>```

Furthermore, the blocks are numbered, starting at 2. If two of the same numbered blocks are moved together, they will merge into the next number. For example, pressing "up" on this board:

```<code>.2..
..22
.2..
....
</code>```

Would create this:

```<code>.422
....
....
....
</code>```

And then after pressing "right," it would become ..44, and therefore pressing right again would create an "8" block, and so on.

Each turn, a new "2" block is created on a random open square. (It's actually not always a "2," but for simplicity let's keep it at that.) If there are no possible moves left (i.e., the board is full and you can't merge anything), the game is lost, and if a 2048 block is created, you win!

Your challenge is to recreate this game, golfed!

For edge-cases, such as pressing "right" on this board:

```<code>....
.222
....
....
</code>```

you must merge the tiles closest to the edge of the arrow key pressed. For example, this would become ..24, because the second and third "2"s are the closest to the right edge.

If the player presses an invalid move (such as "up" on a board like 2.2. / .... / .... / ....), you must ignore the move.

Moves can be accepted in any way, such as clicking, arrow keys, ULRD, etc.

The tiles must all be the same shape—a "1024" tile should be the same size as a "2" tile.

The tiles must be separated in some way. For example, |1024|   2|1024|1024| is a valid example of a row (assuming that the tiles are squares), while 1024   210241024 is not.

You must output "you win" if the player creates a 2048 tile, or "you lose" if there are no valid moves left.

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

答:
APL (Dyalog APL), <s>153</s> <s>150</s> <s>167</s> <s>156</s> <s>155</s> 151 bytes

'you ',{2048∊⍵:'win'
(z/∊n)[?+/z←0=∊n←⍵]←2
⎕←4↑¨⍕¨n
1∊(⍉2=⌿n),(2=/n),0=n:∇{⍵≡r←R⍣¯1⎕UCS{4↑⍺⍺t⎕R(1⌽∪¨t←2/¨⍺⍺2*⍳16)⍺⍺⍵~0}¨(R←↓⍉∘⌽⍣⎕)⍵:∇⍵⋄r}n
'lose'}4 4⍴0
```

<p>Prompts for move; 0=Left, 1=Up 2=Right, 3=Down</p>

<p>Try it online!</p>

<h3>Ungolfed, with whitespace</h3>

<pre class="lang-apl prettyprint-override"><code>C ← ⎕UCS
'you ', {
    2048 ∊ ⍵: 'win'
    n ← ⍵
    z ← 0 = ∊n
    (z / ∊n)[? +/z] ← 2
    ⎕ ← 4 ↑¨ ⍕¨n
    1 ∊ (⍉ 2 =⌿ n) , (2 =/ n) , 0 = n: ∇ {
        R←↓⍉∘⌽⍣⎕
        r ← R⍣¯1 ⎕UCS {
            t ← 2 /¨ ⍺⍺ 2 * ⍳16
            4 ↑ ⍺⍺ t ⎕R (1 ⌽ ∪¨t) ⍺⍺ ⍵ ~ 0
        }¨ R ⍵
        ⍵ ≡ r: ∇ ⍵
        r
    } n
    'lose'
} 4 4⍴0
</code>```

Explanation

Blank lines indicate a newline, while blocks of lines belong on a single line

'you ', "you" prepended to the result of the function {...

2048 ∊ ⍵: 'win' if the argument (the board) contains 2048, then return "win"

n ← ⍵ assign the right argument to n (so it may be modified in-place)

z ← 0 = ∊n z gets the Boolean list where flattened z is 0

(z / ∊n) z filters the flattened n (to get only the zeros)

    [? +/z] use a random number between 1 and the count of zeros (the sum of the Boolean z) to select which zero-containing position

    ← 2 gets a 2

⎕ ← output the

    4 ↑¨ each extended-to-length-4 (with spaces)

    ⍕¨n string representation of each number

1 ∊ if any of the following are found;

    (⍉2=⌿n) pairwise vertical equalities (transposed to be concatenable)

    , or (concatenated to)

    (2=/n) pairwise horizontal equalities

    , or (concatenated to)

    0=n zeros

    : then:

    ∇ call this function on the result of the function {...

R ← R (for Rows of Rotated) is

      ↓ the split-into-rows

      ⍉∘⌽⍣⎕ prompt for numeric input, then rotate (literally mirror horizontally, then transpose) the argument (the board) –90° times the inputted number

r ← r (for result) gets

      R⍣¯1 the inverse of R (rotate back, then merge rows into matrix) applied to the result of the function ⎕UCS{... (where ⍺⍺ means convert to/from UCS points)

t ← t gets

        2 /¨ two of each of

        ⍺⍺ the characters corresponding to the code points

        2 * ⍳16 2¹, 2², 2³,... 2¹⁶

4↑ pad with zeros on the right until length 4

        C convert the following UCS characters to code points

        t ⎕R (1 ⌽ ∪¨t) regex replace each pair t with the unique characters from the next t on the right

        C ⍵~0 the argument (board) without zeros (compacted to the left), then converted to UCS code points

}¨ [end of function] applied to each of

      R ⍵ R applied to the argument (the board)

⍵ ≡ r: if the argument (the old board state) is identical to r (new board state), then:

      ∇⍵ call this function on the unmodified argument (because the user made an invalid move), else

r return r (the new board state)

} n [end of function] applied to n (the new board state), else

'lose' return "lose"

} 4 4 ⍴ 0 [end of function] applied to a 4-by-4 table of zeros (the initial state)

Title: Create a simple 2048 game clone

Body:
APL (Dyalog APL), <s>153</s> <s>150</s> <s>167</s> <s>156</s> <s>155</s> 151 bytes

'you ',{2048∊⍵:'win'
(z/∊n)[?+/z←0=∊n←⍵]←2
⎕←4↑¨⍕¨n
1∊(⍉2=⌿n),(2=/n),0=n:∇{⍵≡r←R⍣¯1⎕UCS{4↑⍺⍺t⎕R(1⌽∪¨t←2/¨⍺⍺2*⍳16)⍺⍺⍵~0}¨(R←↓⍉∘⌽⍣⎕)⍵:∇⍵⋄r}n
'lose'}4 4⍴0

Prompts for move; 0=Left, 1=Up 2=Right, 3=Down

Try it online!

Ungolfed, with whitespace

C ← ⎕UCS
'you ', {
    2048 ∊ ⍵: 'win'
    n ← ⍵
    z ← 0 = ∊n
    (z / ∊n)[? +/z] ← 2
    ⎕ ← 4 ↑¨ ⍕¨n
    1 ∊ (⍉ 2 =⌿ n) , (2 =/ n) , 0 = n: ∇ {
        R←↓⍉∘⌽⍣⎕
        r ← R⍣¯1 ⎕UCS {
            t ← 2 /¨ ⍺⍺ 2 * ⍳16
            4 ↑ ⍺⍺ t ⎕R (1 ⌽ ∪¨t) ⍺⍺ ⍵ ~ 0
        }¨ R ⍵
        ⍵ ≡ r: ∇ ⍵
        r
    } n
    'lose'
} 4 4⍴0

Explanation

Blank lines indicate a newline, while blocks of lines belong on a single line

'you ', "you" prepended to the result of the function {...

2048 ∊ ⍵: 'win' if the argument (the board) contains 2048, then return "win"

n ← ⍵ assign the right argument to n (so it may be modified in-place)

z ← 0 = ∊n z gets the Boolean list where flattened z is 0

(z / ∊n) z filters the flattened n (to get only the zeros)

    [? +/z] use a random number between 1 and the count of zeros (the sum of the Boolean z) to select which zero-containing position

    ← 2 gets a 2

⎕ ← output the

    4 ↑¨ each extended-to-length-4 (with spaces)

    ⍕¨n string representation of each number

1 ∊ if any of the following are found;

    (⍉2=⌿n) pairwise vertical equalities (transposed to be concatenable)

    , or (concatenated to)

    (2=/n) pairwise horizontal equalities

    , or (concatenated to)

    0=n zeros

    : then:

    ∇ call this function on the result of the function {...

R ← R (for Rows of Rotated) is

      ↓ the split-into-rows

      ⍉∘⌽⍣⎕ prompt for numeric input, then rotate (literally mirror horizontally, then transpose) the argument (the board) –90° times the inputted number

r ← r (for result) gets

      R⍣¯1 the inverse of R (rotate back, then merge rows into matrix) applied to the result of the function ⎕UCS{... (where ⍺⍺ means convert to/from UCS points)

t ← t gets

        2 /¨ two of each of

        ⍺⍺ the characters corresponding to the code points

        2 * ⍳16 2¹, 2², 2³,... 2¹⁶

4↑ pad with zeros on the right until length 4

        C convert the following UCS characters to code points

        t ⎕R (1 ⌽ ∪¨t) regex replace each pair t with the unique characters from the next t on the right

        C ⍵~0 the argument (board) without zeros (compacted to the left), then converted to UCS code points

}¨ [end of function] applied to each of

      R ⍵ R applied to the argument (the board)

⍵ ≡ r: if the argument (the old board state) is identical to r (new board state), then:

      ∇⍵ call this function on the unmodified argument (because the user made an invalid move), else

r return r (the new board state)

} n [end of function] applied to n (the new board state), else

'lose' return "lose"

} 4 4 ⍴ 0 [end of function] applied to a 4-by-4 table of zeros (the initial state)


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

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

Requirements:

Does not use any kind of "eval" functions

Can handle floating point and negative numbers

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

Supports brackets and parenthesis for overriding the normal order

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

Evaluates the input using the standard order of operations

Test Cases

Input

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

Output

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

Input

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

Output

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

Input

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

Output

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

答:
Postscript, <s>1000</s> <s>695</s> <s>665</s> 494

Stole ideas from ThomasW. Added feature: accepts strings with or without spaces around operators.[feature removed]

Using ARGUMENTS is shorter than %stdin, and easier to test, to boot!

Simplified the substitution to just replace brackets with parens.

```<code>575(1)10:36 PM:ps 0> gsnd -q -- calc2bg.ps '10 - 3 + 2'
9
576(1)10:37 PM:ps 0> gsnd -q -- calc2bg.ps '8 + 6 / 3 - 7 + -5 / 2.5'
1.0
577(1)10:37 PM:ps 0> gsnd -q -- calc2bg.ps '4 + [ ( -3 + 5 ) * 3.5 ] ^ 2 - 12'
41.0
</code>```

Code:

```<code>/T[/^[/C{exp}/P 4/X{le}>>/*[/C{mul}/P 3/X{lt}>>/[/C{div}/P
3/X{lt}>>/+[/C{add}/P 2/X{lt}>>/-[/C{sub}/P
2/X{lt}>>>>def[/integertype{}/realtype{}/stringtype{V}/nametype{cvlit/N
exch store{P T N get dup/P get exch/X get exec{exit}if C end}loop T N get
begin}91 40 93 41>>begin/V{0 1 2 index length 1 sub{2 copy get
dup where{exch get}if 3 copy put pop pop}for[/N 0/R 0/P 0/C{}>>begin{token
not{exit}if exch/R exch store dup type exec R}loop{P 0 eq{end exit}if C
end}loop}def ARGUMENTS{V ==}forall
</code>```

Ungolfed and commented:

```<code>%!
%Shunting-Yard Algorithm using dictstack for operators
%invoke with %gsnd -q -- calc2bg.ps [ 'expr1' ]*

%The operator table. C:code P:precedence X:test(implements associativity)
/T[
    /^[/C{exp}/P 4/X{le}>>
    /*[/C{mul}/P 3/X{lt}>>
    /[/C{div}/P 3/X{lt}>>
    /+[/C{add}/P 2/X{lt}>>
    /-[/C{sub}/P 2/X{lt}>>
>>def

%The type-dispatch dictionary
%numbers: do nothing
%string: recurse
%name: process op
[%/integertype{}/realtype{} %now uses `where` below
/stringtype{V}/nametype{
pstack()=
    cvlit/N exch store %stash cur-op
    {
        P %prec(tos)
        T N get %prec(tos) cur-op-dict
        dup/P get %prec(tos) cur-op-dict prec(cur-op)
        exch/X get %prec(tos) prec(cur-op) test(cur-op)
        exec{exit}if %exit if prec(tos) < || <= prec(cur-op)
/C load ==
        C %pop-and-apply
        end
pstack()=
    } loop
    T N get begin %push cur-op
}>>begin

%substitutions
[91 40 93 41>>begin %replace brackets with parens
/V {
    %pre-process
    0 1 2 index length 1 sub {
        2 copy get
        dup where { exch get } if
        3 copy put pop pop
    } for
dup ==

    [/N 0/R 0/P 0/C{}>>begin %dummy base operator and storage
    { token not{exit}if exch /R exch store %extract token, stash Remainder
pstack(>)=
        %dispatch type procedure
        dup type dup where { pop exec }{ pop } ifelse
    R }loop
pstack()=
    {
        P 0 eq{end exit}if %hit dummy op: exit
/C load ==
        C end %pop and apply
    } loop
} def

ARGUMENTS{V ==}forall %iterate through the command-line arguments
</code>```

ContentLicense: CC BY-SA 2.5

Title: Advanced Calculator

Body:
Postscript, <s>1000</s> <s>695</s> <s>665</s> 494

Stole ideas from ThomasW. Added feature: accepts strings with or without spaces around operators.[feature removed]

Using ARGUMENTS is shorter than %stdin, and easier to test, to boot!

Simplified the substitution to just replace brackets with parens.

575(1)10:36 PM:ps 0> gsnd -q -- calc2bg.ps '10 - 3 + 2'
9
576(1)10:37 PM:ps 0> gsnd -q -- calc2bg.ps '8 + 6 / 3 - 7 + -5 / 2.5'
1.0
577(1)10:37 PM:ps 0> gsnd -q -- calc2bg.ps '4 + [ ( -3 + 5 ) * 3.5 ] ^ 2 - 12'
41.0

Code:

/T[/^[/C{exp}/P 4/X{le}>>/*[/C{mul}/P 3/X{lt}>>/[/C{div}/P
3/X{lt}>>/+[/C{add}/P 2/X{lt}>>/-[/C{sub}/P
2/X{lt}>>>>def[/integertype{}/realtype{}/stringtype{V}/nametype{cvlit/N
exch store{P T N get dup/P get exch/X get exec{exit}if C end}loop T N get
begin}91 40 93 41>>begin/V{0 1 2 index length 1 sub{2 copy get
dup where{exch get}if 3 copy put pop pop}for[/N 0/R 0/P 0/C{}>>begin{token
not{exit}if exch/R exch store dup type exec R}loop{P 0 eq{end exit}if C
end}loop}def ARGUMENTS{V ==}forall

Ungolfed and commented:

%!
%Shunting-Yard Algorithm using dictstack for operators
%invoke with %gsnd -q -- calc2bg.ps [ 'expr1' ]*

%The operator table. C:code P:precedence X:test(implements associativity)
/T[
    /^[/C{exp}/P 4/X{le}>>
    /*[/C{mul}/P 3/X{lt}>>
    /[/C{div}/P 3/X{lt}>>
    /+[/C{add}/P 2/X{lt}>>
    /-[/C{sub}/P 2/X{lt}>>
>>def

%The type-dispatch dictionary
%numbers: do nothing
%string: recurse
%name: process op
[%/integertype{}/realtype{} %now uses `where` below
/stringtype{V}/nametype{
pstack()=
    cvlit/N exch store %stash cur-op
    {
        P %prec(tos)
        T N get %prec(tos) cur-op-dict
        dup/P get %prec(tos) cur-op-dict prec(cur-op)
        exch/X get %prec(tos) prec(cur-op) test(cur-op)
        exec{exit}if %exit if prec(tos) < || <= prec(cur-op)
/C load ==
        C %pop-and-apply
        end
pstack()=
    } loop
    T N get begin %push cur-op
}>>begin

%substitutions
[91 40 93 41>>begin %replace brackets with parens
/V {
    %pre-process
    0 1 2 index length 1 sub {
        2 copy get
        dup where { exch get } if
        3 copy put pop pop
    } for
dup ==

    [/N 0/R 0/P 0/C{}>>begin %dummy base operator and storage
    { token not{exit}if exch /R exch store %extract token, stash Remainder
pstack(>)=
        %dispatch type procedure
        dup type dup where { pop exec }{ pop } ifelse
    R }loop
pstack()=
    {
        P 0 eq{end exit}if %hit dummy op: exit
/C load ==
        C end %pop and apply
    } loop
} def

ARGUMENTS{V ==}forall %iterate through the command-line arguments


答:
eacal, 26 bytes

```<code>write a string Hello World
</code>```

This writes a string Hello World to file a, creating it if not present. Basically:

```<code>write <fileName> <exec>
</code>```

and

```<code>string <params to convert to string>
</code>```

Run the program as:

```<code>λ node eacal.js writeFile
</code>```

Title: Create and write to a file

Body:
eacal, 26 bytes

write a string Hello World

This writes a string Hello World to file a, creating it if not present. Basically:

write <fileName> <exec>

and

string <params to convert to string>

Run the program as:

λ node eacal.js writeFile


问:
Too Fast, Too Fourier: FFT Code Golf
Implement the Fast Fourier Transform in the fewest possible characters.

Rules:

Shortest solution wins

It can be assumed that the input is a 1D array whose length is a power of two.

You may use the algorithm of your choice, but the solution must actually be a Fast Fourier Transform, not just a naive Discrete Fourier Transform (that is, it must have asymptotic computation cost of \$O(N \log N)\$)

the code should implement the standard forward Fast Fourier Transform, the form of which can be seen in equation (3) of this Wolfram article,

$$F_n = \sum_{k=0}^{N-1}f_ke^{-2\pi ink/N}$$

Using an FFT function from a pre-existing standard library or statistics package is not allowed.  The challenge here is to succinctly implement the FFT algorithm itself.

答:
Jelly, <s>31</s> <s>30</s> <s>28</s> 26 bytes

```<code>LḶ÷$N-*×,N$+ḷF
s2Zß€ç/µ¹Ṗ?
</code>```

This uses the Cooley-Tukey radix-2 recursive algorithm. For an un-golfed version, see my answer in Mathematica.

Try it online or Verify multiple test cases.

Explanation

```<code>LḶ÷$N-*×,N$+ḷF  Helper link. Input: lists A and B
L               Get the length of A
   $            Operate on that length
 Ḷ                Make a range [0, 1, ..., length-1]
  ÷               Divide each by length
    N           Negate each
     -          The constant -1
      *         Compute -1^(x) for each x in that range
       ×        Multiply elementwise between that range and B, call it B'
          $     Operate on that B'
         N        Negate each
        ,         Make a list [B', -B']
            ḷ   Get A
           +    Add vectorized, [B', -B'] + A = [A+B', A-B']
             F  Flatten that and return

s2Zß€ç/µ¹Ṗ?  Main link. Input: list X
         Ṗ   Curtail - Make a copy of X with the last value removed
          ?  If that list is truthy (empty lists are falsey)
       µ       Parse to the left as a monad
s2             Split X into sublists of length 2
  Z            Transpose them to get [even-index, odd-index]
   ß€          Call the main link recursively on each sublist
     ç/        Call the helper link as a dyad on the sublists and return
             Else
        ¹      Identity function on X and return
</code>```

Title: Too Fast, Too Fourier: FFT Code Golf

Body:
Jelly, <s>31</s> <s>30</s> <s>28</s> 26 bytes

LḶ÷$N-*×,N$+ḷF
s2Zß€ç/µ¹Ṗ?

This uses the Cooley-Tukey radix-2 recursive algorithm. For an un-golfed version, see my answer in Mathematica.

Try it online or Verify multiple test cases.

Explanation

LḶ÷$N-*×,N$+ḷF  Helper link. Input: lists A and B
L               Get the length of A
   $            Operate on that length
 Ḷ                Make a range [0, 1, ..., length-1]
  ÷               Divide each by length
    N           Negate each
     -          The constant -1
      *         Compute -1^(x) for each x in that range
       ×        Multiply elementwise between that range and B, call it B'
          $     Operate on that B'
         N        Negate each
        ,         Make a list [B', -B']
            ḷ   Get A
           +    Add vectorized, [B', -B'] + A = [A+B', A-B']
             F  Flatten that and return

s2Zß€ç/µ¹Ṗ?  Main link. Input: list X
         Ṗ   Curtail - Make a copy of X with the last value removed
          ?  If that list is truthy (empty lists are falsey)
       µ       Parse to the left as a monad
s2             Split X into sublists of length 2
  Z            Transpose them to get [even-index, odd-index]
   ß€          Call the main link recursively on each sublist
     ç/        Call the helper link as a dyad on the sublists and return
             Else
        ¹      Identity function on X and return


答:
J, 21 bytes

```<code>'Hello World'1!:3<'o'
</code>```

This writes to a file o in the current directory, or, if not called from a file, in your j64-804 file. 1!:3 is the write foreign, and <'o' is the boxed filename (filenames need to be boxed). The LHS is the string to write.

Title: Create and write to a file

Body:
J, 21 bytes

'Hello World'1!:3<'o'

This writes to a file o in the current directory, or, if not called from a file, in your j64-804 file. 1!:3 is the write foreign, and <'o' is the boxed filename (filenames need to be boxed). The LHS is the string to write.


问:
Snakes all around

Challenge

The challenge is simple: print a snake.

You will get the length of the snake as input.

A snake of length 2 looks like this:

```<code>==(:)-
</code>```

A snake of length 7 looks like this:

```<code>=======(:)-
</code>```

In other words, the length of a snake is how many equal signs are before the head.

Usage

Let's say I made a C++ implementation and compiled it to ./getsnake.

I could run it like so:

```<code>$ ./getsnake 10
==========(:)-
</code>```

Clarifications

Standard loopholes are disallowed.

You can get input and output in any acceptable way.

You can assume all inputs given are positive integers.

You may write a function instead of a regular program.

答:
C#, 42 bytes

```<code>string w(int n)=>new string('=',n)+"(:)-";
</code>```

Try it here!

Title: Snakes all around

Body:
C#, 42 bytes

string w(int n)=>new string('=',n)+"(:)-";

Try it here!


Title: Generate Linus Sequence

Body:
Definition

From the description on OEIS A006345:

To find a(n), consider either a 1 or a 2. For each, find the longest repeated suffix, that is, for each of a(n)=1,2, find the longest sequence s with the property that the sequence a(1),...,a(n) ends with ss. Use the digit that results in the shorter such suffix. a(1) = 1.

Worked-out Example

a(1)=1.

If a(2)=1, we will have the sequence 1 1 where the longest doubled substring from the end is 1. If a(2)=2 instead, then it would be the empty substring. Therefore a(2)=2.

When n=6, we choose between 1 2 1 1 2 1 and 1 2 1 1 2 2. In the first choice, 1 2 1 is doubled consecutively from the end. In the second choice, it is 2 instead. Therefore, a(6)=2.

When n=9, we choose between 1 2 1 1 2 2 1 2 1  and 1 2 1 1 2 2 1 2 2. In the first choice, the longest doubled consecutive substring is 2 1, while in the second choice 1 2 2 is doubled consecutively at the end. Therefore a(9)=1.

Task

Given n, return a(n).

Specs

n will be positive.

You can use 0-indexed instead of 1-indexed. In that case, please state so in your answer. Also, in that case, n can be 0 also.

Testcases

The testcases are 1-indexed. However, you can use 0-indexed.

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

References

WolframMathWorld

Obligatory OEIS A006345

Body:
Haskell, <s>146</s> <s>140</s> <s>137</s> <s>133</s> 118 bytes

s!l|take l s==take l(drop l s)=l|1<2=s!(l-1)
g[w,x]|w<x=1|1<2=2
a 1=1
a n=g$(\s x->(x:s)!n)(a<$>[n-1,n-2..1])<$>[1,2]


答:
PowerShell v2+, 46152 characters

```<code>param([System.Collections.ArrayList]$n)$n=$n|sort length -des;while($n){$x=$n.Count;$o+=$n[0];0..$x|%{if($o.IndexOf($n[$_])-ge0){$n.RemoveAt($_)}}}$o
</code>```

Takes the input as a list, casts it into an ArrayList (so we can manipulate it). We sort it by length in -descending order. Then, while we still have words in our input array, do a loop. Each iteration, set helper $x to be equal to how many we have left, tack on the next item in the list to our output $o, and then trawl through everything still in our list. If the .IndexOf is not equal to -1 (i.e., the word was found somewhere in $o), we remove that word from our list of remaining words. Finally, at the end, output $o.

I don't have access to a Pastebin or similar, so here's the beginning and end of the word for temporary --  telecommunicationscharacterizationresponsibilitiessublimedirectory...fcmxvtwvfxwujmjsuhjjrxjdbkdxqc. Which I guess has shaved about 20,000 characters off of the input, so not that bad, I suppose.

I'm working on refinements.

Title: Compounding english

Body:
A compound word is a word that contains 2 or more words in it.  We can do better than that, though.  We need you to create 1 (nonsensical) word that contains every word.

However, we want this word to be as short as possible.  We can use overlapping letters to achieve this.

For example, if your word list was ["cat", "atom", "a"], you would want to return "catom".

Input/Output

Your program will need to take a list of words as input, and return a compound word as output.

The word list you will be using is the top 10000 words in English, according to Google  (If this list turns out to be too easy, I may change it to a longer one).   For reference, simply appending each word gives you a score of 65888.

Your score is the number of letters in your final word, lower is better.  Tie breaker goes to the first poster.

Body:
PowerShell v2+, 46152 characters

param([System.Collections.ArrayList]$n)$n=$n|sort length -des;while($n){$x=$n.Count;$o+=$n[0];0..$x|%{if($o.IndexOf($n[$_])-ge0){$n.RemoveAt($_)}}}$o

Takes the input as a list, casts it into an ArrayList (so we can manipulate it). We sort it by length in -descending order. Then, while we still have words in our input array, do a loop. Each iteration, set helper $x to be equal to how many we have left, tack on the next item in the list to our output $o, and then trawl through everything still in our list. If the .IndexOf is not equal to -1 (i.e., the word was found somewhere in $o), we remove that word from our list of remaining words. Finally, at the end, output $o.

I don't have access to a Pastebin or similar, so here's the beginning and end of the word for temporary --  telecommunicationscharacterizationresponsibilitiessublimedirectory...fcmxvtwvfxwujmjsuhjjrxjdbkdxqc. Which I guess has shaved about 20,000 characters off of the input, so not that bad, I suppose.

I'm working on refinements.


答:
Python 2, 39254 characters

Takes 1-2 minutes to run on my machine, works by taking the longest word and then always adding the word to the result string that has the most strings in common. (Before that all words that are substrings of other words are removed to prevent unnecessary adding to the string.)

Update: Tried to look in both directions, but that doesn't do any better. (maybe it's using words that can be used better later?)

Link to the word on pastebin.

first 100 chars:

```<code>telecommunicationsawayneillegallynnbabyenbcjrxltdxmlbsrcwvtxxxboxespnycdsriconsentencessexyrsslipodc
</code>```

Code:

```<code>import re
import urllib

def suffix_dist(w1,w2):
    for i in range(min(map(len,[w1,w2])))[::-1]:
        if w1[-i:]==w2[:i]:
            return i
    return 0

url="https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt"
s=urllib.urlopen(url).read()
words=s.split()
words.sort(key=len,reverse=True)

## remove words that are substrings of other words anyway
for i in range(len(words))[::-1]:
    if any(words[i] in w for w in words[:i]):
        words.pop(i)

print len(words)

words.sort(key=len)
w1=words.pop(-1)
result=w1
while words:
    ## get the word with longest shared suffix/prefix
    w2=max(words,key=lambda x:suffix_dist(w1,x))
    print w2
    words.pop(words.index(w2))
    if w2 in result:
        break
    result+=w2[suffix_dist(w1,w2):]
    w1=w2

print result[:100]
print len(result)
print "Test:", all(w in result for w in s.split())
</code>```

Title: Compounding english

Body:
Python 2, 39254 characters

Takes 1-2 minutes to run on my machine, works by taking the longest word and then always adding the word to the result string that has the most strings in common. (Before that all words that are substrings of other words are removed to prevent unnecessary adding to the string.)

Update: Tried to look in both directions, but that doesn't do any better. (maybe it's using words that can be used better later?)

Link to the word on pastebin.

first 100 chars:

telecommunicationsawayneillegallynnbabyenbcjrxltdxmlbsrcwvtxxxboxespnycdsriconsentencessexyrsslipodc

Code:

import re
import urllib

def suffix_dist(w1,w2):
    for i in range(min(map(len,[w1,w2])))[::-1]:
        if w1[-i:]==w2[:i]:
            return i
    return 0

url="https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english.txt"
s=urllib.urlopen(url).read()
words=s.split()
words.sort(key=len,reverse=True)

## remove words that are substrings of other words anyway
for i in range(len(words))[::-1]:
    if any(words[i] in w for w in words[:i]):
        words.pop(i)

print len(words)

words.sort(key=len)
w1=words.pop(-1)
result=w1
while words:
    ## get the word with longest shared suffix/prefix
    w2=max(words,key=lambda x:suffix_dist(w1,x))
    print w2
    words.pop(words.index(w2))
    if w2 in result:
        break
    result+=w2[suffix_dist(w1,w2):]
    w1=w2

print result[:100]
print len(result)
print "Test:", all(w in result for w in s.split())


问:
Integer goes back and forth through time
Input:

An integer.

Output:

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

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

And output the sum of those.

Example:

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

Roman Numerals:

Here is a perhaps useful Roman Numeral Converter.

Challenge rules:

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

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

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

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

* Roman Numeral rules (quote from Wikipedia):

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

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

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

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

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

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

Some examples of the modern use of Roman numerals include:

  1954 as MCMLIV; 1990 as MCMXC; 2014 as MMXIV

  SOURCE

General rules:

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

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

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

Default Loopholes are forbidden.

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

Also, please add an explanation if necessary.

Test cases:

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

Body:
JavaScript (ES6), 183 bytes

f=(n,a=0)=>n<4e3?[256077,230544,128068,102535,25667,23195,12876,10404,2648,2465,1366,1183,329].map((e,i)=>(d=e>>8,c=n/d|0,n-=c*d,r+=c*(e%256+a*-~(i&1))),r=0)|r:f(n/1e3,a+175)+f(n%1e3)

Note: not only prefers (IV) to M(V), but also prefers (VI) to (V)M; in fact it will only use M at the very start of the number.


问:
Ordering a list

Summary

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

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

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

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

Test cases:

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

答:
Java <s>149</s> 140 bytes

```<code>public int[] indexArray(int[] index){
  int[] out=new int[index.length];
  for(int i=-1;++i<index.length;){
    for(int j=-1;++i<index.length;){
      if(index[i]==Arrays.sort(index.clone())[j]){
        out[i]=j;
      }
    }
  }
  return out;
}
</code>```

Golfed

```<code>int[]a(int[]b){int l=b.length;int[]o=new int[l];for(int i=-1;++i<l;)for(int j=-1;++i<l;)if(b[i]==Arrays.sort(b.clone())[j])o[i]=j;return o;}
</code>```

Thanks to @Kevin Cruissjen for shaving of 9 bytes.

Title: Ordering a list

Body:
Java <s>149</s> 140 bytes

public int[] indexArray(int[] index){
  int[] out=new int[index.length];
  for(int i=-1;++i<index.length;){
    for(int j=-1;++i<index.length;){
      if(index[i]==Arrays.sort(index.clone())[j]){
        out[i]=j;
      }
    }
  }
  return out;
}

Golfed

int[]a(int[]b){int l=b.length;int[]o=new int[l];for(int i=-1;++i<l;)for(int j=-1;++i<l;)if(b[i]==Arrays.sort(b.clone())[j])o[i]=j;return o;}

Thanks to @Kevin Cruissjen for shaving of 9 bytes.


问:
Balance chemical equations!
Bernd is a high school student who has some problems in chemistry. In class he has to design chemical equations for some experiments they are doing, such as the combustion of heptane C7H16:

C7H16 + 11O2 → 7CO2 + 8H2O

Since mathematics isn't exactly Bernd's strongest subject, he often has a hard time finding the exact ratios between the pro- and educts of the reaction. Since you are Bernd's tutor, it is your job to help him! Write a program, that calculates the amount of each substance needed to get a valid chemical equation.

Input

The input is a chemical equation without amounts. In order to make this possible in pure ASCII, we write any subscriptions as ordinary numbers. Element names always start with a capital letter and may be followed by a minuscule. The molecules are separated with + signs, an ASCII-art arrow -> is inserted between both sides of the equation:

```<code>Al+Fe2O4->Fe+Al2O3
</code>```

The input is terminated with a newline and won't contain any spaces. If the input is invalid, your program may do whatever you like.

You may assume, that the input is never longer than 1024 characters. Your program may either read the input from standard input, from the first argument or in an implementation defined way at runtime if neither is possible.

Output

The output of your program is the input equation augmented with extra numbers. The number of atoms for each element must be the same on both sides of the arrow. For the example above, a valid output is:

```<code>2Al+Fe2O3->2Fe+Al2O3
</code>```

If the number for a molecule is 1, drop it. A number must always be a positive integer. Your program must yield numbers such that their sum is minimal. For instance, the following is illegal:

```<code>40Al+20Fe2O3->40Fe+20Al2O3
</code>```

If there is no solution, print

```<code>Nope!
</code>```

instead. A sample input that has no solution is

```<code>Pb->Au
</code>```

Testcases

Input->Output

```<code>C7H16+O2->CO2+H2O
C7H16+11O2->7CO2+8H2O

Al+Fe2O3->Fe+Al2O3
2Al+Fe2O3->2Fe+Al2O3

Pb->Au
Nope!
</code>```

This is code-golf, so shortest code wins!

Your program must terminate in reasonable time for all reasonable inputs

答:
C (gcc), 442 bytes

u,t[99];char*s,*m[99];c,v[99][99];i,j,n;
b(k){if(k<0)for(n=j=0;!n&&j<u;j++)for(i=0;i<=c;i++)n+=t[i]*v[i][j];else for(t[k]=0;n&&t[k]++<30;)b(k-1);}
main(int r,char**a){for(s=m[0]=a[1];*s;){if(*s==45)r=0,s++;if(*s<65)m[++c]=++s;j=*s++;if(*s>96)j=*s+++j<<8;for(i=0,t[u]=j;t[i]-j;i++);u+=i==u;for(n=0;*s>>4==3;)n=n*10+*s++-48;n+=!n;v[c][i]=r?n:-n;}b(c);for(i=0,s=n?"Nope!":a[1];*s;putchar(*s++))s==m[i]&&t[i++]>1?printf("%d",t[i-1]):0;putchar(10);}
```
<p>Try it online!</p>
<p>Ungolfed version</p>
<pre class="lang-C prettyprint-override"><code>// element use table, then once parsed reused as molecule weights
u,t[99];

// molecules
char*s,*m[99]; // name and following separator
c,v[99][99]; // count-1, element vector

i,j,n;

// brute force solver, n==0 upon solution - assume at most 30 of each molecule
b(k){
    if(k<0)for(n=j=0;!n&&j<u;j++)for(i=0;i<=c;i++)n+=t[i]*v[i][j]; // check if sums to zero
    else for(t[k]=0;n&&t[k]++<30;)b(k-1); // loop through all combos of weights
}

main(int r,char**a){
    // parse
    for(s=m[0]=a[1];*s;){
        // parse separator, advance next molecule
        if(*s==45)r=0,s++;
        if(*s<65)m[++c]=++s;
        // parse element
        j=*s++;
        if(*s>96)j=*s+++j<<8;
        // lookup element index
        for(i=0,t[u]=j;t[i]-j;i++);
        u+=i==u;
        // parse amount
        for(n=0;*s>>4==3;)n=n*10+*s++-48;
        n+=!n;
        // store element count in molecule vector, flip sign for other side of '->'
        v[c][i]=r?n:-n;
    }
    // solve
    b(c);
    // output
    for(i=0,s=n?"Nope!":a[1];*s;putchar(*s++))s==m[i]&&t[i++]>1?printf("%d",t[i-1]):0;
    putchar(10);
}
<span class="math-container">```
```

Title: Balance chemical equations!

Body:
C (gcc), 442 bytes

u,t[99];char*s,*m[99];c,v[99][99];i,j,n;
b(k){if(k<0)for(n=j=0;!n&&j<u;j++)for(i=0;i<=c;i++)n+=t[i]*v[i][j];else for(t[k]=0;n&&t[k]++<30;)b(k-1);}
main(int r,char**a){for(s=m[0]=a[1];*s;){if(*s==45)r=0,s++;if(*s<65)m[++c]=++s;j=*s++;if(*s>96)j=*s+++j<<8;for(i=0,t[u]=j;t[i]-j;i++);u+=i==u;for(n=0;*s>>4==3;)n=n*10+*s++-48;n+=!n;v[c][i]=r?n:-n;}b(c);for(i=0,s=n?"Nope!":a[1];*s;putchar(*s++))s==m[i]&&t[i++]>1?printf("%d",t[i-1]):0;putchar(10);}

<a href="https://tio.run/##PVDLbsIwEPwVQCqKvYnk8Cqw2XDgwql8QORDcKG1aQyKEy6Ib0/t0HKxd8ee3ZlRyZdSXdfGTbFaSVTfZc1dzKtnF9/C3dc6NrHFQ3Rmd32Kzplgp0sdWTIkcGjHY5O1aAB6VHtMZ6RQe8ACNYWW/OaPwkg8/rjjIPxqirP0Hz03VADZVCDzC5KU4aMqtY20bQZ13GviJbsHkqOqEJLKIpXIHfZiuCOazVlNInYA2CPZYs6qAkBJAnBoiL@e8tWCPXswWbbEP8U@gVaSwSA2Mb10bIE0UYtPq8JvzPMZ0RSZJctTAWFKMluiNzm0eCuU9GyqN3adWHwcIsVe4x3Zzejjcj0OR@t/@de2Ce6iMIYxb6Py9JCH3y7zdHOtfQSnaPT2OfLydJJKthYvVip8UF3Xbd936QL2kyTf7iewm@x/AQ" rel="nofollow noreferrer" title="C (gcc) – Try It Online">Try it online!

Ungolfed version

// element use table, then once parsed reused as molecule weights
u,t[99];

// molecules
char*s,*m[99]; // name and following separator
c,v[99][99]; // count-1, element vector

i,j,n;

// brute force solver, n==0 upon solution - assume at most 30 of each molecule
b(k){
    if(k<0)for(n=j=0;!n&&j<u;j++)for(i=0;i<=c;i++)n+=t[i]*v[i][j]; // check if sums to zero
    else for(t[k]=0;n&&t[k]++<30;)b(k-1); // loop through all combos of weights
}

main(int r,char**a){
    // parse
    for(s=m[0]=a[1];*s;){
        // parse separator, advance next molecule
        if(*s==45)r=0,s++;
        if(*s<65)m[++c]=++s;
        // parse element
        j=*s++;
        if(*s>96)j=*s+++j<<8;
        // lookup element index
        for(i=0,t[u]=j;t[i]-j;i++);
        u+=i==u;
        // parse amount
        for(n=0;*s>>4==3;)n=n*10+*s++-48;
        n+=!n;
        // store element count in molecule vector, flip sign for other side of '->'
        v[c][i]=r?n:-n;
    }
    // solve
    b(c);
    // output
    for(i=0,s=n?"Nope!":a[1];*s;putchar(*s++))s==m[i]&&t[i++]>1?printf("%d",t[i-1]):0;
    putchar(10);
}
```


Title: Snakes all around

Body:
Challenge

The challenge is simple: print a snake.

You will get the length of the snake as input.

A snake of length 2 looks like this:

```<code>==(:)-
</code>```

A snake of length 7 looks like this:

```<code>=======(:)-
</code>```

In other words, the length of a snake is how many equal signs are before the head.

Usage

Let's say I made a C++ implementation and compiled it to ./getsnake.

I could run it like so:

```<code>$ ./getsnake 10
==========(:)-
</code>```

Clarifications

Standard loopholes are disallowed.

You can get input and output in any acceptable way.

You can assume all inputs given are positive integers.

You may write a function instead of a regular program.

Body:
Ruby, 20 bytes

->n{puts?=*n+"(:)-"}


问:
ASCII art reflection
In this challenge, you will be given a text block, and you need to perform reflection on the text.

Input:

A string to be reflected. The text may not be supplied as an array whose elements are the lines of text. For example, "ab\ncd" and ['a','b','\n','c','d'] are allowed, but ['ab','cd'] or [['a','b'],['c','d']] are not. You can assume that all of the lines have the same number of characters (padded with whitespace where needed).

A boolean where True indicates Y reflection and False indicates X reflection

The two inputs can be passed in any order.

Output:

The reflected string. The characters do not change, only their position. The resulting image block should be aligned to the top left (the first row and column must each contain a non-whitespace character). Trailing whitespace (on any of the lines) is allowed.

Test cases:

```<code>False
  o /
--|/
  |
 / \

/ o
 /|--
  |
 \ /
</code>```

```<code>True
  o /
--|/
  |
 / \

 / \
  |
--|/
  o /
</code>```

```<code>True
text

text
</code>```

```<code>False
text

txet
</code>```

```<code>True
P
P
C
G

G
C
P
P
</code>```

```<code>False
P
P
C
G

P
P
C
G
</code>```

```<code>True
abcde
fghij
kl mn
opqrs
tuvwx

tuvwx
opqrs
kl mn
fghij
abcde
</code>```

This is a code-golf, so answer with the shortest answer in your favorite language!

答:
Java 99 bytes

```<code>public String[] reverse(String[]a){
  int i=-1,j=a.length;
  for(;++i<--j;){
    String b=a[i];
    a[i]=a[j];
    a[j]=b;
  }
  return a;
}
</code>```

Golfed:

```<code>String[] e(String[]a){int i=-1,j=a.length;for(;++i<--j;){String b=a[i];a[i]=a[j];a[j]=b;}return a;}
</code>```

Title: ASCII art reflection

Body:
Java 99 bytes

public String[] reverse(String[]a){
  int i=-1,j=a.length;
  for(;++i<--j;){
    String b=a[i];
    a[i]=a[j];
    a[j]=b;
  }
  return a;
}

Golfed:

String[] e(String[]a){int i=-1,j=a.length;for(;++i<--j;){String b=a[i];a[i]=a[j];a[j]=b;}return a;}


答:
Java

```<code>public class H
{
    public static void main(String[] a)
        throws IOException
    {
        FileWriter o = new FileWriter("x");
        o.write("Hello World");
        o.close();
    }
}
</code>```

Simple I/O with no exception handling.

Corrected

Corrected the original code to write the correct string (Hello World).

Title: Create and write to a file

Body:
Challenge

Create a new file and write the string Hello World to it.

Restrictions

Your challenge must write to a file on disk, in the file system.

The file may not be a log file generated during normal operation of the interpreter.

The file must contain only the string Hello World. It is allowed to contain a trailing newline or minimal whitespace. No other content.

No command-line flags/pipes (etc) allowed, except when necessary to run the program. (e.g. perl -p)

Notes

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

Follow the spirit, not the letter, of the rules.

Body:
Java

public class H
{
    public static void main(String[] a)
        throws IOException
    {
        FileWriter o = new FileWriter("x");
        o.write("Hello World");
        o.close();
    }
}

Simple I/O with no exception handling.

Corrected

Corrected the original code to write the correct string (Hello World).