问:
The Ever Amplifying Zigzag
Write a program or function that takes in a positive integer N and outputs the first N numbers of this amplifying zigzag pattern, using only the lines needed:

```<code>                                         26
                                       25  27                                      .
         10                          24      28                                  .
        9  11                      23          29                              .
 2     8     12                  22              30                          44
1 3   7        13              21                  31                      43
   4 6           14          20                      32                  42
    5              15      19                          33              41
                     16  18                              34          40
                       17                                  35      39
                                                             36  38
                                                               37
</code>```

So, if N is 1 the output is

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

If N is 2, the output is

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

If N is 3 the output is

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

If N is 4 the output is

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

If N is 10 the output is

```<code>         10
        9
 2     8
1 3   7
   4 6
    5
</code>```

If N is 19 the output is

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

and so on.

Notes

Each peak or trough of the zigzag reaches its point one more line away from the line with the 1 on it than the previous peak or trough.

N is not limited to 44. The zigzag grows in the same pattern and larger N should be supported.

Numbers with multiple digits should only "touch" at their corners, as depicted. Make sure this works when N is 100 and above.

There should be no empty (or space only) lines in the output except one optional trailing newline.

Any line may have any amount of trailing spaces.

Scoring

The shortest code in bytes wins. Tiebreaker is earlier answer.

答:
JavaScript (ES6), 213 bytes

```<code>with(Math)n=>(a=[...Array(n)].map((_,i)=>n-=1+sqrt(--i)&1||-1).map((e,_,a)=>e-min(...a))).map((e,i)=>r[e][i]=++i,r=[...Array(1+max(...a))].map(_=>a.map((_,i)=>` `.repeat(1+log10(++i)))))&&r.map(a=>a.join``).join`\n`
</code>```

Where \n represents a literal newline character. Explanation:

```<code>with(Math)                          Bring functions into scope
 n=>                                Accepts one parameter
  (a=                               Intermediate result variable
   [...Array(n)].map(               For each number 0..n-1
    (_,i)=>n-=                      Accumulate index for each number
     1+sqrt(--i)&1||-1              Calculate the direction
    ).map((e,_,a)=>e-min(...a))     Scale the smallest index to zero
  ).map((e,i)=>r[e][i]=++i,         Overwrite the padding with 1..n
   r=[...Array(1+max(...a))].map(   Calculate number of lines
    _=>a.map((_,i)=>                For each number 1..n
     ` `.repeat(1+log10(++i)))))    Calculate the padding needed
  &&r.map(a=>a.join``).join`\n`     Join everything together
</code>```

To shorten pow(-1,ceil(sqrt(i))) I rewrite it as sqrt(i-1)&1||-1 however this doesn't work for i=0 so to fix that I add 1 but this then flips the sign of the result which is why I end up with n-=.

Title: The Ever Amplifying Zigzag

Body:
JavaScript (ES6), 213 bytes

with(Math)n=>(a=[...Array(n)].map((_,i)=>n-=1+sqrt(--i)&1||-1).map((e,_,a)=>e-min(...a))).map((e,i)=>r[e][i]=++i,r=[...Array(1+max(...a))].map(_=>a.map((_,i)=>` `.repeat(1+log10(++i)))))&&r.map(a=>a.join``).join`\n`

Where \n represents a literal newline character. Explanation:

with(Math)                          Bring functions into scope
 n=>                                Accepts one parameter
  (a=                               Intermediate result variable
   [...Array(n)].map(               For each number 0..n-1
    (_,i)=>n-=                      Accumulate index for each number
     1+sqrt(--i)&1||-1              Calculate the direction
    ).map((e,_,a)=>e-min(...a))     Scale the smallest index to zero
  ).map((e,i)=>r[e][i]=++i,         Overwrite the padding with 1..n
   r=[...Array(1+max(...a))].map(   Calculate number of lines
    _=>a.map((_,i)=>                For each number 1..n
     ` `.repeat(1+log10(++i)))))    Calculate the padding needed
  &&r.map(a=>a.join``).join`\n`     Join everything together

To shorten pow(-1,ceil(sqrt(i))) I rewrite it as sqrt(i-1)&1||-1 however this doesn't work for i=0 so to fix that I add 1 but this then flips the sign of the result which is why I end up with n-=.


问:
Here's Bub. A not-so-world-class soccer player
This is Bub. Bub is a soccer player. However, he's not a very good one. He still can't kick the ball to the net! (If you haven't noticed, @ is the ball.

```<code>                                                       _____
                                                      |     \
  O                                                   |      \
 \|/                                                  |       \
  |                                                   |  net   \
 / ─   @                                              |_________\
</code>```

To help develop his skills, he's developed a system to help evaluate his performance when he kicks the ball. He's called it the "10 point system."

However, he doesn't know what he needs to do to achieve x number of points. You need to help him visualize where the ball will be, so that he can set an expectation of how many points he wants to get. There are 10 points per round that he can achieve.

Therefore, this is your challenge.

Given a number x, the number of points Bub gets, output the location of the ball on the field. Here are some helpful markers:

Bub is exactly 50 spaces away from the net.

For each point that Bub gets, the ball moves 5 spaces closer to the net. Therefore, if Bub gets 3 points, the ball is 35 spaces away from the net.

For every 3 points that Bub gets, the ball begins to move in the air! It moves one space up.

If the number of points Bub gets would move the ball behind the net, you can put the ball anywhere inside the net.

Remember, you need to draw Bub, the ball, and the net.

To get you started, here's an example:

Number of Points: 5

```<code>                                                       _____
                                                      |     \
  O                                                   |      \
 \|/                                                  |       \
  |                          @                        |        \
 / ─                                                  |_________\
</code>```

Standard rules apply. Code with the lowest number of bytes wins! Happy golfing!

ContentLicense: CC BY-SA 3.0

Body:
Pyth, <s>106</s> 91 bytes

Run-length encoding, followed by internal encoding.

Hexdump:

0000000: 4a 63 72 58 2e 22 30 41 01 b6 07 31 11 af 55 c5 JcrX."0A...1..U.
0000010: 16 6f 93 4f ea 90 6b 39 f6 e0 dc 81 43 9d 01 f7 .o.O..k9....C...
0000020: 36 93 ee 4c c8 fa a5 28 70 22 6d 43 2b 35 38 64 6..L...(p"mC+58d
0000030: 38 22 0a 20 2f 4f 5c 5c 5f 7c 2d 22 39 62 6a 58 8". /O\\_|-"9bjX
0000040: 4a 4b 2d 35 2f 68 53 2c 54 51 33 58 40 4a 4b 68 JK-5/hS,TQ3X@JKh
0000050: 53 2c 35 38 2b 34 2a 35 51 5c 40                S,58+4*5Q\@

Try it online!

Replace the Unicode character ─ (U+2500) as a single hyphen.


问:
The alphabet in programming languages
Our task is to, for each letter of the (English) alphabet, write a program that prints the alphabet, in a language whose name starts with that letter.

Input: none

Output:

```<code>abcdefghijklmnopqrstuvwxyz
</code>```

uppercase and trailing newline optional

Rules:

The scoring metric is the length of the programming language name, plus the length of the code.  Hence, C will be assessed a "penalty" of 1, while GolfScript will be assessed a penalty of 10.

One language/implementation per answer.  Multiple answers are encouraged.

If a programming language name's first letter is not an English letter, it should not be coerced into one.  It will be treated as a separate letter (meaning less competition).

No answer will be accepted until every English letter has a solution.

Current rankings:

APL: 5

Brachylog: 11

Canvas: 7

DOS: 13

Eso2D: 20

Fish: 20

Gaia: 6

Husk: 8

IPEL: 23

Japt: 6

Keg: 6

Ly: 13

MathGolf: 9

Ni: 15

Owl: 14

Pip: 4

QuadR: 31

Ruby: 17

Stax: 6

Thunno: 8

Unix Shell: 31

V: 4

W: 4

XJam: 10

Yorick: 36

Z80Golf: 16

Tell me if I'm missing anybody.

Automatic leaderboard (experimental)

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

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

Winners by Letter

Language	User	Score

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

Everything

	Language	Author	Size

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

```

答:
J is for Java - score: 84 characters + 4 = 88

```<code>interface a{static void main(String[]A){for(char c=65;c<91;System.out.print(c++));}}
</code>```

This prints ABCDEFGHIJKLMNOPQRSTUVWXYZ instead of abcdefghijklmnopqrstuvwxyz. If it's disallowed, one can simply set c to 97 (a) and loop until it reaches 123 ({) at the cost of one extra byte:

```<code>interface a{static void main(String[]A){for(char c=97;c<123;System.out.print(c++));}}
</code>```

ContentLicense: CC BY-SA 4.0

Title: The alphabet in programming languages

Body:
J is for Java - score: 84 characters + 4 = 88

interface a{static void main(String[]A){for(char c=65;c<91;System.out.print(c++));}}

This prints ABCDEFGHIJKLMNOPQRSTUVWXYZ instead of abcdefghijklmnopqrstuvwxyz. If it's disallowed, one can simply set c to 97 (a) and loop until it reaches 123 ({) at the cost of one extra byte:

interface a{static void main(String[]A){for(char c=97;c<123;System.out.print(c++));}}


问:
Sing Happy Birthday to your favourite programming language
Your favourite programming language has just had a birthday. Be nice and sing it the Happy Birthday song.

Of course you should accomplish this by writing a program in that language.
The program takes no input, and writes the following text to the standard output or an arbitrary file:

```<code>Happy Birthday to You
Happy Birthday to You
Happy Birthday Dear [your favourite programming language]
Happy Birthday to You
</code>```

You should substitute the bracketed part (and omit the brackets).

This is a code golf — shortest code wins.

UPDATE

I'm glad that the question aroused great interest. Let me add some extra info about scoring. As stated originally, this question is a code golf, so the shortest code is going to win. The winner will be picked at the end of this week (19th October).

However, I'm also rewarding other witty submissions with up-votes (and I encourage everybody to do so as well). Therefore although this is a code-golf contest, not-so-short answers are also welcome.

Results

Congratulations to Optimizer, the winner of this contest with his 42 byte long, CJam submission.

Leaderboard

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

/* Configuration */

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

```

答:
Reng, 66 bytes

Noncompeting.

```<code>A"uoY ot yadhtriB yppaH"¤ao;A"gneR raeD yadhtriB yppaH ~"S0gO0gao;
</code>```

Simple enough. A is 10, or a newline. "uoY ot yadhtriB yppaH" pushes that string, ¤ duplicates the string, ao; outputs everything. The second part is more interesting. "A"gneR raeD yadhtriB yppaH ~" pushes that string. S pushes 28, and 0g sets the character at (0, 28) to the top of stack, or a ~, the end program signal. This sets the last A to a tilde. Then, O0g sets the character at(0, 24) to a space/nop, removing the duplicate stack command. We print the third line using ao;. Then, we wrap around to the beginning of the line and print the last line again.

Here's a GIF, because who doesn't like those?

Body:
Reng, 66 bytes

Noncompeting.

A"uoY ot yadhtriB yppaH"¤ao;A"gneR raeD yadhtriB yppaH ~"S0gO0gao;

Simple enough. A is 10, or a newline. "uoY ot yadhtriB yppaH" pushes that string, ¤ duplicates the string, ao; outputs everything. The second part is more interesting. "A"gneR raeD yadhtriB yppaH ~" pushes that string. S pushes 28, and 0g sets the character at (0, 28) to the top of stack, or a ~, the end program signal. This sets the last A to a tilde. Then, O0g sets the character at(0, 24) to a space/nop, removing the duplicate stack command. We print the third line using ao;. Then, we wrap around to the beginning of the line and print the last line again.

Here's a GIF, because who doesn't like those?


问:
Rotate a hypercube

Introduction

A hypercube/tesseract is the 4 dimensional equivalent of a normal cube. It's made by taking a cube net, extending it to the 3rd dimension, then – using the 4th dimension – folding it into a hypercube. It's basically a cube, where each side is a cube.

To create a hypercube, you need 16 4d vectors (a vector with an x, a y, a z and a w component). These vectors are the following:

```<code>A(0, 0, 0, 0); B(1, 0, 0, 0); C(1, 0, 1, 0); D(0, 0, 1, 0); E(0, 1, 0, 0); F(1, 1, 0, 0); G(1, 1, 1, 0); H(0, 1, 1, 0);
I(0, 0, 0, 1); J(1, 0, 0, 1); K(1, 0, 1, 1); L(0, 0, 1, 1); M(0, 1, 0, 1); N(1, 1, 0, 1); O(1, 1, 1, 1); P(0, 1, 1, 1);
</code>```

The hypercube has 24 faces. The following list contains all of them (every group marks a quad):

```<code>ABFE, CDHG, BCGF, DAEH, DCBA, FEHG
IJNM, KLPO, JKON, LIMP, LKJI, PMNO
ABJI, DCKL, BCKJ, DAIL, FEMN, GHPO, FGON, EHPM, EAIM, BFNJ, CGOK, HDLP
</code>```

With all this information, you technically have a hypercube in code. To rotate this, you need 6 different matrices for each rotational plane, one for the YZ, XZ, XY, XW, YW and ZW planes. After you have every matrix, you need to multiply the cube's vertices with them.

The following images show the structure of each matrix:

For the rotation on the YZ plane:

For the rotation on the XZ plane:

For the rotation on the XY plane:

For the rotation on the XW plane:

For the rotation on the YW plane:

For the rotation on the ZW plane:

The rotations get applied in this order.

After all this, you have a rotated hypercube. Now you need to draw it. You should use an orthogonal projection combined with a perspective projection to send (x, y, z, w) to (2x/(2+z), 2y/(2+z)).

Input

Your input is 6 integers between 0 (inclusively) and 360 (exclusively). These represent the rotations in degrees on the different rotational planes of the hypercube.

Output

Your output should be a single image containing the hypercube. The display can be a rasterized image, a vector image or an ASCII art. The output image should be at least 100 * 100 pixels, and the cube needs to take up at least 50% of the screen. Any default image output format is allowed.

Test cases

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

```<code>0 0 0 0 0 30
</code>```

```<code>30 0 0 0 0 30
</code>```

```<code>0 0 0 30 30 30
</code>```

```<code>45 45 45 0 0 0
</code>```

```<code>45 45 45 45 45 45
</code>```

Open the images in a new tab, to see them in full size.

Rules

Default rules apply

Standard loopholes are forbidden

Shortest code in bytes wins

答:
Postscript 1075 732 683 640 631 601 590 545 542 526 514 478 470

Uses mat.ps and G.

Edit:-343 Applied binary-encoding generation of vectors and Eulerian circuit stolen borrowed from other answers. And applied binary-token-strings from the G library.

Edit:-49 Redefined sin cos and neg to shorter names.

Edit:-43 Defined short names for sequences 0 0 0 1 1 0.

Edit:-9 al (ie. aload) is shorter than (")@. Factored 3 calls to idi (ie. idiv) at the cost of a do-nothing 1 idiv.

Edit:-30 Applied implicit definition block from G.

Edit:-10 A few more triply-used sequences.

Edit:-45 Remove variables i j k l m n for the angles and always define the current angle as t and functions of angles use the value of the (global) t variable. Defer execution of the code-description of the rotation matrix until its t value is ready.

Edit:-3 Remove <16>$ ie. closepath. And a space.

Edit:-16 Factor-out array brackets from unit vectors in the rotation matrices (J K L and M). Re-apply dropped mo for mod and su for sub.

Edit:-12 In-line the project-and-draw function and remove (now empty) enclosing dictionary.

Edit:-36 Encoded the circuit (ie. the faces) in a string.

Edit:-8 Remove definition of vertices array V. Instead, leave on stack and dup working copies as needed (once, at first, and again at the end of the loop). Also, translated a few operators from binary-token-strings back to abbreviated names where the BTS gave no savings, so (I)$ is now fora (ie. forall). if du could be (T8)$, but if du is clearly a better choice (it's golf, not obfuscation per se). Also, perform the scale before translate, so translated coordinates can be 3 and 4 instead of 300 and 400.

```<code>(mat.ps)run 3(G)run $
t sin
A neg
t cos
0 0
0 1
1 0
2 mu Z 2(!V)@
idi 2 mo .5 su
(>8)$
[F D]
[D E]
[E D]
[D F]

3 4 100(&>88)$(,)# div(<N)#[E 15{[I 1 H I 2 H I 4 H ex 8 H]}fo]E
5{ARGUMENTS 1(XK/)$/t ex d{{J[0 C B 0][0 A C 0]K}{[C 0 A 0]L[B 0
C 0]K}{[C B D][A C D]M K}{[C D A]L M[B D C]}{J[0 C 0 B]M[0 A 0
C]}{J L[D C B][D A C]}}(>K)$[(>?)$]transpose matmul}fo
du(019;:89=?;37?>:26><804<=576451320){48 su get al po{W
Z Y X}{(>3)$}fora X G Y G{li}(D)#{mov}if du}fora(HB)#
</code>```

The 3 4 and 100 in the first line of the second block are parameters representing center-x, center-y and scale, respectively, of the drawing on the page (center coordinates are scaled by scale). (300,400) is roughly the center of US letter-sized paper (612,792) in PS units.

If you can roughly follow postscript, the important bizarre things are the implicit procedure block and the encoded operator strings. As shown by comments in the workfile, below, each line of the first block is implicitly named by A, B, C, etc. So, eg. F E D would produce 1 0 0 1 0 0. For the encoded operator strings, anything that is an argument to $ # or @ is a sequence of operator calls, using the bytes to select operators from the system name table, PLRM 3ed Appendix F. These features and more are available for PostScript with the G library (now includes the mat.ps functions too).

Workfile:

```<code>(mat.ps)run 3(G)run $
t sin %/A
A neg %/B
t cos %/C
0 0 %/D
0 1 %/E
1 0 %/F
2 mu Z 2(!V)@ %/G  %ad div %add div %108 1 54
idi 2 mo .5 su %idiv mod sub %/H %106 169 51
(>8)$ %/I %exch dup
[F D] %/J
[D E] %/K
[E D] %/L
[D F] %/M

3 4
100(&>88)$ %currentlinewidth exch dup dup %38
(,)#  %scale %139-95=44
div(<N)# %div setlinewidth %54 155-95=60 %translate %173-95=78
%/V
[E 15{[ I
    1 H I
    2 H I
    4 H ex
    8 H]}fo]

E 5{ARGUMENTS 1(XK/)$ %index get cvr %88 75 47
    /t ex d %exch def %62 51
    {{J[0 C B 0][0 A C 0]K}
     {[C 0 A 0]L[B 0 C 0]K}
     {[C B D][A C D]M K}
     {[C D A]L M[B D C]}
     {J[0 C 0 B]M[0 A 0 C]}
     {J L[D C B][D A C]}}
    (>K)$ %exch get %62 75
    [
        (>?)$ %exch exec %62 63
    ]
    transpose matmul
}fo %for
du %dup
%d %def
%{transpose matmul}fora d

%[E 9 11 10 8 9 13 15 11 3 7 15 14 10 2 6 14 12 8 0 4 12 13 5 7 6 4 5 1 3 2 0]
%<0001090b0a08090d0f0b03070f0e0a02060e0c0800040c0d050706040501030200>
%          abcdef
%0123456789:;<=>?
(019;:89=?;37?>:26><804<=576451320)
{48 su get % 169 75 %V (>K)$ %sub %exch get

    al po %aload pop %2 117
    {W Z Y X}{(>3)$ %exch def
    }fora %forall %2 117  62 51 73
    X G
    Y G
    {li}(D)# %stopped
    {mov}
    if du%(T8)$ %if %84 du %dup 56
}
%<49a7a1>$ %forall stroke showpage %73 167-95=72 161-95=66
fora(HB)#
</code>```

Ungolfed and lightly commented:

```<code>300 400 translate   %roughly center of letter paper
currentlinewidth
100 dup dup scale
div setlinewidth    %scale x100, reduce line-width/100
(mat.ps)run         %load matrix library
ARGUMENTS aload pop{f e d c b a}{exch cvr def}forall  %define args as
                                 % a,b,etc and convert to real numbers
/m{2 mod .5 sub}def
/P{aload pop{w z y x}{exch def}forall   %P: [x y z w]  project-and-draw  -
    x 2 mul z 2 add div
    y 2 mul z 2 add div
    {lineto}stopped{moveto}if %catch(&handle!) nocurrentpoint error in lineto
}bind def
/V[0 1 15{    % generate vectors with a for-loop
    [ exch
        dup m
        1 index 2 idiv m
        2 index 4 idiv m
        4 3 roll 8 idiv m
    ]
}for]
[[[1 0 0 0][0 a cos a sin neg 0][0 a sin a cos 0][0 0 0 1]]
     [[b cos 0 b sin 0][0 1 0 0][b sin neg 0 b cos 0][0 0 0 1]]
     [[c cos c sin neg 0 0][c sin c cos 0 0][0 0 1 0][0 0 0 1]]
     [[d cos 0 0 d sin][0 1 0 0][0 0 1 0][d sin neg 0 0 d cos]]
     [[1 0 0 0][0 e cos 0 e sin neg][0 0 1 0][0 e sin 0 e cos]]
     [[1 0 0 0][0 1 0 0][0 0 f cos f sin neg][0 0 f sin f cos]]]
{transpose matmul} forall def   % apply array of rotations and define

%Eulerian circuit (borrowed and adjusted for 0-based indexing)
[0 1 9 11 10 8 9 13 15 11 3 7 15 14 10 2 6 14 12 8 0 4 12 13 5 7 6 4 5 1 3 2 0]

% the main program!
% on the stack is the Eulerian circuit array
{
    V exch get  %lookup index in (sextuply-transformed) vertex array
    P           %call project-and-draw
} forall
closepath stroke %draw it, don't just think about it

showpage % gs's cmd-line-args option automatically sets -dBATCH,
    % so without a showpage, gs will immediately exit before you
    % can look at the picture :(
</code>```

Some of my outputs are mirror images of the question's examples.

For gs -- hc.ps 0 0 0 0 0 0, I get:

gs -- hc.ps 0 0 0 0 0 30

gs -- hc.ps 30 0 0 0 0 30

gs -- hc.ps 0 0 0 30 30 30

gs -- hc.ps 45 45 45 0 0 0

gs -- hc.ps 45 45 45 45 45 45

Bonus animation I just made with this program.  This image corresponds to the rotation sequence 0 30 60 0 i i, where i ranges from 0 to 360 by 2.

Title: Rotate a hypercube

Body:
Postscript 1075 732 683 640 631 601 590 545 542 526 514 478 470

Uses mat.ps and G.

Edit:-343 Applied binary-encoding generation of vectors and Eulerian circuit stolen borrowed from other answers. And applied binary-token-strings from the G library.

Edit:-49 Redefined sin cos and neg to shorter names.

Edit:-43 Defined short names for sequences 0 0 0 1 1 0.

Edit:-9 al (ie. aload) is shorter than (")@. Factored 3 calls to idi (ie. idiv) at the cost of a do-nothing 1 idiv.

Edit:-30 Applied implicit definition block from G.

Edit:-10 A few more triply-used sequences.

Edit:-45 Remove variables i j k l m n for the angles and always define the current angle as t and functions of angles use the value of the (global) t variable. Defer execution of the code-description of the rotation matrix until its t value is ready.

Edit:-3 Remove <16>$ ie. closepath. And a space.

Edit:-16 Factor-out array brackets from unit vectors in the rotation matrices (J K L and M). Re-apply dropped mo for mod and su for sub.

Edit:-12 In-line the project-and-draw function and remove (now empty) enclosing dictionary.

Edit:-36 Encoded the circuit (ie. the faces) in a string.

Edit:-8 Remove definition of vertices array V. Instead, leave on stack and dup working copies as needed (once, at first, and again at the end of the loop). Also, translated a few operators from binary-token-strings back to abbreviated names where the BTS gave no savings, so (I)$ is now fora (ie. forall). if du could be (T8)$, but if du is clearly a better choice (it's golf, not obfuscation per se). Also, perform the scale before translate, so translated coordinates can be 3 and 4 instead of 300 and 400.

(mat.ps)run 3(G)run $
t sin
A neg
t cos
0 0
0 1
1 0
2 mu Z 2(!V)@
idi 2 mo .5 su
(>8)$
[F D]
[D E]
[E D]
[D F]

3 4 100(&>88)$(,)# div(<N)#[E 15{[I 1 H I 2 H I 4 H ex 8 H]}fo]E
5{ARGUMENTS 1(XK/)$/t ex d{{J[0 C B 0][0 A C 0]K}{[C 0 A 0]L[B 0
C 0]K}{[C B D][A C D]M K}{[C D A]L M[B D C]}{J[0 C 0 B]M[0 A 0
C]}{J L[D C B][D A C]}}(>K)$[(>?)$]transpose matmul}fo
du(019;:89=?;37?>:26><804<=576451320){48 su get al po{W
Z Y X}{(>3)$}fora X G Y G{li}(D)#{mov}if du}fora(HB)#

The 3 4 and 100 in the first line of the second block are parameters representing center-x, center-y and scale, respectively, of the drawing on the page (center coordinates are scaled by scale). (300,400) is roughly the center of US letter-sized paper (612,792) in PS units.

If you can roughly follow postscript, the important bizarre things are the implicit procedure block and the encoded operator strings. As shown by comments in the workfile, below, each line of the first block is implicitly named by A, B, C, etc. So, eg. F E D would produce 1 0 0 1 0 0. For the encoded operator strings, anything that is an argument to $ # or @ is a sequence of operator calls, using the bytes to select operators from the system name table, PLRM 3ed Appendix F. These features and more are available for PostScript with the G library (now includes the mat.ps functions too).

Workfile:

(mat.ps)run 3(G)run $
t sin %/A
A neg %/B
t cos %/C
0 0 %/D
0 1 %/E
1 0 %/F
2 mu Z 2(!V)@ %/G  %ad div %add div %108 1 54
idi 2 mo .5 su %idiv mod sub %/H %106 169 51
(>8)$ %/I %exch dup
[F D] %/J
[D E] %/K
[E D] %/L
[D F] %/M

3 4
100(&>88)$ %currentlinewidth exch dup dup %38
(,)#  %scale %139-95=44
div(<N)# %div setlinewidth %54 155-95=60 %translate %173-95=78
%/V
[E 15{[ I
    1 H I
    2 H I
    4 H ex
    8 H]}fo]

E 5{ARGUMENTS 1(XK/)$ %index get cvr %88 75 47
    /t ex d %exch def %62 51
    {{J[0 C B 0][0 A C 0]K}
     {[C 0 A 0]L[B 0 C 0]K}
     {[C B D][A C D]M K}
     {[C D A]L M[B D C]}
     {J[0 C 0 B]M[0 A 0 C]}
     {J L[D C B][D A C]}}
    (>K)$ %exch get %62 75
    [
        (>?)$ %exch exec %62 63
    ]
    transpose matmul
}fo %for
du %dup
%d %def
%{transpose matmul}fora d

%[E 9 11 10 8 9 13 15 11 3 7 15 14 10 2 6 14 12 8 0 4 12 13 5 7 6 4 5 1 3 2 0]
%<0001090b0a08090d0f0b03070f0e0a02060e0c0800040c0d050706040501030200>
%          abcdef
%0123456789:;<=>?
(019;:89=?;37?>:26><804<=576451320)
{48 su get % 169 75 %V (>K)$ %sub %exch get

    al po %aload pop %2 117
    {W Z Y X}{(>3)$ %exch def
    }fora %forall %2 117  62 51 73
    X G
    Y G
    {li}(D)# %stopped
    {mov}
    if du%(T8)$ %if %84 du %dup 56
}
%<49a7a1>$ %forall stroke showpage %73 167-95=72 161-95=66
fora(HB)#

Ungolfed and lightly commented:

300 400 translate   %roughly center of letter paper
currentlinewidth
100 dup dup scale
div setlinewidth    %scale x100, reduce line-width/100
(mat.ps)run         %load matrix library
ARGUMENTS aload pop{f e d c b a}{exch cvr def}forall  %define args as
                                 % a,b,etc and convert to real numbers
/m{2 mod .5 sub}def
/P{aload pop{w z y x}{exch def}forall   %P: [x y z w]  project-and-draw  -
    x 2 mul z 2 add div
    y 2 mul z 2 add div
    {lineto}stopped{moveto}if %catch(&handle!) nocurrentpoint error in lineto
}bind def
/V[0 1 15{    % generate vectors with a for-loop
    [ exch
        dup m
        1 index 2 idiv m
        2 index 4 idiv m
        4 3 roll 8 idiv m
    ]
}for]
[[[1 0 0 0][0 a cos a sin neg 0][0 a sin a cos 0][0 0 0 1]]
     [[b cos 0 b sin 0][0 1 0 0][b sin neg 0 b cos 0][0 0 0 1]]
     [[c cos c sin neg 0 0][c sin c cos 0 0][0 0 1 0][0 0 0 1]]
     [[d cos 0 0 d sin][0 1 0 0][0 0 1 0][d sin neg 0 0 d cos]]
     [[1 0 0 0][0 e cos 0 e sin neg][0 0 1 0][0 e sin 0 e cos]]
     [[1 0 0 0][0 1 0 0][0 0 f cos f sin neg][0 0 f sin f cos]]]
{transpose matmul} forall def   % apply array of rotations and define

%Eulerian circuit (borrowed and adjusted for 0-based indexing)
[0 1 9 11 10 8 9 13 15 11 3 7 15 14 10 2 6 14 12 8 0 4 12 13 5 7 6 4 5 1 3 2 0]

% the main program!
% on the stack is the Eulerian circuit array
{
    V exch get  %lookup index in (sextuply-transformed) vertex array
    P           %call project-and-draw
} forall
closepath stroke %draw it, don't just think about it

showpage % gs's cmd-line-args option automatically sets -dBATCH,
    % so without a showpage, gs will immediately exit before you
    % can look at the picture :(

Some of my outputs are mirror images of the question's examples.

For gs -- hc.ps 0 0 0 0 0 0, I get:

gs -- hc.ps 0 0 0 0 0 30

gs -- hc.ps 30 0 0 0 0 30

gs -- hc.ps 0 0 0 30 30 30

gs -- hc.ps 45 45 45 0 0 0

gs -- hc.ps 45 45 45 45 45 45

Bonus animation I just made with this program.  This image corresponds to the rotation sequence 0 30 60 0 i i, where i ranges from 0 to 360 by 2.


问:
Convert the first letter of each word to uppercase, and the rest to lowercase

Description

Your task is to take a string as input, and convert the first letter of each word to uppercase, and the rest to lowercase.

Test Cases

Input => Output

ISN'T THIS A REALLY COOL TEST CASE??? => Isn't This A Really Cool Test Case???

tHis iS A rEALLY WeiRd SeNTEncE => This Is A Really Weird Sentence

I Like This Sentence => I Like This Sentence

Edit: no built-ins allowed.

This is code-golf, so lowest byte count wins. Good luck!

答:
Pyth, 6 bytes

```
<s>jdm+rhd1rtd0c</s>
jdrR4c
```

Test suite.

Split into words, capitalize each, then join by space.

It is not a built-in, because capitalize converts test case into Test case instead of Test Case.

(with built-ins)

```<code>r5
</code>```

Test suite.

Body:
Pyth, 6 bytes

<s>jdm+rhd1rtd0c</s>
jdrR4c

Test suite.

Split into words, capitalize each, then join by space.

It is not a built-in, because capitalize converts test case into Test case instead of Test Case.

(with built-ins)

r5

Test suite.


答:
V, <s>14</s> 8 bytes

```<code>gu$ògUlW
</code>```

Try it online!

Explanation:

```<code>gu$       #Make everything lowercase
   ò      #Recursively
    gUl   #Make the current character uppercase
       W  #And move forward a word
</code>```

Here is a 9-byte, non-competing version (the old interpreter had a bug):

```<code>gu$Ó¼÷/Õ°
</code>```

This version is just a regex:

```<code>gu$            #Make everything lowercase
   Ó¼÷/Õ°      #Expands into ':s/\<\w/\U\0/g`
</code>```

Title: Convert the first letter of each word to uppercase, and the rest to lowercase

Body:
Description

Your task is to take a string as input, and convert the first letter of each word to uppercase, and the rest to lowercase.

Test Cases

Input => Output

ISN'T THIS A REALLY COOL TEST CASE??? => Isn't This A Really Cool Test Case???

tHis iS A rEALLY WeiRd SeNTEncE => This Is A Really Weird Sentence

I Like This Sentence => I Like This Sentence

Edit: no built-ins allowed.

This is code-golf, so lowest byte count wins. Good luck!

Body:
V, <s>14</s> 8 bytes

gu$ògUlW

Try it online!

Explanation:

gu$       #Make everything lowercase
   ò      #Recursively
    gUl   #Make the current character uppercase
       W  #And move forward a word

Here is a 9-byte, non-competing version (the old interpreter had a bug):

gu$Ó¼÷/Õ°

This version is just a regex:

gu$            #Make everything lowercase
   Ó¼÷/Õ°      #Expands into ':s/\<\w/\U\0/g`


答:
Python, <s>51</s> bytes

3 bytes thanks to xnor.

```
<s>lambda n:' '.join(a.capitalize()for a in n.split())</s>
lambda n:' '.join(map(str.capitalize,n.split()))
```

Ideone it!

using built-in, 28 bytes

from string import*
capwords
```

Ideone it!

Body:
Python, <s>51</s> bytes

3 bytes thanks to xnor.

<s>lambda n:' '.join(a.capitalize()for a in n.split())</s>
lambda n:' '.join(map(str.capitalize,n.split()))

Ideone it!

using built-in, 28 bytes

from string import*
capwords

Ideone it!


答:
s-lang, 7 bytes (Non-competing)

Try it here!

```<code>w[ ]Cc!
</code>```

Explanation:

w[ ] splits the input string by spaces

C converts the selection (which is now the split-up words) to lower-case

c! c converts the selection to upper-case, but since it uses the parameter !, it only converts the first letter of each range of characters in the selection (which are words since we split by spaces)

Body:
s-lang, 7 bytes (Non-competing)

Try it here!

w[ ]Cc!

Explanation:

w[ ] splits the input string by spaces

C converts the selection (which is now the split-up words) to lower-case

c! c converts the selection to upper-case, but since it uses the parameter !, it only converts the first letter of each range of characters in the selection (which are words since we split by spaces)


答:
Ruby, 29 bytes

```<code>gets.gsub(/\S+/,&:capitalize)
</code>```

I'm still learning ruby though >_>

Body:
Ruby, 29 bytes

gets.gsub(/\S+/,&:capitalize)

I'm still learning ruby though >_>


答:
Retina, 19 bytes

```<code>T`L`l
T`l`L`(^|\s).
</code>```

Try it online!

Body:
Retina, 19 bytes

T`L`l
T`l`L`(^|\s).

Try it online!


答:
Pyke, 5 bytes

```<code>cml5J
</code>```

Try it here!

Split, map caps, join

Body:
Pyke, 5 bytes

cml5J

Try it here!

Split, map caps, join


问:
Return the integers with square digit-sums

Introduction and Credit

We all know and love our awesome rules to test whether a number is divisble by 11 or 3, which is just some clever sum over the digits of the number. Now this challenge takes this to a new level, by requiring you to compute the sum of the digits and then checking whether the result is a perfect integer square, neither of which operations usually can be done very short. As this property is also very hard to see when looking at a number, we want this to be done for entire lists of numbers so we can save human work. So this is your challenge now!

This was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitely).

Specification

Input

Your input is a list of non-negative integers, in any standard I/O format.

You may choose the list format as your language needs it

Output

The output is a list of integers, in any standard I/O format.

What to do?

Filter out every integer from the input list for which the sum of the digits is not a a square (of an integer).

The order of the elements may not be changed, e.g. if you get [1,5,9] you may not return [9,1]

Potential corner cases

0 is a non-negative integer and thus a valid input and 0 is also a valid integer root, e.g. 0 counts as an integer square.

The empty list is a valid input and output as well.

Who wins?

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

Standard rules apply of course.

Test Cases

```<code>[1,4,9,16,25,1111] -> [1,4,9,1111]
[1431,2,0,22,999999999] -> [1431,0,22,999999999]
[22228,4,113125,22345] -> [22228,4,22345]
[] -> []
[421337,99,123456789,1133557799] -> []
</code>```

Step-by-Step Example

```<code>Example input: [1337,4444]
Handling first number:
Sum of the digits of 1337: 1+3+3+7=14
14 is not an integer square, thus will be dropped!
Handling second number:
Sum of the digits of 4444: 4+4+4+4=16
16 is an integer square because 4*4=16, can get into the output list!
Example output: [4444]
</code>```

答:
Actually, 12 bytes

```<code>`$♂≈Σ;√≈²=`░
</code>```

Try it online!

Explanation:

```<code>`$♂≈Σ;√≈²=`░
`$♂≈Σ;√≈²=`░  filter list, taking only values where the following function is true:
 $♂≈Σ           to string, map int, sum (digital sum, we'll call this n)
     ;√≈²=      compare equality to int(sqrt(n))**2
</code>```

Body:
Actually, 12 bytes

`$♂≈Σ;√≈²=`░

Try it online!

Explanation:

`$♂≈Σ;√≈²=`░
`$♂≈Σ;√≈²=`░  filter list, taking only values where the following function is true:
 $♂≈Σ           to string, map int, sum (digital sum, we'll call this n)
     ;√≈²=      compare equality to int(sqrt(n))**2


问:
Fibonacci Factorization

Fibonacci Numbers

Fibonacci Numbers start with f(1) = 1 and f(2) = 1 (some includes f(0) = 0 but this is irrelevant to this challenge. Then, for n > 2, f(n) = f(n-1) + f(n-2).

The challenge

Your task is to find and output the n-th positive number that can be expressed as products of Fibonacci numbers. You can choose to make it 0-indexed or 1-indexed, whichever suits you better, but you must specify this in your answer.

Also, your answer must compute the 100th term in a reasonable time.

Testcases

```<code>n   result corresponding product (for reference)
1   1      1
2   2      2
3   3      3
4   4      2*2
5   5      5
6   6      2*3
7   8      2*2*2 or 8
8   9      3*3
9   10     2*5
10  12     2*2*3
11  13     13
12  15     3*5
13  16     2*2*2*2 or 2*8
14  18     2*3*3
15  20     2*2*5
16  21     21
17  24     2*2*2*3 or 3*8
18  25     5*5
19  26     2*13
20  27     3*3*3
100 315    3*5*21
</code>```

References

Obligatory OEIS A065108

答:
Julia, 79 bytes

!k=any(i->√(5i^2+[4,-4])%1∋k%i<!(k÷i),2:k)^~-k
<|(n,k=1)=n>0?n-!k<|-~k:~-k
```

Try it online!

Background

In Advanced Problems and Solutions, H-187: Fibonacci is a square, the proposer shows that

where Ln denotes the nth Lucas number, and that – conversely – if

then n is a Fibonacci number and m is a Lucas number.

How it works

We define the binary operator <| for our purposes. It is undefined in recent versions of Julia, but still recognized as an operator by the parser.

When called with only one argument (n), <| initializes k as 1. While n is positive, it subtracts !k (1 if k is a product of Fibonacci numbers, 0 if not) from n and recursively calls itself, increments k by 1. Once n reaches 0, the desired amount of products have been found, so <| returns the previous value of k, i.e., ~-k = k - 1.

The unary operator !, redefined as a test for Fibonacci number products, achieves its task as follows.

If k = 1, k is a product of Fibonacci numbers. In this case, we raise the return value of any(...) to the power ~-k = k - 1 = 0, so the result will be 1.

If k > 1, the result will be the value of any(....), which will return true if and only if the predicate √(5i^2+[4,-4])%1∋k%i<!(k÷i) returns true for some integer i such that 2 ≤ i ≤ k.

The chained conditions in the predicate hold if k%i belongs to √(5i^2+[4,-4])%1 and k%i is less than !(k÷i).

√(5i^2+[4,-4])%1 takes the square root of 5i2 + 4 and 5i2 - 4 and computes their residues modulo 1. Each modulus is 0 if the corresponding number is a perfect square, and a positive number less than 1 otherwise.

Since k%i returns an integer, it can only belong to the array of moduli if k % i = 0 (i.e., k is divisible by i) and at least one among 5i2 + 4 and 5i2 - 4 is a perfect square (i.e., i is a Fibonacci number).

!(k÷i) recursively calls 1 with argument k ÷ i (integer division), which will be greater than 0 if and only if k ÷ i is a product of Fibonacci numbers.

By induction, ! has the desired property.

Title: Fibonacci Factorization

Body:
Julia, 79 bytes

!k=any(i->√(5i^2+[4,-4])%1∋k%i<!(k÷i),2:k)^~-k
<|(n,k=1)=n>0?n-!k<|-~k:~-k

Try it online!

Background

In Advanced Problems and Solutions, H-187: Fibonacci is a square, the proposer shows that

where Ln denotes the nth Lucas number, and that – conversely – if

then n is a Fibonacci number and m is a Lucas number.

How it works

We define the binary operator <| for our purposes. It is undefined in recent versions of Julia, but still recognized as an operator by the parser.

When called with only one argument (n), <| initializes k as 1. While n is positive, it subtracts !k (1 if k is a product of Fibonacci numbers, 0 if not) from n and recursively calls itself, increments k by 1. Once n reaches 0, the desired amount of products have been found, so <| returns the previous value of k, i.e., ~-k = k - 1.

The unary operator !, redefined as a test for Fibonacci number products, achieves its task as follows.

If k = 1, k is a product of Fibonacci numbers. In this case, we raise the return value of any(...) to the power ~-k = k - 1 = 0, so the result will be 1.

If k > 1, the result will be the value of any(....), which will return true if and only if the predicate √(5i^2+[4,-4])%1∋k%i<!(k÷i) returns true for some integer i such that 2 ≤ i ≤ k.

The chained conditions in the predicate hold if k%i belongs to √(5i^2+[4,-4])%1 and k%i is less than !(k÷i).

√(5i^2+[4,-4])%1 takes the square root of 5i2 + 4 and 5i2 - 4 and computes their residues modulo 1. Each modulus is 0 if the corresponding number is a perfect square, and a positive number less than 1 otherwise.

Since k%i returns an integer, it can only belong to the array of moduli if k % i = 0 (i.e., k is divisible by i) and at least one among 5i2 + 4 and 5i2 - 4 is a perfect square (i.e., i is a Fibonacci number).

!(k÷i) recursively calls 1 with argument k ÷ i (integer division), which will be greater than 0 if and only if k ÷ i is a product of Fibonacci numbers.

By induction, ! has the desired property.


问:
Capitalize first letter of each word of input
This is a relatively quick one, but I'm sure you'll like it.

Codegolf a program that will take input in the form of a sentence and then provide the output with the first letter capitalized in each word.

Rules:

Submissions may not be in the form of a function. So no:

function x(y){z=some_kind_of_magic(y);return z;} as your final answer... Your code must show that it takes input, and provides output.

The code must preserve any other capital letters the input has. So

```<code>eCommerce and eBusiness are cool, don't you agree, Richard III?
</code>```

will be rendered as

```<code>ECommerce And EBusiness Are Cool, Don't You Agree, Richard III?
</code>```

Some of you may be thinking, "Easy, I'll just use regex!" and so using the native regex in your chosen golfing language will incur a 30 character penalty which will be applied to your final code count. Evil laugh

A "word" in this case is anything separated by a space. Therefore palate cleanser is two words, whereas pigeon-toed is considered one word. if_you_love_her_then_you_should_put_a_ring_on_it is considered one word. If a word starts with a non-alphabetical character, the word is preserved, so _this after rendering remains as _this. (Kudos to Martin Buttner for pointing this test case out).

4b. There is no guarantee that words in the input phrase will be separated by a single space.

Test Case, (please use to test your code):

Input:

```<code>eCommerce rocks. crazyCamelCase stuff. _those  pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye
</code>```

Output:

```<code>ECommerce Rocks. CrazyCamelCase Stuff. _those  Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye
</code>```

This is code golf, shortest code wins...

Good luck...

答:
Vim, <s>11</s>, 10 bytes

```<code>qqvUW@qq@q
</code>```

Explanation:

```<code>qq           #Start recording in register 'q'
  vU        #Make the character under the cursor uppercase
     W       #Move forward a WORD
      @q     #recursively call macro 'q'
        q    #stop recording
         @q  #Call the recursive macro
</code>```

Do I get a gold-badge for outgolfing Dennis?

Body:
Vim, <s>11</s>, 10 bytes

qqvUW@qq@q

Explanation:

qq           #Start recording in register 'q'
  vU        #Make the character under the cursor uppercase
     W       #Move forward a WORD
      @q     #recursively call macro 'q'
        q    #stop recording
         @q  #Call the recursive macro

Do I get a gold-badge for outgolfing Dennis?


问:
Lithp Tranthlator
My friend made a lisp translator the other day, that is to say it took a string and converted s=>th and S=>Th. It was quite long and I thought that it could be golfed.

So the task is to make a program/function that takes an input string, translates it in to lisp and outputs the string

Test case

```<code>Sam and Sally like Sheep        Tham and Thally like Thheep
Sally likes sausages            Thally liketh thauthageth
Sally sells seashells           Thally thellth theathhellth
</code>```

Note that it doesn't matter that h gets repeated all the time

This is code golf so shortest answer wins

答:
GNU AWK, 31 bytes

Just using gsub function to translate lower or upper S via regex and print it afterwards.  Can work with files, or with stdin as in this case

```<code>$ awk '{gsub(/s/,"th");gsub(/S/,"Th")}1' <<< "This is Sparta"
Thith ith Thparta
</code>```

Title: Lithp Tranthlator

Body:
GNU AWK, 31 bytes

Just using gsub function to translate lower or upper S via regex and print it afterwards.  Can work with files, or with stdin as in this case

$ awk '{gsub(/s/,"th");gsub(/S/,"Th")}1' <<< "This is Sparta"
Thith ith Thparta


答:
Jelly, 9 bytes

```<code>ṣ⁶Œu1¦€j⁶
</code>```

Try it online!

How it works

```<code>ṣ⁶Œu1¦€j⁶  Main link. Argument: s (string)

ṣ⁶         Split s at spaces.
      €    Each; map this over the chunks:
    1¦       Apply this to the first character:
  Œu           Uppercase.
       j⁶  Join, separating by spaces.
</code>```

Title: Capitalize first letter of each word of input

Body:
This is a relatively quick one, but I'm sure you'll like it.

Codegolf a program that will take input in the form of a sentence and then provide the output with the first letter capitalized in each word.

Rules:

Submissions may not be in the form of a function. So no:

function x(y){z=some_kind_of_magic(y);return z;} as your final answer... Your code must show that it takes input, and provides output.

The code must preserve any other capital letters the input has. So

```<code>eCommerce and eBusiness are cool, don't you agree, Richard III?
</code>```

will be rendered as

```<code>ECommerce And EBusiness Are Cool, Don't You Agree, Richard III?
</code>```

Some of you may be thinking, "Easy, I'll just use regex!" and so using the native regex in your chosen golfing language will incur a 30 character penalty which will be applied to your final code count. Evil laugh

A "word" in this case is anything separated by a space. Therefore palate cleanser is two words, whereas pigeon-toed is considered one word. if_you_love_her_then_you_should_put_a_ring_on_it is considered one word. If a word starts with a non-alphabetical character, the word is preserved, so _this after rendering remains as _this. (Kudos to Martin Buttner for pointing this test case out).

4b. There is no guarantee that words in the input phrase will be separated by a single space.

Test Case, (please use to test your code):

Input:

```<code>eCommerce rocks. crazyCamelCase stuff. _those  pigeon-toed shennanigans. Fiery trailblazing 345 thirty-two Roger. The quick brown fox jumped over the lazy dogs. Clancy Brown would have been cool as Lex Luthor. good_bye
</code>```

Output:

```<code>ECommerce Rocks. CrazyCamelCase Stuff. _those  Pigeon-toed Shennanigans. Fiery Trailblazing 345 Thirty-two Roger. The Quick Brown Fox Jumped Over The Lazy Dogs. Clancy Brown Would Have Been Cool As Lex Luthor. Good_bye
</code>```

This is code golf, shortest code wins...

Good luck...

Body:
Jelly, 9 bytes

ṣ⁶Œu1¦€j⁶

Try it online!

How it works

ṣ⁶Œu1¦€j⁶  Main link. Argument: s (string)

ṣ⁶         Split s at spaces.
      €    Each; map this over the chunks:
    1¦       Apply this to the first character:
  Œu           Uppercase.
       j⁶  Join, separating by spaces.


答:
V, 5 (non-competing)

```<code>$òBvU
</code>```

Try it online!

Not too interesting. Just a direct port of my vim answer:

```<code>$        #Move to the last character
 ò       #Recursively
  B      #Move back a WORD
   vU    #Capitalize
</code>```

Body:
V, 5 (non-competing)

$òBvU

Try it online!

Not too interesting. Just a direct port of my vim answer:

$        #Move to the last character
 ò       #Recursively
  B      #Move back a WORD
   vU    #Capitalize


答:
Python, 90 bytes

f=lambda n,a=2,b=3:n<2or n%a<f(n/a)or n-a>0<f(n,b,a+b)
g=lambda k,n=1:k and-~g(k-f(n),n+1)
```
<p>The main function <code>g</code> outputs the <code>k</code>th Fibonacci product, 1-indexed. It computes <code>g(100)</code> as <code>315</code> almost instantly. It goes so with a general recursive recipe of counting up numbers <code>n</code> looking for <code>k</code> instances that satisfy the function <code>f</code>. Each such instance lowers the required count <code>k</code> until it reaches <code>0</code>.</p>
<p>The auxiliary function <code>f</code> tests a number for being a Fibonacci product. It recursively generates the Fibonacci numbers in its optional arguments <code>a</code> and <code>b</code>. It outputs "yes" if any of the following is true:</p>
<ul>
<li><code>n<2</code>. This implies <code>n==1</code>, the trivial product)</li>
<li><code>n%a<f(n/a)</code>. This requires <code>n%a==0</code> and <code>f(n/a)==True</code>, i.e. that <code>n</code> is a multiple of the Fibonacci number <code>a</code>, and removing this factor of <code>a</code> still yield a Fibonacci product.</li>
<li><code>n-a>0<f(n,b,a+b)</code>, equivalent to <code>n>a and f(n,b,a+b)</code>. Checks that the current Fibonacci number being tested isn't at least <code>n</code>, and some greater Fibonacci number works. Thanks to Dennis for 2 saving bytes using the inequality short-circuit instead of <code>and</code>.</li>
</ul>
<p>The function <code>g</code> can be one byte shorter as</p>
<pre class="lang-python prettyprint-override"><code>lambda k:filter(f,range(k*k+1))[k]
</code>```

if g(k) is always at most k*k, which I'm not sure is asymptotically true. A bound of 2**k suffices, but then g(100) takes too long. Maybe instead the recursive of g can be done in f.

Title: Fibonacci Factorization

Body:
Fibonacci Numbers

Fibonacci Numbers start with f(1) = 1 and f(2) = 1 (some includes f(0) = 0 but this is irrelevant to this challenge. Then, for n > 2, f(n) = f(n-1) + f(n-2).

The challenge

Your task is to find and output the n-th positive number that can be expressed as products of Fibonacci numbers. You can choose to make it 0-indexed or 1-indexed, whichever suits you better, but you must specify this in your answer.

Also, your answer must compute the 100th term in a reasonable time.

Testcases

```<code>n   result corresponding product (for reference)
1   1      1
2   2      2
3   3      3
4   4      2*2
5   5      5
6   6      2*3
7   8      2*2*2 or 8
8   9      3*3
9   10     2*5
10  12     2*2*3
11  13     13
12  15     3*5
13  16     2*2*2*2 or 2*8
14  18     2*3*3
15  20     2*2*5
16  21     21
17  24     2*2*2*3 or 3*8
18  25     5*5
19  26     2*13
20  27     3*3*3
100 315    3*5*21
</code>```

References

Obligatory OEIS A065108

Body:
Python, 90 bytes

f=lambda n,a=2,b=3:n<2or n%a<f(n/a)or n-a>0<f(n,b,a+b)
g=lambda k,n=1:k and-~g(k-f(n),n+1)

The main function g outputs the kth Fibonacci product, 1-indexed. It computes g(100) as 315 almost instantly. It goes so with a general recursive recipe of counting up numbers n looking for k instances that satisfy the function f. Each such instance lowers the required count k until it reaches 0.

The auxiliary function f tests a number for being a Fibonacci product. It recursively generates the Fibonacci numbers in its optional arguments a and b. It outputs "yes" if any of the following is true:

n<2. This implies n==1, the trivial product)

n%a<f(n/a). This requires n%a==0 and f(n/a)==True, i.e. that n is a multiple of the Fibonacci number a, and removing this factor of a still yield a Fibonacci product.

n-a>0<f(n,b,a+b), equivalent to n>a and f(n,b,a+b). Checks that the current Fibonacci number being tested isn't at least n, and some greater Fibonacci number works. Thanks to Dennis for 2 saving bytes using the inequality short-circuit instead of and.

The function g can be one byte shorter as

lambda k:filter(f,range(k*k+1))[k]

if g(k) is always at most k*k, which I'm not sure is asymptotically true. A bound of 2**k suffices, but then g(100) takes too long. Maybe instead the recursive of g can be done in f.


答:
JavaScript (ES6), 136

Quite slow golfed this way, computing term 100 in about 8 seconds in my PC.

(n,F=i=>i>1?F(i-1)+F(i-2):i+1,K=(n,i=1,d,x)=>eval('for(;(d=F(i++))<=n&&!(x=!(n%d)&&K(n/d)););x||n<2'))=>eval('for(a=0;n;)K(++a)&&--n;a')
```

<p><em>Less golfed</em> and faster too (avoiding <code>eval</code>)</p>

<pre class="lang-js prettyprint-override"><code>n=>{
  F=i=> i>1 ? F(i-1)+F(i-2) : i+1; // recursive calc Fibonacci number
  K=(n,i=1,d,x)=>{ // recursive check divisibility
    for(; (d=F(i++))<=n && !(x=!(n%d)&&K(n/d)); );
    return x||n<2
  };
  for(a=0; n; )
    K(++a) && --n;
  return a
}
</code>```

Test

X=(n,F=i=>i>1?F(i-1)+F(i-2):i+1,K=(n,i=1,d,x)=>eval('for(;(d=F(i++))<=n&&!(x=!(n%d)&&K(n/d)););x||n<2'))=>eval('for(a=0;n;)K(++a)&&--n;a')

function test() {
  var i=+I.value
  O.textContent=X(i)
}

test()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id=I value=100 >
<button onclick="test()">Go</button><pre id=O>``````

Title: Fibonacci Factorization

Body:
JavaScript (ES6), 136

Quite slow golfed this way, computing term 100 in about 8 seconds in my PC.

(n,F=i=>i>1?F(i-1)+F(i-2):i+1,K=(n,i=1,d,x)=>eval('for(;(d=F(i++))<=n&&!(x=!(n%d)&&K(n/d)););x||n<2'))=>eval('for(a=0;n;)K(++a)&&--n;a')

Less golfed and faster too (avoiding eval)

n=>{
  F=i=> i>1 ? F(i-1)+F(i-2) : i+1; // recursive calc Fibonacci number
  K=(n,i=1,d,x)=>{ // recursive check divisibility
    for(; (d=F(i++))<=n && !(x=!(n%d)&&K(n/d)); );
    return x||n<2
  };
  for(a=0; n; )
    K(++a) && --n;
  return a
}

Test

X=(n,F=i=>i>1?F(i-1)+F(i-2):i+1,K=(n,i=1,d,x)=>eval('for(;(d=F(i++))<=n&&!(x=!(n%d)&&K(n/d)););x||n<2'))=>eval('for(a=0;n;)K(++a)&&--n;a')

function test() {
  var i=+I.value
  O.textContent=X(i)
}

test()

<input id=I value=100 >
<button onclick="test()">Go</button><pre id=O></pre>


问:
The handshake problem
The handshake problem is the classic problem that for n people in a room, if they all shake hands, what's the total number of handshakes that occur.

You code should take an input of any number and output the number of handshakes, both in base ten.

Also the code should not let non-integers through. You should output a falsey in this case. The only expected inputs are positive whole integers and positive real numbers - you don't need to worry about complex numbers or strings as inputs.
This should mean that you should expect n >= 0

Test cases

```<code>(N:handshakes)
0:0
10:45
20:190
10.5:0
1337:893116
</code>```

Normal golfing rules apply and shortest code wins.
If your code isn't self explanatory, please explain.

Jelly and 05AB1E are the winners, both at 2 bytes

答:
Golisp, 18 bytes

```<code>{(n)~[+range[1n]]}
</code>```

Python equivalent: lambda n: sum(range(1, n)).

Oh and Golisp don't have floating point number (for now)

Title: The handshake problem

Body:
Golisp, 18 bytes

{(n)~[+range[1n]]}

Python equivalent: lambda n: sum(range(1, n)).

Oh and Golisp don't have floating point number (for now)


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

There are exactly 16 of them, because:

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

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

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

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

Your functions/programs must be independent.

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

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

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

0,0,1,1 (A)

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

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

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

1,1,0,0 (not A)

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

1,1,1,0 (nand)

1,1,1,1 (true)

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

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Brian & Chuck, 183 bytes

Thanks to Sp3000 for saving 4 bytes.

Some of the programs contain an unprintable character. In particular, every \x01 should be replaced with the <SOH> (0x01) control character:

```<code>0000
?
#>.
0001
,-?,-?>?\x01
#}>.
0010
,-?,?>?\x01
#}>.
0011
,?\x01+?
#>.
0100
,?,-?>?\x01
#}>.
0101
,,?\x01+?
#>.
0110
,?>},?>?_\x01
#}+{>?_}>.
0111
,\x01?,?>?
#{>.
1000
,?,?>?\x01
#}>.
1001
,-?>},?>?_\x01
#}+{>>?_}>.
1010
,,-?\x01+?
#>.
1011
,\x01?,-?>?
#{>.
1100
,-?\x01+?
#>.
1101
,\x01-?,?>?
#{>.
1110
,\x01-?,-?>?
#{>.
1111
?
#>+.
</code>```

Input and output use byte values, so input should be two 0x00 or 0x01 bytes (without separator) and output will be one such byte. This is actually also the most sensible definition of truthy/falsy for B&C because the only control flow command ? regards zeros as falsy and everything else truthy.

Explanations

First a quick B&C primer:

Every program consists of two Brainfuck-like instances, each written on its own line. We call the first one Brian and the second one Chuck. Execution begins on Brian.

Each program's tape is the other program's source code, and each program's instruction pointer is the other program's tape head.

Only Brian can use the , (input byte) command and only Chuck can use the . (output byte) command.

Brainfuck's [] loop does not exist. Instead, the only control flow you have is ? which switches control to the other instance iff the current value under the tape head is nonzero.

In addition to > and <, there's { and } which are essentially equivalent to the Brainfuck snippets [<] and [>], that is, they move the tape head to the next zero position in that direction. The main difference is that { can also be stopped at the left end of the tape, regardless of what value it has.

For convenience, any _s in the source code are replaced with null-bytes (as these are very useful in nontrivial programs in order to catch { and }).

Note that in all programs, Chuck's tape begins with a #. This could really be anything. ? works such that the tape head moves one cell before starting execution (so that the condition itself isn't executed if it happens to be a valid command). So we can't ever use the first cell of Chuck for code.

There are five classes of programs, which I'll explain in detail later. For now I'm listing them here in order of increasing complexity.

0000, 1111: Constant functions

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

```<code>?
#>+.
</code>```

These are very simple. We switch to Chuck unconditionally. Chuck moves the tape head to the unused cell to the right and either prints it directly, or increments it first to print 1.

0011, 0101, 1010, 1100: Functions depending on only one input

```<code>,?\x01+?
#>.
</code>```

```<code>,,?\x01+?
#>.
</code>```

```<code>,,-?\x01+?
#>.
</code>```

```<code>,-?\x01+?
#>.
</code>```

Depending on whether we start with , or ,, we're working with A or B. Let's look at the first example 0011 (i.e. A). After reading the value, we use ? as a conditional on that value. If A = 1, then this switches to Chuck, who moves the tape head to the right and prints the literally embedded 1-byte. Otherwise, control remains on Brian. Here, the 1-byte is a no-op. Then we increment the input well with + to make sure it's non-zero and then switch to Chuck with ?. This time, > moves to an unused cell to the right which is then printed as 0.

In order to negated one of the values we simply decrement it with -. This turns 1 into 0 and 0 into -1, which is non-zero and hence truthy as far as ? is concerned.

0001, 0010, 0100, 1000: Binary functions with one truthy result

```<code>,-?,-?>?\x01
#}>.
</code>```

```<code>,-?,?>?\x01
#}>.
</code>```

```<code>,?,-?>?\x01
#}>.
</code>```

```<code>?
#>.
</code>```0

This is an extension of the previous idea in order to work with two inputs. Let's look at the example of 1000 (NOR). We (potentially) read both inputs with ,?. If either of those is 1, the ? switches to Chuck. He moves the tape head to the end with } (onto the empty cell after Brian's code), moves another cell with > (still zero) and prints it with ..

However, if both inputs are zero, then control is still with Brian. > then moves the tape head onto the } such that this command isn't executed when we switch to Chuck with ?. Now all that Chuck does is >. which only moves onto the 1-cell and prints that.

We can easily obtain the other three functions by negating one or both of the inputs as required.

0111, 1011, 1101, 1110: Binary functions with three truthy results

```<code>?
#>.
</code>```1

```<code>?
#>.
</code>```2

```<code>,\x01-?,?>?
#{>.
</code>```

```<code>,\x01-?,-?>?
#{>.
</code>```

A minor modification of the previous idea in order to negated the result (i.e. print 0 when we've passed through all of Brian and 1 otherwise). Let's look at 0111 (OR) as an example. Note that the embedded 1-byte is a no-op, so this still starts with ,?,?. If either input is 1 we switch to Chuck, who moves the tape head back to the start with {. >. moves the tape head onto that 1-byte and prints it.

If both inputs are zero then we remain with Brian, move the tape head onto { to skip it and then switch to Chuck. When he executes >. this time he moves onto the empty cell after Brian's code and prints the 0.

Again, we easily obtain the other functions by negating one or both inputs.

0110, 1001: Binary functions with two truthy results

```<code>,?>},?>?_\x01
#}+{>?_}>.
</code>```

```<code>,-?>},?>?_\x01
#}+{>>?_}>.
</code>```

This one is a bit trickier. The previous functions were reasonably simple because they can be short-circuited - the value of the first input can decide the output, and if it doesn't then we look at the other input. For these two functions, we always need to look at both inputs.

The basic idea is to use the first input to decide whether the second input choose between 0 and 1 or between 1 and 0. Let's take 0110 (XOR) as an example:

Consider A = 0. In this case we want to output B as is. , reads A, ? does nothing. > moves onto the next (nonzero) cell so that } brings us to the _ on Chuck. Here, we read B with , and use ? again. If B was 0 as well, we're still on Brian. > skips the } on Chuck and ? switches so that the >. prints the 0 embedded in Brian's source code. If B was 1 on the other hand, Chuck does execute the } which moves into the _ in Brian's code already, so the >. then prints the 1-byte instead.

If A = 1, then we do switch to Chuck right away, who will execute }+{>?. What this does is move to the _ in Brian's source code, turns it into a 1 as well with +, then moves back to the start { and skips Brian's ? by moving one cell to the right with > before handing control back to him. This time, after Brian read's B, if B = 0, and Chuck uses >. the cell next to Brian's ? will be 1 instead of 0. Also, when B = 1, Chuck's } skips right over what to used to be a gap and moves all the way to the end of the tape, so that >. prints a zero instead. This way we're printing not B.

In order to implement equivalence, we simply negated A before using it as a condition. Note that due to this we also need to add another > to Chuck to skip that - as well when moving back to the start.

Body:
Brian & Chuck, 183 bytes

Thanks to Sp3000 for saving 4 bytes.

Some of the programs contain an unprintable character. In particular, every \x01 should be replaced with the <SOH> (0x01) control character:

0000
?
#>.
0001
,-?,-?>?\x01
#}>.
0010
,-?,?>?\x01
#}>.
0011
,?\x01+?
#>.
0100
,?,-?>?\x01
#}>.
0101
,,?\x01+?
#>.
0110
,?>},?>?_\x01
#}+{>?_}>.
0111
,\x01?,?>?
#{>.
1000
,?,?>?\x01
#}>.
1001
,-?>},?>?_\x01
#}+{>>?_}>.
1010
,,-?\x01+?
#>.
1011
,\x01?,-?>?
#{>.
1100
,-?\x01+?
#>.
1101
,\x01-?,?>?
#{>.
1110
,\x01-?,-?>?
#{>.
1111
?
#>+.

Input and output use byte values, so input should be two 0x00 or 0x01 bytes (without separator) and output will be one such byte. This is actually also the most sensible definition of truthy/falsy for B&C because the only control flow command ? regards zeros as falsy and everything else truthy.

Explanations

First a quick B&C primer:

Every program consists of two Brainfuck-like instances, each written on its own line. We call the first one Brian and the second one Chuck. Execution begins on Brian.

Each program's tape is the other program's source code, and each program's instruction pointer is the other program's tape head.

Only Brian can use the , (input byte) command and only Chuck can use the . (output byte) command.

Brainfuck's [] loop does not exist. Instead, the only control flow you have is ? which switches control to the other instance iff the current value under the tape head is nonzero.

In addition to > and <, there's { and } which are essentially equivalent to the Brainfuck snippets [<] and [>], that is, they move the tape head to the next zero position in that direction. The main difference is that { can also be stopped at the left end of the tape, regardless of what value it has.

For convenience, any _s in the source code are replaced with null-bytes (as these are very useful in nontrivial programs in order to catch { and }).

Note that in all programs, Chuck's tape begins with a #. This could really be anything. ? works such that the tape head moves one cell before starting execution (so that the condition itself isn't executed if it happens to be a valid command). So we can't ever use the first cell of Chuck for code.

There are five classes of programs, which I'll explain in detail later. For now I'm listing them here in order of increasing complexity.

0000, 1111: Constant functions

?
#>.

?
#>+.

These are very simple. We switch to Chuck unconditionally. Chuck moves the tape head to the unused cell to the right and either prints it directly, or increments it first to print 1.

0011, 0101, 1010, 1100: Functions depending on only one input

,?\x01+?
#>.

,,?\x01+?
#>.

,,-?\x01+?
#>.

,-?\x01+?
#>.

Depending on whether we start with , or ,, we're working with A or B. Let's look at the first example 0011 (i.e. A). After reading the value, we use ? as a conditional on that value. If A = 1, then this switches to Chuck, who moves the tape head to the right and prints the literally embedded 1-byte. Otherwise, control remains on Brian. Here, the 1-byte is a no-op. Then we increment the input well with + to make sure it's non-zero and then switch to Chuck with ?. This time, > moves to an unused cell to the right which is then printed as 0.

In order to negated one of the values we simply decrement it with -. This turns 1 into 0 and 0 into -1, which is non-zero and hence truthy as far as ? is concerned.

0001, 0010, 0100, 1000: Binary functions with one truthy result

,-?,-?>?\x01
#}>.

,-?,?>?\x01
#}>.

,?,-?>?\x01
#}>.

,?,?>?\x01
#}>.

This is an extension of the previous idea in order to work with two inputs. Let's look at the example of 1000 (NOR). We (potentially) read both inputs with ,?. If either of those is 1, the ? switches to Chuck. He moves the tape head to the end with } (onto the empty cell after Brian's code), moves another cell with > (still zero) and prints it with ..

However, if both inputs are zero, then control is still with Brian. > then moves the tape head onto the } such that this command isn't executed when we switch to Chuck with ?. Now all that Chuck does is >. which only moves onto the 1-cell and prints that.

We can easily obtain the other three functions by negating one or both of the inputs as required.

0111, 1011, 1101, 1110: Binary functions with three truthy results

,\x01?,?>?
#{>.

,\x01?,-?>?
#{>.

,\x01-?,?>?
#{>.

,\x01-?,-?>?
#{>.

A minor modification of the previous idea in order to negated the result (i.e. print 0 when we've passed through all of Brian and 1 otherwise). Let's look at 0111 (OR) as an example. Note that the embedded 1-byte is a no-op, so this still starts with ,?,?. If either input is 1 we switch to Chuck, who moves the tape head back to the start with {. >. moves the tape head onto that 1-byte and prints it.

If both inputs are zero then we remain with Brian, move the tape head onto { to skip it and then switch to Chuck. When he executes >. this time he moves onto the empty cell after Brian's code and prints the 0.

Again, we easily obtain the other functions by negating one or both inputs.

0110, 1001: Binary functions with two truthy results

,?>},?>?_\x01
#}+{>?_}>.

,-?>},?>?_\x01
#}+{>>?_}>.

This one is a bit trickier. The previous functions were reasonably simple because they can be short-circuited - the value of the first input can decide the output, and if it doesn't then we look at the other input. For these two functions, we always need to look at both inputs.

The basic idea is to use the first input to decide whether the second input choose between 0 and 1 or between 1 and 0. Let's take 0110 (XOR) as an example:

Consider A = 0. In this case we want to output B as is. , reads A, ? does nothing. > moves onto the next (nonzero) cell so that } brings us to the _ on Chuck. Here, we read B with , and use ? again. If B was 0 as well, we're still on Brian. > skips the } on Chuck and ? switches so that the >. prints the 0 embedded in Brian's source code. If B was 1 on the other hand, Chuck does execute the } which moves into the _ in Brian's code already, so the >. then prints the 1-byte instead.

If A = 1, then we do switch to Chuck right away, who will execute }+{>?. What this does is move to the _ in Brian's source code, turns it into a 1 as well with +, then moves back to the start { and skips Brian's ? by moving one cell to the right with > before handing control back to him. This time, after Brian read's B, if B = 0, and Chuck uses >. the cell next to Brian's ? will be 1 instead of 0. Also, when B = 1, Chuck's } skips right over what to used to be a gap and moves all the way to the end of the tape, so that >. prints a zero instead. This way we're printing not B.

In order to implement equivalence, we simply negated A before using it as a condition. Note that due to this we also need to add another > to Chuck to skip that - as well when moving back to the start.


问:
Find operations required to get result
So task is simple, given array of numbers and result, you need to find what operations you need to use on numbers from array , to obtain requested result.

Let's make it simple for start, and allow only basic operations such as: addition, subtraction, multiplication and division.

Example:

```<code>Input  : [5,5,5,5,5] 100
Output : 5*5*5-5*5
</code>```

To give some advantage to languages like Java, request is to implement function, not entire program, and result can be return via parameter or print to console.

Code is scored based on amount bytes, and as it's golf code challenge, lowest score wins.

Another requirment is <s>You can get additional -10 points</s> if for array contains only digids, support solutions where you could construct numbers from following digits.
Ie

```<code>Input  : [1,2,3,4,5] 0
Output : 12-3-4-5
</code>```

Note that, provided outputs are proposed outputs, some cases might have more than one solution. It's up to you will you provide one or more solutions for given task.

EDIT:
Result has to be valid from mathematical point of view, hence division is rational division, not integer, and operation precedence is same as in classical math (first multiplication and division then addition and subtraction).

答:
JavaScript (ES6), 88 bytes

```<code>a=>o=>eval(`while(eval(e=(a+'').replace(/,/g,_=>'+-*/'.charAt(Math.random()*5)))!=o);e`)
</code>```

Threw in a little randomness to the mix. Much easier than systematically iterating through the combinations.

Test Suite

f=a=>o=>eval(`while(eval(e=(a+'').replace(/,/g,_=>'+-*/'.charAt(Math.random()*5)))!=o);e`)
console.log(f([5,5,5,5,5])(100))
console.log(f([1,2,3,4,5])(0))
console.log(f([3,4])(0.75))
console.log(f([3,4,5,6])(339))```

Title: Find operations required to get result

Body:
JavaScript (ES6), 88 bytes

a=>o=>eval(`while(eval(e=(a+'').replace(/,/g,_=>'+-*/'.charAt(Math.random()*5)))!=o);e`)

Threw in a little randomness to the mix. Much easier than systematically iterating through the combinations.

Test Suite

f=a=>o=>eval(`while(eval(e=(a+'').replace(/,/g,_=>'+-*/'.charAt(Math.random()*5)))!=o);e`)
console.log(f([5,5,5,5,5])(100))
console.log(f([1,2,3,4,5])(0))
console.log(f([3,4])(0.75))
console.log(f([3,4,5,6])(339))


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

This is the mathematical representation:

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

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

Your program/method should return the answer.

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

Test case (Base 10)

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

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

答:
Brachylog, 24 bytes

```<code>:efL:{:2^.}a+S,L+:2^:S-.
</code>```

Expects the 2 numbers in Input as a list, e.g. [91:123].

Explanation

```<code>:efL                     Find the list L of all integers in the range given in Input
    :{:2^.}a             Apply squaring to each element of that list
            +S,          Unify S with the sum of the elements of that list
               L+:2^     Sum the elements of L, then square the result
                    :S-. Unify the Output with that number minus S
</code>```

Title: Difference of the square of the sum

Body:
Brachylog, 24 bytes

:efL:{:2^.}a+S,L+:2^:S-.

Expects the 2 numbers in Input as a list, e.g. [91:123].

Explanation

:efL                     Find the list L of all integers in the range given in Input
    :{:2^.}a             Apply squaring to each element of that list
            +S,          Unify S with the sum of the elements of that list
               L+:2^     Sum the elements of L, then square the result
                    :S-. Unify the Output with that number minus S


答:
Python, 62 bytes

lambda a,b:sum(range(a,b+1))**2-sum(x*x for x in range(a,b+1))
```

<p>Or, longer:</p>

<pre class="lang-python prettyprint-override"><code>lambda a,b:sum(sum(x*y for y in range(a,b+1)if x-y)for x in range(a,b+1))
</code>```

Ideone both!

Title: Difference of the square of the sum

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

This is the mathematical representation:

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

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

Your program/method should return the answer.

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

Test case (Base 10)

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

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

Body:
Python, 62 bytes

lambda a,b:sum(range(a,b+1))**2-sum(x*x for x in range(a,b+1))

Or, longer:

lambda a,b:sum(sum(x*y for y in range(a,b+1)if x-y)for x in range(a,b+1))

Ideone both!


Title: Difference of the square of the sum

Body:
APL, <s>23</s> 20 bytes

-/+/¨2*⍨{(+/⍵)⍵}⎕..⎕

Works in NARS2000.


答:
CJam, 17 bytes

```<code>q~),>_:+2#\2f#:+-
</code>```

Test it here.

Explanation

```<code>q~       e# Read and evaluate input, dumping M and N on the stack.
),       e# Increment, create range [0 1 ... N].
>        e# Discard first M elements, yielding [M M+1 ... N].
_        e# Duplicate.
:+2#     e# Sum and square.
\2f#:+   e# Swap with other copy. Square and sum.
-        e# Subtract.
</code>```

Alternatively, one can just sum the products of all distinct pairs (basically multiplying out the square of the sum, and removing squares), but that's a byte longer:

```<code>q~),>2m*{)-},::*:+
</code>```

Title: Difference of the square of the sum

Body:
CJam, 17 bytes

q~),>_:+2#\2f#:+-

Test it here.

Explanation

q~       e# Read and evaluate input, dumping M and N on the stack.
),       e# Increment, create range [0 1 ... N].
>        e# Discard first M elements, yielding [M M+1 ... N].
_        e# Duplicate.
:+2#     e# Sum and square.
\2f#:+   e# Swap with other copy. Square and sum.
-        e# Subtract.

Alternatively, one can just sum the products of all distinct pairs (basically multiplying out the square of the sum, and removing squares), but that's a byte longer:

q~),>2m*{)-},::*:+


答:
Jelly, <s>9</s> 8 bytes

```<code>rµS²_²S$
</code>```

Try it online!

```<code>r         inclusive range from first input to second input
 µ        pass the range to a new monadic chain
  S       the sum
   ²      squared
    _     minus...
     ²S$  the squares summed
</code>```

Thanks to FryAmTheEggman for a byte!

Title: Difference of the square of the sum

Body:
Jelly, <s>9</s> 8 bytes

rµS²_²S$

Try it online!

r         inclusive range from first input to second input
 µ        pass the range to a new monadic chain
  S       the sum
   ²      squared
    _     minus...
     ²S$  the squares summed

Thanks to FryAmTheEggman for a byte!


答:
MATL, 11 bytes

```<code>&:ts2^w2^s-
</code>```

Try it online!

Explanation:

```<code>&:           #Create a range from the input
  t          #Duplicate it
   s2^       #Sum it and square it
      w      #swap the two ranges
       2^s   #Square it and sum it
          -  #Take the difference
</code>```

Title: Difference of the square of the sum

Body:
MATL, 11 bytes

&:ts2^w2^s-

Try it online!

Explanation:

&:           #Create a range from the input
  t          #Duplicate it
   s2^       #Sum it and square it
      w      #swap the two ranges
       2^s   #Square it and sum it
          -  #Take the difference


答:
PowerShell v2+, 47 bytes

Two variations

```<code>param($n,$m)$n..$m|%{$o+=$_;$p+=$_*$_};$o*$o-$p

$args-join'..'|iex|%{$o+=$_;$p+=$_*$_};$o*$o-$p
</code>```

In both cases we're generating a range with the .. operator, piping that to a loop |%{...}. Each iteration, we're accumulating $o and $p as either the sum or the sum-of-squares. We then calculate the square-of-sums with $o*$o and subtract $p. Output is left on the pipeline and printing is implicit.

Title: Difference of the square of the sum

Body:
PowerShell v2+, 47 bytes

Two variations

param($n,$m)$n..$m|%{$o+=$_;$p+=$_*$_};$o*$o-$p

$args-join'..'|iex|%{$o+=$_;$p+=$_*$_};$o*$o-$p

In both cases we're generating a range with the .. operator, piping that to a loop |%{...}. Each iteration, we're accumulating $o and $p as either the sum or the sum-of-squares. We then calculate the square-of-sums with $o*$o and subtract $p. Output is left on the pipeline and printing is implicit.


答:
MATL, 9 bytes

```<code>&:&*XRssE
</code>```

Try it online!

Explanation

```<code>&:   % Inclusive range between the two implicit inputs
&*   % Matrix of all pair-wise products
XR   % Upper triangular part of matrix, without the diagonal
ss   % Sum of all elements of the matrix
E    % Multiply by 2. Implicit display
</code>```

Example

These are the partial results of each line for inputs 5 and 9:

&:

```<code>5 6 7 8 9
</code>```

&:&*

```<code>25 30 35 40 45
30 36 42 48 54
35 42 49 56 63
40 48 56 64 72
45 54 63 72 81
</code>```

&:&*XR

```<code>0 30 35 40 45
0  0 42 48 54
0  0  0 56 63
0  0  0  0 72
0  0  0  0  0
</code>```

&:&*XRss

```<code>485
</code>```

&:&*XRssE

```<code>970
</code>```

Title: Difference of the square of the sum

Body:
MATL, 9 bytes

&:&*XRssE

Try it online!

Explanation

&:   % Inclusive range between the two implicit inputs
&*   % Matrix of all pair-wise products
XR   % Upper triangular part of matrix, without the diagonal
ss   % Sum of all elements of the matrix
E    % Multiply by 2. Implicit display

Example

These are the partial results of each line for inputs 5 and 9:

&:

5 6 7 8 9

&:&*

25 30 35 40 45
30 36 42 48 54
35 42 49 56 63
40 48 56 64 72
45 54 63 72 81

&:&*XR

0 30 35 40 45
0  0 42 48 54
0  0  0 56 63
0  0  0  0 72
0  0  0  0  0

&:&*XRss

485

&:&*XRssE

970


答:
Perl 6, <s> 36 32 </s> 31 bytes

<s>{([+] $_=@_[0]..@_[1])²-[+] $_»²}
{([+] $_=$^a..$^b)²-[+] $_»²}</s>
{[+]($_=$^a..$^b)²-[+] $_»²}
```

<p>Test it</p>

<h3>Explanation:</h3>

<pre class="lang-perl6 prettyprint-override"><code>{ # bare block with placeholder parameters $a and $b

  [+](# reduce with &infix:<+>
      # create a range, and store it in $_
      $_ = $^a .. $^b
  )²
  -
  [+] # reduce with &infix:<+>
    # square each element of $_ ( possibly in parallel )
    $_»²
}
</code>```

Test:

#! /usr/bin/env perl6
use v6.c;
use Test;

my @tests = (
  (5,9) => 970,
  (91,123) => 12087152,
  (1,10) => 2640,
);

plan +@tests;

my &diff-sq-of-sum = {[+]($_=$^a..$^b)²-[+] $_»²}

for @tests -> $_ ( :key(@input), :value($expected) ) {
  is diff-sq-of-sum(|@input), $expected, .gist
}
```

<pre class="lang-none prettyprint-override"><code>1..3
ok 1 - (5 9) => 970
ok 2 - (91 123) => 12087152
ok 3 - (1 10) => 2640
</code>```

Title: Difference of the square of the sum

Body:
Perl 6, <s> 36 32 </s> 31 bytes

<s>{([+] $_=@_[0]..@_[1])²-[+] $_»²}
{([+] $_=$^a..$^b)²-[+] $_»²}</s>
{[+]($_=$^a..$^b)²-[+] $_»²}

Test it

Explanation:

{ # bare block with placeholder parameters $a and $b

  [+](# reduce with &infix:<+>
      # create a range, and store it in $_
      $_ = $^a .. $^b
  )²
  -
  [+] # reduce with &infix:<+>
    # square each element of $_ ( possibly in parallel )
    $_»²
}

Test:

#! /usr/bin/env perl6
use v6.c;
use Test;

my @tests = (
  (5,9) => 970,
  (91,123) => 12087152,
  (1,10) => 2640,
);

plan +@tests;

my &diff-sq-of-sum = {[+]($_=$^a..$^b)²-[+] $_»²}

for @tests -> $_ ( :key(@input), :value($expected) ) {
  is diff-sq-of-sum(|@input), $expected, .gist
}

1..3
ok 1 - (5 9) => 970
ok 2 - (91 123) => 12087152
ok 3 - (1 10) => 2640


答:
05AB1E, 8 bytes

```<code>ŸDOnsnO-
</code>```

Explained

```<code>ŸD       # range from a to b, duplicate
  On     # sum and square first range
    s    # swap top 2 elements
     nO  # square and sum 2nd range
       - # take difference
</code>```

Try it online

Title: Difference of the square of the sum

Body:
05AB1E, 8 bytes

ŸDOnsnO-

Explained

ŸD       # range from a to b, duplicate
  On     # sum and square first range
    s    # swap top 2 elements
     nO  # square and sum 2nd range
       - # take difference

Try it online


问:
Wait a minute – in less than ten seconds

Task

Using any type of parallelisation, wait multiple periods, for a total sleep time of at least a minute (but less than a minute and a half).

The program/function must terminate within 10 seconds and return (by any means and in any format) two values: the total elapsed time, and the total executed sleep time. Both time values have to have a precision of at least 0.1 seconds.

This is similar to the concept of man-hours: a job that takes 60 hours can be completed in only 6 hours if 10 workers are splitting the job. Here we can have 60 seconds of sleep time e.g. in 10 parallel threads, thus requiring only 6 seconds for the whole job to be completed.

Example

The program MyProgram creates 14 threads, each thread sleeps for 5 seconds:

MyProgram → [5.016,70.105]

The execution time is greater than 5 seconds, and the total sleep time is greater than 70 seconds because of overhead.

答:
Perl, 101 bytes

use Time::HiRes<time sleep>;pipe*1=\time,0;
print time-$1,eval<1>if open-print{fork&fork&fork}-sleep 9
```

<p>Forks 7 child processes, each of which wait 9 seconds.</p>

<p><strong>Sample Output:</strong></p>

<pre class="lang-perl prettyprint-override"><code>perl wait-one-minute.pl
9.00925707817078-63.001741
</code>```

Body:
Perl, 101 bytes

use Time::HiRes<time sleep>;pipe*1=\time,0;
print time-$1,eval<1>if open-print{fork&fork&fork}-sleep 9

Forks 7 child processes, each of which wait 9 seconds.

Sample Output:

perl wait-one-minute.pl
9.00925707817078-63.001741


答:
Mathematica, 21 bytes

```<code>Tr[x=Range@##]^2-x.x&
</code>```

An unnamed function taking two arguments and returning the difference. Usage:

```<code>Tr[x=Range@##]^2-x.x&[91, 123]
(* 12087152 *)
</code>```

There's three small (and fairly standard) golfing tricks here:

## represents both arguments at once, so that we can use prefix notation for Range. Range@## is shorthand for Range[##] which expands to Range[a, b] and gives us an inclusive range as required.

Tr is for trace but using it on a vector simply sums that vector, saving three bytes over Total.

x.x is a dot product, saving four bytes over Tr[x^2].

Title: Difference of the square of the sum

Body:
Mathematica, 21 bytes

Tr[x=Range@##]^2-x.x&

An unnamed function taking two arguments and returning the difference. Usage:

Tr[x=Range@##]^2-x.x&[91, 123]
(* 12087152 *)

There's three small (and fairly standard) golfing tricks here:

## represents both arguments at once, so that we can use prefix notation for Range. Range@## is shorthand for Range[##] which expands to Range[a, b] and gives us an inclusive range as required.

Tr is for trace but using it on a vector simply sums that vector, saving three bytes over Total.

x.x is a dot product, saving four bytes over Tr[x^2].


答:
Python 2, 45 bytes

lambda a,b:(a+~b)*(a-b)*(3*(a+b)**2+a-b-2)/12
```

Closed form solution - not the shortest, but I thought it'd be worth posting anyway.

Explanation

Let p(n) be the nth square pyramidal number, and t(n) be the nth triangular number. Then, for n over the range a, ..., b:

∑n  = t(b)-t(a-1), and

∑n² = p(b) - p(a-1)

So (∑n)²-∑n² = (t(b)-t(a-1))² - (p(b) - p(a-1)).

This expression reduces to that in the code.

Title: Difference of the square of the sum

Body:
Python 2, 45 bytes

lambda a,b:(a+~b)*(a-b)*(3*(a+b)**2+a-b-2)/12

Closed form solution - not the shortest, but I thought it'd be worth posting anyway.

Explanation

Let p(n) be the nth square pyramidal number, and t(n) be the nth triangular number. Then, for n over the range a, ..., b:

∑n  = t(b)-t(a-1), and

∑n² = p(b) - p(a-1)

So (∑n)²-∑n² = (t(b)-t(a-1))² - (p(b) - p(a-1)).

This expression reduces to that in the code.


Title: Difference of the square of the sum

Body:
JavaScript (ES6), 67 bytes

a=>b=>([s=q=0,...Array(b-a)].map((_,i)=>q+=(s+=(n=i+a),n*n)),s*s-q)

Test Suite

f=a=>b=>([s=q=0,...Array(b-a)].map((_,i)=>q+=(s+=(n=i+a),n*n)),s*s-q)
e=s=>`${s} => ${eval(s[0])}` // template tag format for tests
console.log(e`f(5)(9)`)
console.log(e`f(91)(123)`)
console.log(e`f(1)(10)`)