问:
Super speedy totient function
The goal is simple: calculate the totient function for as many numbers as you can in 10 seconds and sum the numbers.

You must print your result at the end and you must actually calculate it. No automated totient function is allowed, but bignum libraries are. You have to start at 1 and count up all the integers consecutively. You are not allowed to skip numbers.

Your score is how many numbers your program can calculate on your machine / how many my program can calculate on your machine. My code is a simple program in C++ (optimizations off), hopefully you can run it.

Important properties you could use!

if gcd(m,n) = 1, phi(mn) = phi(m) * phi(n)

if p is prime, phi(p) = p - 1 (for p < 10^20)

if n is even, phi(2n) = 2 phi(n)

others listed in first link

My code

#include <iostream>
using namespace std;

int gcd(int a, int b)
{
    while (b != 0)
    {
        int c = a % b;
        a = b;
        b = c;
    }
    return a;
}

int phi(int n)
{
    int x = 0;
    for (int i=1; i<=n; i++)
    {
        if (gcd(n, i) == 1)
            x++;
    }
    return x;
}

int main()
{
    unsigned int sum = 0;
    for (int i=1; i<19000; i++) // Change this so it runs in 10 seconds
    {
        sum += phi(i);
    }
        cout << sum << endl;
        return 0;
}
```

答:
Here is my Python implementation that seems to be able to crank out ~60000 numbers in 10seconds. I am factorizing numbers using the pollard rho algorithm and using the Rabin miller primality test.

from Queue import Queue
import random

def gcd ( a , b ):
    while b != 0: a, b = b, a % b
    return a

def rabin_miller(p):
    if(p<2): return False
    if(p!=2 and p%2==0): return False
    s=p-1
    while(s%2==0): s>>=1
    for _ in xrange(10):
        a=random.randrange(p-1)+1
        temp=s
        mod=pow(a,temp,p)
        while(temp!=p-1 and mod!=1 and mod!=p-1):
            mod=(mod*mod)%p
            temp=temp*2
        if(mod!=p-1 and temp%2==0): return False
    return True

def pollard_rho(n):
    if(n%2==0): return 2;
    x=random.randrange(2,1000000)
    c=random.randrange(2,1000000)
    y=x
    d=1
    while(d==1):
        x=(x*x+c)%n
        y=(y*y+c)%n
        y=(y*y+c)%n
        d=gcd(x-y,n)
        if(d==n): break;
    return d;

def primeFactorization(n):
    if n <= 0: raise ValueError("Fucked up input, n <= 0")
    elif n == 1: return []
    queue = Queue()
    factors=[]
    queue.put(n)
    while(not queue.empty()):
        l=queue.get()
        if(rabin_miller(l)):
            factors.append(l)
            continue
        d=pollard_rho(l)
        if(d==l):queue.put(l)
        else:
            queue.put(d)
            queue.put(l/d)
    return factors

def phi(n):

    if rabin_miller(n): return n-1
    phi = n
    for p in set(primeFactorization(n)):
        phi -= (phi/p)
    return phi

if __name__ == '__main__':

  n = 1
  s = 0

  while n < 60000:
    n += 1
    s += phi(n)
  print(s)
```

Title: Super speedy totient function


问:
Unlocking the Secrets to a 1-Dimensional Labyrinth

Background

You awake to find yourself lost in a one dimensional labyrinth! A mystical genie (or something) appears and explains that the exit lies in front of you, but that between you and the exit is a series of challenges. As you wander forward you realize that all of the so-called challenges are merely locked doors. You first see a door with a tee-shaped key-hole, and having no such key yourself, retrace your steps, looking for a key with a T shape.

Frustrated, you find an alphabet soup of keys on the ground, none of which match the door you've come across. By some stroke of genius (or idiocy), you decide that the lower-case t-shaped key might be able to fit in the slot if you jam it in there hard enough. As you approach the door with the lower-case t key in hand, the T hole glows green and the door dissolves in front of you.

One down, many more to go...

Challenge

The goal of this challenge is to mark how many steps it takes you to exit the labyrinth.

The input of this challenge is the labyrinth: one string containing only  characters [A-Za-z^$ ].
Glossary:

^ -- The start space. The input will contain exactly one ^.

$ -- The exit (freedom!). The input will contain exactly one $.

[A-Z] -- Capital letters signify doors. You can only go through this door if you have already collected the requisite key.

[a-z] -- Lower case letters signify keys. You collect these keys by walking onto the space that contains the key.

There will be at most one of each capital letter in the input. This means the total number of doors will be between 0-26 inclusive.

Every locked door [A-Z] will have exactly one corresponding lower case key [a-z]. There may be any number of spaces ( ) in the input.

All of the doors will be to the right of the start, and to the left of the exit. Thus there will be no superfluous doors. All inputs will be solvable.

The output for this challenge will be a number, the number of steps it took to exit the labyrinth.

Algorithm

Your methodical approach to exiting this wretched place is as follows:

Start at the beginning (^) and move forward (right) collecting any keys you come across.

When you come across a door, if you have the correct key, you proceed forward onto the door. If you don't have the correct key, you walk backwards (left) collecting keys you come across until you find the key for the most recent door that you couldn't open.

Once you collect the key for the current troublesome door, you turn back to the right and proceed onward.

Repeat this process until you step on to the exit ($).

Experienced golfers will understand that your code doesn't have to implement this specific algorithm as long as it outputs the same result as if you had run this algorithm.

Counting

Each time you step from one square onto another square, that counts as one step. Turning 180º incurs no additional step. You cannot step forward onto a door without the requisite key. You must step onto a key to pick it up, and must step onto the exit to win. After your first move, the start space (^) behaves just like any other regular space.

Examples

In these examples I've left the spaces as underscores for human-readability.

Input is _a_^_A__$__. The output is 11. You take 1 step forward, notice that you have no key for the A door, and then about face. You walk backward until you occupy the space containing the a (3 steps backward, now 4 total). You then walk forward until you occupy the space containing the exit (7 steps forward, 11 total).

Input is b__j^__a_AJB_$. The output is 41 You make two separate trips to the back of the labyrinth, one to get the j key, and the next one to get the b key.

Input is __m__t_^__x_T_MX_$____. The output is 44. You won't make any extra trip to get the x key, as you picked it up on your way from the start to door T.

Input is g_t_^G_T$. The output is 12. You cannot move onto the G space without a key, and immediately about-face. You're lucky enough to pick up the t key on the way to the g key, and thus open both doors on your way to freedom.

Input is _^_____$. The output is 6. That was easy.

I/O Guidelines and Winning Criterion

Standard I/O rules apply. This is a code-golf challenge.

答:
PHP 5.3, 123 bytes

This is my first post on Code Golf, hopefully this is of golfing quality high enough for a first post. Definitely a fun challenge and an awesome question!

```<code>function n($m){while('$'!=$o=$m[$i++])$o=='^'?$b=$i+$c=0:$o>'Z'||$b<=$k=stripos($m,$o))?$c++:$c+=2*$i-3-2*$b=$k;return$c;}
</code>```

This program nicely abuses the fact that PHP doesn't need you to pre-declare any variables before you use them.

It also turned out to be a couple bytes shorter in my final solution to start at 0 and reset the step count when the start character is found, rather than starting at the '^'.

Any tips are definitely welcome!

ContentLicense: CC BY-SA 3.0

Body:
PHP 5.3, 123 bytes

This is my first post on Code Golf, hopefully this is of golfing quality high enough for a first post. Definitely a fun challenge and an awesome question!

function n($m){while('$'!=$o=$m[$i++])$o=='^'?$b=$i+$c=0:$o>'Z'||$b<=$k=stripos($m,$o))?$c++:$c+=2*$i-3-2*$b=$k;return$c;}

This program nicely abuses the fact that PHP doesn't need you to pre-declare any variables before you use them.

It also turned out to be a couple bytes shorter in my final solution to start at 0 and reset the step count when the start character is found, rather than starting at the '^'.

Any tips are definitely welcome!


问:
Write an interpreter for my new programming language
I have a new programming language called Brussels-Sprout. Brussels-Sprout functions in an array of 256 boolean values, all initialized to zero, has one instruction pointer, and one "bit index".

After each (non-branching) instruction is executed, the instruction pointer is incremented by one. If the instruction pointer goes off the right side of the instruction array, the program terminates. Going off the left side is undefined behavior.

If the bit index is outside the bounds of the array, it should be reset to 0.

Brussels-Sprout uses the following keywords, which are always lowercase:

chew - Invert the value in the array at the bit index. (flip the bit at the bit index)

swallow - Increment the bit index.

vomit - Decrement the bit index.

complain - Output the bit at the bit index to stdout, or equivalent output log.

feedtodog - If the bit at the bit index is 0, skip the next instruction. Otherwise, increment instruction pointer by 1.

playwithfood - If the bit at the bit index is 1, jump backwards 2 instructions. Otherwise, increment instruction pointer by 1.

If an instruction not on this list is executed, undefined behavior occurs.

I'm sure that this sounds like a very certain other turing-tarpit programming language. But since this programming language operates in boolean values and not bytes, I think it is different.

Test cases:

```<code>chew complain -> 1
swallow chew swallow chew swallow vomit complain playwithfood -> 11
chew complain swallow chew complain swallow chew complain swallow complain -> 1110
chew feedtodog undefinedbehaviour complain -> 1
</code>```

Your challenge is to write an interpreter for Brussels-Sprout. This is code golf, so shortest program wins!

答:
Java 8

1. Relaxed version (<s>301</s> <s>283</s> <s>280</s> <s>277</s> 275 bytes)

Golfed as this:

class C{static int i,j,x,b[]=new int[256];public static void main(String[]z){Runnable[]r=new Runnable[26];r[20]=()->b[i]=-~x;r[9]=()->i++;r[6]=()->i--;r[13]=()->System.out.print(x);r[1]=()->j+=x;r[22]=()->j-=3*x;for(;;){x=b[i];r[z[j].charAt(3)-99].run();i*=~(i>>8)&1;j++;}}}
```

<p>Somewhat ungolfed version (whitespaces and comments added):</p>

<pre class="lang-java prettyprint-override"><code>class C {
    // Declared as static so they may be changed inside the lambdas without the compiler complaining about that.
    // i is the bit index and j is the instruction pointer.
    // x is just to avoid refering to b[i] in order to save 3 bytes.
    // b is our array. Uses ints instead of booleans to save bytes and use some clever math tricks.
    static int i, j, x, b[] = new int[256];

    public static void main(String[] z) {

        // An array of lambdas. The index is the ascii code of 4th letter of the command name subtracted from 99.
        // Thanks for CatsAreFluffy for telling about the 4th letter trick.
        Runnable[] r = new Runnable[26];
        r[20] = () -> b[i] = -~x; // chew
        r[9] = () -> i++; // swallow
        r[6] = () -> i--; // vomit
        r[13] = () -> System.out.print(x); // complain
        r[1] = () -> j += x; // feedtodog. It is 1 or 0 instead of 2 and 1 due to the j++ down there.
        r[22] = () -> j -= 3 * x; // playwithfood. It is -3 or 0 instead of -2 and +1 due to the j++ down there.

        // This is the interpreter itself. Runs forever (or until an exception is raised).
        for (;;) {
            x = b[i];

            // Fetch an instruction and runs it. May throw an exception or execute some arbitrary instruction if the instruction name is unknown or was mistyped.
            r[z[j].charAt(3) - 99].run();

            // Resets the bit index if out of range.
            i *= ~(i >> 8) & 1;

            // Next instruction. No special treatment for branching needed because they already considers this.
            j++;
        }
    }
}
</code>```

We surely should have testcases. I am not sure if there is some bug hiding out there.

Anyway I run it with that (input is given as command line arguments):

chew complain swallow chew complain swallow chew complain swallow complain
```

<p>And here is the output:</p>

```1110
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at C.main(C.java:1)
```

<p>The <code>ArrayIndexOutOfBoundsException</code> is the standard way to finish the program, it is not a bug!</p>

<p>BTW, this answer abuses the fact that the 4th char of each command is different than each other (thanks CatsAreFluffy). This means that <code>whew</code> is interpreted as <code>chew</code> and that <code>yellow</code> is interpreted as <code>swallow</code>.</p>

<h2>2. Strict version (<s>354</s> <s>337</s> <s>334</s> <s>331</s> 329 bytes)</h2>

<p>If strict conformance to command names are required (and just looking for the 4th letter in command's name is not enough), then I have this alternative similar answer with 329 bytes:</p>

<pre class="lang-java prettyprint-override"><code>import java.util.*;class C{static int i,j,x,b[]=new int[256];public static void main(String[]z){List o=Arrays.asList("chew","swallow","vomit","complain","feedtodog","playwithfood");Runnable[]r={()->b[i]=-~x,()->i++,()->i--,()->System.out.print(x),()->j+=x,()->j-=3*x};for(;;){x=b[i];r[o.indexOf(z[j])].run();i*=~(i>>8)&1;j++;}}}
</code>```

Somewhat ungolfed version (whitespaces and comments added):

// Needed for java.util.List and java.util.Arrays.
import java.util.*;

class C {
    // Declared as static so they may be changed inside the lambdas without the compiler complaining about that.
    // i is the bit index and j is the instruction pointer.
    // x is just to avoid refering to b[i] in order to save 3 bytes.
    // b is our array. Uses ints instead of booleans to save bytes and use some clever math tricks.
    static int i, j, x, b[] = new int[256];

    public static void main(String[] z) {

        // Declared as a list so we can use the indexOf method further down. Screw up the generics.
        List o = Arrays.asList("chew", "swallow", "vomit", "complain", "feedtodog", "playwithfood");

        // An array of lambdas.
        Runnable[] r = {
            () -> b[i] = -~x, // chew
            () -> i++, // swallow
            () -> i--, // vomit
            () -> System.out.print(x), // complain
            () -> j += x, // feedtodog. It is 1 and 0 instead of 2 and 1 due to the j++ down there.
            () -> j -= 3 * x // playwithfood. It is -3 and 0 instead of -2 and +1 due to the j++ down there.
        };

        // This is the interpreter itself. Runs forever (or until an exception is raised).
        for (;;) {
            x = b[i];

            // Fetch an instruction and runs it. Throws an exception on unknown or mistyped instructions.
            r[o.indexOf(z[j])].run();

            // Resets the bit index if out of range.
            i *= ~(i >> 8) & 1;

            // Next instruction. No special treatment for branching needed because the branching instructions already considers this.
            j++;
        }
    }
}
```

Body:
Java 8

1. Relaxed version (<s>301</s> <s>283</s> <s>280</s> <s>277</s> 275 bytes)

Golfed as this:

class C{static int i,j,x,b[]=new int[256];public static void main(String[]z){Runnable[]r=new Runnable[26];r[20]=()->b[i]=-~x;r[9]=()->i++;r[6]=()->i--;r[13]=()->System.out.print(x);r[1]=()->j+=x;r[22]=()->j-=3*x;for(;;){x=b[i];r[z[j].charAt(3)-99].run();i*=~(i>>8)&1;j++;}}}

Somewhat ungolfed version (whitespaces and comments added):

class C {
    // Declared as static so they may be changed inside the lambdas without the compiler complaining about that.
    // i is the bit index and j is the instruction pointer.
    // x is just to avoid refering to b[i] in order to save 3 bytes.
    // b is our array. Uses ints instead of booleans to save bytes and use some clever math tricks.
    static int i, j, x, b[] = new int[256];

    public static void main(String[] z) {

        // An array of lambdas. The index is the ascii code of 4th letter of the command name subtracted from 99.
        // Thanks for CatsAreFluffy for telling about the 4th letter trick.
        Runnable[] r = new Runnable[26];
        r[20] = () -> b[i] = -~x; // chew
        r[9] = () -> i++; // swallow
        r[6] = () -> i--; // vomit
        r[13] = () -> System.out.print(x); // complain
        r[1] = () -> j += x; // feedtodog. It is 1 or 0 instead of 2 and 1 due to the j++ down there.
        r[22] = () -> j -= 3 * x; // playwithfood. It is -3 or 0 instead of -2 and +1 due to the j++ down there.

        // This is the interpreter itself. Runs forever (or until an exception is raised).
        for (;;) {
            x = b[i];

            // Fetch an instruction and runs it. May throw an exception or execute some arbitrary instruction if the instruction name is unknown or was mistyped.
            r[z[j].charAt(3) - 99].run();

            // Resets the bit index if out of range.
            i *= ~(i >> 8) & 1;

            // Next instruction. No special treatment for branching needed because they already considers this.
            j++;
        }
    }
}

We surely should have testcases. I am not sure if there is some bug hiding out there.

Anyway I run it with that (input is given as command line arguments):

chew complain swallow chew complain swallow chew complain swallow complain

And here is the output:

1110
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at C.main(C.java:1)

The ArrayIndexOutOfBoundsException is the standard way to finish the program, it is not a bug!

BTW, this answer abuses the fact that the 4th char of each command is different than each other (thanks CatsAreFluffy). This means that whew is interpreted as chew and that yellow is interpreted as swallow.

2. Strict version (<s>354</s> <s>337</s> <s>334</s> <s>331</s> 329 bytes)

If strict conformance to command names are required (and just looking for the 4th letter in command's name is not enough), then I have this alternative similar answer with 329 bytes:

import java.util.*;class C{static int i,j,x,b[]=new int[256];public static void main(String[]z){List o=Arrays.asList("chew","swallow","vomit","complain","feedtodog","playwithfood");Runnable[]r={()->b[i]=-~x,()->i++,()->i--,()->System.out.print(x),()->j+=x,()->j-=3*x};for(;;){x=b[i];r[o.indexOf(z[j])].run();i*=~(i>>8)&1;j++;}}}

Somewhat ungolfed version (whitespaces and comments added):

// Needed for java.util.List and java.util.Arrays.
import java.util.*;

class C {
    // Declared as static so they may be changed inside the lambdas without the compiler complaining about that.
    // i is the bit index and j is the instruction pointer.
    // x is just to avoid refering to b[i] in order to save 3 bytes.
    // b is our array. Uses ints instead of booleans to save bytes and use some clever math tricks.
    static int i, j, x, b[] = new int[256];

    public static void main(String[] z) {

        // Declared as a list so we can use the indexOf method further down. Screw up the generics.
        List o = Arrays.asList("chew", "swallow", "vomit", "complain", "feedtodog", "playwithfood");

        // An array of lambdas.
        Runnable[] r = {
            () -> b[i] = -~x, // chew
            () -> i++, // swallow
            () -> i--, // vomit
            () -> System.out.print(x), // complain
            () -> j += x, // feedtodog. It is 1 and 0 instead of 2 and 1 due to the j++ down there.
            () -> j -= 3 * x // playwithfood. It is -3 and 0 instead of -2 and +1 due to the j++ down there.
        };

        // This is the interpreter itself. Runs forever (or until an exception is raised).
        for (;;) {
            x = b[i];

            // Fetch an instruction and runs it. Throws an exception on unknown or mistyped instructions.
            r[o.indexOf(z[j])].run();

            // Resets the bit index if out of range.
            i *= ~(i >> 8) & 1;

            // Next instruction. No special treatment for branching needed because the branching instructions already considers this.
            j++;
        }
    }
}


答:
Python <s>3</s> 2, <s>200</s> <s>187</s> <s>149</s> <s>146</s> 136 bytes

-9bytes thanks to Cyoce

```<code>def f(n,a=[0]*256,x=0,z=0):
 while 1:y=a[z];exec'a[z]^=~1 z+=1 z-=1 print-y/2 if~y:x+=1 if~~y:x-=3'.split()["wlipdy".find(n[x][3])];x+=1
</code>```

Input as list, exits by error. Bonus feature: you can specify start array, start IP, and start DP in that very exact order.

Title: Write an interpreter for my new programming language

Body:
I have a new programming language called Brussels-Sprout. Brussels-Sprout functions in an array of 256 boolean values, all initialized to zero, has one instruction pointer, and one "bit index".

After each (non-branching) instruction is executed, the instruction pointer is incremented by one. If the instruction pointer goes off the right side of the instruction array, the program terminates. Going off the left side is undefined behavior.

If the bit index is outside the bounds of the array, it should be reset to 0.

Brussels-Sprout uses the following keywords, which are always lowercase:

chew - Invert the value in the array at the bit index. (flip the bit at the bit index)

swallow - Increment the bit index.

vomit - Decrement the bit index.

complain - Output the bit at the bit index to stdout, or equivalent output log.

feedtodog - If the bit at the bit index is 0, skip the next instruction. Otherwise, increment instruction pointer by 1.

playwithfood - If the bit at the bit index is 1, jump backwards 2 instructions. Otherwise, increment instruction pointer by 1.

If an instruction not on this list is executed, undefined behavior occurs.

I'm sure that this sounds like a very certain other turing-tarpit programming language. But since this programming language operates in boolean values and not bytes, I think it is different.

Test cases:

```<code>chew complain -> 1
swallow chew swallow chew swallow vomit complain playwithfood -> 11
chew complain swallow chew complain swallow chew complain swallow complain -> 1110
chew feedtodog undefinedbehaviour complain -> 1
</code>```

Your challenge is to write an interpreter for Brussels-Sprout. This is code golf, so shortest program wins!

Body:
Python <s>3</s> 2, <s>200</s> <s>187</s> <s>149</s> <s>146</s> 136 bytes

-9bytes thanks to Cyoce

def f(n,a=[0]*256,x=0,z=0):
 while 1:y=a[z];exec'a[z]^=~1 z+=1 z-=1 print-y/2 if~y:x+=1 if~~y:x-=3'.split()["wlipdy".find(n[x][3])];x+=1

Input as list, exits by error. Bonus feature: you can specify start array, start IP, and start DP in that very exact order.


问:
Open the browser to http://codegolf.stackexchange.com
Your job is to open a browser window of the default browser to http://codegolf.stackexchange.com.

Your code must open the browser itself, and cannot rely on an open one.

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

Moderator note: A large number of answers to this challenge use the URLs http://ppcg.lol or http://ppcg.ga. These URLs did direct to https://codegolf.stackexchange.com at the time, but have since expired. By this meta discussion, they have been allowed to stay, with the note that they are currently invalid.

答:
Windows Batch, 17 bytes

```<code>start www.gfa1.tk
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Windows Batch, 17 bytes

start www.gfa1.tk


问:
Tweetable hash function challenge
In this code-challenge you will write a hash function in 140 bytes1 or less of source code. The hash function must take an ASCII string as input, and return a 24-bit unsigned integer ([0, 224-1]) as output.

Your hash function will be evaluated for every word in this large British English dictionary2. Your score is the amount of words that share a hash value with another word (a collision).

The lowest score wins, ties broken by first poster.

Test case

Before submitting, please test your scoring script on the following input:

```<code>duplicate
duplicate
duplicate
duplicate
</code>```

If it gives any score other than 4, it is buggy.

Clarifying rules:

Your hash function must run on a single string, not a whole array. Also, your hash function may not do any other I/O than the input string and output integer.

Built-in hash functions or similar functionality (e.g. encryption to scramble bytes) is disallowed.

Your hash function must be deterministic.

Contrary to most other contests optimizing specifically for the scoring input is allowed.

1 I am aware Twitter limits characters instead of bytes, but for simplicity we will use bytes as a limit for this challenge.

2 Modified from Debian's wbritish-huge, removing any non-ASCII words.

答:
Python 2, 140 bytes, 4266 colliding words

I didn’t really want to start with the non-printable bytes thing given their unclear tweetability, but well, I didn’t start it.  :-P

```<code>00000000: efbb bf64 6566 2066 2873 293a 6e3d 696e  ...def f(s):n=in
00000010: 7428 732e 656e 636f 6465 2827 6865 7827  t(s.encode('hex'
00000020: 292c 3336 293b 7265 7475 726e 206e 2528  ),36);return n%(
00000030: 382a 2a38 2b31 2d32 3130 2a6f 7264 2827  8**8+1-210*ord('
00000040: 6f8e 474c 9f5a b49a 01ad c47f cf84 7b53  o.GL.Z........{S
00000050: 49ea c71b 29cb 929a a53b fc62 3afb e38e  I...)....;.b:...
00000060: e533 7360 982a 50a0 2a82 1f7d 768c 7877  .3s`.*P.*..}v.xw
00000070: d78a cb4f c5ef 9bdb 57b4 7745 3a07 8cb0  ...O....W.wE:...
00000080: 868f a927 5b6e 2536 375d 2929            ...'[n%67]))
</code>```

Python 2, 140 printable bytes, <s>4662</s> <s>4471</s> 4362 colliding words

def f(s):n=int(s.encode('hex'),16);return n%(8**8+3-60*ord('4BZp%(jTvy"WTf.[Lbjk6,-[LVbSvF[Vtw2e,NsR?:VxC0h5%m}F5,%d7Kt5@SxSYX-=$N>'[n%71]))
```

Inspired by the form of kasperd’s solution, obviously—but with the important addition of an affine transformation on the modulus space, and entirely different parameters.

Title: Tweetable hash function challenge

Body:
Python 2, 140 bytes, 4266 colliding words

I didn’t really want to start with the non-printable bytes thing given their unclear tweetability, but well, I didn’t start it.  :-P

00000000: efbb bf64 6566 2066 2873 293a 6e3d 696e  ...def f(s):n=in
00000010: 7428 732e 656e 636f 6465 2827 6865 7827  t(s.encode('hex'
00000020: 292c 3336 293b 7265 7475 726e 206e 2528  ),36);return n%(
00000030: 382a 2a38 2b31 2d32 3130 2a6f 7264 2827  8**8+1-210*ord('
00000040: 6f8e 474c 9f5a b49a 01ad c47f cf84 7b53  o.GL.Z........{S
00000050: 49ea c71b 29cb 929a a53b fc62 3afb e38e  I...)....;.b:...
00000060: e533 7360 982a 50a0 2a82 1f7d 768c 7877  .3s`.*P.*..}v.xw
00000070: d78a cb4f c5ef 9bdb 57b4 7745 3a07 8cb0  ...O....W.wE:...
00000080: 868f a927 5b6e 2536 375d 2929            ...'[n%67]))

Python 2, 140 printable bytes, <s>4662</s> <s>4471</s> 4362 colliding words

def f(s):n=int(s.encode('hex'),16);return n%(8**8+3-60*ord('4BZp%(jTvy"WTf.[Lbjk6,-[LVbSvF[Vtw2e,NsR?:VxC0h5%m}F5,%d7Kt5@SxSYX-=$N>'[n%71]))

Inspired by the form of kasperd’s solution, obviously—but with the important addition of an affine transformation on the modulus space, and entirely different parameters.


问:
Ordering words to fit in a given string
Given a string of letters and a set of words, output an ordering of the words so
that they can be found in the string by dropping letters that are not needed.
Words may occur more than once in the word set. The input string and all words
will consist of 1 to 1000 lower case letters each. The letters to be dropped may occur inside words or between words.

Your program or function can accept the letter string and words as lists, a string, or from STDIN, and must output all words in a correct order as a list
or string output. If there is more than one correct solution, only output one of
them. If there is no possible correct solution, output an empty list or an empty
string.

Examples:

```<code>dogcatfrog cat frog dog
-> dog cat frog

xxcatfixsxhingonxgrapexxxfishingcxat cat grape catfish fishing
-> catfish grape fishing cat

dababbabadbaccbcbaaacdacdbdd aa bb cc dd ba ba ba ab ac da db dc
-> da ab ba ba ba cc bb aa ac dc db dd

flea antelope
->
(no solution)
</code>```

This is code golf. Lowest number of bytes wins.

Edit: Explained that extra characters can be inside words.

答:
Pyth, <s>20</s> 24 bytes

My first attempt on Pyth :)

```<code>Jcw;FG.ptJI:hJj".*"G0jdG
</code>```

How it works:

```<code>Jcw;FG.ptJI:hJj".*"G0jdG
Jcw                         assign("J",chop(input()))
    FG.ptJ                  for G in permutations(tail(J)):
          I:hJj".*"G0        if match(head(J),join(".*",G)):
                     jdG      print(join(" ",G))
</code>```

Notes: it takes a long time in the third example (dababbabadbaccbcbaaacdacdbdd aa bb cc dd ba ba ba ab ac da db dc).

Title: Ordering words to fit in a given string

Body:
Pyth, <s>20</s> 24 bytes

My first attempt on Pyth :)

Jcw;FG.ptJI:hJj".*"G0jdG

How it works:

Jcw;FG.ptJI:hJj".*"G0jdG
Jcw                         assign("J",chop(input()))
    FG.ptJ                  for G in permutations(tail(J)):
          I:hJj".*"G0        if match(head(J),join(".*",G)):
                     jdG      print(join(" ",G))

Notes: it takes a long time in the third example (dababbabadbaccbcbaaacdacdbdd aa bb cc dd ba ba ba ab ac da db dc).


答:
Pyth, 10 bytes

```<code>h@s./Myz.p
</code>```

Demonstration

This program is very much brute force. It first constructs every subset of the input, then every partition of the subsets, then checks for the first one which is a reordering of the word list. No possibilities is handled via erroring with no output to stdout, which is allowed by meta consensus. The error can be removed for 2 extra bytes.

Note that for many of the given test cases, the program will not complete in a reasonable period of time.

Title: Ordering words to fit in a given string

Body:
Given a string of letters and a set of words, output an ordering of the words so
that they can be found in the string by dropping letters that are not needed.
Words may occur more than once in the word set. The input string and all words
will consist of 1 to 1000 lower case letters each. The letters to be dropped may occur inside words or between words.

Your program or function can accept the letter string and words as lists, a string, or from STDIN, and must output all words in a correct order as a list
or string output. If there is more than one correct solution, only output one of
them. If there is no possible correct solution, output an empty list or an empty
string.

Examples:

```<code>dogcatfrog cat frog dog
-> dog cat frog

xxcatfixsxhingonxgrapexxxfishingcxat cat grape catfish fishing
-> catfish grape fishing cat

dababbabadbaccbcbaaacdacdbdd aa bb cc dd ba ba ba ab ac da db dc
-> da ab ba ba ba cc bb aa ac dc db dd

flea antelope
->
(no solution)
</code>```

This is code golf. Lowest number of bytes wins.

Edit: Explained that extra characters can be inside words.

Body:
Pyth, 10 bytes

h@s./Myz.p

Demonstration

This program is very much brute force. It first constructs every subset of the input, then every partition of the subsets, then checks for the first one which is a reordering of the word list. No possibilities is handled via erroring with no output to stdout, which is allowed by meta consensus. The error can be removed for 2 extra bytes.

Note that for many of the given test cases, the program will not complete in a reasonable period of time.


问:
N-queen-and-equine quine
There is a variant of the well-known N-queens problem which involves queens and knights and is said to be "considerably more difficult" 1. The problem statement is as follows:

You must place an equal number of knights ♞ and queens ♛ on a chessboard
  such that no piece attacks any other piece. What is the maximum number
  of pieces you can so place on the board, and how many different ways
  can you do it?

In this code-golf challenge, you will be given an input n between 3 and 32 (in a way that is the most suitable for your language). For a given n, there might be zero or more solutions to the above problem. In case there is no solution, you must output/return nothing (nil, empty string, false, ...). Otherwise, you must give two results:

A solution board (see below) for size n where it is not possible to add a queen or a knight chess piece without having any piece being under attack. There must be an equal number of queens and knights.

The source of a program to be run which accepts no input and gives (i) another solution (or nothing) for the same size n, in the same format, as well as (ii) another program for the next solution (and so on...).

Note that:

The sequence of programs must never return the same board twice, must cover all possible solutions for the problem of size n and eventually has to terminate (producing no output).

You can either return two values, return one and print the other, or print the two return values.

However, if you print both the board and the next program, the board must not be considered to be a part of the next program (I'd recommend printing the board in comment, or use both standard output and error streams).

The program-as-a-return-value must be a string, not a closure.

Board format

A board is a square of size n.

A board cell can be empty, a queen or a knight.

You must choose distinct values for each kind of cells (i.e. you can use other symbols than Q, N when printing the board).

If you return a non-string board, it must be an ordered collection of the n2 values of the board (e.g. matrix, vector or list in row/column-major order, ...).

If you print the board, you can either print it squared, or as a line.
For example, a solution board of size 4 can be printed as follows (spaces not required; symbols at your discretion):

```<code>Q - - -
- - - -
- - - -
- - N -
</code>```

If you feel so, you can also output:

```<code>♛ · · ·
· · · ·
· · · ·
· · ♞ ·
</code>```

... but this is sufficient:

```<code>Q-------------N-
</code>```

It does not matter if you iterate through cells in a row-major or column-major order, because there are symmetrical solutions.
For example, the solutions for n=4 are:

```<code>Q------N--------
Q----------N----
Q------------N--
Q-------------N-
-Q----------N---
-Q------------N-
-Q-------------N
--Q---------N---
--Q----------N--
--Q------------N
---QN-----------
---Q----N-------
---Q---------N--
---Q----------N-
---NQ-----------
----Q------N----
----Q----------N
N------Q--------
-------QN-------
-------Q----N---
---N----Q-------
-------NQ-------
--------Q------N
N----------Q----
----N------Q----
-----------QN---
-N----------Q---
--N---------Q---
-------N----Q---
-----------NQ---
N------------Q--
--N----------Q--
---N---------Q--
N-------------Q-
-N------------Q-
---N----------Q-
-N-------------Q
--N------------Q
----N----------Q
--------N------Q
</code>```

You can also look at the solutions for n=5 as matrices; the boards contains #, q and n symbols, which are empty cells of different kinds (see my answer below).
I count 2836 boards for n=6, like in Sleafar's answer (I introduced a bug when reducing byte count, but it is fixed now).

Many thanks to Sleafar for finding not one but two bugs in my code.

Score

Shortest code in bytes win.

We measure the size of the first program, the one which accepts n.

1. Queens and Knights, by Roger K.W. Hui (beware! contains a solution)

答:
Common Lisp, 737

self-answer

(lambda(n &aux(d 1))#2=(catch'$(let((s(* n n))(c d))(labels((R(w % @ b ! &aux r h v a)(loop for u from % below s do(setf h(mod u n)v(floor u n)a #4=(aref b u))(when(< 0(logand a w)4)(and(= 6 w)!(throw'! t))(let((b(copy-seq b))(o 5))(loop for(K D)on'(-1 -2 -1 2 1 -2 1 2)for y =(+ K v)for x =(+(or D -1)h)for u =(and(< -1 y n)(< -1 x n)(+(* y n)x))if u do #1=(if(< #4#4)(setf #4#(logand #4#o(if(= w o)3 0)))))(#8=dotimes(y N)(#8#(x N)(let((u(+(* y n)x))(o 6))(if(or(= x h)(= y v)(=(abs(- h x))(abs(- v y))))#1#))))(setf #4#w r(or(cond((= w 5)(R 6 @ U b !))((R 5 @ U b())t)((catch'!(R 5 0 0 b t))t)(t(and(=(decf c)0)(incf d)(or(format t"~%(lambda(&aux(n ~A)(d ~A))~%~S)"n d'#2#)(throw'$ B)))t))r)))))r))(R 5 0 0(fill(make-array s)3)())))))
```

<h2>Example</h2>

<p>Paste the above in the REPL, which returns a function object:</p>

<pre class="lang-lisp prettyprint-override"><code>#<FUNCTION (LAMBDA (N &AUX (D 1))) {1006D1010B}>
</code>```

Call it (the star is bound to the last returned value):

QN> (funcall * 4)
```

<p>This prints the following to the standard output:</p>

<pre class="lang-lisp prettyprint-override"><code>(lambda(&aux(n 4)(d 2))
#1=(CATCH '$
 (LET ((S (* N N)) (C D))
   (LABELS ((R (W % @ B ! &AUX R H V A)
              (LOOP FOR U FROM % BELOW S
                    DO (SETF H (MOD U N)
                             V (FLOOR U N)
                             A #2=(AREF B U)) (WHEN (< 0 (LOGAND A W) 4)
                                                (AND (= 6 W) !
                                                     (THROW '! T))
                                                (LET ((B (COPY-SEQ B))
                                                      (O 5))
                                                  (LOOP FOR (K D) ON '(-1
                                                                       -2
                                                                       -1 2
                                                                       1 -2
                                                                       1 2)
                                                        FOR Y = (+ K V)
                                                        FOR X = (+
                                                                 (OR D -1)
                                                                 H)
                                                        FOR U = (AND
                                                                 (< -1 Y N)
                                                                 (< -1 X N)
                                                                 (+ (* Y N)
                                                                    X))
                                                        IF U
                                                        DO #3=(IF (< #2# 4)
                                                                  (SETF #2#
                                                                          (LOGAND
                                                                           #2#
                                                                           O
                                                                           (IF (=
                                                                                W
                                                                                O)
                                                                               3
                                                                               0)))))
                                                  (DOTIMES (Y N)
                                                    (DOTIMES (X N)
                                                      (LET ((U
                                                             (+ (* Y N) X))
                                                            (O 6))
                                                        (IF (OR (= X H)
                                                                (= Y V)
                                                                (=
                                                                 (ABS
                                                                  (- H X))
                                                                 (ABS
                                                                  (- V
                                                                     Y))))
                                                            #3#))))
                                                  (SETF #2# W
                                                        R
                                                          (OR
                                                           (COND
                                                            ((= W 5)
                                                             (R 6 @ U B !))
                                                            ((R 5 @ U B
                                                                NIL)
                                                             T)
                                                            ((CATCH '!
                                                               (R 5 0 0 B
                                                                  T))
                                                             T)
                                                            (T
                                                             (AND
                                                              (= (DECF C)
                                                                 0)
                                                              (INCF D)
                                                              (OR
                                                               (FORMAT T
                                                                       "~%(lambda(&aux(n ~A)(d ~A))~%~S)"
                                                                       N D
                                                                       '#1#)
                                                               (THROW '$
                                                                 B)))
                                                             T))
                                                           R)))))
              R))
     (R 5 0 0 (FILL (MAKE-ARRAY S) 3) NIL)))))
</code>```

Also, the value returned by this function is:

#(5 0 0 0 0 0 0 6 0 0 0 2 0 2 0 0)
```

<p>... which is an array literal. Number 5 represents queens, 6 is for knights and anything else stands for an empty cell, except there are more informations stored internally. If we copy-paste the returned function to the repl, we obtain a new function.</p>

<pre class="lang-lisp prettyprint-override"><code>#<FUNCTION (LAMBDA (&AUX (N 4) (D 2))) {100819148B}>
</code>```

And we can call it to, without arguments:

QN> (funcall * )
```

<p>This call returns a new solution <code>#(5 0 0 0 0 0 0 2 0 0 0 6 0 0 2 0)</code> and the source of another function (not shown here). In case the original function or the last generated one does not find a solution, nothing is printed and nothing is returned.</p>

<h2>Internal values</h2>

<pre class="lang-lisp prettyprint-override"><code>|----------+--------+---------+--------+-----------------|
|          | Binary | Decimal | Symbol | Meaning         |
|----------+--------+---------+--------+-----------------|
| Empty    |    000 |       0 | -      | safe for none   |
|          |    001 |       1 | q      | safe for queen  |
|          |    010 |       2 | n      | safe for knight |
|          |    011 |       3 | #      | safe for both   |
|----------+--------+---------+--------+-----------------|
| Occupied |    101 |       5 | Q      | a queen         |
|          |    110 |       6 | K      | a knight        |
|----------+--------+---------+--------+-----------------|
</code>```

I used to generate too few solutions. Now, I propagate what cell is safe for a queen and for a knight, independently. For example, here is an output for n=5 with pretty-printing:

Q - - - -
- - - n N
- q - n n
- # n - n
- n # # -
```

<p>When we placed the queen <code>Q</code>, positions that are a knight-move away from this queen are still safe for queens and denoted <code>q</code>. Likewise, knights that are reachable only by queens are safe for other knights.
Values are bitwise <em>and</em>-ed to represent the possible moves and some cells are reachable by no kind of piece. </p>

<p>More precisely, here is the sequence of boards leading to the following solution (from left to right), where free cells are gradually constrained with different values:</p>

<pre class="lang-lisp prettyprint-override"><code># # # # # #     q - - - q #     - - - - - #     - - - - - #     - - - - - n
# # # # # #     - - Q - - -     - - Q - - -     - - Q - - -     - - Q - - -
# # # # # #     q - - - q #     q - - - - -     Q - - - - -     Q - - - - -
# # # # # #     - q - q - #     - q - - - n     - - - - - n     - - - - - n
# # # # # #     # # - # # -     n n - n N -     - - - n N -     - - - - N -
# # # # # #     # # - # # #     # # - n n n     - # - - n n     - n - - n N
</code>```

Non-quine approach

Ungolfed, commented version

(defun queens-and-knights
    (n    ; size of problem
     fn   ; function called for each solution

     ;; AUX parameters are like LET* bindings but shorter.
     &aux
       ;; total number of cells in a board
       (s (* n n)))

  (labels
      ;; Define recursive function R
      ((R (w      ; what piece to place: 5=queen, 6=knight
           %      ; min position for piece of type W
           @      ; min position for the other kind of piece
           b      ; current board
           !      ; T iff we are in "check" mode (see below)
           &aux
           r      ; result of this function: will be "true" iff we can
                  ; place at least one piece of type W on the board b
           h      ; current horizontal position
           v      ; current vertical position
           a      ; current piece at position (h,v)
           )

         (loop
            ;; only consider position U starting from position %,
            ;; because any other position below % was already visited
            ;; at a higher level of recursion (e.g. the second queen
            ;; we place is being placed in a recursive call, and we
            ;; don't visit position before the first queen).
            for u from % below s

            do
              (setf h (mod u n)         ; Intialize H, V and A
                    v (floor u n)       ;
                    a (aref b u))       ;

            ;; Apply an AND mask to current value A in the board
            ;; with the type of chess piece W. In order to consider
            ;; position U as "safe", the result of the bitwise AND
            ;; must be below 4 (empty cell) and non-null.
              (when (< 0 (logand a w) 4)

                ;; WE FOUND A SAFE PLACE TO PUT PIECE W

                (when (and ! (= 6 w))
                  ;; In "check" mode, when we place a knight, we knwo
                  ;; that the check is successful. In other words, it
                  ;; is possible to place an additional queen and
                  ;; knight in some board up the call stack. Instead
                  ;; of updating the board we can directly exit from
                  ;; here (that gave a major speed improvement since
                  ;; we do this a lot). Here we do a non-local exit to
                  ;; the catch named "!".
                  (throw '! t))

                ;; We make a copy of current board b and bind it to the
                ;; same symbol b. This allocates a lot of memory
                ;; compared to the previous approach where I used a
                ;; single board and an "undo" list, but it is shorter
                ;; both in code size and in runtime.
                (let ((b (copy-seq b)))

                  ;; Propagate knights' constraints
                  (loop
                     ;; O is the other kind of piece, i.e. queen here
                     ;; because be propagate knights. This is used as
                     ;; a mask to remove knights pieces as possible
                     ;; choices.
                     with o = 5

                     ;; The list below is arranged so that two
                     ;; consecutive numbers form a knight-move. The ON
                     ;; iteration keyword descend sublist by sublist,
                     ;; i.e. (-1 -2), (-2 -1), (-1 2), ..., (2 NIL). We
                     ;; destructure each list being iterated as (K D),
                     ;; and when D is NIL, we use value -1.
                     for (K D) on '(-1 -2 -1 2 1 -2 1 2)

                     ;; Compute position X, Y and index U in board,
                     ;; while checking that the position is inside the
                     ;; board.
                     for y = (+ K v)
                     for x = (+ (or D -1) h)
                     for u = (and (< -1 y n)
                                  (< -1 x n)
                                  (+(* y n)x))

                     ;; if U is a valid position...
                     if u
                     do
                     ;; The reader variable #1# is affected to the
                     ;; following expression and reused below for
                     ;; queens. That's why the expression is not
                     ;; specific to knights. The trick here is to
                     ;; use the symbols with different lexical
                     ;; bindings.
                       #1=(when (< (aref b u) 4) ; empty?
                            (setf (aref b u)

                                  (logand
                                   ;; Bitwise AND of current value ...
                                   (aref b u)

                                   ;; ... with o: position U is not a
                                   ;; safe place for W (inverse of O)
                                   ;; anymore, because if we put a W
                                   ;; there, it would attack our
                                   ;; current cell (H,V).
                                   o

                                   ;; ... and with zero (unsafe for
                                   ;; all) if our piece W is also a
                                   ;; knight (resp. queen). Indeed, we
                                   ;; cannot put anything at position
                                   ;; U because we are attacking it.
                                   (if (= w o) 3 0)))))

                  ;; Propagate queens' constraints
                  (dotimes (y N)
                    (dotimes (x N)
                      (let ((u(+(* y n)x))(o 6))
                        (if (or (= x h)
                                (= y v)
                                (= (abs(- h x)) (abs(- v y))))

                            ;; Same code as above #1=(if ...)
                            #1#))))

                  (setf
                   ;; Place piece
                   (aref b u) w

                   ;; Set result value
                   r (or (cond
                           ;; Queen? Try to place a Knight and maybe
                           ;; other queens. The result is true only if
                           ;; the recursive call is.
                           ((= w 5) (R 6 @ U b !))

                           ;; Not a queen, so all below concern
                           ;; knights: we always return T because
                           ;; we found a safe position.
                           ;; But we still need to know if
                           ;; board B is an actual solution and
                           ;; call FN if it is.
                           ;; ------------------------------------

                           ;; Can be place a queen too? then current
                           ;; board is not a solution.
                           ((R 5 @ U b()) t)

                           ;; Try to place a queen and a knight
                           ;; without constraining the min positions
                           ;; (% and @); this is the "check" mode that
                           ;; is represented by the last argument to
                           ;; R, set to T here. If it throws true,
                           ;; then board B is a duplicate of a
                           ;; previous one, except that it is missing
                           ;; pieces due to constraints % and @. The
                           ;; "check" mode is a fix to a bug where we
                           ;; reported as solutions boards where there
                           ;; was still room for other pieces.
                           ((catch'!(R 5 0 0 b t)) t)

                           ;; Default case: we could not add one more
                           ;; layer of pieces, and so current board B
                           ;; is a solution. Call function FN.
                           (t (funcall fn b) t))

                         ;; R keeps being true if it already was for
                         ;; another position.
                         r)))))

         ;; Return result R
         r))

    ;; Start search with a queen and an empty board.
    (R 5 0 0 (fill (make-array s) 3)  nil)))
```

<h3>Duplicates and bugs</h3>

<p>My very first solution outputted duplicate solutions. In order to solve it, I introduced two counters for queens and knights. The counter for queens (resp. knights) keep track of the first position in the board where a queen (resp. knight) exists: I add a queen (resp. a knight) only at positions that follow that minimal position.</p>

<p>That methods prevents me from revisiting solutions that were already found in previous iterations, because I iterate with an increasing queen (resp. knight) position.</p>

<p>However, Sleafar noticed that there were solutions for which there could be room for queens and knights, which is against the rules. For a while I though I had to revert to a normal search and store all the known solutions to prevent duplicates, which felt too costly (both in terms of bytes and memory usage).</p>

<p>Instead, here is what I do now: when a potential solution board is found, I try to add exactly <em>one</em> queen and <em>one</em> knight, without taking into account the counters (i.e. for all cells on the board). If this is possible, then current board is a duplicate of a previous one, and I reject the solution.</p>

<h3>Tests</h3>

<pre class="lang-lisp prettyprint-override"><code>|---+---------+------------+--------------|
| N |  boards |    seconds |        bytes |
|---+---------+------------+--------------|
| 3 |       0 |          0 |        32768 |
| 4 |      40 |          0 |       360416 |
| 5 |     172 |          0 |      3440016 |
| 6 |    2836 |   0.085907 |     61251584 |
| 7 |   23876 |   1.265178 |    869666288 |
| 8 |  383586 |  24.991300 |  17235142848 |
| 9 | 6064506 | 524.982987 | 359952648832 |
|---+---------+------------+--------------|
</code>```

Quine-ification

I had different ideas to make successive quines.
The easiest one is probably to generate all solutions first as a list of strings and write sequential quines which pop from that list at each generation. However this did not seem to be shorter than current approach.
Alternatively, I tried to rewrite the recursive code with a custom stack and dump all the state variables each time I find a solution; the goal is that the next step can be processed as a continuation of current step.
 Maybe this would be better suited for a stack based language.
The current one is quite simple and rely on Common Lisp reader variables, which are always fun to use.

Title: N-queen-and-equine quine

Body:
Common Lisp, 737

self-answer

(lambda(n &aux(d 1))#2=(catch'$(let((s(* n n))(c d))(labels((R(w % @ b ! &aux r h v a)(loop for u from % below s do(setf h(mod u n)v(floor u n)a #4=(aref b u))(when(< 0(logand a w)4)(and(= 6 w)!(throw'! t))(let((b(copy-seq b))(o 5))(loop for(K D)on'(-1 -2 -1 2 1 -2 1 2)for y =(+ K v)for x =(+(or D -1)h)for u =(and(< -1 y n)(< -1 x n)(+(* y n)x))if u do #1=(if(< #4#4)(setf #4#(logand #4#o(if(= w o)3 0)))))(#8=dotimes(y N)(#8#(x N)(let((u(+(* y n)x))(o 6))(if(or(= x h)(= y v)(=(abs(- h x))(abs(- v y))))#1#))))(setf #4#w r(or(cond((= w 5)(R 6 @ U b !))((R 5 @ U b())t)((catch'!(R 5 0 0 b t))t)(t(and(=(decf c)0)(incf d)(or(format t"~%(lambda(&aux(n ~A)(d ~A))~%~S)"n d'#2#)(throw'$ B)))t))r)))))r))(R 5 0 0(fill(make-array s)3)())))))

Example

Paste the above in the REPL, which returns a function object:

#<FUNCTION (LAMBDA (N &AUX (D 1))) {1006D1010B}>

Call it (the star is bound to the last returned value):

QN> (funcall * 4)

This prints the following to the standard output:

(lambda(&aux(n 4)(d 2))
#1=(CATCH '$
 (LET ((S (* N N)) (C D))
   (LABELS ((R (W % @ B ! &AUX R H V A)
              (LOOP FOR U FROM % BELOW S
                    DO (SETF H (MOD U N)
                             V (FLOOR U N)
                             A #2=(AREF B U)) (WHEN (< 0 (LOGAND A W) 4)
                                                (AND (= 6 W) !
                                                     (THROW '! T))
                                                (LET ((B (COPY-SEQ B))
                                                      (O 5))
                                                  (LOOP FOR (K D) ON '(-1
                                                                       -2
                                                                       -1 2
                                                                       1 -2
                                                                       1 2)
                                                        FOR Y = (+ K V)
                                                        FOR X = (+
                                                                 (OR D -1)
                                                                 H)
                                                        FOR U = (AND
                                                                 (< -1 Y N)
                                                                 (< -1 X N)
                                                                 (+ (* Y N)
                                                                    X))
                                                        IF U
                                                        DO #3=(IF (< #2# 4)
                                                                  (SETF #2#
                                                                          (LOGAND
                                                                           #2#
                                                                           O
                                                                           (IF (=
                                                                                W
                                                                                O)
                                                                               3
                                                                               0)))))
                                                  (DOTIMES (Y N)
                                                    (DOTIMES (X N)
                                                      (LET ((U
                                                             (+ (* Y N) X))
                                                            (O 6))
                                                        (IF (OR (= X H)
                                                                (= Y V)
                                                                (=
                                                                 (ABS
                                                                  (- H X))
                                                                 (ABS
                                                                  (- V
                                                                     Y))))
                                                            #3#))))
                                                  (SETF #2# W
                                                        R
                                                          (OR
                                                           (COND
                                                            ((= W 5)
                                                             (R 6 @ U B !))
                                                            ((R 5 @ U B
                                                                NIL)
                                                             T)
                                                            ((CATCH '!
                                                               (R 5 0 0 B
                                                                  T))
                                                             T)
                                                            (T
                                                             (AND
                                                              (= (DECF C)
                                                                 0)
                                                              (INCF D)
                                                              (OR
                                                               (FORMAT T
                                                                       "~%(lambda(&aux(n ~A)(d ~A))~%~S)"
                                                                       N D
                                                                       '#1#)
                                                               (THROW '$
                                                                 B)))
                                                             T))
                                                           R)))))
              R))
     (R 5 0 0 (FILL (MAKE-ARRAY S) 3) NIL)))))

Also, the value returned by this function is:

#(5 0 0 0 0 0 0 6 0 0 0 2 0 2 0 0)

... which is an array literal. Number 5 represents queens, 6 is for knights and anything else stands for an empty cell, except there are more informations stored internally. If we copy-paste the returned function to the repl, we obtain a new function.

#<FUNCTION (LAMBDA (&AUX (N 4) (D 2))) {100819148B}>

And we can call it to, without arguments:

QN> (funcall * )

This call returns a new solution #(5 0 0 0 0 0 0 2 0 0 0 6 0 0 2 0) and the source of another function (not shown here). In case the original function or the last generated one does not find a solution, nothing is printed and nothing is returned.

Internal values

|----------+--------+---------+--------+-----------------|
|          | Binary | Decimal | Symbol | Meaning         |
|----------+--------+---------+--------+-----------------|
| Empty    |    000 |       0 | -      | safe for none   |
|          |    001 |       1 | q      | safe for queen  |
|          |    010 |       2 | n      | safe for knight |
|          |    011 |       3 | #      | safe for both   |
|----------+--------+---------+--------+-----------------|
| Occupied |    101 |       5 | Q      | a queen         |
|          |    110 |       6 | K      | a knight        |
|----------+--------+---------+--------+-----------------|

I used to generate too few solutions. Now, I propagate what cell is safe for a queen and for a knight, independently. For example, here is an output for n=5 with pretty-printing:

Q - - - -
- - - n N
- q - n n
- # n - n
- n # # -

When we placed the queen Q, positions that are a knight-move away from this queen are still safe for queens and denoted q. Likewise, knights that are reachable only by queens are safe for other knights.
Values are bitwise and-ed to represent the possible moves and some cells are reachable by no kind of piece.

More precisely, here is the sequence of boards leading to the following solution (from left to right), where free cells are gradually constrained with different values:

# # # # # #     q - - - q #     - - - - - #     - - - - - #     - - - - - n
# # # # # #     - - Q - - -     - - Q - - -     - - Q - - -     - - Q - - -
# # # # # #     q - - - q #     q - - - - -     Q - - - - -     Q - - - - -
# # # # # #     - q - q - #     - q - - - n     - - - - - n     - - - - - n
# # # # # #     # # - # # -     n n - n N -     - - - n N -     - - - - N -
# # # # # #     # # - # # #     # # - n n n     - # - - n n     - n - - n N

Non-quine approach

Ungolfed, commented version

(defun queens-and-knights
    (n    ; size of problem
     fn   ; function called for each solution

     ;; AUX parameters are like LET* bindings but shorter.
     &aux
       ;; total number of cells in a board
       (s (* n n)))

  (labels
      ;; Define recursive function R
      ((R (w      ; what piece to place: 5=queen, 6=knight
           %      ; min position for piece of type W
           @      ; min position for the other kind of piece
           b      ; current board
           !      ; T iff we are in "check" mode (see below)
           &aux
           r      ; result of this function: will be "true" iff we can
                  ; place at least one piece of type W on the board b
           h      ; current horizontal position
           v      ; current vertical position
           a      ; current piece at position (h,v)
           )

         (loop
            ;; only consider position U starting from position %,
            ;; because any other position below % was already visited
            ;; at a higher level of recursion (e.g. the second queen
            ;; we place is being placed in a recursive call, and we
            ;; don't visit position before the first queen).
            for u from % below s

            do
              (setf h (mod u n)         ; Intialize H, V and A
                    v (floor u n)       ;
                    a (aref b u))       ;

            ;; Apply an AND mask to current value A in the board
            ;; with the type of chess piece W. In order to consider
            ;; position U as "safe", the result of the bitwise AND
            ;; must be below 4 (empty cell) and non-null.
              (when (< 0 (logand a w) 4)

                ;; WE FOUND A SAFE PLACE TO PUT PIECE W

                (when (and ! (= 6 w))
                  ;; In "check" mode, when we place a knight, we knwo
                  ;; that the check is successful. In other words, it
                  ;; is possible to place an additional queen and
                  ;; knight in some board up the call stack. Instead
                  ;; of updating the board we can directly exit from
                  ;; here (that gave a major speed improvement since
                  ;; we do this a lot). Here we do a non-local exit to
                  ;; the catch named "!".
                  (throw '! t))

                ;; We make a copy of current board b and bind it to the
                ;; same symbol b. This allocates a lot of memory
                ;; compared to the previous approach where I used a
                ;; single board and an "undo" list, but it is shorter
                ;; both in code size and in runtime.
                (let ((b (copy-seq b)))

                  ;; Propagate knights' constraints
                  (loop
                     ;; O is the other kind of piece, i.e. queen here
                     ;; because be propagate knights. This is used as
                     ;; a mask to remove knights pieces as possible
                     ;; choices.
                     with o = 5

                     ;; The list below is arranged so that two
                     ;; consecutive numbers form a knight-move. The ON
                     ;; iteration keyword descend sublist by sublist,
                     ;; i.e. (-1 -2), (-2 -1), (-1 2), ..., (2 NIL). We
                     ;; destructure each list being iterated as (K D),
                     ;; and when D is NIL, we use value -1.
                     for (K D) on '(-1 -2 -1 2 1 -2 1 2)

                     ;; Compute position X, Y and index U in board,
                     ;; while checking that the position is inside the
                     ;; board.
                     for y = (+ K v)
                     for x = (+ (or D -1) h)
                     for u = (and (< -1 y n)
                                  (< -1 x n)
                                  (+(* y n)x))

                     ;; if U is a valid position...
                     if u
                     do
                     ;; The reader variable #1# is affected to the
                     ;; following expression and reused below for
                     ;; queens. That's why the expression is not
                     ;; specific to knights. The trick here is to
                     ;; use the symbols with different lexical
                     ;; bindings.
                       #1=(when (< (aref b u) 4) ; empty?
                            (setf (aref b u)

                                  (logand
                                   ;; Bitwise AND of current value ...
                                   (aref b u)

                                   ;; ... with o: position U is not a
                                   ;; safe place for W (inverse of O)
                                   ;; anymore, because if we put a W
                                   ;; there, it would attack our
                                   ;; current cell (H,V).
                                   o

                                   ;; ... and with zero (unsafe for
                                   ;; all) if our piece W is also a
                                   ;; knight (resp. queen). Indeed, we
                                   ;; cannot put anything at position
                                   ;; U because we are attacking it.
                                   (if (= w o) 3 0)))))

                  ;; Propagate queens' constraints
                  (dotimes (y N)
                    (dotimes (x N)
                      (let ((u(+(* y n)x))(o 6))
                        (if (or (= x h)
                                (= y v)
                                (= (abs(- h x)) (abs(- v y))))

                            ;; Same code as above #1=(if ...)
                            #1#))))

                  (setf
                   ;; Place piece
                   (aref b u) w

                   ;; Set result value
                   r (or (cond
                           ;; Queen? Try to place a Knight and maybe
                           ;; other queens. The result is true only if
                           ;; the recursive call is.
                           ((= w 5) (R 6 @ U b !))

                           ;; Not a queen, so all below concern
                           ;; knights: we always return T because
                           ;; we found a safe position.
                           ;; But we still need to know if
                           ;; board B is an actual solution and
                           ;; call FN if it is.
                           ;; ------------------------------------

                           ;; Can be place a queen too? then current
                           ;; board is not a solution.
                           ((R 5 @ U b()) t)

                           ;; Try to place a queen and a knight
                           ;; without constraining the min positions
                           ;; (% and @); this is the "check" mode that
                           ;; is represented by the last argument to
                           ;; R, set to T here. If it throws true,
                           ;; then board B is a duplicate of a
                           ;; previous one, except that it is missing
                           ;; pieces due to constraints % and @. The
                           ;; "check" mode is a fix to a bug where we
                           ;; reported as solutions boards where there
                           ;; was still room for other pieces.
                           ((catch'!(R 5 0 0 b t)) t)

                           ;; Default case: we could not add one more
                           ;; layer of pieces, and so current board B
                           ;; is a solution. Call function FN.
                           (t (funcall fn b) t))

                         ;; R keeps being true if it already was for
                         ;; another position.
                         r)))))

         ;; Return result R
         r))

    ;; Start search with a queen and an empty board.
    (R 5 0 0 (fill (make-array s) 3)  nil)))

Duplicates and bugs

My very first solution outputted duplicate solutions. In order to solve it, I introduced two counters for queens and knights. The counter for queens (resp. knights) keep track of the first position in the board where a queen (resp. knight) exists: I add a queen (resp. a knight) only at positions that follow that minimal position.

That methods prevents me from revisiting solutions that were already found in previous iterations, because I iterate with an increasing queen (resp. knight) position.

However, Sleafar noticed that there were solutions for which there could be room for queens and knights, which is against the rules. For a while I though I had to revert to a normal search and store all the known solutions to prevent duplicates, which felt too costly (both in terms of bytes and memory usage).

Instead, here is what I do now: when a potential solution board is found, I try to add exactly one queen and one knight, without taking into account the counters (i.e. for all cells on the board). If this is possible, then current board is a duplicate of a previous one, and I reject the solution.

Tests

|---+---------+------------+--------------|
| N |  boards |    seconds |        bytes |
|---+---------+------------+--------------|
| 3 |       0 |          0 |        32768 |
| 4 |      40 |          0 |       360416 |
| 5 |     172 |          0 |      3440016 |
| 6 |    2836 |   0.085907 |     61251584 |
| 7 |   23876 |   1.265178 |    869666288 |
| 8 |  383586 |  24.991300 |  17235142848 |
| 9 | 6064506 | 524.982987 | 359952648832 |
|---+---------+------------+--------------|

Quine-ification

I had different ideas to make successive quines.
The easiest one is probably to generate all solutions first as a list of strings and write sequential quines which pop from that list at each generation. However this did not seem to be shorter than current approach.
Alternatively, I tried to rewrite the recursive code with a custom stack and dump all the state variables each time I find a solution; the goal is that the next step can be processed as a continuation of current step.
 Maybe this would be better suited for a stack based language.
The current one is quite simple and rely on Common Lisp reader variables, which are always fun to use.


问:
Shortest code for infinite disk I/O
(Just open 50 tabs in Google Chrome :D (just kidding, no you can't))

Shortest code for infinite disk I/O any language, C# example:

using System.IO;

namespace FileApp {
    static class Program {
        public static void Main() {
            do {
                File.WriteAllText("a", "a");
                File.Delete("a");
            } while (true);
        }
    }
}
```

You can't just fill the entire disk though, as then it would halt in the end and would be finite.

And you can't do reading only, infinite writing has to happen. (It has to kill my SSD after enough runtime.)

Get cracking! :)

答:
ZSH, 14 bytes

```<code>for ((;;)) :>:
</code>```

Zsh, unlike Bash and other Bourne-like shells, allows loops without the do ... done fence, provided the condition is suitably delimited.

Alternatively, with while:

```<code>while {} {:>:}
</code>```

Note that : is a builtin. You can't suspend this loop.

The principle is the same as in Digital Trauma's answer - nothing is written to the file, the IO is purely from creating and truncating the file.

Title: Shortest code for infinite disk I/O

Body:
ZSH, 14 bytes

for ((;;)) :>:

Zsh, unlike Bash and other Bourne-like shells, allows loops without the do ... done fence, provided the condition is suitably delimited.

Alternatively, with while:

while {} {:>:}

Note that : is a builtin. You can't suspend this loop.

The principle is the same as in Digital Trauma's answer - nothing is written to the file, the IO is purely from creating and truncating the file.


问:
Write the shortest code to match a tail-repeating string where one character falls off the head in each repetition
In this code-golf, you will attempt to match a string that is tail-repeating with one character falling off the head on each iteration. The code needs to be able to accept a string, and return to the user whether the string meets the above criteria.

Examples:

```<code>"", "x", and "xx" -> False
</code>```

EDIT: There is some speculation about whether this is theoretically correct. I will accept any implementation that returns the same value for the three above values as of now. However I do not have an official position on whether this is true or false. Hopefully someone can formalize this.

The above cases will always be false regardless of the circumstance because the string is too short to have the property of tail repetition with one character falling off the head. For example "xx"'s first "tail" would be "x" and there is nothing after the "xx", so it would be false. The character does not matter here, "x" is an example.

```<code>"abb" -> True
</code>```

"abb" is the simplest string I can think of that should be true, because if you take what we will call the "tail" off of it, you get "bb", then knock one character off the head, and you get "b", which is the next character in the string.

```<code>"abcbcc" -> True
</code>```

"abcbcc" is the next simplest string I can think of that should be true. So far in contemplating this problem, testing the truth from the beginning to the end of the string seems difficult, so I'll explain from the end up.

```<code>"c", "cb", "cba"
</code>```

When you examine the string in reverse it seems easier to determine where the "first tail" ends. It ends at the first "c" in "abc", but this can only be inferred from examining the string in reverse, to the best of my knowledge so far.

Here is an example of a string that does not match:

```<code>"abcbca" -> False
</code>```

If we try to apply the above reverse-proof method to it:

```<code>"a", "cb"
</code>```

we realize at the second step when the first character in the second string is not "a", that this must be false.

Shortest code in characters to implement this logic in any programming language wins.

EDIT: If you find a solution other than the suggested one, it is still a valid entry (and very cool!)

答:
Pyth, <s>33</s> 22 bytes

This is my second attempt on Pyth :)

```<code>qz_jk.__<z/t@+1*8lz2 2
                       print(
q                       is_equal(
 z                       input(),
  _                       reverse(
   jk                      concat(
     ._                     all_prefixes(
       _                     reverse(
        <z                    input()[:
          /t@h*8lz2 2          divide(decrement(root(increment(multiply(8,len(z))),2)),2)
                                ])))))
</code>```

Previous attempt:

```<code>KJ<z/t@+1*8lz2 2;WnkJ=K+K=JtJ;qKz
</code>```

Try it online!

How it works:

```<code>KJ<z/t@+1*8lz2 2;WnkJ=K+K=JtJ;qKz
                                    z=input()
KJ<z/t@+1*8lz2 2                    K=J=z[:(root(1+8*len(z),2)-1)/2]
  <z                                    z[:
       +1*8lz                                    1+8*len(z)
      @      2                              root(          ,2)
     t                                                        -1
                 WnKJ               while not_equal(k,J):
                     =K+K=JtJ        K=plus(K,J=tail(J))
                              qKz   equal(K,z)
</code>```

Body:
Pyth, <s>33</s> 22 bytes

This is my second attempt on Pyth :)

qz_jk.__<z/t@+1*8lz2 2
                       print(
q                       is_equal(
 z                       input(),
  _                       reverse(
   jk                      concat(
     ._                     all_prefixes(
       _                     reverse(
        <z                    input()[:
          /t@h*8lz2 2          divide(decrement(root(increment(multiply(8,len(z))),2)),2)
                                ])))))

Previous attempt:

KJ<z/t@+1*8lz2 2;WnkJ=K+K=JtJ;qKz

Try it online!

How it works:

KJ<z/t@+1*8lz2 2;WnkJ=K+K=JtJ;qKz
                                    z=input()
KJ<z/t@+1*8lz2 2                    K=J=z[:(root(1+8*len(z),2)-1)/2]
  <z                                    z[:
       +1*8lz                                    1+8*len(z)
      @      2                              root(          ,2)
     t                                                        -1
                 WnKJ               while not_equal(k,J):
                     =K+K=JtJ        K=plus(K,J=tail(J))
                              qKz   equal(K,z)


问:
Turn a string into a windmill
The code on this site is rapidly being depleted. We need to invest in renewable strings. So you must write a program that takes a string and converts it into a windmill.

The Challenge

Let's take a simple wind-mill string as an example. Take the string abc. The pivot is the center character, in this case b. Since the string is 3 chars long, every output will be exactly three lines tall and three characters wide. Here is your output on step 1. (Note the whitespace)

```

abc

```

To get the next step, rotate each character around the pivot clockwise. Here is step 2:

```
a
 b
  c
```

Here are steps 3-8:

```
 a
 b
 c
```
```
  a
 b
c
```
```

cba

```
```
c
 b
  a
```
```
 c
 b
 a
```
```
  c
 b
a
```

And on the ninth step, it comes around full circle to the original string:

```

abc

```

Note that the b stayed in the same spot the whole time. This is because b is the pivot character. You must write a program or function that takes a string as input and repeatedly prints out this sequence until the program is closed.

Clarifications

All input strings will have an odd number of characters. (So that every windmill will have a pivot)

To keep the challenge simple, all strings will only contain upper and lowercase alphabet characters.

The output must be len(input_string) characters wide and tall.

It doesn't matter which step of the sequence you start on, just as long as you continue rotating and looping forever.

More Test IO:

Since the post is already pretty long, here is a link to  the output for "windmill":

Sidenote:

Since this is supposed to be a windmill, it would be awesome if you include some boilerplate code to animate it with a small time delay or a user input between each step. However, since some languages don't have time builtins, this is not mandatory. The competing part of your submission can just print the sequence as fast as possible.

答:
05AB1E, <s>88</s> 53 bytes

Code:

```<code>¹VYg;ïU[2FX¶×DYsJ,YvNð×y¶J?}YvðX×yJ,}Yv¹gN>-ð×yJ,}YRV
</code>```

Try it online!. Make sure to hit the kill button right after you run it, because it goes into an infinite loop.

Title: Turn a string into a windmill

Body:
05AB1E, <s>88</s> 53 bytes

Code:

¹VYg;ïU[2FX¶×DYsJ,YvNð×y¶J?}YvðX×yJ,}Yv¹gN>-ð×yJ,}YRV

Try it online!. Make sure to hit the kill button right after you run it, because it goes into an infinite loop.


答:
Ruby, <s>122</s>119 bytes

```<code>->n{c=0
loop{i=[l=n.size,m=l+1,m+1,1][3-c=c+1&7]*(3.5<=>c)
s=(' '*l+$/)*l
l.times{|j|s[m*l/2-1+(j-l/2)*i]=n[j]}
$><<s}}
</code>```

Ungolfed version with sleep, in test program

The rotation isn't very convincing at full console height. But if you reduce the height to the the length of the input string, the rotation is a lot more convincing.

```<code>f=->n{
  c=0                                     #loop counter
  m=1+l=n.size                            #l=string length. m=l+1
  loop{                                   #start infinite loop
    s=(' '*l+$/)*l                        #make a string of l newline-terminated lines of l spaces. Total m characters per line.
    i=[m-1,m,m+1,1][3-c=c+1&7]*(3.5<=>c)  #array contains positive distance between characters in string 1=horizontal, m=vertical, etc.
                                          #c=c+1&7 cycles through 0..7. Array index 3..-4 (negative indices count from end of array, so 3=-1, 0=-4 etc)
                                          #(3.5<=>c) = 1 or -1. We use to flip the sign. This is shorter than simply using 8 element array [m-1,m,m+1,1,1-m,-m,-m+1,-1]
    l.times{|j|s[m*l/2-1+i*(j-l/2)]=n[j]} #for each character in n, write the appropriate space character in s to the character in n
    puts s                                #print s
    sleep 1                               #sleep for 1 second
  }
}

f[gets.chomp]                             #get input, remove newline, call function
</code>```

Title: Turn a string into a windmill

Body:
The code on this site is rapidly being depleted. We need to invest in renewable strings. So you must write a program that takes a string and converts it into a windmill.

The Challenge

Let's take a simple wind-mill string as an example. Take the string abc. The pivot is the center character, in this case b. Since the string is 3 chars long, every output will be exactly three lines tall and three characters wide. Here is your output on step 1. (Note the whitespace)

```

abc

```

To get the next step, rotate each character around the pivot clockwise. Here is step 2:

```
a
 b
  c
```

Here are steps 3-8:

```
 a
 b
 c
```
```
  a
 b
c
```
```

cba

```
```
c
 b
  a
```
```
 c
 b
 a
```
```
  c
 b
a
```

And on the ninth step, it comes around full circle to the original string:

```

abc

```

Note that the b stayed in the same spot the whole time. This is because b is the pivot character. You must write a program or function that takes a string as input and repeatedly prints out this sequence until the program is closed.

Clarifications

All input strings will have an odd number of characters. (So that every windmill will have a pivot)

To keep the challenge simple, all strings will only contain upper and lowercase alphabet characters.

The output must be len(input_string) characters wide and tall.

It doesn't matter which step of the sequence you start on, just as long as you continue rotating and looping forever.

More Test IO:

Since the post is already pretty long, here is a link to  the output for "windmill":

Sidenote:

Since this is supposed to be a windmill, it would be awesome if you include some boilerplate code to animate it with a small time delay or a user input between each step. However, since some languages don't have time builtins, this is not mandatory. The competing part of your submission can just print the sequence as fast as possible.

Body:
Ruby, <s>122</s>119 bytes

->n{c=0
loop{i=[l=n.size,m=l+1,m+1,1][3-c=c+1&7]*(3.5<=>c)
s=(' '*l+$/)*l
l.times{|j|s[m*l/2-1+(j-l/2)*i]=n[j]}
$><<s}}

Ungolfed version with sleep, in test program

The rotation isn't very convincing at full console height. But if you reduce the height to the the length of the input string, the rotation is a lot more convincing.

f=->n{
  c=0                                     #loop counter
  m=1+l=n.size                            #l=string length. m=l+1
  loop{                                   #start infinite loop
    s=(' '*l+$/)*l                        #make a string of l newline-terminated lines of l spaces. Total m characters per line.
    i=[m-1,m,m+1,1][3-c=c+1&7]*(3.5<=>c)  #array contains positive distance between characters in string 1=horizontal, m=vertical, etc.
                                          #c=c+1&7 cycles through 0..7. Array index 3..-4 (negative indices count from end of array, so 3=-1, 0=-4 etc)
                                          #(3.5<=>c) = 1 or -1. We use to flip the sign. This is shorter than simply using 8 element array [m-1,m,m+1,1,1-m,-m,-m+1,-1]
    l.times{|j|s[m*l/2-1+i*(j-l/2)]=n[j]} #for each character in n, write the appropriate space character in s to the character in n
    puts s                                #print s
    sleep 1                               #sleep for 1 second
  }
}

f[gets.chomp]                             #get input, remove newline, call function


答:
MATL, <s>47</s> 44 bytes

```<code>' 'jntX"tGtnXyg(wGtnQ2/Y(XJDXKD`J@_X!DK3X!DT
</code>```

Try it online! (but kill it immediately, infinite loop)

With 1-second pause: 56 bytes

```<code>' 'jntX"tGtnXyg(wGtnQ2/Y(XJD1Y.XKD1Y.`J@_X!D1Y.K3X!D1Y.T
</code>```

Try it online! (again, infinite loop)

Title: Turn a string into a windmill

Body:
MATL, <s>47</s> 44 bytes

' 'jntX"tGtnXyg(wGtnQ2/Y(XJDXKD`J@_X!DK3X!DT

Try it online! (but kill it immediately, infinite loop)

With 1-second pause: 56 bytes

' 'jntX"tGtnXyg(wGtnQ2/Y(XJD1Y.XKD1Y.`J@_X!D1Y.K3X!D1Y.T

Try it online! (again, infinite loop)


问:
Find the shortest way to advance a counter to a certain number
I have a counter. It's a small device that looks like this:

The display goes from 0000 to 9999. It has a little push-button at the top that increases the count by 1, and a little knob at the right whose purpose is to reset the counter back to 0.

Now, the thing about the little knob is that if you turn it backwards, you can make it increase any digit that you want once you turn it forwards again. So if I push the counter button 10 times so that the counter shows 0010, I can then turn the knob backwards until i hear a tiny click, then turn it forwards again and make it go straight to 0090.

But, the knob will always increase all occurrences of the same digit by 1 every time it pushes numbers forward. So if the counter shows 6060, you can only make it increase to 7070, not to 6070 or 7060. Also, the knob will roll 9s over to 0 without carrying, so 0990 will advance to 0000 instead of 1000 or 1100.

I want to know the most efficient way to set the counter to a certain number. Your task is to write a program or function that will determine the shortest sequence of button pushes and knob advancements required to do so.

Your program will take as input a 4-digit number from 0000 to 9999, and return a series of steps in the following format:

```<code>> 0001
C
> 0093
C12345678C12345678CCC
> 1000
C12345678C12345678C12345678C12345678C12345678C12345678C12345678C
> 9999
012345678
</code>```

Where C stands for "push the counter button" and any digit D from 0 to 9 stands for "use the knob to advance all occurrences of D by 1".

Your program must produce a valid sequence of steps for all possible four-digit combinations, and will be scored by the total number of steps required for all 10,000 cases. In the case of a tie (most likely when the optimal algorithm is found), the shorter code will win.

答:
Lua, 327763 steps (optimum, 276 bytes)

Golfed version:

```<code>a={[0]=""}t=tonumber for i=0,52 do A={}for k,v in pairs(a)do A[k]=v L=("%04d"):format(k)for i=1,4 do c=L:sub(i,i)d=L:gsub(c,(t(c)+1)%10)e=a[t(d)]A[d]=(not e or #e>#v)and v..c or e end b=k+1 if k<9999then e=a[b]A[b]=(not e or #e>#v)and v.."C"or e end end a=A endprint(a[(...)])
</code>```

Improved version of the examples in question (only 1000 is improved):

```<code>0001:C
0093:CCCCCCCCCC12345678CCC
1000:0CCCCCCCCCCC2345678C23456789
     (0000>1111>1122>1199>1200>1000)
9999:012345678
</code>```

Ungolfed version:

```<code>a = {[0]=""}
for i=0,52 do
    A = {}
    for k,v in pairs(a) do
        A[k] = v
        L=("%04d"):format(k)
        for i=1,4 do
           c=L:sub(i,i)
           d=L:gsub(c,(tonumber(c)+1)%10)
           e=a[tonumber(d)]
           A[d] = (not e or #e > #v) and v..c or e
        end
        b=k+1
        if k < 9999 then
            e=a[b]
            A[b] = (not e or #e > #v) and v.."C" or e
        end
    end
    a=A
end
print(a[93],a[1000],a[9999])
</code>```

Body:
Lua, 327763 steps (optimum, 276 bytes)

Golfed version:

a={[0]=""}t=tonumber for i=0,52 do A={}for k,v in pairs(a)do A[k]=v L=("%04d"):format(k)for i=1,4 do c=L:sub(i,i)d=L:gsub(c,(t(c)+1)%10)e=a[t(d)]A[d]=(not e or #e>#v)and v..c or e end b=k+1 if k<9999then e=a[b]A[b]=(not e or #e>#v)and v.."C"or e end end a=A endprint(a[(...)])

Improved version of the examples in question (only 1000 is improved):

0001:C
0093:CCCCCCCCCC12345678CCC
1000:0CCCCCCCCCCC2345678C23456789
     (0000>1111>1122>1199>1200>1000)
9999:012345678

Ungolfed version:

a = {[0]=""}
for i=0,52 do
    A = {}
    for k,v in pairs(a) do
        A[k] = v
        L=("%04d"):format(k)
        for i=1,4 do
           c=L:sub(i,i)
           d=L:gsub(c,(tonumber(c)+1)%10)
           e=a[tonumber(d)]
           A[d] = (not e or #e > #v) and v..c or e
        end
        b=k+1
        if k < 9999 then
            e=a[b]
            A[b] = (not e or #e > #v) and v.."C" or e
        end
    end
    a=A
end
print(a[93],a[1000],a[9999])


问:
Code a code page

Introduction

A code page maps integer values to a specific character. We can visualize a code page like this:

```
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
|   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 0 | q | w | e | r | t | z | u | i | o | p | a | s | d | f | g | j |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 1 | k | l | y | x | c | v | b | n | m | Q | W | E | R | T | Z | U |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 2 | I | O | P | A | S | D | F | G | H | J |   |   |   |   |   |   |
+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
```

The rows specify the first digit and the columns the second digit of the hex-number.

The Challenge

Given a string of 16-255 unique characters, output the corresponding code page using the zero-based index of each character in the string as it's value.
The input qwertzuiopasdfgjklyxcvbnmQWERTZUIOPASDFGHJ for example would yield the table above.

The output has to be in the exact same format as the table above. Only a trailing newline is optional.

If the input length is not a multiple of 16, you need to start a new row for the remaining characters and leave the unused cells empty (=filled with 3 spaces).

Each character is placed exactly in the middle of a cell, padded by one space to the left and right.

The values in the first row and column are given by hex-numbers with the digits 0123456789ABCDEF. Those are padded with one space to the left and right as well. You may choose to use lowercase hex-digits but you need to stick to one.

The only characters present in the output are hyphens -, pluses +, pipes |, spaces  , the digits for hexadecimal numbers and the characters from the input.

Any builtins that are related to ASCII-art tables or trivialize the problem in any way are forbidden.

You may assume that the input consists only of characters of a specific encoding. Please specify if that is the case.

If your language can only handle ASCII input, you may assume ASCII-only input and repeated characters.

Rules

Function or full program allowed.

Default rules for input/output.

Standard loopholes apply.

This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Happy Coding!

答:
JavaScript (ES6), 148 bytes

```<code>s=>(s=' 0123456789ABCDEF'+s+' '.repeat(15)).match(/(?!^).{16}/g).map((t,i)=>d+`+
| `+[s[i],...t].join` | `,d=`+---`.repeat(17)).join` |
`+` |
${d}+`
</code>```

The ' 0123456789ABCDEF' exists to populate the first column, but conveniently also covers the first row. The input string is then padded with spaces to allow it to be split into substrings of length 16, with the (?!^) preventing the leading space from being matched. The rest is just joining up the pieces.

Title: Code a code page

Body:
JavaScript (ES6), 148 bytes

s=>(s=' 0123456789ABCDEF'+s+' '.repeat(15)).match(/(?!^).{16}/g).map((t,i)=>d+`+
| `+[s[i],...t].join` | `,d=`+---`.repeat(17)).join` |
`+` |
${d}+`

The ' 0123456789ABCDEF' exists to populate the first column, but conveniently also covers the first row. The input string is then padded with spaces to allow it to be split into substrings of length 16, with the (?!^) preventing the leading space from being matched. The rest is just joining up the pieces.