The highest prime factor of neighboring numbers I think it's easiest to explain this challenge in a sequential manner. Start with an input number \$N\$ and:

Find its highest prime factor
Check numbers above and below \$N\$ and see if the highest prime factor is higher (i.e. the highest prime factor of \$N-1\$ and/or \$N+1\$ is higher than the factor of \$N\$.
Continue to check higher and/or lower numbers neighboring \$N\$ in the directions where the highest factors are increasing (\$(N-2, N-3 ...)\$ and/or \$(N+2, N+3 ...)\$ and so on)
Once there aren't any prime factors in either direction that are higher than the ones we've already found we stop and output the highest prime factor we have encountered.

Let's look at an example:
245 has the prime factors 5, 7, 7. Its neighbors are:
244 -> 2,  2,  61
245 -> 5,  7,  7
246 -> 2,  3,  41

The highest prime factor is increasing in both direction, so we must look at the next neighbor:
243 -> 3,   3,  3,  3,  3
244 -> 2,   2,  2,  61
245 -> 5,   7,  7
246 -> 2,   3,  41
247 -> 13,  19

The highest prime factors are now decreasing in both direction, so the highest prime factor we've encountered is 61, and should therefore be returned.
Another example:
Let's look at 1024. Its prime factors are 2, 2, 2, 2, 2, 2, 2, 2, 2, 2.
The prime factors of its nearest neighbors are:
1023 -> 3, 11, 31
1024 -> 2,  2,  2,  2,  2,  2,  2,  2,  2,  2
1025 -> 5,  5, 41

The highest prime factor are increasing in both direction, from 2 to 31 or 41. Let's look at the neighbors:
1022 -> 2, 7,  73
1023 -> 3, 11, 31
1024 -> 2,  2,  2,  2,  2,  2,  2,  2,  2,  2
1025 -> 5,  5, 41
1026 -> 2,  3,  3, 19

The highest prime factor for 1022 is 73, and the highest prime factor for 1026 is 19. Since 19 is lower than 41 we're not interested in it. It's still increasing for numbers smaller than \$N\$, so we'll check the next one in that direction:
1021 -> 1021
1022 -> 2, 7,  73
1023 -> 3, 11, 31
1024 -> 2,  2,  2,  2,  2,  2,  2,  2,  2,  2
1025 -> 5,  5, 41
1026 -> 2,  3,  3, 19

1021 is a prime, and the highest prime we've encountered, so it should be returned.
Rules:

You will only get positive \$N\$ larger than \$1\$ and smaller than \$2^{31}-2\$.
Input and output formats are optional, but the numbers must be in base 10.
You should continue searching for higher primes as long as the highest value is increasing in that direction. The directions are independent of each other.

Test cases:
Format: N, highest_factor
2, 3
3, 3
6, 7
8, 11
24, 23
1000, 997
736709, 5417
8469038, 9431

Mathematica, 82 74 bytes

Thanks to Martin Ender for saving 8 bytes!

Max@@(±n_:=#//.x_/;l[t=x+n]>l@x:>t;l=FactorInteger[#][[-1,1]]&)/@{±-1,±1}&

Unnamed function taking an integer input and returning an integer.

±n_:=#//.x_/;l[t=x+n]>l@x:>t defines a unary function ± which keeps increasing the global function's integer input by n as long as the largest prime factor is increasing. (The largest-prime-factor function is defined with l=FactorInteger[#][[-1,1]]&.) {±-1,±1} therefore applies that function twice to the input integer, with increment -1 and again with increment 1. Then, Max@@(...l...)/@... takes the larger of the two largest-prime-factors thus found.

Previous submission:

Max@@(l=FactorInteger[#][[-1,1]]&)/@(#//.x_/;l[t=x+#2]>l[x]:>t&@@@{{#,-1},{#,1}})&


JavaScript (V8),  72 71 70  69 bytes
A full program that prints the sequence forever.

for(n=1;c=2;c||print(n))for(d=++n;d--;)c>>=n==(h=n=>n&&h(n&n-1)+d)(d)

Try it online!
Commented
for(                   // infinite outer loop:
  n = 1;               //   start with n = 1
  c = 2;               //   before each iteration: initialize c to 2
  c || print(n)        //   after each iteration: print n if c = 0
)                      //
  for(                 //   inner loop:
    d = ++n;           //     increment n and start with d = n
    d--;               //     stop when d = 0 / decrement d
  )                    //
    c >>=              //     right-shift d by 1 position if ...
      n == (           //       ... n is equal to ...
        h = n =>       //       ... the result of the recursive function h
          n &&         //       which adds d as many times as there are
          h(n & n - 1) //       bits set in d, using n & n - 1 to clear
          + d          //       the least significant bit at each iteration
      )(d)             //

Note
We decrement \$d\$ right away in the inner loop, which means that we never consider the case where the divisor of \$n\$ is \$n\$ itself. But that would only work if there's a single 1 in the binary representation of \$n\$, which means that \$n\$ is a power of \$2\$ and all its divisors have a single 1 in their binary representation as well. Therefore, \$n=1\times n\$ is the only possible solution and \$n\$ does not belong to the sequence.


just a caesar cipher... with a twist I have been going to puzzling.se, and people over there write stuff in rot13 a lot, sot this gave me an idea:
Write a program that takes 2 inputs, a string and integer:

the message to encode or decode
how far to shift

You can input in a function call, and output in any legal way
twist:
it must work with any printable ascii character.
Example code:
def ceasar_cipher(message,shift):
    o = ""
    for n in message:
        o+=(chr(ord(n)+shift))
    return o

python 3 examples:
input:

ceasar_cipher(“hello, world”,13):

output:

"uryy|9-\x84|\x7fyq."

This is code-golf, so shortest code in bytes wins.
The output should be a string
-Can raise an error if it will go past ASCII-characters, or just not shift said characters
Good luck!

BQN, 1 byte
Anonymous tacit infix function. Order of arguments doesn't matter.
+

Try BQN!


MacGyver's Second Toolbox In this question each answer will get a "toolbox" that can be used to construct a program/function.  The toolbox will consist of two things:

a list of programming languages
a list of valid characters

You must write a valid program/function in one of the languages provided using only the characters in the toolbox.  Your program/function should output the number of answers already present on this question.

Once you have written and posted an answer the language and characters you have used will be removed from the toolbox and 1 new language and 8 new characters will be randomly added to be used as the toolbox for the next answer.

Rules

Each answer will:

Output the number of valid answers coming before it
Contain a subset of the characters provided in the toolbox for that answer.  (repeats are allowed)
Be in one of the languages from the provided toolbox

The next toolbox will determined by this python program.  To generate the next toolbox put in the remaining languages and characters along with the post id of the last answer.
The language list here is all the languages available on try it online at the time of this post.  The characters have char codes 0-127.
You may write either a full program or a function as your answer.  Since REPLs are different languages they will not be allowed.  (use the TIO version of every language)
If a language uses a special encoding the characters should be interpreted as bytes (decoded from ASCII and padded with a zero).
The starting toolbox will be randomized from this questions post id (128464), there will be 7 languages to start and I will add the characters echoprint0 and ascii 0-31 for free to get people started.
You may not answer twice in a row

Scoring

Each time a person answers they will get a number of points for their answer.  The goal is to get as many points as possible. For an answer in language X you will get as many turns as language X has gone unused in the toolbox. For example the first person to answer will get 1 point because the language was just added to the toolbox.  There will not necessarily be an end and I will not be accepting any answers.

Sporting

This is a competition, but I encourage you to put fun above winning while still staying competitive (if I could make the winning criteria "fun had" I would).  Some things that are not fun:

Intentionally using characters you don't need to stunt future answers.
Attempting to game the post id system to make future tool boxes harder to use.
Attempting to game the post id system to make future tool boxes easier to use.

I can't prevent any one from doing these things, but I will be downvoting any answers I suspect are doing this.

On a more positive note, here are some things that are good sporting and encouraged:

Coordinating with other users in chat.
Saving characters for harder or more restrictive languages

  This is a second iteration of a challenge found here.  It improves a number of problems with the first one. Here is a meta discussing these questions.

This is impossible

Going through all of the languages in the langbox:

The tcl programming language consists of words separated by spaces. The space character is not in the toolbox, so no valid programs can be written.
Str programs by default transform input. In order for them to do anything when given no input, the ; character is required, which is not in the toolbox.
The only means for a program in scheme-chez to do anything is by calling a function using parentheses. All scheme-chez programs therefore need the ( character, which is not in the toolbox
Brain-Flak programs need balanced brackets. The only bracket character in the toolbox is ), so no programs containing balanced brackets are possible.
Similar to scheme, maxima programs require parentheses to do anything.
Java programs require the { or -> character sequences to declare a function (and all full programs need at least one function), none of which are in the toolbox.
Condit programs require the word when, which contains the "e" character, which is not in the toolbox.

Proofs of impossibility are allowed as answers


How should I tile my kitchen? I recently ordered some new and colorful tiles to replace my boring old white tiling for my kitchen.  However, when the tiles arrived, they were all in a weird shape!  Therefore, I need a program to figure out how to arrange the tiles so that I need to use as few of my old boring white tiling as possible.

Even though the tiles are weird, I'm not a fan of abstract design stuff, so the tiling should be regular. To be precise, it should be a lattice: there should no rotation or reflection of the tiles, and there should be two translations S and T which are combined to place the tiles with relative offsets of aS + bT for all a and b. Of course, the tiles shouldn't overlap when placed in this lattice arrangement.

I'll give you the tile in string format, and I need you to output the tiling.  You may need to cut some of the tiles where they extend beyond the edges of my kitchen.  For example:

abc        abcdefabcdef
 def   ->  cdefabcdefab
           efabcdefabcd

can be broken down as

+-----+   +-+-----+   +-+
|a b c|d e f|a b c|d e f|
+-+   +-+---+-+   +-+---+
 c|d e f|a b c|d e f|a b
  +-+---+-+   +-+---+-+
 e f|a b c|d e f|a b c|d
----+-+   +-----+-+   +-

where the translations are (+6, 0) and (+4, +1). All but three of the tiles have been cut in this example.

You will be given a string to tile either via function parameter or STDIN.  Spaces in the tile are considered "empty" and can be filled with other tiles.

My kitchen is 30x30 squares big, so all you need to do is make the number of empty squares is as small as possible in that area.  You only need to print out 1 valid 30x30 square, which means that there may not be any lattice arrangement which has a 30x30 square with fewer empty squares.

Examples (I'm not going to give the full 30x30 square for brevity):

Input:
ab
 a
Output:
abaaba
baabaa
aabaab

Input:
xxx
x x y
xxx

Output:
xxxxxxxxxxx
xyxxyxxyxxy
xxxxxxxxxxx
xxxxxxxxxxx
xyxxyxxyxxy
xxxxxxxxxxx

Input:
012
 3 4
  56
Output:
0123 456
23 45601
 4560123
5601234

Input:
rrr
R r
Output:
rrrR r
R rrrr
rrrR r

Input:
defg
  c
ab
Output:
cabdefg cab
defg cabdef
g cabdefg c
abdefg cabd
efg cabdefg
 cabdefg ca
bdefg cabde
fg cabdefg

Your program should run in a reasonable amount of time, and this is code-golf, so the shortest program wins!

APL (Dyalog Unicode), 193 bytes

{G←{⍵⊃⍨⊃⍋(+/' '=,)¨⍵}
G{s←,30-⍳,⍨61
G,⊢∘⊂⌺30 30⊢((≢a)/⍪' '~⍨,x)@(B∘.+a)⊢''⍴⍨(⍴b)+⊃⌈/a←(⊢-⌊/)(⊃+/)¨s×⊂⍵}¨o/⍨(⍱/X∊⍨+/,-/)¨o←,∘.,⍨⊂¨∪{⍵/⍨0<2⊥¨×⍵}(,B∘.-⍸b<(1∊⊢)⌺3 3⊢b)~X←,B∘.-B←⍸b←(⍉0,⌽)⍣4⊢' '≠x←⍵}

Try it online!
A monadic dfn that takes a matrix of characters and returns the 30-by-30 matrix of a possible tiling with minimal blanks. Runs in 5 seconds for the smallest test case and in under a minute for the last one.
The idea
The task looks pretty straightforward at first glance, but it was surprisingly hard to derive a valid solution, and even harder to get one that "runs in a reasonable amount of time" (which somewhat explains why it was unanswered so far).
The first obstacle was that there are infinitely many possible tiling vectors. I solved this by limiting the vectors to the ones where the original tile and the moved tile share at least a point. If ab is the given tile, this means the following movements are considered as tiling vector candidates:
                                        AB   AB  AB  AB   AB
ABab    ab   ab  ab  ab   ab    abAB  ab    ab   ab   ab    ab
      AB    AB   AB   AB    AB

Then I filter out redundant ones (keeping only one of \$v\$ or \$w\$ when \$v = -w\$), generate all possible pairs of these candidate tiling vectors, and only keep the ones \$v, w\$ where neither \$v+w\$ nor \$v-w\$ movement overlaps with the original tile.
Reasoning: We know that the pairs of tiles at offsets \$(0, v)\$ and \$(0, w)\$ do not overlap, and therefore \$(v, v+w)\$ and \$(w, v+w)\$. Once it is known that \$(0, v+w)\$ and \$(v, w)\$ (alternatively \$(0, v-w)\$) pairs are safe, we know that \$(0, v, w, v+w)\$ are mutually safe, and by translation in four directions \$v, w, -v, -w\$, the entire infinite tiling is safe.
Given a full list of candidate vector pairs, I chose a naive way: for each vector pair, generate a large enough board of actual tiling, extract all 30-by-30 regions, and choose the one with the smallest number of blanks. For that, I used \$-30 \le a,b \le 30\$ for the formula \$av + bw\$. In order to prevent the memory (and execution time) blowing up, I apply this filtering twice, first within each vector pair, and then across all minimally chosen boards.
Ungolfed
The code changed a lot while golfing, but the core idea remains the same.
f←{
  ⍝ A boolean matrix where 1 means non-blanks, padded once to all directions
  bool←(⍉0,,∘0)⍣2⊢' '≠x←⍵
  ⍝ Spread 1s to adjacent cells (8 directions)
  padded←({1∊⍵}⌺3 3>⊢)bool
  ⍝ Extract the coordinates of ones
  cbool←⍸bool
  cpadded←⍸padded
  ⍝ badoffs: All offsets that move a cell to already occupied cell
  ⍝ offs: All offsets that move a cell to a cell adjacent to the tile,
  ⍝       badoffs removed and (negative, any) and (zero, negative) removed
  offs←∪{⍵/⍨0<2⊥¨×⍵}(,cbool∘.-cpadded)~badoffs←,cbool∘.-cbool
  ⍝ Pairs of valid offsets
  offpairs←,∘.,⍨⊂¨offs
  ⍝ Remove offset pairs (v,w) if v+w or v-w is bad
  filter←{⍱/(⍺+⍵)(⍺-⍵)∊badoffs}/¨offpairs
  pairs←filter/offpairs

  ⍝ Aux. function: Select the matrix with smallest number of blanks
  MinBlanks←{⍵⊃⍨⊃⍋(+/' '=,)¨⍵}
  ⍝ Aux. function: Given an offset pair, tile the floor using them and
  ⍝                extract the 30x30 region with minimum blanks
  GetResults←{
    somepair←⍵
    ⍝ -30 to 30, inclusive (the values of a and b)
    steps←30-⍳61
    ⍝ All values of av + bw, offset to the minimum coordinates of (0,0)
    alloffs←⊃{,(steps×⊂⍺)∘.+steps×⊂⍵}/somepair
    alloffs-←⌊/alloffs
    ⍝ Initialize a big enough blank grid
    dims←(⍴bool)+⊃⌈/alloffs
    grid←dims⍴''
    ⍝ Fill the grid with the tiles' cells moved accordingly
    filled←((≢alloffs)/⍪' '~⍨,x)@(cbool∘.+alloffs)⊢grid
    ⍝ Extract all 30x30 regions and return the one with minimum blanks
    results←,{⊂⍵}⌺30 30⊢filled
    MinBlanks results
  }
  ⍝ Map the above function over each of the pairs, and extract min blanks
  results←GetResults¨pairs
  MinBlanks results
}


Compare two numbers given as strings I have a problem at work. I need to compare two numbers that come as strings from two different databases. The numbers may come with leading zeroes and/or leading/trailing spaces. So I may have "0001 " from one database and " 1  " from the other one.

I solved the problem in C# with the following code:

   Func<string, string, bool> f = (a,b) => int.Parse(a.Trim()) == int.Parse(b.Trim())

The challenge

This is a really simple challenge, suitable for beginners and any kind of esoteric languages. Given two numbers as strings that may come with leading zeroes and/or leading/trailing spaces, write the shortest code that checks if the two strings represent the same number.

The inputs need to be two strings or the equivalent in your language (a char array is OK), and they will always represent integer values greater than zero.
The output must be any two consistent values that represent a truthy value and a falsey value.

Examples

A          B          Result
----------------------------
"0001"     "1    "    true
"1450"     "1450 "    true
"0010001 " " 10001  " true
"0010000"  "  10  "   false
"101023"   "101024"   false

This is code-golf, so may the shortest code for each language win!

Javascript, 11 bytes
a=>b=>+a==b

Abusing Javascript's casting rules a bit; +a coerces a into a numeric type.
-6 bytes thanks to Shaggy and Martin Ender♦
Also a cool take by LiefdeWen:
a=>b=>~~a==~~b


ASCII Exact Cover with Rectangles Challenge
Given a rectangular area arrange a group of rectangles such that they cover the rectangular area entirely.
Input

An integer denoting the height.

An integer denoting the width.

The dimensions of the rectangles consisting
of the following form: axb,cxd,... where a,b,c, and d are integers - any reasonable format is acceptable.

Output
An exact cover of the rectangular area.
Rectangles used to cover the area are represented in the following way:
2x3
00
00
00

or
000
000

1x3
0
0
0

or
000

Each rectangle is represented using a character 0-9 where 0 is used for the first rectangle inputted 1 for the second and so on. The max number of rectangles given in input is therefore 10.
Test Cases
Input 1
5
7
4x2,3x2,3x2,5x2,5x1

Output 1
0000111
0000111
2233333
2233333
2244444

Input 2
4
4
3x2,2x1,2x2,2x2

Output 2
0001
0001
2233
2233

Input 3
2
10
4x2,3x2,3x2

Output 3
0000111222
0000111222

Clarifications

The dimensions of the rectangles used to cover the region are interchangeable e.g. for axb a could be the height or width same goes for b.
If there are multiple solutions any of them is acceptable (just display 1).
Assume all inputs are valid.
You can have a full program or a function (inputs may be treated broadly as 3 separate arguments).
Output to stdout (or something similar).
This is code-golf so shortest answer in bytes wins.

APL (Dyalog Unicode), 76 bytes

⎕CY'dfns'
{⍺⍴v+.×(X m)⌿m←⊃⍪/(⍺∘{⍪↑,(⍳⍺)↓¨⊂⌽⊖⍺↑⍵⍴1}¨⊢∘⌽\2/⍵),⍤1¨2/↓∘.=⍨v←⍳≢⍵}

Try it online!
Dyalog APL comes with a built-in Exact Cover solver X, so the main part of the code is construction of the constraint matrix.
A constraint matrix is a boolean matrix where a column indicates a constraint, and a row indicates an action that satisfies some of the constraints. In the case of rectangle cover, an action is positioning of a specific rectangle at certain position and orientation, which satisfies two kinds of constraints: a specific rectangle is consumed, and the certain cells are covered by that rectangle.
For example, consider positioning a 2×3 rectangle in a 4×4 rectangular space. There are 12 ways to place it inside the space:
Horizontally
OOO. .OOO
OOO. .OOO
.... ....
.... ....

.... ....
OOO. .OOO
OOO. .OOO
.... ....

.... ....
.... ....
OOO. .OOO
OOO. .OOO

Vertically
OO.. .OO. ..OO
OO.. .OO. ..OO
OO.. .OO. ..OO
.... .... ....

.... .... ....
OO.. .OO. ..OO
OO.. .OO. ..OO
OO.. .OO. ..OO

If it is the second rectangle out of four rectangle pieces, a part of the constraint matrix would look like this (where type 1 constraints mark the rectangle used, and type 2 mark the cells occupied):
            <--           Type 2           -->
<-Type 1->  <-r1-->  <-r2-->  <-r3-->  <-r4-->
0 1 0 0     1 1 0 0  1 1 0 0  1 1 0 0  0 0 0 0
0 1 0 0     0 1 1 0  0 1 1 0  0 1 1 0  0 0 0 0
0 1 0 0     0 0 1 1  0 0 1 1  0 0 1 1  0 0 0 0
0 1 0 0     0 0 0 0  1 1 0 0  1 1 0 0  1 1 0 0
0 1 0 0     0 0 0 0  0 1 1 0  0 1 1 0  0 1 1 0
0 1 0 0     0 0 0 0  0 0 1 1  0 0 1 1  0 0 1 1
...

In the actual code, the fact that "there will always be a solution" is abused for the sake of golfing. It actually generates a matrix where type 2 comes before type 1, and the rectangle pieces are allowed to be partially overflowed to the top left. It still works since using an overflowed piece will always fail to cover the entire rectangular area.
⍝ Load dfns library to use the function X
⎕CY'dfns'

⍝ An inline function; ⍺←area (w,h), ⍵←n pieces
{
  v←⍳≢⍵    ⍝ Generate 0..n-1
  ↓∘.=⍨    ⍝ Generate Type 1 constraints as a nested array
  2/       ⍝ Two copies of each, to match with two orientations of each rect
  ,⍤1¨     ⍝ Concatenate row-wise with
  (...)    ⍝ the Type 2 constraints:
  2/⍵      ⍝   Two copies of each rectangle
  ⊢∘⌽\     ⍝   Flip the rows and columns at odd (0-based) indices
  ⍺∘{...}¨ ⍝   Generate boolean matrices for each rectangle:
  ⍺↑⍵⍴1    ⍝     Create the rectangle-shaped 1s, 0-filled to the size of the space
  ⌽⊖       ⍝     Reverse in both dimensions, so the 1s go to the bottom right
  (⍳⍺)↓¨⊂  ⍝     The above with leading rows/columns dropped in all possible ways
           ⍝     (all combinations of 0..h-1 rows and 0..w-1 columns dropped)
  ⍪↑,      ⍝     Format the result as Type 2 constraint sub-matrix
  m←⊃⍪/    ⍝ Vertically concatenate all the constraint sub-matrices
           ⍝ generated for each rectangle
  (X m)⌿m  ⍝ Solve the Exact Cover problem, and extract the rows
           ⍝ (the collection of rectangles that actually cover the area)
  v+.×     ⍝ Number the cells by the containing rectangle's 0-based index
  ⍺⍴       ⍝ Reshape the cells to the shape of the area
}


Output the Arecibo Message The Arecibo message is a 1974 interstellar radio message carrying basic information about humanity and Earth sent to globular star cluster M13 in the hope that extraterrestrial intelligence might receive and decipher it... The message consisted of 1,679 binary digits, approximately 210 bytes...
The number 1,679 was chosen because it is a semiprime (the product of two prime numbers), to be arranged rectangularly as 73 rows by 23 columns. The alternative arrangement, 23 rows by 73 columns, produces an unintelligible set of characters (as do all other X/Y formats).

This is the message with color added to highlight its separate parts. The actual binary transmission carried no color information.

Source: Wikipedia

Your task is to output the Arecibo Message in the exact 23x73 arrangement shown in the image. Any of these output formats is acceptable:

Text, using one character for ones and another for zeros (using the usual rules for row separation)
A 2D array of two distinct values
A 23x73 image with two distinct colors
Aan uninterrupted stream of 1679 items of two distinct values (i.e. any of the above formats, but flat.)
A 1679-bit integer. Indicate bit and byte order (endianness) in your solution.

For your convenience, here is a copy-pastable version (also an example output in text format):
00000010101010000000000
00101000001010000000100
10001000100010010110010
10101010101010100100100
00000000000000000000000
00000000000011000000000
00000000001101000000000
00000000001101000000000
00000000010101000000000
00000000011111000000000
00000000000000000000000
11000011100011000011000
10000000000000110010000
11010001100011000011010
11111011111011111011111
00000000000000000000000
00010000000000000000010
00000000000000000000000
00001000000000000000001
11111000000000000011111
00000000000000000000000
11000011000011100011000
10000000100000000010000
11010000110001110011010
11111011111011111011111
00000000000000000000000
00010000001100000000010
00000000001100000000000
00001000001100000000001
11111000001100000011111
00000000001100000000000
00100000000100000000100
00010000001100000001000
00001100001100000010000
00000011000100001100000
00000000001100110000000
00000011000100001100000
00001100001100000010000
00010000001000000001000
00100000001100000000100
01000000001100000000100
01000000000100000001000
00100000001000000010000
00010000000000001100000
00001100000000110000000
00100011101011000000000
00100000001000000000000
00100000111110000000000
00100001011101001011011
00000010011100100111111
10111000011100000110111
00000000010100000111011
00100000010100000111111
00100000010100000110000
00100000110110000000000
00000000000000000000000
00111000001000000000000
00111010100010101010101
00111000000000101010100
00000000000000101000000
00000000111110000000000
00000011111111100000000
00001110000000111000000
00011000000000001100000
00110100000000010110000
01100110000000110011000
01000101000001010001000
01000100100010010001000
00000100010100010000000
00000100001000010000000
00000100000000010000000
00000001001010000000000
01111001111101001111000

If your language, for some reason, has a builtin for the Arecibo Message, you may not use that builtin.
Good Luck!
UPDATE: I accepted the 05AB1E answer since it was the first one to be shorter than the original message. Don't let that dissuade you from new solutions.
UPDATE 2019-09-09: Accepted answer moved to a new 05AB1E answer, as it obsoletes the previous 05AB1E answer. Same point goes as previous update; new solutions still welcome.

05AB1E, 215 210 200 bytes

Saved 15 bytes thanks to Magic Octopus Urn

•cOž¤4é57ñΛ\Ö₃BαöĀíL½₅üBdoÙRθLγ¨G×Tćú$G(˜ƒ¦!€R»SDrµCnJ†d∊ζ·<8‡T@|‹ï=BζćósxG\ÙÎ$¿o₁5/ÔŸÇBûXé-”a::Ž]°∊y;ζ]MÜβ‘иL”β{üÃÇíäc€÷›ÎU=}¨иaŸdY`»¾ÚUβ:ô©¦β†₅DGŠβ3Jêθ,äá!ícqšVÖ›lÈΣ¯pε €êÊƒDpÙ/¬Žλ8:ãÿ3=€.Þć•3BY¾4×:

Try it online!
or with Additional formatting

Base-255 encoded trinary string with occurrences of 0000 replaced by 2.


The Ackermann function The Ackermann function is notable for being the one of the simplest examples of a total, computable function that isn't primitive recursive.
We will use the definition of \$A(m,n)\$ taking in two nonnegative integers where
$$\begin{align}
A(0,n) & = n+1 \\
A(m,0) & = A(m-1,1) \\
A(m,n) & = A(m-1,A(m,n-1))
\end{align}$$
You may implement

a named or anonymous function taking two integers as input, returning an integer, or
a program taking two space- or newline-separated integers on STDIN, printing a result to STDOUT.

You may not use an Ackermann function or hyperexponentiation function from a library, if one exists, but you may use any other function from any other library. Regular exponentiation is allowed.
Your function must be able to find the value of \$A(m,n)\$ for \$m \le 3\$ and \$n \le 10\$ in less than a minute. It must at least theoretically terminate on any other inputs: given infinite stack space, a native Bigint type, and an arbitrarily long period of time, it would return the answer. Edit: If your language has a default recursion depth that is too restrictive, you may reconfigure that at no character cost.
The submission with the shortest number of characters wins.
Here are some values, to check your answer:
$$\begin{array}{c|cccccccccc}
A & n = 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 \\
\hline
m=0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 \\
1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 \\
2 & 3 & 5 & 7 & 9 & 11 & 13 & 15 & 17 & 19 & 21 & 23 \\
3 & 5 & 13 & 29 & 61 & 125 & 253 & 509 & 1021 & 2045 & 4093 & 8189 \\
4 & 13 & 65533 & \text{big}
\end{array}$$

Haskell, 35
0%n=1+n
m%n=iterate((m-1)%)1!!(n+1)

this defines the operator function %.
this works by noticing that m%n (where a is the ackerman function) for nonzero m is (m-1)% applied n+1 times to 1. for example, 3%2 is defined as 2%(3%1) which is 2%(2%(3%0)), and this is 2%(2%(2%1))


North Korean dictionary order The objective

Given a string of Hangul syllables, sort the characters in North Korean dictionary order.

Introduction to Hangul syllables

Hangul(한글) is the Korean writing system invented by Sejong the Great. Hangul syllables are allocated in Unicode point U+AC00 – U+D7A3. A Hangul syllable consists of an initial consonant, a vowel, and an optional final consonant.

The initial consonants are:

ㄱ ㄲ ㄴ ㄷ ㄸ ㄹ ㅁ ㅂ ㅃ ㅅ ㅆ ㅇ ㅈ ㅉ ㅊ ㅋ ㅌ ㅍ ㅎ

The vowels are:

ㅏ ㅐ ㅑ ㅒ ㅓ ㅔ ㅕ ㅖ ㅗ ㅘ ㅙ ㅚ ㅛ ㅜ ㅝ ㅞ ㅟ ㅠ ㅡ ㅢ ㅣ

The final consonants are:

(none) ㄱ ㄲ ㄳ ㄴ ㄵ ㄶ ㄷ ㄹ ㄺ ㄻ ㄼ ㄽ ㄾ ㄿ ㅀ ㅁ ㅂ ㅄ ㅅ ㅆ ㅇ ㅈ ㅊ ㅋ ㅌ ㅍ ㅎ

For example, 뷁 has initial consonant ㅂ, vowel ㅞ, and final consonant ㄺ.

South Korean dictionary order

The consonants and vowels above are sorted in South Korean dictionary order. The syllables are firstly sorted by initial consonants, secondly by vowels, and finally by (optional) final consonants.

The Unicode block for Hangul syllables contains every consonant/vowel combinations, and is entirely sorted in South Korean dictionary order.

The Unicode block can be seen here, and the first 256 characters are shown for illustrative purpose:

  가각갂갃간갅갆갇갈갉갊갋갌갍갎갏감갑값갓갔강갖갗갘같갚갛개객갞갟갠갡갢갣갤갥갦갧갨갩갪갫갬갭갮갯갰갱갲갳갴갵갶갷갸갹갺갻갼갽갾갿걀걁걂걃걄걅걆걇걈걉걊걋걌걍걎걏걐걑걒걓걔걕걖걗걘걙걚걛걜걝걞걟걠걡걢걣걤걥걦걧걨걩걪걫걬걭걮걯거걱걲걳건걵걶걷걸걹걺걻걼걽걾걿검겁겂것겄겅겆겇겈겉겊겋게겍겎겏겐겑겒겓겔겕겖겗겘겙겚겛겜겝겞겟겠겡겢겣겤겥겦겧겨격겪겫견겭겮겯결겱겲겳겴겵겶겷겸겹겺겻겼경겾겿곀곁곂곃계곅곆곇곈곉곊곋곌곍곎곏곐곑곒곓곔곕곖곗곘곙곚곛곜곝곞곟고곡곢곣곤곥곦곧골곩곪곫곬곭곮곯곰곱곲곳곴공곶곷곸곹곺곻과곽곾곿

For example, the following sentence (without spaces and punctuations):

키스의고유조건은입술끼리만나야하고특별한기술은필요치않다

is sorted to:

건고고기끼나다리만별술술스않야요유은은의입조치키특필하한

In C++, if the string is in std::wstring, the sorting above is plain std::sort.

North Korean dictionary order

North Korean dictionary has different consonant/vowel order.

The initial consonants are sorted like:

ㄱ ㄴ ㄷ ㄹ ㅁ ㅂ ㅅ ㅈ ㅊ ㅋ ㅌ ㅍ ㅎ ㄲ ㄸ ㅃ ㅆ ㅉ ㅇ

The vowels are sorted like:

ㅏ ㅑ ㅓ ㅕ ㅗ ㅛ ㅜ ㅠ ㅡ ㅣ ㅐ ㅒ ㅔ ㅖ ㅚ ㅟ ㅢ ㅘ ㅝ ㅙ ㅞ

The final consonants are sorted like:

(none) ㄱ ㄳ ㄴ ㄵ ㄶ ㄷ ㄹ ㄺ ㄻ ㄼ ㄽ ㄾ ㄿ ㅀ ㅁ ㅂ ㅄ ㅅ ㅇ ㅈ ㅊ ㅋ ㅌ ㅍ ㅎ ㄲ ㅆ

Like South, the syllables are firstly sorted by initial consonants, secondly by vowels, and finally by (optional) final consonants.

If the sentence above is given, the output must be:

건고고기나다리만별술술스조치키특필하한끼않야요유은은입의

Rules

If the input contains a character not within U+AC00 – U+D7A3, it falls in don't care situation.
As this is a code-golf, the shortest code in bytes wins.

JavaScript (ES6),  150 148  137 bytes
Saved 10 bytes thanks to @Grimy
I/O: arrays of characters.

a=>a.map(c=>"ANBCODEFPGQSHRIJKLM"[(n=c.charCodeAt()-44032)/588|0]+"AKBLCMDNERTOFGSUPHIQJ"[n/28%21|0]+~(n%28%18==2)+c).sort().map(s=>s[4])

Try it online!
Splitting Hangul syllables
Given a Hangul character of code point 0xAC00 + \$n\$, the initial consonant \$I\$, vowel \$V\$ and final consonant \$F\$ are given by:
$$I=\left\lfloor\frac{n}{588}\right\rfloor,\ V=\left\lfloor\frac{n}{28}\right\rfloor\bmod 21,\ F=n\bmod 28$$
Commented
a => a.map(c =>                  // for each character c in the input:
  "ANBCODEFPGQSHRIJKLM"[         //   start with a letter from 'A' to 'S'
    (n = c.charCodeAt() - 44032) //   for the initial consonant
    / 588 | 0                    //
  ] +                            //
  "AKBLCMDNERTOFGSUPHIQJ"[       //   append a letter from 'A' to 'U'
    n / 28 % 21 | 0              //   for the vowel
  ] +                            //
  ~(                             //   append "-2" for ㄲ or ㅆ (the only North
    n % 28 % 18 == 2             //   Korean final consonants that are sorted
  ) +                            //   differently) or "-1" otherwise
  c                              //   append the original character
)                                // end of map()
.sort()                          // sort in lexicographical order
.map(s => s[4])                  // isolate the original characters


Maximal 2-distance Sets In the plane (\$\mathbb R^2\$) we can have at most five distinct points such that the distances from each point to every other point (except itself) can assume at most two distinct values.

An example of such an arrangement is a regular pentagon - the two different distances are marked with red and blue:

Challenge

Given a number \$n = 1,2,3,\ldots\$ find the size \$s_n\$ of the largest 2-distance set in \$\mathbb R^n\$.

Definitions

We measure the Euclidean distance \$d(a, b) = \sqrt{\sum_{i=1}^n (a_i - b_i)^2}\$.
A set \$S \subseteq R^n\$ is a 2-distance set if the number of distinct distances \$| \{ d(a,b) \mid a,b \in S, a \neq b\}| = 2\$.

Details

Any output format defined in sequence is allowed.

Examples

  n =  1, 2, 3,  4,  5,  6,  7,  8
s_n =  3, 5, 6, 10, 16, 27, 29, 45

This is OEIS A027627, and these are all the terms that we know so far. Answers to this challenge are expected to be able to find any term of this sequence - given enough ressources - not just the first eight.

Mathematica, 220 218 bytes

For[n=1,1>0,n++,For[m=1,1>0,m++,x=Array[a,{m,n}];d=Table[(Norm[x[[i]]-x[[j]]]^2-1)*(Norm[x[[i]]-x[[j]]]^2-y)==0,{i,1,m-1},{j,i+1,m}];If[Not[CylindricalDecomposition[Flatten@{d,y>0},Flatten@{y,x}]],Break[]]];Print[m-1]]

Try it online! Un-golfed version:

For[ n = 1, 1>0, n++,
  For[ m = 1, 1>0, m++,
   x = Array[a, {m, n}];
   d = Table[(Norm[x[[i]] - x[[j]]]^2 - 1)*(Norm[x[[i]] - x[[j]]]^2 -
         y) == 0, {i, 1, m - 1}, {j, i + 1, m}];
   If[Not[
      CylindricalDecomposition[Flatten@{d, y > 0}, Flatten@{y, x}]],
      Break[]]
  ];
  Print[m - 1]
]

In this code, we apply a key tool from real algebraic geometry. A semialgebraic set is a subset of \$\mathbb{R}^d\$ defined by polynomial equalities and inequalities. We may identify the set of 2-distance subsets of \$\mathbb{R}^n\$ of cardinality \$m\$ with a semialgebraic subset of \$\mathbb{R}^{mn+2}\$. We force one of the distances to equal 1 without loss of generality, which means our semialgebraic set is a subset of \$\mathbb{R}^{mn+1}\$. We denote the other distance (squared) by \$y\$.

For which values \$Y\subseteq\mathbb{R}\$ of \$y\$ does there exists a size-\$m\$ subset of \$\mathbb{R}^n\$ with squared distances \$\{1,y\}\$? This can be answered with the help of Tarski--Seidenberg, which says that the projection of any semialgebraic set is semialgebraic. In our case, this means there is some univariate polynomial \$p\$ and relation \$*\in\{=,<,\leq\}\$ such that \$Y=\{y\in\mathbb{R}:p(y)*0\}\$. This projection may be accomplished using cylindrical algebraic decomposition (CAD), which enjoys an implementation in Mathematica.

Given a set of polynomial equalities and inequalities, as well as an ordered list of variables, Mathematica's implementation returns either an explicit description of every point in the corresponding semialgebraic set, or False if the set is empty. In the above code, we run CAD for increasingly larger values of \$m\$ until we get False, at which point we know that \$s_n=m-1\$. Sadly, the runtime of CAD is doubly exponential in the number of variables, and so we shouldn't expect this approach to determine \$s_9\$ any time soon. In fact, a minute of runtime only gives \$s_1=3\$.


Solve a Rubik's Cube Your challenge is to write a program to solve a 3x3x3 Rubik's Cube. This challenge is based on this one from 2013, rewritten to adhere to current community standards, and reposted with the original author's permission and help on meta.

Input

The input should represent an unsolved Rubik's Cube.
You may read this input via any standard means, and the input can be in any format you choose, except a sequence of moves to get the cube to an unsolved state (or anything similar); that would trivialize this challenge.

That means that the input can look like this:

    UUU
    UUU
    UUU
 LLLFFFRRRBBB
 LLLFFFRRRBBB
 LLLFFFRRRBBB
    DDD
    DDD
    DDD

U representing cubies on the top/upper face, L representing the left, etc.

It could also look like a Cubically cube-dump, an array of characters/integers, or the weird format in the original challenge; however you like. You must specify how input should be taken in your answer.

You can translate a cube-dump to an ULFRBD scheme here or the other way around here.

Output

You will output, via any allowed means, the moves that must be performed on the inputted Rubik's Cube to return it to the solved state. You may use any chosen notation or method to describe rotation; please specify what you use in your answer.

I recommend that you use Singmaster's notation as it is the simplest and clearest:

R - turn the right face of the cube 90 degrees clockwise
L - turn the left face of the cube 90 degrees clockwise
U - turn the top face of the cube 90 degrees clockwise
D - turn the bottom face of the cube 90 degrees clockwise
F - turn the front face of the cube 90 degrees clockwise
B - turn the back face of the cube 90 degrees clockwise

Append ' to any move to make it counterclockwise and 2 to any move to make it 180 degrees.

If you are unsure of the validity of an I/O method, feel free to comment or ping me in chat.

Examples

Input is in the format of a cube-dump and a ULFRBD layout; output is in Singmaster's notation.

Input -> D'U'R'L'R'L2R'F2U'D'U'D'LR'B'F'U'D'L2R'
Input -> RF2U2R2ULB2R2U2R'L'DB2U2D2B'R'F'B2DFU2RU2L'
Input -> L2FL'R'FB'U2D'F'R'LBF2R2L'F2D2BL2F2RU2D'LF'
Input -> B'U'FURD'B'F'RBF2D'F2R2L2FU'R'U'R2L2F'B2R'F
Input -> R2FUF2D'FR'B'D2L2F'URB2R'U'D'R2L'UD'R2B2UD2

Your program may assume that the given cube is possible to solve; i.e. you do not need to handle the case that the inputted cube is unsolvable.

Restrictions

Answers like this, while valid/interesting on other challenges, are not welcome here. You may not use an algorithm that iterates through every possible state of the cube and prints the moves as it goes, or anything similar.

To define these restrictions, your program must be able to solve each of the test cases above on TIO. So it must:

Exit in under 60 seconds.
Output less than 128KiB.

Validation

To validate that your program indeed solves the Rubik's Cube, you can obviously use a physical cube or an online cube emulator by mixing it how you like, feeding its state into your program, and then performing the output moves on the cube.

However, if you choose to format your input as the cube dump (or the ULFRBD scheme and translate it to a cube dump), you can validate your program via Cubically's online interpreter like so:

Go to the online interpreter.
Type rs into the Code section.
Paste your unsolved cube-dump into the Input section.
Run your program with the unsolved cube-dump. Copy the output into the Footer section.
Click Run. If your program is valid, Solved! will appear in the Output section.

Winning

As this is code-golf, the shortest code in bytes wins!

Cubically, 3 bytes

rp▦

Try it online! You can use this to print a random cube.

Explanation:

r    read cube from stdin
 p   set PRINTMOVES flag to display moves as they are performed on the cube
  ▦  insert moves to solve the cube at the current point in the program

Capitalize the P to see prettier output (e.g. RLD'U2 as opposed to R1L1D3U2).


Get the length of a Sumac Sequence Heavily based on this closed challenge.
Codidact post, Sandbox
Description
A Sumac sequence starts with two non-zero integers \$t_1\$ and  \$t_2.\$
The next term, \$t_3 = t_1 - t_2\$
More generally, \$t_n = t_{n-2} - t_{n-1}\$
The sequence ends when \$t_n ≤ 0\$. All values in the sequence must be positive.
Challenge
Given two integers \$t_1\$ and \$t_2\$, compute the Sumac sequence, and output its length.
If there is a negative number in the input, remove everything after it, and compute the length.
You may take the input in any way (Array, two numbers, etc.)
Test Cases
(Sequence is included for clarification)
[t1,t2]   Sequence          n
------------------------------
[120,71]  [120,71,49,22,27] 5
[101,42]  [101,42,59]       3
[500,499] [500,499,1,498]   4
[387,1]   [387,1,386]       3
[3,-128]  [3]               1
[-2,3]    []                0
[3,2]     [3,2,1,1]         4

Scoring
This is code-golf. Shortest answer in each language wins.

x86 machine code (8086), 15 13 bytes
-2 bytes thanks to @EasyasPi.
00000000  31 C9 48 7C 07 40 41 29-D8 93 EB F6 C3            1.H|.@A).....

Callable function.
Expects AX = t1, BX = t2. Output is to CX.
Disassembly:
31C9          XOR     CX,CX    ; Set CX to 0
          LOP:
48            DEC     AX       ; --AX
7C07          JL      END      ; If AX < 0, jump to 'END'
40            INC     AX       ; ++AX
41            INC     CX       ; ++CX
29D8          SUB     AX,BX    ; AX -= BX
93            XCHG    BX,AX    ; Swap AX and BX
EBF6          JMP     LOP      ; Jump to tag 'LOP'
          END:
C3            RET              ; Return to caller

Example run
Tested with DOS debug:
-r
AX=0078  BX=0047  CX=0000  DX=0000  SP=FFEE  BP=0000  SI=0000  DI=0000
DS=0B17  ES=0B17  SS=0B17  CS=1000  IP=0000   NV UP EI PL NZ NA PO NC
1000:0000 31C9          XOR     CX,CX
-t

AX=0078  BX=0047  CX=0000  DX=0000  SP=FFEE  BP=0000  SI=0000  DI=0000
DS=0B17  ES=0B17  SS=0B17  CS=1000  IP=0002   NV UP EI PL ZR NA PE NC
1000:0002 48            DEC     AX
...
-t

AX=FFFA  BX=0020  CX=0005  DX=0000  SP=FFEE  BP=0000  SI=0000  DI=0000
DS=0B17  ES=0B17  SS=0B17  CS=1000  IP=000C   NV UP EI NG NZ NA PE CY
1000:000C C3            RET
```


Water-Bucket problem This challenge is to calculate how to measure 4 liters of water with just two unevenly sized buckets, one of 3 liters and another of 5 liters, in minimum number of steps. To extend and generalize this, write a program to evaluate the minimum number of steps to measure “X” liters of water, with “Y” buckets each having a separate denomination.

Assumptions:

Each bucket used for measuring water should be unique in denomination and the number of buckets will be <= 3
The target amount to be reached has to finally reside in a single bucket (at the end of the measuring activity).
The bucket capacities and target amount will be <= 99
If there are multiple ways to measure the same amount, only one single way, having the minimum number of steps is required.
Ties will be broken by the smallest program.

Examples:

  2,3,5,4
  Implies that there are 2 buckets of capacity 3 and 5 each and the target amount desired is 4.

  3,4,6,9,7
  Implies that there are 3 buckets of capacity 4, 6 and 9 each and the target amount desired is 7.

Answers:

  2,3,5,4
  Fill 5
  Move 5 to 3
  Empty 3
  Move 5 to 3
  Fill 5
  Move 5 to 3

  3,4,6,9,7
  Fill 4
  Move 4 to 6
  Fill 9
  Move 9 to 6

Python, 363 chars

Golfed it, not sure if it is golf or not.  The map P maps a reachable state to the instructions used to get to that state.  Keeps enumerating reachable states until it finds one with the target amount of water in it.

I=input()
B=I[1:-1]
R=range(I[0])
P={(0,)*I[0]:""}
while P:
 Q={}
 for s in P:
  if I[-1]in s:print P[s];P=Q={};break
  for i in R:
   Q[s[:i]+(0,)+s[i+1:]]=P[s]+"Empty %d "%B[i];Q[s[:i]+(B[i],)+s[i+1:]]=P[s]+"Fill %d "%B[i]
   for d in R:m=min(s[i],B[d]-s[d]);Q[tuple(s[j]-[0,m][j==i]+[0,m][j==d]for j in R)]=P[s]+"Move %d to\
 %d "%(B[i],B[d])
 Q.update(P);P=Q


Jelly, 16 bytes

ḟṚṁṣj
z-ç€-ZFḟ-ṁ

Try it online! or verify all test cases.

How it works

z-ç€-ZFḟ-ṁ  Main link. Argument: M (matrix / 2D array)

z-          Zip the rows of M, using -1 as filler.
  ç€-       Map the helper link over the result, with right argument -1.
     Z      Zip the rows of the result.
      F     Flatten the resulting matrix.
       ḟ-   Filterfalse -1; remove all occurrences of -1.
         ṁ  Mold; shape the result like M.

ḟṚṁṣj       Helper link.
            Left argument: A (row / 1D array). Right argument: -1

ḟ           Filterfalse; remove all occurrences of -1.
 Ṛ          Reverse the resulting vector.
   ṣ        Split A at occurrences of -1.
  ṁ         Mold; shape the vector to the left like the 2D array to the right.
    j       Join the resulting 2D array, separating by -1.


Output a list of all rational numbers Out of all of mathematics, there will always be a few theorems that go beyond all common sense. One of these is the fact that there are different sizes of infinity. Another interesting fact is the idea that many infinities which seem to be of different size are actually of the same size. There are just as many even numbers as integers, as there are rational numbers.

The general concept of this question is to confront the bizarre reality of infinity. In this challenge, your program will output a list which will:

At any specific moment of time, always have a whole number of entries
Eventually contain (if left to run long enough) any specific (non-zero) rational number precisely once on the entire list
Contain an unbounded number of empty slots (entries on the list that are needlessly set to 0)
Have a proportion of empty slots that approaches a limit of 100%
For every positive integer N, have an infinite number of places with N consecutive empty slots

The Challenge

Your challenge is to write that shortest possible program that will output a special list with the following rules:

All entries with an index that is not a square number should be set to zero. So, the first entry will be nonzero, the second and third will be zero, the fourth will nonzero, etc.
All rational numbers will be in the form of an improper fraction (such as 4/5 or 144/13) that has been simplified. The exception is zeroes, which will be simply 0.
All (positive and negative) rational numbers should eventually appear on the list if your program runs for long enough and with enough memory. For any particular rational number, the time required may be an arbitrarily large, but always finite, amount of time.
If run for an infinite amount of time, no non-zero rational number should ever appear twice.

Rule 3 does allow for some variation, as in there is an infinite number of different possible legal outputs.

Output will be a stream of lines. Each line will be of the general form of 5: 2/3 where the first number is the entry number, then followed by the rational number. Note that 1: 0 will always be the first line of output.

Example snippet of output:

1: 1/1
2: 0
3: 0
4: 2/1
5: 0
6: 0
7: 0
8: 0
9: -2/1
10: 0
etc...

Rules, Regulations, and Notes

This is code golf. Standard code golf rules apply. Also, due to the variation allowed in the output, you need to at least show why you believe that your list will contain all possible rational numbers exactly once, and that your solution is correct.

EDIT: Since the primes numbers did distract from the challenge, I am changing it to square numbers. This accomplishes the same purpose, and also shortens the solutions.

Haskell, 184 characters

main=putStr.unlines$zip[1..](s>>=g)>>=h
s=(1,1):(s>>=f)
f(a,b)=[(a,a+b),(a+b,b)]
g x@(a,b)=[x,(-a,b)]
h(i,(a,b))=(i^2)%(u a++'/':u b):map(%"0")[i^2+1..i*(i+2)]
i%s=u i++": "++s
u=show

This does a breadth-first traversal of the Calkin-Wilf Tree, yielding all positive rational numbers in reduced form exactly once. It then alternates between positive and negative to cover all the non-zero rational numbers and pads with zeroes between the square entries.

Output (excluding zero lines for brevity):

1: 1/1
4: -1/1
9: 1/2
16: -1/2
25: 2/1
36: -2/1
49: 1/3
64: -1/3
81: 3/2
100: -3/2
...


Keep the unique characters down It's very simple: Your program or function should generate the following text:

Elizabeth obnoxiously quoted (just too rowdy for my peace): "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG," giving me a look.

Fine print

You may write a program or function, which returns the output as a string or printing it to STDOUT (or closest alternative). You may optionally include a single trailing newline in the output.

Scoring

The number of bytes in your code multiplied by the number of unique bytes in your code

Lowest score wins.

For example, a brainfuck or a whitespace answer would have a huge advantage here, as the multiplier would be very low (8 and 3 respectively). However, generally, writing programs in those languages produces much longer code which may negate that advantage.

Standard loopholes which are no longer funny are banned.

CJam, 266 281 456 bytes * 14 12 7 unique = 3724 3372 3192

Try it online.

14301201124204202034420112034224204431020210101232301021240204310431312122132100240400222324402030223103420431324402222132223233141443401210314023001122320404112224314302132421403301243334313000011124244441400003310332301330220022110121411122100040310110020040121444302100143202204330334033211334242120304123121024200421121232100303121022431044444423243331440434010014400~~10~~100~~1~43c~c~4~~41c~100~~1~43c~c~123~~100~~1~43c~c~44~~14~~43c~c100~~40c~c43c~~

Explanation

The strategy I've used is to treat each character in the string as a base-123 digit and encode that as a decimal number in the program. The program then converts that number back to base 123 and maps each base-123 digit back to a character. Because it's hard to explain why the program is in its current state, I'll explain each version of it.

Here's what the end of the program looked like in the first version:

...2068438725 123b:c

This implements the strategy in the most straightforward way possible. The number, encoded normally in base 10, is converted back to base 123 and each base-123 digit is mapped back to a character. But this uses 4 unique non-digit characters, and being able to get rid of any one of them would likely be worth the size hit due to having to use less straightforward code.

First, I realized that I could get rid of the b and the : operators by creating them at runtime as their ASCII character values converted back to a character (with the already present c operator) and evaluating them with the ~ operator. It turned out to be a little tricky to do this with the : operator, since it has to be parsed together with the following c operator. I solved this by producing the characters : and c and then producing and evaluating the character +, which concatenates the former two characters into the string :c which can then be evaluated properly.

Second, I realized that the ~ operator I just introduced had a handy new overloaded variant: when given a number, it produces the bitwise complement. By using this twice in a row after a number, I could introduce a token break in the source with no resultant computational effect, allowing me to replace the spaces used to separate numbers with ~~.

The final result is 15 more bytes of code at the end, but this cost is greatly outweighed by the benefit of eliminating 2 unique characters out of 14. Here's a comparison of the end of the first version with the end of the second version:

...2068438725  123[ b  ][   :c    ]
...2068438725~~123~~98c~58c99c43c~~

Using any fewer than the 2 operators I was using would be impossible, but I still wanted fewer unique characters. So the next step was to eliminate digits. By changing the number's encoding so that each decimal digit was really a base-5 digit, I could potentially eliminate the digits 6-9. Before eliminating anything from the end of the prgoram, it looked like this:

...4010014400 10b5b123b:c

As mentioned before, eliminating the space is easy. But the b, :, and c would not be so easy, as their character codes are 98, 58, and 99, respectively. These all contained digits marked for elimination, so I had to find ways to derive them all. And the only useful numeric operators with character values not containing 5-9 were decrement, increment, multiply, and add.

For 98, I initially used 100~~40c~40c~, which decrements 100 twice. But then I realized I could make yet another use of the ~ operator, as bitwise complement lets me get negative numbers which, when added, let me emulate subtraction. So I then used 100~~1~43c~, which adds 100 and -2 and is 2 bytes smaller. For 58, I used 44~~14~~43c~, which adds 44 and 14. And for 99, I used 100~~40c~, which decrements 100.

The final result is pretty big and obfuscated, but the cost of the significantly larger number and processing code were slightly outweighed by the big benefit of eliminating 5 unique characters out of 12. Here's a comparison of the final end of the program before eliminations and after eliminations:

...4010014400  10[      b      ][  5  ][     b     ]123[      b      ][            :c            ]
...4010014400~~10~~100~~1~43c~c~4~~41c~100~~1~43c~c~123~~100~~1~43c~c~44~~14~~43c~c100~~40c~c43c~~


Shortest code to find next prime palindrome I was trying to find the shortest code possible that given a number n, returns the next prime palindrome number (limited to below 100000). If the number itself is a prime palindrome, the code should return the next one.

Write the shortest program/function that, when given an input n (less than 100000), returns the next palindromic prime number.

This is an example working program:

def golf(n):
    n+=1
    while str(n)!=str(n)[::-1] or not all(n%i for i in xrange(2,n)):n+=1
    return n

CJam, 15 bytes

li{)__mfsW%i^}g

Reads a single, positive integer from STDIN. Try it online.

Example run

$ cjam <(echo 'li{)__mfsW%i^}g') <<< 250
313

How it works

This uses a tricky prime check instead of the built-in mp:

15 mf, for example, pushes [3 5]. We cast to a string ("35"), reverse that string ("53"), cast to integer (53) and XOR the result with the original integer (22). Since the result in non-zero, 35 is not a palindromic prime.

li                 " N := int(input())        ";
  {          }g    " While R:                 ";
   )               "   N += 1                 ";
     _mfs          "   R := str(factorize(N)) ";
         W%i       "   R := int(reverse(K))   ";
    _       ^      "   R ^= N                 ";


The shortest distance between two points is a line Code a program or function to construct an interactive canvas on the screen of at least 400 pixels x 400 pixels in size. The canvas can be any color you wish, bordered or borderless, with or without a title bar, etc., just some form of obvious canvas.

The user will click on two distinct areas of the canvas and the program must output the Euclidean distance (in pixels) between those two clicks in some fashion (STDOUT, displaying an alert, etc.). The two clicks can be only left clicks, only right clicks, a left click for the first and right click for the second, two double-left-clicks, etc., any combination is acceptable. Special Note: Clicking-and-dragging (e.g., using MOUSEUP as the second point) is specifically not allowed; they must be two distinct clicks.

The user must be able do this multiple times, and must get an output each time, until the program is closed/force-quit/killed/etc. You can choose the method of closure (clicking an X, ctrl-C, etc.), whatever is golfier for your code.

Rules

Either a full program or a function are acceptable. If a function, however, you must still display the output to the user somehow (simply returning the value is not acceptable).
Output can be to the console, displayed as an alert, populated onto the canvas, etc.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

LOGO (FMSLogo), 54 52 bytes

[mouseon[setpos mousepos]"[pr distance mousepos]"[]]

Unfortunately, I can't find any Logo interpreter online support mouse handling like FMSLogo.

This is a "explicit-slot template", which is similar to lambda in other programming languages. Click left mouse for first point and right mouse for second point (print distance).

Explanation: (Logo is a turtle graphics programming language)

mouseon                  Turn on mouse handling, with the following action:
[setpos mousepos]        Set the turtle to `mousepos` (the position of the mouse) on left mouse down
"                        Do nothing on left mouse up
[pr distance mousepos]   Print the distance from turtle position (`distance` is Logo builtin for that purpose) to `mousepos` on right mouse down
"                        Do nothing on right mouse up
[]                       Do nothing on mouse movement

The " is an empty word. Normally template is expected to be a list (where [], an empty list, does nothing), passing a word is acceptable (it is wrapped in a list), and in this case it saves 2 bytes.

Run:

apply [... <put the code here> ...] []

The apply is one way to run template in Logo, the [] is argument list, for which the template receive none.


Distinguish between Masculine and Feminine Nouns in French within 100 characters You are to write a very small program within 100 characters. Your program must distinguish between masculine and feminine french nouns. The output should be un if it is masculine and une if it is feminine. Often, there are certain statistical rules you can follow (e.g. if it ends in an "e" it is more likely feminine than masculine).

Input:

A french word; it may consist of any  lowercase letters and dashes, including lowercase letters with accents.

Example input: ami

Output:

un if the word is masculine and une if the word is feminine.

Example output: un

You do not have to get every word right; your goal is to be as accurate as possible.

Scoring: Your answer must be within 100 characters. Statements such as print or console.log or alert do not count as part of your total bytes. You may also write a function or method that performs this task, in which case the first few bytes (e.g. f=x=>) which are part of the function declaration do not count to your total. Your total score is the number of incorrect answers. Ties are broken by code size.

Nouns to test with:

un ami
un café
un chapeau
un concert
un crayon
un garage
un garçon
un lit
un livre
un mari
un musée
un oncle
un ordinateur
un pantalon
un piano
un pique-nique
un portable
un père
un sandwich
un saxophone
un stade
un stylo
un théâtre
un téléphone
un voisin
une botte
une boum
une chaise
une chaussette
une chemise
une clarinette
une copine
une femme
une fille
une glace
une heure
une lampe
une maison
une montagne
une personne
une piscine
une pizza
une radio
une raquette
une salade
une souris
une sœur
une table
une télé
une voiture

CJam, 0 incorrect, 32 29 bytes

This code uses a few odd characters (some of them unprintable), but they are all well within extended ASCII range. So again, I'm counting each character as a single byte.

"un"'el2b"zPB:  ":i+:%2/*

Due to the unprintable characters, I'm sure Stack Exchange swallows some, so you might want to copy the code from the character counter (it shows bytes with UTF-8 encoding, which is suboptimal for this challenge; also, the link doesn't seem to work in Firefox, but does in Chrome).

Test it here.

After some more discussion in chat, we figured that the regex golfing wouldn't bring us much further. So following an earlier (joking) suggestion of mine we started looking into manipulating the character codes of the words with certain functions, such that all words from one group would yield a number with some property that is easy to check. And we got luckier than we expected! Here is what the code does to the words:

Implicitly convert the characters in the word to their code points.
Interpret those as digits in base 2 (yes, the digits will be much larger than 0 or 1, but CJam can handle that).
Repeatedly take the result modulo... the following numbers: [133, 122, 80, 66, 58, 26, 20, 14, 9, 4]. This sequence of numbers is itself encoded as the code points of a string (this is where the weird and unprintable characters come in).
As if by magic, all 25 masculine nouns yield 0 or 1, and all 25 feminine nouns yield 2 or 3 with this procedure. So if we divide this by 2 (integer division) we get zeroes for masculine nouns and ones for feminine nouns.

To round it off, we push "un" on the stack, the we push a single e. Then we read the input word from STDIN and perform the above computation, and finally multiply the e by the result.

I have never folded modulo onto any list before, and I feel like I never will again...

Many thanks for xnor and Sp3000 for throwing ideas around and helping with the search for divisor chain.


Crack a Vigenère Cipher A Vigenère Cipher is encrypted by repeating a keyword to be the length of the plaintext, and summing each character in that text with the corresponding letter in the plaintext modulo 26. (using A=0,B=1 etc.)

For example, if the keyword is LEMON and the plaintext is ATTACKATDAWN, then the key is repeated to form LEMONLEMONLE, which is summed with the plaintext to form the ciphertext, LXFOPVEFRNHR.

Write a program or function which, given a list of words and a ciphertext, outputs all possible plaintexts for that ciphertext, such that the plaintext is the concatenation of words in the list, and the key is also a word from the list.

All words use only upper-case letters A to Z.

Your code must run in polynomial time with respect to the total length of the ciphertext and words list.

Shortest code (in bytes) wins.

Example Inputs/Outputs

The input/output format for your program is flexible, but here I'm giving the list of words separated by commas followed by the ciphertext as input, and the output is the list of plaintexts separated by commas.

Inputs

LEMON,ATTACK,AT,DAWN,BUNNY
LXFOPVEFRNHR

A,AA,AAA,AAAA,AAAAA,AAAAAA,AAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

XHQT,GIXIIR,QTIA,AZXO,KSECS,THIS,CIPHER,IS,EASY,TO,CRACK,CODE,GOLF
ZVTXIWAMKFTXKODDZCNWGQV

A,B,C,D,E,F,G,H,Z
DBCCBHF

A,AA
AAA

Outputs

ATTACKATDAWN

(none)

THISCIPHERISEASYTOCRACK,XHQTGIXIIRQTIAAZXOKSECS

BZAAZFD,CABBAGE,DBCCBHF

AAA

Doesn’t respect specifications – OCaml - 118 bytes

I’ll get back to it when I’ll have time on my hand.

open Char;;
fun m->List.map(fun k->String.mapi(fun i c->chr(65+(code c-code k.[i mod String.length k]+26)mod 26))m);;

  - : string -> string list -> string list = <fun>

As the function type shows, the function expect as arguments:

a string: the encoded message
a list of strings: the keys

It returns a list of strings, the messages as decoded by each string in the same order.

The function is anonymous, you can call it by inserting putting it inside parentheses (i.e. 2 bytes) and entering its arguments as follows:

open Char;;
(fun m->List.map(fun k->String.mapi(fun i c->chr(65+(code c-code k.[i mod String.length k]+26)mod 26))m)"ZVTXIWAMKFTXKODDZCNWGQV"["XHQT";"GIXIIR";"QTIA";"AZXO";"KSECS";"THIS";"CIPHER";"IS";"EASY";"TO";"CRACK";"CODE";"GOLF"];;

Ungolfed

(* unshift the character x back to what it was before being shifted by k *)
(* Char.chr and Char.code translate from ASCII int to char and back      *)
(* '+ 26' because the modulo operator can return negative numbers -__-   *)
open Char;;
let unshift k x = chr ( 65 + (code x - code k + 26) mod 26 );;
(* Use the n-th character of the key to decrypt x, loops when necessary  *)
let unshiftWithKeyAtPos key n x = unshift key.[n mod String.length key] x;;

(* Maps unshiftWithKeyAtPos key i x for each position i in cipherText    *)
(* where x = cipherText.[i] is the i-th character of cipherText.         *)
let decrypt key cipherText = String.mapi (unshiftWithKeyAtPos key) cipherText;;

(* Maps decrypt cipherText key for each key in keyList                   *)
let tryHard cipherText keyList = List.map (fun key -> decrypt key cipherText) keyList;;

(* And finally, call the function                                        *)
let hiddenMessage = "LXFOPVEFRNHR";;
let keys = ["LEMON";"CODE";"GOLF"];;
tryHard hiddenMessage keys;;


Generate self-avoiding loops of a specific length This question is a sequel to this one, working in the opposite direction.

For a reminder of terminology, the letters L, R, U, and D represent one-unit movement of a robot on the coordinate plane in the directions left, right, up, and down respectively. Given a positive even integer n, generate and print all sequences of L, R, U, and D of length n that result in a closed loop that does not intersect itself. In other words, when the robot follows the instructions in the sequence of letters, it must visit a new cell with every movement until it completes the loop and returns to the original cell.

Any of the generally accepted output formats for arrays and strings are allowed. The elements printed must be in alphabetical order. It can be assumed that the input is always a positive even integer.

Test cases

2 -> {"DU", "LR", "RL", "UD"}
4 -> {"DLUR", "DRUL", "LDRU", "LURD", "RDLU", "RULD", "ULDR", "URDL"}
6 -> {"DDLUUR", "DDRUUL", "DLLURR", "DLUURD", "DRRULL", "DRUULD", "LDDRUU", "LDRRUL", "LLDRRU", "LLURRD", "LURRDL", "LUURDD", "RDDLUU", "RDLLUR", "RRDLLU", "RRULLD", "RULLDR", "RUULDD", "ULDDRU", "ULLDRR", "URDDLU", "URRDLL", "UULDDR", "UURDDL"}

This is a standard code golf challenge, where the shortest answer wins. Standard rules apply.

APL (Dyalog Extended), 39 bytes

{∧'LURD'⊇⍨m⌿⍨(⍲∘⍧=⊢/)⍤1+\0J1*m←⍉4⊤⍳4*⍵}

Try it online!

The output is a matrix of characters, one path on a line.

How it works

{∧'LURD'⊇⍨m⌿⍨(⍲∘⍧=⊢/)⍤1+\0J1*m←⍉4⊤⍳4*⍵}  ⍝ Input ⍵←n

m←⍉4⊤⍳4*⍵  ⍝ A matrix of all length-n combinations of 0..3
     ⍳4*⍵  ⍝ 0..4^n-1
   4⊤      ⍝ Convert each to base 4 (each goes to a column)
m←⍉        ⍝ Transpose and assign to m

∧'LURD'⊇⍨m⌿⍨(⍲∘⍧=⊢/)⍤1+\0J1*m
                        0J1*m  ⍝ Power of i (directions on complex plane)
                      +\       ⍝ Cumulative sum; the path of the robot
            (      )⍤1  ⍝ Test each row:
                 ⊢/     ⍝   the last number (real+imag is always even)
                =       ⍝   equals
             ⍲∘⍧        ⍝   NAND of the nub-sieve
                        ⍝   (0 if all numbers are unique, 1 otherwise)
                        ⍝ The condition is satisfied only if both are 0
         m⌿⍨  ⍝  Extract the rows that satisfy the above
 'LURD'⊇⍨     ⍝  Index each number into the string 'LURD'
∧             ⍝  Ascending sort


Line editor (more text here) In the misty years of yore, when fanfold terminals walked the earth, there lived a strange creature. Oddly crippled and yet oddly powerful, the line editor teemed across the programming landscape in untold numbers; covering the earth as far as the eye could see.
Now it is fallen on hard times. That vast population hunted, hounded, and driven to the brink of extinction. Only a few specimens remain, most in cramped and unembelished cages in the less enlightened kind of zoo, though a few stuffed and mounted examples can be seen in backwater museums. Oh, and there is ed.
Frankenstein-like, we shall resurrect the noble beast!
Commands
Our editor is fairly minimal and will support the following commands
Focus moving commands

<number>[,<number>] -- move the focus to the stated line and if the second argument is given to the state column. Excessive line number gets the last line. Excessive column number gets the end of the line.
,<number> -- move to column number on the current line
e -- move the focus to the end of the file but do not begin a new line.
b -- move the focus to the beginning of the file.

Informational commands

L -- Echo the current context. The five lines centered on the current line are printed. All five lines are indented by one character; the current line is marked with a ">", the others with a " ". Under these lines another line is printed consisting entirely of spaces except for a "^" in the current column (a total of six lines are printed).
l -- echo the current line
p [[<start>],[<end>]] -- Print the file from starting to ending address. These value default to 1 and 0 (the end of the file).

File altering commands

A [<text>] -- Move to the line beyond the end of the file (that is begin a new line) and (possibly) append text.
<return> (alone) -- Insert a newline. Thus a <return> <return> inserts a newline after the current one.
r <text> -- replaces everything from the focus to the end of the line with text.
i [<text>] -- inserts text followed by by newline at the current focus. Any portion of this line beyond the focus ends up on the next line.
I <text> -- inserts text at the current focus, preserving the rest of the line. Focus remains on this line.
d -- Delete the contents of the current line or if the current line is already empty, remove the line.
j -- join this line to the next

Of this last group the first four end with the focus moving to the next line, while I preserves the focus at the end of the added text. When deleting or joining focus remains at the same line and column number.
The Interpretation of line numbers in commands
Number beginning with '+' or '-' are interpreted as offsets from the current line number. Numbers without a sign are interpreted as absolute line numbers, except that '0' means the last line of the file.
Prompt and interaction
The editor functions as a shell, and the prompt has the form <line>','<column>'>' where line is the line number except that "end" is used when the focus is at the last character of the file.
Each command is accepted only when the user presses newline. And takes affect.
Readline support is allowed but not required.
No feedback is provided except the changing values of  and  in the prompt, unless explicitly stated in the commands description.
Scoring
This is code-golf, so the shortest answer in each language wins.
Special thanks to dmkee for making this in sandbox where I adopted it.

C (gcc), 1288 1212 1188 1171 1146 bytes

#define P printf(
#define A case
#define B break
#define L(i,e,t,f,s)for(o=i;o e;){strcpy(l[o t],l[o f]);c[o t]=c[s o];}
#define R(m,o){return b<1|b>m?m o:b;}
#define N(f)sscanf(f,"%d,%d",&i,&j)||sscanf(f,",%d",&j)
r,i,j,o,z,c[999],*C,x=1,y=1;char a[999],l[999][999],(*L)[999];D(){L(r,>y,,-1,--)r++?strcpy(l[o],l[o-1]+--x),c[o-1]=x,l[o-1][x]=0:0;c[y++]=strlen(l[o]);x=1;}U(){strcat(*L,l[y]);*C=strlen(*L);L(y+1,<r,-1,,++)--r;*l[r]=c[r]=0;}X(b)R(c[y-1],+1)Y(b)R(r,)main(){for(;;){z=i=y;L=l+--z;C=c+z;j=x;!r||y/r&&x>*C?P"end> "):P"%d,%d> ",y,x);scanf("%[^\n]%*c",a)?a[2]*=!!a[1],N(a)?y=Y(i+(i<0|*a=='+')*y),x=X(j+(j<0||strchr(a+1,'+'))*x):0:(*a=D(),scanf("%*c"));switch(*a){A'e':y=r;x=c[r-1]+1;B;A'b':y=1;x=1;B;A'L':for(o=y-4;++o<y+2;)o<0^o<r&&P"%c%s\n",o^z?' ':'>',l[o]);for(o=x+1;--o;)P" ");P"^\n");B;A'l':puts(*L);B;A'p':i=1;j=0;N(a+2);for(o=Y(i)-1;o<Y(j);++o)puts(l[o]);B;A'A':y=r++;strcpy(l[y],a+2);x=c[y]=strlen(a+2);++x;++y;B;A'i':D();--y;x=X(0);A'r':strcpy(*L+x-1,a+2);*C=strlen(*L);x=1;++y>r&&++r;B;A'I':o=strlen(a+2);memmove(*L+x+o-1,*L+x-1,*C-x+1);*C+=o;memcpy(*L+x-1,a+2,o);x+=o;B;A'd':**L?**L=*C=0,x=1:U();y=y>r?r:y;B;A'j':y<r&&U();}}}

Demo

First time trying to do something like this, so there are probably some missed opportunities for making it smaller. (Thanks Jerry Jeremiah for pointing out some)

Here's a (slightly) more readable version:

// often used functions/keywords:
#define P printf(
#define A case
#define B break

// loops for copying rows upwards/downwards are similar -> macro
#define L(i,e,t,f,s)for(o=i;o e;){strcpy(l[o t],l[o f]);c[o t]=c[s o];}

// range check for rows/columns is similar -> macro
#define R(m,o){return b<1|b>m?m o:b;}

// checking for numerical input is needed twice (move and print command):
#define N(f)sscanf(f,"%d,%d",&i,&j)||sscanf(f,",%d",&j)

// room for 999 rows with each 999 cols (not specified, should be enough)
// also declare "current line pointers" (*L for data, *C for line length),
// an input buffer (a) and scratch variables
r,i,j,o,z,c[999],*C,x=1,y=1;char a[999],l[999][999],(*L)[999];

// move rows down from current cursor position
D()
{
    L(r,>y,,-1,--)
    r++?strcpy(l[o],l[o-1]+--x),c[o-1]=x,l[o-1][x]=0:0;
    c[y++]=strlen(l[o]);
    x=1;
}

// move rows up, appending uppermost to current line
U()
{
    strcat(*L,l[y]);
    *C=strlen(*L);
    L(y+1,<r,-1,,++)
    --r;
    *l[r]=c[r]=0;
}

// normalize positions, treat 0 as max
X(b)R(c[y-1],+1)
Y(b)R(r,)

main()
{
    for(;;)
    {
        // initialize z as current line index, the current line pointers,
        // i and j for default values of positioning
        z=i=y;L=l+--z;C=c+z;j=x;

        // prompt:
        !r||y/r&&x>*C?P"end> "):P"%d,%d> ",y,x);

        // read a line of input (using scanf so we don't need an include)
        scanf("%[^\n]%*c",a)?

        // no command arguments -> make check easier:
        a[2]*=!!a[1],

        // numerical input -> have move command:
        // calculate new coordinates, checking for "relative"
        N(a)?y=Y(i+(i<0|*a=='+')*y),x=X(j+(j<0||strchr(a+1,'+'))*x):0:

        // check for empty input, read single newline and perform <return> command:
        (*a=D(),scanf("%*c"));

        switch(*a)
        {
            A'e':y=r;x=c[r-1]+1;B;
            A'b':y=1;x=1;B;
            A'L':for(o=y-4;++o<y+2;)o<0^o<r&&P"%c%s\n",o^z?' ':'>',l[o]);for(o=x+1;--o;)P" ");P"^\n");B;
            A'l':puts(*L);B;
            A'p':i=1;j=0;N(a+2);for(o=Y(i)-1;o<Y(j);++o)puts(l[o]);B;
            A'A':y=r++;strcpy(l[y],a+2);x=c[y]=strlen(a+2);++x;++y;B;
            A'i':D();--y;x=X(0);
            // Commands i and r are very similar -> fall through from i to r
            // after moving rows down and setting position at end of line:
            A'r':strcpy(*L+x-1,a+2);*C=strlen(*L);x=1;++y>r&&++r;B;
            A'I':o=strlen(a+2);memmove(*L+x+o-1,*L+x-1,*C-x+1);*C+=o;memcpy(*L+x-1,a+2,o);x+=o;B;
            A'd':**L?**L=*C=0,x=1:U();y=y>r?r:y;B;
            A'j':y<r&&U();
        }
    }
}

This challenge leaves quite a lot of corner cases to explore -- I guess I fixed all bugs by now, but if somebody finds one more, please comment. Regarding the revisions, I removed byte counts for earlier versions that contained subtle bugs.


Implement Smokey's !!/alive command Note: SmokeDetector is a bot that detects spam and offensive posts on the network and posts alerts to chat.

What to implement
Smokey's !!/alive command uniformly at random picks one of these messages:

Yup
You doubt me?
Of course
... did I miss something?
plz send teh coffee
Watching this endless list of new questions never gets boring
Kinda sorta
You should totally drop that and use jQuery
¯\_(ツ)_/¯
... good question

and prints it to the screen.
Your task is to implement that command.
Rules
Regular code-golf — the shortest answer in bytes wins ;)
Good luck!


Find the nearest Date, given a TargetDate and Day of Week Find the nearest Date to a TargetDate for a given Day of Week.

For example, given a date of 20161219 and a day of week of Friday (6), the answer is 20161216.

Another example, given a date of 20161219 and a day of week of Wednesday (4), the answer is 20161221.

A final example, given a date of 20161219 and a day of week of Monday (2), the answer is 20161219.

Rules:

The Date format for the input and output must match. In the examples, I used yyyymmdd, but you may use any format as long as the year (at least two digits), month, and day of month are "human readable".
Day of Week is input as an integer. In my example, Sunday is the first day of the week, therefore it is day of week number 1. You can have any Day of Week numbering, as long as you note it when it differs from the example.
Years 1970 through 2030 must be accommodated.
Common language date tools and libraries are allowed, but street cred is given to those that choose not to use them.
Least number of bytes wins.

Perl 6, 83 bytes
->$_,\w{~(Date.new(|m/(....)(..)(..)/)-3...*.day-of-week%7+1==w)[*-1]~~{S:g/"-"//}}

Try it
Expanded
->     # pointy block lambda
  $_,
  \w
{
  ~(  # turn into a Str

    Date.new( |m/(....)(..)(..)/ ) - 3 # three days earlier
    ...                                # generate a sequence
    *.day-of-week % 7 + 1 == w         # stop when the right day is found

  )[*-1]  # the last one

  ~~      # apply the following block

  {
    S:g/"-"//  # remove ｢-｣
  }
}


Minimum number of platforms required for a railway station Challenge
Given daily arrival and departure times of every train that reaches a railway station, find the minimum number of platforms required for the railway station so that no train waits.
In other words, find the maximal number of trains simultaneously present in the station.
Input

a pair of lists of times: arrivals and departures; the two lists have same length; arrival i corresponds to the same train as departure i.
alternatively, a list of pairs of times, or any equivalent.
times are numbers between 0, included, and 24, excluded.
there are no dates, only times: input is the daily schedule and repeats every day.
the departure time of a train can be lower than its arrival time; in that case, the train is understood to arrive on a day and depart on the next day; that train will require a platform before midnight and after midnight.
if the arrival time is lower than the departure time, the train is understood to arrive and depart on the same day.
input can be restricted to integers

Output

one integer, the minimum required number of platforms.

Test cases

arrivals   = [10, 13, 16]
departures = [12, 15, 18]
out = 1

arrivals   = [10, 11]
departures = [12, 13]
out = 2

arrivals   = [ 1, 3, 7, 9,10,10,19,23]
departures = [11, 4,11,10,11, 2, 2, 2]
out = 5

arrivals   = [1, 2]
departures = [2, 3]
out = 2

arrivals   = [1, 2]
departures = [3, 2]
out = 2

arrivals   = [2, 22]
departures = [5,  6]
out = 2

Rules

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

Related challenges

Count the timespans

Python, 62 bytes

lambda l:max(sum(a-b^b-h^h-a<1for a,b in l)for h in range(24))

Try it online!
Golfing Surculose Sputum's solution. The new part is a-b^b-h^h-a<1 to check whether the time h lies in the interval from a to b taken cyclically, that is, their sorted ordering is a cyclic permutation of [a,h,b]. To do this, we check whether an odd number of the differences a-b, b-h,h-a are negative. I first did this with multiplication (a-b)^(b-h)^(h-a)<1. But, xor (^) lets us do the same and cuts parens with better precedence.


Find columns where all characters are the same I came across this question on SO and thought it'd make a nice golf challenge.  So here it is:

Challenge:

Write a program that reads a sequence of character strings, one per line, and outputs a list of all positions where each string has the same character.

Input and output:

The input consists of one or more lines of printable non-whitespace ASCII characters, each followed by a newline.  You may assume that all input lines have the same length.  The newline is not to be considered part of the input (i.e. you should not output it as a matching character).

Example input (shamelessly stolen from the SO question):

abcdefg
avcddeg
acbdeeg

After reading the input, your program should print the positions of each matching column and the characters they contain.  (Your program may, but need not, stop reading further input if it can determine early that there are no matching columns.)  Any reasonable output format is permitted; in particular, you may use either 0-based or 1-based indexing for the positions.

Example output for the above input (using 0-based indexing):

0: a
3: d
6: g

Scoring:

This is code golf, so shortest answer wins.  In the event of a tie, fractional tie-breaker chars may be awarded for additional features:

−½ chars for correctly handling input lines of unequal length.  (Output should not contain positions past the end of the shortest input line.)
−¼ chars for correctly handling input consisting of arbitrary UTF-8 encoded Unicode characters.

For inspiration, you may find some ungolfed solutions at the SO question (see above).

Clarifications:

Simply concatenating the positions and characters, as in 0a3d6g, does not count as "reasonable output".  You should provide some kind of separator (such as a space) between each element of the output so that it can be parsed unambiguously.
The input will be provided on the standard input stream (stdin), or using whatever text file input mechanism is most natural to your language of choice.  (If your chosen language doesn't have a natural mechanism for file input, do whatever seems closest in spirit.)
The input ends when there is no more data to be read (i.e. when an end-of-file condition occurs).  If you wish, you may require that the input be terminated by a blank line (which you then should not count as part of the input, obviously).  If you do so, please mention it in your answer so that others can provide correct input for testing.
Every input line, including the last one, ends with a newline character.  Your answer must not report this newline as a matching column.  (It's fine if your solution can also handle input where the last line doesn't end in a newline, but that's not required.)

APL, 25 characters

∩/{0=⍴⍵:⍬⋄(⊂⍵,⍨¨⍳⍴⍵),∇⍞}⍞

I used Dyalog APL (version 13) as my interpreter. It handles both inputs of unequal length and Unicode (UTF-8) characters.

Examples:

      ∩/{0=⍴⍵:⍬⋄(⊂⍵,⍨¨⍳⍴⍵),∇⍞}⍞
abcdefg
avcddeg
acbdeeg

  1 a  4 d  7 g

      ∩/{0=⍴⍵:⍬⋄(⊂⍵,⍨¨⍳⍴⍵),∇⍞}⍞
test日本
blat日本国foo

  4 t  5 日  6 本

Explanation, somewhat from right to left:

The main chunk of this answer is the direct function (basically, anonymous function), defined within the curly braces. Its right argument is specified by ⍵.

0=⍴⍵:⍬ is our first expression, and it checks if we've gotten an empty line (i.e., we are done). It uses a guard (a familiar construct to many functional programmers) to conditionally execute the expression to the right of the colon. In this case, if 0 is equal to the shape/length (⍴) of the right argument, we return the empty set (⍬).
⋄ separates the two expressions within the function. If the previous expression didn't get evaluated (and thus didn't return anything), we move to the next expression.
We recursively call the function using the self-reference function (∇). The argument to the function is a line of non-evaluated user input, given by quote-quad (⍞).
⊂⍵,⍨¨⍳⍴⍵ creates pairs for each character in the string, where each pair's first element is its position in the string, and its second element is the character.
⍳⍴⍵ gives a vector from 1 to ⍴⍵, or the length of the input string.
⍵,⍨¨ applies the commuted concatenation function (,⍨) to each (¨) element to its left (⍵, in this case the user's input) and right. Commuting the concatenation function causes its left and right arguments to be swapped.
Finally, we enclose the result using ⊂, so that we can differentiate between lines of input.

We initially feed our function with user input (⍞).
Finally, we reduce (/) our resulting vector of vectors of pairs using the intersection function (∩), yielding the pairs that are found in all of the sub-vectors.


Volumes of ASCII boxes Introduction

In this challenge, you are given as input the ASCII representation of the net (unfolded surface) of a rectangular cuboid (3D box).
The format is this:

....+--+.......
....|##|.......
....|##|.......
....|##|.......
+---+--+---+--+
|###|##|###|##|
+---+--+---+--+
....|##|.......
....|##|.......
....|##|.......
....+--+.......

Each face of the cuboid is a rectangle of #s surrounded by +-|-characters.
The outside of the net is filled with .s.
The net will always have the same orientation: there's a middle face surrounded by its four neighboring faces, and the counterpart of the middle face is at the right border of the input.
The input is padded with .s to a rectangular shape and will not contain extra rows or columns of .s.

The task

Your task is to take as input a diagram as above, and compute the volume of the cuboid that it represents, which is just the product of its height, width and depth.
You can take the input as a newline-delimited string or an array of strings.

The length of each edge is the distance between the +-characters at its two ends.
For example, the horizontal edge +--+ has length 3, and the vertical edge

+
|
|
|
+

has length 4.
The minimum length of an edge is 1.
The example cuboid above has volume 2*3*4 = 24.

Rules and scoring

You can write a full program or a function, and the lowest byte count wins.

Test cases

.++..
+++++
+++++
.++..
1

...++....
...||....
...||....
+--++--++
+--++--++
...||....
...||....
...++....
3

..+-+....
..|#|....
+-+-+-+-+
|#|#|#|#|
|#|#|#|#|
+-+-+-+-+
..|#|....
..+-+....
12

.+---+.....
++---++---+
||###||###|
||###||###|
||###||###|
++---++---+
.+---+.....
16

....++.....
....||.....
....||.....
....||.....
+---++---++
|###||###||
|###||###||
|###||###||
+---++---++
....||.....
....||.....
....||.....
....++.....
16

...+--+......
...|##|......
...|##|......
+--+--+--+--+
|##|##|##|##|
+--+--+--+--+
...|##|......
...|##|......
...+--+......
18

....+--+.......
....|##|.......
....|##|.......
....|##|.......
+---+--+---+--+
|###|##|###|##|
+---+--+---+--+
....|##|.......
....|##|.......
....|##|.......
....+--+.......
24

....+-----+..........
....|#####|..........
....|#####|..........
....|#####|..........
+---+-----+---+-----+
|###|#####|###|#####|
|###|#####|###|#####|
|###|#####|###|#####|
|###|#####|###|#####|
+---+-----+---+-----+
....|#####|..........
....|#####|..........
....|#####|..........
....+-----+..........
120

Retina, 29 28 bytes

T`.p`xy`\G\..+¶
xy

¶\|
$`
y

Try it online!

There's a lot of ways to approach this in Retina, depending on which area you want to multiply with which side, so I'm not sure how optimal this is, but it's actually already a lot shorter than I thought it would be.

I've currently got two other solutions at the same byte count which seem a bit more golfable than the above approach:

\G\..+¶

¶\|
$'¶
G`\.
T`.|+

¶\||\+¶\.\D+
$'¶
G`\.
T`.|+

Although in these I could save a byte each if I assume that the input ends with a trailing linefeed, but I'd rather not have to rely on that.

And another one, still at 28 bytes (this one actually multiplies three sides instead of multiplying one area by a side):

\G\.
x
-(?<=^.+)
$`
¶\|
$`
x

Explanation

The main idea is to multiply the area of the face on top by the length of the vertical side that touches the length border of the input.

I'll use the following input as an example (it has side lengths 2, 3 and 4, so an area of 24):

...+---+.......
...|###|.......
...|###|.......
+--+---+--+---+
|##|###|##|###|
+--+---+--+---+
...|###|.......
...|###|.......
...+---+.......

Stage 1: Transliterate

T`.p`xy`\G\..+¶

The regex \G\..+¶ matches a line which starts with . and is immediately adjacent to the previous line. So this matches all the lines that contain the top face. The stage itself turns . into x and all other characters (any of |+-#) into y. This gives us the following result:

xxxyyyyyxxxxxxx
xxxyyyyyxxxxxxx
xxxyyyyyxxxxxxx
+--+---+--+---+
|##|###|##|###|
+--+---+--+---+
...|###|.......
...|###|.......
...+---+.......

This has one more column of y than we need to represent the area of the top face. We fix this with the next stage.

Stage 2: Replace

xy

So we match a y that is preceded by an x (which is exactly one of them per line) and remove them both from the string. We get this:

xxyyyyxxxxxxx
xxyyyyxxxxxxx
xxyyyyxxxxxxx
+--+---+--+---+
|##|###|##|###|
+--+---+--+---+
...|###|.......
...|###|.......
...+---+.......

So now we've got the area of the top face represented by the number of ys.

Stage 3: Replace

¶\|
$`

Our goal here is to multiply this area A by the missing side length, which is the number of | at the beginning of a line plus 1. However, it's actually easier to multiply by a number n+1 because we've already got one copy of A in the string. If we replace n things with A, we end up with n+1 copies of A. This makes things a lot easier for us.

So we simply replace any | immediately after a linefeed with everything in front of the match. This mangles the string quite a lot and makes it a fair bit larger than we need, but the number of ys ends up being the result we're looking for:

xxyyyyxxxxxxx
xxyyyyxxxxxxx
xxyyyyxxxxxxx
+--+---+--+---+xxyyyyxxxxxxx
xxyyyyxxxxxxx
xxyyyyxxxxxxx
+--+---+--+---+##|###|##|###|
+--+---+--+---+
...|###|.......
...|###|.......
...+---+.......

Stage 4: Match

y

All that's left is to count the number of ys, which is printed as a decimal number at the end.


The sequence is too meta We start with a blank 1-indexed sequence:

_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,...

In the nth step, we fill in every a(n) blanks with the integers greater than 1 starting at the first remaining blank, where a(n) is the nth entry in the sequence.

After the first step:

2,_,3,_,4,_,5,_,6,_,7,_,8,_,9,_,10,_,11,_,12,_,13,_,...

Note that a(1) has to be 2 because the first integer greater than 1 is 2.

In the second step, we fill in every a(2) blanks. It will be apparent that a(2) must be 2.

2,2,3,_,4,3,5,_,6,4,7,_,8,5,9,_,10,6,11,_,12,7,13,_,...

In the third step, we fill in every a(3) blanks. From the sequence, a(3) = 3.

2,2,3,2,4,3,5,_,6,4,7,_,8,5,9,3,10,6,11,_,12,7,13,_,...

In the fourth step, we fill in every a(4) blanks. From the sequence, a(4) = 2.

2,2,3,2,4,3,5,2,6,4,7,_,8,5,9,3,10,6,11,3,12,7,13,_,...

Eventually:

2,2,3,2,4,3,5,2,6,4,7,2,8,5,9,3,10,6,11,3,12,7,13,2,...

Task

Given n, return the nth element of the sequence.

The first 10,000,000 terms of the sequence can be found here.

This is code-golf. Shortest answer in bytes wins. Standard loopholes apply.

Haskell, 80 67 bytes

g~(a:b)|let k!l=k:take(a-1)l++(k+1)!drop(a-1)l=2!g b
m=g m
(!!)$0:m

Try it online!

Haskell is the perfect language for defining an infinite list in terms of itself.


Turtles All the Way Down Write a program or function that takes in a positive integer and prints or returns a stack of that many ASCII-art turtles, where each turtle is larger than the one above it.

Specifically, if the input is 1, the output should be:

 __
/,,\o

If the input is 2:

  __
o/,,\
 ____
/,__,\o

If the input is 3:

   __
  /,,\o
  ____
o/,__,\
 ______
/,____,\o

If the input is 4:

    __
  o/,,\
   ____
  /,__,\o
  ______
o/,____,\
 ________
/,______,\o

If the input is 5:

     __
    /,,\o
    ____
  o/,__,\
   ______
  /,____,\o
  ________
o/,______,\
 __________
/,________,\o

And so on in the same pattern for larger inputs.

Note that:

The head (the o) of the bottom turtle is always on the right. The heads of the turtles above then alternate back and forth.
No lines may have trailing spaces.
Superfluous leading spaces are not allowed. (i.e. the back of the bottom turtle should be at the start of the line.)
A single optional trailing newline is allowed.

The shortest code in bytes wins.

Batch, 256 bytes

@set i=echo
@%i%off
set u=
for /l %%j in (2,2,%1)do call set i=%%i%%
set/af=%1^&1
if %f%==1 %i% __&%i%/,,\o&set u=__
for /l %%j in (2,2,%1)do call:l
exit/b
:l
set i=%i:~0,-2%
%i%  _%u%_
%i%o/,%u%,\
%i% __%u%__
%i%/,_%u%_,\o
set u=__%u%__

Note that line 1 has a trailing space and line 4 has two trailing spaces. i therefore contains an echo command with the appropriate amount of indentation for each turtle. Meanwhile u contains the number of underscores in alternate turtles. A leading odd turtle is special-cased and then the rest of the turtles are output in pairs.


Detect loops in a linked list This comes from one of my favorite interview questions, though apparently it is now a fairly well-known puzzle. I have no way of knowing, but if you have already heard the answer it would be polite to let others try instead.

Task:

Write a function that takes as input a singly-linked list and returns true if it loops back on itself, and false if it terminates somewhere.

Here's some example code in C as a starting point so you can see what I mean, but feel free to write your answer in whatever language you like:

struct node
{
    void *value;
    struct node *next;
};

int has_loops(struct node *first)
{
    /* write your own loop detection here */
}

Hints:

There is a way to make this function run in O(n) time with a constant amount of extra memory. Good on you if you figure it out, but any working answer deserves some upvotes in my book.

C, non-golfed

The idea is to have to pointers p1 and p2 that traverse the list. p2 moves twice as fast as p1. If p2 reaches p1 at some point then there is a loop. Here is the C code (not tested, though).

struct node
{
  void *value;
  struct node *next;
};

int has_loops(struct node *p)
{
  struct node *p1 = p, *p2 = p->next;
  if (!p2) return 0;

  while (p1 != p2) {
    // p1 goes one step
    p1 = p1->next;
    if (!p1) return 0;

    // p2 goes two steps
    p2 = p2->next;
    if (!p2) return 0;
    p2 = p2->next;
    if (!p2) return 0;
  }

  return 1;
}


Creating a falling ball map Introduction
For the ones who never heard of this game before. You are playing a ball which needs to survive as long as possible. This is done by moving to the left or right, going to the holes. Since the map moves upwards, you need to go downwards to survive longer. If you search for images, you probably know which game I mean.
The Task
Given a positive integer n, output a falling ball map of n layers. Between the layers, there are 4 newlines. The width of the layer is made up of 25 underscore characters, with one hole of length 5. That means that the total width is equal to 30. This is randomly shifted after each layer. An example of a valid layer is:
_______________     __________

The hole can also be at the edges, as if the layer is like a cylinder:
  _________________________

Note that there are 2 leading spaces and 3 trailing spaces. Making a single hole of width 5.
Test cases
For n=4, this is a valid output:
_______________     __________

______     ___________________

_______________________     __

  _________________________

Note: the holes must be uniformly distributed. Trailing and/or leading newlines are allowed.
This is code-golf, so the submission with the least amount of bytes wins!

Pyth, 19 bytes

VQ.>+*\_25*d5O30*b4

Try it here!

Explanation

VQ.>+*\_25*d5O30*b4  # Q = input

VQ                   # Repeat Q times
     *\_25           # 25 underscores
          *d5        # 5 spaces
    +                # concat the underscores and spaces
  .>         O25     # rotate this string 0-29 times
                *b4  # print the seperating newlines


"Fill the Grid" Problem A challenge with simple rules but non-trivial algorithms. :-)

Task

Take input in the form of space-separated integers:

N A B S

Where N is the side length of a 2D square matrix filled with unique numbers (integers) between A and B inclusive. For each row and column in this matrix, the sum is always the same: S. (In other words, the matrix is a semi-magic square).

Note:

All numbers are positive. Exception is A, which can be 0.

Examples

For

3 1 10000 2015

a valid solution would be

For

8 1 300 500

a valid solution would be

Output

You output should be an ASCII table. Example for the first example above:

 384  159 1472
1174  499  342
 457 1357  201

Right-aligned integers padded by spaces. The width of each column is the width of the largest integer in that column.

Scoring

This is code-golf, so shortest code in bytes wins. Standard loopholes apply (especially about built-ins to solve this problem). You don't have to care about wrong or otherwise impossible inputs (including negative numbers). Please provide a sample output in your answer (mandatory) for the second example above.

CJam, 119 91 bytes

q~:M;),>:R;(:L{{R{ML)d/-Y#)mr}$L/L<2{{M1$:+-+}%z}*:U:+__O|=R*-}gU{:s_:,:e>f{Se[}}%zSf*N*}M?

This is a provably correct, non-deterministic approach.

On my desktop, the second test case generally finishes in less than 10 minutes.

The first case finishes instantly. Try it online in the CJam interpreter.

Sample run

$ cjam grid.cjam <<< '8 1 300 500'
77  66  37 47  56  46 86  85
63 102  70 72  49  54 81   9
62  69  58 57  71  17 48 118
64  65  67 87  53  44 80  40
73  60  55 89  51  76 84  12
68  59  28 78  74  38 50 105
61  75  52 43 125  83 42  19
32   4 133 27  21 142 29 112

Idea

Without time limits, we could just randomly generate squares until finding a valid square. This approach builds on that idea, adding two optimizations:

Instead of pseudo-randomly generating square of side length N, we generate squares of side length N-1, add one column to form a N × (N-1) rectangle whose rows have sum S, then one row to form a square of side length N whose columns have sum S.

Since the sum of the elements of all columns will be NS and the sum of the elements of the first N-1 rows is (N-1)S, the last row will also have sum S.

However, this process may generate an invalid matrix, since there's no guarantee that all elements of the last row and column will be unique or fall in the range [A ... B].
Picking a square of unique integers in [A ... B] and side length N-1 uniformly at random would take way too long. We somehow have to prioritize squares that have a higher chance of resulting in a valid square of side length N after applying the process detailed in the previous bullet point.

Given that each row and column has to have a sum of S, its elements have an average of S/N. Thus, picking more elements close to that average should increase our chances.

For each I in [A ... B], we pseudo-randomly pick a float between 0 and (I - S/N)2 + 1 and sort the elements of [A ... B] by the picked floats. We keep the first N2 numbers and place them in reading order in a square.

Assuming a perfectly uniform distribution of all real numbers between 0 and (I - S/N)2 + 1 in each step, all squares have a non-zero probability of being picked, meaning that the process will finish eventually.

Code

q~          e# Read all input from STDIN and evaluate it.
:M;         e# Save "S" in M and discard it from the stack.
),>:R;      e# Transform "A B" into [A ... B], save in R and discard.
(:L         e# Save "N - 1" in L and keep it on the stack.
{           e# If L is non-zero:
  {         e#   Do:
    R{      e#     For each I in R:
      ML)d/ e#       Compute M/Double(L+1).
      -Y#   e#       Subtract the result from I and square the difference.
      )mr   e#       Add 1 and pick a non-negative Double below the result.
    }$      e#     Sort the values of I according to the picks.
    L/      e#     Split the shuffled R into chunks of length L.
    L<      e#     Keep only the first L chunks.
    2{      e#     Do twice:
      {     e#       For each row of the  L x L array.
        M1$ e#       Push M and a copy of the row.
        :+- e#       Add the integers of the row and subtract their sum from M.
        +   e#       Append the difference to the row.
      }%    e#
      z     e#       Transpose rows and columns.
    }*      e#
    :U:+    e#     Save the result in U and concatenate its rows.
    __O|    e#     Push two copies. Deduplicate the second copy.
    =R*     e#     Push R if all elements are unique, an empty array otherwise.
    -       e#     Remove the result's elements from U's elements.
  }g        e#   If the resulting array is non-empty, repeat the loop.
  U{        e#   For each row in U:
    :s      e#     Convert its integers into strings.
    _:,     e#     Copy and replace each string with its length.
    :e>     e#     Compute the maximum length.
    f{      e#     For each integer, push the maximum length; then
      Se[   e#       Left-pad the integer with spaces to that length.
    }       e#
  }%        e#
  z         e#   Transpose rows with columns.
  Sf*N*     e#   Join columns by spaces, rows by linefeeds.
}M?         e# Else, push M.