答:
Ruby, 72 bytes

```<code>(1..100).each{|n|puts "#{n%3==0?'Fizz':''}#{n%5==0?'Buzz':n%3!=0?n:''}"}
</code>```

Explanation

For each number from 1 to 100, print 'Fizz' if the number mod 3 is 0, then if the number mod 5 is 0, print 'Buzz' else if the number mod 3 is 0, print the number.

Title: 1, 2, Fizz, 4, Buzz

Body:
Introduction

In our recent effort to collect catalogues of shortest solutions for standard programming exercises, here is PPCG's first ever vanilla FizzBuzz challenge. If you wish to see other catalogue challenges, there is "Hello World!" and "Is this number a prime?".

Challenge

Write a program that prints the decimal numbers from 1 to 100 inclusive. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.

Output

The output will be a list of numbers (and Fizzes, Buzzes and FizzBuzzes) separated by a newline (either \n or \r\n). A trailing newline is acceptable, but a leading newline is not.  Apart from your choice of newline, the output should look exactly like this:

```<code>1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz
</code>```

The only exception to this rule is constant output of your language's interpreter that cannot be suppressed, such as a greeting, ANSI color codes or indentation.

Further Rules

This is not about finding the language with the shortest approach for playing FizzBuzz, this is about finding the shortest approach in every language. Therefore, no answer will be marked as accepted.

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

Nothing can be printed to STDERR.

Feel free to use a language (or language version) even if it's newer than this challenge. If anyone wants to abuse this by creating a language where the empty program generates FizzBuzz output, then congrats for paving the way for a very boring answer.

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

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

Because the output is fixed, you may hardcode the output (but this may not be the shortest option).

You may use preexisting solutions, as long as you credit the original author of the program.

Standard loopholes are otherwise disallowed.

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

Catalogue

var QUESTION_ID=58615;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=30525;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"https://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+lang+'').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang.toLowerCase(),user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw>b.lang_raw)return 1;if(a.lang_raw<b.lang_raw)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:700}table td{padding:5px}</code>```

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
Ruby, 72 bytes

(1..100).each{|n|puts "#{n%3==0?'Fizz':''}#{n%5==0?'Buzz':n%3!=0?n:''}"}

Explanation

For each number from 1 to 100, print 'Fizz' if the number mod 3 is 0, then if the number mod 5 is 0, print 'Buzz' else if the number mod 3 is 0, print the number.


问:
Stack Overflowing
(Inspired by this question)

Objective

Your task is to write a program or function to print an ASCII version of the Stack Overflow logo to STDOUT

```<code> \|/
(-)
(-)
(-)
(-)
</code>```

Your program should take two inputs, referred to here as H and N.
The height of the stack "container" (the parentheses) is determined by H. The number of items in the stack is determined by N. If N>H, the stack will "overflow".

Input/Output

H will determine the height of the containers

For example:

H=1:

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

H=2:

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

H=3:

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

H will always be at least 1

N will determine how many items are in the stack. The following examples are all H = 2:

N=0

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

N=1

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

N=2

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

N=3

```<code> \
(-)
(-)
</code>```

N=4

```<code> \|
(-)
(-)
</code>```

N=5

```<code> \|/
(-)
(-)
</code>```

N=6

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

N=7

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

N will never be more than 2H+3 (In other words, the stack will never go through the ground).

Rules

No Standard Loopholes.

Your program must not produce any errors.

All test cases must pass.

You can input H and N any way you want.

I seriously doubt that your language has a built-in for this.

Each line may optionally have an extra space at the end. A blank line above a stack where N <= H is optional, as is a trailing newline.

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

Test Cases

In addition to all of the H=2 test cases from the Input/Output section, all of the following test cases must pass:

H=1, N=1

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

H=1, N=5

```<code> \|/
(-)-
</code>```

H=4, N=7

```<code> \|/
(-)
(-)
(-)
(-)
</code>```

H=5, N=0

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

Leaderboards

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

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

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

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

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

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

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

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

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

var QUESTION_ID=81167,OVERRIDE_USER=41505;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+)(?=[^\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

```

答:
JavaScript (ES6), <s>149</s> <s>139</s> 137 bytes

```<code>h=>n=>` ${[(g=(j,m=1)=>` -\\|/`[(j<n)*m])(h,2),g(h+1,3),g(h+2,4)].join``}${[...Array(h)].map((_,i)=>`
(${g(h-i-1)})${g(h+i+3)}`).join``}`
</code>```

I liked @MartinEnder's idea about indexing the -\|/ characters and I wanted to see how it would fare in ES6. Apparently I didn't do so well. Trying to figure out if this could be improved using for...of.

Edits

I managed to remove regexp and the call to .replace, moving the indexing directly into g() instead.

I accidentally counted f= in the second byte count

Test

f=h=>n=>` ${[(g=(j,m=1)=>` -\\|/`[(j<n)*m])(h,2),g(h+1,3),g(h+2,4)].join``}${[...Array(h)].map((_,i)=>`
(${g(h-i-1)})${g(h+i+3)}`).join``}`
document.write(````${[[2,0],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6],[2,7],[1,1],[1,5],[4,7],[5,0]].map(a=>f(a.shift())(a.shift())).join`

`}````)```

ContentLicense: CC BY-SA 3.0

Title: Stack Overflowing

Body:
JavaScript (ES6), <s>149</s> <s>139</s> 137 bytes

h=>n=>` ${[(g=(j,m=1)=>` -\\|/`[(j<n)*m])(h,2),g(h+1,3),g(h+2,4)].join``}${[...Array(h)].map((_,i)=>`
(${g(h-i-1)})${g(h+i+3)}`).join``}`

I liked @MartinEnder's idea about indexing the -\|/ characters and I wanted to see how it would fare in ES6. Apparently I didn't do so well. Trying to figure out if this could be improved using for...of.

Edits

I managed to remove regexp and the call to .replace, moving the indexing directly into g() instead.

I accidentally counted f= in the second byte count

Test

f=h=>n=>` ${[(g=(j,m=1)=>` -\\|/`[(j<n)*m])(h,2),g(h+1,3),g(h+2,4)].join``}${[...Array(h)].map((_,i)=>`
(${g(h-i-1)})${g(h+i+3)}`).join``}`
document.write(`<pre>${[[2,0],[2,1],[2,2],[2,3],[2,4],[2,5],[2,6],[2,7],[1,1],[1,5],[4,7],[5,0]].map(a=>f(a.shift())(a.shift())).join`

`}</pre>`)


答:
Python 3, <s>134</s> <s>121</s> <s>118</s> 111 bytes

```<code>def f(h,n):print('\|/'[:max(0,n-h)]+'\n'+'\n'.join('(-)-'if h<n-x-3else('(-)','( )')[x+n<h] for x in range(h)))
</code>```

Test it here: https://repl.it/CYL1/0

Un-golfed:

```<code>def f(h,n):
  top=['\|/'[:max(0,n-h)]]
  stack=['( )'if x+n<h else'(-)'for x in range(h)]
  overflow=top+stack
  v=n-3
  while v>h:
      overflow[h-v]+='-' #add side overflow
      v-=1

  print('\n'.join(overflow))
</code>```

<s>I'd like to have added the side overflow to the list comprehension, but I couldn't squeeze it in, so I had to go with the while loop.</s> Saved 13 bytes!

Title: Stack Overflowing

Body:
(Inspired by this question)

Objective

Your task is to write a program or function to print an ASCII version of the Stack Overflow logo to STDOUT

```<code> \|/
(-)
(-)
(-)
(-)
</code>```

Your program should take two inputs, referred to here as H and N.
The height of the stack "container" (the parentheses) is determined by H. The number of items in the stack is determined by N. If N>H, the stack will "overflow".

Input/Output

H will determine the height of the containers

For example:

H=1:

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

H=2:

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

H=3:

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

H will always be at least 1

N will determine how many items are in the stack. The following examples are all H = 2:

N=0

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

N=1

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

N=2

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

N=3

```<code> \
(-)
(-)
</code>```

N=4

```<code> \|
(-)
(-)
</code>```

N=5

```<code> \|/
(-)
(-)
</code>```

N=6

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

N=7

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

N will never be more than 2H+3 (In other words, the stack will never go through the ground).

Rules

No Standard Loopholes.

Your program must not produce any errors.

All test cases must pass.

You can input H and N any way you want.

I seriously doubt that your language has a built-in for this.

Each line may optionally have an extra space at the end. A blank line above a stack where N <= H is optional, as is a trailing newline.

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

Test Cases

In addition to all of the H=2 test cases from the Input/Output section, all of the following test cases must pass:

H=1, N=1

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

H=1, N=5

```<code> \|/
(-)-
</code>```

H=4, N=7

```<code> \|/
(-)
(-)
(-)
(-)
</code>```

H=5, N=0

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

Leaderboards

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

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

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

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

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

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

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

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

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

var QUESTION_ID=81167,OVERRIDE_USER=41505;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+)(?=[^\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

```

Body:
Python 3, <s>134</s> <s>121</s> <s>118</s> 111 bytes

def f(h,n):print('\|/'[:max(0,n-h)]+'\n'+'\n'.join('(-)-'if h<n-x-3else('(-)','( )')[x+n<h] for x in range(h)))

Test it here: https://repl.it/CYL1/0

Un-golfed:

def f(h,n):
  top=['\|/'[:max(0,n-h)]]
  stack=['( )'if x+n<h else'(-)'for x in range(h)]
  overflow=top+stack
  v=n-3
  while v>h:
      overflow[h-v]+='-' #add side overflow
      v-=1

  print('\n'.join(overflow))

<s>I'd like to have added the side overflow to the list comprehension, but I couldn't squeeze it in, so I had to go with the while loop.</s> Saved 13 bytes!


问:
Jam don't add like that

Background

Jelly's arithmetic atoms vectorize automatically. In fact, x + y is well-defined whenever x and y are numbers or ragged arrays of numbers. Jelly's source code implements this behavior using a generic vectorizer, but for this challenge, we'll only consider addition of integers and nested integer arrays.

Definitions

Define the depth of x as 0 if x is an integer, as 1 if it is a (possibly empty) flat array of integers, and as n + 1 if it contains at least one element of depth n and no elements of depth k > n.

This way, 1 has depth 0, [] and [1] and [1, 1] have depth 1, [[], []] and [[1], [1]] and [[1]] and [1, []] have depth 2, [1, [1, [1]]] has depth 3, etc.

The operation x + y is defined as follows.

If x and y have depth 0, return their sum.

If x and y have equal but positive depths, recursively apply + to all items of x and the corresponding items of y.

If x and y have different lengths, append the tail of the longer array to the array of sums.

Return the result.

If x's depth is strictly smaller than y's depth, recursively apply + to x and all items of y, and return the result.

Do the opposite if y's depth is strictly smaller than x's.

For example, consider the operation [1, [2, 3], [4]] + [[[10, 20], [30], 40, 50], 60].

The depth of the left argument is 2, while the depth of the right argument is 3, so we compute [1, [2, 3], [4]] + [[10, 20], [30], 40, 50] and [1, [2, 3], [4]] + 60.

[1, [2, 3], [4]] and [[10, 20], [30], 40, 50] both have depth 2, so we compute 1 + [10, 20], [2, 3] + [30] and [4] + 40.

1 + [10, 20] = [1 + 10, 1 + 20] = [11, 21]

[2, 3] + [30] = [2 + 30, 3] = [32, 3]

Note that 3 remains untouched, since it doesn't have a matching element.

[4] + 40 = [4 + 40] = [44]

50 doesn't have a matching element, so the result is [[[11, 21], [32, 3], [44], 50]].

[1, [2, 3], [4]] + 60 = [1 + 60, [2, 3] + 60, [4] + 60] = [61, [2 + 60, 3 + 60], [4 + 60]], resulting in [61, [62, 63], [64]].

The final result is [[[11, 21], [32, 3], [44], 50], [61, [62, 63], [64]]].

Task

Write a program or a function that takes two integers, two nested arrays of integers or a combination thereof as input and returns their sum, as defined above.

If your language has multiple array-like types (lists, tuples, vectors, etc.) you may choose any of them for your answer. The return type must match the argument type.

To prevent boring and unbeatable solutions, if a language has this exact operation as a built-in, you may not use that language.

All built-ins of all other languages are allowed. If your language of choice permits this, you may overload and/or redefine the built-in addition.

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

Test cases

```<code>0 + 0                           = 0
[-1, 0, -1] + [1]               = [0, 0, -1]
[] + [0]                        = [0]
[] + 0                          = []
[] + []                         = []
[[], 0] + []                    = [[], []]
[1, 2, 3] + 10                  = [11, 12, 13]
[1, 2, 3] + [10]                = [11, 2, 3]
[1, 2, 3] + [10, [20]]          = [[11, 12, 13], [21, 2, 3]]
[1, 2, 3, []] + [10, [20]]      = [11, [22], 3, []]
[1, [2, [3, [4]]]] + [10, [20]] = [[11, [21]], [[12, [22]], [13, [24]]]]
</code>```

To generate more test cases, you can use this Jelly program.

答:
Haskell, 150 bytes

```<code>data L=S Int|V{v::[L]}
d(V z)=1+maximum(d<$>S 0:z);d _=0
S x!S y=S$x+y
x!y|d x<d y=V$(x!)<$>v y|d x>d y=y!x|1<2=V$v x#v y
(x:a)#(y:b)=x!y:a#b;a#b=a++b
</code>```

Explanation

The first line defines an algebraic data type L, which is either a Scalar (containing an Int) or a Vector (containing a list of Ls, accessed using a record getter v, which is a partial function L → [L].)

The second line defines the depth function: the depth of a Vector is one plus its maximum depth. I prepend S 0 to the values in the vector, so that depth [] == 1 + maximum [depth (S 0)] == 1. The depth of “anything else” (a scalar) is 0.

The third line defines the base case for ! (the addition function): the sum of scalars is simply a scalar.

The fifth line defines a variant of zipWith (!) that just picks elements from the longest list when one of them is empty.

The fourth line is split in three cases:

```<code>x!y | d x<d y = V$(x!)<$>v y
    | d x>d y = y!x
    | True    = V$v x#v y
</code>```

If the depth of x is strictly less than the depth of y, map (x!) over the elements of y. (The use of v is guaranteed to be valid, as d(y) ≥ 1.)

If the depth of x is strictly greater, flip the arguments and restart.

If their depths are equal, zip the arguments together with (!). (The use of v is guaranteed to be valid, as the case d(x) = d(y) = 0 was handled as a base case.)

Test cases

```<code>instance Show L where
  show (S x) = show x
  show (V x) = show x

lArg = V [S 1, V [S 2, V [S 3, V [S 4]]]]
rArg = V [S 10, V [S 20]]
</code>```

Then show (lArg ! rArg) == "[[11,[21]],[[12,[22]],[13,[24]]]]".

Title: Jam don't add like that

Body:
Haskell, 150 bytes

data L=S Int|V{v::[L]}
d(V z)=1+maximum(d<$>S 0:z);d _=0
S x!S y=S$x+y
x!y|d x<d y=V$(x!)<$>v y|d x>d y=y!x|1<2=V$v x#v y
(x:a)#(y:b)=x!y:a#b;a#b=a++b

Explanation

The first line defines an algebraic data type L, which is either a Scalar (containing an Int) or a Vector (containing a list of Ls, accessed using a record getter v, which is a partial function L → [L].)

The second line defines the depth function: the depth of a Vector is one plus its maximum depth. I prepend S 0 to the values in the vector, so that depth [] == 1 + maximum [depth (S 0)] == 1. The depth of “anything else” (a scalar) is 0.

The third line defines the base case for ! (the addition function): the sum of scalars is simply a scalar.

The fifth line defines a variant of zipWith (!) that just picks elements from the longest list when one of them is empty.

The fourth line is split in three cases:

x!y | d x<d y = V$(x!)<$>v y
    | d x>d y = y!x
    | True    = V$v x#v y

If the depth of x is strictly less than the depth of y, map (x!) over the elements of y. (The use of v is guaranteed to be valid, as d(y) ≥ 1.)

If the depth of x is strictly greater, flip the arguments and restart.

If their depths are equal, zip the arguments together with (!). (The use of v is guaranteed to be valid, as the case d(x) = d(y) = 0 was handled as a base case.)

Test cases

instance Show L where
  show (S x) = show x
  show (V x) = show x

lArg = V [S 1, V [S 2, V [S 3, V [S 4]]]]
rArg = V [S 10, V [S 20]]

Then show (lArg ! rArg) == "[[11,[21]],[[12,[22]],[13,[24]]]]".


问:
Implement SHA-256
Given a sequence of bytes, output the SHA-256 hash value of the sequence.

The SHA-256 Algorithm

The following pseudocode is taken from the Wikipedia page for SHA-2.

```<code>Note 1: All variables are 32 bit unsigned integers and addition is calculated modulo 2^32
Note 2: For each round, there is one round constant k[i] and one entry in the message schedule array w[i], 0 ≤ i ≤ 63
Note 3: The compression function uses 8 working variables, a through h
Note 4: Big-endian convention is used when expressing the constants in this pseudocode,
    and when parsing message block data from bytes to words, for example,
    the first word of the input message "abc" after padding is 0x61626380

Initialize hash values:
(first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
h0 := 0x6a09e667
h1 := 0xbb67ae85
h2 := 0x3c6ef372
h3 := 0xa54ff53a
h4 := 0x510e527f
h5 := 0x9b05688c
h6 := 0x1f83d9ab
h7 := 0x5be0cd19

Initialize array of round constants:
(first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311):
k[0..63] :=
   0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
   0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
   0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
   0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
   0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
   0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
   0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
   0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2

Pre-processing:
append the bit '1' to the message
append k bits '0', where k is the minimum number >= 0 such that the resulting message
    length (modulo 512 in bits) is 448.
append length of message (without the '1' bit or padding), in bits, as 64-bit big-endian integer
    (this will make the entire post-processed length a multiple of 512 bits)

Process the message in successive 512-bit chunks:
break message into 512-bit chunks
for each chunk
    create a 64-entry message schedule array w[0..63] of 32-bit words
    (The initial values in w[0..63] don't matter, so many implementations zero them here)
    copy chunk into first 16 words w[0..15] of the message schedule array

    Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array:
    for i from 16 to 63
        s0 := (w[i-15] rightrotate 7) xor (w[i-15] rightrotate 18) xor (w[i-15] rightshift 3)
        s1 := (w[i-2] rightrotate 17) xor (w[i-2] rightrotate 19) xor (w[i-2] rightshift 10)
        w[i] := w[i-16] + s0 + w[i-7] + s1

    Initialize working variables to current hash value:
    a := h0
    b := h1
    c := h2
    d := h3
    e := h4
    f := h5
    g := h6
    h := h7

    Compression function main loop:
    for i from 0 to 63
        S1 := (e rightrotate 6) xor (e rightrotate 11) xor (e rightrotate 25)
        ch := (e and f) xor ((not e) and g)
        temp1 := h + S1 + ch + k[i] + w[i]
        S0 := (a rightrotate 2) xor (a rightrotate 13) xor (a rightrotate 22)
        maj := (a and b) xor (a and c) xor (b and c)
        temp2 := S0 + maj

        h := g
        g := f
        f := e
        e := d + temp1
        d := c
        c := b
        b := a
        a := temp1 + temp2

    Add the compressed chunk to the current hash value:
    h0 := h0 + a
    h1 := h1 + b
    h2 := h2 + c
    h3 := h3 + d
    h4 := h4 + e
    h5 := h5 + f
    h6 := h6 + g
    h7 := h7 + h

Produce the final hash value (big-endian):
digest := hash := h0 append h1 append h2 append h3 append h4 append h5 append h6 append h7
</code>```

Reference implementation

Here is a reference implementation, in Python 3:

#!/usr/bin/env python3

import sys

# ror function modified from http://stackoverflow.com/a/27229191/2508324
def ror(val, r_bits):
   return (val >> r_bits) | (val << (32-r_bits)) % 2**32

h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]

k = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
   0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
   0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
   0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
   0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
   0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
   0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
   0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]

s = sys.stdin.read().encode()
msg = [int(x,2) for c in s for x in '{:08b}'.format(c)]
msg.append(1)
while len(msg) % 512 != 448:
    msg.append(0)
msg.extend([int(x,2) for x in '{:064b}'.format(len(s) * 8)])

for i in range(len(msg)//512):
    chunk = msg[512*i:512*(i+1)] # sloth love chunk
    w = [0 for _ in range(64)]
    for j in range(16):
        w[j] = int(''.join(str(x) for x in chunk[32*j:32*(j+1)]),2)
    for j in range(16, 64):
        s0 = ror(w[j-15], 7) ^ ror(w[j-15], 18) ^ (w[j-15] >> 3)
        s1 = ror(w[j-2], 17) ^ ror(w[j-2], 19) ^ (w[j-2] >> 10)
        w[j] = (w[j-16] + s0 + w[j-7] + s1) % 2**32
    work = h[:]
    for j in range(64):
        S1 = ror(work[4], 6) ^ ror(work[4], 11) ^ ror(work[4], 25)
        ch = (work[4] & work[5]) ^ (~work[4] & work[6])
        temp1 = (work[7] + S1 + ch + k[j] + w[j]) % 2**32
        S0 = ror(work[0], 2) ^ ror(work[0], 13) ^ ror(work[0], 22)
        maj = (work[0] & work[1]) ^ (work[0] & work[2]) ^ (work[1] & work[2])
        temp2 = (S0 + maj) % 2**32
        work = [(temp1 + temp2) % 2**32] + work[:-1]
        work[4] = (work[4] + temp1) % 2**32
    h = [(H+W)%2**32 for H,W in zip(h,work)]

print(''.join('{:08x}'.format(H) for H in h))
```

<h2>Restrictions</h2>

<ul>
<li>The usage of builtins which compute SHA-256 hashes or otherwise trivialize the challenge is forbidden</li>
<li>The input and output may be in any reasonable format (encoded in a single-byte encoding, base64, hexadecimal, etc.)</li>
</ul>

<h2>Test cases</h2>

```<empty string> -> e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
abc -> ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
Hello, World! -> c98c24b677eff44860afea6f493bbaec5bb1c4cbb209c6fc2bbb47f66ff2ad31
1234 -> 03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4
```

答:
Python 2, 633 bytes

n=range
f=2**32
q=512
r=lambda v,b:v%f>>b|(v<<32-b)%f
t=int
g=lambda e:[t(x**e%1*f)for x in n(2,312)if 383**~-x%x==1]
h=g(.5)
k=g(1/3.)
m=map(t,input())
l=len(m)
m+=[1]+[0]*((447-l)%q)+map(t,'{:064b}'.format(l))
for i in n(l/q+1):
 c=m[q*i:][:q];w=[t(`c[j*32:][:32]`[1::3],2) for j in n(16)];x=h[:8]
 for j in n(48):a,o=w[j+1],w[j+14];w+=[(w[j]+(r(a,7)^r(a,18)^(a>>3))+w[j+9]+(r(o,17)^r(o,19)^(o>>10)))%f]
 for j in n(64):a,o=x[::4];d=x[7]+(r(o,6)^r(o,11)^r(o,25))+(o&x[5]^~o&x[6])+k[j]+w[j];e=(r(a,2)^r(a,13)^r(a,22))+(x[1]&a|x[2]&a|x[1]&x[2]);x=[d+e]+x[:7];x[4]+=d
 h=[(H+W)%f for H,W in zip(h,x)]
print''.join('%08x'%H for H in h)
```

This solution is the result of a collaboration between myself, Leaky Nun, and Mars Ultor. As such, I've made it community wiki out of fairness. It takes input as a binary string wrapped in quotes (e.g. '011000010110001001100011' for abc) and outputs a hex string.

Title: Implement SHA-256

Body:
Python 2, 633 bytes

n=range
f=2**32
q=512
r=lambda v,b:v%f>>b|(v<<32-b)%f
t=int
g=lambda e:[t(x**e%1*f)for x in n(2,312)if 383**~-x%x==1]
h=g(.5)
k=g(1/3.)
m=map(t,input())
l=len(m)
m+=[1]+[0]*((447-l)%q)+map(t,'{:064b}'.format(l))
for i in n(l/q+1):
 c=m[q*i:][:q];w=[t(`c[j*32:][:32]`[1::3],2) for j in n(16)];x=h[:8]
 for j in n(48):a,o=w[j+1],w[j+14];w+=[(w[j]+(r(a,7)^r(a,18)^(a>>3))+w[j+9]+(r(o,17)^r(o,19)^(o>>10)))%f]
 for j in n(64):a,o=x[::4];d=x[7]+(r(o,6)^r(o,11)^r(o,25))+(o&x[5]^~o&x[6])+k[j]+w[j];e=(r(a,2)^r(a,13)^r(a,22))+(x[1]&a|x[2]&a|x[1]&x[2]);x=[d+e]+x[:7];x[4]+=d
 h=[(H+W)%f for H,W in zip(h,x)]
print''.join('%08x'%H for H in h)

This solution is the result of a collaboration between myself, Leaky Nun, and Mars Ultor. As such, I've made it community wiki out of fairness. It takes input as a binary string wrapped in quotes (e.g. '011000010110001001100011' for abc) and outputs a hex string.


问:
Implement Bogosort
Is solving Sudoku too hard? Even the brute force version? Here's a coding exercise that's a little easier. I hope. :-P

Write the shortest function to implement bogosort. In specific, your function should:

Take an array (or your language's equivalent) as input

Check if its elements are in sorted order; if so, return the array

If not, shuffle the elements, and start again

The shortest entry wins. In the case of a tie, a function that supports a custom comparator (and/or pseudorandom number generator) is favoured. Any remaining ties are resolved by favouring the earlier submission.

Clarifications: You can use any element type you want, as long as there's some way to order them, of course. Also, the shuffling has to be uniform; none of this "I'll just quicksort it and call it shuffled" business. :-)

答:
Python, 71 characters

```<code>from random import*
def b(l):
 while l!=sorted(l):shuffle(l)
 return(l)
</code>```

Not the shortest one, but it works.

Ungolfed:

```<code>from random import *
def bogosort(list):
    while list != sorted(list):
        shuffle(list)

    return(list)
</code>```

Usage:

Input: b([1, 7, 3, 9, 2])

Output: [1, 2, 3, 7, 9]

ContentLicense: CC BY-SA 2.5

Title: Implement Bogosort

Body:
Python, 71 characters

from random import*
def b(l):
 while l!=sorted(l):shuffle(l)
 return(l)

Not the shortest one, but it works.

Ungolfed:

from random import *
def bogosort(list):
    while list != sorted(list):
        shuffle(list)

    return(list)

Usage:

Input: b([1, 7, 3, 9, 2])

Output: [1, 2, 3, 7, 9]


Title: Display "Happy Easter!"

Body:
Your task is to print the following ASCII Art:

```<code> _     _                            _______                           _
| |   | |                          (_______)          _              | |
| |__ | | ____ ____  ____  _   _    _____   ____  ___| |_  ____  ____| |
|  __)| |/ _  |  _ \|  _ \| | | |  |  ___) / _  |/___)  _)/ _  )/ ___)_|
| |   | ( ( | | | | | | | | |_| |  | |____( ( | |___ | |_( (/ /| |    _
|_|   |_|\_||_| ||_/| ||_/ \__  |  |_______)_||_(___/ \___)____)_|   |_|
              |_|   |_|   (____/
</code>```

Remember, this is code-golf, so the code with the smallest amount of bytes wins.
Good luck.

Body:
Javascript (ES6) 464 352 bytes

00000000  63 6f 6e 73 6f 6c 65 2e  6c 6f 67 28 60 08 09 28  |console.log(`..(|
00000010  09 c3 a0 39 c3 98 09 08  0f 0c 08 0c 18 0c 08 0c  |...9............|
00000020  c3 90 0a 39 0e 50 09 70  0c 08 0c 0f 0c 08 0c 11  |...9.P.p........|
00000030  08 0c 08 0c 08 21 08 21  10 21 10 09 18 09 20 29  |.....!.!.!.... )|
00000040  18 21 10 19 0c 08 0c 09  10 21 10 21 0c 08 0c 0f  |.!.......!.!....|
00000050  0c 10 11 0e 0c 08 0c 0a  08 09 10 0c 10 09 08 0c  |................|
00000060  10 09 08 0c 08 0c 08 0c  08 0c 10 0c 10 19 0e 08  |................|
00000070  0a 08 09 10 0c 0a 19 0e  10 09 0e 0a 08 09 10 0e  |................|
00000080  0a 08 19 0e 09 0c 0f 0c  08 0c 18 0c 08 0a 08 0a  |................|
00000090  08 0c 08 0c 08 0c 08 0c  08 0c 08 0c 08 0c 08 0c  |................|
000000a0  08 0c 09 0c 08 0c 10 0c  08 0c 21 0a 08 0a 08 0c  |..........!.....|
000000b0  08 0c 19 08 0c 08 0c 09  0a 08 0a 08 0a 0c 08 0c  |................|
000000c0  20 09 08 0f 0c 09 0c 18  0c 09 0c 09 14 09 0c 08  | ...............|
000000d0  14 09 0a 0c 08 14 09 0a  08 11 10 0c 10 0c 39 0e  |..............9.|
000000e0  09 14 09 0a 19 0a 08 19  0e 21 0e 09 0c 18 0c 09  |.........!......|
000000f0  0c 0f 70 0c 09 0c 18 0c  09 0c 18 0a 21 60 2e 73  |..p.........!`.s|
00000100  70 6c 69 74 28 22 22 29  2e 6d 61 70 28 61 3d 3e  |plit("").map(a=>|
00000110  61 2e 63 68 61 72 43 6f  64 65 41 74 28 29 29 2e  |a.charCodeAt()).|
00000120  6d 61 70 28 61 3d 3e 41  72 72 61 79 28 28 61 3e  |map(a=>Array((a>|
00000130  3e 33 29 2b 31 29 2e 6a  6f 69 6e 28 22 20 5f 2f  |>3)+1).join(" _/|
00000140  5c 5c 7c 28 29 5c 6e 22  2e 73 70 6c 69 74 28 22  |\\|()\n".split("|
00000150  22 29 5b 61 26 37 5d 29  29 2e 6a 6f 69 6e 28 22  |")[a&7])).join("|
00000160  22 29 29                                          |"))|

Try it here!


问:
Generating PBM bitmap files from ASCII text
The PBM (Portable BitMap) format is a very simple ASCII black and white bitmap format.

Here's an example for the letter 'J' (copy-pasted from the wikipedia link):

```
P1
# This is an example bitmap of the letter "J"
6 10
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
0 0 0 0 1 0
1 0 0 0 1 0
0 1 1 1 0 0
0 0 0 0 0 0
0 0 0 0 0 0
```

It's time we build a small tool to generate files in this nifty little format!

Your goal is to write the shortest program (in any language) that conforms to the following rules:

Your program takes one string from stdin (for example CODEGOLF.STACKEXCHANGE.COM!)

It generates a PBM file with a bitmapped (readable) representation of the string.

Each character is constructed as a 8x8 grid.

You must support the characters [A-Z] (all uppercase), space, a point ('.') and an exclamation mark ('!').

No external libraries allowed (certainly no PBM related ones)!

The used character set must not simply be external to your program. Part of the challenge is storing the characters efficiently...

Testing for validness of the PBM format can be done with the GIMP (or others). Do show off sample input and output!

The shortest solution will be awarded the answer points on 2012-01-31.

Have fun golfing!

PS: I've added a bounty (percentage-wise a huge part of my codegolf reputation) to (hopefully) draw in more competitors.

答:
Python 2, <s>248</s> 247 bytes

```<code>s=raw_input();k=len(s);print"P1",k*8,8
for i in range(k*24):a=s[i/3%k];j=max(".!".find(a)+1,ord(a)-62)*3;print int("00080084IMVAENBSIFERBSUF4UFQQEMVDT4NAP4MNDSI9MRTMRBARA4NBQRAMNBE4E94NURDARDNRDMLD95DSL7"[j:j+3],32)>>(i/3/k*3+i%3)&1," 0"*(i%3/2*5)
</code>```

Uses a 3x5 font, packed into a printable string, 3 bytes per character.  The font is clearly legible, although the n is lowercase and the v might be mistaken for a u if it isn't seen in context.

Actual Size:

Zoomed x3:

The output is a P1 type PBM, as per the example in the challenge.  It was a fun challenge.

Body:
Python 2, <s>248</s> 247 bytes

s=raw_input();k=len(s);print"P1",k*8,8
for i in range(k*24):a=s[i/3%k];j=max(".!".find(a)+1,ord(a)-62)*3;print int("00080084IMVAENBSIFERBSUF4UFQQEMVDT4NAP4MNDSI9MRTMRBARA4NBQRAMNBE4E94NURDARDNRDMLD95DSL7"[j:j+3],32)>>(i/3/k*3+i%3)&1," 0"*(i%3/2*5)

Uses a 3x5 font, packed into a printable string, 3 bytes per character.  The font is clearly legible, although the n is lowercase and the v might be mistaken for a u if it isn't seen in context.

Actual Size:

Zoomed x3:

The output is a P1 type PBM, as per the example in the challenge.  It was a fun challenge.


Title: Stack Overflowing

Body:
Java, 186 177 bytes

void f(int h,int n){for(int i=0;i<h+1;i++)System.out.print((i>0?"(":" ")+(i>0?n>h-i-2?"-":" ":n>h+0?"\\":" ")+(i>0?")":n>h+1?"|":" ")+(i>0?n>h+2+i?"-":" ":n>h+2?"/":" ")+"\n");}

Ungolfed try online

String f(int h, int n)
{
    String s=" ";
    s+=n>h+0?"\\":" ";
    s+=n>h+1? "|":" ";
    s+=n>h+2? "/":" ";
    s+="\n";

    for(int i=0; i<h; i++)
    {
        s+="(";
        s+=n>h-i-1?"-":" ";
        s+=")";
        s+=n>h+3+i?"-":" ";
        s+="\n";
    }

    return s;
}


答:
APL, 44 bytes

```<code>{1=≡⍺⍵:⍺+⍵⋄=/∆←|≡¨⍺⍵:⊃∇¨/↓↑⍺⍵⋄</∆:⍺∘∇¨⍵⋄⍵∇⍺}
</code>```

APL's + distributes over arrays as well, but in a different enough manner that this can't really be used. However, there is a built-in depth function (≡).

Explanation:

1=≡⍺⍵:⍺+⍵: if the depths of ⍺ ⍵ are both zero (and therefore the depth of ⍺ ⍵ is 1), add them.

∆←|≡¨⍺⍵: take the absolute of the depth of both ⍺ and ⍵ and store them in ∆. (≡ gives a negative value if not all elements have the same depth.)

=/∆: if they have the same depth:

↓↑⍺⍵: pad the shortest array with zeroes to match the longer array

⊃∇¨/: distribute the function over both arrays

</∆: if the depth of ⍺ is less than that of ⍵:

⍺∘∇¨⍵: bind ⍺ and then map over ⍵

⍵∇⍺: if nothing else (so ⍵ is deeper than ⍺), swap the arguments and try again.

Title: Jam don't add like that

Body:
Background

Jelly's arithmetic atoms vectorize automatically. In fact, x + y is well-defined whenever x and y are numbers or ragged arrays of numbers. Jelly's source code implements this behavior using a generic vectorizer, but for this challenge, we'll only consider addition of integers and nested integer arrays.

Definitions

Define the depth of x as 0 if x is an integer, as 1 if it is a (possibly empty) flat array of integers, and as n + 1 if it contains at least one element of depth n and no elements of depth k > n.

This way, 1 has depth 0, [] and [1] and [1, 1] have depth 1, [[], []] and [[1], [1]] and [[1]] and [1, []] have depth 2, [1, [1, [1]]] has depth 3, etc.

The operation x + y is defined as follows.

If x and y have depth 0, return their sum.

If x and y have equal but positive depths, recursively apply + to all items of x and the corresponding items of y.

If x and y have different lengths, append the tail of the longer array to the array of sums.

Return the result.

If x's depth is strictly smaller than y's depth, recursively apply + to x and all items of y, and return the result.

Do the opposite if y's depth is strictly smaller than x's.

For example, consider the operation [1, [2, 3], [4]] + [[[10, 20], [30], 40, 50], 60].

The depth of the left argument is 2, while the depth of the right argument is 3, so we compute [1, [2, 3], [4]] + [[10, 20], [30], 40, 50] and [1, [2, 3], [4]] + 60.

[1, [2, 3], [4]] and [[10, 20], [30], 40, 50] both have depth 2, so we compute 1 + [10, 20], [2, 3] + [30] and [4] + 40.

1 + [10, 20] = [1 + 10, 1 + 20] = [11, 21]

[2, 3] + [30] = [2 + 30, 3] = [32, 3]

Note that 3 remains untouched, since it doesn't have a matching element.

[4] + 40 = [4 + 40] = [44]

50 doesn't have a matching element, so the result is [[[11, 21], [32, 3], [44], 50]].

[1, [2, 3], [4]] + 60 = [1 + 60, [2, 3] + 60, [4] + 60] = [61, [2 + 60, 3 + 60], [4 + 60]], resulting in [61, [62, 63], [64]].

The final result is [[[11, 21], [32, 3], [44], 50], [61, [62, 63], [64]]].

Task

Write a program or a function that takes two integers, two nested arrays of integers or a combination thereof as input and returns their sum, as defined above.

If your language has multiple array-like types (lists, tuples, vectors, etc.) you may choose any of them for your answer. The return type must match the argument type.

To prevent boring and unbeatable solutions, if a language has this exact operation as a built-in, you may not use that language.

All built-ins of all other languages are allowed. If your language of choice permits this, you may overload and/or redefine the built-in addition.

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

Test cases

```<code>0 + 0                           = 0
[-1, 0, -1] + [1]               = [0, 0, -1]
[] + [0]                        = [0]
[] + 0                          = []
[] + []                         = []
[[], 0] + []                    = [[], []]
[1, 2, 3] + 10                  = [11, 12, 13]
[1, 2, 3] + [10]                = [11, 2, 3]
[1, 2, 3] + [10, [20]]          = [[11, 12, 13], [21, 2, 3]]
[1, 2, 3, []] + [10, [20]]      = [11, [22], 3, []]
[1, [2, [3, [4]]]] + [10, [20]] = [[11, [21]], [[12, [22]], [13, [24]]]]
</code>```

To generate more test cases, you can use this Jelly program.

Body:
APL, 44 bytes

{1=≡⍺⍵:⍺+⍵⋄=/∆←|≡¨⍺⍵:⊃∇¨/↓↑⍺⍵⋄</∆:⍺∘∇¨⍵⋄⍵∇⍺}

APL's + distributes over arrays as well, but in a different enough manner that this can't really be used. However, there is a built-in depth function (≡).

Explanation:

1=≡⍺⍵:⍺+⍵: if the depths of ⍺ ⍵ are both zero (and therefore the depth of ⍺ ⍵ is 1), add them.

∆←|≡¨⍺⍵: take the absolute of the depth of both ⍺ and ⍵ and store them in ∆. (≡ gives a negative value if not all elements have the same depth.)

=/∆: if they have the same depth:

↓↑⍺⍵: pad the shortest array with zeroes to match the longer array

⊃∇¨/: distribute the function over both arrays

</∆: if the depth of ⍺ is less than that of ⍵:

⍺∘∇¨⍵: bind ⍺ and then map over ⍵

⍵∇⍺: if nothing else (so ⍵ is deeper than ⍺), swap the arguments and try again.


问:
Paint Starry Night, objectively, in 1kB of code
Note: a 1000 point bounty is still available for this challenge, which I will create and award if anyone takes the top score without using built-in compression.

Below is a 386x320 png representation of van Gogh's Starry Night.

Your goal is to reproduce this image as closely as possible, in no more than 1024 bytes of code. For the purposes of this challenge, the closeness of images is measured by the squared differences in RGB pixel values, as explained below.

This is code-challenge. Scores are calculated using the validation script below. The lowest score wins.

Your code must obey the following restrictions:

It must be a complete program

It must output an image in a format that can be read by the validation script below, running on my machine. The script uses Python's PIL library, which can load a wide variety of file formats, including png, jpg and bmp.

It must be completely self-contained, taking no input and loading no files (other than importing libraries, which is allowed)

If your language or library includes a function that outputs Starry Night, you are not allowed to use that function.

It should run deterministically, producing the same output every time.

The dimensions of the output image must be 386x320

For the avoidance of doubt: valid answers must use programming languages as per the usual PPCG rules. It must be a program that outputs an image, not just an image file.

It is likely that some submissions will themselves be generated by code. If this is the case, please include in your answer the code that was used to produce your submission, and explain how it works. The above restrictions only apply to the 1kB image-generating program that you submit; they don't apply to any code used to generate it.

Scoring

To calculate your score, take your output image and the original above and convert the RGB pixel values to floating point numbers ranging from 0 to 1. The score of a pixel is (orig_r-img_r)^2 +(orig_g-img_g)^2 + (orig_b-img_b)^2, i.e. the squared distance in RGB space between the two images. The score of an image is the sum of the scores of its pixels.

Below is a Python script that performs this calculation - in the case of any inconsistency or ambiguity, the definitive score is the one calculated by that script running on my machine.

Note that the score is calculated based on the output image, so if you use a lossy format that will affect the score.

The lower the score the better. The original Starry Night image would have a score of 0. In the astronomically unlikely event of a tie, the answer with the most votes will determine the winner.

Bonus objectives

Because the answers were dominated by solutions using built-in compression, I awarded a series of bounties to answers that use other techniques. The next one will be a bounty of 1000 points, to be awarded if and when an answer that does not use built-in compression takes the top place overall.

The previously awarded bonus bounties were as follows:

A 100 point bounty was awarded to nneonneo's answer, for being the highest-scoring answer that did not use built-in compression at the time. It had 4852.87 points at the time it was awarded. Honourable mentions go to 2012rcampion, who made a valiant attempt to beat nneonneo using an approach based on Voronoi tesselation, scoring 5076 points, and to Sleafar, whose answer was in the lead until near the end, with 5052 points, using a similar method to nneonneo.

A 200 point bounty was awarded to Strawdog's entry. This was awarded for being an optimization-based strategy that took the lead among non-built-in-compression answers and held it for a week. It scored 4749.88 points using an impressively clever method.

Scoring/validation script

The following Python script should be placed in the same folder as the image above (which should be named ORIGINAL.png) and run using a command of the form python validate.py myImage.png.

from PIL import Image
import sys

orig = Image.open("ORIGINAL.png")
img  = Image.open(sys.argv[1])

if img.size != orig.size:
    print("NOT VALID: image dimensions do not match the original")
    exit()

w, h = img.size

orig = orig.convert("RGB")
img = img.convert("RGB")

orig_pix = orig.load()
img_pix = img.load()

score = 0

for x in range(w):
    for y in range(h):
        orig_r, orig_g, orig_b = orig_pix[x,y]
        img_r, img_g, img_b = img_pix[x,y]
        score += (img_r-orig_r)**2
        score += (img_g-orig_g)**2
        score += (img_b-orig_b)**2

print(score/255.**2)
```
<p><strong>Technical note:</strong> Objective measures of image similarity are a tricky thing. In this case I've opted for one that's easy for anyone to implement, in full knowledge that much better measures exist.</p>
<h2>Leaderboard</h2>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var QUESTION_ID=69930,OVERRIDE_USER=21034;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="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});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;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,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.lang>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;</code>```

body{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;float:left}table thead{font-weight:700}table td{padding:5px}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Score</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td>Link</td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td>Link</td></tr></tbody> </table></code>```

答:
Python 2 (no built-in compression), score 4497.730

This uses the same manually-decoded 16-color image approach as my previous answer, but this time I actually applied a gradient-descent optimization strategy to significantly improve the score. The previous submission scored 4755.886 points, whereas the new submission scores over 250 points better, beating out a lot of built-in compression approaches in the process.

As before, the final program is exactly 1024 bytes long. In fact, the raw output of the optimization algorithm contained four bytes that were escaped (\0), and which I had to "fudge" in order to reduce the byte count to 1024 bytes. Without the fudge, the 1028-byte program would score 4490.685 - 7 points better.

The basic idea is to optimize both the palette and data jointly. In a single iteration, I search over all tweaks of the palette (basically, every modified palette which differs by 1 in some color component) and pick the modified palette which best improves the score. Then, I search over all tweaks of the data (every modified index array in which one pixel is changed to some other palette entry) and choose a modification which reduces the score (here I don't care about best, because I don't want to fruitlessly search the full space of over 25000 tweaks every iteration).

Finally, when generating the final program output, I run another optimization pass which rearranges the palette to minimize the number of backslashes required in the final output (e.g. for the program shown below, the palette was rearranged using the hex table "0e3428916b7df5ca").

This approach yielded both a significant numerical and perceptual improvement over the previous naïve ImageMagick approach. Previous submission output:

And new submission output:

The new optimization-based approach has significantly more detail and accurate color reproduction.

Here is the hexdump of the final program:

```<code>0000000: efbb bf66 726f 6d20 5049 4c2e 496d 6167  ...from PIL.Imag
0000010: 6520 696d 706f 7274 2a0a 6672 6f6d 6275  e import*.frombu
0000020: 6666 6572 2827 5247 4227 2c28 3430 2c34  ffer('RGB',(40,4
0000030: 3129 2c27 272e 6a6f 696e 2827 b39b 2620  1),''.join('..&
0000040: b4b9 7e20 2634 8120 5567 7520 3547 7320  ..~ &4. Ugu 5Gs
0000050: 242e 5620 1c1f 1b20 7890 a420 4348 3d20  $.V ... x.. CH=
0000060: 9fae a420 3a52 8e20 262b 3220 7d90 7f20  ... :R. &+2 }..
0000070: 3a49 5720 4a67 9720 5d79 9c27 2e73 706c  :IW Jg. ]y.'.spl
0000080: 6974 2829 5b69 6e74 2863 2c31 3629 5d66  it()[int(c,16)]f
0000090: 6f72 2063 2069 6e27 8388 88b6 86b6 6b66  or c in'......kf
00000a0: 6bb8 b8b8 8888 dd8b bbbb bb8d b688 bb66  k..............f
00000b0: 6666 6666 b68d bdb6 bb88 33bd 5b55 bb68  ffff......3.[U.h
00000c0: b888 b66b 6666 6666 66bb 6688 88d8 bbb5  ...kfffff.f.....
00000d0: 553d 868b bb8b 6666 666b 6666 66b6 3d68  U=....fffkfff.=h
00000e0: bb66 5dd4 8363 b8bd dbd8 6666 66b6 66b6  .f]..c....fff.f.
00000f0: bbbb bbb6 d666 6bd6 f3bd d3d4 b5dd 666b  .....fk.......fk
0000100: 6666 6666 b668 63d5 66b8 5bd8 66bb 5b5b  ffff.hc.f.[.f.[[
0000110: 884b b66b 666b 666b 686d 8d85 dbb6 dd4b  .K.kfkfkhm.....K
0000120: 5b33 6db5 b5bd 6b6b 6b66 66bb d5b3 dddb  [3m...kkkff.....
0000130: bad4 58b5 d435 3b33 b555 6b66 6666 66bb  ..X..5;3.Ukffff.
0000140: 5346 db84 d45d bbbd 54d7 4d3b 5bbb b6b6  SF...]..T.M;[...
0000150: 6666 66b5 6bd3 d4f3 eddd 4333 c5d3 3c83  fff.k.....C3..<.
0000160: b2a5 5666 6666 66b6 b534 84d5 4444 b8b8  ..Vffff..4..DD..
0000170: b383 8333 3ffe 7666 66b6 6b42 2555 2eaa  ...3?.vff.kB%U..
0000180: 5b4a 4343 ad33 3388 43fe f666 b6d6 64e3  [JCC.33.C..f..d.
0000190: 564f d534 4455 aaea aaef ffee e737 3666  VO.4DU.......76f
00001a0: 6bb6 c73e ef3a f352 445b b25a eaee ffee  k..>.:.RD[.Z....
00001b0: ff79 3666 6b63 7c73 f3ec ee34 b55b 53b6  .y6fkc|s...4.[S.
00001c0: 5baf eee3 3717 3666 6dda 3fc1 ccc3 cc3a  [...7.6fm.?....:
00001d0: f333 7e34 bbb2 feea 7c7e d666 6ddf 99f3  .3~4....|~.fm...
00001e0: c7c1 c717 c777 7f77 f35b b6bb 374a 4666  .....w.w.[..7JFf
00001f0: be49 9999 aeee fac9 cc99 997c c79b 5bbb  .I.........|..[.
0000200: a3ae 4666 bad9 9197 e7ae fae4 acf3 ef99  ..Ff............
0000210: 9cf7 d6b5 4afe 3666 bf79 9099 a5ef af4a  ....J.6f.y.....J
0000220: ee77 ce49 999f 7b66 aeec 1b66 be39 1999  .w.I..{f...f.9..
0000230: a474 a2ef a7ef fcaf 1979 997c 7ee1 1b66  .t.......y.|~..f
0000240: baf7 999f efff 7cee e77e 7ffa 7999 9999  ......|..~..y...
0000250: 1eac c666 d4fe f7ff 7fff feff eeff e7ef  ...f............
0000260: a919 1999 f3ae a6b6 d4a5 aef7 ecf4 44a3  ..............D.
0000270: 7aa4 a7fe fe79 9199 e777 76b6 e4b4 ae77  z....y...wv....w
0000280: 7f4e ffef 3977 9fee f7ee 7719 9777 f36b  .N..9w....w..w.k
0000290: e45e 4e7f fafe ff7a eec3 3eef feff eaa1  .^N....z..>.....
00002a0: f7f7 3f66 9f5f ceef fe7a e777 aeaa ee3e  ..?f._...z.w...>
00002b0: efee fefe caae c766 77fc 1aff f7ff 7f77  .......fw......w
00002c0: edea eeea faff faff ef9f e7d6 7fff c547  ...............G
00002d0: 37ef fef7 4eaa affe e7ff 77ff fcf7 c7dd  7...N.....w.....
00002e0: 7e9f ff64 e3ef a7fa faef fffa ee19 197f  ~..d............
00002f0: fcf5 2abf f7fc f774 aaa3 e74e 7a3c 77ee  ..*....t...Nz<w.
0000300: ff11 119c ca54 a2ba 2aef f3cc af3f 7ee7  .....T..*....?~.
0000310: f2c1 17ae f110 5c30 17ea aa2a b3c3 2eef  ......\0...*....
0000320: fc33 3fee f745 7ccf ef91 1001 09aa 2aaa  .3?..E|.......*.
0000330: bc0c 2a4e e717 97f7 fa5a affe ef91 1011  ..*N.....Z......
0000340: 1c2a aa2a 6c03 2a44 fea3 3444 24e4 4aa2  .*.*l.*D..4D$.J.
0000350: ee91 0111 195a aa4a 6434 222a 52d4 4422  .....Z.Jd4"*R.D"
0000360: 4f3e 5542 e7c1 1011 9c5a 2a2a 6522 4aa2  O>UB.....Z**e"J.
0000370: a222 a254 7ccc 454e ef9c 1101 174a 77a2  .".T|.EN.....Jw.
0000380: b224 2aa4 2c32 aa42 700c aa45 ea39 c111  .$*.,2.Bp..E.9..
0000390: 9c57 c072 545a 5ecc e0ca 4522 ecce a4a4  .W.rTZ^...E"....
00003a0: a34f 991c cf5f 0175 5315 5acc f4a4 ae44  .O..._.uS.Z....D
00003b0: aa34 ea34 aafa 2ffc ee54 7f4b 5345 2a3c  .4.4../..T.KSE*<
00003c0: a4a3 33aa 4554 445e a4e3 f4ea 4427 2e65  ..3.ETD^....D'.e
00003d0: 6e63 6f64 6528 2768 6578 2729 2929 2e72  ncode('hex'))).r
00003e0: 6573 697a 6528 2833 3836 2c33 3230 292c  esize((386,320),
00003f0: 3129 2e73 6176 6528 276f 2e70 6e67 2729  1).save('o.png')
</code>```

There's still room to improve. For example, a simple histogram shows that some colors are barely used:

```<code> 6: 203
15: 167
14: 154
11: 152
10: 145
 7: 120
 4: 110
 3: 107
 5: 85
 9: 77
12: 77
13: 66
 1: 56
 8: 54
 2: 49
 0: 18
</code>```

This suggests that a rebalanced palette might improve efficiency, perhaps enough to catch the 5th place BPG solution. However, I am quite doubtful that this optimization approach (or really, anything that doesn't involve the extraordinary machinery of H.265) can catch the first place BPG implementation.

ContentLicense: CC BY-SA 4.0

Body:
Python 2 (no built-in compression), score 4497.730

This uses the same manually-decoded 16-color image approach as my previous answer, but this time I actually applied a gradient-descent optimization strategy to significantly improve the score. The previous submission scored 4755.886 points, whereas the new submission scores over 250 points better, beating out a lot of built-in compression approaches in the process.

As before, the final program is exactly 1024 bytes long. In fact, the raw output of the optimization algorithm contained four bytes that were escaped (\0), and which I had to "fudge" in order to reduce the byte count to 1024 bytes. Without the fudge, the 1028-byte program would score 4490.685 - 7 points better.

The basic idea is to optimize both the palette and data jointly. In a single iteration, I search over all tweaks of the palette (basically, every modified palette which differs by 1 in some color component) and pick the modified palette which best improves the score. Then, I search over all tweaks of the data (every modified index array in which one pixel is changed to some other palette entry) and choose a modification which reduces the score (here I don't care about best, because I don't want to fruitlessly search the full space of over 25000 tweaks every iteration).

Finally, when generating the final program output, I run another optimization pass which rearranges the palette to minimize the number of backslashes required in the final output (e.g. for the program shown below, the palette was rearranged using the hex table "0e3428916b7df5ca").

This approach yielded both a significant numerical and perceptual improvement over the previous naïve ImageMagick approach. Previous submission output:

And new submission output:

The new optimization-based approach has significantly more detail and accurate color reproduction.

Here is the hexdump of the final program:

0000000: efbb bf66 726f 6d20 5049 4c2e 496d 6167  ...from PIL.Imag
0000010: 6520 696d 706f 7274 2a0a 6672 6f6d 6275  e import*.frombu
0000020: 6666 6572 2827 5247 4227 2c28 3430 2c34  ffer('RGB',(40,4
0000030: 3129 2c27 272e 6a6f 696e 2827 b39b 2620  1),''.join('..&
0000040: b4b9 7e20 2634 8120 5567 7520 3547 7320  ..~ &4. Ugu 5Gs
0000050: 242e 5620 1c1f 1b20 7890 a420 4348 3d20  $.V ... x.. CH=
0000060: 9fae a420 3a52 8e20 262b 3220 7d90 7f20  ... :R. &+2 }..
0000070: 3a49 5720 4a67 9720 5d79 9c27 2e73 706c  :IW Jg. ]y.'.spl
0000080: 6974 2829 5b69 6e74 2863 2c31 3629 5d66  it()[int(c,16)]f
0000090: 6f72 2063 2069 6e27 8388 88b6 86b6 6b66  or c in'......kf
00000a0: 6bb8 b8b8 8888 dd8b bbbb bb8d b688 bb66  k..............f
00000b0: 6666 6666 b68d bdb6 bb88 33bd 5b55 bb68  ffff......3.[U.h
00000c0: b888 b66b 6666 6666 66bb 6688 88d8 bbb5  ...kfffff.f.....
00000d0: 553d 868b bb8b 6666 666b 6666 66b6 3d68  U=....fffkfff.=h
00000e0: bb66 5dd4 8363 b8bd dbd8 6666 66b6 66b6  .f]..c....fff.f.
00000f0: bbbb bbb6 d666 6bd6 f3bd d3d4 b5dd 666b  .....fk.......fk
0000100: 6666 6666 b668 63d5 66b8 5bd8 66bb 5b5b  ffff.hc.f.[.f.[[
0000110: 884b b66b 666b 666b 686d 8d85 dbb6 dd4b  .K.kfkfkhm.....K
0000120: 5b33 6db5 b5bd 6b6b 6b66 66bb d5b3 dddb  [3m...kkkff.....
0000130: bad4 58b5 d435 3b33 b555 6b66 6666 66bb  ..X..5;3.Ukffff.
0000140: 5346 db84 d45d bbbd 54d7 4d3b 5bbb b6b6  SF...]..T.M;[...
0000150: 6666 66b5 6bd3 d4f3 eddd 4333 c5d3 3c83  fff.k.....C3..<.
0000160: b2a5 5666 6666 66b6 b534 84d5 4444 b8b8  ..Vffff..4..DD..
0000170: b383 8333 3ffe 7666 66b6 6b42 2555 2eaa  ...3?.vff.kB%U..
0000180: 5b4a 4343 ad33 3388 43fe f666 b6d6 64e3  [JCC.33.C..f..d.
0000190: 564f d534 4455 aaea aaef ffee e737 3666  VO.4DU.......76f
00001a0: 6bb6 c73e ef3a f352 445b b25a eaee ffee  k..>.:.RD[.Z....
00001b0: ff79 3666 6b63 7c73 f3ec ee34 b55b 53b6  .y6fkc|s...4.[S.
00001c0: 5baf eee3 3717 3666 6dda 3fc1 ccc3 cc3a  [...7.6fm.?....:
00001d0: f333 7e34 bbb2 feea 7c7e d666 6ddf 99f3  .3~4....|~.fm...
00001e0: c7c1 c717 c777 7f77 f35b b6bb 374a 4666  .....w.w.[..7JFf
00001f0: be49 9999 aeee fac9 cc99 997c c79b 5bbb  .I.........|..[.
0000200: a3ae 4666 bad9 9197 e7ae fae4 acf3 ef99  ..Ff............
0000210: 9cf7 d6b5 4afe 3666 bf79 9099 a5ef af4a  ....J.6f.y.....J
0000220: ee77 ce49 999f 7b66 aeec 1b66 be39 1999  .w.I..{f...f.9..
0000230: a474 a2ef a7ef fcaf 1979 997c 7ee1 1b66  .t.......y.|~..f
0000240: baf7 999f efff 7cee e77e 7ffa 7999 9999  ......|..~..y...
0000250: 1eac c666 d4fe f7ff 7fff feff eeff e7ef  ...f............
0000260: a919 1999 f3ae a6b6 d4a5 aef7 ecf4 44a3  ..............D.
0000270: 7aa4 a7fe fe79 9199 e777 76b6 e4b4 ae77  z....y...wv....w
0000280: 7f4e ffef 3977 9fee f7ee 7719 9777 f36b  .N..9w....w..w.k
0000290: e45e 4e7f fafe ff7a eec3 3eef feff eaa1  .^N....z..>.....
00002a0: f7f7 3f66 9f5f ceef fe7a e777 aeaa ee3e  ..?f._...z.w...>
00002b0: efee fefe caae c766 77fc 1aff f7ff 7f77  .......fw......w
00002c0: edea eeea faff faff ef9f e7d6 7fff c547  ...............G
00002d0: 37ef fef7 4eaa affe e7ff 77ff fcf7 c7dd  7...N.....w.....
00002e0: 7e9f ff64 e3ef a7fa faef fffa ee19 197f  ~..d............
00002f0: fcf5 2abf f7fc f774 aaa3 e74e 7a3c 77ee  ..*....t...Nz<w.
0000300: ff11 119c ca54 a2ba 2aef f3cc af3f 7ee7  .....T..*....?~.
0000310: f2c1 17ae f110 5c30 17ea aa2a b3c3 2eef  ......\0...*....
0000320: fc33 3fee f745 7ccf ef91 1001 09aa 2aaa  .3?..E|.......*.
0000330: bc0c 2a4e e717 97f7 fa5a affe ef91 1011  ..*N.....Z......
0000340: 1c2a aa2a 6c03 2a44 fea3 3444 24e4 4aa2  .*.*l.*D..4D$.J.
0000350: ee91 0111 195a aa4a 6434 222a 52d4 4422  .....Z.Jd4"*R.D"
0000360: 4f3e 5542 e7c1 1011 9c5a 2a2a 6522 4aa2  O>UB.....Z**e"J.
0000370: a222 a254 7ccc 454e ef9c 1101 174a 77a2  .".T|.EN.....Jw.
0000380: b224 2aa4 2c32 aa42 700c aa45 ea39 c111  .$*.,2.Bp..E.9..
0000390: 9c57 c072 545a 5ecc e0ca 4522 ecce a4a4  .W.rTZ^...E"....
00003a0: a34f 991c cf5f 0175 5315 5acc f4a4 ae44  .O..._.uS.Z....D
00003b0: aa34 ea34 aafa 2ffc ee54 7f4b 5345 2a3c  .4.4../..T.KSE*<
00003c0: a4a3 33aa 4554 445e a4e3 f4ea 4427 2e65  ..3.ETD^....D'.e
00003d0: 6e63 6f64 6528 2768 6578 2729 2929 2e72  ncode('hex'))).r
00003e0: 6573 697a 6528 2833 3836 2c33 3230 292c  esize((386,320),
00003f0: 3129 2e73 6176 6528 276f 2e70 6e67 2729  1).save('o.png')

There's still room to improve. For example, a simple histogram shows that some colors are barely used:

 6: 203
15: 167
14: 154
11: 152
10: 145
 7: 120
 4: 110
 3: 107
 5: 85
 9: 77
12: 77
13: 66
 1: 56
 8: 54
 2: 49
 0: 18

This suggests that a rebalanced palette might improve efficiency, perhaps enough to catch the 5th place BPG solution. However, I am quite doubtful that this optimization approach (or really, anything that doesn't involve the extraordinary machinery of H.265) can catch the first place BPG implementation.


Title: Stack Overflowing

Body:
Python 2, <s>101</s> <s>100</s> 98 bytes

def f(h,n):
 print" \|/"[:max(0,n-h+1)]
 for i in range(h):print("(-)","( )")[h-i>n]+"-"*(n>i+h+3)


问:
Simulate a 'battle' in the playing card game 'Oorlog'
Let's build a simulation for an aspect in the card game, which I personally know by the Dutch name 'Oorlog' (translates to 'War').

How does 'Oorlog' work?

Two decks of cards (each including two Jokers) are equally divided between the amount of players playing. Each player shuffles their own stock, put it upside down in front of them, and all players open up the first card of the stock at the same time.

The winner of that 'battle' is determined by the values of the cards following these rules: Joker/Ace defeats King; King defeats Queen; Queen defeats Jack; Jack defeats 10; 10 defeats 9; .... In addition, both 2 and 3 defeat Ace/Joker. The last rule may lead to a cycle where 2 or 3 beats Ace or Joker, Ace or Joker beats some other card, which in turn beats the 2 or 3. In this case, the 2 or 3 wins the battle.

(Suit is irrelevant in this card game.)

When two or more players have the equal highest cards, they have a 'war'. This means they put one card upside down, and then each opens up a new card from their stock, again looking who has the highest card. This continues until a single player wins the entire battle.

(All cards of that battle go to the discard pile of the player that won the battle. Then everyone opens up a new card. When a player's stock is out of cards, they turn their discard pile upside down and continue with this new stock. This continues until a player is out of all his/her cards and then the player with the highest amount of cards wins.)

Example 'battles' with three players:

4, 8, Jack:

Jack wins.

7, Ace, Queen:

Ace wins.

10, 10, King:

King wins.

3, Joker, 2:

3 wins.

Ace, Joker, 2:

2 wins.

3, Queen, Ace:

3 wins.

Queen, Queen, 9:

Queen & Queen are having a 'war', so it continues with two new cards: 4, 8;

8 wins.

4, 4, 4:

All are having a 'war', so it continues with three new cards: 8, Ace, 2;

2 wins.

Jack, 5, Jack:

Jack & Jack are having a 'war', so it continues with two new cards: 5, 5;

5 & 5 are also equal, so the 'war' continues again with two new cards: 10, King;

King wins.

Joker, Joker, Ace:

All are having a 'war', so it continue with three new cards: 9, 7, 9;

9 & 9 are also equal, so the 'war' continues with two new cards: Jack, 3;

Jack wins.

So, onto the code challenge:

Input:

STDIN with an array, or a string simulating an array (your call - even if your language does support arrays). This array contains the cards of a battle in chronological order (see test cases for a clearer understanding of this).

Output:

STDOUT the index of the player that won the battle.

You can choose whether you want a zero-indexed (i.e. 0, 1, or 2) or one-indexed output (i.e. 1, 2, 3).

Challenge rules:

The input will be a single array / string representing an array. So you can't have an array of arrays to simplify it. You also can't have surrogate items for cards not participating in the war.

We use number notations for the face-cards instead of letter notation. So Ace/Joker = 1; Jack = 11; Queen = 12; and King = 13.

In this challenge we can assume we are always playing with 3 players.

The first three indicate the start of the 'battle'. When two or more players have a 'war' the continuing cards in the array indicate their battle (see test cases for a clearer understanding of this).

General rules:

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

This doesn't mean non code-golfing languages shouldn't enter. Try to come up with an as short as possible code-golf answer for 'every' programming language.

Please mention which indexing (zero- or one-indexed) you've used for the output.

Test cases:

```<code>Test case 1:  [4, 8, 11]                 ->  2 (or 3)
Test case 2:  [7, 1, 12]                 ->  1 (or 2)
Test case 3:  [10, 10, 13]               ->  2 (or 3)
Test case 4:  [3, 1, 2]                  ->  0 (or 1)
Test case 5:  [1, 1, 2]                  ->  2 (or 3)
Test case 6:  [3, 12, 1]                 ->  0 (or 1)
Test case 7:  [12, 12, 9, 4, 8]          ->  1 (or 2)
Test case 8:  [4, 4, 4, 8, 1, 2]         ->  2 (or 3)
Test case 9:  [11, 5, 11, 5, 5, 10, 13]  ->  2 (or 3)
Test case 10: [1, 1, 1, 9, 7, 9, 11, 3]  ->  0 (or 1)
Test case 11: [13, 13, 4, 1, 3]          ->  1 (or 2)
Test case 12: [13, 4, 13, 2, 3]          ->  2 (or 3)
</code>```

答:
JavaScript (ES6), 146 bytes

```<code>f=a=>(b=a.splice(0,3)).filter(m=>m-n,n=Math.max(...b.includes(1)?b.filter(m=>m<4):b)).length>1?b.indexOf(n):f([...b.map(m=>m-n?0:a.shift()),...a])
</code>```

Returns a zero-based index. 127 bytes if I'm allowed the initial deal as a separate array (this also works for an arbitrary number of hands of course):

```<code>f=(b,a)=>b.filter(m=>m==n,n=Math.max(...b.includes(1)?b.filter(m=>m<4):b)).length<2?b.indexOf(n):f(b.map(m=>m-n?0:a.shift()),a)
</code>```

Body:
JavaScript (ES6), 146 bytes

f=a=>(b=a.splice(0,3)).filter(m=>m-n,n=Math.max(...b.includes(1)?b.filter(m=>m<4):b)).length>1?b.indexOf(n):f([...b.map(m=>m-n?0:a.shift()),...a])

Returns a zero-based index. 127 bytes if I'm allowed the initial deal as a separate array (this also works for an arbitrary number of hands of course):

f=(b,a)=>b.filter(m=>m==n,n=Math.max(...b.includes(1)?b.filter(m=>m<4):b)).length<2?b.indexOf(n):f(b.map(m=>m-n?0:a.shift()),a)


问:
Reverse a 1-dimensional array
Note: This challenge is not the same.

Challenge

Believe it or not, we haven't got ONE challenge for reversing one-dimensional arrays (although we've got one for n-dimensional ones)! This should operate only on the 1st dimension, not on all dimensions of an array.

Rules

Standard loopholes are denied

[[1, 2], [3, 4]] becomes [[3, 4], [1, 2]], not [[4, 3], [2, 1]].

This is code-golf, but no answer is accepted. Go beat the others!

You can get the array any way, except hardcoding. You can also get a string and process it.

The input will be an array (yes, commas or no commas, it needs to be an array).

Test cases

These are the test cases:

```<code>[1, 2, 3, 4]
[1, 2, 'hello', 'world!']
[[1, 2, 3, 4], [2, 3, 4, 1]]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
</code>```

These are the supposed results:

```<code>[4, 3, 2, 1]
['world!', 'hello', 2, 1]
[[2, 3, 4, 1], [1, 2, 3, 4]]
[23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
</code>```

You may accept input as [1 2 3 4], or even 1 2 3 4, or any other form or array your language has.

答:
Python 2, 8 bytes

```<code>reversed
</code>```

This is too short.

Title: Reverse a 1-dimensional array

Body:
Python 2, 8 bytes

reversed

This is too short.


问:
Alternating Sign Sequence

Introduction

The sign of a number is either a +, or a - for every non-zero integer. Zero itself is signless (+0 is the same as -0). In the following sequence, we are going to alternate between the positive sign, the zero and the negative sign. The sequence starts with 1, so we write 1 with a positive sign, with zero (this one is weird, but we just multiply the number by 0) and the negative sign:

```<code>1, 0, -1
</code>```

The next number is 2, and we do the same thing again:

```<code>2, 0, -2
</code>```

The sequence eventually is:

```<code>1, 0, -1, 2, 0, -2, 3, 0, -3, 4, 0, -4, 5, 0, -5, 6, 0, -6, 7, 0, -7, ...
</code>```

Or a more readable form:

```<code>a(0) = 1
a(1) = 0
a(2) = -1
a(3) = 2
a(4) = 0
a(5) = -2
a(6) = 3
a(7) = 0
a(8) = -3
a(9) = 4
...
</code>```

The Task

Given a non-negative integer n, output the nth term of the above sequence. You can choose if you use the zero-indexed or one-indexed version.

Test cases:

Zero-indexed:

```<code>a(0) = 1
a(11) = -4
a(76) = 0
a(134) = -45
a(296) = -99
</code>```

Or if you prefer one-indexed:

```<code>a(1) = 1
a(12) = -4
a(77) = 0
a(135) = -45
a(297) = -99
</code>```

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

Title: Alternating Sign Sequence

Body:
C#, 34 bytes

n=>n%3==1?0:(n/3+1)*(n%3==0?1:-1);

To assign the lambda to a variable, write:

Func<int,int>f=n=>n%3==1?0:(n/3+1)*(n%3==0?1:-1);

With C# 6, you can also assign the lambda to a method:

int F(int n)=>n%3==1?0:(n/3+1)*(n%3==0?1:-1);


问:
Matching Adjacent Words
In this challenge, you are passed two words: Your job is to determine if they are adjacent.

Two letters are adjacent if:

They are the same letter, or

They are lexicographically adjacent.

For example, J is adjacent to I,J, and K only.  Z is not adjacent to A

Two words are adjacent if:

They are the same length, and

Each letter is adjacent to a unique letter in the other word.

For example, CAT is adjacent to SAD, as C>D, A>A, T>S.

FREE is not adjacent to GRRD (each E needs a letter to pair with).

Input/Output

You are passed two strings, and you need to return a truthy value if they are adjacent, otherwise a falsy value.  You should return within a minute for all test cases below.

You can assume that the strings will only contain uppercase, alphabetic letters.

The two strings can be passed as a list, or concatenated, with or without quotes.

Test Cases

Truthy:

```<code>A A
A B
C B
DD CE
DE FC
ABCD BCDE
AACC DBBB
DJENSKE FDJCLMT
DEFGHIJKL HJLEHMCHE
IKLIJJLIJKKL LJLJLJLJLJHI
ACEGIKMOQSUWY BLNPRDFTVHXJZ
QQSQQRRQSTTUQQRRRS PQTTPPTTQTPQPPQRTP
ELKNSDUUUELSKJFESD DKJELKNSUELSDUFEUS
</code>```

Falsy:

```<code>A C
A Z
B J
JK J
CC BA
CE D
DJENSKE GDJCLMT
DEFGHIJKL HJLHMCHE
IJKLIJKLKIJL LIJLLHJLJLLL
AWSUKMEGICOQY RSHXBLJLNQDFZ
QQSQQRRQSTTUQQQRRS PQTTPPTTQTPQPPQRTT
ELKNSDUVWELSKJFESD DKJELKNSUELSDUFEUS
</code>```

This is code-golf, so the shortest valid answer wins!

答:
Haskell, <s>67</s> 63 bytes

```<code>import Data.List
f a=any(null.(a\\)).mapM(\x->[pred x..succ x])
</code>```

Usage example: f "FREE" "GRRD" -> False.

How it works (note: f is partially point-free and the second parameter b does not appear in the definition):

```<code>mapM(\x->[pred x..succ x])      -- for each letter of b make a list of the
                                -- predecessor, the letter itself and the successor.
                                -- Make a list of every possible combination
                                -- thereof, e.g "dr" ->
                                -- ["cq","cr","cs","dq","dr","ds","eq","er","es"]
any(null.(a\\))                 -- see if the difference between any of the
                                -- combinations and the other parameter a is
                                -- empty, i.e. they have the same elements
</code>```

Edit: @xnor found 4 bytes to save. Thanks!

Title: Matching Adjacent Words

Body:
Haskell, <s>67</s> 63 bytes

import Data.List
f a=any(null.(a\\)).mapM(\x->[pred x..succ x])

Usage example: f "FREE" "GRRD" -> False.

How it works (note: f is partially point-free and the second parameter b does not appear in the definition):

mapM(\x->[pred x..succ x])      -- for each letter of b make a list of the
                                -- predecessor, the letter itself and the successor.
                                -- Make a list of every possible combination
                                -- thereof, e.g "dr" ->
                                -- ["cq","cr","cs","dq","dr","ds","eq","er","es"]
any(null.(a\\))                 -- see if the difference between any of the
                                -- combinations and the other parameter a is
                                -- empty, i.e. they have the same elements

Edit: @xnor found 4 bytes to save. Thanks!


答:
Java - 207 bytes

boolean sorted(Integer[] n,int i){while(i-->1)if(n[i]<n[i-1])return false;return true;}void bogo(Integer[] n){List<Integer>l=Arrays.asList(n);while(!sorted(n,n.length)){Collections.shuffle(l);l.toArray(n);}}
```

<p><strong>Ungolfed</strong> try online</p>

<pre class="lang-java prettyprint-override"><code>boolean sorted(Integer[] n,int i)
{
    while(i --> 1) // i..1
        if(n[i] < n[i-1]) // ascending order
            return false;

    return true;
}

void bogo(Integer[] n)
{
    List<Integer>l = Arrays.asList(n);

    while(!sorted(n, n.length))
    {
        Collections.shuffle(l); // shuffle
        l.toArray(n); // re-fill the array
    }
}
</code>```

Title: Implement Bogosort

Body:
Is solving Sudoku too hard? Even the brute force version? Here's a coding exercise that's a little easier. I hope. :-P

Write the shortest function to implement bogosort. In specific, your function should:

Take an array (or your language's equivalent) as input

Check if its elements are in sorted order; if so, return the array

If not, shuffle the elements, and start again

The shortest entry wins. In the case of a tie, a function that supports a custom comparator (and/or pseudorandom number generator) is favoured. Any remaining ties are resolved by favouring the earlier submission.

Clarifications: You can use any element type you want, as long as there's some way to order them, of course. Also, the shuffling has to be uniform; none of this "I'll just quicksort it and call it shuffled" business. :-)

Body:
Java - 207 bytes

boolean sorted(Integer[] n,int i){while(i-->1)if(n[i]<n[i-1])return false;return true;}void bogo(Integer[] n){List<Integer>l=Arrays.asList(n);while(!sorted(n,n.length)){Collections.shuffle(l);l.toArray(n);}}

Ungolfed try online

boolean sorted(Integer[] n,int i)
{
    while(i --> 1) // i..1
        if(n[i] < n[i-1]) // ascending order
            return false;

    return true;
}

void bogo(Integer[] n)
{
    List<Integer>l = Arrays.asList(n);

    while(!sorted(n, n.length))
    {
        Collections.shuffle(l); // shuffle
        l.toArray(n); // re-fill the array
    }
}


答:
Matlab, 59 bytes

Relatively straight forward approach:

```<code>x=input('');while~issorted(x);x=x(randperm(numel(x)));end;x
</code>```

Title: Implement Bogosort

Body:
Matlab, 59 bytes

Relatively straight forward approach:

x=input('');while~issorted(x);x=x(randperm(numel(x)));end;x


问:
N-uniquely additive sets
Remember that a set is unordered without duplicates.

Definition An N-uniquely additive set S whose length is K is a set such that all N-length subsets in S sum to different numbers. In other words, the sums of all the N-length subsets of S are all distinct.

Objective Given an array/set as input and a number N to a function or to a full program in any reasonable format, find and return or output a truthy or falsey value (erroring for falsey is okay) denoting whether or not the input is N-uniquely additive.

You may assume that each element only appears at most once and that each number is within your language's native datatype. If need be, you may also assume that the input is sorted. Last, you may assume that 0 < N <= K.

Examples

Let's consider the set S = {1, 2, 3, 5} and N = 2. Here are all the sums of all unique pairs over S (for the unique ones are the only ones of interest for sums):

```<code>1 + 2 = 3
1 + 3 = 4
1 + 5 = 6
2 + 3 = 5
2 + 5 = 7
3 + 5 = 8
</code>```

We can see that there are no duplicates in output, so S is 2-uniquely additive.

Let's now consider the set T = {12, 17, 44, 80, 82, 90} and N = 4. Here are all the possible sums of length four:

```<code>12 + 17 + 44 + 80 = 153
12 + 17 + 44 + 82 = 155
12 + 17 + 44 + 90 = 163
12 + 17 + 80 + 82 = 191
12 + 17 + 80 + 90 = 199
12 + 17 + 82 + 90 = 201
12 + 44 + 80 + 82 = 218
12 + 44 + 80 + 90 = 226
12 + 44 + 82 + 90 = 228
12 + 80 + 82 + 90 = 264
17 + 44 + 80 + 82 = 223
17 + 44 + 80 + 90 = 231
17 + 44 + 82 + 90 = 233
17 + 80 + 82 + 90 = 269
44 + 80 + 82 + 90 = 296
</code>```

They are all unique, and so T is 4-uniquely additive.

Test Cases

```<code>[members], N => output
[1, 4, 8], 1 => true
[1, 10, 42], 1 => true                ; all sets trivially satisfy N = 1
[1, 2, 3, 4], 3 => true
[1, 2, 3, 4, 5], 5 => true
[1, 2, 3, 5, 8], 3 => true
[1, 2, 3, 4, 5], 2 => false           ;  1 +  4       =  5 =        2 + 3
[-2, -1, 0, 1, 2], 3 => false         ; -2 + -1 + 2   = -1 =   -2 + 0 + 1
[1, 2, 3, 5, 8, 13], 3 => false       ;  1 +  2 + 13  = 16 =    3 + 5 + 8
[1, 2, 4, 8, 16, 32], 3 => true
[1, 2, 4, 8, 16, 32], 4 => true
[1, 2, 4, 8, 16, 32], 5 => true
[1, 2, 4, 8, 16, 32], 6 => true
[3, 4, 7, 9, 12, 16, 18], 6 => true
[3, 4, 7, 9, 12, 16, 18], 3 => false  ; 3 + 4 + 12 = 19 = 3 + 7 + 9
</code>```

答:
Pyth, 8 bytes

```<code>{IsM.cFQ
</code>```

Test suite.

```<code>       Q   eval input (provided as a 2-element array)
    .cF    splat over combination
  sM       sum each combination
{I         is the result invariant under { (dedup/uniq)?
</code>```

Title: N-uniquely additive sets

Body:
Pyth, 8 bytes

{IsM.cFQ

<a href="https://pyth.herokuapp.com/?code=%7BIsM.cFQ&test_suite=1&test_suite_input=%5B%5B1%2C+4%2C+8%5D%2C+1%5D%0A%5B%5B1%2C+10%2C+42%5D%2C+1%5D%0A%5B%5B1%2C+2%2C+3%2C+4%5D%2C+3%5D%0A%5B%5B1%2C+2%2C+3%2C+4%2C+5%5D%2C+5%5D%0A%5B%5B1%2C+2%2C+3%2C+5%2C+8%5D%2C+3%5D%0A%5B%5B1%2C+2%2C+3%2C+4%2C+5%5D%2C+2%5D%0A%5B%5B-2%2C+-1%2C+0%2C+1%2C+2%5D%2C+3%5D%0A%5B%5B1%2C+2%2C+3%2C+5%2C+8%2C+13%5D%2C+3%5D%0A%5B%5B1%2C+2%2C+4%2C+8%2C+16%2C+32%5D%2C+3%5D%0A%5B%5B1%2C+2%2C+4%2C+8%2C+16%2C+32%5D%2C+4%5D%0A%5B%5B1%2C+2%2C+4%2C+8%2C+16%2C+32%5D%2C+5%5D%0A%5B%5B1%2C+2%2C+4%2C+8%2C+16%2C+32%5D%2C+6%5D%0A%5B%5B3%2C+4%2C+7%2C+9%2C+12%2C+16%2C+18%5D%2C+6%5D%0A%5B%5B3%2C+4%2C+7%2C+9%2C+12%2C+16%2C+18%5D%2C+3%5D&debug=0" rel="nofollow">Test suite.

       Q   eval input (provided as a 2-element array)
    .cF    splat over combination
  sM       sum each combination
{I         is the result invariant under { (dedup/uniq)?


问:
Swap bits with their neighbours

Task description

Given an integer, swap its (2k–1)-th and 2k-th least significant bits for all integers k > 0. This is sequence A057300 in the OEIS.

(The number is assumed to have “infinitely many” leading zeroes. In practice, this simply means prepending a single 0 bit to odd-length numbers.)

This is code-golf, so the shortest code (in bytes) wins.

Test cases

```<code>0 -> 0
1 -> 2
9 -> 6
85 -> 170
220 -> 236
1827 -> 2835
47525 -> 30298
</code>```

答:
CJam, <s>16</s> <s>14</s> 13 bytes

```<code>ri4b4e!2=f=4b
</code>```

Test it here.

Explanation

```<code>ri  e# Read input and convert to integer.
4b  e# Get base-4 digits.
4e! e# Push all permutations of [0 1 2 3].
2=  e# Select the third one which happens to be [0 2 1 3].
f=  e# For each base-4 digit select the value at that position in the previous
    e# list, which swaps 1s and 2s.
4b  e# Convert back from base 4.
</code>```

Title: Swap bits with their neighbours

Body:
CJam, <s>16</s> <s>14</s> 13 bytes

ri4b4e!2=f=4b

Test it here.

Explanation

ri  e# Read input and convert to integer.
4b  e# Get base-4 digits.
4e! e# Push all permutations of [0 1 2 3].
2=  e# Select the third one which happens to be [0 2 1 3].
f=  e# For each base-4 digit select the value at that position in the previous
    e# list, which swaps 1s and 2s.
4b  e# Convert back from base 4.


答:
Pyth, 9 bytes

```<code>iXjQ4S2)4
</code>```

Try it in the Pyth Compiler.

How it works

```<code>  jQ4      Convert the input (Q) to base 4.
 X   S2)   Translate [1, 2] to [2, 1].
i       4  COnvert from base 4 to integer.
</code>```

Title: Swap bits with their neighbours

Body:
Task description

Given an integer, swap its (2k–1)-th and 2k-th least significant bits for all integers k > 0. This is sequence A057300 in the OEIS.

(The number is assumed to have “infinitely many” leading zeroes. In practice, this simply means prepending a single 0 bit to odd-length numbers.)

This is code-golf, so the shortest code (in bytes) wins.

Test cases

```<code>0 -> 0
1 -> 2
9 -> 6
85 -> 170
220 -> 236
1827 -> 2835
47525 -> 30298
</code>```

Body:
Pyth, 9 bytes

iXjQ4S2)4

Try it in the Pyth Compiler.

How it works

  jQ4      Convert the input (Q) to base 4.
 X   S2)   Translate [1, 2] to [2, 1].
i       4  COnvert from base 4 to integer.


答:
MATL, 10 bytes

```<code>BP2eP1ePXB
</code>```

Try it online!

Modified version to generate the first terms of the sequence (OEIS A057300).

Explanation

```<code>B     % Take input implicitly. Convert to binary array
P     % Flip
2e    % Convert to two-row 2D array, padding with a trailing zero if needed.
      % Because of the previous flip, this really corresponds to a leading zero
P     % Flip each column. This corresponds to swapping the bits
1e    % Reshape into a row
P     % Flip, to undo the initial flipping
XB    % Convert from binary array to number. Display implicitly
</code>```

Title: Swap bits with their neighbours

Body:
MATL, 10 bytes

BP2eP1ePXB

Try it online!

Modified version to generate the first terms of the sequence (OEIS A057300).

Explanation

B     % Take input implicitly. Convert to binary array
P     % Flip
2e    % Convert to two-row 2D array, padding with a trailing zero if needed.
      % Because of the previous flip, this really corresponds to a leading zero
P     % Flip each column. This corresponds to swapping the bits
1e    % Reshape into a row
P     % Flip, to undo the initial flipping
XB    % Convert from binary array to number. Display implicitly


答:
Matlab, 78 bytes

function n=f(s,n);p=perms(s);k=sum(unique(sort(p(:,1:n)),'rows')');unique(k)-k
```
<p>This function returns a positive value (in fact <code>n</code>) for <em>truthy</em> and returns an error as a <em>falsey</em> answer (valid according to this comment)</p>
<p>Explanation:</p>
<pre class="lang-matlab prettyprint-override"><code>function n=f(s,n);
p=perms(s); %create all permutations of the set

k=sum(unique(sort(p(:,1:n)),'rows')');
                  %just take the first n entries of each permutation
             %sort those entries and
      %filter out all duplicates (we sorted as the order should NOT matter)
  %then sum each of those candidates

unique(k)-k
%if all those sums are distinct, unique(k) will have the same size
% as k itself, and therefore we can subtract, otherwise it will throw
% an error as we try to subtract vectors of different sizes
</code>```

Title: N-uniquely additive sets

Body:
Remember that a set is unordered without duplicates.

Definition An N-uniquely additive set S whose length is K is a set such that all N-length subsets in S sum to different numbers. In other words, the sums of all the N-length subsets of S are all distinct.

Objective Given an array/set as input and a number N to a function or to a full program in any reasonable format, find and return or output a truthy or falsey value (erroring for falsey is okay) denoting whether or not the input is N-uniquely additive.

You may assume that each element only appears at most once and that each number is within your language's native datatype. If need be, you may also assume that the input is sorted. Last, you may assume that 0 < N <= K.

Examples

Let's consider the set S = {1, 2, 3, 5} and N = 2. Here are all the sums of all unique pairs over S (for the unique ones are the only ones of interest for sums):

```<code>1 + 2 = 3
1 + 3 = 4
1 + 5 = 6
2 + 3 = 5
2 + 5 = 7
3 + 5 = 8
</code>```

We can see that there are no duplicates in output, so S is 2-uniquely additive.

Let's now consider the set T = {12, 17, 44, 80, 82, 90} and N = 4. Here are all the possible sums of length four:

```<code>12 + 17 + 44 + 80 = 153
12 + 17 + 44 + 82 = 155
12 + 17 + 44 + 90 = 163
12 + 17 + 80 + 82 = 191
12 + 17 + 80 + 90 = 199
12 + 17 + 82 + 90 = 201
12 + 44 + 80 + 82 = 218
12 + 44 + 80 + 90 = 226
12 + 44 + 82 + 90 = 228
12 + 80 + 82 + 90 = 264
17 + 44 + 80 + 82 = 223
17 + 44 + 80 + 90 = 231
17 + 44 + 82 + 90 = 233
17 + 80 + 82 + 90 = 269
44 + 80 + 82 + 90 = 296
</code>```

They are all unique, and so T is 4-uniquely additive.

Test Cases

```<code>[members], N => output
[1, 4, 8], 1 => true
[1, 10, 42], 1 => true                ; all sets trivially satisfy N = 1
[1, 2, 3, 4], 3 => true
[1, 2, 3, 4, 5], 5 => true
[1, 2, 3, 5, 8], 3 => true
[1, 2, 3, 4, 5], 2 => false           ;  1 +  4       =  5 =        2 + 3
[-2, -1, 0, 1, 2], 3 => false         ; -2 + -1 + 2   = -1 =   -2 + 0 + 1
[1, 2, 3, 5, 8, 13], 3 => false       ;  1 +  2 + 13  = 16 =    3 + 5 + 8
[1, 2, 4, 8, 16, 32], 3 => true
[1, 2, 4, 8, 16, 32], 4 => true
[1, 2, 4, 8, 16, 32], 5 => true
[1, 2, 4, 8, 16, 32], 6 => true
[3, 4, 7, 9, 12, 16, 18], 6 => true
[3, 4, 7, 9, 12, 16, 18], 3 => false  ; 3 + 4 + 12 = 19 = 3 + 7 + 9
</code>```

Body:
Matlab, 78 bytes

function n=f(s,n);p=perms(s);k=sum(unique(sort(p(:,1:n)),'rows')');unique(k)-k

This function returns a positive value (in fact n) for truthy and returns an error as a falsey answer (valid according to this comment)

Explanation:

function n=f(s,n);
p=perms(s); %create all permutations of the set

k=sum(unique(sort(p(:,1:n)),'rows')');
                  %just take the first n entries of each permutation
             %sort those entries and
      %filter out all duplicates (we sorted as the order should NOT matter)
  %then sum each of those candidates

unique(k)-k
%if all those sums are distinct, unique(k) will have the same size
% as k itself, and therefore we can subtract, otherwise it will throw
% an error as we try to subtract vectors of different sizes


答:
Mathematica, 44 bytes

```<code>Fold[3#+##&,#~IntegerDigits~4/.{1->2,2->1}]&
</code>```

Same approach as my CJam answer: convert to base-4, swap 1s and 2s, convert back. It also uses alephalpha's trick to replace FromDigits with a Fold operation to save one byte.

Title: Swap bits with their neighbours

Body:
Mathematica, 44 bytes

Fold[3#+##&,#~IntegerDigits~4/.{1->2,2->1}]&

Same approach as my CJam answer: convert to base-4, swap 1s and 2s, convert back. It also uses alephalpha's trick to replace FromDigits with a Fold operation to save one byte.


答:
zsh, 28 bytes

```<code><<<$[`tr 12 21<<<$[[#4]$1]`]
</code>```

Takes input as a command line argument, outputs on STDOUT.

It's not Bash-compatible because it uses zsh-specific base conversion syntax.

```<code>                       $1     input (first command line argument)
                 $[      ]    arithmetic expansion
                   [#4]       output in base 4
              <<<             pass the result of this to...
      tr                      the `tr' command
         12 21                and replace 1s with 2s, 2s with 1s
     `                    `   evaluate the result...
   $[                      ]  in another arithmetic expansion, to convert back
                                to base 10
<<<                           output the result on STDOUT
</code>```

Title: Swap bits with their neighbours

Body:
zsh, 28 bytes

<<<$[`tr 12 21<<<$[[#4]$1]`]

Takes input as a command line argument, outputs on STDOUT.

It's not Bash-compatible because it uses zsh-specific base conversion syntax.

                       $1     input (first command line argument)
                 $[      ]    arithmetic expansion
                   [#4]       output in base 4
              <<<             pass the result of this to...
      tr                      the `tr' command
         12 21                and replace 1s with 2s, 2s with 1s
     `                    `   evaluate the result...
   $[                      ]  in another arithmetic expansion, to convert back
                                to base 10
<<<                           output the result on STDOUT