问:
Random word-sentence-story generator
This question got me nostalgic: Build a word generator!

In the '80s I wrote a simple word generator in under 42kB (code and working memory) that would take a collection of strings and use them to create new words and phrases.

Your task is to recreate this program in as few bytes as possible, with a few minor updates.

Your program will take the input and ensure that there are two spaces after each sentence. Each sentence should end with a full-stop (.). There must not be three consecutive spaces anywhere in the text. Line breaks should be replaced by a single space. There should only be two spaces after a sentence and nowhere else.

Record the number of times each character triplet appears. If you're using regex to break up the text /\X/ is a good way to match a Unicode glyph (could be multiple codepoints, not necessarily a single codepoint). For the purposes of counting, assume that there are two spaces at the start of the text and two spaces at the end.

Hopefully, you now have some good data to work with! Randomly select a triplet where the first two characters are both spaces. For example, if the only two matching triplets are [' ', ' ', 'I'] => 3 and [' ', ' ', 'A'] => 7 there should be a 30% chance of selecting I and a 70% chance of selecting A. Shift the characters along and randomly select one of the next triplets. If A was the first character selected the next triplets might be [' ', 'A', 'n'] => 2, [' ', 'A', 't'] => 2 and [' ', 'A', 's'] => 3. Randomly select one using the correct weightings and so on. Repeat until the last two characters are both spaces, then output the string generated if it's 100 characters or longer. If the output is less than 100 characters, repeat the process again, adding to the existing string until it is at least 100 characters long.

You should end up with output something like below, which looks almost like the input language. As my test input I used the first chapter of Charles Dickens' A Tale of Two Cities but you can use any text you feel like. Please provide a link to your input text (preferably not copyrighted) and a sample of the output.

In harithe dir, in hadede Fards fouses, by we aws, mand by nouse St. Merty exce, he th at ing ithe inceir farce, a Capir bod day, one defor ond rodmane of the ce witsethe after seas a pleark parison a prion to eves hund Parglairty the beere tielaires, and wrece to ente comses itic plaw andozene hich tat andiver, a he pent wer thneople, the werseved froads se sebron theire mands inge Woodmage larestown ther Ligh, sed and was the withaved broce pers. Brity-fired of bust a din humakings th, incre pas of the amonoblis the a kne Chrooteres, to offle ound lies yeargland this thing by on the goil ituarivesdozen, moolurd instive the whe only a king was thelfe one divery. Und the intren a king thiging ors, and he tow, afty out pas musears, thot he in aces, it it Fran, tho the blets be anglaters ouseticiodmand whimeng was by the primed tord a ce a dirience.

TL;DR

Build sentences from test input by analysing the frequency of the character triplets, and using those frequencies to randomly select each character in sequence.

You can pre-format your text to make sure it matches the input requirements. It doesn't have to contribute to your byte-count.

If your language can't cope with Unicode at all, limit the input to ASCII characters. Ideally, your program should be able to cope with combining marks (accents and the like) if they are encoded separately but it doesn't have to. It shouldn't affect the output much, although it's possible you might get weird output in rare cases. e.g. if é is encoded as two codepoints, e+combining acute accent, it SHOULD (but doesn't HAVE to) treat it as a single glyph.

答:
PowerShell, 141 bytes

```<code>param($d)$o='  '
while($o.Length-lt100-or$o.EndsWith('  ')){if(($s=$d[($x=Get-Random $d.Length)-2]+$d[$x-1])-eq$o[-2]+$o[-1]){$o+=$d[$x]}}$o
</code>```

It's a port of @Blue's answer as well. Assuming pre-formatted text, as mentioned in the question.

e.g.

```<code>PS U:\posh> .\New-RandomStory.ps1 @'
  It was the best of times, it was the worst of times,
it was the age of wisdom, it was the age of foolishness,
it was the epoch of belief, it was the epoch of incredulity,
it was the season of Light, it was the season of Darkness,
it was the spring of hope, it was the winter of despair,
we had everything before us, we had nothing before us,
we were all going direct to Heaven, we were all going direct
the other way--in short, the period was so far like the present
period, that some of its noisiest authorities insisted on its
being received, for good or for evil, in the superlative degree
of comparison only.
'@

  It wincres the befor evil, its the all going redulight, fort, the of it we best waso forst waso fo
</code>```

Title: Random word-sentence-story generator

Body:
PowerShell, 141 bytes

param($d)$o='  '
while($o.Length-lt100-or$o.EndsWith('  ')){if(($s=$d[($x=Get-Random $d.Length)-2]+$d[$x-1])-eq$o[-2]+$o[-1]){$o+=$d[$x]}}$o

It's a port of @Blue's answer as well. Assuming pre-formatted text, as mentioned in the question.

e.g.

PS U:\posh> .\New-RandomStory.ps1 @'
  It was the best of times, it was the worst of times,
it was the age of wisdom, it was the age of foolishness,
it was the epoch of belief, it was the epoch of incredulity,
it was the season of Light, it was the season of Darkness,
it was the spring of hope, it was the winter of despair,
we had everything before us, we had nothing before us,
we were all going direct to Heaven, we were all going direct
the other way--in short, the period was so far like the present
period, that some of its noisiest authorities insisted on its
being received, for good or for evil, in the superlative degree
of comparison only.
'@

  It wincres the befor evil, its the all going redulight, fort, the of it we best waso forst waso fo


问:
Draw the national flag of Iceland
This year's UEFA Euro 2016 is over and besides a couple of negative headlines there has been a very positive surprise as well – the Iceland national football team. Let's draw their national flag.

Input

Well, obviously this challenge has no input.

Output

Draw the flag of Iceland in any applicable visual format of at least 100 x 72 pixels or 25 x 18 characters.

Save the output to a file or present it instantly – example formats are: images like png, jpg etc., vector graphics, draw on HTML canvas or even use non-whitespace characters for visualization.

Use these colors: blue: #0048e0, white: #ffffff and red: #d72828.

If your language doesn't support specific color values, use the standard values for red, blue and white from the ANSI color codes.

Draw the flag with the correct proportions, as shown in the figure below:

Boilerplate

You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it.

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

Standard loopholes are disallowed.

Leaderboard

var QUESTION_ID = 85141; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 41859; // This should be the user ID of the challenge author.
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;function answersUrl(index) {return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;}function commentUrl(index, answers) {return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;}function getAnswers() {jQuery.ajax({url: answersUrl(answer_page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);answers_hash = [];answer_ids = [];data.items.forEach(function(a) {a.comments = [];var id = +a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id] = a;});if (!data.has_more) more_answers = false;comment_page = 1;getComments();}});}function getComments() {jQuery.ajax({url: commentUrl(comment_page++, answer_ids),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {data.items.forEach(function(c) {if (c.owner.user_id === OVERRIDE_USER)answers_hash[c.post_id].comments.push(c);});if (data.has_more) getComments();else if (more_answers) getAnswers();else process();}});}getAnswers();var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG = /^Override\s*header:\s*/i;function getAuthorName(a) {return a.owner.display_name;}function process() {var valid = [];answers.forEach(function(a) {var body = a.body;a.comments.forEach(function(c) {if(OVERRIDE_REG.test(c.body))body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';});var match = body.match(SCORE_REG);if (match)valid.push({user: getAuthorName(a),size: +match[2],language: match[1],link: a.share_link,});});valid.sort(function (a, b) {var aB = a.size,bB = b.size;return aB - bB});var languages = {};var place = 1;var lastSize = null;var lastPlace = 1;valid.forEach(function (a) {if (a.size != lastSize)lastPlace = place;lastSize = a.size;++place;var answer = jQuery("#answer-template").html();answer = answer.replace("{{PLACE}}", lastPlace + ".").replace("{{NAME}}", a.user).replace("{{LANGUAGE}}", a.language).replace("{{SIZE}}", a.size).replace("{{LINK}}", a.link);answer = jQuery(answer);jQuery("#answers").append(answer);var lang = a.language;if (! /<a/.test(lang)) lang = '' + lang + '';lang = jQuery(lang).text().toLowerCase();languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};});var langs = [];for (var lang in languages)if (languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function (a, b) {if (a.uniq > b.uniq) return 1;if (a.uniq < b.uniq) return -1;return 0;});for (var i = 0; i < langs.length; ++i){var language = jQuery("#language-template").html();var lang = langs[i];language = language.replace("{{LANGUAGE}}", lang.lang).replace("{{NAME}}", lang.user).replace("{{SIZE}}", lang.size).replace("{{LINK}}", lang.link);language = jQuery(language);jQuery("#languages").append(language);}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}#answer-list {padding: 10px;width: 290px;float: left;}#language-list {padding: 10px;width: 290px;float: left;}table thead {font-weight: bold;}table td {padding: 5px;}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

If you can't find your answer, format your language and byte count as explained in the Leaderboard's "Info Section".

This challenge is inspired by Draw the national flag of france.

答:
Atari 8-bit executable, 123 bytes

Another "just for fun" entry, this program is meant to be run on an Atari 8-bit computer or emulator. For example, to load the program on Atari800, just run:

```<code>atari800 iceland.xex
</code>```

Machine code (in hex bytes)

```<code>ff ff 00 06 74 06 a9 1b 8d 30 02 a9 06 8d 31 02
a9 44 8d c4 02 a9 0f 8d c5 02 a9 84 8d c6 02 d0
fe 70 70 70 48 57 06 48 57 06 48 57 06 48 57 06
48 57 06 48 57 06 48 57 06 48 61 06 48 6b 06 48
6b 06 48 61 06 48 57 06 48 57 06 48 57 06 48 57
06 48 57 06 48 57 06 48 57 06 41 1b 06 ff fe 5b
ff ff ff c0 00 00 00 aa aa 5a aa aa aa 80 00 00
00 55 55 55 55 55 55 40 00 00 00
</code>```

Assembler source code (can be compiled with MADS):

```<code>        org $0600
        lda <dlist
        sta $0230
        lda >dlist
        sta $0231
        lda #$44
        sta $02c4
        lda #$0f
        sta $02c5
        lda #$84
        sta $02c6
loop    bne loop
dlist   dta $70, $70, $70
        dta $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1)
        dta $48, a(line2)
        dta $48, a(line3), $48, a(line3)
        dta $48, a(line2)
        dta $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1)
        dta $41, a(dlist)
line1   dta $ff, $fe, $5b, $ff, $ff, $ff, $c0, $00, $00, $00
line2   dta $aa, $aa, $5a, $aa, $aa, $aa, $80, $00, $00, $00
line3   dta $55, $55, $55, $55, $55, $55, $40, $00, $00, $00
</code>```

How it works:

The program uses a custom display list that's based on ANTIC Mode 8 (40 pixels per line, 2 bpp). Repeated lines are loaded from the same memory location. After setting up the display, the program enters an infinite loop.

Screenshot:

ContentLicense: CC BY-SA 3.0

Title: Draw the national flag of Iceland

Body:
Atari 8-bit executable, 123 bytes

Another "just for fun" entry, this program is meant to be run on an Atari 8-bit computer or emulator. For example, to load the program on Atari800, just run:

atari800 iceland.xex

Machine code (in hex bytes)

ff ff 00 06 74 06 a9 1b 8d 30 02 a9 06 8d 31 02
a9 44 8d c4 02 a9 0f 8d c5 02 a9 84 8d c6 02 d0
fe 70 70 70 48 57 06 48 57 06 48 57 06 48 57 06
48 57 06 48 57 06 48 57 06 48 61 06 48 6b 06 48
6b 06 48 61 06 48 57 06 48 57 06 48 57 06 48 57
06 48 57 06 48 57 06 48 57 06 41 1b 06 ff fe 5b
ff ff ff c0 00 00 00 aa aa 5a aa aa aa 80 00 00
00 55 55 55 55 55 55 40 00 00 00

Assembler source code (can be compiled with MADS):

        org $0600
        lda <dlist
        sta $0230
        lda >dlist
        sta $0231
        lda #$44
        sta $02c4
        lda #$0f
        sta $02c5
        lda #$84
        sta $02c6
loop    bne loop
dlist   dta $70, $70, $70
        dta $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1)
        dta $48, a(line2)
        dta $48, a(line3), $48, a(line3)
        dta $48, a(line2)
        dta $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1), $48, a(line1)
        dta $41, a(dlist)
line1   dta $ff, $fe, $5b, $ff, $ff, $ff, $c0, $00, $00, $00
line2   dta $aa, $aa, $5a, $aa, $aa, $aa, $80, $00, $00, $00
line3   dta $55, $55, $55, $55, $55, $55, $40, $00, $00, $00

How it works:

The program uses a custom display list that's based on ANTIC Mode 8 (40 pixels per line, 2 bpp). Repeated lines are loaded from the same memory location. After setting up the display, the program enters an infinite loop.

Screenshot:


问:
m3ph1st0s's programming puzzle 1 (C++)
This is the first of a series of C++ puzzles for you. Hope you will enjoy.

So, puzzle no.1:

Given the following program:

```<code>#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}
</code>```

Insert some code on a single new line anywhere inside the program so that the output will be 0. The new line will contain AT MOST 18 characters (including spaces), and the rest of the lines will remain unmodified.
 To be clear, here is an example of a valid new code:

```<code>#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   int* p = NULL;
   const float c=0.5;
   std::cout << a/b-a*c;
}
</code>```

A new line with 15 characters was inserted so it's ok. However it does not solve the problem.

If this is too simple for you, don't worry, more is coming!!

答:
We can get rid of a=1 by moving it into another scope:

```<code>#include <iostream>
main()
{
int a=0;if(0)
    const int a=1;
    const int b=2;
    const float c=0.5;
    std::cout << a/b-a*c;
}
</code>```

This is I think 13 characters. Or better yet get a new a that also results in 0:

```<code>#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
if(int a=2)
   std::cout << a/b-a*c;
}
</code>```

That's 11 characters

Title: m3ph1st0s's programming puzzle 1 (C++)

Body:
We can get rid of a=1 by moving it into another scope:

#include <iostream>
main()
{
int a=0;if(0)
    const int a=1;
    const int b=2;
    const float c=0.5;
    std::cout << a/b-a*c;
}

This is I think 13 characters. Or better yet get a new a that also results in 0:

#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
if(int a=2)
   std::cout << a/b-a*c;
}

That's 11 characters


问:
Walk the labyrinth
Or maybe it's not really a labyrinth, but still.

Rules:

Input is a two-line string, consisting of *, 1, x and X. That string is a labyrinth to walk through. The lines have the equal length.

You could take the input as a string with , (comma) or any convenient separator between these two lines. Or you could take both lines as separate arguments to your function.

Output is the number of steps you have to take to exit the string (last step is the step which moves you out of the string).

You start in the top left corner (the higher line), before the first symbol.

For each step, you move forward by one symbol (from nth to (n+1)th position). Then, depending on the character you step on, the outcome is different. Here's what each char does:

* - nothing. You just step on it normally.

x - once you stepped on it, switch the line, but remain on the same horizontal distance from the beginning. For example, you stepped on the third position of the higher line, and met a lowercase x here. Then you immediately move to the lower line, but again at the third position.

X - switch the line and go to the next position. The example is the same there, but you also move from the third to the forth position (thus you're on the second line at the forth position).

1 - just move forward by yet another position.

Once each character does its job, it's replaced with a space and no longer "works".

Examples follow.

Input:

```<code>x
*
</code>```

As said before, you start before the first symbol of the first line. The first step moves you on letter x and this letter switches you to the second line. The letter x no longer functions as x, but replaced with *. This will be more relevant in the latter examples. You're now on an asterisk on the lower line, and it did nothing to you.

The second step is moving you forward and you exit the string, so the labyrinth is completed, and it took 2 steps.

Output 2.

Input:

```<code>xX*
x1*
</code>```

1st step: you move on x, which moves you on the x of the lower line. Here comes the rule which says that the used character is replaced with asterisk. Then you move back on the first line, but it's no longer x there, since it has been used and became an asterisk. So you move safely on this asterisk and the step is completed (you are now on the first position of the first line).

2nd step: you move on X, it pushes you to the lower line and then pushes you forward. You now reside on the third position of the second line (asterisk), having never visited the second position (which contains 1).

3rd step: you move forward, exiting the string.

Output: 3.

Test cases:

Input:

```<code>*1*
xxx
</code>```

Output: 3. (because 1 makes you jump on the third position). There you never visit the second line, but it's required part of the input.

Input:

```<code>*X*1*x
x*1xx*
</code>```

Output: 4.

Input:

```<code>1x1x
***X
</code>```

Output: 3.

Input:

```<code>1*x1xxx1*x
x*x1*11X1x
</code>```

Output: 6.

Input:

```<code>xXXXxxx111*
**xxx11*xxx
</code>```

Output: 6.

答:
Snails, 34 bytes

```<code>A^
\1r|\xud|\Xaa7},(\*|\xud=\x)r},
</code>```

Expanded:

```<code>{
    {
        \1 r |
        \x ud |
        \X aa7
    },
    (\* | \x ud =\x)
    r
},
</code>```

For a path that takes N steps, the program finds one successful match for each traversal of 0 steps, 1 steps, ..., N - 1 steps.

Title: Walk the labyrinth

Body:
Snails, 34 bytes

A^
\1r|\xud|\Xaa7},(\*|\xud=\x)r},

Expanded:

{
    {
        \1 r |
        \x ud |
        \X aa7
    },
    (\* | \x ud =\x)
    r
},

For a path that takes N steps, the program finds one successful match for each traversal of 0 steps, 1 steps, ..., N - 1 steps.


问:
Is it a max-heap?
A heap, also known as a priority-queue, is an abstract data type. Conceptually, it's a binary tree where the children of every node are smaller than or equal to the node itself. (Assuming it's a max-heap.) When an element is pushed or popped, the heap rearranges itself so the the biggest element is the next to be popped. It can easily be implemented as a tree or as an array.

Your challenge, should you choose to accept it, is to determine if an array is a valid heap. An array is in heap form if every element's children are smaller than or equal to the element itself. Take the following array as an example:

```<code>[90, 15, 10, 7, 12, 2]
</code>```

Really, this is a binary tree arranged in the form of an array. This is because every element has children. 90 has two children, 15 and 10.

```<code>       15, 10,
[(90),         7, 12, 2]
</code>```

15 also has children, 7 and 12:

```<code>               7, 12,
[90, (15), 10,        2]
</code>```

10 has children:

```<code>                      2
[90, 15, (10), 7, 12,  ]
</code>```

and the next element would also be a child of 10, except that there isn't room. 7, 12 and 2 would all also have children if the array was long enough. Here is another example of a heap:

```<code>[16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
</code>```

And here is a visualization of the tree the previous array makes:

Just in case this isn't clear enough, here is the explicit formula to get the children of the i'th element

```<code>//0-indexing:
child1 = (i * 2) + 1
child2 = (i * 2) + 2

//1-indexing:
child1 = (i * 2)
child2 = (i * 2) + 1
</code>```

You must take an non-empty array as input and output a truthy value if the array is in heap order, and a falsy value otherwise. This can be a 0-indexed heap, or a 1-indexed heap as long as you specify which format your program/function expects. You may assume that all arrays will only contain positive integers. You may not use any heap-builtins. This includes, but is not limited to

Functions that determine if an array is in heap-form

Functions that convert an array into a heap or into heap-form

Functions that take an array as input and return a heap data-structure

You can use this python script to verify if an array is in heap-form or not (0 indexed):

```<code>def is_heap(l):
    for head in range(0, len(l)):
        c1, c2 = head * 2 + 1, head * 2 + 2
        if c1 < len(l) and l[head] < l[c1]:
            return False
        if c2 < len(l) and l[head] < l[c2]:
            return False

    return True
</code>```

Test IO:

All of these inputs should return True:

```<code>[90, 15, 10, 7, 12, 2]
[93, 15, 87, 7, 15, 5]
[16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[100, 19, 36, 17, 3, 25, 1, 2, 7]
[5, 5, 5, 5, 5, 5, 5, 5]
</code>```

And all of these inputs should return False:

```<code>[4, 5, 5, 5, 5, 5, 5, 5]
[90, 15, 10, 7, 12, 11]
[1, 2, 3, 4, 5]
[4, 8, 15, 16, 23, 42]
[2, 1, 3]
</code>```

As usual, this is code-golf, so standard loopholes apply and the shortest answer in bytes wins!

答:
Haskell, 33 bytes

f(a:b)=and$zipWith(<=)b$a:b<*"xx"
```

<p>or</p>

<pre class="lang-hs prettyprint-override"><code>and.(zipWith(<=).tail<*>(<*"xx"))
</code>```

Title: Is it a max-heap?

Body:
Haskell, 33 bytes

f(a:b)=and$zipWith(<=)b$a:b<*"xx"

or

and.(zipWith(<=).tail<*>(<*"xx"))


答:
Pyth, 8 bytes

```<code>.AgV.i+h

       hQ      first element of input
      +  Q     plus input
    .i    Q    interleaved with input
  gV       Q   vectorized greater-than-or-equal comparison with input
.A             check if all results are true
</code>```

Try it online

Title: Is it a max-heap?

Body:
A heap, also known as a priority-queue, is an abstract data type. Conceptually, it's a binary tree where the children of every node are smaller than or equal to the node itself. (Assuming it's a max-heap.) When an element is pushed or popped, the heap rearranges itself so the the biggest element is the next to be popped. It can easily be implemented as a tree or as an array.

Your challenge, should you choose to accept it, is to determine if an array is a valid heap. An array is in heap form if every element's children are smaller than or equal to the element itself. Take the following array as an example:

```<code>[90, 15, 10, 7, 12, 2]
</code>```

Really, this is a binary tree arranged in the form of an array. This is because every element has children. 90 has two children, 15 and 10.

```<code>       15, 10,
[(90),         7, 12, 2]
</code>```

15 also has children, 7 and 12:

```<code>               7, 12,
[90, (15), 10,        2]
</code>```

10 has children:

```<code>                      2
[90, 15, (10), 7, 12,  ]
</code>```

and the next element would also be a child of 10, except that there isn't room. 7, 12 and 2 would all also have children if the array was long enough. Here is another example of a heap:

```<code>[16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
</code>```

And here is a visualization of the tree the previous array makes:

Just in case this isn't clear enough, here is the explicit formula to get the children of the i'th element

```<code>//0-indexing:
child1 = (i * 2) + 1
child2 = (i * 2) + 2

//1-indexing:
child1 = (i * 2)
child2 = (i * 2) + 1
</code>```

You must take an non-empty array as input and output a truthy value if the array is in heap order, and a falsy value otherwise. This can be a 0-indexed heap, or a 1-indexed heap as long as you specify which format your program/function expects. You may assume that all arrays will only contain positive integers. You may not use any heap-builtins. This includes, but is not limited to

Functions that determine if an array is in heap-form

Functions that convert an array into a heap or into heap-form

Functions that take an array as input and return a heap data-structure

You can use this python script to verify if an array is in heap-form or not (0 indexed):

```<code>def is_heap(l):
    for head in range(0, len(l)):
        c1, c2 = head * 2 + 1, head * 2 + 2
        if c1 < len(l) and l[head] < l[c1]:
            return False
        if c2 < len(l) and l[head] < l[c2]:
            return False

    return True
</code>```

Test IO:

All of these inputs should return True:

```<code>[90, 15, 10, 7, 12, 2]
[93, 15, 87, 7, 15, 5]
[16, 14, 10, 8, 7, 9, 3, 2, 4, 1]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[100, 19, 36, 17, 3, 25, 1, 2, 7]
[5, 5, 5, 5, 5, 5, 5, 5]
</code>```

And all of these inputs should return False:

```<code>[4, 5, 5, 5, 5, 5, 5, 5]
[90, 15, 10, 7, 12, 11]
[1, 2, 3, 4, 5]
[4, 8, 15, 16, 23, 42]
[2, 1, 3]
</code>```

As usual, this is code-golf, so standard loopholes apply and the shortest answer in bytes wins!

Body:
Pyth, 8 bytes

.AgV.i+h

       hQ      first element of input
      +  Q     plus input
    .i    Q    interleaved with input
  gV       Q   vectorized greater-than-or-equal comparison with input
.A             check if all results are true

<a href="https://pyth.herokuapp.com/?code=.AgV.i%2Bh&input=%5B90%2C+15%2C+10%2C+7%2C+12%2C+2%5D%0A%5B93%2C+15%2C+87%2C+7%2C+15%2C+5%5D%0A%5B16%2C+14%2C+10%2C+8%2C+7%2C+9%2C+3%2C+2%2C+4%2C+1%5D%0A%5B10%2C+9%2C+8%2C+7%2C+6%2C+5%2C+4%2C+3%2C+2%2C+1%5D%0A%5B100%2C+19%2C+36%2C+17%2C+3%2C+25%2C+1%2C+2%2C+7%5D%0A%5B5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%5D%0A&test_suite=1&test_suite_input=%5B90%2C+15%2C+10%2C+7%2C+12%2C+2%5D%0A%5B93%2C+15%2C+87%2C+7%2C+15%2C+5%5D%0A%5B16%2C+14%2C+10%2C+8%2C+7%2C+9%2C+3%2C+2%2C+4%2C+1%5D%0A%5B10%2C+9%2C+8%2C+7%2C+6%2C+5%2C+4%2C+3%2C+2%2C+1%5D%0A%5B100%2C+19%2C+36%2C+17%2C+3%2C+25%2C+1%2C+2%2C+7%5D%0A%5B5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%5D%0A%5B4%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%2C+5%5D%0A%5B90%2C+15%2C+10%2C+7%2C+12%2C+11%5D%0A%5B1%2C+2%2C+3%2C+4%2C+5%5D%0A%5B4%2C+8%2C+15%2C+16%2C+23%2C+42%5D%0A%5B2%2C+1%2C+3%5D" rel="nofollow">Try it online


问:
Return the nth digit of the sequence of aliquot series

0. DEFINITIONS

A sequence is a list of numbers.

A series is the sum of a list of numbers.

The set of natural numbers contains all "non-negative integers greater than zero".

A divisor (in this context) of a natural number j is a natural number i, such that j÷i is also a natural number.

1. PREAMBLE

A couple of other questions on this site mention the concept of the aliquot, or the sequence of divisors of a natural number a which are less than a. Determining amicable numbers involves computing the sum of these divisors, called an aliquot sum or aliquot series. Every natural number has its own aliquot sum, although the value of a number's aliquot sum is not necessarily unique to that number. (Exempli gratia, every prime number has an aliquot sum of 1.)

2. CHALLENGE

Given a natural number n, return the nth digit of the sequence of aliquot sums. The first several series in the sequence, starting with the series for 1, are:

```<code>{0, 1, 1, 3, 1, 6, 1, 7, 4, 8, 1, 16, 1, 10, 9, 15, 1, 21, 1, 22, 11, 14, 1, 36, 6, 16, 13}
</code>```

Concatenated, these look like:

```<code>0113161748116110915121122111413661613
</code>```

Input may be zero-indexed or one-indexed, according to your preference. Solutions must be programs or functions capable of returning the 10,000th digit (input up to 9999 or 10000). The shortest working solution wins.

3. TEST CASES

Correct input-output pairs should include, but are not limited to, the following:

```<code>   0 or     1    ->    0
   4 or     5    ->    1
  12 or    13    ->    6
9999 or 10000    ->    7
</code>```

The number preceding the "or" is 0-indexed; the number following is 1-indexed.

Additional test cases may be provided upon request.

4. REFERENCES

OEIS has a list of numbers and their aliquot sums.

答:
Mathematica, 51 bytes

```<code>Array[##&@@IntegerDigits[Tr@Divisors@#-#]&,#][[#]]&
</code>```

An unnamed function which takes and returns an integer and uses 1-based indexing. Handles input 10000 instantly.

Explanation

This is a very straight-forward implementation of the definition, making use of the fact that the first n divisor sums are always enough to determine the nth digit. As usual, the reading order of golfed Mathematica is a bit funny though:

```<code>Array[...&,#]...&
</code>```

This generates a list with all the results of applying the unnamed function on the left to all the values i from 1 to n inclusive.

```<code>...Tr@Divisors@#-#...
</code>```

We start by computing the divisors of i, summing them with Tr and subtracting i itself so that it's just the sum of divisors less than i.

```<code>...IntegerDigits[...]...
</code>```

This turns the result into a list of its decimal digits.

```<code>##&@@...
</code>```

And this removes the "list" head, so that all the digit lists are automatically concatenated in the result of Array. For more details on how ## works, see the "Sequences of arguments" section in this post.

```<code>...[[#]]
</code>```

Finally, we select the nth digit from the result.

Body:
Mathematica, 51 bytes

Array[##&@@IntegerDigits[Tr@Divisors@#-#]&,#][[#]]&

An unnamed function which takes and returns an integer and uses 1-based indexing. Handles input 10000 instantly.

Explanation

This is a very straight-forward implementation of the definition, making use of the fact that the first n divisor sums are always enough to determine the nth digit. As usual, the reading order of golfed Mathematica is a bit funny though:

Array[...&,#]...&

This generates a list with all the results of applying the unnamed function on the left to all the values i from 1 to n inclusive.

...Tr@Divisors@#-#...

We start by computing the divisors of i, summing them with Tr and subtracting i itself so that it's just the sum of divisors less than i.

...IntegerDigits[...]...

This turns the result into a list of its decimal digits.

##&@@...

And this removes the "list" head, so that all the digit lists are automatically concatenated in the result of Array. For more details on how ## works, see the "Sequences of arguments" section in this post.

...[[#]]

Finally, we select the nth digit from the result.


答:
Pyth, <s>26</s> <s>21</s> <s>20</s> 15 bytes

```<code>@sm`sf!%dTtUdSh
</code>```

Try it online. Test suite.

Uses 0-based indexing. The program is O(n²) and completes for n = 9999 in about 14 minutes on my 2008 machine.

Title: Return the nth digit of the sequence of aliquot series

Body:
0. DEFINITIONS

A sequence is a list of numbers.

A series is the sum of a list of numbers.

The set of natural numbers contains all "non-negative integers greater than zero".

A divisor (in this context) of a natural number j is a natural number i, such that j÷i is also a natural number.

1. PREAMBLE

A couple of other questions on this site mention the concept of the aliquot, or the sequence of divisors of a natural number a which are less than a. Determining amicable numbers involves computing the sum of these divisors, called an aliquot sum or aliquot series. Every natural number has its own aliquot sum, although the value of a number's aliquot sum is not necessarily unique to that number. (Exempli gratia, every prime number has an aliquot sum of 1.)

2. CHALLENGE

Given a natural number n, return the nth digit of the sequence of aliquot sums. The first several series in the sequence, starting with the series for 1, are:

```<code>{0, 1, 1, 3, 1, 6, 1, 7, 4, 8, 1, 16, 1, 10, 9, 15, 1, 21, 1, 22, 11, 14, 1, 36, 6, 16, 13}
</code>```

Concatenated, these look like:

```<code>0113161748116110915121122111413661613
</code>```

Input may be zero-indexed or one-indexed, according to your preference. Solutions must be programs or functions capable of returning the 10,000th digit (input up to 9999 or 10000). The shortest working solution wins.

3. TEST CASES

Correct input-output pairs should include, but are not limited to, the following:

```<code>   0 or     1    ->    0
   4 or     5    ->    1
  12 or    13    ->    6
9999 or 10000    ->    7
</code>```

The number preceding the "or" is 0-indexed; the number following is 1-indexed.

Additional test cases may be provided upon request.

4. REFERENCES

OEIS has a list of numbers and their aliquot sums.

Body:
Pyth, <s>26</s> <s>21</s> <s>20</s> 15 bytes

@sm`sf!%dTtUdSh

Try it online. Test suite.

Uses 0-based indexing. The program is O(n²) and completes for n = 9999 in about 14 minutes on my 2008 machine.


问:
Tips for Golfing in Batch
Windows Batch (CMD) is probably the least suitable language for code golfing.

Avoid newline characters. If you're looking for the shortest code in bytes, as opposed to characters, you will want to get rid of all unnecessary carriage returns (newline characters = 2 bytes). You can use the & operation to do this, trimming one byte for each command.

```<code>echo Hello&echo World.
</code>```

Setting variables. When setting variables using switches, the set parser will ignore spaces.

```<code>set /a a+=1
set /p b="User Input: "
:: Will be handled the same as..
set/aa+=1
set/pb="User Input: "
</code>```

Note that the same parser rules do not apply to all commands - as an example, for loops require spaces. Except between the set, string, or command (i.e. what is inside the brackets) and the word do.

```<code>for /f %%a in (file.txt)do ...
</code>```

Simple mathematical expressions. Also, notice the expression that I used for incrementing in the set /a command. For simple mathematical expressions use += -= *= /= instead of (for example) set /a a=%a%+1.

Gathering command output. To get the output of a command, it can sometimes be useful to output to and read from a file, where you otherwise might have used a for loop to gather the output:

```<code>for /f %%a in ('echo test') do set a=%%a
:: Can be shortened to
echo test>f&set/pa=<f
</code>```

echo test send stdout to a file called f, >f, start a new command & and get the contents of the file in a variable set/pa=<f. Obviously this isn't always useful. But it can be when all you need is a single line of output.

Command output. When suppressing command output, use @ before the commands, unless you need to suppress more than 9 commands, in which case, use @echo off at the start of your script. @echo off is 9 bytes long, and therefore will generally save more bytes with longer scripts.

Commands often do more than just what is obvious - think about what your commands are doing. For example; if you need to set a variable and echo another variable, instead of:

```<code>set a=OUTPUT
echo %a%
echo test>f
set /p b=<f
</code>```

You can use the set command with the /p switch to output %a% for you.

```<code>set a=OUTPUT
echo test>f
set /p b=%a%<f
</code>```

Completely golfed...

```<code>set a=OUTPUT&echo test>f&set/pb=%a%<f
</code>```

A couple of expamples - Count sum of all digits - Goldbach's conjecture.

Any other tips are more than appreciated - I'll keep updating this if I think of anything else.

答:
Directly print the result of a numeric calculation

If the challenge requires you to output a number that needs to be calculated, you can use cmd/c set/a to output the result of the calculation directly instead of saving the calculation and then echoing it. Example:

```<code>@set/a a=%1+%2
@echo %a%
</code>```

becomes

```<code>@cmd/cset/a%1+%2
</code>```

Edit: Apparently no spaces are necessary at all, saving 2 more bytes.

Title: Tips for Golfing in Batch

Body:
Directly print the result of a numeric calculation

If the challenge requires you to output a number that needs to be calculated, you can use cmd/c set/a to output the result of the calculation directly instead of saving the calculation and then echoing it. Example:

@set/a a=%1+%2
@echo %a%

becomes

@cmd/cset/a%1+%2

Edit: Apparently no spaces are necessary at all, saving 2 more bytes.


答:
Python 3.5, <s>103</s> <s>93</s> 92 bytes:

```<code>R=range;A=lambda f:''.join([str(sum([j for j in R(1,i)if i/j%1==0]))for i in R(1,f+1)])[f-1]
</code>```

Pretty straightforward implementation of method described in post.

Try It Online! (Ideone)

Does not quite finish within the allotted 5 seconds in the online compiler for input 10000, but it does finish on my machine for the same input within about 8.5 seconds.

Body:
Python 3.5, <s>103</s> <s>93</s> 92 bytes:

R=range;A=lambda f:''.join([str(sum([j for j in R(1,i)if i/j%1==0]))for i in R(1,f+1)])[f-1]

Pretty straightforward implementation of method described in post.

Try It Online! (Ideone)

Does not quite finish within the allotted 5 seconds in the online compiler for input 10000, but it does finish on my machine for the same input within about 8.5 seconds.


问:
Tips for golfing in vim
I've recently realized how vim works great for golfing, especially for kolmogorov-complexity. Also, according to meta vim is a perfectly acceptable 'programming language' at least, for the scope of this site, that is.

What general tips do you have for golfing in Vim? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Vim (e.g. "remove comments" is not an answer).

Please post one tip per answer.

答:
This came up in chat earlier, so I thought I might as well post it as a full tip.

<C-a> and <C-x> increment and decrement the next number on the line. This is an extremely useful feature for some simple math, but it also allows for a neat little hack.

Let's say you need to jump to the next number. For example, we need to change

```<code>I need 2 spell better
</code>```

to

```<code>I need to spell better
</code>```

The obvious way is to jump to the 2, then do:

```<code>sto                "Synonymous with 'clto'
</code>```

Since this is shorter than

```<code>:s/2/to<cr>
</code>```

There are many different ways to jump to the 2. For example,

```<code>/2<cr>
ww
2w
ee
2e
8|
f2
</code>```

As well as many other ways.

These are all 2 (or more) keystrokes. However, since <C-a> and <C-x> not only increment/decrement numbers, but  also jump to the next number, we can take a byte off with

```<code><C-a>sto
</code>```

Title: Tips for golfing in vim

Body:
This came up in chat earlier, so I thought I might as well post it as a full tip.

<C-a> and <C-x> increment and decrement the next number on the line. This is an extremely useful feature for some simple math, but it also allows for a neat little hack.

Let's say you need to jump to the next number. For example, we need to change

I need 2 spell better

to

I need to spell better

The obvious way is to jump to the 2, then do:

sto                "Synonymous with 'clto'

Since this is shorter than

:s/2/to<cr>

There are many different ways to jump to the 2. For example,

/2<cr>
ww
2w
ee
2e
8|
f2

As well as many other ways.

These are all 2 (or more) keystrokes. However, since <C-a> and <C-x> not only increment/decrement numbers, but  also jump to the next number, we can take a byte off with

<C-a>sto


答:
Brachylog, 40 bytes

```<code>:2-I,?:?:1yrc:Im.;0.
:1e:2f+.
>.>0,?:.%0
</code>```

This is 1-indexed, takes about 0.15 seconds for N = 100, 15 seconds for N = 1000. I'm currently running for N = 10000, I'll report the run time once it ends (If my estimation is correct, it should take about 8 hours)

Edit: by fixing premature constraints propagation in Brachylog, it now (on a 3 bytes longer code) takes about 2.5 minutes for 10000 but returns an out of global stack error.

Explanation

Main Predicate: Input = N

```<code>:2-I,                 I = N - 2
     ?:?:1y           Find the N first valid outputs of predicate 1 with input N
           rc         Reverse and concatenate into a single number
             :Im.     Output is the Ith digit of that number
                 ;    Or (I strictly less than 0)
                  0.  Output is 0
</code>```

Predicate 1: computes the sum of the divisors

```<code>:1e                   Get a number between N and 1
   :2f                Find all valid outputs of predicate 2 with that number as input
      +.              Output is the sum of those outputs
</code>```

Predicate 2: unifies output with a divisor of the input

```<code>>.>0,                 Output is a number between Input and 0
     ?:.%0            Input is divisible by Output
</code>```

Body:
Brachylog, 40 bytes

:2-I,?:?:1yrc:Im.;0.
:1e:2f+.
>.>0,?:.%0

This is 1-indexed, takes about 0.15 seconds for N = 100, 15 seconds for N = 1000. I'm currently running for N = 10000, I'll report the run time once it ends (If my estimation is correct, it should take about 8 hours)

Edit: by fixing premature constraints propagation in Brachylog, it now (on a 3 bytes longer code) takes about 2.5 minutes for 10000 but returns an out of global stack error.

Explanation

Main Predicate: Input = N

:2-I,                 I = N - 2
     ?:?:1y           Find the N first valid outputs of predicate 1 with input N
           rc         Reverse and concatenate into a single number
             :Im.     Output is the Ith digit of that number
                 ;    Or (I strictly less than 0)
                  0.  Output is 0

Predicate 1: computes the sum of the divisors

:1e                   Get a number between N and 1
   :2f                Find all valid outputs of predicate 2 with that number as input
      +.              Output is the sum of those outputs

Predicate 2: unifies output with a divisor of the input

>.>0,                 Output is a number between Input and 0
     ?:.%0            Input is divisible by Output


答:
```<code>#include <iostream>
main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   return puts("0");
   std::cout << a/b-a*c;
}
</code>```

<p>17 chars. </p>

Title: m3ph1st0s's programming puzzle 1 (C++)

Body:
This is the first of a series of C++ puzzles for you. Hope you will enjoy.

So, puzzle no.1:

Given the following program:

```<code>#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}
</code>```

Insert some code on a single new line anywhere inside the program so that the output will be 0. The new line will contain AT MOST 18 characters (including spaces), and the rest of the lines will remain unmodified.
 To be clear, here is an example of a valid new code:

```<code>#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   int* p = NULL;
   const float c=0.5;
   std::cout << a/b-a*c;
}
</code>```

A new line with 15 characters was inserted so it's ok. However it does not solve the problem.

If this is too simple for you, don't worry, more is coming!!

Body:
#include <iostream>
main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   return puts("0");
   std::cout << a/b-a*c;
}

17 chars.


问:
Is case sensitivity important?
Tom is going to implement a new programming language of his invention.  But before actually starting working on it, he wants to know whether his language should be case sensitive or not.

On one hand, case insensitivity seems more easy to implement to him, but he worries that it could cause a lack in the possibilities of combinations of characters that form a variable, meaning that longer variable names should then be used to avoid naming clashes (for an example, you can use Hello, HEllo, heLLo and a bunch of other possibilities if the language is case sensitive, but only HELLO if not).

But Tom is a meticulous person, so just a worry isn't enough for him. He wants to know the numbers.

The challenge

Write a function (or a full program if your language doesn't support them) that, given an integer n as the input, outputs (or returns) the difference in the number of permutations possible for a string of length n with case sensitivity and without.

In Tom's language, variable names can include all alphabet letters, underscores and, starting from the second character, digits.

Testcases

```<code>Input (length of the variable) -> Output (difference between the possibilities with case sensitivity and the possibilities with case insensitivity)
0 -> 0
1 -> 26
2 -> 2340
5 -> 784304586
8 -> 206202813193260
9 -> 13057419408922746
</code>```

Non-competing C++ reference implementation

void diff(int n) {
    long long total[2] = {0, 0}; //array holding the result for case insensivity ([0]) and case sensitivity ([1])

    for (int c = 1; c <= 2; c ++) //1 = insensitivity, 2 = sensitivity
        for (int l = 1; l <= n; l ++) //each character of the name
            if (l == 1)
                total[c - 1] = 26 * c + 1; //first character can't be a number
            else
                total[c - 1] *= 26 * c + 1 + 10; //starting from the second character, characters can include numbers

    std::cout << total[1] - total[0] << std::endl;
}
```

Scoring

Tom likes golf, so the shortest program in bytes wins.

Note

It's okay if maybe the last two testcases aren't right because of numerical precision. After all, I am not even sure my code handled number 9 correctly.

Title: Is case sensitivity important?

Body:
dc, 19 bytes

1-d63r^53*r37r^27*-

This is just a difference of two exponentials, 53 × 63^(n-1) - 27 × 37^(n-1).  The special case of zero falls out naturally, as dc starts with a precision of 0, meaning that x^-1 == 0 for all positive x.

As normal for dc, input is taken from top of stack, and output is pushed to top of stack.  For a full program, enclose between ? and p to make a pipeline filter.

Test output

$ for i in {0..30}; do printf '%2d -> %s\n' "$i" `./85108.dc <<<$i`; done
 0 -> 0
 1 -> 26
 2 -> 2340
 3 -> 173394
 4 -> 11884860
 5 -> 784304586
 6 -> 50726849940
 7 -> 3244471004034
 8 -> 206202813193260
 9 -> 13057419408922746
10 -> 825083183338785540
11 -> 52071473691679633074
12 -> 3283878468805254213660
13 -> 207009241705220196670506
14 -> 13046203459736972095009140
15 -> 822081803558828931061964514
16 -> 51797480091236011152730146060
17 -> 3263475325027970876967575323866
18 -> 205607606410125945699743561920740
19 -> 12953599658372394455762938112142354
20 -> 816088635295235866150191568376990460
21 -> 51414022725857535138635748098295218826
22 -> 3239099663712558709867478263942757120340
23 -> 204063879397281956578587897577149556950594
24 -> 12856046623614221305157697924464388847546860
25 -> 809931759486357889731081403194103267502851386
26 -> 51025731268991039110785546457483836346653407940
27 -> 3214622195536403670115403894902928918116194213234
28 -> 202521239965622254844299280697898069287570327415260
29 -> 12758839658766868529390921590771079620628184030477546
30 -> 803806955516821376897030535770307562553491969842783540

Performance is reasonable for small n, but does start to tail off once it reaches a few hundred thousand or so:

   1024:   0.00s
   2048:   0.00s
   4096:   0.01s
   8192:   0.04s
  16384:   0.12s
  32768:   0.38s
  65536:   1.16s
 131072:   3.48s
 262144:  10.41s
 524288:  30.63s
1048576:  93.70s

That last example does produce a 1941435-digit result, so maybe it's not too bad for all that.


问:
Narayana-Zidek-Capell numbers
Generate the nth Narayana-Zidek-Capell number given an input n. Fewest bytes win.

f(1)=1, f(n) is the sum of the previous floor(n/2) Narayana-Zidek-Capell terms.

Test Cases:

```<code>f(1)=1

f(9)=42

f(14)=1308

f(15)=2605

f(23)=664299
</code>```

答:
R, 55 bytes

```<code>x[1]=1;for(i in 2:10){x[i]=sum(x[i-1:floor(i/2)])};x[9]
</code>```

Change 10 in the for loop and x[9] to get whichever index the user wants.

Title: Narayana-Zidek-Capell numbers

Body:
R, 55 bytes

x[1]=1;for(i in 2:10){x[i]=sum(x[i-1:floor(i/2)])};x[9]

Change 10 in the for loop and x[9] to get whichever index the user wants.


答:
ZX Spectrum Z80 Assembly, 65 bytes

```<code>    ld hl,22528
    ld b,7
    ld de,120*256+8 ; white, blue
    ld a,16         ; red

; create the first row

blueleft:
    ld (hl),e
    inc hl
    djnz blueleft

    ld (hl),d
    inc hl
    ld (hl),a
    inc hl
    ld (hl),a
    inc hl
    ld (hl),d
    inc hl

    ld b,14
blueright:
    ld (hl),e
    inc hl
    djnz blueright

; copy the first row to the next 17 rows

    ld l,b
    ld de,22528+32
    ld bc,17*32
    ldir

; add the horizontal stripe

    ld hl,22528+7*32
    dec d
    ld e,b
    ld c,2
midrep:
    ld b,25
midstripe:
    cp (hl)
    jr z,red
    ld (hl),120
red:
    ld (de),a
    inc hl
    inc de
    djnz midstripe

    ld hl,22528+10*32
    ld e,9*32
    dec c
    jr nz,midrep
    ret
</code>```

Title: Draw the national flag of Iceland

Body:
This year's UEFA Euro 2016 is over and besides a couple of negative headlines there has been a very positive surprise as well – the Iceland national football team. Let's draw their national flag.

Input

Well, obviously this challenge has no input.

Output

Draw the flag of Iceland in any applicable visual format of at least 100 x 72 pixels or 25 x 18 characters.

Save the output to a file or present it instantly – example formats are: images like png, jpg etc., vector graphics, draw on HTML canvas or even use non-whitespace characters for visualization.

Use these colors: blue: #0048e0, white: #ffffff and red: #d72828.

If your language doesn't support specific color values, use the standard values for red, blue and white from the ANSI color codes.

Draw the flag with the correct proportions, as shown in the figure below:

Boilerplate

You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it.

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

Standard loopholes are disallowed.

Leaderboard

var QUESTION_ID = 85141; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 41859; // This should be the user ID of the challenge author.
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;function answersUrl(index) {return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;}function commentUrl(index, answers) {return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;}function getAnswers() {jQuery.ajax({url: answersUrl(answer_page++),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {answers.push.apply(answers, data.items);answers_hash = [];answer_ids = [];data.items.forEach(function(a) {a.comments = [];var id = +a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id] = a;});if (!data.has_more) more_answers = false;comment_page = 1;getComments();}});}function getComments() {jQuery.ajax({url: commentUrl(comment_page++, answer_ids),method: "get",dataType: "jsonp",crossDomain: true,success: function (data) {data.items.forEach(function(c) {if (c.owner.user_id === OVERRIDE_USER)answers_hash[c.post_id].comments.push(c);});if (data.has_more) getComments();else if (more_answers) getAnswers();else process();}});}getAnswers();var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG = /^Override\s*header:\s*/i;function getAuthorName(a) {return a.owner.display_name;}function process() {var valid = [];answers.forEach(function(a) {var body = a.body;a.comments.forEach(function(c) {if(OVERRIDE_REG.test(c.body))body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';});var match = body.match(SCORE_REG);if (match)valid.push({user: getAuthorName(a),size: +match[2],language: match[1],link: a.share_link,});});valid.sort(function (a, b) {var aB = a.size,bB = b.size;return aB - bB});var languages = {};var place = 1;var lastSize = null;var lastPlace = 1;valid.forEach(function (a) {if (a.size != lastSize)lastPlace = place;lastSize = a.size;++place;var answer = jQuery("#answer-template").html();answer = answer.replace("{{PLACE}}", lastPlace + ".").replace("{{NAME}}", a.user).replace("{{LANGUAGE}}", a.language).replace("{{SIZE}}", a.size).replace("{{LINK}}", a.link);answer = jQuery(answer);jQuery("#answers").append(answer);var lang = a.language;if (! /<a/.test(lang)) lang = '' + lang + '';lang = jQuery(lang).text().toLowerCase();languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};});var langs = [];for (var lang in languages)if (languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function (a, b) {if (a.uniq > b.uniq) return 1;if (a.uniq < b.uniq) return -1;return 0;});for (var i = 0; i < langs.length; ++i){var language = jQuery("#language-template").html();var lang = langs[i];language = language.replace("{{LANGUAGE}}", lang.lang).replace("{{NAME}}", lang.user).replace("{{SIZE}}", lang.size).replace("{{LINK}}", lang.link);language = jQuery(language);jQuery("#languages").append(language);}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { text-align: left !important}#answer-list {padding: 10px;width: 290px;float: left;}#language-list {padding: 10px;width: 290px;float: left;}table thead {font-weight: bold;}table td {padding: 5px;}</code>```

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

If you can't find your answer, format your language and byte count as explained in the Leaderboard's "Info Section".

This challenge is inspired by Draw the national flag of france.

Body:
ZX Spectrum Z80 Assembly, 65 bytes

    ld hl,22528
    ld b,7
    ld de,120*256+8 ; white, blue
    ld a,16         ; red

; create the first row

blueleft:
    ld (hl),e
    inc hl
    djnz blueleft

    ld (hl),d
    inc hl
    ld (hl),a
    inc hl
    ld (hl),a
    inc hl
    ld (hl),d
    inc hl

    ld b,14
blueright:
    ld (hl),e
    inc hl
    djnz blueright

; copy the first row to the next 17 rows

    ld l,b
    ld de,22528+32
    ld bc,17*32
    ldir

; add the horizontal stripe

    ld hl,22528+7*32
    dec d
    ld e,b
    ld c,2
midrep:
    ld b,25
midstripe:
    cp (hl)
    jr z,red
    ld (hl),120
red:
    ld (de),a
    inc hl
    inc de
    djnz midstripe

    ld hl,22528+10*32
    ld e,9*32
    dec c
    jr nz,midrep
    ret


答:
SpecaBAS - 150 bytes

```<code>1 a=15,b=250,c=180: FOR i=1 TO 5: READ k,x,y,w,h: RECTANGLE INK k;x,y,w,h FILL: NEXT i
2 DATA 1,0,0,b,c,a,71,0,40,c,a,0,71,b,40,2,81,0,20,c,2,0,81,b,20
</code>```

Reads the ink colour, x,y, width and height and draws a rectangle with those coordinates/dimensions.

Title: Draw the national flag of Iceland

Body:
SpecaBAS - 150 bytes

1 a=15,b=250,c=180: FOR i=1 TO 5: READ k,x,y,w,h: RECTANGLE INK k;x,y,w,h FILL: NEXT i
2 DATA 1,0,0,b,c,a,71,0,40,c,a,0,71,b,40,2,81,0,20,c,2,0,81,b,20

Reads the ink colour, x,y, width and height and draws a rectangle with those coordinates/dimensions.


问:
A Peak Experience: Quickly Visit All the Peaks
I am standing at point (0,0) in a H x W map where the altitude is represented by digits, for example:

```<code>1132
2221
1230    # H = 3, W = 4
</code>```

I'd like to experience the views from every peak, which in this case are the areas with altitude 3. However, climbing up hills is not an easy task, and I am also running out of time.

Challenge

The challenge is to find the quickest path to visit all the peaks and come back.

Shortest program wins.

Input

H, W - height and width of the map (Integers) (optional, may be a list/tuple or two separate integer inputs)

The map, given as H sets of W digits (0-9), in any convenient format (2D list, string separated by newlines, etc.)

Output

Shortest time taken to visit every peak and come back to your starting point (Integer)

Conditions

The altitude of a given area is represented by a digit from 0 to 9.

The "peak" is defined by the area with the highest altitude.

The path must both begin and end at the top-left (0,0) area.

You can only move to areas adjacent to your current area, and you may not move diagonally.

It takes 3 minutes to move from one area to another if there is no change in altitude.

It takes 11 minutes to climb up; that is, moving from one area to another area that is exactly 1 unit higher.

It takes 2 minutes to climb down; that is, moving from one area to another area that is exactly 1 unit lower.

You cannot move to areas that are more than 1 unit higher or lower than where you are. (You cannot go from an area with altitude 1 to an adjacent area with altitude, say, 3)

A path to all the peaks is guaranteed

Maximum number of peaks is 15.

Samples

Input

```<code>4 5
32445
33434
21153
12343
</code>```

Output

```<code>96
</code>```

Explanation

You start at the top-left 3. You have to visit the two 5s that are located at (0,4) and (3,3) and come back to the 3 at (0,0) in the shortest time possible.

```<code>3  2  4->4->5
V     ^
3->3->4  3  4

2  1  1  5  3

1  2  3  4  3    # 3 + 3 + 11 + 3 + 3 + 11 = 34 minutes to visit 1st peak

3  2  4  4  5
            V
3  3  4  3  4
            V
2  1  1  5  3
         ^  V
1  2  3  4<-3    # 2 + 2 + 3 + 11 + 11 = 29 minutes to visit 2nd

3  2  4  4  5
^
3  3  4  3  4
^
2  1  1  5  3
^        V
1<-2<-3<-4  3    # 2 + 2 + 2 + 2 + 11 + 11 + 3 = 33 minutes to come back

# 34 + 29 + 33 = 96 minutes total is the answer
</code>```

Input

```<code>2 7
6787778
5777679
</code>```

Output

```<code>75
</code>```

答:
Pyth, 92 bytes

```<code>hSms@Lu.dm,bhS,@Gb+@G,hbH@G,HebG[FQ.dm,(Fb?|tsaMCb>.aJ-F@LQb1.n4@[3hT2)J*QQC.<B+]hSQd1.p.M@Q
</code>```

The input format is a dict mapping coordinates to heights: {(0, 0): 3, (0, 1): 2, (0, 2): 4, …}.  This finds the fastest paths between all pairs of points using the Floyd–Warshall algorithm, then minimizes the total time of the desired cycle over all permutations of peaks.

Try it online

Body:
Pyth, 92 bytes

hSms@Lu.dm,bhS,@Gb+@G,hbH@G,HebG[FQ.dm,(Fb?|tsaMCb>.aJ-F@LQb1.n4@[3hT2)J*QQC.<B+]hSQd1.p.M@Q

The input format is a dict mapping coordinates to heights: {(0, 0): 3, (0, 1): 2, (0, 2): 4, …}.  This finds the fastest paths between all pairs of points using the Floyd–Warshall algorithm, then minimizes the total time of the desired cycle over all permutations of peaks.

<a href="https://pyth.herokuapp.com/?code=hSms%40Lu.dm%2CbhS%2C%40Gb%2B%40G%2ChbH%40G%2CHebG%5BFQ.dm%2C%28Fb%3F%7CtsaMCb%3E.aJ-F%40LQb1.n4%40%5B3hT2%29J%2aQQC.%3CB%2B%5DhSQd1.p.M%40Q&test_suite=1&test_suite_input=%7B%280%2C0%29%3A3%2C%280%2C1%29%3A2%2C%280%2C2%29%3A4%2C%280%2C3%29%3A4%2C%280%2C4%29%3A5%2C%281%2C0%29%3A3%2C%281%2C1%29%3A3%2C%281%2C2%29%3A4%2C%281%2C3%29%3A3%2C%281%2C4%29%3A4%2C%282%2C0%29%3A2%2C%282%2C1%29%3A1%2C%282%2C2%29%3A1%2C%282%2C3%29%3A5%2C%282%2C4%29%3A3%2C%283%2C0%29%3A1%2C%283%2C1%29%3A2%2C%283%2C2%29%3A3%2C%283%2C3%29%3A4%2C%283%2C4%29%3A3%7D%0A%7B%280%2C0%29%3A6%2C%280%2C1%29%3A7%2C%280%2C2%29%3A8%2C%280%2C3%29%3A7%2C%280%2C4%29%3A7%2C%280%2C5%29%3A7%2C%280%2C6%29%3A8%2C%281%2C0%29%3A5%2C%281%2C1%29%3A7%2C%281%2C2%29%3A7%2C%281%2C3%29%3A7%2C%281%2C4%29%3A6%2C%281%2C5%29%3A7%2C%281%2C6%29%3A9%7D" rel="nofollow">Try it online


答:
PHP, 90 bytes

0 indexed

```<code><?php for(;strlen($s)<=$a=$argv[1];$s.=$n)for($n=0,$j=++$i;--$j;)$i%$j||$n+=$j;echo$s[$a];
</code>```

Absolutely not subtle or with a clever way of approaching it at all.

Also, as usual, produces three notices which are ignored.

Body:
PHP, 90 bytes

0 indexed

<?php for(;strlen($s)<=$a=$argv[1];$s.=$n)for($n=0,$j=++$i;--$j;)$i%$j||$n+=$j;echo$s[$a];

Absolutely not subtle or with a clever way of approaching it at all.

Also, as usual, produces three notices which are ignored.


答:
J, 34 bytes

```<code>{[:;1<@":@(-~>:@#.~/.~&.q:)@+i.@>:
</code>```

This is zero-indexed and uses the formula below to calculate the divisor sums.

Explanation

```<code>{[:;1<@":@(-~>:@#.~/.~&.q:)@+i.@>:  Input: n
                                >:  Increment n
                             i.@    Create the range [0, 1, ..., n]
    1                       +       Add one to each to get [1, 2, ..., n+1]
          (               )@        For each value
                        q:            Get the prime factors
                   /.~&.              For each group of equal prime factors
                #.~                     Raise the first to the first power, the second
                                        squared and so on, and sum them
             >:@                        Increment that sum
                      &.q:            Reduce the groups using multiplication
           -~                         Subtract the initial value from that sum
       ":@                            Convert each to a string
     <@                               Box each
 [:;                                Unbox each and concatenate the strings
{                                   Select the character from that string at index n
                                    and return it
</code>```

Body:
J, 34 bytes

{[:;1<@":@(-~>:@#.~/.~&.q:)@+i.@>:

This is zero-indexed and uses the formula below to calculate the divisor sums.

Explanation

{[:;1<@":@(-~>:@#.~/.~&.q:)@+i.@>:  Input: n
                                >:  Increment n
                             i.@    Create the range [0, 1, ..., n]
    1                       +       Add one to each to get [1, 2, ..., n+1]
          (               )@        For each value
                        q:            Get the prime factors
                   /.~&.              For each group of equal prime factors
                #.~                     Raise the first to the first power, the second
                                        squared and so on, and sum them
             >:@                        Increment that sum
                      &.q:            Reduce the groups using multiplication
           -~                         Subtract the initial value from that sum
       ":@                            Convert each to a string
     <@                               Box each
 [:;                                Unbox each and concatenate the strings
{                                   Select the character from that string at index n
                                    and return it


问:
Illustrate music beats
You know—they look like this:

source

The goal is to draw a music beats illustration like the following:

```<code>=     =      =
=  =  =      =          =
== = ==   =  ==     = ====
== ====  == ===   = = =======
======== == ====  = ========= =
=================================
</code>```

The rules are:

The width of the illustration is 33 symbols, but if you need—any trailing spaces exceeding this width are allowed.

Each column is made of equals signs (=).

Each column has a random height (the height of the next column shouldn’t depend in any way on the height of the previous column), varying from 1 to 6. It’s also fine if it’s at least possible to get some input with no strict math probability (i.e. some inputs could appear more rarely than others).

A column can’t float above the bottom and have gaps in it.

Since every column has the minimal height of 1, the last row can’t have any gaps either—it always consists of 33 equals signs.

Since it’s possible to have no columns with the height of 6 (it’s all random after all): in this case you don’t need to have a top line made of spaces. Applies to any edge cases of this nature: if suddenly your code provided no columns with the height greater than 1, you don’t need to have additional lines made of spaces above the bottom line.

You don’t take any input.

答:
Haskell, 164 Bytes

Being a purely functional language, Haskell was doomed from the start. I did it anyway and it turns out, that the necessary overhead is actually not that large.

```<code>import System.Random
import Data.List
f r n|r>n=' '|0<1='='
s=do
g<-newStdGen
mapM_ putStrLn$transpose$map(\n->map(f$mod n 6)[0..5])(take 33(randoms g)::[Int])
</code>```

Usage:

```<code>s
</code>```

Explanation:

```<code>import System.Random
</code>```

to be able to use newStdGen and randoms

```<code>import Data.List
</code>```

to be able to use transpose

```<code>f r n|r>n=' '|0<1='='
</code>```

defines a function that prints a space if its first argument is larger than the second and a = otherwise. It is called with map (f m) [0..5] on a given number m and the list [0,1,2,3,4,5]. (See below)

```<code>s=do
g<-newStdGen
</code>```

Creates a new standard random number generator

```<code>(take 33(randoms g)::[Int])
</code>```

takes 33 random integers.

```<code>map(\n->map(f$mod n 6)[0..5])
</code>```

Calculates m = n % 6 and maps (f m) to the list [0,1,2,3,4,5], which results in one of "======", " =====", ..., "     =". These lines are mapped to the list of the 33 random integers resulting in a table. (A table in Haskell is a list of lists)

```<code>transpose$
</code>```

switches columns and rows of the table

```<code>mapM_ putStrLn$
</code>```

prints every line in the table

Title: Illustrate music beats

Body:
Haskell, 164 Bytes

Being a purely functional language, Haskell was doomed from the start. I did it anyway and it turns out, that the necessary overhead is actually not that large.

import System.Random
import Data.List
f r n|r>n=' '|0<1='='
s=do
g<-newStdGen
mapM_ putStrLn$transpose$map(\n->map(f$mod n 6)[0..5])(take 33(randoms g)::[Int])

Usage:

s

Explanation:

import System.Random

to be able to use newStdGen and randoms

import Data.List

to be able to use transpose

f r n|r>n=' '|0<1='='

defines a function that prints a space if its first argument is larger than the second and a = otherwise. It is called with map (f m) [0..5] on a given number m and the list [0,1,2,3,4,5]. (See below)

s=do
g<-newStdGen

Creates a new standard random number generator

(take 33(randoms g)::[Int])

takes 33 random integers.

map(\n->map(f$mod n 6)[0..5])

Calculates m = n % 6 and maps (f m) to the list [0,1,2,3,4,5], which results in one of "======", " =====", ..., "     =". These lines are mapped to the list of the 33 random integers resulting in a table. (A table in Haskell is a list of lists)

transpose$

switches columns and rows of the table

mapM_ putStrLn$

prints every line in the table


答:
MATL, <s>16</s> 15 bytes

```<code>:"@@q:\~fsV]vG)
</code>```

Indexing is 1-based.

The last test case times out in the online compiler, but it does give the correct result with the offline compiler, in about 15 seconds.

Try it online!

```<code>:         % Take input n. Push [1 2 ... n]
"         % For each k in [1 2 ... n]
  @       %   Push k
  @q:     %   Push [1 2 ... k-1]
  \       %   Modulo. Zero values correspond to divisors
  ~f      %   Indices of zeros. These are the divisors
  s       %   Sum
  V       %   Convert to string
]         % End for each
v         % Concatenate all stack contents vertically
G)        % Take n-th digit. Implicitly display
</code>```

Body:
0. DEFINITIONS

A sequence is a list of numbers.

A series is the sum of a list of numbers.

The set of natural numbers contains all "non-negative integers greater than zero".

A divisor (in this context) of a natural number j is a natural number i, such that j÷i is also a natural number.

1. PREAMBLE

A couple of other questions on this site mention the concept of the aliquot, or the sequence of divisors of a natural number a which are less than a. Determining amicable numbers involves computing the sum of these divisors, called an aliquot sum or aliquot series. Every natural number has its own aliquot sum, although the value of a number's aliquot sum is not necessarily unique to that number. (Exempli gratia, every prime number has an aliquot sum of 1.)

2. CHALLENGE

Given a natural number n, return the nth digit of the sequence of aliquot sums. The first several series in the sequence, starting with the series for 1, are:

```<code>{0, 1, 1, 3, 1, 6, 1, 7, 4, 8, 1, 16, 1, 10, 9, 15, 1, 21, 1, 22, 11, 14, 1, 36, 6, 16, 13}
</code>```

Concatenated, these look like:

```<code>0113161748116110915121122111413661613
</code>```

Input may be zero-indexed or one-indexed, according to your preference. Solutions must be programs or functions capable of returning the 10,000th digit (input up to 9999 or 10000). The shortest working solution wins.

3. TEST CASES

Correct input-output pairs should include, but are not limited to, the following:

```<code>   0 or     1    ->    0
   4 or     5    ->    1
  12 or    13    ->    6
9999 or 10000    ->    7
</code>```

The number preceding the "or" is 0-indexed; the number following is 1-indexed.

Additional test cases may be provided upon request.

4. REFERENCES

OEIS has a list of numbers and their aliquot sums.

Body:
MATL, <s>16</s> 15 bytes

:"@@q:\~fsV]vG)

Indexing is 1-based.

The last test case times out in the online compiler, but it does give the correct result with the offline compiler, in about 15 seconds.

Try it online!

:         % Take input n. Push [1 2 ... n]
"         % For each k in [1 2 ... n]
  @       %   Push k
  @q:     %   Push [1 2 ... k-1]
  \       %   Modulo. Zero values correspond to divisors
  ~f      %   Indices of zeros. These are the divisors
  s       %   Sum
  V       %   Convert to string
]         % End for each
v         % Concatenate all stack contents vertically
G)        % Take n-th digit. Implicitly display


问:
Interpret Kipple!

Introduction

Kipple is a stack-based, esoteric programming language invented by Rune Berg in March 2003.

Kipple has 27 stacks, 4 operators, and a control structure.

Stacks

The stacks are named a-z and contain 32-bit signed integers. There is also a special stack, @, to make outputting numbers more convenient. When a number is pushed onto @, the ASCII values of that number's digits are in fact pushed instead. (For example, if you push 12 to @, it will push 49 and then 50 to @ instead.)

Input is pushed onto the input stack i before the program is executed. The interpreter will ask for values to store in i before execution. After execution finishes, anything on the output stack o is popped to output as ASCII character . Since this is Kipple's only IO mechanism, interacting with a Kipple program is impossible.

Operators

An operand is either a stack identifier or a signed 32 bit integer.

Push: > or <

Syntax: Operand>StackIndentifier or StackIndentifier<Operand

The Push operator takes the operand to the left and pushes it onto the specified stack. For example, 12>a will push the value 12 onto stack a. a>b will pop the topmost value from stack a and push it onto stack b. Popping an empty stack always returns 0. a<b is equivalent to b>a. ac pops topmost value from b and pushes to both c and a.

Add: +

Syntax: StackIndentifier+Operand

The Add operator pushes the sum of the topmost item on the stack and the operand onto the stack. If the operand is a stack, then the value is popped from it. For example, if the topmost value of stack a is 1, then a+2 will push 3 onto it. If a is empty, then a+2 will push 2 onto it. If the topmost values of stack a and b are 1 and 2, then a+b will pop the value 2 from stack b and push 3 onto stack a.

Subtract: -

Syntax: StackIndentifier-Operand

The Subtract operator works exactly like the Add operator, except that it subtracts instead of adding.

Clear: ?

Syntax: StackIndentifier?

The Clear operator empties the stack if its topmost item is 0.

The interpreter will ignore anything that isn't next to an operator, so the following program would work: a+2 this will be ignored c<i. However, the proper way to add comments is by using the # character. Anything between a # and an end-of-line character is removed before execution. ASCII character #10 is defined as end-of-line in Kipple.

Operands may be shared by two operators, e.g. a>b c>b c? may be written as a>b<c?.

The program 1>a<2 a+a will result in a containing the values [1 4] (from bottom to top) and not [1 3]. Likewise for the - operator.

The Control Structure

There is only one control structure in Kipple: the loop.

Syntax: (StackIndentifier code )

As long as the specified stack is not empty, the code within the matching parentheses will be repeated. Loops may contain other loops. For example, (a a>b) will move all the values of stack a onto stack b, though the order will be reversed. A functionally identical, but more elegant way to do this is (a>b).

Examples

```<code>100>@ (@>o)
</code>```

This will output 100

```<code>33>o 100>o 108>o 114>o 111>o 87>o 32>o 111>o 108>o 108>o 101>o 72>o
</code>```

This will print "Hello World!". When the o stack is being output, it starts to pop characters from top of the stack to bottom.

```<code>#prime.k by Jannis Harder
u<200
#change 200

k<2>m
u-2
(u-1 u>t u>z u<t
  (k>e e+0 e>r)
  (e>k)
  m+1
  m>t
  m>z
  m<t
  t<0>z? t?
  1>g
  (r>b
    m+0 m>a
    b+0 b>w
    (a-1
      b+0 b>j
      j?
      1>s
      (j<0>s j?)
      s?
      (s<0 w+0 w>b s?)
      a>t
      a>z
      t>a
      b-1
      b>t
      b>z
      t>b
      z<0>t? z?
    a?)
    b?
    1>p
    (b<0 b? 0>p)
    p?
    (p 0>r? 0>p? 0>g)
  )
  g?
  (g m+0 m>k 0>g?)
u?)
(k>@
  10>o
  (@>o)
)
</code>```

This is a prime number generator, but I'm not sure how it works.

Rules

You must write a program/function that interprets Kipple. This program/function may get a Kipple program via a source file, or get it via STDIN directly from the user. If STDIN is not available, it must get it from keyboard input, and continue getting input until a specific unprintable character is entered. For example, if your interpreter is written in x86 machine code, it would get the Kipple program character by character from keyboard, and continue to do so until esc (or any other key other that does not emit a printable character) is pressed.

If there is an error, e.g. a syntax error or stack overflow, it must acknowledge it in some way, for example by returning 10 instead of 0 or error messages produced by the interpreter/compiler, BUT NOT PRINTING ERROR MESSAGES.

Any other regular rules for code golf apply for this challenge.

Your code will be tested with some of the examples in Kipple's samples archive

This is a code-golf . Shortest code in bytes will win.
Good Luck!

Note that there is an optional operator in Kipple, ", but it is not a part of the specification and just an extra feature in official interpreter. I haven't mentioned it here so it does not need to be supported in your submission.

If you have any doubt about any part of specification , you can examine it with official interpreter written in Java . This will download a zip file containing compiled program and source code . It's licensed under the GPL.

答:
Ruby, 718 bytes (currently noncompeting)

i'm very tired

File is loaded as a command line argument, and input is sent through STDIN. Alternatively, pipe the file into STDIN if you don't need input in your i register.

<s>Because of some confusion regarding the spec, the current version is not handling ac properly, and therefore is noncompeting until it is fixed.</s>

ac is fixed now. However, it still returns the wrong result when running the primes function, so it still remains as a noncompeting answer.

```<code>(f=$<.read.gsub(/#.*?\n|\s[^+-<>#()?]*\s/m,' ').tr ?@,?`
t=Array.new(27){[]}
t[9]=STDIN.read.bytes
k=s=2**32-1
r=->c{c=c[0];c[0]==?(?(s[c[1..-2]]while[]!=t[c[1].ord-96]):(c=c.sub(/^(.)<(\D)>(.)/){$1+"<#{t[$2.ord-96].pop||0}>"+$3}.sub(/(\d+|.)(\W)(\d+|.)?/){_,x,y,z=*$~
a=x.ord-96
b=(z||?|).ord-96
q=->i,j=z{j[/\d/]?j.to_i: (t[i]||[]).pop||0}
l=t[a]
y<?-?(x==z ?l[-1]*=2:l<<(l.pop||0)+q[b]
l[-1]-=k while l[-1]>k/2):y<?.?(x==z ?l[-1]=0:l<<(l.pop||0)-q[b]
l[-1]+=k while l[-1]<-k/2-1):y<?>?t[a]+=a<1?q[b].to_s.bytes: [q[b]]:y<???
(t[b]+=b<1?q[a,x].to_s.bytes: [q[a,x]]): l[-1]==0?t[a]=[]:0
z||x}while c !~/^(\d+|.)$/)}
s=->c{(z=c.scan(/(\((\g<1>|\s)+\)|[^()\s]+)/m)).map &r}
s[f]
$><<t[15].reverse.map(&:chr)*'')rescue 0
</code>```

Title: Interpret Kipple!

Body:
Ruby, 718 bytes (currently noncompeting)

i'm very tired

File is loaded as a command line argument, and input is sent through STDIN. Alternatively, pipe the file into STDIN if you don't need input in your i register.

<s>Because of some confusion regarding the spec, the current version is not handling a<b>c properly, and therefore is noncompeting until it is fixed.</s>

a<b>c is fixed now. However, it still returns the wrong result when running the primes function, so it still remains as a noncompeting answer.

(f=$<.read.gsub(/#.*?\n|\s[^+-<>#()?]*\s/m,' ').tr ?@,?`
t=Array.new(27){[]}
t[9]=STDIN.read.bytes
k=s=2**32-1
r=->c{c=c[0];c[0]==?(?(s[c[1..-2]]while[]!=t[c[1].ord-96]):(c=c.sub(/^(.)<(\D)>(.)/){$1+"<#{t[$2.ord-96].pop||0}>"+$3}.sub(/(\d+|.)(\W)(\d+|.)?/){_,x,y,z=*$~
a=x.ord-96
b=(z||?|).ord-96
q=->i,j=z{j[/\d/]?j.to_i: (t[i]||[]).pop||0}
l=t[a]
y<?-?(x==z ?l[-1]*=2:l<<(l.pop||0)+q[b]
l[-1]-=k while l[-1]>k/2):y<?.?(x==z ?l[-1]=0:l<<(l.pop||0)-q[b]
l[-1]+=k while l[-1]<-k/2-1):y<?>?t[a]+=a<1?q[b].to_s.bytes: [q[b]]:y<???
(t[b]+=b<1?q[a,x].to_s.bytes: [q[a,x]]): l[-1]==0?t[a]=[]:0
z||x}while c !~/^(\d+|.)$/)}
s=->c{(z=c.scan(/(\((\g<1>|\s)+\)|[^()\s]+)/m)).map &r}
s[f]
$><<t[15].reverse.map(&:chr)*'')rescue 0


答:
Jelly, <s>13</s> <s>11</s> 10 bytes

2 bytes thanks to @Adnan and 1 more thanks to @Dennis.

```<code>ÆDṖSDµ€Fị@
</code>```

Try it online!

Uses 1-based indexing. Completes for n = 10000 in under 2 seconds online.

Body:
Jelly, <s>13</s> <s>11</s> 10 bytes

2 bytes thanks to @Adnan and 1 more thanks to @Dennis.

ÆDṖSDµ€Fị@

Try it online!

Uses 1-based indexing. Completes for n = 10000 in under 2 seconds online.


答:
05AB1E, <s>14</s> <s>11</s> 10 bytes

Compute n = 9999 in about 15 seconds. Code:

```<code>ÌL€Ñ€¨OJ¹è
</code>```

Explanation:

```<code>Ì           # Increment implicit input by 2
 L          # Generate the list [1 .. input + 2]
  €Ñ        # For each, get the divisors
    €¨      # For each, pop the last one out
      O     # Sum all the arrays in the array
       J    # Join them all together
        ¹è  # Get the nth element
</code>```

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

Body:
05AB1E, <s>14</s> <s>11</s> 10 bytes

Compute n = 9999 in about 15 seconds. Code:

ÌL€Ñ€¨OJ¹è

Explanation:

Ì           # Increment implicit input by 2
 L          # Generate the list [1 .. input + 2]
  €Ñ        # For each, get the divisors
    €¨      # For each, pop the last one out
      O     # Sum all the arrays in the array
       J    # Join them all together
        ¹è  # Get the nth element

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


Title: Walk the labyrinth

Body:
Or maybe it's not really a labyrinth, but still.

Rules:

Input is a two-line string, consisting of *, 1, x and X. That string is a labyrinth to walk through. The lines have the equal length.

You could take the input as a string with , (comma) or any convenient separator between these two lines. Or you could take both lines as separate arguments to your function.

Output is the number of steps you have to take to exit the string (last step is the step which moves you out of the string).

You start in the top left corner (the higher line), before the first symbol.

For each step, you move forward by one symbol (from nth to (n+1)th position). Then, depending on the character you step on, the outcome is different. Here's what each char does:

* - nothing. You just step on it normally.

x - once you stepped on it, switch the line, but remain on the same horizontal distance from the beginning. For example, you stepped on the third position of the higher line, and met a lowercase x here. Then you immediately move to the lower line, but again at the third position.

X - switch the line and go to the next position. The example is the same there, but you also move from the third to the forth position (thus you're on the second line at the forth position).

1 - just move forward by yet another position.

Once each character does its job, it's replaced with a space and no longer "works".

Examples follow.

Input:

```<code>x
*
</code>```

As said before, you start before the first symbol of the first line. The first step moves you on letter x and this letter switches you to the second line. The letter x no longer functions as x, but replaced with *. This will be more relevant in the latter examples. You're now on an asterisk on the lower line, and it did nothing to you.

The second step is moving you forward and you exit the string, so the labyrinth is completed, and it took 2 steps.

Output 2.

Input:

```<code>xX*
x1*
</code>```

1st step: you move on x, which moves you on the x of the lower line. Here comes the rule which says that the used character is replaced with asterisk. Then you move back on the first line, but it's no longer x there, since it has been used and became an asterisk. So you move safely on this asterisk and the step is completed (you are now on the first position of the first line).

2nd step: you move on X, it pushes you to the lower line and then pushes you forward. You now reside on the third position of the second line (asterisk), having never visited the second position (which contains 1).

3rd step: you move forward, exiting the string.

Output: 3.

Test cases:

Input:

```<code>*1*
xxx
</code>```

Output: 3. (because 1 makes you jump on the third position). There you never visit the second line, but it's required part of the input.

Input:

```<code>*X*1*x
x*1xx*
</code>```

Output: 4.

Input:

```<code>1x1x
***X
</code>```

Output: 3.

Input:

```<code>1*x1xxx1*x
x*x1*11X1x
</code>```

Output: 6.

Input:

```<code>xXXXxxx111*
**xxx11*xxx
</code>```

Output: 6.

Body:
JavaScript (ES6), 119

l=>{z=-~l.search`
`,l=[...l+' '];for(n=p=0;(c=l[p%=2*z])>' ';p+=c>'X'?z:c>'1'?z+1:c>'0'?1:(++n,1))l[p]='*';return-~n}

Less golfed

l=>{
  z=1+l.search`\n`;
  l=[...l+' '];
  for( n = p = 0;
       (c=l[p%=2*z])>' ';
       p += c>'X' ? z : c>'1' ? z+1 : c>'0'? 1 : (++n,1) )
    l[p] = '*';
  return 1+n
}

Test

f=l=>{z=-~l.search`
`,l=[...l+' '];for(n=p=0;(c=l[p%=2*z])>' ';p+=c>'X'?z:c>'1'?z+1:c>'0'?1:(++n,1))l[p]='*';return-~n}

[['x\n*',2]
,['xX*\nx1*',3]
,['*1*\nxxx',3]
,['*X*1*x\nx*1xx*',4]
,['1x1x\n***X',3]
,['1*x1xxx1*x\nx*x1*11X1x',6]
,['xXXXxxx111*\n**xxx11*xxx',6]
].forEach(t=>{
  var i=t[0],k=t[1],r=f(i)
  console.log('Test result '+r+(r==k?' OK ':' KO (expected '+k+')')+'\n'+i)
})


答:
Perl, 128 bytes

$b=" 0 9 27"x28;$w=" 31"x12;$r=" 26 5 5"x8;
$t="$b$w$r$w$b$b"x28;
$m=($w x8 .$r.$w x15)x4;
print"P3 100 72 31",$t,$m,$r x100,$m,$t;
```

(newlines added for readability, and not counted)

This is a straightforward compression of a PPM image.  A PPM is supposed to have a line length of 70 or less, but in practice all readers will accept this image that's all on a single line.  If you want to be properly portable, replace the first space in each of $b, $w and $r with a newline.

I've assumed that the RGB values supplied are in sRGB coordinates, so no need to apply any gamma correction for PPM.

Title: Draw the national flag of Iceland

Body:
Perl, 128 bytes

$b=" 0 9 27"x28;$w=" 31"x12;$r=" 26 5 5"x8;
$t="$b$w$r$w$b$b"x28;
$m=($w x8 .$r.$w x15)x4;
print"P3 100 72 31",$t,$m,$r x100,$m,$t;

(newlines added for readability, and not counted)

This is a straightforward compression of a PPM image.  A PPM is supposed to have a line length of 70 or less, but in practice all readers will accept this image that's all on a single line.  If you want to be properly portable, replace the first space in each of $b, $w and $r with a newline.

I've assumed that the RGB values supplied are in sRGB coordinates, so no need to apply any gamma correction for PPM.


答:
Go, 63 bytes

```<code>func f(i int) int{if(i<4){return 1};return 2*f(i-1)-i%2*f(i/2)}
</code>```

Pretty much a direct port from the C answer

Title: Narayana-Zidek-Capell numbers

Body:
Generate the nth Narayana-Zidek-Capell number given an input n. Fewest bytes win.

f(1)=1, f(n) is the sum of the previous floor(n/2) Narayana-Zidek-Capell terms.

Test Cases:

```<code>f(1)=1

f(9)=42

f(14)=1308

f(15)=2605

f(23)=664299
</code>```

Body:
Go, 63 bytes

func f(i int) int{if(i<4){return 1};return 2*f(i-1)-i%2*f(i/2)}

Pretty much a direct port from the C answer


问:
Draw the national flag of France
There have been many other flag challenges posted but not one for the national flag of France. This week seems like an appropriate time.

Produce this flag in the fewest bytes possible:

The image must be in a ratio of 3:2, with size at least 78 pixels wide and 52 pixels tall.

Each stripe takes up one third of the width.

The stripe colors from left to right are RGB: (0, 85, 164), (255, 255, 255), (239, 65, 53).

The image can be saved to a file or piped raw to STDOUT in any common image file format, or it can be displayed.

Alternatively, output a block of text at least 78 characters wide made of non-whitespace characters that depicts the flag, using ANSI color codes to color it. (Use standard blue, white, and red.)

Built-in flag images/libraries are not allowed.

The shortest code in bytes wins.

Leaderboard

The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

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

Straightforward as PPM:

```<code>print"P6 78 52 255 "+(26*"\x00U\xff"+78*"\xff"+26*"\xefA5")*52
</code>```

Usage:

```<code>python golf_france.py > france.ppm
</code>```

Edit1: Binary PPM is shorter, haven't figured out how to use to strange codes directly in the strings.

ContentLicense: CC BY-SA 4.0

Title: Draw the national flag of France

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

Straightforward as PPM:

print"P6 78 52 255 "+(26*"\x00U\xff"+78*"\xff"+26*"\xefA5")*52

Usage:

python golf_france.py > france.ppm

Edit1: Binary PPM is shorter, haven't figured out how to use to strange codes directly in the strings.


问:
Power Grid Resource Costs

Power Grid Resource Costs

Introduction

In the board game Power Grid, an integral part of the game is the act of buying resources to fuel your power stations. There are four types of resource used in the game (five, if you include renewable energy, but obviously you can't buy resources for that). These are Coal, Oil, Garbage, and Uranium. The resource market looks like this:

```<code>1---- | 2---- | 3---- | 4---- | 5---- | 6---- | 7---- | 8---- | 10  | 12
CCC   | CCC   | CCC   | CCC   | CCC   | CCC   | CCC   | CCC   |  U  |  U
OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | OOO U | 14  | 16
GGG   | GGG   | GGG   | GGG   | GGG   | GGG   | GGG   | GGG   |  U  |  U
</code>```

When resources are bought, they are taken from the left of the market, where they are cheapest. When new resources are added to the market, they are added from the right. As can be seen, this produces a supply and demand balance - if more resources of a particular type are being bought than are being replenished each round, the price of that resource will rise. Similarly, if it's less, the cost will reduce.

Coal, Oil, and Garbage all scale up in cost at the same rate, while Uranium scales much faster. A single unit of a non-Uranium resource costs 8 - floor((<units available> - 1) / 3). A single unit of Uranium costs 13 - <units available> if there are 5 or more units available, and 18 - (2 * <units available>) otherwise.

For example, at the start of the game there are all 24 units of Coal available to buy. If the first player would like to buy 4 units of Coal, the first three units would cost 1 each, and the 4th would cost 2, making the total cost 5. This leaves 20 units available. If the second player would also like to buy 4 units of Coal, the cost would be (2*2 + 2*3) = 10.

The Challenge

Your challenge is to write a program or function which calculates the cost of buying a given amount of a particular resource, assuming that there is a given amount of that resource present in the market.

Your submission should accept, in any reasonable input format and in any order, the following parameters:

The resource type - guaranteed to be one of [C, O, G, U].

The amount of that resource that is present in the market - guaranteed to be a non-negative integer. If the resource type is not U, it will not be greater than 24. If the resource type is U, it will not be greater than 12.

The amount of that resource that a player would like to buy - guaranteed to be a non-negative integer which is less than or equal to the amount already present in the market.

The output should be the cost of the requested resources.

Additional Rules

The formulae given are for illustrative purposes only, feel free to use any method of calculating the costs you like.

The letter codes for the different resource types (C, O, G, U) may be replaced by their lower case equivalents. You may also replace the letters for numbers, either in the form C=0, O=1, G=2, U=3 or C=1, O=2, G=3, U=4.

This is code-golf, so the smallest submission in bytes will be the winner.

If your submission requires the input in a different order or format than specified in the previous section, you should provide details.

Test cases

Test case format:

```<code>resource type, amount in market, amount to buy
> result
</code>```

Test cases:

```<code>C, 24, 4
> 5

C, 20, 4
> 10

O, 3, 3
> 24

U, 1, 1
> 16

C, 1, 1
> 8

G, 0, 0
> 0

O, 10, 7
> 44

U, 12, 4
> 10

G, 11, 4
> 22
</code>```

答:
Lua, <s>107</s> 101 Bytes

Recursive function that have to be called with f(resource,stock,buy). resource have to be a number between 0 and 3.
The output is done via the returned value.

Thanks LeakyNun for saving me 6 bytes : (25-y+(y-1)%3)/3 is shorter than 8-math.floor((y-1)/3) by 5 bytes and allow me to gain one more byte due to its placement.

function f(x,y,z)return z<1 and 0or(x<3 and(25-y+(y-1)%3)/3or(y<5 and 18-y*2or 13-y))+f(x,y-1,z-1)end
```

<h3>Ungolfed</h3>

<pre class="lang-lua prettyprint-override"><code>function f(x,y,z)                      -- define a function f with 3 parameters
  return z<1                           -- if we don't buy anything else
           and 0                       --   return 0
         or(                           -- else
           x<3                         --   if we're not buying Uranium
             and (25-y+(y-1)%3)/3      --     return 8-floor((stock-1)/3)
           or(y<5                      --   elseif there's less than 5 Uranium left
                and 18-y*2             --     return 18-stock*2
              or 13-y))                --   else return 13-stock
         +f(x,y-1,z-1)                 -- if we bought this iteration
                                       -- add f(resource,stock-1,toBuy-1)
                                       -- to the returned value
end
</code>```

You can test this code online by copy-pasting the following snippet.

function f(x,y,z)return z<1 and 0or(x<3 and(25-y+(y-1)%3)/3or(y<5 and 18-y*2or 13-y))+f(x,y-1,z-1)end
print(f(1,24,4))
print(f(2,20,4))
print(f(0,10,7))
print(f(3,1,1))
print(f(3,12,4))
```

Title: Power Grid Resource Costs

Body:
Lua, <s>107</s> 101 Bytes

Recursive function that have to be called with f(resource,stock,buy). resource have to be a number between 0 and 3.
The output is done via the returned value.

Thanks LeakyNun for saving me 6 bytes : (25-y+(y-1)%3)/3 is shorter than 8-math.floor((y-1)/3) by 5 bytes and allow me to gain one more byte due to its placement.

function f(x,y,z)return z<1 and 0or(x<3 and(25-y+(y-1)%3)/3or(y<5 and 18-y*2or 13-y))+f(x,y-1,z-1)end

Ungolfed

function f(x,y,z)                      -- define a function f with 3 parameters
  return z<1                           -- if we don't buy anything else
           and 0                       --   return 0
         or(                           -- else
           x<3                         --   if we're not buying Uranium
             and (25-y+(y-1)%3)/3      --     return 8-floor((stock-1)/3)
           or(y<5                      --   elseif there's less than 5 Uranium left
                and 18-y*2             --     return 18-stock*2
              or 13-y))                --   else return 13-stock
         +f(x,y-1,z-1)                 -- if we bought this iteration
                                       -- add f(resource,stock-1,toBuy-1)
                                       -- to the returned value
end

You can test this code online by copy-pasting the following snippet.

function f(x,y,z)return z<1 and 0or(x<3 and(25-y+(y-1)%3)/3or(y<5 and 18-y*2or 13-y))+f(x,y-1,z-1)end
print(f(1,24,4))
print(f(2,20,4))
print(f(0,10,7))
print(f(3,1,1))
print(f(3,12,4))