问:
Golf you a quine for great good!
Using your language of choice, golf a quine.

A quine is a non-empty computer program which takes no input and produces a copy of its own source code as its only output.

No cheating -- that means that you can't just read the source file and print it. Also, in many languages, an empty file is also a quine: that isn't considered a legit quine either.

No error quines -- there is already a separate challenge for error quines.

Points for:

Smallest code (in bytes)

Most obfuscated/obscure solution

Using esoteric/obscure languages

Successfully using languages that are difficult to golf in

The following Stack Snippet can be used to get a quick view of the current score in each language, and thus to know which languages have existing answers and what sort of target you have to beat:

var QUESTION_ID=69;
var OVERRIDE_USER=98;

var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,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:!0,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=!1;comment_page=1;getComments()}})}
function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,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=(function(){var headerTag=String.raw `h\d`
var score=String.raw `\-?\d+\.?\d*`
var normalText=String.raw `[^\n<>]*`
var strikethrough=String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>`
var noDigitText=String.raw `[^\n\d<>]*`
var htmlTag=String.raw `<[^\n<>]+>`
return new RegExp(String.raw `<${headerTag}>`+String.raw `\s*([^\n,]*[^\s,]),.*?`+String.raw `(${score})`+String.raw `(?=`+String.raw `${noDigitText}`+String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+String.raw `</${headerTag}>`+String.raw `)`)})();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;lang=jQuery(''+a.language+'').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;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

  <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654">

Winners by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

 ```

答:
R, 73 bytes (incl. tabs and newlines)

```<code>(f=function()
{
    cat("(f=function()\n")
    print(body(f))
    cat(")()")
}
)()
</code>```

Shorter, less interesting quines are possible: function()1 is 11 bytes. + (1 byte) is an arguable quine, since the command prompt for an unfinished line is a plus sign by default, and + on its own counts as an unfinished line.

Title: Golf you a quine for great good!

Body:
R, 73 bytes (incl. tabs and newlines)

(f=function()
{
    cat("(f=function()\n")
    print(body(f))
    cat(")()")
}
)()

Shorter, less interesting quines are possible: function()1 is 11 bytes. + (1 byte) is an arguable quine, since the command prompt for an unfinished line is a plus sign by default, and + on its own counts as an unfinished line.


问:
Creating a Crossed Square

Creating a Crossed Square

You are to take input of an integer of one or more and output a square made of any printable character of your choice with a diagonal cross through the centre.

The general idea is for the output to be a hollow square that has a diagonal cross through it.:

```<code>Input: 7
Output:
*******
*#   #*
* # # *
*  #  *
* # # *
*#   #*
*******
</code>```

In the above example the '*'s represent the outer box and the '#'s represent the diagonal cross.

Note that the above example uses two different characters so that it is easier to see what the output looks like, your program should use one character only.

Input

An integer of 1 or more, it is guaranteed to be odd.

Output

A square that is made up of a character of your choice with a cross through the middle.

The cross must be diagonal

The square may be output via the function or written to output

Trailing newlines are okay

Can output as a graphic, diagram or image if you wish too

Examples

```<code>Input: 1
Output:
*

Input: 3
Output:
***
***
***

Input: 5
Output:
*****
** **
* * *
** **
*****

Input: 7
Output:
*******
**   **
* * * *
*  *  *
* * * *
**   **
*******
</code>```

Specs

Functions or full programs are allowed

You can get input by your preferred means

Standard loopholes are disallowed

Programs must work without any additional statements i.e. usings in C#, they must be included in the entry

You can output from a function or print the result

This is code golf so the shortest solution wins.

答:
Scala, 141 137 bytes

```<code>val s=args(0).toInt-1;val t=0 to s;print(t.map{x=>t.map{y=>if(x==0||x==s||y==0||y==s||x==y||x==s-y)"*" else " "}.mkString+"\n"}.mkString)
</code>```

Run:

$ scala cross.scala 10

Technically I could remove the print stuff and go to something like

```<code>def c(n:Int)={val (s,t)=(n-1,0 to n-1);t.map{x=>t.map{y=>if(x==0||x==s||y==0||y==s||x==y||x==s-y)"*" else " "}.mkString+"\n"}.mkString}
</code>```

This would make it 135 or 121 bytes depending on whether you count the function syntax stuff.

Readable version:

```<code>def cross(n: Int) = {
   // Declares both s and t as variables with tuple expansion
   // s is the zero-based size and t is a range from 0 to s
   val (s,t) = (n-1, 0 to n-1)

   // Maps all rows by mapping the columns to a star or a space
   t.map { x =>
      t.map { y =>
        if (x == 0 || x == s || y == 0 || y == s || x == y || x == s-y) "*"
        else " "
      }.mkString+"\n" // Concatenate the stars and spaces and add a newline
   }.mkString         // Concatenate the created strings
 }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Creating a Crossed Square

Body:
Scala, 141 137 bytes

val s=args(0).toInt-1;val t=0 to s;print(t.map{x=>t.map{y=>if(x==0||x==s||y==0||y==s||x==y||x==s-y)"*" else " "}.mkString+"\n"}.mkString)

Run:

$ scala cross.scala 10

Technically I could remove the print stuff and go to something like

def c(n:Int)={val (s,t)=(n-1,0 to n-1);t.map{x=>t.map{y=>if(x==0||x==s||y==0||y==s||x==y||x==s-y)"*" else " "}.mkString+"\n"}.mkString}

This would make it 135 or 121 bytes depending on whether you count the function syntax stuff.

Readable version:

def cross(n: Int) = {
   // Declares both s and t as variables with tuple expansion
   // s is the zero-based size and t is a range from 0 to s
   val (s,t) = (n-1, 0 to n-1)

   // Maps all rows by mapping the columns to a star or a space
   t.map { x =>
      t.map { y =>
        if (x == 0 || x == s || y == 0 || y == s || x == y || x == s-y) "*"
        else " "
      }.mkString+"\n" // Concatenate the stars and spaces and add a newline
   }.mkString         // Concatenate the created strings
 }


问:
Highlight the Bounding Box, Part I: Cartesian Grid
You're given a rectangular grid of the characters . and #, like this:

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

Your task is to fill the entire axis-aligned bounding box of the # with further #:

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

The axis-aligned bounding box is the smallest rectangle which contains all the #.

Want more? Try Part II!

Rules

You may use any two distinct printable ASCII characters (0x20 to 0x7E, inclusive), in place of # and .. I'll continue referring to them as # and . for the remainder of the specification though.

Input and output may either be a single linefeed-separated string or a list of strings (one for each line), but the format has to be consistent.

You may assume that the input contains at least one # and all lines are the same length.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

Each test case has input and output next to each other.

```<code>#    #

...    ...
#..    #..
...    ...

...    ...
#..    ###
..#    ###

.#.    ###
#..    ###
..#    ###

.....    .....
.#.#.    .###.
.....    .....

...    ...
.#.    .#.
...    .#.
.#.    .#.
...    ...

..........    ..........
..........    ..........
....#.....    ....#.....
..........    ..........

..........    ..........
..........    ..........
....#.....    ...##.....
...#......    ...##.....

..........    ..........
..#.......    ..###.....
....#.....    ..###.....
...#......    ..###.....

..........    ..........
..#.......    ..######..
....#..#..    ..######..
...#......    ..######..

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

答:
PowerShell v3+, <s>215</s> <s>162</s> <s>148</s> <s>144</s> 139 bytes

```<code>param($n)$n|%{(((-join(0..($n[0].length-1)|%{$i=$_;+('1'-in(0..($n.length-1)|%{$n[$_][$i]}))}))-replace'(?<=1.*?).(?=.*?1)',1),$_)[0-ge$_]}
</code>```

Takes input as an array of strings $n, with 0 instead of . and 1 instead of #. Then, we loop through $n, each iteration testing whether the current string is smaller than 0 (i.e., there's a 1 in it), and if so, output a string. Uses a pseudo-ternary in place of an if/else operation.

The string is constructed from loops through the width of the input string. Each iteration, we tack on a 0 or a 1 depending upon if 1 is found somewhere in the corresponding vertical column. For the last test case, for example, this will result in a string like 0011001001. Requires v3+ for the -in operator. That string is paired with a fancy-dancy regex replace to replace any "inner" 0s with 1s. Much thanks to Business Cat in chat for the assist on that. Our string would be 0011111111 at this point.

Else, output the current (all-zeros) string $_.

The resulting strings are left on the pipeline, and output is implicit. The default Write-Output for an array of strings is with a newline between each element, so that's visually what happens.

Examples

```<code>PS C:\Tools\Scripts\golfing> .\highlight-the-bounding-box-cartesian.ps1 '0000000001','0010000000','0000100100','0001000000'
0011111111
0011111111
0011111111
0011111111

PS C:\Tools\Scripts\golfing> .\highlight-the-bounding-box-cartesian.ps1 '0000000000','0000000000','0000100000','0001000000'
0000000000
0000000000
0001100000
0001100000
</code>```

Body:
PowerShell v3+, <s>215</s> <s>162</s> <s>148</s> <s>144</s> 139 bytes

param($n)$n|%{(((-join(0..($n[0].length-1)|%{$i=$_;+('1'-in(0..($n.length-1)|%{$n[$_][$i]}))}))-replace'(?<=1.*?).(?=.*?1)',1),$_)[0-ge$_]}

Takes input as an array of strings $n, with 0 instead of . and 1 instead of #. Then, we loop through $n, each iteration testing whether the current string is smaller than 0 (i.e., there's a 1 in it), and if so, output a string. Uses a pseudo-ternary in place of an if/else operation.

The string is constructed from loops through the width of the input string. Each iteration, we tack on a 0 or a 1 depending upon if 1 is found somewhere in the corresponding vertical column. For the last test case, for example, this will result in a string like 0011001001. Requires v3+ for the -in operator. That string is paired with a fancy-dancy regex replace to replace any "inner" 0s with 1s. Much thanks to Business Cat in chat for the assist on that. Our string would be 0011111111 at this point.

Else, output the current (all-zeros) string $_.

The resulting strings are left on the pipeline, and output is implicit. The default Write-Output for an array of strings is with a newline between each element, so that's visually what happens.

Examples

PS C:\Tools\Scripts\golfing> .\highlight-the-bounding-box-cartesian.ps1 '0000000001','0010000000','0000100100','0001000000'
0011111111
0011111111
0011111111
0011111111

PS C:\Tools\Scripts\golfing> .\highlight-the-bounding-box-cartesian.ps1 '0000000000','0000000000','0000100000','0001000000'
0000000000
0000000000
0001100000
0001100000


问:
Find the minimum and maximum integers in an array, without using builtins

Challenge

Given an array of integers, received from stdin, function arguments, program arguments, or some other method:

Output only the minimum and maximum numbers in the array, through a return value, stdout, or other fitting methods.

Example session

```<code>> minmax( {0, 15, 2, 3, 7, 18, -2, 9, 6, -5, 3, 8, 9, -14} )
-14 18
</code>```

Reference implementation

```<code>// C++14

void minmax(std::vector<int> v) {
    int min = v[0]; int max = v[0];
    for(auto it : v) {
        if (*it < min)
            min = *it;
        if (*it > max)
            max = *it;
    }
    std::cout << min << ' ' << max << std::endl;
}
</code>```

Rules

You may not use a built-in function to calculate the values.

Standard loopholes disallowed.

Creative implementations encouraged.

This is code-golf, shortest answer wins but will not be selected.

Clarifications

If the array contains 1 element you need to output it twice.

If the minimum and maximum values are the same, you need to output them both.

答:
dc, 110 bytes

```<code>?ddsMsmzdsAsa[z1-:az0<S]dsSx[>R]s?[la;asM]sR[lM]sQ[lQxla1-dsa;al?xla0<N]dsNxlAsa[<R]s?[la;asm]sR[lm]sQlNxlmlMf
</code>```

Help me, dcers! You are my only hope!

Thanks to @seshoumara for finding that bug!

I'll add an explanation later. Here it is broken up a bit:

```<code>?dd sM sm
zd sA sa
[z 1- :a z0<S]dsSx
 [>R]s?
 [la;asM]sR
 [lM]sQ
[lQx la 1- dsa ;a l?x la0<N]dsNx
lA sa
 [<R]s?
 [la;a sm]sR
 [lm]sQ
lNx
lm lM f
</code>```

Body:
dc, 110 bytes

?ddsMsmzdsAsa[z1-:az0<S]dsSx[>R]s?[la;asM]sR[lM]sQ[lQxla1-dsa;al?xla0<N]dsNxlAsa[<R]s?[la;asm]sR[lm]sQlNxlmlMf

Help me, dcers! You are my only hope!

Thanks to @seshoumara for finding that bug!

I'll add an explanation later. Here it is broken up a bit:

?dd sM sm
zd sA sa
[z 1- :a z0<S]dsSx
 [>R]s?
 [la;asM]sR
 [lM]sQ
[lQx la 1- dsa ;a l?x la0<N]dsNx
lA sa
 [<R]s?
 [la;a sm]sR
 [lm]sQ
lNx
lm lM f


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

```<code>+ÆR©_f®
</code>```

Try it online!

Explanation

```<code>+          add the upper bound and the difference
 ÆR        find all primes up to that number
   ©       save that in the register
    _      subtract the difference from each
     f®    remove anything not in the original prime list
</code>```

Title: Variable Prime "Twins"

Body:
I am 2/3 twins with my brother, i.e. born on the same day of the same month but twelve years later. When I was 5, he was 17, both primes; the last pair of ages we can reasonably count on is [71, 83] with both of us being alive and able to celebrate this coincidental jubilee.

Task

Create a code that

takes two integers as input: the difference between the counter and the "twin" as a positive integer k (well yes, I'm the younger) and the upper bound as a positive integer u (runtime consideration)

and gives output as an array or list of all i numbers lower than or equal u for which both i and i+k are primes. The output does not need to be sorted.

Test Cases

```<code>12, 1000 -> [5, 7, 11, 17, 19, 29, 31, 41, 47, 59, 61, 67, 71, 89, 97, 101, 127, 137, 139, 151, 167, 179, 181, 199, 211, 227, 229, 239, 251, 257, 269, 271, 281, 337, 347, 367, 389, 397, 409, 419, 421, 431, 449, 467, 479, 487, 491, 509, 557, 587, 601, 607, 619, 631, 641, 647, 661, 727, 739, 757, 761, 797, 809, 811, 827, 907, 929, 941, 971, 997]
2, 999 -> [3, 5, 11, 17, 29, 41, 59, 71, 101, 107, 137, 149, 179, 191, 197, 227, 239, 269, 281, 311, 347, 419, 431, 461, 521, 569, 599, 617, 641, 659, 809, 821, 827, 857, 881]
3, 1500 -> [2]
30, 1500 -> [7, 11, 13, 17, 23, 29, 31, 37, 41, 43, 53, 59, 67, 71, 73, 79, 83, 97, 101, 107, 109, 127, 137, 149, 151, 163, 167, 181, 193, 197, 199, 211, 227, 233, 239, 241, 251, 263, 277, 281, 283, 307, 317, 337, 349, 353, 359, 367, 379, 389, 401, 409, 419, 431, 433, 449, 457, 461, 479, 491, 541, 547, 557, 563, 569, 571, 577, 587, 601, 613, 617, 631, 643, 647, 653, 661, 709, 727, 739, 743, 757, 797, 809, 823, 827, 829, 853, 857, 877, 881, 907, 911, 937, 941, 947, 953, 967, 983, 991, 1009, 1019, 1021, 1031, 1033, 1039, 1061, 1063, 1087, 1093, 1123, 1151, 1163, 1171, 1187, 1193, 1201, 1229, 1249, 1259, 1277, 1289, 1291, 1297, 1399, 1409, 1423, 1429, 1451, 1453, 1459, 1481, 1493]
</code>```

Edit

Since I failed to specify the upper bound, both inclusive and exclusive solutions are welcome.

Edit No. 2

The challenge ends on 1st September, one week from the start.

Looks like we have a winner but in case of a tie popularity is the tie-breaker; in this case the "second" will be compensated via bounty.

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

+ÆR©_f®

Try it online!

Explanation

+          add the upper bound and the difference
 ÆR        find all primes up to that number
   ©       save that in the register
    _      subtract the difference from each
     f®    remove anything not in the original prime list


问:
How many switches are ON
A class has N student and the class room has N switches (all turned OFF and numbered 1 to N). Each student has an enrollment number assigned from 1 to N. Each student serially (by number) toggles the switches that has a number which is divisible by his/her enrollment number.

Example: Student 1 will turn all the switches ON. Student 2 will turn all even switches OFF. Student N just toggles the Nth switch.

Write a function that takes N as input as returns number of ON switches.
sample I/O

```<code>Input: 10
Output:3
</code>```

No upper bound for N is given, but greater the scope, better the code. Shortest and innovative function wins

答:
Python, 19 characters

f=lambda n:n**.5//1
```
<p>Perfect squares are the only numbers with an odd number of divisors.</p>
<p>This used to be a <strong>21-character</strong> answer:</p>
<pre class="lang-python prettyprint-override"><code>f=lambda n:int(n**.5)
</code>```

but since I originally wrote it in 2011, the floor-division // operator was introduced, which can replace the int call.

As a consequence, the answer is now returned as a floating-point number. (But f(10) == 3.0 is still a correct number of lockers!)

ContentLicense: CC BY-SA 2.5

Title: How many switches are ON

Body:
Python, 19 characters

f=lambda n:n**.5//1

Perfect squares are the only numbers with an odd number of divisors.

This used to be a 21-character answer:

f=lambda n:int(n**.5)

but since I originally wrote it in 2011, the floor-division // operator was introduced, which can replace the int call.

As a consequence, the answer is now returned as a floating-point number. (But f(10) == 3.0 is still a correct number of lockers!)

ContentLicense: CC BY-SA 4.0


问:
How does math work in Anastasiya's world?

Background:

Standard operation math like basic addition and multiplication in the real world work like these:

```<code>12 + 123 = 135
</code>```

and

```<code>12 * 123 = 1476
</code>```

That's not interesting and boring! Many schools are already interpreting this as practice, practice, practice of formal algorithms. That implies a pretty rigid and boring mathematical diet and is not what is intended in this challenge. Get ready to play some fun on our beloved site.

Consider the process of adding two positive integer numbers, then adding again all the digits of its result. Repeating with the addition until only a single digit is obtained. For example:

The result of 12 + 123 is 135.

Adding all the digits of 135 we obtain 1 + 3 + 5 = 9.

The number of steps required to obtain a single digit value 9 in this repeated addition is 2.

As with the previous process of the addition, the multiplication of two positive integer numbers follows the same process. Multiply all the digits of its result and then repeating this process until only a single digit remains. Take the above example:

The result of 12 * 123 is 1476.

Multiply all the digits of 1476 we obtain 1 * 4 * 7 * 6 = 168.

Multiply again all the digits of 168 we obtain 1 * 6 * 8 = 48.

Multiply again all the digits of 48 we obtain 4 * 8 = 32.

Multiply once again all the digits of 32 we obtain 3 * 2 = 6.

The number of steps required to obtain a single digit value 6 this repeated multiplication is 5.

For this challenge's sake and avoiding any misuse of math notations, I introduce these two dummy notations: (+) and (*), but you may use any notation you like, which work like the followings:

The operation of repeated addition process to obtain a single value is 12 (+) 123 = 9.

The operation of repeated multiplication process to obtain a single value is 12 (*) 123  = 6.

Challenge:

The challenge is to write either a program or a function which can perform both of operations as explained in the background section: (+) and (*).

Input:

The inputs of the program or the function are two positive integers and one operation either (+) and (*). The format of the input is an arbitrary choice of the programmer. You may format the input, for example, a (+) b or F(a, (+), b) or any format you wish.

Output:

The output of the program or the function must contain the result of operation and the number of steps required with freestyle format as you wish.

Test Cases (ignore the input and output format):

```<code>    81 (+) 31       -->   (4 ; 2)
    351 (+) 14568   -->   (6 ; 3)
    21 (*) 111      -->   (8 ; 3)
    136 (*) 2356    -->   (0 ; 2)
</code>```

General rules:

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

Don't let esolangs discourage you from posting an answer with regular languages. Enjoy this challenge by providing an answer as short as possible with your programming language. If you post a clever answer and a clear explanation, your answer will be appreciated (hence the upvotes) regardless of the programming language you use.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/ method with the proper parameters, full programs, etc. The choice is yours.

If possible, your program can properly handle large numbers. If not, that will just be fine.

Let the game begin!!

答:
Perl, 38 bytes

Includes +2 for -ap

Run with the input on STDIN and spaces around the operator:

```<code>amath.pl <<< "12 + 123"
amath.pl <<< "12 * 123"
</code>```

The output is digit and steps separated by +A

amath.pl:

```<code>#!/usr/bin/perl -ap
1while++$\,$_=eval."+A",s/\B/$F[1]/g
</code>```

If outputting the steps in unary is ok this 35 byte version works better:

```<code>#!/usr/bin/perl -lap
1while$\.=1,$_=eval,s/\B/$F[1]/g
</code>```

Body:
Perl, 38 bytes

Includes +2 for -ap

Run with the input on STDIN and spaces around the operator:

amath.pl <<< "12 + 123"
amath.pl <<< "12 * 123"

The output is digit and steps separated by +A

amath.pl:

#!/usr/bin/perl -ap
1while++$\,$_=eval."+A",s/\B/$F[1]/g

If outputting the steps in unary is ok this 35 byte version works better:

#!/usr/bin/perl -lap
1while$\.=1,$_=eval,s/\B/$F[1]/g


答:
R, <s>158</s> 155 bytes

This program takes in input points . and hashtags #, line by line.

```<code>v=c();f=which((d=matrix(strsplit(paste0(a<-scan(,""),collapse=""),"")[[1]],nr=sum(a<0),b=T))=="#",a=T);d[min(f[,1]):max(f[,1]),min(f[,2]):max(f[,2])]="#";d
</code>```

Ungolfed :

```<code>a<-scan(,"")             #Input

v=c()                   #Empty vector
f=which((d=(matrix(strsplit(paste0(a,collapse=""),"")[[1]],nr=length(a),b=T)))=="#",a=T) #Main work is here !

d[min(f[,1]):max(f[,1]),min(f[,2]):max(f[,2])]="#"                        #Creates
                                                                          #the new figure

d                       #Displays it
</code>```

Here are the details of the third line :

```<code>paste0(a,collapse="")
#Collapses the input into a single string

strsplit(paste0(a,collapse=""),"")[[1]]
#Split this string character-wise

matrix(strsplit(paste0(a,collapse=""),"")[[1]],nr=sum(a<0),b=T)
#Creates and fills (by row) a matrix with number of row the number of line of the input

which((d=(matrix(strsplit(paste0(a,collapse=""),"")[[1]],nr=l,b=T)))=="#",a=T)
#Gives the index of the matrix's elements that are "#"
</code>```

Title: Highlight the Bounding Box, Part I: Cartesian Grid

Body:
You're given a rectangular grid of the characters . and #, like this:

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

Your task is to fill the entire axis-aligned bounding box of the # with further #:

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

The axis-aligned bounding box is the smallest rectangle which contains all the #.

Want more? Try Part II!

Rules

You may use any two distinct printable ASCII characters (0x20 to 0x7E, inclusive), in place of # and .. I'll continue referring to them as # and . for the remainder of the specification though.

Input and output may either be a single linefeed-separated string or a list of strings (one for each line), but the format has to be consistent.

You may assume that the input contains at least one # and all lines are the same length.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

Each test case has input and output next to each other.

```<code>#    #

...    ...
#..    #..
...    ...

...    ...
#..    ###
..#    ###

.#.    ###
#..    ###
..#    ###

.....    .....
.#.#.    .###.
.....    .....

...    ...
.#.    .#.
...    .#.
.#.    .#.
...    ...

..........    ..........
..........    ..........
....#.....    ....#.....
..........    ..........

..........    ..........
..........    ..........
....#.....    ...##.....
...#......    ...##.....

..........    ..........
..#.......    ..###.....
....#.....    ..###.....
...#......    ..###.....

..........    ..........
..#.......    ..######..
....#..#..    ..######..
...#......    ..######..

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

Body:
R, <s>158</s> 155 bytes

This program takes in input points . and hashtags #, line by line.

v=c();f=which((d=matrix(strsplit(paste0(a<-scan(,""),collapse=""),"")[[1]],nr=sum(a<0),b=T))=="#",a=T);d[min(f[,1]):max(f[,1]),min(f[,2]):max(f[,2])]="#";d

Ungolfed :

a<-scan(,"")             #Input

v=c()                   #Empty vector
f=which((d=(matrix(strsplit(paste0(a,collapse=""),"")[[1]],nr=length(a),b=T)))=="#",a=T) #Main work is here !

d[min(f[,1]):max(f[,1]),min(f[,2]):max(f[,2])]="#"                        #Creates
                                                                          #the new figure

d                       #Displays it

Here are the details of the third line :

paste0(a,collapse="")
#Collapses the input into a single string

strsplit(paste0(a,collapse=""),"")[[1]]
#Split this string character-wise

matrix(strsplit(paste0(a,collapse=""),"")[[1]],nr=sum(a<0),b=T)
#Creates and fills (by row) a matrix with number of row the number of line of the input

which((d=(matrix(strsplit(paste0(a,collapse=""),"")[[1]],nr=l,b=T)))=="#",a=T)
#Gives the index of the matrix's elements that are "#"


问:
Smallest palindrome divisible by the input
Given a positive integer N, output the smallest positive integer such that this number is a palindrome (i.e. is its own reverse) and is divisible by N.

The palindrome (i.e. the output) must not need a leading zero to be a palindrome, e.g. 080 is not the valid answer for 16.

The input will never be a multiple of 10, because of the previous reason.

Your program may take as much time as necessary, even if in practice it would be way too long to output the answer.

Inputs and outputs

You may take the input through STDIN, as a function argument, or anything similar.

You may print the output to STDOUT, return it from a function, or anything similar.

Inputs and outputs must be in the decimal base.

Test cases

```<code>N        Output
1        1
2        2
16       272
17       272
42       252
111      111
302      87278
1234     28382
</code>```

Scoring

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

答:
Mathematica, 49 bytes

```<code>(c=#;Not[PalindromeQ@c&&c~Mod~#==0]~While~c++;c)&
</code>```

Starts the search at c = N, and increments c if not a palindrome and not divisible by N. When conditions are met, outputs c.

Body:
Mathematica, 49 bytes

(c=#;Not[PalindromeQ@c&&c~Mod~#==0]~While~c++;c)&

Starts the search at c = N, and increments c if not a palindrome and not divisible by N. When conditions are met, outputs c.


答:
Perl, 25 bytes

Includes +2 for -ap

Run with the input on STDIN:

```<code>palidiv.pl <<< 16
</code>```

palidiv.pl:

```<code>#!/usr/bin/perl -ap
$_+="@F"while$_-reverse
</code>```

Title: Smallest palindrome divisible by the input

Body:
Given a positive integer N, output the smallest positive integer such that this number is a palindrome (i.e. is its own reverse) and is divisible by N.

The palindrome (i.e. the output) must not need a leading zero to be a palindrome, e.g. 080 is not the valid answer for 16.

The input will never be a multiple of 10, because of the previous reason.

Your program may take as much time as necessary, even if in practice it would be way too long to output the answer.

Inputs and outputs

You may take the input through STDIN, as a function argument, or anything similar.

You may print the output to STDOUT, return it from a function, or anything similar.

Inputs and outputs must be in the decimal base.

Test cases

```<code>N        Output
1        1
2        2
16       272
17       272
42       252
111      111
302      87278
1234     28382
</code>```

Scoring

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

Body:
Perl, 25 bytes

Includes +2 for -ap

Run with the input on STDIN:

palidiv.pl <<< 16

palidiv.pl:

#!/usr/bin/perl -ap
$_+="@F"while$_-reverse


答:
C#, <s>112</s> 101 bytes

Thanks to TheLethalCoder for reminding me that these anonymous lambda statement-nor-expression things are allowed in C#.

```<code>n=>{var r="";for(int y=n--,x;y-->0;r+="*\n")for(x=0;x<n;r+=y%n*x<1|y==x|y==n-x++?"*":" ");return r;};
</code>```

Who said C# isn't a fun golfing language?

Title: Creating a Crossed Square

Body:
Creating a Crossed Square

You are to take input of an integer of one or more and output a square made of any printable character of your choice with a diagonal cross through the centre.

The general idea is for the output to be a hollow square that has a diagonal cross through it.:

```<code>Input: 7
Output:
*******
*#   #*
* # # *
*  #  *
* # # *
*#   #*
*******
</code>```

In the above example the '*'s represent the outer box and the '#'s represent the diagonal cross.

Note that the above example uses two different characters so that it is easier to see what the output looks like, your program should use one character only.

Input

An integer of 1 or more, it is guaranteed to be odd.

Output

A square that is made up of a character of your choice with a cross through the middle.

The cross must be diagonal

The square may be output via the function or written to output

Trailing newlines are okay

Can output as a graphic, diagram or image if you wish too

Examples

```<code>Input: 1
Output:
*

Input: 3
Output:
***
***
***

Input: 5
Output:
*****
** **
* * *
** **
*****

Input: 7
Output:
*******
**   **
* * * *
*  *  *
* * * *
**   **
*******
</code>```

Specs

Functions or full programs are allowed

You can get input by your preferred means

Standard loopholes are disallowed

Programs must work without any additional statements i.e. usings in C#, they must be included in the entry

You can output from a function or print the result

This is code golf so the shortest solution wins.

Body:
C#, <s>112</s> 101 bytes

Thanks to TheLethalCoder for reminding me that these anonymous lambda statement-nor-expression things are allowed in C#.

n=>{var r="";for(int y=n--,x;y-->0;r+="*\n")for(x=0;x<n;r+=y%n*x<1|y==x|y==n-x++?"*":" ");return r;};

Who said C# isn't a fun golfing language?


答:
Mathematica, 43 bytes

```<code>(Prime@Range@PrimePi@#2+#)~Select~PrimeQ-#&
</code>```

Generate all primes less than or equal to the upper bound. Add the difference of ages to the result. Select prime numbers among them. Subtract the difference of ages to the result.

Title: Variable Prime "Twins"

Body:
Mathematica, 43 bytes

(Prime@Range@PrimePi@#2+#)~Select~PrimeQ-#&

Generate all primes less than or equal to the upper bound. Add the difference of ages to the result. Select prime numbers among them. Subtract the difference of ages to the result.


答:
Python, <s>219</s> 212 bytes

```<code>def b(a):j=len(a[0]);g=range;z=g(len(a));h=[i for i in z if'#'in a[i]];w=[i for i,c in[(i,[r[i]for r in a])for i in g(j)]if'#'in c];return[[any((r<h[0],h[-1]<r,c<w[0],w[-1]<c))and'.'or'#'for c in g(j)]for r in z]
</code>```

(Although I think another method may well be shorter)

Takes and returns a list of list of chars.

Test it on ideoone

Body:
Python, <s>219</s> 212 bytes

def b(a):j=len(a[0]);g=range;z=g(len(a));h=[i for i in z if'#'in a[i]];w=[i for i,c in[(i,[r[i]for r in a])for i in g(j)]if'#'in c];return[[any((r<h[0],h[-1]<r,c<w[0],w[-1]<c))and'.'or'#'for c in g(j)]for r in z]

(Although I think another method may well be shorter)

Takes and returns a list of list of chars.

Test it on ideoone


问:
Calculate the correlation coefficient
Given a series of numbers for events X and Y, calculate Pearson's correlation coefficient. The probability of each event is equal, so expected values can be calculated by simply summing each series and dividing by the number of trials.

Input

```<code>1   6.86
2   5.92
3   6.08
4   8.34
5   8.7
6   8.16
7   8.22
8   7.68
9   12.04
10  8.6
11  10.96
</code>```

Output

```<code>0.769
</code>```

Shortest code wins. Input can be by stdin or arg. Output will be by stdout.

Edit: Builtin functions should not be allowed (ie calculated expected value, variance, deviation, etc) to allow more diversity in solutions. However, feel free to demonstrate a language that is well suited for the task using builtins (for exhibition).

Based on David's idea for input for Mathematica (86 char using builtin mean)

```<code>m=Mean;x=d[[All,1]];y=d[[All,2]];(m@(x*y)-m@x*m@y)/Sqrt[(m@(x^2)-m@x^2)(m@(y^2)-m@y^2)]

m = Mean;
x = d[[All,1]];
y = d[[All,2]];
(m@(x*y) - m@x*m@y)/((m@(x^2) - m@x^2)(m@(y^2) - m@y^2))^.5
</code>```

Skirting by using our own mean (101 char)

```<code>m=Total[#]/Length[#]&;x=d[[All,1]];y=d[[All,2]];(m@(x*y)-m@x*m@y)/((m@(x^2)-m@x^2)(m@(y^2)-m@y^2))^.5

m = Total[#]/Length[#]&;
x = d[[All,1]];
y = d[[All,2]];
(m@(x*y)-m@x*m@y)/((m@(x^2)-m@x^2)(m@(y^2)-m@y^2))^.5
</code>```

答:
Mathematica 34 bytes

Here are a few ways to obtain the Pearson product moment correlation.  They all produce the same result.
From Dr. belisarius: 34 bytes

```<code>Dot@@Normalize/@(#-Mean@#&)/@{x,y}
</code>```

Built-in Correlation function I: 15 chars

This assumes that x and y are lists corresponding to each variable.

```<code>x~Correlation~y
</code>```

0.76909

Built-in Correlation function II: 31 chars

This assumes d is a list of ordered pairs.

```<code>d[[;;,1]]~Correlation~d[[;;,2]]
</code>```

0.76909

The use of ;; for All thanks to A Simmons.

Relying on the Standard Deviation function: <s>118</s> 115 chars

The correlation can be determined by:

```<code>s=StandardDeviation;
m=Mean;
n=Length@d;
x=d[[;;,1]];
y=d[[;;,2]];
Sum[((x[[i]]-m@x)/s@x)((y[[i]]-m@y)/s@y),{i,n}]/(n-1)
</code>```

0.76909

Hand-rolled Correlation: 119 chars

Assuming x and y are lists...

```<code>s=Sum;n=Length@d;m@p_:=Tr@p/n;
(s[(x[[i]]-m@x)(y[[i]]-m@y),{i,n}]/Sqrt@(s[(x[[i]]-m@x)^2,{i,n}] s[(y[[i]] - m@y)^2,{i,n}]))
</code>```

0.76909

Title: Calculate the correlation coefficient

Body:
Mathematica 34 bytes

Here are a few ways to obtain the Pearson product moment correlation.  They all produce the same result.
From Dr. belisarius: 34 bytes

Dot@@Normalize/@(#-Mean@#&)/@{x,y}

Built-in Correlation function I: 15 chars

This assumes that x and y are lists corresponding to each variable.

x~Correlation~y

0.76909

Built-in Correlation function II: 31 chars

This assumes d is a list of ordered pairs.

d[[;;,1]]~Correlation~d[[;;,2]]

0.76909

The use of ;; for All thanks to A Simmons.

Relying on the Standard Deviation function: <s>118</s> 115 chars

The correlation can be determined by:

s=StandardDeviation;
m=Mean;
n=Length@d;
x=d[[;;,1]];
y=d[[;;,2]];
Sum[((x[[i]]-m@x)/s@x)((y[[i]]-m@y)/s@y),{i,n}]/(n-1)

0.76909

Hand-rolled Correlation: 119 chars

Assuming x and y are lists...

s=Sum;n=Length@d;m@p_:=Tr@p/n;
(s[(x[[i]]-m@x)(y[[i]]-m@y),{i,n}]/Sqrt@(s[(x[[i]]-m@x)^2,{i,n}] s[(y[[i]] - m@y)^2,{i,n}]))

0.76909


问:
Exploded view of a string
Don't you love those exploded-view diagrams  in which a machine or object is taken apart into its smallest pieces?

Let's do that to a string!

The challenge

Write a program or function that

inputs a string containing only printable ASCII characters;

dissects the string into groups of non-space equal characters (the "pieces" of the string);

outputs those groups in any convenient format, with some separator between groups.

For example, given the string

```<code>Ah, abracadabra!
</code>```

the output would be the following groups:

```
!
,
A
aaaaa
bb
c
d
h
rr
```

Each group in the output contains equal characters, with spaces removed. A newline has been used as separator between groups. More about allowed formats below.

Rules

The input should be a string or an array of chars. It will only contain printable ASCII chars (the inclusive range from space to tilde). If your language does not support that, you can take the input in the form of numbers representing ASCII codes.

You can assume that the input contains at least one non-space character.

The output should consist of characters (even if the input is by means of ASCII codes). There has to be an unambiguous separator between groups, different than any non-space character that may appear in the input.

If the output is via function return, it may also be an array or strings, or an array of arrays of chars, or similar structure. In that case the structure provides the necessary separation.

A separator between characters of each group is optional. If there is one, the same rule applies: it can't be a non-space character that may appear in the input. Also, it can't be the same separator as used between groups.

Other than that, the format is flexible. Here are some examples:

The groups may be strings separated by newlines, as shown above.

The groups may be separated by any non-ASCII character, such as  ¬. The output for the above input would be the string:

```<code>!¬,¬A¬aaaaa¬bb¬c¬d¬h¬rr
</code>```

The groups may be separated by n>1 spaces (even if n is variable), with chars between each group separated by a single space:

```<code>!  ,    A   a a a a a    b b  c       d   h  r r
</code>```

The output may also be an array or list of strings returned by a function:

```<code>['!', 'A', 'aaaaa', 'bb', 'c', 'd', 'h', 'rr']
</code>```

Or an array of char arrays:

```<code>[['!'], ['A'], ['a', 'a', 'a', 'a', 'a'], ['b', 'b'], ['c'], ['d'], ['h'], ['r', 'r']]
</code>```

Examples of formats that are not allowed, according to the rules:

A comma can't be used as separator (!,,,A,a,a,a,a,a,b,b,c,d,h,r,r), because the input may contain commas.

It's not accepted to drop the separator between groups (!,Aaaaaabbcdhrr) or to use the same separator between groups and within groups (! , A a a a a a b b c d h r r).

The groups may appear in any order in the output. For example: alphabetical order (as in the examples above), order of first appearance in the string, ... The order need not be consistent or even deterministic.

Note that the input cannot contain newline characters, and A and a are different characters (grouping is case-sentitive).

Shortest code in bytes wins.

Test cases

In each test case, first line is input, and the remaining lines are the output, with each group in a different line.

Test case 1:

```
Ah, abracadabra!
!
,
A
aaaaa
bb
c
d
h
rr
```

Test case 2:

```
\o/\o/\o/
///
\\\
ooo
```

Test case 3:

```
A man, a plan, a canal: Panama!
!
,,
:
A
P
aaaaaaaaa
c
ll
mm
nnnn
p
```

Test case 4:

```
"Show me how you do that trick, the one that makes me scream" she said
""
,
S
aaaaa
cc
dd
eeeeeee
hhhhhh
ii
kk
mmmm
n
ooooo
rr
ssss
tttttt
u
ww
y
```

答:
Perl, 31 bytes

Includes +1 for -p

Run with input on STDIN:

```<code>explode.pl <<< "ab.ceaba.d"
</code>```

explode.pl:

```<code>#!/usr/bin/perl -p
s%.%$&x s/\Q$&//g.$/%eg;y/
//s
</code>```

If you don't care about spurious newlines inbetween the lines the following 24 bytes version works too:

```<code>#!/usr/bin/perl -p
s%.%$&x s/\Q$&//g.$/%eg
</code>```

Title: Exploded view of a string

Body:
Perl, 31 bytes

Includes +1 for -p

Run with input on STDIN:

explode.pl <<< "ab.ceaba.d"

explode.pl:

#!/usr/bin/perl -p
s%.%$&x s/\Q$&//g.$/%eg;y/
//s

If you don't care about spurious newlines inbetween the lines the following 24 bytes version works too:

#!/usr/bin/perl -p
s%.%$&x s/\Q$&//g.$/%eg


答:
Actually, <s>15</s> 14 bytes

Asked to answer by Leaky Nun. Golfing suggestions welcome. Try it online!

```<code>╖2`╜*$;R=`╓N╜*
</code>```

Ungolfing

```<code>          Implicit input n.
╖         Save n in register 0.
2`...`╓   Push first 2 values where f(x) is truthy, starting with f(0).
  ╜*$       Push register 0, multiply by x, and str().
  ;R        Duplicate str(n*x) and reverse.
  =         Check if str(n*x) == reverse(str(n*x)).
          The map will always result in [0, the x we want].
N         Grab the last (second) value of the resulting list.
╜*        Push n and multiply x by n again.
          Implicit return.
</code>```

Body:
Actually, <s>15</s> 14 bytes

Asked to answer by Leaky Nun. Golfing suggestions welcome. Try it online!

╖2`╜*$;R=`╓N╜*

Ungolfing

          Implicit input n.
╖         Save n in register 0.
2`...`╓   Push first 2 values where f(x) is truthy, starting with f(0).
  ╜*$       Push register 0, multiply by x, and str().
  ;R        Duplicate str(n*x) and reverse.
  =         Check if str(n*x) == reverse(str(n*x)).
          The map will always result in [0, the x we want].
N         Grab the last (second) value of the resulting list.
╜*        Push n and multiply x by n again.
          Implicit return.


问:
Permutapalindromic numbers
Given an integer N as input, output the Nth permutapalindromic number.

A permutapalindromic number is a strictly positive integer such that there is at least one permutation of its digits that results in a palindrome (i.e. a number that is its own reverse).

For example, 117 is a permutapalindromic number since its digits can be permuted into 171, which is a palindrome.

We consider that numbers like 10 are not permutapalindromic numbers, even though 01 = 1 is a palindrome. We impose that the palindromic permutation must not have a leading zero (as such, 0 itself is not permutapalindromic).

Numbers that are already palindromes are also permutapalindromic, since permuting nothing is valid.

Inputs and outputs

N may be either 0-indexed or 1-indexed. Please indicate which of the two your answer uses.

The input can be taken through STDIN, as a function argument, or anything similar in your language of choice. The output can be written to STDOUT, returned from a function, or anything similar in your language of choice.

The input and output must be in the decimal base.

Test cases

The following test cases are 1-indexed. Your program must be able to pass any of the test cases presented here in at most 1 minute.

```<code>N      Output

1      1
2      2
3      3
4      4
5      5
6      6
7      7
8      8
9      9
10     11
42     181
100    404
128    511
256    994
270    1166
</code>```

Scoring

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

答:
Haskell, <s>89</s> 87 bytes

```<code>import Data.List
(filter(any(show.floor.read.reverse>>=(==)).permutations.show)[0..]!!)
</code>```

Title: Permutapalindromic numbers

Body:
Haskell, <s>89</s> 87 bytes

import Data.List
(filter(any(show.floor.read.reverse>>=(==)).permutations.show)[0..]!!)


答:
Oracle SQL 11.2, 123 bytes

SELECT LISTAGG(c)WITHIN GROUP(ORDER BY 1)FROM(SELECT SUBSTR(:1,LEVEL,1)c FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))GROUP BY c;
```

<p>Un-golfed </p>

<pre class="lang-sql prettyprint-override"><code>SELECT LISTAGG(c)WITHIN GROUP(ORDER BY 1)
FROM (SELECT SUBSTR(:1,LEVEL,1)c FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))
GROUP BY c
</code>```

Title: Exploded view of a string

Body:
Don't you love those exploded-view diagrams  in which a machine or object is taken apart into its smallest pieces?

Let's do that to a string!

The challenge

Write a program or function that

inputs a string containing only printable ASCII characters;

dissects the string into groups of non-space equal characters (the "pieces" of the string);

outputs those groups in any convenient format, with some separator between groups.

For example, given the string

```<code>Ah, abracadabra!
</code>```

the output would be the following groups:

```
!
,
A
aaaaa
bb
c
d
h
rr
```

Each group in the output contains equal characters, with spaces removed. A newline has been used as separator between groups. More about allowed formats below.

Rules

The input should be a string or an array of chars. It will only contain printable ASCII chars (the inclusive range from space to tilde). If your language does not support that, you can take the input in the form of numbers representing ASCII codes.

You can assume that the input contains at least one non-space character.

The output should consist of characters (even if the input is by means of ASCII codes). There has to be an unambiguous separator between groups, different than any non-space character that may appear in the input.

If the output is via function return, it may also be an array or strings, or an array of arrays of chars, or similar structure. In that case the structure provides the necessary separation.

A separator between characters of each group is optional. If there is one, the same rule applies: it can't be a non-space character that may appear in the input. Also, it can't be the same separator as used between groups.

Other than that, the format is flexible. Here are some examples:

The groups may be strings separated by newlines, as shown above.

The groups may be separated by any non-ASCII character, such as  ¬. The output for the above input would be the string:

```<code>!¬,¬A¬aaaaa¬bb¬c¬d¬h¬rr
</code>```

The groups may be separated by n>1 spaces (even if n is variable), with chars between each group separated by a single space:

```<code>!  ,    A   a a a a a    b b  c       d   h  r r
</code>```

The output may also be an array or list of strings returned by a function:

```<code>['!', 'A', 'aaaaa', 'bb', 'c', 'd', 'h', 'rr']
</code>```

Or an array of char arrays:

```<code>[['!'], ['A'], ['a', 'a', 'a', 'a', 'a'], ['b', 'b'], ['c'], ['d'], ['h'], ['r', 'r']]
</code>```

Examples of formats that are not allowed, according to the rules:

A comma can't be used as separator (!,,,A,a,a,a,a,a,b,b,c,d,h,r,r), because the input may contain commas.

It's not accepted to drop the separator between groups (!,Aaaaaabbcdhrr) or to use the same separator between groups and within groups (! , A a a a a a b b c d h r r).

The groups may appear in any order in the output. For example: alphabetical order (as in the examples above), order of first appearance in the string, ... The order need not be consistent or even deterministic.

Note that the input cannot contain newline characters, and A and a are different characters (grouping is case-sentitive).

Shortest code in bytes wins.

Test cases

In each test case, first line is input, and the remaining lines are the output, with each group in a different line.

Test case 1:

```
Ah, abracadabra!
!
,
A
aaaaa
bb
c
d
h
rr
```

Test case 2:

```
\o/\o/\o/
///
\\\
ooo
```

Test case 3:

```
A man, a plan, a canal: Panama!
!
,,
:
A
P
aaaaaaaaa
c
ll
mm
nnnn
p
```

Test case 4:

```
"Show me how you do that trick, the one that makes me scream" she said
""
,
S
aaaaa
cc
dd
eeeeeee
hhhhhh
ii
kk
mmmm
n
ooooo
rr
ssss
tttttt
u
ww
y
```

Body:
Oracle SQL 11.2, 123 bytes

SELECT LISTAGG(c)WITHIN GROUP(ORDER BY 1)FROM(SELECT SUBSTR(:1,LEVEL,1)c FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))GROUP BY c;

Un-golfed

SELECT LISTAGG(c)WITHIN GROUP(ORDER BY 1)
FROM (SELECT SUBSTR(:1,LEVEL,1)c FROM DUAL CONNECT BY LEVEL<=LENGTH(:1))
GROUP BY c


答:
Scala, 317 characters

```<code>val a=input.split("\n");val e=a.map{s=>(s.indexOf("#"),s.lastIndexOf("#"))}.zipWithIndex.filter(_._1._1!= -1);val b=(e.map{s=>s._1._1}.min,e.map{s=>s._1._2}.max,e.head._2,e.last._2);print((0 to a.length-1).map{y=>(0 to a(y).length-1).map{x=>if(x>=b._1&&x<=b._2&&y>=b._3&&y<=b._4)"#" else "."}.mkString+"\n"}.mkString)
</code>```

More readable version, could probably have golfed it more:

```<code>val a=input.split("\n")
val e=a.map{s=>
    (s.indexOf("#"),s.lastIndexOf("#"))
}.zipWithIndex        // Need the indexes for the Y values
.filter(_._1._1!= -1) // Ugly because of tupleception: (actual tuple, index)

val b=(
    e.map{s=>s._1._1}.min,
    e.map{s=>s._1._2}.max,
    e.head._2,
    e.last._2)

print(
    (0 to a.length-1).map{y=>
        (0 to a(y).length-1).map{x=>
            if(x>=b._1&&x<=b._2&&y>=b._3&&y<=b._4)"#"
            else "."
        }.mkString+"\n"
    }.mkString
)
</code>```

Body:
Scala, 317 characters

val a=input.split("\n");val e=a.map{s=>(s.indexOf("#"),s.lastIndexOf("#"))}.zipWithIndex.filter(_._1._1!= -1);val b=(e.map{s=>s._1._1}.min,e.map{s=>s._1._2}.max,e.head._2,e.last._2);print((0 to a.length-1).map{y=>(0 to a(y).length-1).map{x=>if(x>=b._1&&x<=b._2&&y>=b._3&&y<=b._4)"#" else "."}.mkString+"\n"}.mkString)

More readable version, could probably have golfed it more:

val a=input.split("\n")
val e=a.map{s=>
    (s.indexOf("#"),s.lastIndexOf("#"))
}.zipWithIndex        // Need the indexes for the Y values
.filter(_._1._1!= -1) // Ugly because of tupleception: (actual tuple, index)

val b=(
    e.map{s=>s._1._1}.min,
    e.map{s=>s._1._2}.max,
    e.head._2,
    e.last._2)

print(
    (0 to a.length-1).map{y=>
        (0 to a(y).length-1).map{x=>
            if(x>=b._1&&x<=b._2&&y>=b._3&&y<=b._4)"#"
            else "."
        }.mkString+"\n"
    }.mkString
)


答:
JavaScript (ES6), 168 bytes

```<code>s=>/^#/gm.test(s)?/#$/gm.test(s)?s.replace(/^.*#[^]*#.*$/m,s=>s.replace(/./g,'#'))?f(s.replace(/.$/gm,'')).replace(/$/gm,'.'):f(s.replace(/^./gm,'')).replace(/^/gm,'.')
</code>```

Takes input as a multiline string. Works by recursively stripping leading and trailing .s from all lines until at least one line begins and one ends with a #, then selects as many lines as possible but starting and finishing on lines containing # and changes all the .s to #. Probably readily golfable.

Body:
JavaScript (ES6), 168 bytes

s=>/^#/gm.test(s)?/#$/gm.test(s)?s.replace(/^.*#[^]*#.*$/m,s=>s.replace(/./g,'#'))?f(s.replace(/.$/gm,'')).replace(/$/gm,'.'):f(s.replace(/^./gm,'')).replace(/^/gm,'.')

Takes input as a multiline string. Works by recursively stripping leading and trailing .s from all lines until at least one line begins and one ends with a #, then selects as many lines as possible but starting and finishing on lines containing # and changes all the .s to #. Probably readily golfable.


答:
C, <s>217</s> 189 bytes

Standalone version :

```<code>int a(char*b){int c=strlen(b);for(int i=0;i<c/2;i++)if(b[i]!=b[c-i-1])return 0;}int main(int e,char **f){int b,c;char d[9];b=atoi(f[1]);c=b;while(1){sprintf(d,"%d",c);if(a(d)&&(c/b)*b==c)return printf("%d",c);c++;}}
</code>```

Call to a function version :

```<code>int s(char*a){int b=strlen(a);for(int i=0;i<b/2;i++)if(a[i]!=a[b-i-1])return 0;}int f(int a){int b;char c[9];b=a;while(1){sprintf(c,"%d",b);if(s(c)&&(b/a)*a==b)return printf("%d",b);b++;}}
</code>```

Ungolfed :

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

int check_palindrome(char *str) {
  int length = strlen(str);

  for (int i = 0; i < length / 2; i++) {
    if (str[i] != str[length - i - 1])
      return 0;
  }
  return 1;
}

int main(int argc, char **argv) {
  int number;
  int pal;
  char string[15];

  number = atoi(argv[1]);
  pal = number;
  while (1) {
    sprintf(string, "%d", pal);
    if (check_palindrome(string) && (pal / number) * number == pal)
      {
        printf("%d\n", pal);
        return 1;
      }
    pal++;
  }
  return 0;
}
</code>```

Call to a function ungolfed :

```<code>int s(char *a) {
  int b = strlen(a);

  for (int i = 0; i < b / 2; i++) {
    if (a[i] != a[b - i - 1])
      return 0;
  }
  return 1; //We can remove it, it leads to a undefined behaviour but it works
}

int f(int a) {
  int b;
  char c[9];

  b = a;
  while (1) {
    sprintf(c, "%d", b);
    if (s(c) && (b / a) * a == b)
      {
        printf("%d\n", b); //no need for the \n
        return 1; //just return whatever printf returns, who cares anyway ?
      }
    b++;
  }
  return 0; //no need for that
}
</code>```

I included the standalone version for historicity.

This is my first codegolf, any comment is welcome !

Body:
C, <s>217</s> 189 bytes

Standalone version :

int a(char*b){int c=strlen(b);for(int i=0;i<c/2;i++)if(b[i]!=b[c-i-1])return 0;}int main(int e,char **f){int b,c;char d[9];b=atoi(f[1]);c=b;while(1){sprintf(d,"%d",c);if(a(d)&&(c/b)*b==c)return printf("%d",c);c++;}}

Call to a function version :

int s(char*a){int b=strlen(a);for(int i=0;i<b/2;i++)if(a[i]!=a[b-i-1])return 0;}int f(int a){int b;char c[9];b=a;while(1){sprintf(c,"%d",b);if(s(c)&&(b/a)*a==b)return printf("%d",b);b++;}}

Ungolfed :

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int check_palindrome(char *str) {
  int length = strlen(str);

  for (int i = 0; i < length / 2; i++) {
    if (str[i] != str[length - i - 1])
      return 0;
  }
  return 1;
}

int main(int argc, char **argv) {
  int number;
  int pal;
  char string[15];

  number = atoi(argv[1]);
  pal = number;
  while (1) {
    sprintf(string, "%d", pal);
    if (check_palindrome(string) && (pal / number) * number == pal)
      {
        printf("%d\n", pal);
        return 1;
      }
    pal++;
  }
  return 0;
}

Call to a function ungolfed :

int s(char *a) {
  int b = strlen(a);

  for (int i = 0; i < b / 2; i++) {
    if (a[i] != a[b - i - 1])
      return 0;
  }
  return 1; //We can remove it, it leads to a undefined behaviour but it works
}

int f(int a) {
  int b;
  char c[9];

  b = a;
  while (1) {
    sprintf(c, "%d", b);
    if (s(c) && (b / a) * a == b)
      {
        printf("%d\n", b); //no need for the \n
        return 1; //just return whatever printf returns, who cares anyway ?
      }
    b++;
  }
  return 0; //no need for that
}

I included the standalone version for historicity.

This is my first codegolf, any comment is welcome !


答:
Pyth, <s>27</s> 25 bytes

```<code>jmsm?|qFKaLJ/Q2,dk}JKN\ Q
</code>```

Try it online!

Probably golfable.

Title: Creating a Crossed Square

Body:
Pyth, <s>27</s> 25 bytes

jmsm?|qFKaLJ/Q2,dk}JKN\ Q

Try it online!

Probably golfable.


答:
Jelly, <s>21</s> <s>19</s> <s>18</s> 17 bytes

```<code>|/Tr/FṬ|
ỴµZÇZ&ÇY
</code>```

This is a full program. Input and output are strings of 0's and 1's, delimited by linefeeds.

Try it online! or verify all test cases.

How it works

```<code>ỴµZÇZ&ÇY  Main link. Argument: s (string)

Ỵ         Split s at linefeeds into the array A.
 µ        Begin a new, monadic chain. Argument: A
  Z       Zip/transpose A.
   Ç      Apply the helper link to the transpose.
    Z     Zip/transpose to restore the original order.
      Ç   Apply the helper link to A.
     &    Take the bitwise AND of both results.
       Y  Join, separating by linefeeds.

|/Tr/FṬ|  Helper link. Argument: A (array of strings)

|/        Reduce A columnwise by bitwise OR. This casts to integer.
  T       Truth; yield the indices of 1's.
   r/     Reduce by range. This yields an exponentially growing, nested, ragged
          array that contains all integers between the lowest and highest index
          in the previous result, at least once but possibly multiple times.
     F    Flatten the result.
      Ṭ   Untruth; yield an array with 1's at the specified indices.
          Multiple occurrences of the same index are ignored.
       |  Take the bitwise OR of the result and each row of A.
</code>```

Body:
You're given a rectangular grid of the characters . and #, like this:

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

Your task is to fill the entire axis-aligned bounding box of the # with further #:

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

The axis-aligned bounding box is the smallest rectangle which contains all the #.

Want more? Try Part II!

Rules

You may use any two distinct printable ASCII characters (0x20 to 0x7E, inclusive), in place of # and .. I'll continue referring to them as # and . for the remainder of the specification though.

Input and output may either be a single linefeed-separated string or a list of strings (one for each line), but the format has to be consistent.

You may assume that the input contains at least one # and all lines are the same length.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

Each test case has input and output next to each other.

```<code>#    #

...    ...
#..    #..
...    ...

...    ...
#..    ###
..#    ###

.#.    ###
#..    ###
..#    ###

.....    .....
.#.#.    .###.
.....    .....

...    ...
.#.    .#.
...    .#.
.#.    .#.
...    ...

..........    ..........
..........    ..........
....#.....    ....#.....
..........    ..........

..........    ..........
..........    ..........
....#.....    ...##.....
...#......    ...##.....

..........    ..........
..#.......    ..###.....
....#.....    ..###.....
...#......    ..###.....

..........    ..........
..#.......    ..######..
....#..#..    ..######..
...#......    ..######..

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

Body:
Jelly, <s>21</s> <s>19</s> <s>18</s> 17 bytes

|/Tr/FṬ|
ỴµZÇZ&ÇY

This is a full program. Input and output are strings of 0's and 1's, delimited by linefeeds.

Try it online! or <a href="http://jelly.tryitonline.net/#code=fC9Uci9G4bmsfArhu7TCtVrDh1omw4dZCsWT4bmj4oCcwrbCtuKAncOH4oKsauKAnMK2wrbigJ0&input=&args=MQoKMDAwCjEwMAowMDAKCjAwMAoxMDAKMDAxCgowMTAKMTAwCjAwMQoKMDAwMDAKMDEwMTAKMDAwMDAKCjAwMAowMTAKMDAwCjAxMAowMDAKCjAwMDAwMDAwMDAKMDAwMDAwMDAwMAowMDAwMTAwMDAwCjAwMDAwMDAwMDAKCjAwMDAwMDAwMDAKMDAwMDAwMDAwMAowMDAwMTAwMDAwCjAwMDEwMDAwMDAKCjAwMDAwMDAwMDAKMDAxMDAwMDAwMAowMDAwMTAwMDAwCjAwMDEwMDAwMDAKCjAwMDAwMDAwMDAKMDAxMDAwMDAwMAowMDAwMTAwMTAwCjAwMDEwMDAwMDAKCjAwMDAwMDAwMDEKMDAxMDAwMDAwMAowMDAwMTAwMTAwCjAwMDEwMDAwMDA" rel="nofollow">verify all test cases.

How it works

ỴµZÇZ&ÇY  Main link. Argument: s (string)

Ỵ         Split s at linefeeds into the array A.
 µ        Begin a new, monadic chain. Argument: A
  Z       Zip/transpose A.
   Ç      Apply the helper link to the transpose.
    Z     Zip/transpose to restore the original order.
      Ç   Apply the helper link to A.
     &    Take the bitwise AND of both results.
       Y  Join, separating by linefeeds.

|/Tr/FṬ|  Helper link. Argument: A (array of strings)

|/        Reduce A columnwise by bitwise OR. This casts to integer.
  T       Truth; yield the indices of 1's.
   r/     Reduce by range. This yields an exponentially growing, nested, ragged
          array that contains all integers between the lowest and highest index
          in the previous result, at least once but possibly multiple times.
     F    Flatten the result.
      Ṭ   Untruth; yield an array with 1's at the specified indices.
          Multiple occurrences of the same index are ignored.
       |  Take the bitwise OR of the result and each row of A.


答:
Q

Assuming builtins are allowed and x,y data are seperate vectors (7 chars):

```<code>x cor y
</code>```

If data are stored as orderded pairs, as indicated by David Carraher, we get (for 12 characters):

```<code>{(cor).(+)x}
</code>```

Title: Calculate the correlation coefficient

Body:
Given a series of numbers for events X and Y, calculate Pearson's correlation coefficient. The probability of each event is equal, so expected values can be calculated by simply summing each series and dividing by the number of trials.

Input

```<code>1   6.86
2   5.92
3   6.08
4   8.34
5   8.7
6   8.16
7   8.22
8   7.68
9   12.04
10  8.6
11  10.96
</code>```

Output

```<code>0.769
</code>```

Shortest code wins. Input can be by stdin or arg. Output will be by stdout.

Edit: Builtin functions should not be allowed (ie calculated expected value, variance, deviation, etc) to allow more diversity in solutions. However, feel free to demonstrate a language that is well suited for the task using builtins (for exhibition).

Based on David's idea for input for Mathematica (86 char using builtin mean)

```<code>m=Mean;x=d[[All,1]];y=d[[All,2]];(m@(x*y)-m@x*m@y)/Sqrt[(m@(x^2)-m@x^2)(m@(y^2)-m@y^2)]

m = Mean;
x = d[[All,1]];
y = d[[All,2]];
(m@(x*y) - m@x*m@y)/((m@(x^2) - m@x^2)(m@(y^2) - m@y^2))^.5
</code>```

Skirting by using our own mean (101 char)

```<code>m=Total[#]/Length[#]&;x=d[[All,1]];y=d[[All,2]];(m@(x*y)-m@x*m@y)/((m@(x^2)-m@x^2)(m@(y^2)-m@y^2))^.5

m = Total[#]/Length[#]&;
x = d[[All,1]];
y = d[[All,2]];
(m@(x*y)-m@x*m@y)/((m@(x^2)-m@x^2)(m@(y^2)-m@y^2))^.5
</code>```

Body:
Q

Assuming builtins are allowed and x,y data are seperate vectors (7 chars):

x cor y

If data are stored as orderded pairs, as indicated by David Carraher, we get (for 12 characters):

{(cor).(+)x}


答:
Swift, 142 bytes

```<code>func f(a:Int,b:Int)->Array<Int>{let p={(n:Int)->Int in([Int]()+(2..<n)).filter{n%$0<1}.count}
return([Int]()+(2...b)).filter{p($0)+p($0+a)<1}}
</code>```

Title: Variable Prime "Twins"

Body:
I am 2/3 twins with my brother, i.e. born on the same day of the same month but twelve years later. When I was 5, he was 17, both primes; the last pair of ages we can reasonably count on is [71, 83] with both of us being alive and able to celebrate this coincidental jubilee.

Task

Create a code that

takes two integers as input: the difference between the counter and the "twin" as a positive integer k (well yes, I'm the younger) and the upper bound as a positive integer u (runtime consideration)

and gives output as an array or list of all i numbers lower than or equal u for which both i and i+k are primes. The output does not need to be sorted.

Test Cases

```<code>12, 1000 -> [5, 7, 11, 17, 19, 29, 31, 41, 47, 59, 61, 67, 71, 89, 97, 101, 127, 137, 139, 151, 167, 179, 181, 199, 211, 227, 229, 239, 251, 257, 269, 271, 281, 337, 347, 367, 389, 397, 409, 419, 421, 431, 449, 467, 479, 487, 491, 509, 557, 587, 601, 607, 619, 631, 641, 647, 661, 727, 739, 757, 761, 797, 809, 811, 827, 907, 929, 941, 971, 997]
2, 999 -> [3, 5, 11, 17, 29, 41, 59, 71, 101, 107, 137, 149, 179, 191, 197, 227, 239, 269, 281, 311, 347, 419, 431, 461, 521, 569, 599, 617, 641, 659, 809, 821, 827, 857, 881]
3, 1500 -> [2]
30, 1500 -> [7, 11, 13, 17, 23, 29, 31, 37, 41, 43, 53, 59, 67, 71, 73, 79, 83, 97, 101, 107, 109, 127, 137, 149, 151, 163, 167, 181, 193, 197, 199, 211, 227, 233, 239, 241, 251, 263, 277, 281, 283, 307, 317, 337, 349, 353, 359, 367, 379, 389, 401, 409, 419, 431, 433, 449, 457, 461, 479, 491, 541, 547, 557, 563, 569, 571, 577, 587, 601, 613, 617, 631, 643, 647, 653, 661, 709, 727, 739, 743, 757, 797, 809, 823, 827, 829, 853, 857, 877, 881, 907, 911, 937, 941, 947, 953, 967, 983, 991, 1009, 1019, 1021, 1031, 1033, 1039, 1061, 1063, 1087, 1093, 1123, 1151, 1163, 1171, 1187, 1193, 1201, 1229, 1249, 1259, 1277, 1289, 1291, 1297, 1399, 1409, 1423, 1429, 1451, 1453, 1459, 1481, 1493]
</code>```

Edit

Since I failed to specify the upper bound, both inclusive and exclusive solutions are welcome.

Edit No. 2

The challenge ends on 1st September, one week from the start.

Looks like we have a winner but in case of a tie popularity is the tie-breaker; in this case the "second" will be compensated via bounty.

Body:
Swift, 142 bytes

func f(a:Int,b:Int)->Array<Int>{let p={(n:Int)->Int in([Int]()+(2..<n)).filter{n%$0<1}.count}
return([Int]()+(2...b)).filter{p($0)+p($0+a)<1}}


问:
Together Everyone Achieves More
(related: one, two, three)

An acrostic is a style of poem/writing where the beginning character of each line, when read vertically, also produces a word or message. For example,

```<code>Together
Everyone
Achieves
More
</code>```

also spells out the word TEAM when the first column is read vertically.

Acrostics are a subset of mesostics, where the vertical word can be anywhere in the horizontal words. For example, the TEAM one above could also be written as a mesostic as follows

```<code>   togeTher
everyonE
       Achieves
       More
</code>```

along with several other variations.

The challenge here will be to produce an acrostic or mesostic from a given list of input words.

Input

A list of words in any any suitable format.

The list will only contain words made from lowercase [a-z].

The list is guaranteed to form an acrostic or a mesostic (no need to handle bogus input).

One of the words in the input will form the vertical word, while the rest make the horizontal words - part of the challenge here is to find the appropriate vertical word, so it cannot be taken separately.

Output

The ASCII-art acrostic or mesostic formed from the input words, written to STDOUT or returned, in any reasonable format.

The corresponding vertical word must be capitalized (as in the examples).

Leading spaces to get the vertical word to line up appropriately are required. Trailing spaces, and leading/trailing newlines are optional. Extra leading spaces are fine as well, so long as the words align correctly.

If both an acrostic and mesostic are possible, output only the acrostic.

If more than one acrostic/mesostic is possible, your code can output any or all of them.

Rules

Either a full program or a function are acceptable.

Standard loopholes are forbidden.

This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples

```<code>['together', 'team', 'everyone', 'achieves', 'more']
Together
Everyone
Achieves
More

['aaa', 'aaa', 'aaa', 'aaa']
Aaa
Aaa
Aaa
# One output, or multiple (of the same) output is allowed

['aaa', 'aaa', 'aab', 'baa']
Aaa
Aaa
Baa
# This is the only allowed output, since others would be mesostic, which are lower priority

['live', 'every', 'love', 'very', 'ohio']
Live
Ohio
Very
Every
# Note that 'live' couldn't be the vertical word since then it would be a mesostic, which is lower priority output

['cow', 'of', 'fox']
cOw
 Fox
# A shorter mesostic test case

['late', 'ballroom', 'anvil', 'to', 'head']
anviL
   bAllroom
    To
   hEad
</code>```

答:
Haskell, <s>214</s> <s>206</s> <s>204</s> 202 bytes

```<code>import Data.List
z=zipWith
h i j t|(u,v:w)<-splitAt j t=([1..sum i-j]>>" ")++u++toEnum(fromEnum v-32):w
f x=uncurry(z=<<h)$sort[(head<$>z elemIndices w l,l)|w:l<-permutations x,(True<$w)==z elem w l]!!0
</code>```

Returns a list of space padded strings, e.g. f ["late","ballroom","anvil","to","head"] -> [" baLlroom","   Anvil","   To","  hEad"] or more display friendly:

```<code>*Main> mapM_ putStrLn $ f ["late", "ballroom", "anvil", "to", "head"]
 baLlroom
   Anvil
   To
  hEad
</code>```

f selects the words that are written horizontally together with a list of offsets. h pads each word according to the corresponding offset and inserts the uppercase letter. In detail:

```<code>                permutations x       -- for each permutation of the input list x
         w:l<-                       -- bind w to the first word and l to the rest
             (True<$w)==z elem w l   -- keep it if the list of other words
                                     -- containing the next letter of w
                                     -- equals (length w) times True, i.e. we have
                                     -- as many matching letters as letters in w.
                                     -- This rules out combinations shortcut by zipWith

                                     -- for all the remaining w and l make a pair
         head<$>z elemIndices w l    -- the first element of the list of list of
                                     -- indices where the letter appears in the word
                                l    -- and l itself
   sort                              -- sort the pairs (all 0 indices, i.e. acrostics
                                     -- go first)
                               !!0   -- pick the first
                                     -- now we have a pair like
                                     -- ([2,0,0,1],["ballroom","anvil","to","head"])
 uncurry(z=<<h)                      -- loop over (index,word) and
                                     -- provide the third parameter for h

 h i j t                             -- h takes the list of indices and
                                     -- an index j and a word t
       (u,v:w)<-splitAt j t          -- split the word at the index and bind
                                     --   u: part before the split
                                     --   v: letter at the split
                                     --   w: part after the split
         [1..sum i-j]>>" "           -- the spaces to pad
           ++ u                      -- followed by u
           ++ toEnum(fromEnum v-32)  -- and uppercase v
           :                         -- and w
</code>```

Title: Together Everyone Achieves More

Body:
Haskell, <s>214</s> <s>206</s> <s>204</s> 202 bytes

import Data.List
z=zipWith
h i j t|(u,v:w)<-splitAt j t=([1..sum i-j]>>" ")++u++toEnum(fromEnum v-32):w
f x=uncurry(z=<<h)$sort[(head<$>z elemIndices w l,l)|w:l<-permutations x,(True<$w)==z elem w l]!!0

Returns a list of space padded strings, e.g. f ["late","ballroom","anvil","to","head"] -> [" baLlroom","   Anvil","   To","  hEad"] or more display friendly:

*Main> mapM_ putStrLn $ f ["late", "ballroom", "anvil", "to", "head"]
 baLlroom
   Anvil
   To
  hEad

f selects the words that are written horizontally together with a list of offsets. h pads each word according to the corresponding offset and inserts the uppercase letter. In detail:

                permutations x       -- for each permutation of the input list x
         w:l<-                       -- bind w to the first word and l to the rest
             (True<$w)==z elem w l   -- keep it if the list of other words
                                     -- containing the next letter of w
                                     -- equals (length w) times True, i.e. we have
                                     -- as many matching letters as letters in w.
                                     -- This rules out combinations shortcut by zipWith

                                     -- for all the remaining w and l make a pair
         head<$>z elemIndices w l    -- the first element of the list of list of
                                     -- indices where the letter appears in the word
                                l    -- and l itself
   sort                              -- sort the pairs (all 0 indices, i.e. acrostics
                                     -- go first)
                               !!0   -- pick the first
                                     -- now we have a pair like
                                     -- ([2,0,0,1],["ballroom","anvil","to","head"])
 uncurry(z=<<h)                      -- loop over (index,word) and
                                     -- provide the third parameter for h

 h i j t                             -- h takes the list of indices and
                                     -- an index j and a word t
       (u,v:w)<-splitAt j t          -- split the word at the index and bind
                                     --   u: part before the split
                                     --   v: letter at the split
                                     --   w: part after the split
         [1..sum i-j]>>" "           -- the spaces to pad
           ++ u                      -- followed by u
           ++ toEnum(fromEnum v-32)  -- and uppercase v
           :                         -- and w


Title: Creating a Crossed Square

Body:
Creating a Crossed Square

You are to take input of an integer of one or more and output a square made of any printable character of your choice with a diagonal cross through the centre.

The general idea is for the output to be a hollow square that has a diagonal cross through it.:

```<code>Input: 7
Output:
*******
*#   #*
* # # *
*  #  *
* # # *
*#   #*
*******
</code>```

In the above example the '*'s represent the outer box and the '#'s represent the diagonal cross.

Note that the above example uses two different characters so that it is easier to see what the output looks like, your program should use one character only.

Input

An integer of 1 or more, it is guaranteed to be odd.

Output

A square that is made up of a character of your choice with a cross through the middle.

The cross must be diagonal

The square may be output via the function or written to output

Trailing newlines are okay

Can output as a graphic, diagram or image if you wish too

Examples

```<code>Input: 1
Output:
*

Input: 3
Output:
***
***
***

Input: 5
Output:
*****
** **
* * *
** **
*****

Input: 7
Output:
*******
**   **
* * * *
*  *  *
* * * *
**   **
*******
</code>```

Specs

Functions or full programs are allowed

You can get input by your preferred means

Standard loopholes are disallowed

Programs must work without any additional statements i.e. usings in C#, they must be included in the entry

You can output from a function or print the result

This is code golf so the shortest solution wins.

Body:
PowerShell (133)

filter s($x){1..$x|%{$o="";$r=$_;1..$x|%{if($_-eq1-or$r-eq1-or$_-eq$x-or$r-eq$x-or$r-eq$_-or$r-1-eq$x-$_){$o+="*"}else{$o+="_"}};$o}}

Clunky, but it works well enough.

s(11)
***********
**_______**
*_*_____*_*
*__*___*__*
*___*_*___*
*____*____*
*___*_*___*
*__*___*__*
*_*_____*_*
**_______**
***********

Golfing suggestions definitely welcome, it's been too long since I've PowerShell'd.


答:
Python 3, <s>114</s> <s>92</s> 90 bytes

Thanks to @Dennis for -2 bytes

```<code>def f(k,u):
 i=P=1;l={0}
 while i<u+k:l|={P%i*i};P*=i*i;i+=1
 return{i-k for i in l}&l-{0}
</code>```

A function that takes input via argument and returns an unsorted set. This is exclusive with respect to the upper bound.

This uses the method in @xnor's answer here to find primes.

Try it on Ideone

How it works

Prime finding

We first initialise a test value i and a product P as 1, and a list of primes l as the set containing 0. Then, a while loop that tests all values of i in the range [1, u+k-1] for primality is executed. The idea is that by multiplying P by i^2 at the end of each iteration, P takes the value (i-1)!^2 while testing i, i.e the product of the integers [1, i+1] squared. The actual primality test is then performed by calculating P mod i; if this returns zero, then i cannot be prime since this implies that i is divisible by at least one of the values that make up the product. If this returns 1, then i must be prime since it is not divisible by any of the values in the product. If i is prime, it is appended to l, and if not, 0 is appended. The squaring of the product prevents false identification of 4 as prime, and is useful here since it guarantees that only 0 or 1 will be returned, allowing the choice of the value to be appended to be made by simply multiplying the result by i.

Identification of 'twin' primes

We now create a furter set, containing all the elements of l-k, element-wise. The intersection of this set and l is then found using &, which leaves a set containing only the elements common to both sets. A number i is only in both sets if both i and i+k are prime, meaning that this leaves the desired output. However, if k is prime, 0 will be present in both sets, meaning that this must be removed before returning.

Title: Variable Prime "Twins"

Body:
Python 3, <s>114</s> <s>92</s> 90 bytes

Thanks to @Dennis for -2 bytes

def f(k,u):
 i=P=1;l={0}
 while i<u+k:l|={P%i*i};P*=i*i;i+=1
 return{i-k for i in l}&l-{0}

A function that takes input via argument and returns an unsorted set. This is exclusive with respect to the upper bound.

This uses the method in @xnor's answer here to find primes.

Try it on Ideone

How it works

Prime finding

We first initialise a test value i and a product P as 1, and a list of primes l as the set containing 0. Then, a while loop that tests all values of i in the range [1, u+k-1] for primality is executed. The idea is that by multiplying P by i^2 at the end of each iteration, P takes the value (i-1)!^2 while testing i, i.e the product of the integers [1, i+1] squared. The actual primality test is then performed by calculating P mod i; if this returns zero, then i cannot be prime since this implies that i is divisible by at least one of the values that make up the product. If this returns 1, then i must be prime since it is not divisible by any of the values in the product. If i is prime, it is appended to l, and if not, 0 is appended. The squaring of the product prevents false identification of 4 as prime, and is useful here since it guarantees that only 0 or 1 will be returned, allowing the choice of the value to be appended to be made by simply multiplying the result by i.

Identification of 'twin' primes

We now create a furter set, containing all the elements of l-k, element-wise. The intersection of this set and l is then found using &, which leaves a set containing only the elements common to both sets. A number i is only in both sets if both i and i+k are prime, meaning that this leaves the desired output. However, if k is prime, 0 will be present in both sets, meaning that this must be removed before returning.


答:
ARM Machine Code, 26 bytes

Hex dump (little endian):

```<code>6810 4601 f852 cb04 4560 bfc8 4660 4561 bfb8 4661 3b01 d8f5 4770
</code>```

This is a function, with no system call or library dependence. The encoding is Thumb-2, a variable (2 or 4 byte) encoding for 32-bit ARM. As one might imagine, there's no easy way to just sort and pick the first and last elements here. Overall there's nothing really that fancy going on here, it's more or less the same as the reference implementation.

Ungolfed assembly (GNU syntax):

```<code>.syntax unified
.text
.global minmax
.thumb_func
minmax:
    @Input: @r0 and r1 are dummy parameters (they don't do anything)
    @r2 - Pointer to list of integers (int*)
    @r3 - Number of integers to sort (size_t)
    @Output:
    @Minimum of the list in r0 (int)
    @Maximum in r1 (int)
    ldr r0,[r2] @min=r2[0]
    mov r1,r0 @max=min
    loop:
        @ip is intra-procedure call register, a.k.a. r12
        ldr ip,[r2],#4 @ip=*r2++
        cmp r0,ip
        it gt @if (r0>ip)
        movgt r0,ip @r0=ip
        cmp r1,ip
        it lt @if (r1<ip)
        movlt r1,ip @r1=ip
        subs r3,r3,#1
        bhi loop @while (--r3>0)
    bx lr @Return
</code>```

Tested on the Raspberry Pi 3; here's the testing script (C99, input through argv):

```<code>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
//First 2 arguments are dummies.
uint64_t minmax(int,int,int* array,size_t size);

int main(int argc,char** argv) {
    int i;
    int array[argc-1];
    for (i=1;i<argc;i++) {
        array[i-1]=atoi(argv[i]);
    }
    uint64_t result = minmax(0,0,array,argc-1);
    printf("Minimum is %d, maximum is %d.\n",(unsigned)result,(unsigned)(result>>32));
}
</code>```

Title: Find the minimum and maximum integers in an array, without using builtins

Body:
Challenge

Given an array of integers, received from stdin, function arguments, program arguments, or some other method:

Output only the minimum and maximum numbers in the array, through a return value, stdout, or other fitting methods.

Example session

```<code>> minmax( {0, 15, 2, 3, 7, 18, -2, 9, 6, -5, 3, 8, 9, -14} )
-14 18
</code>```

Reference implementation

```<code>// C++14

void minmax(std::vector<int> v) {
    int min = v[0]; int max = v[0];
    for(auto it : v) {
        if (*it < min)
            min = *it;
        if (*it > max)
            max = *it;
    }
    std::cout << min << ' ' << max << std::endl;
}
</code>```

Rules

You may not use a built-in function to calculate the values.

Standard loopholes disallowed.

Creative implementations encouraged.

This is code-golf, shortest answer wins but will not be selected.

Clarifications

If the array contains 1 element you need to output it twice.

If the minimum and maximum values are the same, you need to output them both.

Body:
ARM Machine Code, 26 bytes

Hex dump (little endian):

6810 4601 f852 cb04 4560 bfc8 4660 4561 bfb8 4661 3b01 d8f5 4770

This is a function, with no system call or library dependence. The encoding is Thumb-2, a variable (2 or 4 byte) encoding for 32-bit ARM. As one might imagine, there's no easy way to just sort and pick the first and last elements here. Overall there's nothing really that fancy going on here, it's more or less the same as the reference implementation.

Ungolfed assembly (GNU syntax):

.syntax unified
.text
.global minmax
.thumb_func
minmax:
    @Input: @r0 and r1 are dummy parameters (they don't do anything)
    @r2 - Pointer to list of integers (int*)
    @r3 - Number of integers to sort (size_t)
    @Output:
    @Minimum of the list in r0 (int)
    @Maximum in r1 (int)
    ldr r0,[r2] @min=r2[0]
    mov r1,r0 @max=min
    loop:
        @ip is intra-procedure call register, a.k.a. r12
        ldr ip,[r2],#4 @ip=*r2++
        cmp r0,ip
        it gt @if (r0>ip)
        movgt r0,ip @r0=ip
        cmp r1,ip
        it lt @if (r1<ip)
        movlt r1,ip @r1=ip
        subs r3,r3,#1
        bhi loop @while (--r3>0)
    bx lr @Return

Tested on the Raspberry Pi 3; here's the testing script (C99, input through argv):

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
//First 2 arguments are dummies.
uint64_t minmax(int,int,int* array,size_t size);

int main(int argc,char** argv) {
    int i;
    int array[argc-1];
    for (i=1;i<argc;i++) {
        array[i-1]=atoi(argv[i]);
    }
    uint64_t result = minmax(0,0,array,argc-1);
    printf("Minimum is %d, maximum is %d.\n",(unsigned)result,(unsigned)(result>>32));
}


问:
Implement a Truth-Machine
A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

Gets a number (either 0 or 1) from STDIN.

If that number is 0, print out 0 and terminate.

If that number is 1, print out 1 forever.

Challenge

Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

take input from STDIN or an acceptable alternative

If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program

must output to STDOUT or an acceptable alternative

If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.

when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory

the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of code-golf must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Shakespeare Programming Language, 189 bytes

```<code>.
Ajax,.
Ford,.
Act I:.
Scene I:.
[Enter Ajax and Ford]
Ford:
Listen to thy heart.
Scene II:.
Ford:
Open thy heart.Is cat as big as you?If so, let us return to scene II.
[Exeunt]
</code>```

Ungolfed:

```<code>The Construction of a Truth-Machine in Denmark.

Hamlet, the input.
Ophelia, who orders him around.

Act I: A truth-machine.

Scene I: In which Hamlet learns that all he needs, he can find in his heart.

[Enter Hamlet and Ophelia]

Ophelia:
  Listen to thy heart.

Scene II: In which Ophelia proclaims her doubts about Hamlet.

Ophelia:
  Open thy heart. Is my lover as fair as thee?
  If so, let us return to scene II.

[Exeunt]
</code>```

I'm using drsam94's SPL compiler + GCC to compile this.

To test:

```<code>$ python splc.py tm.spl > tm.c
$ gcc tm.c -o tm.exe
$ echo 0 | ./tm
0
$ echo 1 | ./tm
1111111111111111111111111111111111111111111111...
</code>```

Title: Implement a Truth-Machine

Body:
Shakespeare Programming Language, 189 bytes

.
Ajax,.
Ford,.
Act I:.
Scene I:.
[Enter Ajax and Ford]
Ford:
Listen to thy heart.
Scene II:.
Ford:
Open thy heart.Is cat as big as you?If so, let us return to scene II.
[Exeunt]

Ungolfed:

The Construction of a Truth-Machine in Denmark.

Hamlet, the input.
Ophelia, who orders him around.

Act I: A truth-machine.

Scene I: In which Hamlet learns that all he needs, he can find in his heart.

[Enter Hamlet and Ophelia]

Ophelia:
  Listen to thy heart.

Scene II: In which Ophelia proclaims her doubts about Hamlet.

Ophelia:
  Open thy heart. Is my lover as fair as thee?
  If so, let us return to scene II.

[Exeunt]

I'm using drsam94's SPL compiler + GCC to compile this.

To test:

$ python splc.py tm.spl > tm.c
$ gcc tm.c -o tm.exe
$ echo 0 | ./tm
0
$ echo 1 | ./tm
1111111111111111111111111111111111111111111111...


答:
Logo, 155 bytes

Graphical solution, implemented as a function

I retooled my answer for Alphabet Triangle and changed the angles around a bit.  As before, r draws a line of characters.  This time, the b function draws a box by drawing one straight edge and one diagonal, rotating, and repeating four times.  This causes the diagonals to be drawn twice (on top of each other), but it was less code than handling it separately.  This answer also properly handles even numbers.  I had to add special handling for an input of 1 to prevent it from going forward.

I implemented it as a function, b which takes the size as an argument:

```<code>pu
to r:n:b:l repeat:n[rt:b label "A lt:b if repcount>1[fd:l]] end
to b:s
repeat 4[rt 90
r:s 90-heading 20 rt 135
r:s 90-heading 20*sqrt 2 rt 45]
end
</code>```

Try it out on Calormen.com's Logo interpreter.
To call it, append a line and call b in the following format:

```<code>b 7
</code>```

... or try the sampler platter, which draws four samples in sizes 5, 7, 9, and 11, rotating 90 degrees in between:

```<code>repeat 4[
  b repcount*2+3
  rt 90
]
</code>```

Title: Creating a Crossed Square

Body:
Logo, 155 bytes

Graphical solution, implemented as a function

I retooled my answer for Alphabet Triangle and changed the angles around a bit.  As before, r draws a line of characters.  This time, the b function draws a box by drawing one straight edge and one diagonal, rotating, and repeating four times.  This causes the diagonals to be drawn twice (on top of each other), but it was less code than handling it separately.  This answer also properly handles even numbers.  I had to add special handling for an input of 1 to prevent it from going forward.

I implemented it as a function, b which takes the size as an argument:

pu
to r:n:b:l repeat:n[rt:b label "A lt:b if repcount>1[fd:l]] end
to b:s
repeat 4[rt 90
r:s 90-heading 20 rt 135
r:s 90-heading 20*sqrt 2 rt 45]
end

Try it out on Calormen.com's Logo interpreter.
To call it, append a line and call b in the following format:

b 7

... or try the sampler platter, which draws four samples in sizes 5, 7, 9, and 11, rotating 90 degrees in between:

repeat 4[
  b repcount*2+3
  rt 90
]


答:
Python 2, 93 bytes

S=sorted
f=lambda n,i=1:n and-~f(n-(S(`i`)in[S(`k`)for k in range(9*i)if`k`==`k`[::-1]]),i+1)
```

<p>1-indexed. Depending on your system, the last test case may exceed the allowed recursion depth.</p>

<p>Does not compute permutations. Instead, uses the fact that two strings are permutations if they are equal when sorted. To test if a number is permutapalindromic, checks if its sorted digits equal the sorted digits of any palindrome up to a bound.</p>

<hr>

<p><strong>96 bytes:</strong></p>

<pre class="lang-python prettyprint-override"><code>f=lambda n,i=1:n and-~f(n-(sum(`i`.count(`d`)%2for d in range(10))<2*(set(`i`[1:])!={'0'})),i+1)
</code>```

1-indexed. Depending on your system, the last test case may exceed the allowed recursion depth.

This doesn't look at permutations and instead uses the following characterization:

A number is permutapalindromic exactly when

At most one of its digits appears an odd number of times, and

It does not have the form d00...00 with one or more zeroes.

This is true because a palindrome must pair off digits from the start and end, except for a possible center digit. The exception comes from the requirement that the leading digit be nonzero, and so some nonzero digit must appear twice unless the number is single-digit.

Title: Permutapalindromic numbers

Body:
Given an integer N as input, output the Nth permutapalindromic number.

A permutapalindromic number is a strictly positive integer such that there is at least one permutation of its digits that results in a palindrome (i.e. a number that is its own reverse).

For example, 117 is a permutapalindromic number since its digits can be permuted into 171, which is a palindrome.

We consider that numbers like 10 are not permutapalindromic numbers, even though 01 = 1 is a palindrome. We impose that the palindromic permutation must not have a leading zero (as such, 0 itself is not permutapalindromic).

Numbers that are already palindromes are also permutapalindromic, since permuting nothing is valid.

Inputs and outputs

N may be either 0-indexed or 1-indexed. Please indicate which of the two your answer uses.

The input can be taken through STDIN, as a function argument, or anything similar in your language of choice. The output can be written to STDOUT, returned from a function, or anything similar in your language of choice.

The input and output must be in the decimal base.

Test cases

The following test cases are 1-indexed. Your program must be able to pass any of the test cases presented here in at most 1 minute.

```<code>N      Output

1      1
2      2
3      3
4      4
5      5
6      6
7      7
8      8
9      9
10     11
42     181
100    404
128    511
256    994
270    1166
</code>```

Scoring

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

Body:
Python 2, 93 bytes

S=sorted
f=lambda n,i=1:n and-~f(n-(S(`i`)in[S(`k`)for k in range(9*i)if`k`==`k`[::-1]]),i+1)

1-indexed. Depending on your system, the last test case may exceed the allowed recursion depth.

Does not compute permutations. Instead, uses the fact that two strings are permutations if they are equal when sorted. To test if a number is permutapalindromic, checks if its sorted digits equal the sorted digits of any palindrome up to a bound.

96 bytes:

f=lambda n,i=1:n and-~f(n-(sum(`i`.count(`d`)%2for d in range(10))<2*(set(`i`[1:])!={'0'})),i+1)

1-indexed. Depending on your system, the last test case may exceed the allowed recursion depth.

This doesn't look at permutations and instead uses the following characterization:

A number is permutapalindromic exactly when

At most one of its digits appears an odd number of times, and

It does not have the form d00...00 with one or more zeroes.

This is true because a palindrome must pair off digits from the start and end, except for a possible center digit. The exception comes from the requirement that the leading digit be nonzero, and so some nonzero digit must appear twice unless the number is single-digit.


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

Please post one tip per answer.

答:
Find the n'th number meeting a condition

Many sequence challenges ask you to find the n'th number in a sequence of increasing positive integers. When you have a expression p(i) that checks membership, you can do this with the recursive function:

f=lambda n,i=1:n and-~f(n-p(i),i+1)
```

<p>Note that expression <code>p(i)</code> must give 0 or 1, not just Falsey or Truthy. The outputs are one-indexed, so say for the sequence of primes, it would give</p>

<pre class="lang-python prettyprint-override"><code>f(1) = 2
f(2) = 3
...
</code>```

For 0-indexed outputs, shift the base case

f=lambda n,i=1:n+1and-~f(n-p(i),i+1)
```

<p>The recursive function <code>f=lambda n,i=1:n and-~f(n-p(i),i+1)</code> works by decrementing the required count <code>n</code> each time it gets a hit, and incrementing the output value each time for each value it checks. It might seem weird to redundantly track <code>i</code>, but it's longer to do:</p>

<pre class="lang-python prettyprint-override"><code>f=lambda n,i=1:n and f(n-p(i),i+1)or~-i
</code>```

Also compare the natural list strategy (zero-indexed here)

lambda n:[i for i in range(n*n)if p(i)][n]
```

(You might need a larger bound than n*n.)

Title: Tips for golfing in Python

Body:
Find the n'th number meeting a condition

Many sequence challenges ask you to find the n'th number in a sequence of increasing positive integers. When you have a expression p(i) that checks membership, you can do this with the recursive function:

f=lambda n,i=1:n and-~f(n-p(i),i+1)

Note that expression p(i) must give 0 or 1, not just Falsey or Truthy. The outputs are one-indexed, so say for the sequence of primes, it would give

f(1) = 2
f(2) = 3
...

For 0-indexed outputs, shift the base case

f=lambda n,i=1:n+1and-~f(n-p(i),i+1)

The recursive function f=lambda n,i=1:n and-~f(n-p(i),i+1) works by decrementing the required count n each time it gets a hit, and incrementing the output value each time for each value it checks. It might seem weird to redundantly track i, but it's longer to do:

f=lambda n,i=1:n and f(n-p(i),i+1)or~-i

Also compare the natural list strategy (zero-indexed here)

lambda n:[i for i in range(n*n)if p(i)][n]

(You might need a larger bound than n*n.)