问:
m3ph1st0s's programming puzzle 2 (C++): "Call hard!"
I am back with a brand new puzzle for C/C++ addicts. Following the feedback received on the 1st puzzle, this time I will try to make the requirements crystal clear and to provide a perfectly valid code.

Here is the problem.
Given the following code:

```<code>#include <iostream>

char message[6]="hello";

void print_hello_message() {
   std::cout << message;
}

int main() {
   char* q = &message[0];

   // insert your code here
}
</code>```

You are required to insert two more lines where the comment specifies in order to make the program print "hello" and nothing more, with the following restrictions:

the first line will NOT call any function, including cout

the second line will contain AT MOST 5 letters (and as many other symbols as you want)

the first line may contain new variable declarations but may not initialize them

the symbols # and / will not be used at all.

no logical operators will be used

The shortest code wins!

答:
Use q to store a pointer to print_hello_message, then cast it back to a function pointer and invoke it.

```<code>q = (char *) &print_hello_message;
(*(void(*)())q)();
</code>```

Short version:

```<code>q=(char*)print_hello_message;
(*(void(*)())q)();
</code>```

Body:
Use q to store a pointer to print_hello_message, then cast it back to a function pointer and invoke it.

q = (char *) &print_hello_message;
(*(void(*)())q)();

Short version:

q=(char*)print_hello_message;
(*(void(*)())q)();


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

答:
JavaFX, 527 bytes

```<code>import javafx.scene.*;import javafx.scene.paint.*;import javafx.scene.shape.Rectangle;public class I extends javafx.application.Application{public void start(javafx.stage.Stage s){Color w=Color.WHITE;Paint z=Paint.valueOf("#d72828");Group g=new Group();Scene n=new Scene(g,250,180,Color.valueOf("#0048e0"));g.getChildren().addAll(r(70,0,40,180,w),r(0,70,250,40,w),r(0,80,250,20,z),r(80,0,20,180,z));s.setScene(n);s.show();}Rectangle r(int x,int y,int w,int h,Paint p){Rectangle r=new Rectangle(x,y,w,h);r.setFill(p);return r;}}
</code>```

Two red rectangles on two white rectangles on a blue background.

Ungolfed:

```<code>import javafx.scene.*;
import javafx.scene.paint.*;
import javafx.scene.shape.Rectangle;

public class I extends javafx.application.Application {
    public void start(javafx.stage.Stage s) {
        Color w = Color.WHITE;
        Paint z = Paint.valueOf("#d72828");
        Group g = new Group();
        Scene n = new Scene(g, 250, 180, Color.valueOf("#0048e0"));
        g.getChildren().addAll(
            r(70, 0, 40, 180, w),
            r(0, 70, 250, 40, w),
            r(0, 80, 250, 20, z),
            r(80, 0, 20, 180, z));
        s.setScene(n);
        s.show();
    }

    Rectangle r(int x, int y, int w, int h, Paint p) {
        Rectangle r = new Rectangle(x, y, w, h);
        r.setFill(p);
        return r;
    }
}
</code>```

(Weirdly, if I change it to import javafx.scene.shape.*; it won't compile with Java 1.8.0_92. I'm not sure if that's a bug.)

ContentLicense: CC BY-SA 3.0

Title: Draw the national flag of Iceland

Body:
JavaFX, 527 bytes

import javafx.scene.*;import javafx.scene.paint.*;import javafx.scene.shape.Rectangle;public class I extends javafx.application.Application{public void start(javafx.stage.Stage s){Color w=Color.WHITE;Paint z=Paint.valueOf("#d72828");Group g=new Group();Scene n=new Scene(g,250,180,Color.valueOf("#0048e0"));g.getChildren().addAll(r(70,0,40,180,w),r(0,70,250,40,w),r(0,80,250,20,z),r(80,0,20,180,z));s.setScene(n);s.show();}Rectangle r(int x,int y,int w,int h,Paint p){Rectangle r=new Rectangle(x,y,w,h);r.setFill(p);return r;}}

Two red rectangles on two white rectangles on a blue background.

Ungolfed:

import javafx.scene.*;
import javafx.scene.paint.*;
import javafx.scene.shape.Rectangle;

public class I extends javafx.application.Application {
    public void start(javafx.stage.Stage s) {
        Color w = Color.WHITE;
        Paint z = Paint.valueOf("#d72828");
        Group g = new Group();
        Scene n = new Scene(g, 250, 180, Color.valueOf("#0048e0"));
        g.getChildren().addAll(
            r(70, 0, 40, 180, w),
            r(0, 70, 250, 40, w),
            r(0, 80, 250, 20, z),
            r(80, 0, 20, 180, z));
        s.setScene(n);
        s.show();
    }

    Rectangle r(int x, int y, int w, int h, Paint p) {
        Rectangle r = new Rectangle(x, y, w, h);
        r.setFill(p);
        return r;
    }
}

(Weirdly, if I change it to import javafx.scene.shape.*; it won't compile with Java 1.8.0_92. I'm not sure if that's a bug.)


问:
Use 16 colors while writing Hey! 4 times
i.e each byte appears in a different ANSI shell colour.

Rules

Resetting the color of the shell after output is not required

Must be output in STDOUT or the primary colour text output of your language.

Must be done programmatically (iterating through each color and letter of the string induvidually) instead of just writing a fixed string to shell like the reference command.

Must output the same as the reference command:
echo -e '\e[30mH\e[31me\e[32my\e[33m!\e[34mH\e[35me\e[36my\e[37m!\e[90mH\e[91me\e[92my\e[93m!\e[94mH\e[95me\e[96my\e[97m!'
on a recent version of bash (I am using 4.3 installed via Homebrew on OS X) i.e like this:

Obviously colours will vary based on terminal colour scheme.

Scoring

This is code-golf, so lowest bytes wins.

答:
bash, <s>101</s> 72 bytes

29 bytes saved with a trick from @DomHastings.

```<code>s='y!He'
for i in {30..37} {90..97}
do
printf "\e["$i"m"${s:$i%4:1}
done
</code>```

If I hadn´t scrambled the string, this would have been 105 (($i+2)%4 instead of $i%4), just as my

previous approach, 105 bytes

```<code>function p
{
s='Hey!'
for i in {0..3}
do
let r=i+$1
printf "\e["$r"m"${s:$i:1}
done
}
p 30;p 34;p 90;p 94
</code>```

Body:
bash, <s>101</s> 72 bytes

29 bytes saved with a trick from @DomHastings.

s='y!He'
for i in {30..37} {90..97}
do
printf "\e["$i"m"${s:$i%4:1}
done

If I hadn´t scrambled the string, this would have been 105 (($i+2)%4 instead of $i%4), just as my

previous approach, 105 bytes

function p
{
s='Hey!'
for i in {0..3}
do
let r=i+$1
printf "\e["$r"m"${s:$i:1}
done
}
p 30;p 34;p 90;p 94


问:
Minimum Scalar Product
Minimum Scalar Product

The inspiration for this code golf problem is from Google's code jam competition. The premise behind the problem is, given the input of two vectors of varying lengths, find the minimum possible scalar. A scalar can be found using the following formula:

```<code>x1 * y1 + x2 * y2 + ... + xn * yn
</code>```

The problem, however, is that multiple values for the scalar can be found depending on the order of the numerals in the input case (seen below). Your goal is to determine the minimum possible scalar integer solution by plugging in the input case numbers into the equation and solving for it. You may use every number in the input only once, and must use all of the numbers.

Allow me to provide an example with the following vectors.

Input

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

Output

```<code>-25
</code>```

The first integer on the line represents the number of numbers, n, in each vector. In this case, we have three numbers in each vector.

The number n may vary with each test case, but there will always be two vectors.

In the example input, the minimum scalar product would be -25.

```<code>(-5 * 4) + (1 * 1) + (3 * -2) = 25
</code>```

Rules

You may only use each integer in both vectors once.

You must use all integers in the vectors.

Your output must only include the final product

I'll select the solution with the least amount of code, which follows all of the specifications listed above, in any language!

 Hint: You don't need to brute force this problem, unless it makes your code shorter. There is a specific method involved in finding the minimum spanning scalar :).

答:
Python, 139 bytes

```<code>def mdp(n, a, b):
    a = list(reversed(sorted(a)))
    b = sorted(b)
    res = sum([a[i] * b[i] for i in range(len(a))])
    return res
</code>```

Title: Minimum Scalar Product

Body:
Python, 139 bytes

def mdp(n, a, b):
    a = list(reversed(sorted(a)))
    b = sorted(b)
    res = sum([a[i] * b[i] for i in range(len(a))])
    return res


答:
Python 3.5 + Tkinter, 235 bytes:

```<code>from tkinter import*;C=Canvas(Tk(),height=126,width=175,bg='#d72828');C.pack();X=lambda*a:C.create_rectangle(a,fill='#0048E0',outline='#fff',width=7);X(0,0,8,8);X(0,11,8,19);X(11,0,26,8);X(11,11,26,19);C.scale('all',0,0,7,7);mainloop()
</code>```

Really long, but happy with it regardless. Basically creates a canvas with a red background and then draws 4 blue rectangles with white borders over the background in the 4 corners. After the drawing is all done, the canvas is enlarged by a scale factor of 7. Displays the completed flag in a new window on a canvas with the dimensions 175 x 126.

Image of Output:

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:
Python 3.5 + Tkinter, 235 bytes:

from tkinter import*;C=Canvas(Tk(),height=126,width=175,bg='#d72828');C.pack();X=lambda*a:C.create_rectangle(a,fill='#0048E0',outline='#fff',width=7);X(0,0,8,8);X(0,11,8,19);X(11,0,26,8);X(11,11,26,19);C.scale('all',0,0,7,7);mainloop()

Really long, but happy with it regardless. Basically creates a canvas with a red background and then draws 4 blue rectangles with white borders over the background in the 4 corners. After the drawing is all done, the canvas is enlarged by a scale factor of 7. Displays the completed flag in a new window on a canvas with the dimensions 175 x 126.

Image of Output:


问:
Find the paths!
You must write a program or function.

The input is a 'map' of numbers. You can choose to take the map as either a string with new line characters (\n) or a 2D array of strings.

All maps are 5 characters by 5 characters, and the characters are always either digits greater than 0 or spaces.

Here is an example of a map:

```<code>12 45
11233
  233
    1
2 899
</code>```

Your task is to find the connected components in the map. A valid component is a series of at least three horizontally and/or vertically (not diagonally) connected identical digits (not spaces). You will then need to replace the characters of the valid connected components with xs and print or return that result.

So, the output for the above example would be:

```<code>x2 45
xx2xx
  2xx
    1
2 899
</code>```

Here's another test case (thanks to Martin Ender):

```<code>Input:
2   3
    4
 1  5
111 6
11  7

Output:
2   3
    4
 x  5
xxx 6
xx  7
</code>```

This is code golf so shortest code in bytes wins!

答:
Ruby, 304 bytes

```<code>def b(s,i)
  @v=[]
  b2(s,i,s[i])
end
def b2(s,i,c)
  if(0...s.size)===i&&s[i]==c&&!@v[i]
    @v[i]=s[i]='x'
    [1,-1,6,-6].each{|j|b2(s,i+j,c)}
  end
  s
end
def f(s)
  z = s.dup
  ps = ->(i){b(z.dup,i).scan('x').size}
  (0...s.size).each{|i|b(s, i)if ![' ',"\n"].include?(s[i])&&ps.call(i)>2}
  s
end
</code>```

example usage:

```<code>puts f(File.read("map.txt"))
</code>```

the code reuses the 'blot' method to calculate the path length.

variables/methods:

f(s): function to convert map string, returns new map with 'x's

ps(i): path size from map index i (where x = i % 6, y = i / 6)

s: input string, map lines separated by "\n"

z: copy of input string

b(s,i): 'blot' function: writes 'x' from map index i over paths

@v: 'visited' array

Attempt at more detailed explanation:

make a copy of the input string, which we use for finding the length of the path from any given point in the map.

```<code>z = s.dup
</code>```

define a 'ps' (path length) anonymous function (lambda) which takes the map index i as an argument. it returns the length of the path from that point. it does this by calling the 'b' (blot) method to insert x's on a copy of the original map and then counting the number of x's in the returned string.

```<code>  ps = ->(i){b(z.dup,i).scan('x').size}
</code>```

the following part iterates over each character in the map (index i, character s[i]). it calls the 'b' (blot) function on map position i if the path length from position i is greater than 2, and if it's not a space or newline character.

```<code>  (0...s.size).each { |i|
     b(s, i) if ![' ',"\n"].include?(s[i]) && ps.call(i) > 2
  }
</code>```

the b (blot) function takes the map string and an index as argument. it initialises @v (visited array) and calls the b2 helper function.

```<code>def b(s,i)
  @v=[]
  b2(s,i,s[i])
end
</code>```

the b2 function takes the map string, a map position (i), and a character in the current path (c). it calls itself recursively to replace connected sections of digits with the 'x' character. it returns the input string (this is so the ps function can call scan() on the return value).

this if statement is checking that the map position (i) given is within the bounds of the string (0...s.size) and that the character at s[i] is the same as the starting character. also @v[i] is checked to avoid infinite recursion.

```<code>if(0...s.size) === i && s[i] == c && !@v[i]
</code>```

this is the bit that replaces the character at index (i) with the 'x' character. it also marks that index as visited.

```<code>@v[i] = s[i] = 'x'
</code>```

this is where b2 calls itself recursively searching for the path. i+1 is one character to the right, i-1 is one character to the left, i+6 is one row down (5 digits + 1 newline = 6 characters), i-6 is one row up.

```<code>[1,-1,6,-6].each { |j| b2(s, i+j, c) }
</code>```

Title: Find the paths!

Body:
Ruby, 304 bytes

def b(s,i)
  @v=[]
  b2(s,i,s[i])
end
def b2(s,i,c)
  if(0...s.size)===i&&s[i]==c&&!@v[i]
    @v[i]=s[i]='x'
    [1,-1,6,-6].each{|j|b2(s,i+j,c)}
  end
  s
end
def f(s)
  z = s.dup
  ps = ->(i){b(z.dup,i).scan('x').size}
  (0...s.size).each{|i|b(s, i)if ![' ',"\n"].include?(s[i])&&ps.call(i)>2}
  s
end

example usage:

puts f(File.read("map.txt"))

the code reuses the 'blot' method to calculate the path length.

variables/methods:

f(s): function to convert map string, returns new map with 'x's

ps(i): path size from map index i (where x = i % 6, y = i / 6)

s: input string, map lines separated by "\n"

z: copy of input string

b(s,i): 'blot' function: writes 'x' from map index i over paths

@v: 'visited' array

Attempt at more detailed explanation:

make a copy of the input string, which we use for finding the length of the path from any given point in the map.

z = s.dup

define a 'ps' (path length) anonymous function (lambda) which takes the map index i as an argument. it returns the length of the path from that point. it does this by calling the 'b' (blot) method to insert x's on a copy of the original map and then counting the number of x's in the returned string.

  ps = ->(i){b(z.dup,i).scan('x').size}

the following part iterates over each character in the map (index i, character s[i]). it calls the 'b' (blot) function on map position i if the path length from position i is greater than 2, and if it's not a space or newline character.

  (0...s.size).each { |i|
     b(s, i) if ![' ',"\n"].include?(s[i]) && ps.call(i) > 2
  }

the b (blot) function takes the map string and an index as argument. it initialises @v (visited array) and calls the b2 helper function.

def b(s,i)
  @v=[]
  b2(s,i,s[i])
end

the b2 function takes the map string, a map position (i), and a character in the current path (c). it calls itself recursively to replace connected sections of digits with the 'x' character. it returns the input string (this is so the ps function can call scan() on the return value).

this if statement is checking that the map position (i) given is within the bounds of the string (0...s.size) and that the character at s[i] is the same as the starting character. also @v[i] is checked to avoid infinite recursion.

if(0...s.size) === i && s[i] == c && !@v[i]

this is the bit that replaces the character at index (i) with the 'x' character. it also marks that index as visited.

@v[i] = s[i] = 'x'

this is where b2 calls itself recursively searching for the path. i+1 is one character to the right, i-1 is one character to the left, i+6 is one row down (5 digits + 1 newline = 6 characters), i-6 is one row up.

[1,-1,6,-6].each { |j| b2(s, i+j, c) }


问:
Print a bunch of uninteresting numbers!
An uninteresting number (which I totally didn't make up only for this challenge) is created like this:

Take a positive integer N

Create a new number O by adding the digits of N at the end of N

The final uninteresting number is O*N

For example for N=12:

O = 1212

O*N = 1212 * 12

Final number is 14544

Input

A positive integer N (N > 0) or your language's equivalent. You don't have to catch incorrect input.

Output

The corresponding uninteresting number.

Test cases

```<code>  1 -> 11
  2 -> 44
  3 -> 99
 10 -> 10100
174 -> 30306276
</code>```

Scoring

Shortest Code in Bytes wins.

答:
TI-BASIC, 22 or 24 bytes

```<code>Prompt X
X(X+X10^(1+int(log(X
</code>```

Or, 22 bytes stored as a Y-var (basically a function).

Title: Print a bunch of uninteresting numbers!

Body:
TI-BASIC, 22 or 24 bytes

Prompt X
X(X+X10^(1+int(log(X

Or, 22 bytes stored as a Y-var (basically a function).


问:
Latin square compression
A Latin square is a square that has no repeated symbols in the rows or columns:.

```<code>13420
21304
32041
04213
40132
</code>```

And as many Sudoku players know, you don't need all of the numbers to deduce the remaining numbers.

Your challenge is to compress a Latin square into as few bytes as possible.  You need to provide one or two program(s) that compresses/decompresses.

Various info:

The numbers used will always be 0..N-1, where N is the length of the square's edge, and N<=25

On decompression, the latin square must be identical to the input.

Your program(s) should be able to (de)compress any latin square (within the maximum square size), not just the ones I've provided.  Compression ratios should be similar as well.

You must actually run the compression and decompressor to obtain your score (No end-of-universe runtimes)

The test cases can be found on github.  Your score is total size of compressed test cases.

EDIT: As of 20:07 on July 7th, I updated the test cases (in order to fix a generation issue).  Please rerun your program on the new test cases.  Thanks Anders Kaseorg.

答:
Java, 2310 bytes

We convert each row of the square to a number representing which lexicographic permutation it is using factoradic numbers, also known as a factorial number system, which is useful for numbering permutations.

We write the square to a binary file where the first byte is the size of the square, and then each row has one byte for the number of bytes in the binary representation of a Java BigInteger, followed by the bytes of that BigInteger.

To reverse the process and decompress the square we read the size back and then each BigInteger, and use that number to generate each row of the square.

```<code>import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Latin {
    public static void main(String[] args) {
        if (args.length != 3) {
            System.out.println("java Latin {-c | -d} infile outfile");
        } else if (args[0].equals("-c")) {
            compress(args[1], args[2]);
        } else if (args[0].equals("-d")) {
            decompress(args[1], args[2]);
        } else {
            throw new IllegalArgumentException(
                "Invalid mode: " + args[0] + ", not -c or -d");
        }
    }

    public static void compress(String filename, String outname) {
        try (BufferedReader br = Files.newBufferedReader(Paths.get(filename))) {
            try (OutputStream os =
                    new BufferedOutputStream(new FileOutputStream(outname))) {
                String line = br.readLine();
                if (line == null) return;
                int size = line.split(",").length;
                if (size > 127) throw new ArithmeticException(
                    "Overflow: square too large");
                Permutor perm = new Permutor(size);
                os.write((byte) size); // write size of square

                do {
                    List<Integer> nums = Arrays.stream(line.split(","))
                        .map(Integer::new)
                        .collect(Collectors.toList());
                    byte[] bits = perm.which(nums).toByteArray();
                    os.write((byte) bits.length); // write length of bigint
                    os.write(bits); // write bits of bigint
                } while ((line = br.readLine()) != null);
            }
        } catch (IOException e) {
            System.out.println("Error compressing " + filename);
            e.printStackTrace();
        }
    }

    public static void decompress(String filename, String outname) {
        try (BufferedInputStream is =
                new BufferedInputStream(new FileInputStream(filename))) {
            try (BufferedWriter bw =
                    Files.newBufferedWriter(Paths.get(outname))) {
                int size = is.read(); // size of latin square
                Permutor perm = new Permutor(size);
                for (int i = 0; i < size; ++i) {
                    int num = is.read(); // number of bytes in bigint
                    if (num == -1) {
                        throw new IOException(
                            "Unexpected end of file reading " + filename);
                    }
                    byte[] buf = new byte[num];
                    int read = is.read(buf); // read bits of bigint into buf
                    if (read != num) {
                        throw new IOException(
                            "Unexpected end of file reading " + filename);
                    }
                    String row = perm.nth(new BigInteger(buf)).stream()
                        .map(Object::toString)
                        .collect(Collectors.joining(","));
                    bw.write(row);
                    bw.newLine();
                }
            }
        } catch (IOException e) {
            System.out.println("Error reading " + filename);
            e.printStackTrace();
        }
    }
}
</code>```

Permutor is adapted from a class I wrote a few years ago to work with permutations:

```<code>import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import java.math.BigInteger;
import static java.math.BigInteger.ZERO;
import static java.math.BigInteger.ONE;

public class Permutor {
    private final List<Integer> items;

    public Permutor(int n) {
        items = new ArrayList<>();
        for (int i = 0; i < n; ++i) items.add(i);
    }

    public BigInteger size() {
        return factorial(items.size());
    }

    private BigInteger factorial(int x) {
        BigInteger f = ONE;
        for (int i = 2; i <= x; ++i) {
            f = f.multiply(BigInteger.valueOf(i));
        }
        return f;
    }

    public List<Integer> nth(long n) {
        return nth(BigInteger.valueOf(n));
    }

    public List<Integer> nth(BigInteger n) {
        if (n.compareTo(size()) > 0) {
            throw new IllegalArgumentException("too high");
        }
        n = n.subtract(ONE);
        List<Integer> perm = new ArrayList<>(items);
        int offset = 0, size = perm.size() - 1;
        while (n.compareTo(ZERO) > 0) {
            BigInteger fact = factorial(size);
            BigInteger mult = n.divide(fact);
            n = n.subtract(mult.multiply(fact));
            int pos = mult.intValue();
            Integer t = perm.get(offset + pos);
            perm.remove((int) (offset + pos));
            perm.add(offset, t);
            --size;
            ++offset;
        }
        return perm;
    }

    public BigInteger which(List<Integer> perm) {
        BigInteger n = ONE;
        List<Integer> copy = new ArrayList<>(items);
        int size = copy.size() - 1;
        for (Integer t : perm) {
            int pos = copy.indexOf(t);
            if (pos < 0) throw new IllegalArgumentException("invalid");
            n = n.add(factorial(size).multiply(BigInteger.valueOf(pos)));
            copy.remove((int) pos);
            --size;
        }
        return n;
    }
}
</code>```

Usage:

With a Latin square in latin.txt, compress it:

```<code>java Latin -c latin.txt latin.compressed
</code>```

And decompress it:

```<code>java Latin -d latin.compressed latin.decompressed
</code>```

Title: Latin square compression

Body:
Java, 2310 bytes

We convert each row of the square to a number representing which lexicographic permutation it is using factoradic numbers, also known as a factorial number system, which is useful for numbering permutations.

We write the square to a binary file where the first byte is the size of the square, and then each row has one byte for the number of bytes in the binary representation of a Java BigInteger, followed by the bytes of that BigInteger.

To reverse the process and decompress the square we read the size back and then each BigInteger, and use that number to generate each row of the square.

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Latin {
    public static void main(String[] args) {
        if (args.length != 3) {
            System.out.println("java Latin {-c | -d} infile outfile");
        } else if (args[0].equals("-c")) {
            compress(args[1], args[2]);
        } else if (args[0].equals("-d")) {
            decompress(args[1], args[2]);
        } else {
            throw new IllegalArgumentException(
                "Invalid mode: " + args[0] + ", not -c or -d");
        }
    }

    public static void compress(String filename, String outname) {
        try (BufferedReader br = Files.newBufferedReader(Paths.get(filename))) {
            try (OutputStream os =
                    new BufferedOutputStream(new FileOutputStream(outname))) {
                String line = br.readLine();
                if (line == null) return;
                int size = line.split(",").length;
                if (size > 127) throw new ArithmeticException(
                    "Overflow: square too large");
                Permutor perm = new Permutor(size);
                os.write((byte) size); // write size of square

                do {
                    List<Integer> nums = Arrays.stream(line.split(","))
                        .map(Integer::new)
                        .collect(Collectors.toList());
                    byte[] bits = perm.which(nums).toByteArray();
                    os.write((byte) bits.length); // write length of bigint
                    os.write(bits); // write bits of bigint
                } while ((line = br.readLine()) != null);
            }
        } catch (IOException e) {
            System.out.println("Error compressing " + filename);
            e.printStackTrace();
        }
    }

    public static void decompress(String filename, String outname) {
        try (BufferedInputStream is =
                new BufferedInputStream(new FileInputStream(filename))) {
            try (BufferedWriter bw =
                    Files.newBufferedWriter(Paths.get(outname))) {
                int size = is.read(); // size of latin square
                Permutor perm = new Permutor(size);
                for (int i = 0; i < size; ++i) {
                    int num = is.read(); // number of bytes in bigint
                    if (num == -1) {
                        throw new IOException(
                            "Unexpected end of file reading " + filename);
                    }
                    byte[] buf = new byte[num];
                    int read = is.read(buf); // read bits of bigint into buf
                    if (read != num) {
                        throw new IOException(
                            "Unexpected end of file reading " + filename);
                    }
                    String row = perm.nth(new BigInteger(buf)).stream()
                        .map(Object::toString)
                        .collect(Collectors.joining(","));
                    bw.write(row);
                    bw.newLine();
                }
            }
        } catch (IOException e) {
            System.out.println("Error reading " + filename);
            e.printStackTrace();
        }
    }
}

Permutor is adapted from a class I wrote a few years ago to work with permutations:

import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import java.math.BigInteger;
import static java.math.BigInteger.ZERO;
import static java.math.BigInteger.ONE;

public class Permutor {
    private final List<Integer> items;

    public Permutor(int n) {
        items = new ArrayList<>();
        for (int i = 0; i < n; ++i) items.add(i);
    }

    public BigInteger size() {
        return factorial(items.size());
    }

    private BigInteger factorial(int x) {
        BigInteger f = ONE;
        for (int i = 2; i <= x; ++i) {
            f = f.multiply(BigInteger.valueOf(i));
        }
        return f;
    }

    public List<Integer> nth(long n) {
        return nth(BigInteger.valueOf(n));
    }

    public List<Integer> nth(BigInteger n) {
        if (n.compareTo(size()) > 0) {
            throw new IllegalArgumentException("too high");
        }
        n = n.subtract(ONE);
        List<Integer> perm = new ArrayList<>(items);
        int offset = 0, size = perm.size() - 1;
        while (n.compareTo(ZERO) > 0) {
            BigInteger fact = factorial(size);
            BigInteger mult = n.divide(fact);
            n = n.subtract(mult.multiply(fact));
            int pos = mult.intValue();
            Integer t = perm.get(offset + pos);
            perm.remove((int) (offset + pos));
            perm.add(offset, t);
            --size;
            ++offset;
        }
        return perm;
    }

    public BigInteger which(List<Integer> perm) {
        BigInteger n = ONE;
        List<Integer> copy = new ArrayList<>(items);
        int size = copy.size() - 1;
        for (Integer t : perm) {
            int pos = copy.indexOf(t);
            if (pos < 0) throw new IllegalArgumentException("invalid");
            n = n.add(factorial(size).multiply(BigInteger.valueOf(pos)));
            copy.remove((int) pos);
            --size;
        }
        return n;
    }
}

Usage:

With a Latin square in latin.txt, compress it:

java Latin -c latin.txt latin.compressed

And decompress it:

java Latin -d latin.compressed latin.decompressed


问:
Zeroes at the end of a factorial
Write a program or function that finds the number of zeroes at the end of n! in base 10, where n is an input number (in any desired format).

It can be assumed that n is a positive integer, meaning that n! is also an integer. There are no zeroes after a decimal point in n!. Also, it can be assumed that your programming language can handle the value of n and n!.

Test cases

```<code>1
==> 0

5
==> 1

100
==> 24

666
==> 165

2016
==> 502

1234567891011121314151617181920
==> 308641972752780328537904295461
</code>```

This is code golf. Standard rules apply. The shortest code in bytes wins.

答:
bc, 51 bytes

define f(x){if(x){return x/5+f(x/5)}else{return 0}}
```

Same tactic as in xnor and Cᴏɴᴏʀ O'Bʀɪᴇɴ's answers, but longer.

Title: Zeroes at the end of a factorial

Body:
bc, 51 bytes

define f(x){if(x){return x/5+f(x/5)}else{return 0}}

Same tactic as in xnor and Cᴏɴᴏʀ O'Bʀɪᴇɴ's answers, but longer.


答:
Erlang, 33 bytes

f(0)->0;f(N)->N div 5+f(N div 5).
```

<p>Same tactic as in xnor and Cᴏɴᴏʀ O'Bʀɪᴇɴ's answers.</p>

<p>Ungolfed:</p>

<pre class="lang-erlang prettyprint-override"><code>f(0) -> 0;
f(N) when N > 0 -> N div 5 + f(N div 5).
</code>```

Title: Zeroes at the end of a factorial

Body:
Write a program or function that finds the number of zeroes at the end of n! in base 10, where n is an input number (in any desired format).

It can be assumed that n is a positive integer, meaning that n! is also an integer. There are no zeroes after a decimal point in n!. Also, it can be assumed that your programming language can handle the value of n and n!.

Test cases

```<code>1
==> 0

5
==> 1

100
==> 24

666
==> 165

2016
==> 502

1234567891011121314151617181920
==> 308641972752780328537904295461
</code>```

This is code golf. Standard rules apply. The shortest code in bytes wins.

Body:
Erlang, 33 bytes

f(0)->0;f(N)->N div 5+f(N div 5).

Same tactic as in xnor and Cᴏɴᴏʀ O'Bʀɪᴇɴ's answers.

Ungolfed:

f(0) -> 0;
f(N) when N > 0 -> N div 5 + f(N div 5).


问:
Duplicate & switch case
The goal is, having taken a string as input, duplicate each latin letter and "toggle" its case (i.e. uppercase becomes lowercase and vice-versa).

Example inputs & outputs:

```<code>Input      Output
bad        bBaAdD
Nice       NniIcCeE
T e S t    Tt eE Ss tT
s E t      sS Ee tT
1!1!1st!   1!1!1sStT!
n00b       nN00bB
(e.g.)     (eE.gG.)
H3l|@!     Hh3lL|@!
</code>```

The input consists of printable ASCII symbols.

You shouldn't duplicate non-latin letters, numbers, special chars.

答:
Java 8, <s>105</s> <s>104</s> 80 bytes

a->{for(char c:a)System.out.print(c+(c>64&c<91|c>96&c<123?(char)(c^32)+"":""));}
```
<p><strong>Explanation:</strong></p>
<p>Try it here.</p>
<pre class="lang-java prettyprint-override"><code>a->{                          // Method with character-array parameter and no return-type
  for(char c:a)               //  For each character in the input:
    System.out.print(c        //   Print the current character
     +(c>64&c<91|c>96&c<123?  //   And if it's a letter:
       (char)(c^32)+""        //    Print the letter again with reversed case
      :                       //   Else:
       ""));}                 //    Print nothing more
</code>```

Title: Duplicate & switch case

Body:
Java 8, <s>105</s> <s>104</s> 80 bytes

a->{for(char c:a)System.out.print(c+(c>64&c<91|c>96&c<123?(char)(c^32)+"":""));}

Explanation:

Try it here.

a->{                          // Method with character-array parameter and no return-type
  for(char c:a)               //  For each character in the input:
    System.out.print(c        //   Print the current character
     +(c>64&c<91|c>96&c<123?  //   And if it's a letter:
       (char)(c^32)+""        //    Print the letter again with reversed case
      :                       //   Else:
       ""));}                 //    Print nothing more


答:
If I understand what you're asking for, this is what I'd add:

```<code>using std::cout;
cout<<q;
</code>```

The first line brings std::cout into the current name space so that we can use it without qualification. using namespace std; would have worked as well but is longer so I didn't use it.

The second line uses the limit of five letters (plus three symbols and no necessary white space beyond whatever the platform uses to denote end of line).

There may be something shorter, but I can't think of it at the moment.

Title: m3ph1st0s's programming puzzle 2 (C++): "Call hard!"

Body:
I am back with a brand new puzzle for C/C++ addicts. Following the feedback received on the 1st puzzle, this time I will try to make the requirements crystal clear and to provide a perfectly valid code.

Here is the problem.
Given the following code:

```<code>#include <iostream>

char message[6]="hello";

void print_hello_message() {
   std::cout << message;
}

int main() {
   char* q = &message[0];

   // insert your code here
}
</code>```

You are required to insert two more lines where the comment specifies in order to make the program print "hello" and nothing more, with the following restrictions:

the first line will NOT call any function, including cout

the second line will contain AT MOST 5 letters (and as many other symbols as you want)

the first line may contain new variable declarations but may not initialize them

the symbols # and / will not be used at all.

no logical operators will be used

The shortest code wins!

Body:
If I understand what you're asking for, this is what I'd add:

using std::cout;
cout<<q;

The first line brings std::cout into the current name space so that we can use it without qualification. using namespace std; would have worked as well but is longer so I didn't use it.

The second line uses the limit of five letters (plus three symbols and no necessary white space beyond whatever the platform uses to denote end of line).

There may be something shorter, but I can't think of it at the moment.


答:
Python 3, <s>238</s> <s>237</s> <s>200</s> <s>199</s> <s>192</s> 181 bytes

def f(a,i=0):F=lambda i,n,c:29>i>=0!=" "!=a[i]==c!=n and(a.__setitem__(i,n)or-~sum(F(i+j,n,c)for j in[-1,1,-6,6]));j=i+i//5;F(j,[a[j],"x"][2<F(j,1,a[j])],1);i>23or f(a,i+1);return a
```
<p>Defines a function <code>f(a)</code> that takes the input as an array of characters and returns the same array modified. (Arrays of characters are acceptable as strings by default.)</p>
<h3>Ungolfed with explanation</h3>
<p>The modified code is recursive, but works the same.</p>
<pre class="lang-python prettyprint-override"><code># The main function; fills all continuous nonempty areas of size >= 3 in array
# with x's. Both modifies and returns array.
def findpaths(array):
    # Fills a continuous area of curr_char in array with new_char, starting
    # from index. Returns the number of cells affected.
    def floodfill(index, new_char, curr_char):
        if (0 <= index < 29                   # Check that the position is in bounds
                and (index + 1) % 6 != 0      # Don't fill newlines
                and array[index] != " "       # Don't fill empty cells
                and array[index] == curr_char # Don't fill over other characters
                and curr_char != new_char):   # Don't fill already filled-in cells
            array[index] = new_char # Fill current position
            return (1 # Add neighboring cells' results, plus 1 for this cell
                    + floodfill(index + 1, new_char, curr_char)  # Next char
                    + floodfill(index - 1, new_char, curr_char)  # Previous char
                    + floodfill(index + 6, new_char, curr_char)  # Next line
                    + floodfill(index - 6, new_char, curr_char)) # Previous line
        return 0 # Nothing was filled. The golfed solution returns False here,
                 # but that's coerced to 0 when adding.

    for i in range(25): # Loop through the 25 cells
        i += i // 5 # Accommodate for newlines in input
        curr_char = array[i] # Get the cell's contents
        # Fill the area from the cell with dummies
        area_size = floodfill(i, 1, curr_char)
        # Convert dummies to "x" if area was large enough, back to original otherwise
        fill_char = "x" if 2 < area_size else curr_char
        floodfill(i, fill_char, 1)
    return array
</code>```

Title: Find the paths!

Body:
You must write a program or function.

The input is a 'map' of numbers. You can choose to take the map as either a string with new line characters (\n) or a 2D array of strings.

All maps are 5 characters by 5 characters, and the characters are always either digits greater than 0 or spaces.

Here is an example of a map:

```<code>12 45
11233
  233
    1
2 899
</code>```

Your task is to find the connected components in the map. A valid component is a series of at least three horizontally and/or vertically (not diagonally) connected identical digits (not spaces). You will then need to replace the characters of the valid connected components with xs and print or return that result.

So, the output for the above example would be:

```<code>x2 45
xx2xx
  2xx
    1
2 899
</code>```

Here's another test case (thanks to Martin Ender):

```<code>Input:
2   3
    4
 1  5
111 6
11  7

Output:
2   3
    4
 x  5
xxx 6
xx  7
</code>```

This is code golf so shortest code in bytes wins!

Body:
Python 3, <s>238</s> <s>237</s> <s>200</s> <s>199</s> <s>192</s> 181 bytes

def f(a,i=0):F=lambda i,n,c:29>i>=0!=" "!=a[i]==c!=n and(a.__setitem__(i,n)or-~sum(F(i+j,n,c)for j in[-1,1,-6,6]));j=i+i//5;F(j,[a[j],"x"][2<F(j,1,a[j])],1);i>23or f(a,i+1);return a

Defines a function f(a) that takes the input as an array of characters and returns the same array modified. (Arrays of characters are acceptable as strings by default.)

Ungolfed with explanation

The modified code is recursive, but works the same.

# The main function; fills all continuous nonempty areas of size >= 3 in array
# with x's. Both modifies and returns array.
def findpaths(array):
    # Fills a continuous area of curr_char in array with new_char, starting
    # from index. Returns the number of cells affected.
    def floodfill(index, new_char, curr_char):
        if (0 <= index < 29                   # Check that the position is in bounds
                and (index + 1) % 6 != 0      # Don't fill newlines
                and array[index] != " "       # Don't fill empty cells
                and array[index] == curr_char # Don't fill over other characters
                and curr_char != new_char):   # Don't fill already filled-in cells
            array[index] = new_char # Fill current position
            return (1 # Add neighboring cells' results, plus 1 for this cell
                    + floodfill(index + 1, new_char, curr_char)  # Next char
                    + floodfill(index - 1, new_char, curr_char)  # Previous char
                    + floodfill(index + 6, new_char, curr_char)  # Next line
                    + floodfill(index - 6, new_char, curr_char)) # Previous line
        return 0 # Nothing was filled. The golfed solution returns False here,
                 # but that's coerced to 0 when adding.

    for i in range(25): # Loop through the 25 cells
        i += i // 5 # Accommodate for newlines in input
        curr_char = array[i] # Get the cell's contents
        # Fill the area from the cell with dummies
        area_size = floodfill(i, 1, curr_char)
        # Convert dummies to "x" if area was large enough, back to original otherwise
        fill_char = "x" if 2 < area_size else curr_char
        floodfill(i, fill_char, 1)
    return array


问:
Post-determined Array Sorting
Input:

An array containing three integers: 0, 1 and 2 in any order (i.e. [2, 0, 1])

And a string of length >= 2 only containing alphabetic letters (both lower- and uppercase) and digits (i.e. a1B2c3)

Output:

Based on the array we sort and output the string.

How does this work?

The array indicates the order precedence of a-z, A-Z and 0-9, the first being 0; second being 1; and third being 2.

The individual characters of the string can then be ordered based on that.

Example:

Array: [2, 0, 1]

String: a1B2c3

Based on the array, we know our order precedence is 0-9a-zA-Z.

Based on that, we can convert and output the string: 123acB.

Challenge rules:

For the array you can choose to use 0-indexed or 1-indexed input, so [3, 1, 2] is also a valid input if you prefer to use 1-indexed arrays.

The string (both input and output) only contains valid characters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.

If your language doesn't support arrays (or if you choose to), you are free to use strings instead of arrays for the first parameter (i.e. 012, [0,1,2], etc.).

General rules:

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

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

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

Default Loopholes are forbidden.

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

Also, please add an explanation if necessary.

Test cases:

```<code>[2, 0, 1]  &  a1B2c3             ->   123acB
[2, 1, 0]  &  aAaA909UuHWw9gh2   ->   02999AAHUWaaghuw
[2, 1, 0]  &  6Bx43              ->   346Bx
[1, 0, 2]  &  jfjf33g            ->   ffgjj33
[0, 2, 1]  &  AbC13              ->   b13AC
[1, 2, 0]  &  Qfl0l              ->   Q0fll
[0, 1, 2]  &  9870abcABC         ->   abcABC0789
[0, 2, 1]  &  test123            ->   estt123
[2, 0, 1]  &  WHAT               ->   AHTW
[2, 0, 1]  &  WhAt               ->   htAW
[1, 0, 2]  &  102BACbac          ->   ABCabc012
</code>```

答:
JavaScript (ES6), 87 bytes

```<code>(a,s)=>a.map(n=>[...s].sort().join``.replace([/[^a-z]/g,/[^A-Z]/g,/\D/g][n],``)).join``
</code>```

If the input array gave the order, rather than the precedence, of the three ranges (this only makes a difference for [1, 2, 0] and [2, 1, 0] whose effects are swapped) then this would have worked for 80 bytes:

```<code>(a,s,o=c=>a[(c<'a')+(c<'A')])=>[...s].sort((a,b)=>o(a)-o(b)||(a>b)-(a<b)).join``
</code>```

I misread the question and still got 7 upvotes with this. Feel free to remove your upvotes and give them to @CharlieWynn instead, who came up with the best correction to my approach.

```<code>(a,s)=>a.map(n=>s.replace([/[^a-z]/g,/[^A-Z]/g,/\D/g][n],``)).join``
</code>```

Title: Post-determined Array Sorting

Body:
JavaScript (ES6), 87 bytes

(a,s)=>a.map(n=>[...s].sort().join``.replace([/[^a-z]/g,/[^A-Z]/g,/\D/g][n],``)).join``

If the input array gave the order, rather than the precedence, of the three ranges (this only makes a difference for [1, 2, 0] and [2, 1, 0] whose effects are swapped) then this would have worked for 80 bytes:

(a,s,o=c=>a[(c<'a')+(c<'A')])=>[...s].sort((a,b)=>o(a)-o(b)||(a>b)-(a<b)).join``

I misread the question and still got 7 upvotes with this. Feel free to remove your upvotes and give them to @CharlieWynn instead, who came up with the best correction to my approach.

(a,s)=>a.map(n=>s.replace([/[^a-z]/g,/[^A-Z]/g,/\D/g][n],``)).join``


答:
Pyth, <s>17</s> <s>16</s> 15 bytes

```<code>s@RSz@L[GrG1`UT
</code>```

Test suite.

```<code>       [          array literal containing...
        G           the alphabet (lowercase)
         rG1        the alphabet, converted to uppercase
            `UT     inspect-range-10, generating the range [0,10) and
                      stringifying it, resulting in a string that contains no
                      letters and all numbers (so equivalent to '0123456789' for
                      filtering)
                    this creates ['ab...z', 'AB...Z', '01...9']

     @L           map over first (implicit) input (the ordering array) and take
                   the nth element in this array for each item
                   this gives us ['01...9', 'ab...z', 'AB...Z']

   Sz             take another line of input as a string and sort it, and then...
 @R               map over intersection: filter the line of input over presence
                    in each element in the new array
                    this results in ['123', 'ac', 'B']

s                 concatenate all and implicitly output
</code>```

Thanks to @FryAmTheEggman for a byte and @Jakube for another!

Title: Post-determined Array Sorting

Body:
Input:

An array containing three integers: 0, 1 and 2 in any order (i.e. [2, 0, 1])

And a string of length >= 2 only containing alphabetic letters (both lower- and uppercase) and digits (i.e. a1B2c3)

Output:

Based on the array we sort and output the string.

How does this work?

The array indicates the order precedence of a-z, A-Z and 0-9, the first being 0; second being 1; and third being 2.

The individual characters of the string can then be ordered based on that.

Example:

Array: [2, 0, 1]

String: a1B2c3

Based on the array, we know our order precedence is 0-9a-zA-Z.

Based on that, we can convert and output the string: 123acB.

Challenge rules:

For the array you can choose to use 0-indexed or 1-indexed input, so [3, 1, 2] is also a valid input if you prefer to use 1-indexed arrays.

The string (both input and output) only contains valid characters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.

If your language doesn't support arrays (or if you choose to), you are free to use strings instead of arrays for the first parameter (i.e. 012, [0,1,2], etc.).

General rules:

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

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

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

Default Loopholes are forbidden.

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

Also, please add an explanation if necessary.

Test cases:

```<code>[2, 0, 1]  &  a1B2c3             ->   123acB
[2, 1, 0]  &  aAaA909UuHWw9gh2   ->   02999AAHUWaaghuw
[2, 1, 0]  &  6Bx43              ->   346Bx
[1, 0, 2]  &  jfjf33g            ->   ffgjj33
[0, 2, 1]  &  AbC13              ->   b13AC
[1, 2, 0]  &  Qfl0l              ->   Q0fll
[0, 1, 2]  &  9870abcABC         ->   abcABC0789
[0, 2, 1]  &  test123            ->   estt123
[2, 0, 1]  &  WHAT               ->   AHTW
[2, 0, 1]  &  WhAt               ->   htAW
[1, 0, 2]  &  102BACbac          ->   ABCabc012
</code>```

Body:
Pyth, <s>17</s> <s>16</s> 15 bytes

s@RSz@L[GrG1`UT

Test suite.

       [          array literal containing...
        G           the alphabet (lowercase)
         rG1        the alphabet, converted to uppercase
            `UT     inspect-range-10, generating the range [0,10) and
                      stringifying it, resulting in a string that contains no
                      letters and all numbers (so equivalent to '0123456789' for
                      filtering)
                    this creates ['ab...z', 'AB...Z', '01...9']

     @L           map over first (implicit) input (the ordering array) and take
                   the nth element in this array for each item
                   this gives us ['01...9', 'ab...z', 'AB...Z']

   Sz             take another line of input as a string and sort it, and then...
 @R               map over intersection: filter the line of input over presence
                    in each element in the new array
                    this results in ['123', 'ac', 'B']

s                 concatenate all and implicitly output

Thanks to @FryAmTheEggman for a byte and @Jakube for another!


问:
Cannonball Conundrum
Your task is to, with an input number p, find the smallest positive cannonball number of order p that is NOT 1.

Definition

A cannonball number (of order p) is a number which is both:

An p-gonal number (See this page).

and an p-gonal pyramid number.

The nth p-gonal pyramid number is the sum of the 1st to nth p-gonal numbers.

(e.g. 4th square pyramid number = 1 + 4 + 9 + 16 = 30)

The picture below represents the 4th square pyramid number, as a square pyramid.

For more info, visit this link.

The cannonball number of order 3, for example, is 10, because it is:

The fourth triangle number (1 + 2 + 3 + 4 = 10)

and the third triangular pyramid number. (1 + 3 + 6 = 10)

Formulas

NOTE: If you can find (or make) more useful formulae than my ones here, please post it here (or message me on the question chat thing).

If you're interested, the formula for the nth p-gonal number is:

And the nth p-gonal pyramid number is:

Specs

p is guaranteed to be larger than 2.

The program must check values for a solution for p up to (and including) 2^16. Your program may do anything if no solutions are found for p.

Only positive indices for n.

Test cases

3 outputs 10 (4th triangle number, 3rd triangle pyramid number)

4 outputs 4900 (70th square number, 24th square pyramid number)

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

Note: If you do post a solution, please include a description of how the code works.

Should I start a bounty for a solution which is better and doesn't use my formulae?

答:
C, 107 bytes

```<code>#define X(x)(1+p/2.0*x)*++x
c(p,m,n,a,b){m=n=a=b=1;p-=2;do if(a>b)b+=X(n);else a=X(m);while(a^b);return a;}
</code>```

Ungolfed with test parameters:

```<code>#include <stdio.h>

#define X(x)(1+p/2.0*x)*++x
int c(int p)
{
    int m = 1, n = 1, a = 1, b = 1;
    p -= 2;
    do
        if(b < X(m))
            b += X(n);
        else
            a = X(m);
    while(a != b);
    return a;
}

int main()
{
    printf("%d\n", c(3));
    printf("%d\n", c(4));
}
</code>```

This uses the fact that the n-th p-gonal number can be defined as n(1+(p-2)(n-1)/2) and the pyramid number is the sum of the aforementioned numbers.

I think it can be further golfed, given that it's not really necessary for variable a to be saved.

Title: Cannonball Conundrum

Body:
C, 107 bytes

#define X(x)(1+p/2.0*x)*++x
c(p,m,n,a,b){m=n=a=b=1;p-=2;do if(a>b)b+=X(n);else a=X(m);while(a^b);return a;}

Ungolfed with test parameters:

#include <stdio.h>

#define X(x)(1+p/2.0*x)*++x
int c(int p)
{
    int m = 1, n = 1, a = 1, b = 1;
    p -= 2;
    do
        if(b < X(m))
            b += X(n);
        else
            a = X(m);
    while(a != b);
    return a;
}

int main()
{
    printf("%d\n", c(3));
    printf("%d\n", c(4));
}

This uses the fact that the n-th p-gonal number can be defined as n(1+(p-2)(n-1)/2) and the pyramid number is the sum of the aforementioned numbers.

I think it can be further golfed, given that it's not really necessary for variable a to be saved.


答:
Ruby with Shoes, <s>150</s> 149 characters

Shoes.app(width:100,height:72){background'0048e0'
stroke fill'fff'
rect 28,0,15,72
rect 0,28,99,15
stroke fill'd72828'
rect 32,0,7,72
rect 0,32,99,7}
```

Thanks to:

Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ for suggesting to use hex code for white (-1 character)

Sample output:

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:
Ruby with Shoes, <s>150</s> 149 characters

Shoes.app(width:100,height:72){background'0048e0'
stroke fill'fff'
rect 28,0,15,72
rect 0,28,99,15
stroke fill'd72828'
rect 32,0,7,72
rect 0,32,99,7}

Thanks to:

Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ for suggesting to use hex code for white (-1 character)

Sample output:


答:
KV(lang), 730 B :D

Not a competing answer, rather showing a language Kivy uses to make designing its widgets easier. The language requires indentation and newlines, therefore I'm forced to leave it in this shape. Kivy also takes rgb(a) as a color input, so I need to convert it and although there's a built-in, it's surely not suitable for golfing. :D

I'm traveling and with Kivy I'm able to code even on android. + its code is already crossplatform in I think 9/10 cases. ^^

```<code>#:import h kivy.utils.rgba
<F>:
    canvas:
        Color:
            rgb: h('#d72828')
        Rectangle:
            size: [100,72]
        Color:
            rgb: h('#ffffff')
        Rectangle:
            pos: [40,0]
            size: [60,32]
        Rectangle:
            pos: [40,40]
            size: [60,32]
        Rectangle:
            pos: [0,40]
            size: [32,32]
        Rectangle:
            size: [32,32]
        Color:
            rgb: h('#0048e0')
        Rectangle:
            pos: [44,0]
            size: [56,28]
        Rectangle:
            pos: [44,44]
            size: [56,28]
        Rectangle:
            pos: [0,44]
            size: [28,28]
        Rectangle:
            size: [28,28]
</code>```

To run it you need to install Kivy and either save it as a .kv file, or have something like this in Python to parse it as a string:

```<code>from kivy.lang import Builder
from kivy.base import runTouchApp
from kivy.uix.boxlayout import BoxLayout
Builder.load_string('''KVstring''')
class F(BoxLayout):pass
runTouchApp(F())
</code>```

Title: Draw the national flag of Iceland

Body:
KV(lang), 730 B :D

Not a competing answer, rather showing a language Kivy uses to make designing its widgets easier. The language requires indentation and newlines, therefore I'm forced to leave it in this shape. Kivy also takes rgb(a) as a color input, so I need to convert it and although there's a built-in, it's surely not suitable for golfing. :D

I'm traveling and with Kivy I'm able to code even on android. + its code is already crossplatform in I think 9/10 cases. ^^

#:import h kivy.utils.rgba
<F>:
    canvas:
        Color:
            rgb: h('#d72828')
        Rectangle:
            size: [100,72]
        Color:
            rgb: h('#ffffff')
        Rectangle:
            pos: [40,0]
            size: [60,32]
        Rectangle:
            pos: [40,40]
            size: [60,32]
        Rectangle:
            pos: [0,40]
            size: [32,32]
        Rectangle:
            size: [32,32]
        Color:
            rgb: h('#0048e0')
        Rectangle:
            pos: [44,0]
            size: [56,28]
        Rectangle:
            pos: [44,44]
            size: [56,28]
        Rectangle:
            pos: [0,44]
            size: [28,28]
        Rectangle:
            size: [28,28]

To run it you need to install Kivy and either save it as a .kv file, or have something like this in Python to parse it as a string:

from kivy.lang import Builder
from kivy.base import runTouchApp
from kivy.uix.boxlayout import BoxLayout
Builder.load_string('''KVstring''')
class F(BoxLayout):pass
runTouchApp(F())


答:
C++, 124 bytes

```<code>#include<algorithm>
int m(int*a,int*b,int n){std::sort(a,a+n);std::sort(b,b+n);int r=0;while(--n>=0)r+=a[n]**b++;return r;}
</code>```

ungolfed:

```<code>#include<algorithm>
int m(int*a,int*b,int n){
 std::sort(a,a+n);
 std::sort(b,b+n);
 int r=0;
 while(--n>=0)
  r+=a[n]*(*b++);
return r;
}
</code>```

At first i used std::greater<int>() for the sort in b but just reversing the order in the summation is easier.

Title: Minimum Scalar Product

Body:
Minimum Scalar Product

The inspiration for this code golf problem is from Google's code jam competition. The premise behind the problem is, given the input of two vectors of varying lengths, find the minimum possible scalar. A scalar can be found using the following formula:

```<code>x1 * y1 + x2 * y2 + ... + xn * yn
</code>```

The problem, however, is that multiple values for the scalar can be found depending on the order of the numerals in the input case (seen below). Your goal is to determine the minimum possible scalar integer solution by plugging in the input case numbers into the equation and solving for it. You may use every number in the input only once, and must use all of the numbers.

Allow me to provide an example with the following vectors.

Input

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

Output

```<code>-25
</code>```

The first integer on the line represents the number of numbers, n, in each vector. In this case, we have three numbers in each vector.

The number n may vary with each test case, but there will always be two vectors.

In the example input, the minimum scalar product would be -25.

```<code>(-5 * 4) + (1 * 1) + (3 * -2) = 25
</code>```

Rules

You may only use each integer in both vectors once.

You must use all integers in the vectors.

Your output must only include the final product

I'll select the solution with the least amount of code, which follows all of the specifications listed above, in any language!

 Hint: You don't need to brute force this problem, unless it makes your code shorter. There is a specific method involved in finding the minimum spanning scalar :).

Body:
C++, 124 bytes

#include<algorithm>
int m(int*a,int*b,int n){std::sort(a,a+n);std::sort(b,b+n);int r=0;while(--n>=0)r+=a[n]**b++;return r;}

ungolfed:

#include<algorithm>
int m(int*a,int*b,int n){
 std::sort(a,a+n);
 std::sort(b,b+n);
 int r=0;
 while(--n>=0)
  r+=a[n]*(*b++);
return r;
}

At first i used std::greater<int>() for the sort in b but just reversing the order in the summation is easier.


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

答:
TSQL(sqlserver 2012+), 276 bytes

Golfed:

```<code>DECLARE @i VARCHAR(99)=
'xXXXxxx111*'+CHAR(13)+CHAR(10)+
'**xxx11*xxx'

,@t BIT=0,@c INT=1,@ INT=1WHILE @<LEN(@i)/2SELECT @t-=IIF(a like'[1*]'or'xx'=a+b,0,1),@c+=IIF(a='*'or'xx'=a+b,1,0),@+=IIF(a='x'and'x'>b,0,1)FROM(SELECT SUBSTRING(d,@t*c+@,1)a,SUBSTRING(d,(1-@t)*c+@,1)b FROM(SELECT LEN(@i)/2+1c,REPLACE(@i,'X','q'COLLATE thai_bin)d)x)x PRINT @c
</code>```

Ungolfed:

```<code>DECLARE @i VARCHAR(99)=
'xXXXxxx111*'+CHAR(13)+CHAR(10)+
'**xxx11*xxx'

,@t BIT=0,@c INT=1,@ INT=1
WHILE @<LEN(@i)/2
  SELECT
    @t-=IIF(a like'[1*]'or'xx'=a+b,0,1),
    @c+=IIF(a='*'or'xx'=a+b,1,0),
    @ +=IIF(a='x'and'x'>b,0,1)
  FROM
    (
      SELECT
        SUBSTRING(d,@t*c+@,1)a,
        SUBSTRING(d,(1-@t)*c+@,1)b
      FROM
        (SELECT LEN(@i)/2+1c,REPLACE(@i,'X','q'COLLATE thai_bin)d)x
    )x

PRINT @c
</code>```

Fiddle

Title: Walk the labyrinth

Body:
TSQL(sqlserver 2012+), 276 bytes

Golfed:

DECLARE @i VARCHAR(99)=
'xXXXxxx111*'+CHAR(13)+CHAR(10)+
'**xxx11*xxx'

,@t BIT=0,@c INT=1,@ INT=1WHILE @<LEN(@i)/2SELECT @t-=IIF(a like'[1*]'or'xx'=a+b,0,1),@c+=IIF(a='*'or'xx'=a+b,1,0),@+=IIF(a='x'and'x'>b,0,1)FROM(SELECT SUBSTRING(d,@t*c+@,1)a,SUBSTRING(d,(1-@t)*c+@,1)b FROM(SELECT LEN(@i)/2+1c,REPLACE(@i,'X','q'COLLATE thai_bin)d)x)x PRINT @c

Ungolfed:

DECLARE @i VARCHAR(99)=
'xXXXxxx111*'+CHAR(13)+CHAR(10)+
'**xxx11*xxx'

,@t BIT=0,@c INT=1,@ INT=1
WHILE @<LEN(@i)/2
  SELECT
    @t-=IIF(a like'[1*]'or'xx'=a+b,0,1),
    @c+=IIF(a='*'or'xx'=a+b,1,0),
    @ +=IIF(a='x'and'x'>b,0,1)
  FROM
    (
      SELECT
        SUBSTRING(d,@t*c+@,1)a,
        SUBSTRING(d,(1-@t)*c+@,1)b
      FROM
        (SELECT LEN(@i)/2+1c,REPLACE(@i,'X','q'COLLATE thai_bin)d)x
    )x

PRINT @c

Fiddle


问:
Compute the CRC32 table at compile-time
The reference implementation of CRC32 computes a lookup table at runtime:

```<code>/* Table of CRCs of all 8-bit messages. */
unsigned long crc_table[256];

/* Flag: has the table been computed? Initially false. */
int crc_table_computed = 0;

/* Make the table for a fast CRC. */
void make_crc_table(void)
{
    unsigned long c;

    int n, k;
    for (n = 0; n < 256; n++) {
        c = (unsigned long) n;
        for (k = 0; k < 8; k++) {
            if (c & 1) {
                c = 0xedb88320L ^ (c >> 1);
            } else {
                c = c >> 1;
            }
        }
        crc_table[n] = c;
    }
    crc_table_computed = 1;
}
</code>```

Can you compute the table at compile-time, thus getting rid of the function and the status flag?

答:
C/C++, 306 295 bytes

```<code>#define C(c)((c)>>1^((c)&1?0xEDB88320L:0))
#define K(c)(C(C(C(C(C(C(C(C(c))))))))),
#define F(h,l)K((h)|(l+0))K((h)|(l+1))K((h)|(l+2))K((h)|(l+3))
#define R(h)F(h<<4,0)F(h<<4,4)F(h<<4,8)F(h<<4,12)
unsigned long crc_table[]={R(0)R(1)R(2)R(3)R(4)R(5)R(6)R(7)R(8)R(9)R(10)R(11)R(12)R(13)R(14)R(15)};
</code>```

Working in reverse, we wind up with an unsigned long array named crc_table. We can omit the size of the array as the macros will ensure there are exactly 256 elements in the array. We initialize the array with 16 'rows' of data by using 16 invocations of the macro R.

Each invocation of R expands into four fragments (macro F) of four constants (macro K) for a total of 16 'columns' of data.

The macro K is the unrolled loop indexed by k in the code from the original question. It updates the value c eight times by invoking the macro C.

This preprocessor based solution uses quite a bit of memory during macro expansion. I tried to make it a little shorter by having an extra level of macro expansion and my compiler puked. The code above compiles (slowly) with both Visual C++ 2012 and g++ 4.5.3 under Cygwin (Windows 7 64 bit 8GB RAM).

Edit:

The fragment above is 295 bytes including white space. After expanding all of the macros except for C it grows to 9,918 bytes. As each level of C macro is expanded the size grows quickly:

25,182

54,174

109,086

212,766

407,838

773,406

1,455,390

2,721,054

So by the time all the macros have been expanded, that little 295 byte file expands into over 2.7 megabytes of code that must be compiled to generate the original 1024 byte array (assuming 32 bit unsigned long values)!

Another edit:

I modified the C macro based on a macro from another answer to squeeze an extra 11 bytes out, and greatly reduced the full expanded macro size. While 2.7 MB isn't as bad as 54 MB (the previous final size of all macro expansion), it is still significant.

Title: Compute the CRC32 table at compile-time

Body:
C/C++, 306 295 bytes

#define C(c)((c)>>1^((c)&1?0xEDB88320L:0))
#define K(c)(C(C(C(C(C(C(C(C(c))))))))),
#define F(h,l)K((h)|(l+0))K((h)|(l+1))K((h)|(l+2))K((h)|(l+3))
#define R(h)F(h<<4,0)F(h<<4,4)F(h<<4,8)F(h<<4,12)
unsigned long crc_table[]={R(0)R(1)R(2)R(3)R(4)R(5)R(6)R(7)R(8)R(9)R(10)R(11)R(12)R(13)R(14)R(15)};

Working in reverse, we wind up with an unsigned long array named crc_table. We can omit the size of the array as the macros will ensure there are exactly 256 elements in the array. We initialize the array with 16 'rows' of data by using 16 invocations of the macro R.

Each invocation of R expands into four fragments (macro F) of four constants (macro K) for a total of 16 'columns' of data.

The macro K is the unrolled loop indexed by k in the code from the original question. It updates the value c eight times by invoking the macro C.

This preprocessor based solution uses quite a bit of memory during macro expansion. I tried to make it a little shorter by having an extra level of macro expansion and my compiler puked. The code above compiles (slowly) with both Visual C++ 2012 and g++ 4.5.3 under Cygwin (Windows 7 64 bit 8GB RAM).

Edit:

The fragment above is 295 bytes including white space. After expanding all of the macros except for C it grows to 9,918 bytes. As each level of C macro is expanded the size grows quickly:

25,182

54,174

109,086

212,766

407,838

773,406

1,455,390

2,721,054

So by the time all the macros have been expanded, that little 295 byte file expands into over 2.7 megabytes of code that must be compiled to generate the original 1024 byte array (assuming 32 bit unsigned long values)!

Another edit:

I modified the C macro based on a macro from another answer to squeeze an extra 11 bytes out, and greatly reduced the full expanded macro size. While 2.7 MB isn't as bad as 54 MB (the previous final size of all macro expansion), it is still significant.


答:
APLX, 19 bytes

```<code>s[(∊(⎕a⎕A⎕D)[a])⍋s]
</code>```

⎕a⎕A⎕D lower upper digits

(…)[a] reorder according to array a

∊ flatten

(…)⍋s according to that "alphabet", give the indices that would sort string s

s[…] use that to reorder s

Title: Post-determined Array Sorting

Body:
APLX, 19 bytes

s[(∊(⎕a⎕A⎕D)[a])⍋s]

⎕a⎕A⎕D lower upper digits

(…)[a] reorder according to array a

∊ flatten

(…)⍋s according to that "alphabet", give the indices that would sort string s

s[…] use that to reorder s


问:
The Lucas-nacci Numbers

Background

Most everyone is familiar with the Fibonacci numbers \$F(n)\$:

\$0, 1, 1, 2, 3, 5, 8, 13, 21, ...\$

These are formed by the recursion function \$F(n) = F(n-1) + F(n-2)\$ with \$F(0)=0\$ and \$F(1)=1\$. A000045

A closely related sequence is the Lucas numbers \$L(m)\$:

\$2, 1, 3, 4, 7, 11, 18, 29, ...\$

These are formed by the recursion function \$L(m) = L(m-1) + L(m-2)\$ with \$L(0)=2\$ and \$L(1)=1\$. A000032

We can alternate between the two sequences based on even/odd indices, with the construction

$$A(x) = \begin{cases}
F(x) & x \equiv 0 \pmod 2 \\
L(x) & x \equiv 1 \pmod 2 \\
\end{cases}$$

For example, \$A(4)\$ is equal to \$F(4)\$ since \$4 \bmod 2 \equiv 0\$. We'll call this sequence the Lucas-nacci Numbers, \$A(x)\$:

0, 1, 1, 4, 3, 11, 8, 29, 21, 76 ...

This can be formed by the recursion function \$A(x) = 3A(x-2) - A(x-4)\$ with \$A(0)=0, A(1)=1, A(2)=1\$, and \$A(3)=4\$. A005013

Challenge

Given input \$n\$, output the sequence of \$n+1\$ numbers up to and including \$A(n)\$ as described above. Fewest bytes (or byte-equivalents, such as for LabVIEW, as determined individually on Meta) wins.

Input

A single non-negative integer \$n\$.

Output

A list of numbers that correspond to the subsequence of Lucas-nacci numbers from \$A(0)\$ to \$A(n)\$. The list must be in sequential order as described above.

Rules

Standard code-golf rules and loophole restrictions apply.

Standard input/output rules apply.

Input number can be in any suitable format: unary or decimal, read from STDIN, function or command-line argument, etc. - your choice.

Output can be printed to STDOUT or returned as a result of the function call. If printed, suitable delimiters to differentiate the numbers must be included (space-separated, comma-separated, etc.).

Additionally, if output to STDOUT, surrounding whitespace, trailing newline, etc. are all optional.

If the input is a non-integer or a negative integer, the program can do anything or nothing, as behavior is undefined.

Examples

```<code>Input -> Output
0 -> 0
5 -> 0, 1, 1, 4, 3, 11
18 -> 0, 1, 1, 4, 3, 11, 8, 29, 21, 76, 55, 199, 144, 521, 377, 1364, 987, 3571, 2584
</code>```

答:
C++ Template Meta Programming, 130 bytes

template<int X>struct L{enum{v=3*L<X-2>::v-L<X-4>::v};};
#define D(X,A) template<>struct L<X>{enum{v=A};};
D(0,0)D(1,1)D(2,1)D(3,4)
```
<p>Recursive definitions somehow cry for C++TMP, usage:</p>
```L<x>::v
```

with x being the A(x) you like.

ContentLicense: CC BY-SA 4.0

Title: The Lucas-nacci Numbers

Body:
C++ Template Meta Programming, 130 bytes

template<int X>struct L{enum{v=3*L<X-2>::v-L<X-4>::v};};
#define D(X,A) template<>struct L<X>{enum{v=A};};
D(0,0)D(1,1)D(2,1)D(3,4)

Recursive definitions somehow cry for C++TMP, usage:

L<x>::v

with x being the A(x) you like.


答:
Dyalog APL, 22 bytes

```<code>s[s⍋⍨∊(819⌶⎕A)⎕A⎕D[a]]
</code>```

(819⌶⎕A) fold the uppercase alphabet to lowercase

(…)⎕A⎕D[a] lower upper digits reordered according to array a

∊ flatten

s⍋⍨ for string s, get the indices that would sort s according to that "alphabet"

s[…] use that to reorder s

Title: Post-determined Array Sorting

Body:
Dyalog APL, 22 bytes

s[s⍋⍨∊(819⌶⎕A)⎕A⎕D[a]]

(819⌶⎕A) fold the uppercase alphabet to lowercase

(…)⎕A⎕D[a] lower upper digits reordered according to array a

∊ flatten

s⍋⍨ for string s, get the indices that would sort s according to that "alphabet"

s[…] use that to reorder s


问:
Showcase of Languages

Notes

This thread is open and unlocked only because the community decided to make an exception. Please do not use this question as evidence that you can ask similar questions here. Please do not create additional showcase questions.

This is no longer a popularity-contest, nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes.

This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible.

How this works

All answers should include the name of the programming language at the top of the post, prefixed by a #.

Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language.

Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions.

The snippets do not need to be related. In fact, snippets that are too related may be redundant.

Since this is not a contest, all programming languages are welcome, whenever they were created.

Answers that contain more than a handful of code snippets should use a Stack Snippet to collapse everything except the factoid and one of the snippets.

Whenever possible, there should be only one answer per programming language. This is a community wiki, so feel free to add snippets to any answer, even if you haven't created it yourself. There is a Stack Snippet for compressing posts, which should mitigate the effect of the 30,000 character limit.

Answers that predate these guidelines should be edited. Please help updating them as needed.

Current answers, sorted alphabetically by language name

$.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/44680/answers?site=codegolf&filter=withbody",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('
' + temp.innerText || temp.textContent + '');}}})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="http://codegolf.stackexchange.com"><ul id="list"></ul></code>```

答:
Your Mom

Factoid

Your Mom is a stack-based golfing language created because of a mbomb007's chat message on TNB:

I think someone should create a language called "Your Mom", just so that during an argument over which language is a better one, they can interject that "Your mom is a better language"

Source

Since Your Mom use Unicode, the length of the snippets are in characters, not bytes

Length 1

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

+ pop two values and return their sum. Since there is nothing on the stack, the two values are read from stdin.

Length 2

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

Define a empty function. ) is not needed since it's the end of the program.

Length 3

```<code>#II
</code>```

# push a zero, I pop the last value, multiply it by 24 and add 18, because Your Mom use base 24. The state of the stack at the end is [ 450 ]

Length 4

```<code>¥()@
</code>```

This snippet create a infinite loop.

¥ push 1 to the stack, () define a empty function and @ pop a function and call it while the element on the top of the stack is true (but don't pop it)

Length 5

```<code>çç#,.
</code>```

This snippet create 2 array (ç), push 0 in the last array (,) and concatenate the two arrays (.)

Length 6

```<code>çÐ,€²Ç
</code>```

This snippet create a array, push to it the user input (Ð), define a 1 character function that process the sqare of it's input (€²), and map it to the array.

Length 7

```<code>Ð(:_⊟)@
</code>```

This snippet read the user input and print it, and decrement it while it's not 0

Length 8

```<code>##21®€²Ç
</code>```

This snippet create a range from 0 to 20, create a one character function that square it's argument, and map on the range.

Title: Showcase of Languages

Body:
Your Mom

Factoid

Your Mom is a stack-based golfing language created because of a mbomb007's chat message on TNB:

I think someone should create a language called "Your Mom", just so that during an argument over which language is a better one, they can interject that "Your mom is a better language"

Source

Since Your Mom use Unicode, the length of the snippets are in characters, not bytes

Length 1

+

+ pop two values and return their sum. Since there is nothing on the stack, the two values are read from stdin.

Length 2

()

Define a empty function. ) is not needed since it's the end of the program.

Length 3

#II

# push a zero, I pop the last value, multiply it by 24 and add 18, because Your Mom use base 24. The state of the stack at the end is [ 450 ]

Length 4

¥()@

This snippet create a infinite loop.

¥ push 1 to the stack, () define a empty function and @ pop a function and call it while the element on the top of the stack is true (but don't pop it)

Length 5

çç#,.

This snippet create 2 array (ç), push 0 in the last array (,) and concatenate the two arrays (.)

Length 6

çÐ,€²Ç

This snippet create a array, push to it the user input (Ð), define a 1 character function that process the sqare of it's input (€²), and map it to the array.

Length 7

Ð(:_⊟)@

This snippet read the user input and print it, and decrement it while it's not 0

Length 8

##21®€²Ç

This snippet create a range from 0 to 20, create a one character function that square it's argument, and map on the range.


答:
05AB1E, <s>15</s> <s>14</s> 12 bytes

Code:

```<code>v²žK26ôyèÃ{?
</code>```

Explanation:

```<code>v             # For each in the input array.
  žK          #   Push a-zA-Z0-9.
    26ô       #   Split into pieces of 26.
       yè     #   Get the element-th element of the array.
 ²       Ã    #   Keep the characters of that element from the second input.
          {?  #   Sort pop and print without a newline.
</code>```

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

Title: Post-determined Array Sorting

Body:
05AB1E, <s>15</s> <s>14</s> 12 bytes

Code:

v²žK26ôyèÃ{?

Explanation:

v             # For each in the input array.
  žK          #   Push a-zA-Z0-9.
    26ô       #   Split into pieces of 26.
       yè     #   Get the element-th element of the array.
 ²       Ã    #   Keep the characters of that element from the second input.
          {?  #   Sort pop and print without a newline.

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