Rank Correlation Coefficient The usual correlation coefficient (in 2d) measures how well a set of points can be described by a line, and if yes, its sign tells us whether we have a positive or negative correlation. But this assumes that coordinates of the points can actually interpreted quantitatively for instance as measurements.

If you cannot do that but you can still order the coordinates, there is the rank correlation coefficient: It measures how well the points can be described by a monotonic function.

Challenge

Given a list of 2d points, determine their rank correlation coefficient.

Details

You can assume the input to be positive integers (but you don't have to), or any other "sortable" values.
The points can be taken as a list of points, or two lists for the x- and y-coordinates or a matrix or 2d array etc.
The output must be a floating point or rational type, as it should represent a real number between 0 and 1.

Definitions

Rank: Given a list of numbers X=[x(1),...,x(n)] we can assign a positive number rx(i) called rank to each entry x(i). We do so by sorting the list and assigning the index of x(i) in the sorted list rx(i). If two or more x(i) have the same value, then we just use the arithmetic mean of all the corresponding indices as rank. Example:

          List: [21, 10, 10, 25, 3]
Indices sorted: [4, 2, 3, 5, 1]

The number 10 appears twice here. In the sorted list it would occupy the indices 2 and 3. The arithmetic mean of those is 2.5 so the ranks are

         Ranks: [4, 2.5, 2.5, 5, 1]

Rank Correlation Coefficient: Let [(x(1),y(1)),(x(2),y(2)),...,(x(n),y(n))] be the given points where each x(i) and y(i) is a real number (wlog. you can assume it is an integer)
For each i=1,...,n we compute the rank rx(i) and ry(i) of x(i) and y(i) respectively.

Let d(i) = rx(i)-ry(i) be the rank difference and let S be the sum S = d(1)^2 + d(2)^2 + ... + d(n)^2. Then the rank correlation coefficient rho is given by

rho = 1 - 6 * S / (n * (n^2-1))

Example

x   y   rx              ry   d      d^2
21  15  4               5   -1      1
10  6   2&3 -> 2.5      2    0.5    0.25
10  7   2&3 -> 2.5      3   -0.5    0.25
25  11  5               4    1      1
3   5   1               1    0      0

    rho = 1 - 6 * (1+0.25+0.25+1)/(5*(5^2-1)) = 0.875

MATL, 33 bytes
,it7#utb,&S]2XQw)]-Us6*1GntUq*/_Q

Try it online!
Explanation
,           % Do...twice
  it        %   Input a numeric vector. Duplicate
  7#u       %   Replace each element by a unique integer label (1, 2, ...)
  t         %   Duplicate
  b         %   Bubble up: moves original numeric vector to top
  ,         %   Do...twice
    &S      %     Sort and push the indices of the sorting
  ]         %   End
            %   The above do...twice loop gives the sorted indices (as
            %   explained in the challenge text) for the current input
  2XQ       %   Compute average for entries with the same integer label
  w         %   Swap: move vector of integer labels to top
  )         %   Index. This gives the rank vector for the current input
]           % End
-           % Subtract the two results. Gives d
Us          % Square each entry, sum of vector. S
6*          % Times 6. Gives 6*S
1G          % Push first input vector again
n           % Number of entries. Gives n
t           % Duplicate
Uq          % Square, minus 1. Gives n^2-1
*           % Times. Gives n*(n^2-1)
/           % Divide. Gives 6*S/(n*(n^2-1))
_Q          % Negate, plus 1. Gives 1-6*S/(n*(n^2-1))


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:

"", "x", and "xx" -> False

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.

"abb" -> True

"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.

"abcbcc" -> True

"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.

"c", "cb", "cba"

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:

"abcbca" -> False

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

"a", "cb"

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!)

Python

Used the fact that the length of a valid string will always be a Triangle Number.

t=raw_input()
x=int(len(t+t)**.5)
print t==''.join(t[i:x]for i in range(x))

A Ruby solution might be shorter, will post soon.


Break the broken cipher I have designed a simple random generator that cycles two numbers in a chaotic way using a multiply and modulus method. It works great for that.

If I were to use it as a cipher generator it would however be vulnerable to a known plaintext attack, given that an attacker can reverse engineer the seed from a series of random numbers in a computationally efficient manner.

To prove the cipher broken find a legal pair of seed values that generate 7 zeros in a row in the range [0;255], using as little power, CPU-time etc. as possible.

Here is the random generator written in JavaScript:

function seed(state1,state2){
    //Constants
    var mod1=4294967087
    var mul1=65539
    var mod2=4294965887
    var mul2=65537
    function random(limit){
        //Cycle each state variable 1 step
        state1=(state1*mul1)%mod1
        state2=(state2*mul2)%mod2
        //Return a random variable
        return (state1+state2)%limit
    }
    //Return the random function
    return random
}

//Initiate the random generator using 2 integer values,
//they must be in the ranges [1;4294967086] and [1;4294965886]
random=seed(31337,42)
//Write 7 random values in the range [0;255] to screen
for(a=0;a<7;a++){
    document.write(random(256)+"<br>")
}

I have made a tool for testing candidate number pairs, it can be found here.

For the next 3 days, no spoilers allowed, an answer must contain only a set of numbers, and it should of course be a different set from those posted by previous solvers. Thereafter you are encouraged to post code and explain your approach.

Edit, quarantine is over:
Answers should contain both a unique set of numbers and explanation and code to document the solving method.

Most elegant solution wins.

For the record:
Writing a program that can find a solution quickly is elegant.
Making a program that utilize the features of a GPU efficiently to do it even faster is elegant.
Doing the job on a piece of "museumware" is elegant.
Finding a solution method that can feasibly be utilized using only pen and paper is very elegant.
Explaining your solution in an instructive and easily understandable manner is elegant.

Using multiple or very expensive computers is inelegant.

C++, 44014022 / 164607120

It is in C++, uses 1 GB of memory, and took about 45 seconds to find this first pair.  I'll update the time once it finds them all.
Code below.  It first finds all pairs that generate 4 zeros, then whittles those down by simple trial (see the check method).  It finds pairs that generate 4 zeros by generating two large arrays, one which contains the first 4 low-order bytes of the state1 generator, and the second which contains the negative of the first 4 low-order bytes of the state2 generator.  These arrays are then sorted and searched for a match, which corresponds to the overall generator outputting 4 zeros to start.
The arrays are too big to store in memory, so it does the work in batches sized to just fit in memory.
Looks like the complete run will take ~12 hours.
Edit: Improved the code so it only takes ~1 hour to get all possible seeds.  Now it generates the tables into 256 different files, one for each first byte of output.  We can then process each file independently so we don't have to regenerate data.
Edit: Turns out you can generate the 256 subtables individually instead of all at once, so no disk needed.  Running time down to ~15 minutes using 256MB.
#include <stdio.h>
#include <stdint.h>
#include <algorithm>
using namespace std;

#define M1 65539
#define N1 4294967087
#define M2 65537
#define N2 4294965887
#define MATCHES 7

// M^-1 mod N
#define M1_INV 3027952124
#define M2_INV 1949206866

int npairs = 0;

void check(uint32_t seed1, uint32_t seed2) {
  uint32_t s1 = seed1;
  uint32_t s2 = seed2;
  for (int i = 0; i < MATCHES; i++) {
    s1 = (uint64_t)s1 * M1 % N1;
    s2 = (uint64_t)s2 * M2 % N2;
    if (((s1 + s2) & 0xff) != 0) return;
  }
  printf("%d %u %u\n", npairs++, seed1, seed2);
}

struct Record {
  uint32_t signature; // 2nd through 5th generated bytes
  uint32_t seed;      // seed that generated them
};
// for sorting Records
bool operator<(const Record &a, const Record &b) {
  return a.signature < b.signature;
}

int main(int argc, char *argv[]) {
  Record *table1 = (Record*)malloc((N1/256+1)*sizeof(*table1));
  Record *table2 = (Record*)malloc((N2/256+1)*sizeof(*table2));

  for (int i = 0; i < 256; i++) {  // iterate over first byte
    printf("first byte %x\n", i);

    // generate signatures (bytes 2 through 5) for all states of generator 1
    // that generate i as the first byte.
    Record *r = table1;
    for (uint64_t k = i; k < N1; k += 256) {
      uint32_t sig = 0;
      uint32_t v = k;
      for (int j = 0; j < 4; j++) {
        v = (uint64_t)v * M1 % N1;
        sig = (sig << 8) + (v & 0xff);
      }
      r->signature = sig;
      r->seed = k;
      r++;
    }
    Record *endtable1 = r;

    // generate signatures (bytes 2 through 5) for all states of generator 2
    // that generate -i as the first byte.
    r = table2;
    for (uint64_t k = (-i & 0xff); k < N2; k += 256) {
      uint32_t sig = 0;
      uint32_t v = k;
      for (int j = 0; j < 4; j++) {
        v = (uint64_t)v * M2 % N2;
        sig = (sig << 8) + (-v & 0xff);
      }
      r->signature = sig;
      r->seed = k;
      r++;
    }
    Record *endtable2 = r;

    sort(table1, endtable1);
    sort(table2, endtable2);

    // iterate through looking for matches
    const Record *p1 = table1;
    const Record *p2 = table2;
    while (p1 < endtable1  && p2 < endtable2) {
      if (p1->signature < p2->signature) p1++;
      else if (p1->signature > p2->signature) p2++;
      else {
        check((uint64_t)p1->seed * M1_INV % N1, (uint64_t)p2->seed * M2_INV % N2);
        // NOTE: may skip some potential matches, if p1->signature==(p1+1)->signature or p2->signature==(p2+1)->signature
        p1++;
      }
    }
  }
}


A, Buzz, C, D, E, Fizz, G A simple FizzBuzz using strings.
Given

1 word or phrase (string)
2 unique characters

Output
The word or phrase with each occurrence of the first character replaced with fizz and each of the second character replaced with buzz
Rules

The first letter in both Fizz and Buzz must remain capitalized
For the rest of the words fizz and buzz, you must match the case of the replaced character (if no case then keep lowercase)
If given characters are not in the phrase, output the original phrase

Test Cases
Given: Hello, h, l
Output: FIZZeBuzzBuzzo

Given: test, a, b
Output: test

Given: PCG rocks!,  , !
PCGFizzrocksBuzz

Given: This
Is
SPARTA!,
, S
Output: ThiBuzzFizzIBuzzFizzBUZZPARTA!

Given: FizzBuzz, a, b
Output: FizzBUZZuzz

This is code-golf so the shortest code, in bytes, wins!
Note
Technically handling the newline case (This Is SPARTA!) is a part of the challenge. However, I will not void an answer for not including it, as it is very challenging or even impossible in some languages.

Python 3, 180 174 168 160 152 bytes

from sys import*
J=''.join
L=str.lower
s,a,b=J(stdin).split(', ')
print(J('FBFBiuIUzzZZzzZZ'[L(k)==L(b)::2][k!=L(k)::2]*(L(k)in L(a+b))or k for k in s))

This is just a more golfed version of Stephen's answer, in Python 3. This chips away 42% of his bytes. Python 2 would save one byte on the print, but such is the price of progress. This handles newlines properly.

Thanks to Blckknight for saving 8 bytes on input.


Help me get the day of the week correct Sometimes, I will think it is one day of the week (e.g Friday) when in reality, it's earlier in the week (e.g Tuesday).
Your challenge is to display the number of days my estimates are off by.
Challenge
Given a day of the week I think it is, and the day of the week it actually is, output/return the number of days between the two.
Test Cases
Incorrect date, Actual Date -> Days between
Monday, Monday -> 0
Friday, Tuesday ->  3
Saturday, Sunday -> 6
Tuesday, Friday -> 4
Thursday, Wednesday ->  1
Monday, Friday -> 3

Rules

Dates have to be taken as the actual date name (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday). This is non-negotiable.
Date names must be taken as strings or equivalent in your language (ADTs aren't allowed unless they store their values as the allowed strings)
Input and output can be given/taken in any reasonable format.
Full program or function - it doesn't matter.

And finally, this is code-golf, so the answer in each language with the fewest bytes wins.

JavaScript (ES6), 48 bytes
Expects (day1)(day2).
a=>b=>((g=s=>parseInt(s,34)%72%23)(a)-g(b)+21)%7

Try it online!
How?
We need a hash function \$g\$ that turns a day string into an index. The results of this function are actually quite flexible:

They can be in ascending or descending order: 0,1,2,3,4,5,6 or 6,5,4,3,2,1,0. (We'll have to compute either \$g(a)-g(b)\$ or \$g(b)-g(a)\$ accordingly.)
Day #0 may be any day of the week. For instance, 3,4,5,6,0,1,2 or 4,3,2,1,0,6,5 are also valid.
The results may be greater than \$6\$ as long as they are correct modulo \$7\$. Because the sign of the modulo is the sign of the dividend in JS, we'll have to do something like (g(a) - g(b) + k) % 7 anyway, where \$k\$ is a large enough multiple of \$7\$.

The following function was found by brute-force:
g = s => parseInt(s, 34) % 72 % 23

which gives:
 day         | base34 -> dec | mod 72 | mod 23 | mod 7
-------------+---------------+--------+--------+-------
 "Monday"    |      30369728 |   56   |   10   |   3
 "Tuesday"   |    1358300452 |    4   |    4   |   4
 "Wednesday" | 1702996445748 |   12   |   12   |   5
 "Thursday"  |   45612914380 |   52   |    6   |   6
 "Friday"    |      21127508 |   44   |   21   |   0
 "Saturday"  |   43748842416 |   24   |    1   |   1
 "Sunday"    |      38623568 |   32   |    9   |   2


Help me juice my avocados In this challenge, I have a field of avocados which I'd like to juice as quickly and completely as possible. Can you write a program or function to help me work out how to juice all the avocados perfectly?

As input, you'll get the avocados as an mxm square grid, where m is an integer between 3 and 6. Each square contains exactly one avocado. Avocados have several stages of juiciness:

Stage 1: The avocado has not been juiced at all.
 Stage 2: The avocado has been partially juiced.
 Stage 3: The avocado has been completely juiced.
 Stage 4: The avocado has exploded due to over-juicing.

When you use a juicing tool, the avocados in that juicing tool's area of effect move to the next stage. Exploding avocados have a lot of force and will destroy the entire avocado field, so make sure none of the avocados explode!

Here is an example of a grid of avocados. In these examples, I've used the  coordinate 0,0 for the bottom-left corner, and the coordinate 2,2 for the top-right corner, although you can adjust the coordinate system to suit your language.

112
221
231

The goal is to make all the avocados perfectly juiced (i.e. stage 3). To achieve this you have three different juicing tools in your possession. Each juicing tool have a different area of effect, but they all increase the juiciness of affected avocados by 1.

Here are all the tools you have at your disposal. You use the juicers by specifying the first letter of the tool, then the coordinates which you want to juice. For example, to use the Slicer on square 5,2, you would output S 5,2.

Slicer: Juices the target coordinate and the avocado on either side.

112     112     112
221 --> XXX --> 332
231     231     231

Grater: Juices the target coordinate and the avocado above and below.

112     1X2     122
221 --> 2X1 --> 231 --> kaboom!
231     2X1     241

Rocket Launcher: Juices the target coordinate and all adjacent avocados.

112     1X2     122
221 --> XXX --> 332
221     2X1     231

Sample Inputs and Outputs

323
212
323

G 1,1
S 1,1

3312
3121
1213
2133

R 0,0
R 1,1
R 2,2
R 3,3

22322
22222
22222
33233
33333

G 0,3
G 1,3
G 2,2
G 3,3
G 4,3

222332
333221
222332
333222
222333
333222

S 1,5
S 1,3
S 1,1
S 4,5
S 4,3
S 4,1
G 5,4

Mathematica — 350 bytes

Not a very short solution, but better than no solution at all, right?

t[x_]:=Flatten@Table[x/@{G,S,R},{i,n},{j,n}];""<>Cases[StringReplace[(First@Solve[(Table[G[i,j]+G[i-1,j]+G[i+1,j]+S[i,j]+S[i,j-1]+S[i,j+1]+R[i,j]+R[i-1,j]+R[i+1,j]+R[i,j-1]+R[i,j+1],{i,n=Length@#},{j,n}]/.(G|S|R)[___,0|n+1,___]->0)==3-#&&And@@t[#[i,j]>=0&],t[#[i,j]&],Integers])/.{(x_->m_):>ToString[m x]},{"["->" ","]"->"\n",", "->","}],Except@"0"]&

A more readable version (with extra spaces and indents and stuff):

t[x_] := Flatten@Table[x /@ {G, S, R}, {i, n}, {j, n}];
"" <> Cases[
   StringReplace[(First@
       Solve[(Table[
             G[i, j] + G[i - 1, j] + G[i + 1, j] + S[i, j] +
              S[i, j - 1] + S[i, j + 1] + R[i, j] + R[i - 1, j] +
              R[i + 1, j] + R[i, j - 1] + R[i, j + 1], {i,
              n = Length@#}, {j, n}] /. (G | S | R)[___,
              0 | n + 1, ___] -> 0) == 3 - # &&
         And @@ t[#[i, j] >= 0 &], t[#[i, j] &],
        Integers]) /. {(x_ -> m_) :> ToString[m x]}, {"[" -> " ",
     "]" -> "\n", ", " -> ","}], Except@"0"] &

Input is an array (e.g. {{3,2,3},{2,2,2},{3,2,3}}), output is a string (with a trailing newline — if this is unacceptable, enclose the function in StringDrop[...,-1] for an extra 15 bytes). I used the coordinate system that says (1,1) is the top-left corner, (n,n) is the bottom right (where n is the dimension of the matrix). Sometimes, if the solution requires doing the same operation multiple times, the output includes things like 3 G 2,2 (for "use the grater at (2,2) three times") — since you didn't say what to do in this case, I hope that's OK.

Explanation:

Table[G[i,j]+G[i-1,j]+G[i+1,j]+S[i,j]+S[i,j-1]+S[i,j+1]+R[i,j]+R[i-1,j]+R[i+1,j]+R[i,j-1]+R[i,j+1],{i,n=Length@#},{j,n}] creates an array with the variables G[i,j] in each place that's affected by using the grater at (i,j), and similarly for S[i,j] and R[i,j]. These variables represent the number of times the tool is used at that position.
.../.(G|S|R)[___,0|n+1,___]->0 removes the effects of using tools at positions outside the avocado field.
...==3-# compares this to the difference between the input and a field of perfectly juiced avocados.
...&&And@@t[#[i,j]>=0&] says the variables G[i,j], S[i,j], R[i,j] must be non-negative (you can't un-juice the avocados!), using the shorthand t[x_]:=Flatten@Table[x/@{G,S,R},{i,n},{j,n}].
First@Solve[...,t[#[i,j]&],Integers] finds the first integer solution to our equations in terms of the variables G[i,j], S[i,j], R[i,j].
/.{(x_->m_):>ToString[m x]} hides the variables that equal zero, while also putting the solution in a nice string form.
StringReplace[...,{"["->" ","]"->"\n",", "->","}] turns strings like "2 G[1, 4]" into strings like "2 G 1,4", and adds a newline on the end.
""<>Cases[...,Except@"0"] removes all the leftover "0"s and joins all the strings together.


Move to the printable ASCII front Background

The move-to-front transform (MTF) is a data encoding algorithm designed to improve the performance of entropy encoding techniques.

In the bzip2 compression algorithm, it is applied after the Burrows–Wheeler transform (as seen in Burrows, Wheeler and Back), with the objective of turning groups of repeated characters into small, easily compressible non-negative integers.

Definition

For the purpose of this challenge, we'll define the printable ASCII version of the MTF as follows:

Given an input string s, take an empty array r, the string d of all printable ASCII characters (0x20 to 0x7E) and repeat the following for each character c of s:

Append the index of c in d to r.
Move c to the front of d, i.e., remove c from d and prepend it to the remainder.

Finally, we take the elements of r as indexes in the original d and fetch the corresponding characters.

Step-by-step example

INPUT: "CODEGOLF"

0. s = "CODEGOLF"
   d = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = []
1. s = "ODEGOLF"
   d = "C !\"#$%&'()*+,-./0123456789:;<=>?@ABDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35]
2. s = "DEGOLF"
   d = "OC !\"#$%&'()*+,-./0123456789:;<=>?@ABDEFGHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35 47]
3. s = "EGOLF"
   d = "DOC !\"#$%&'()*+,-./0123456789:;<=>?@ABEFGHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35 47 37]
4. s = "GOLF"
   d = "EDOC !\"#$%&'()*+,-./0123456789:;<=>?@ABFGHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35 47 37 38]
5. s = "OLF"
   d = "GEDOC !\"#$%&'()*+,-./0123456789:;<=>?@ABFHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35 47 37 38 40]
6. s = "LF"
   d = "OGEDC !\"#$%&'()*+,-./0123456789:;<=>?@ABFHIJKLMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35 47 37 38 40 3]
7. s = "F"
   d = "LOGEDC !\"#$%&'()*+,-./0123456789:;<=>?@ABFHIJKMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35 47 37 38 40 3 45]
8. s = ""
   d = "FLOGEDC !\"#$%&'()*+,-./0123456789:;<=>?@ABHIJKMNPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
   r = [35 47 37 38 40 3 45 41]

OUTPUT: "COEFH#MI"

Task

Write a program or function that implements the printable ASCII MTF (as defined above).

Test cases

Input:  Programming Puzzles & Code Golf
Output: Prpi"do lp%((uz rnu&3!P/o&$U$(p

Input:  NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN BATMAN!
Output: Na! !! !! !! !! !! !! !! !! !! !! !! !! !! !! !!"DDUP"%'

Input:  Two more questions and I have bzip2 in less than 100 bytes!
Output: Twp#o"si$sv#uvq(u$(l#o#W!r%w+$pz,xF%#,"x(. #0--'$GG ".z(**:

Additional rules

You cannot use any built-in operator that computes the MTF of a string.
Your code may print a trailing newline if you choose STDOUT for output.
Your code has to work for any input of 1000 or less printable ASCII characters (0x20 to 0x7E).
Standard code golf rules apply. The shortest submission in bytes wins.

Ostrich, 46 45 chars

Don't have a version number in the header because this is actually just the latest commit. I added the O (ascii code to string) operator after releasing the latest version (but still before this challenge was posted).

{a95,{32+O}%:d3@{:x\.3@?3@\+\x-x\+}/;{d=}%s*}

Explanation:

a             this is the "r" array (a is short for [], empty array)
95,{32+O}%:d  this is the "d" array
3@{...}/      for each character in the input (as an "argument")...
  :x            store in variable x (stack is now [r d c])
  \.3@?         find index in d     (stack is now [r d idx])
  3@\+          append index to r   (stack is now [d modified_r])
  \x-           remove char from d, and then...
  x\+           prepend char to d   (stack is now [modified_r modified_d])
;             throw away modified_d
{d=}%         map r to indices of (original) d
s*            join (s is short for ``, empty string)


Tournament Format Synonyms I spent all of today at a Super Smash Bros. tournament, and I started thinking about some of the terminology we use when describing sets. These are the three kinds of sets that I see played at tournaments:

Best of 3 (Bo3)

Three games are played. The winner of the set is the player who won the majority of the games.
If a single player wins two games of the set, they are immediately declared the winner, because it would be impossible for the opponent to catch up.

Best of 5 (Bo5)

Five games are played. The winner of the set is the player who won the majority of the games.
If a single player wins three games of the set, they are immediately declared the winner, because it would be impossible for the opponent to catch up.

First to 5 (Ft5)

Okay, I cheated a bit with my wording earlier. This kind of set isn't part of a tournament, but you'll often see them happening in the venue. This is traditionally the kind of set you'll play if you've challenged another player and money is on the line.
It's as simple as it sounds: The players repeatedly play games until one of them has won five, and that player is declared the winner.

Obviously, Bo3 and Bo5 are very similar, differing only in the number of games played. But Ft5 is clearly different... right? Not really! No matter how a Bo3 set goes down, the winner will have won exactly two games. The winner of a Bo5 set will have won exactly 3 games. Why not call them Ft2, or Ft3? The same logic, applied in reverse, will show that Ft5 is exactly the same as Bo9.

The objective of this challenge is to determine the synonym of a set format.

Specification

Your program or function will take a single string from input. The first two characters will be Bo or Ft, and they will be followed by a number. The program/function will output a string with the opposite prefix and a number such that the input and output strings mean the same thing.

Any string beginning with Bo will end in an odd number.

You may assume that the number in the input string will never be greater than 200. You may also assume that you will never receive input for which the correct output would include a number greater than 200. Likewise, the input and correct output numbers will always be greater than 0.

Examples

Bo3 -> Ft2
Ft2 -> Bo3

Bo5 -> Ft3
Ft3 -> Bo5

Bo9 -> Ft5
Ft5 -> Bo9

Bo51 -> Ft26
Ft26 -> Bo51

Bo199 -> Ft100
Ft100 -> Bo199

Python 2, 59

lambda s:'FBto'[s>'C'::2]+`eval(s[2:]+'/*22+-11'[s>'C'::2])`

In short challenges where functions are allowed, the brevity of lambda usually wins out even when the code must repeat itself due to the inability to assign variables.

We check which case we're in with string comparison s>'C'. Then, get the right prefix with the list slicing trick 'FBto'[s>'C'::2].

To get the number, we must evaluate the characters beyond the second and do either *2+1 or /2-1 to it. We do this by tacking on either of those two expressions as strings, again chosen by list slicing, evaluating the result, and turning that number into a string.

Edit: Saved one char (59):

lambda s:eval("''FBto''++``%%ss/*22+-11``"[s>'C'::2]%s[2:])

Don't even ask...


More fun with case-(very)-sensitive strings Inspired by this challenge (or, more specifically, by misreading it), I've come up with the following challenge:
Given an input string S, reverse the order of all uppercase characters, and all lowercase characters. Leave all non-letter characters in place. For instance:

Note that the uppercase W (the first uppercase letter) was replaced with H (the last). Same goes for the lowercase letters: 'd' (the first) is swapped with e (the last), l (second) gets replaced with l (pen-ultimate) ... All the non-letter characters are left in place.
Input

Input is a string with only ASCII characters in the range 32-126.
Input is guaranteed to be at least 1 character long, and won't exceed your language's limit.

Output

That same string, with the characters swapped as described.

Additional rules

Standard loopholes are forbidden
Answer must be a full program or a function, not a snippet or a REPL-entry.
code-golf, shortest answer in bytes wins.

Test cases
A
A

Ok
Ok

OK
KO

Hello, World!
Wdlro, Holle!

0123456789
0123456789

The quick brown Fox jumps over the lazy doge
Feg odyza lehtr Tev ospmu jxon wor bkci uqeh

odd
ddo

racecar
racecar

EtOn Em OsN R AaToNsIsIhT!!1!
ThIs Is NoT A RaNsOmEnOtE!!1!

Retina, 19 bytes

Retina doesn't have a direct way to reverse a string, but we can do it by exploiting the sorting stage:

O^#`[a-z]
O^#`[A-Z]

Sort (O), reading them as numbers (#), and then reverse the ordering (^), of all the strings matching the given regex (lowercase letters for the first line, and uppercase letters for the second).

This works because when we try to read strings without numeric characters as numbers they get treated as 0, so all the characters have the same value for sorting. Since sorting is stable they are left in the same order, and reversing them returns the original string reversed.

Try it online!


Exit code string output You must write a program or function that, when given a nonempty string S of N printable ASCII characters†, outputs a program that will exit with exit code C, where C is the ASCII codepoint at position 0 in S. This program you write will additionally output a program P, such that, when run, it exits with exit code C′, where C′ is the ASCII codepoint at position 1 in S. Program P will output another program P′. This process repeats until there are no characters left in S. After this is done, you must output nothing, followed by an optional newline; and should exit with exit code 0.

†The characters between 0x20 and 0x7e inclusive.

Some more rules:

Self-modifying programs are not allowed: you must output the source to STDOUT (or, return value initially)
You may not read your own source code.

The shortest such program in bytes will win.

For some rudimentary testing, this ruby script can be used. (The first argument is the way you invoke the script, the second is the program, and the third is the input string.)

Hypothetical Example

Say the program is FOO. When given the string "ABC", it outputs BARA. This program exits with code 65 and outputs BARB. This in turn exits with code 66 and ouputs BARC. This program exits with code 67 and outputs BAR!. This outputs nothing, and exits with code 0.

Python 2, 126 101 94 bytes
In the process of making this, I found that Python code may not contain literal NUL bytes.

lambda i,s='''i=%r;s=%r
try:print s%%(i[1:],s,i[0])
except:0
exit(ord(%r))''':s%(i[1:],s,i[0])

Try it online (shows the exit code in the Debug info)

Note that each of the non-empty programs below has a trailing linefeed.
For input Hello, the above outputs:
i='ello';s='i=%r;s=%r\ntry:print s%%(i[1:],s,i[0])\nexcept:print s%%(0,s,"\\0")*(i>0)\nexit(ord(%r))'
try:print s%(i[1:],s,i[0])
except:0
exit(ord('H'))

which prints
...
which prints
i='o';s='i=%r;s=%r\ntry:print s%%(i[1:],s,i[0])\nexcept:print s%%(0,s,"\\0")*(i>0)\nexit(ord(%r))'
try:print s%(i[1:],s,i[0])
except:0
exit(ord('l'))

which prints
i='';s='i=%r;s=%r\ntry:print s%%(i[1:],s,i[0])\nexcept:print s%%(0,s,"\\0")*(i>0)\nexit(ord(%r))'
try:print s%(i[1:],s,i[0])
except:0
exit(ord('o'))

which prints nothing (the empty program)

which prints nothing and exits with code 0.


The Essential™ (comment-free) Convenient Palindromic Quine Golf A program is "conveniently palindromic" if

it is equal to the string derived when its reverse has all its parentheses (()), brackets ([]), and braces ({}) flipped. No other characters are special and require flipping. (<> are sometimes paired but often not so they are left out.)
copied from this challenge.

Write a conveniently palindromic program that prints its own source.
You must be able to prove that it is impossible to remove one or more byte from the program so that the resulting program, when executed in the same language:

prints the original source, or
prints the new modified source

Note that the resulting program won't necessarily be a convenient palindrome. It also means that you cannot use comments or equivalent structures.
Rules

Program must be longer than one character
Reading you own source code (from the file or any other resource) is forbidden.
Your program must be a proper quine.

Jelly, 17 bytes

ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð

Try it online!

Verfication

A string of length 17 has only 217 = 131,072 subsequences, so this can be done by brute force.

$ # Generate all 131,072 subsequences of the source code.
$ jelly eun '“ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð”ṾḊṖŒPY' > subsequences
$ wc -l subsequences
131072 subsequences
$ cat verify.py
import jelly

# Discard extraneous output to STDOUT (just a bunch of 0's and [0]'s).

jelly.print = lambda _, end: None

for line in open('subsequences').readlines():
        line = line.strip()
        try:
                output = jelly.stringify(jelly.jelly_eval(line, []))
        except:
                output = ''
        if output == line or output == 'ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð':
                print(repr(line))

$ time python3 verify.py
'ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð'

real    0m9.678s
user    0m9.653s
sys     0m0.028s

How it works

ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð  Main link. No arguments. Implicit left argument: 0

       ø           Make the chain to the right niladic.
        “øḄŒṚṖṾṛð  Yield the string 'øḄŒṚṖṾṛð'.
ð                  Make the chain to the right and up to ø dyadic.
                   The main link is now a monadic 2,0-chain, so the dyadic chain
                   is called with the implicit left argument 0 and right argument
                   'øḄŒṚṖṾṛð'.
 ṛ                 Yield the right argument, i.e., 'øḄŒṚṖṾṛð'.
  Ṿ                Uneval; yield the string representation of the right argument,
                   i.e., '“øḄŒṚṖṾṛð”'.
   Ṗ               Pop; remove the last character, yielding '“øḄŒṚṖṾṛð'.
    Ṛ              Reverse, yielding 'ðṛṾṖṚŒḄø“'.
     ŒḄ            Bounce, yielding 'ðṛṾṖṚŒḄø“øḄŒṚṖṾṛð'.
                   (implicit) Print the last return value.


Python 2, 56 bytes

for n in range(9999):
 if eval('<'.join(`n`))**n:print n

Try it online!

Converts each number like 124 to an expression 1<2<4 and evaluates it to check if the digits are sorted,

A hiccup happens for one-digit numbers giving an expression that just is the number itself. This causes 0 to evaluate to a Falsey value even though it should be printed. This is fixed by a trick suggested by Erik the Outgolfer of doing **n, which gives truthy value 0**0 for n=0 and doesn't affect the truth value otherwise.


A small language deserves a small interpreter Here is a very simple language definition:

A Variable is any string that does not contain ^, <, >, !, or ?
The empty string is a valid variable identifier
The value of every variable starts at 0.
A Statement is one of (var is a Variable, P is a Program):
    var^   -> changes var to be equal to 1 more than itself
    var<P> -> while var > 0, changes var to be equal to 1 less than itself, then runs P
    var! -> output value of var
    var? -> ask for non-negative integer as input, increase var by that value
A Program is a concatenation of Statements, running a Program means running each Statement in order

Example programs (note that the empty string is a variable, but I will use it sparingly for the sake of clarity, and some variables are zeroed out in the program when they are usually 0 by default):

<>: sets the value of the empty string variable to 0
b<>b?b<a^>: asks for b, then adds the value stored in b to a, zeroing b in the process
b<>b?a<>b<a^>: asks for b, then sets a to the value of b, zeroing b in the process
a<>c<>b<a^c^>c<b^> : copies the value in b into a without zeroing it
b<>c<>a<c^c^c<b^>>b! : outputs a multiplied by 2
b^b<a<>a?a!b^> : outputs what you input, forever

Your goal is to write the smallest interpreter for this language.

The value of a variable can be arbitrarily large and should only be limited by the total memory your language has access to, in theory, but you are only required to handle values up to 2^256.
Your program should be able to handle arbitrarily long programs, in theory, but you will only be required to work on programs under 2^32 characters long. You are required to handle nested loops of depth up to 2^32 as well.
You can assume that the program is a valid program, and that you will only ever get non-negative integers when you ask for input. You can also assume that only ASCII printable characters are included in the input string.
The speed of the program you interpret doesn't matter, it will already be painfully slow for things as simple as 5-digit multiplication, without optimization.
If you want to use a language which cannot reasonably accept input or produce output in the way described by the language, use any interpretation you want to make it possible. This applies to any reason your language can't implement some required behavior. I want all languages to be able to compete.
Shortest program wins. Standard loopholes apply.

Ruby, 182 bytes

$h=Hash.new 0
def r(c)c.scan(/(([^!?^<>]*)(<(\g<1>*)>|[!?^]))/){$4?($1=~/(.*?)<(.*)>/
($h[$1]-=1;r$2)while$h[$1]>0):$3<?"?p($h[$2]):$h[$2]+=$3<?@?STDIN.gets.to_i:
1}end
r IO.read *$*

Try it like this:

$ cat code
a?b<>c<>a<c^c^c<b^>>b!

$ ruby lynn.rb code
3                           <-- input
6                           <-- output

How it works

The r function tokenizes an input string and executes each token:

def r(c)
    c.scan(/(([^!?^<>]*)(<(\g<1>*)>|[!?^]))/){
        ...
    }
end

We look for some variable name $2 matching [^!?^<>]*, followed by either

<...> where ... matches zero or more programs (\g is recursion), in which case $4 isn't nil
A !, ?, or ^ character, captured by $3, in which case $4 is nil.

Then the logic for executing a token is quite simple when indenting it a bit:

$4 ? (                                    # If it's a loop:
    $1 =~ /(.*?)<(.*)>/                   #   Re-match token*
    ($h[$1]-=1; r $2) while $h[$1] > 0    #   Recurse to run loop
) :                                       # Else:
    $3 < ?"                               #   If it's an !:
      ? p($h[$2])                         #     Print the var
      : $h[$2] +=                         #   Else, increment it by:
          $3 < ?@                         #     If it's a ?:
              ? STDIN.gets.to_i           #       User input
              : 1                         #     Else: 1

* There's an oniguruma bug, I think, that keeps me from simply using $3 here.


Prime sieve and sort (x86 asm) Your challenge is to write a routine, in x86 assembly, which takes a buffer containing 32-bit signed integers and writes a sorted list of the prime values to another buffer, then returns the number of values written to the output buffer. The winning solution is the one that uses the least instructions.

Here's a pseudo-C example of the process:

int __stdcall SortedPrimes(DWORD* input, DWORD* output)
{
    int ctr_in = 0;
    int ctr_out = 0;
    int val = 0;
    // copy primes to output buffer
    while((val = input[ctr_in]) != 0)
    {
        ctr_in++;
        if(isPrime(val))
            output[ctr_out++] = val;
    }
    // you must implement this sort, too!
    sort(output);
    return ctr_out;
}

// for testing/illustration purposes only
// you don't need to implement this part!
void test()
{
    int count = 0;
    int i = 0;
    int v = 0;

    // allocate buffers
    DWORD* input = (DWORD*)calloc(1024, sizeof(DWORD));
    DWORD* output = (DWORD*)calloc(1024, sizeof(DWORD));

    // fill input buffer with data
    input[0] = 0x12345678;
    input[1] = 0x57AC0F10;
    ...
    input[1022] = 0x13371337;
    input[1023] = 0; // terminating value is zero!

    // invoke your function! :]
    count = SortedPrimes(input, output);

    // dump output
    printf("Found %n primes.\n", count);
    while((v = output[i++]) != 0)
        printf("0x%x\n", v);

    free(input);
    free(output);
}

Rules:

Assume a modern Intel CPU (e.g. Core i3) running in x86-32 mode.
Assume __stdcall, i.e. parameters pushed from right to left, esp+4 is a pointer to input, esp+8 is a pointer to output, callee is responsible for cleaning stack.
You cannot call any APIs or library functions - the solution must be in pure assembly.
The input buffer consists of 32-bit non-zero signed integers, followed by 0x00000000.
The output buffer is allocated and zero'd before being passed to the function, and its size is the same as the input buffer.
Assume there are no negative inputs, i.e. the range is 0x00000001 to 0x7FFFFFFF.
The sort must be lowest to highest, such that output[0] is the lowest value in the list.
Must give an empty output buffer when given an empty input buffer.
Must properly handle cases where all values are prime / no values are prime.
You may not use compiler macros.
The code must be able to process 1000 inputs in 60 seconds or less.
I'll accept answers in AT&T syntax, but I'd prefer Intel syntax for uniformity.
Winner is the code that has the least number of instructions (i.e. lowest number of lines of code), not the least number of characters.

Assembly is pretty terse, so please add comments to your code where necessary.

Enjoy :)

32 30 29 28 27 Instructions

Changed my algorithm so we're not all trying to implement the same thing, and it's a little smaller than my earlier attempt. The code repeatedly searches through the input array, finding the smallest value, and replacing it with 0xfffffffd. It then tests if the found value is prime and outputs it if so. The code exits when the input has been completely replaced with 0xfffffffd.

    pushad
    mov     ecx, 0              ; zero output count and position
    mov     esi, [esp + 8+32]   ; load output array
find_smallest:
    mov     eax,-3              ; 0xfffffffd is larger than any valid input
    mov     edi, [esp + 4+32]   ; load input array
find_smallest_loop:
    scasd
    jbe     find_smallest_loop
    xchg    eax,[edi-4]          ; swap ecx with values that are smaller, values
                                 ; get replaced with 0xfffffffd as they are used
    cmp     eax,1
    je      find_smallest        ; skip inputs of 1
    ja      find_smallest_loop   ; exit loop if a 0 is reached
    xchg    eax,[edi-4]          ; swap 0 with lowest value found
    mov     [esi+ecx*4],eax      ; store value in next output position
    mov     ebx,2                ; ebx is divisor, start it at 2
test_next_divisor:               ; primality test
    mov     eax,[esi+ecx*4]
    cdq
    idiv    ebx                  ; use signed division
    cmp     eax,ebx
    cmovb   edx,[edi-4]          ; zero edx if prime to exit loop later on
    adc     ecx,0                ; increment output & count if prime
    inc     ebx
    test    edx,edx
    jz      find_smallest
    jns     test_next_divisor    ; exit if remainder is negative
exit_function:
    mov     [esp+28],ecx         ; move count to eax position
    popad
    ret 8


Jelly, 21 19 11 10 7 bytes

²~³¡H+2

Try it online!

Idea

Assume for a second that the first term of the final sum is subtracted rather than added.

Let n be a positive integer.

Even case

 1              6
    8       11
      15 16
      21 22
   26       29
31             36

The differences between the diagonal elements on the lower half of the rows are the first n ÷ 2 odd natural numbers. Since 1 + 3 + 5 + … + (2k + 1) = k2, they sum to (n ÷ 2)2 = n2 ÷ 4.

In this example

- 1 + 6 - 8 + 11 - 15 + 16 - 21 + 22 - 26 + 29 - 31 + 36  =
-(1 - 6)-(8 - 11)-(15 - 16)-(21 - 22)-(26 - 29)-(31 - 36) =
(    5   +   3    +    1  )+(   1    +    3    +    5   ) =
             9             +              9               = 18

Thus, the sum is 2 × n2 ÷ 4 = n2 ÷ 2.

Odd case

 1           5
    7     9
      13
   17    19
21          25

The differences between the diagonal elements on the corresponding rows from above and below (1 and 5, and 21 and 25; 7 and 9, and 17 and 19) is the same, so they will cancel out in the alternating sum.

In this example

- 1 + 5 - 7 + 9 - 13 + 17 - 19 + 21 - 25  =
-(1 - 5)-(7 - 9)- 13 +(17 - 19)+(21 - 25) =
    4   +   2   - 13 -    2    -    4     = -13

All that's left is the negative of the central element, which is the arithmetic mean of the first and last number, so it can be calculated as -(n2 + 1) ÷ 2.

General case

Since ~x = -(x + 1) for two's complement integers (~ denotes bitwise NOT), the formula for the odd case can be rewritten as ~n2 ÷ 2.

Also, since the first term (1) of the original sum is added instead of subtracted, the above formulas leave an error of 2, which has to be corrected.

Therefore, the nth cross-alternate sum is n2 ÷ 2 + 2 if n is even, and ~n2 ÷ 2 + 2 if it is odd.

Finally, bitwise NOT is an involution, i.e., ~~x = x for all x. This way ~~~x = ~x, ~~~~x = x, and, in general, ~nx (meaning that ~ is applied n times) is x if n is even and ~x if it is odd.

Thus, we can rewrite our general formula as ~nn2 ÷ 2 + 2 for all positive integers n.

Code

²~³¡H+2    Main link. Input: n

²          Yield n².
 ~         Apply bitwise NOT to n²...
  ³¡           n times.
    H      Halve the result.
     +2    Add 2.


Random triple with uniform marginals Output a random triple \$(x,y,z)\$ of real numbers such that

\$x+y+z=\frac{3}{2}\$
Each of \$x,y,z\$, taken alone, is uniformly distributed from \$0\$ to \$1\$.

Please explain in your answer what distribution your code produces and why it meets these conditions. In particular, please include a demonstration that with many samples produced by running your code many times, the distribution of each variable alone is approximately uniform.

Allowances for precision

Since computers can't produce actual real numbers, you can approximate them by outputting any of:

Floats
Decimals
Rationals

I've tried to make the rules here as friendly as possible.

Your outputs need to be accurate within \$\pm 10^{-3}\$, that is 3 decimal digits. That means you can imagine that each real-number output from your true distribution has been fudged by at most \$\pm 10^{-3}\$ in any way. It's fine if this makes \$x+y+z\$ be a bit off from \$\frac{3}{2}\$.

You may output rationals as (numerator, denominator) pairs of integers or similar. You may also choose to output just one denominator that applies to all three values, that is, output \$a,b,c\$ and \$d\$ to represent \$\frac{a}{d},\frac{b}{d},\frac{c}{d}\$. Rationals don't have to be in reduced form.

Randomness

You can assume any standard PRNG is in fact random. For instance, if it outputs random floats from 0 to 1, you can assume these are uniformly random reals that are independent from each other, and not worry about any endpoint issues. It's also fine if your code fails in a probability-zero event.

To decide whether a pseudo-random source such as time or memory contents is sufficiently random, consider an empirical test where your code is run many times in sequence to check if the randomness varies sufficiently between runs. You may have these runs be done within your language such as in a loop, or by repeatedly calling the code from outside like with a shell command. You may not assume any intentional time delay or other actions taken between runs.

APL (Dyalog Unicode), 15 bytesSBCS

1|(-,.5∘-,+⍨)?0

Try it online!

A full program that generates three floating-point numbers \$ X,Y,Z \$.

The distribution

Uses the same method as Luis Mendo's MATL answer, which in turn is from this Math.SE answer. The Math.SE answer presents the following random variables:

$$
X = \text{uniform random value in } (0,1) \\
Y = \begin{cases} X + \frac12, \quad X < \frac12 \\
X - \frac12, \quad X \geq \frac12 \end{cases} \\
Z = \frac32 - (X + Y)
$$

I found that this is equivalent to

$$
X = \text{uniform random value in } (0,1) \\
Y = \{ X + 1/2 \}, Z = \{-2X\}
$$

which, in turn, has the same distribution with

$$
r = \text{uniform random value in } (0,1) \\
X = \{ -r \}, Y = \{ 1/2 - r \}, Z = \{ 2r \}
$$

where the notation \$ \{ x \} \$ means the positive fractional part of \$ x \$.

How the code works

1|(-,.5∘-,+⍨)?0
             ?0  ⍝ r←Generate a random number from (0,1)
  ( ,    ,  )    ⍝ Create a 3-element array from r:
   -             ⍝ -r
     .5∘-        ⍝ 0.5 - r
          +⍨     ⍝ r + r (= 2r)
1|               ⍝ Extract positive fractional part from each number

Test script

⍝ Take 10000 samples of X, Y, Z's
data←f¨⍳10000

⍝ Tests that X+Y+Z = 1.5 in all cases
∧/1.5=+/¨data

⍝ Shows the distribution of X,Y,Z in 10 bins
{(⊂∘⍋⌷⊢)↓,∘≢⌸⍵}¨⌊10×↓⍉↑data
                    ↓⍉↑data  ⍝ Reform the data into X's, Y's, and Z's
                ⌊10×         ⍝ Classify into 10 bins
{             }¨     ⍝ For each of X's, Y's, or Z's,
        ↓,∘≢⌸⍵       ⍝ Gather the list of (bin, count)
 (⊂∘⍋⌷⊢)             ⍝ Sort the bins

⍝ Example result
X:  0 1012  1 1016  2 993   3 1025  4 1002  5 969   6 1002  7 977  8 1049  9 955
Y:  0 969   1 1002  2 977   3 1049  4 955   5 1012  6 1016  7 993  8 1025  9 1002
Z:  0 1013  1 944   2 1022  3 1052  4 990   5 980   6 1039  7 979  8 959   9 1022

Alternative method, 21 bytesSBCS

(3*9),3⊥¨3|(⍳3)+⊂?9/3

Try it online!

This one uses the OP's formulation from the same Math.SE question:

Generate a uniform random number \$ X \$ from \$ (0, 1) \$.
Take its ternary digits \$ X = 0.X_1 X_2 X_3 \cdots \$ and generate ternary digits of \$ Y \$ and \$ Z \$:

$$
Y_i = (X_i + 1) \% 3 \\
Z_i = (X_i + 2) \% 3
$$

Then the resulting numbers \$ X,Y,Z \$ are uniform in range \$ (0, 1) \$, and their sum is

$$
\frac3{3^1} + \frac3{3^2} + \frac3{3^3} + \cdots = \frac32
$$

Theoretically it requires infinite number of digits; the code approximates the scheme with just 9 digits, which makes \$ X+Y+Z=1.499923792 \$. I'm not exactly sure if it meets the OP's spec though.

How the code works

(3*9),3⊥¨3|(⍳3)+⊂?9/3
                 ?9/3  ⍝ Generate 9 ternary digits
         3|(⍳3)+⊂      ⍝ Ternary digits for X,Y,Z
      3⊥¨  ⍝ Convert each list of digits to numerator for the fraction
(3*9),     ⍝ Prepend the denominator


Secret Message Part 1, Elements You and your friend want to send each other secret messages.  However, because you are conspiracy theorists and think that the government has a quantum computer that can crack any standard encryption.  Therefore, you are inventing one of your own.  The first step of this is as follows: taking an input string, you check if all the letters can be represented by the symbols for the elements of the periodic table (case insensitive).  If they can be, you replace each section with the name of the element the symbol represents.  If all letters cannot be replaced in this way, you simply use the original string.

Your Task:

You are to write a program or function that encodes a message, as outlined previously.  Remember that if your program fetches data from an outside source, the size of the outside source must be added to the byte count (this loophole).  The elements and symbols used are here:

H   Hydrogen
He  Helium
Li  Lithium
Be  Beryllium
B   Boron
C   Carbon
N   Nitrogen
O   Oxygen
F   Fluorine
Ne  Neon
Na  Sodium
Mg  Magnesium
Al  Aluminum
Si  Silicon
P   Phosphorus
S   Sulfur
Cl  Chlorine
Ar  Argon
K   Potassium
Ca  Calcium
Sc  Scandium
Ti  Titanium
V   Vanadium
Cr  Chromium
Mn  Manganese
Fe  Iron
Co  Cobalt
Ni  Nickel
Cu  Copper
Zn  Zinc
Ga  Gallium
Ge  Germanium
As  Arsenic
Se  Selenium
Br  Bromine
Kr  Krypton
Rb  Rubidium
Sr  Strontium
Y   Yttrium
Zr  Zirconium
Nb  Niobium
Mo  Molybdenum
Tc  Technetium
Ru  Ruthenium
Rh  Rhodium
Pd  Palladium
Ag  Silver
Cd  Cadmium
In  Indium
Sn  Tin
Sb  Antimony
Te  Tellurium
I   Iodine
Xe  Xenon
Cs  Cesium
Ba  Barium
La  Lanthanum
Ce  Cerium
Pr  Praseodymium
Nd  Neodymium
Pm  Promethium
Sm  Samarium
Eu  Europium
Gd  Gadolinium
Tb  Terbium
Dy  Dysprosium
Ho  Holmium
Er  Erbium
Tm  Thulium
Yb  Ytterbium
Lu  Lutetium
Hf  Hafnium
Ta  Tantalum
W   Tungsten
Re  Rhenium
Os  Osmium
Ir  Iridium
Pt  Platinum
Au  Gold
Hg  Mercury
Tl  Thallium
Pb  Lead
Bi  Bismuth
Po  Polonium
At  Astatine
Rn  Radon
Fr  Francium
Ra  Radium
Ac  Actinium
Th  Thorium
Pa  Protactinium
U   Uranium
Np  Neptunium
Pu  Plutonium
Am  Americium
Cm  Curium
Bk  Berkelium
Cf  Californium
Es  Einsteinium
Fm  Fermium
Md  Mendelevium
No  Nobelium
Lr  Lawrencium
Rf  Rutherfordium
Db  Dubnium
Sg  Seaborgium
Bh  Bohrium
Hs  Hassium
Mt  Meitnerium
Ds  Darmstadtium
Rg  Roentgenium
Cn  Copernicium
Nh  Nihonium
Fl  Flerovium
Mc  Moscovium
Lv  Livermorium
Ts  Tennessine
Og  Oganesson

Input:

A string to be encoded.  You may take this in all caps or lowercase if you wish, as long as you specify that requirement in your answer.

Output:

The string, encoded as outlined previously if possible.

Examples:

Hi!                --> HydrogenIodine!
This is an example --> This is an example
Neon               --> NeonOxygenNitrogen
Snip               --> SulfurNitrogenIodinePhosphorus OR TinIodinePhosphorus
Nag                --> NitrogenSilver

Scoring:

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

JavaScript (ES6), 881 871 bytes

Takes the input string in all caps.

s=>(o={},'HEelLIithBEeryllMGagnesCAalcTIitanVanadCRhromGAallGEermanSEelenRBubidSRtrontYttrZRirconTCechnetRUuthenRHhodPDalladCDadmTEellurBAarCEerPRraseodymNDeodymPMromethSMamarEUuropGDadolinTBerbDYysprosERrbTMhulLUutetREhenIRridTLhallFRrancRAadACctinTHhorPArotactinUranAMmericCMurESinsteinFMermMDendelevLRawrencRFutherfordDBubnSGeaborgMTeitnerDSarmstadtRGoentgenFLlerovMCoscovLVivermorHydrogenBoronCarbonNitrogenOxygenFluorineNEeonALluminumPhosphorusSulfurCLhlorineARrgonMNanganeseZNincASrsenicBRromineKRryptonMOolybdenumIodineXEenonLAanthanumTAantalumPTlatinumATstatineRNadonTSennessineOGganessonNAsodiumKpotassiumFEironAGsilverWtungstenAUgoldHGmercury'.split(/([A-Z]+|[a-z]+)/).map((r,i,a)=>i%4-3?0:o[e=a[i-2]]=i>339?r[0].toUpperCase()+r.slice(1):e[0]+r+(i<235?'ium':'')),g=([c,...s],r)=>c?c<'A'|c>'Z'?g(s,r+c):o[c]&&g(s,r+o[c])||o[c+=s.shift()]&&g(s,r+o[c]):r)(s,'')||s

Extended test cases

Because this challenge is also a variant of the exact cover set problem, I've added the following test cases:

"NA" → "Sodium"
"NAG" → "N" + "AG" → "NitrogenSilver"
"NAP" → "NA" + "P" → "SodiumPhosphorus"

let f =

s=>(o={},'HEelLIithBEeryllMGagnesCAalcTIitanVanadCRhromGAallGEermanSEelenRBubidSRtrontYttrZRirconTCechnetRUuthenRHhodPDalladCDadmTEellurBAarCEerPRraseodymNDeodymPMromethSMamarEUuropGDadolinTBerbDYysprosERrbTMhulLUutetREhenIRridTLhallFRrancRAadACctinTHhorPArotactinUranAMmericCMurESinsteinFMermMDendelevLRawrencRFutherfordDBubnSGeaborgMTeitnerDSarmstadtRGoentgenFLlerovMCoscovLVivermorHydrogenBoronCarbonNitrogenOxygenFluorineNEeonALluminumPhosphorusSulfurCLhlorineARrgonMNanganeseZNincASrsenicBRromineKRryptonMOolybdenumIodineXEenonLAanthanumTAantalumPTlatinumATstatineRNadonTSennessineOGganessonNAsodiumKpotassiumFEironAGsilverWtungstenAUgoldHGmercury'.split(/([A-Z]+|[a-z]+)/).map((r,i,a)=>i%4-3?0:o[e=a[i-2]]=i>339?r[0].toUpperCase()+r.slice(1):e[0]+r+(i<235?'ium':'')),g=([c,...s],r)=>c?c<'A'|c>'Z'?g(s,r+c):o[c]&&g(s,r+o[c])||o[c+=s.shift()]&&g(s,r+o[c]):r)(s,'')||s

console.log(f('HI!'))
console.log(f('THIS IS AN EXAMPLE'))
console.log(f('NEON'))
console.log(f('SNIP'))
console.log(f('NA'))
console.log(f('NAG'))
console.log(f('NAP'))

How?

Preliminary optimization

We ignore the following 26 elements entirely, because they can safely be replaced with two symbols of one character among BCFHIKNOPSUVWY:

Bh, Bi, Bk, Cf, Cn, Co, Cs, Cu, Hf, Ho, Hs, In, Nb,
Nh, Ni, No, Np, Os, Pb, Po, Pu, Sb, Sc, Si, Sn, Yb

Encoding and decoding the elements

We use an interlaced list of element symbols in upper case and element names in lower case. Symbols are always stored as-is, while names are shortened according to the following rules:

If the first letter of the name matches the first letter of the symbol, we omit it.
If the element passes rule #1 and its name ends in "ium", we omit this suffix.

Examples:

Ag / Silver: "AGsilver"
K / Potassium: "Kpotassium"
Zn / Zinc: "ZNinc"
He / Helium: "HEel"

The 58 elements that trigger both rules are stored at the beginning of the list, followed by the 27 elements that trigger rule #1 only, followed by the 7 elements that do not trigger any rule.

We decode this list to populate the lookup table o, where the keys are the symbols and the values are the decoded element names:

"HEelLIith[...]HGmercury"       // encoded list
.split(/([A-Z]+|[a-z]+)/)       // split it by character case, which gives:
                                // [ '', 'HE', '', 'el', '', 'LI', '', 'ith', etc. ]
.map((r, i, a) =>               // for each item 'r' at position 'i' in this array 'a':
  i % 4 - 3 ?                   //   if we're not currently pointing to an element name:
    0                           //     do nothing
  :                             //   else:
    o[e = a[i - 2]] =           //     save o[e], where e = element symbol
      i > 339 ?                 //     if symbol/name first letters do not match:
        r[0].toUpperCase() +    //       we need to capitalize the first letter of the name
        r.slice(1)              //       and keep the rest unchanged
      :                         //     else:
        e[0] +                  //       we use the first letter of the symbol,
        r +                     //       followed by the name,
        (i < 235 ? 'ium' : '')  //       followed by the 'ium' suffix when appropriate
)                               // end of map()

Covering the input string

We try to replace all upper-case letters in the input string with element symbols, using the recursive function g() which eventually returns a replacement string or undefined if no exact cover is found:

g = ([c,                                  // c = next character
         ...s],                           // s = array of remaining characters
                r) =>                     // r = replacement string
  c ?                                     // if there's still at least one character:
    c < 'A' | c > 'Z' ?                   //   if it's not an upper-case letter:
      g(s, r + c)                         //     just append it to 'r'
    :                                     //   else:
      o[c] && g(s, r + o[c]) ||           //     try to find a symbol matching 'c'
      o[c += s.shift()] && g(s, r + o[c]) //     or a symbol matching 'c' + the next char.
  :                                       // else:
    r                                     //   success: return 'r'


Print X without X (cop's thread) This is the cop's thread of a cops-and-robbers challenge. You can view the robber's thread here
A pretty common beginner style question is to print some string, but there's a catch! You need to do it without using any of the characters in the string itself!
For this challenge, we will find out who is the best at printing X without X.  There are two threads to this, a cop's thread and a robber's thread.
In the cop's thread (this thread), users will choose a language (which we will call Y) and a string (which we will call X) and write a program in language Y which takes no input, and outputs exactly X without using any of the characters in X.  The cop will then post both X and Y without revealing the program they have written.
Robbers will select the cop's answers and write programs in language Y which take no input and output X.  They will post these "cracks" as answers in their thread.  A crack need only work, not to be the intended solution.
Once a cop's answer is one week old, so long as it has not been cracked, the cop may reveal their program and mark it as "safe". Safe answers can no longer be cracked and are eligible for scoring.
Cops will be scored by length of X in characters with smaller scores being better.  Only safe answers are eligible for scoring.
Extra Rules
You may be as specific or precise in choosing your language as you wish.  For example you may say your language is Python, or Python 3, Python 3.9 (pre-release), or even point to a specific implementation.  Robber's solutions need only work in one implementation of the given language.  So, for example, if you say Python is your language, a robber's crack is not required to work in all versions of Python, only one.
Since command line flags count as different languages, you should indicate specific command line flags or the possibility of command line flags as part of your language.  For ease of use, I ask that you assume there are no command line flags in cases where command line flags are not mentioned.
You may choose to have your output as an error.  If your intended solution does output as an error, you must indicate this in your answer.
Find Uncracked Cops

Python 3, Score: 81, Cracked
X =  abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'*,./:;<=>?@[]^_`{|}~
Not terribly interesting since it has such a high score, but this should be somewhat difficult to crack...
Clarification: This is in fact a full Python 3 program, running it locally with python3 print_x_out.py produces the above output for me. Likewise, the below verifier script produces no output:
with open("print_x_out.py") as file:
    source = file.read()

output = """ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'*,./:;<=>?@[\]^_`{|}~"""

for c in output:
    if c in source:
        print(f"Failed verifier check for '{c}'")

Edit: Well, that was faster than expected...


Are there any functional programming languages designed for code-golfing? Are there any functional programming languages designed for code golfing? I know that golfscript and CJam fulfill the same category for stack based, but I couldn't find a functional code golfing language.

Husk

Husk is a pure functional golfing language created by me and Leo and inspired by Haskell.
It combines a rigid type system, type inference and extensive overloading.
Functions are first class values and can be manipulated as easily as other data.
Development of Husk is ongoing and many features are still missing, but you can try it out at TIO.
We also have a SE chatroom for the language.


Gasket Weaving - draw a Sierpiński knot Given an integer N >= 2, produce an image showing a Sierpiński knot of degree N.

For example, here are knots of degree 2, 3, 4 and 5:

Click on the images to view full size (the higher the degree the larger the image).

Specification

A Sierpiński knot of degree N is drawn using the vertices of a Sierpiński triangle of degree N as guide points. A Sierpiński triangle of degree N is three Sierpiński triangles of degree N-1 arranged into a larger triangle. A Sierpiński triangle of degree 0 is an equilateral triangle.
The smallest component triangles have side length 64, giving the Sierpiński triangle on which the knot is based an overall side length of
The centre of the outer triangle is positioned at the centre of the image. This does not give equal white space at top and bottom.
The output is a square image of side length  where  is ceiling(x), the smallest integer greater than or equal to x. This is just large enough for the top vertex of the underlying Sierpiński triangle to be contained within the image when the centre of the triangle is at the centre of the image.
The single curve must pass over and under itself, strictly alternating. Solutions can choose between under then over, or over then under.
The example images show black foreground and white background. You may choose any two easily distinguished colours. Anti-aliasing is permitted but not necessary.
There must not be gaps where two arcs meet or where the curve passes over or under itself.
Output may be to any raster format image file, or to any vector format image file that includes a correct default display size. If you display directly to screen, this must be in a form that allows scrolling to see the full image when larger than the screen.

Determining arc centre, radius and thickness

The knot is constructed as a series of circular arcs that meet at points where their tangents are parallel, to give a seamless join. These arcs are displayed as annular sectors (arcs with thickness).
The centres of these arcs are the vertices of the smallest upside down triangles. Each such vertex is the centre of exactly one arc.
Each arc has a radius of
The exception is that the arcs in the three outermost triangles (at the corners of the large triangle) have a centre which is the midpoint of the two adjacent inner vertices, and thus have a radius of
Each arc is represented with a total thickness (difference between inner radius and outer radius) of  and the black borders of this each have a thickness of  The curve must have these borders, and not just be a solid strip.

Units of measure

All distances are in pixels (1 is the horizontal or vertical distance between 2 adjacent pixels).
The square root of 3 must be accurate to 7 significant figures. That is, your calculations must be equivalent to using a ROOT3 such that 1.7320505 <= ROOT3 < 1.7320515

Scoring

The shortest code in bytes wins.

For those wondering, N=0 and N=1 are not included because they correspond to a circle and a trefoil, which don't quite match the pattern that applies for N>=2. I would expect that most approaches to this challenge would need to add special case code for 0 and 1, so I decided to omit them.

Ruby, 1168 932
Corrected a mistake from last night, more golfing to do after clarifying.
This is (currently) a full program that accepts a number from stdin and outputs an svg file to stdout. I chose svg because I knew it was possible to meet all the requirements of the question, but it did have some issues. in particular SVG only supports arcs of circles as part of the path object, and does not define them in terms of their centre but rather the two endpoints.
Code
n=gets.to_i
r=64*w=0.75**0.5
m=1<<n-2
z=128*m/w
a=(s="<path style='fill:none;stroke:black;stroke-width:3.464102' transform='translate(%f %f)'
")%[0,r-r*m*8/3]+"d='M18.11943,-2A#{b=r-6*w-32} #{b} 0 0,0 #{-b} 0#{k='A%f %f 0 0 '%([58*w]*2)}0 0,38.71692
M28.58980,1.968882#{l='A%f %f 0 0 '%([70*w]*2)}0 #{c=r+6*w-32} 0A#{c} #{c} 0 0,0 #{-c} 0#{l}0 -9 44.65423'/>"
p=2
m.times{|i|(i*2+1).times{|j|(p>>j)%8%3==2&&a<<s%[128*(j-i),r*3+r*i*4-r*m*8/3]+
"d='M-55,44.65423#{k}0 11.5,25.11473#{l}1 35.41020,1.968882
M-64,51.48786#{l}0 20.5,30.31089#{k}1 36.82830,13.17993
M-82.17170,-2.408529#{l}1 -11.5,25.11473#{k}0 0,38.71692
M-81.52984 8.35435#{k}1 -20.5,30.31089#{l}0 -9,44.65423
M9,44.65423#{k}0 81.52984,8.35435
M0,51.48786#{l}0 91.17169,13.17993'/>"}
p^=p*4}
puts "<svg xmlns='http://www.w3.org/2000/svg' viewBox='#{-z} #{-z} #{e=2*z+1} #{e}' width='#{e}px' height='#{e}px'>"+
"<g transform='rotate(%d)'>#{a}</g>"*3%[0,120,240]+"</svg>"

Output N=4
rescaled by Stack exchange. Looks much better as original.

Explanation
At first I considered something like http://euler.nmt.edu/~jstarret/sierpinski.html where the triangle is broken down into three differently coloured strands, each of which forms a path from one corner to another. The incomplete circles are shown as incomplete hexagons there. inscribing circles inside the hexagons shows that the circle radius should be sqrt(3)/2 times the sidelength. The strands could be built up recursively as shown, but there is an added complication because the corners need to be rounded and it is difficult to know in which direction to curve, so I did not use this approach.
What I did was the following.
In the image below you can see there are horizontal twists belonging to the N=2 units (in green) arranged in a sierpinski triangle and additional bridging twists (in blue.)
It is common knowledge that the odd numbers on Pascal's triangle form a sierpinski triangle. A sierpinski triangle of binary digits can be obtained in an analogous manner by starting with the number p=1 and iteratively xoring it with p<<1.
I modified this approach, starting at p=2 and iteratively xoring with p*4. This gives a sierpinski triangle alternating with columns of zeros.
Now we can rightshift p and inspect the last three bits using %8. If they are 010 we need to draw a green twist belonging to an N=2 unit. if they are 101 we need to draw a blue, bridging twist. To test for both of these numbers together we find the modulo %3 and if this is 2 we need to draw the twist.
Finally, in additional to the horizontal twists, we make two copies rotated through 120 and 240 degrees to draw the diagonal twists and complete the picture. All that remains is to add the corners.
Commented code
n=gets.to_i

#r=vertical distance between rows
r=64*w=0.75**0.5

#m=number of rows of horizontal twists
m=1<<n-2

#z=half the size of the viewport
z=128*m/w

#s=SVG common to all paths
s="<path style='fill:none;stroke:black;stroke-width:3.464102' transform='translate(%f %f)'
"

#initialize a with SVG to draw top corner loop. Set k and l to the SVG common to all arcs of 58*w and 70*w radius
a=s%[0,r-r*m*8/3]+
"d='M18.11943,-2A#{b=r-6*w-32} #{b} 0 0,0 #{-b} 0#{k='A%f %f 0 0 '%([58*w]*2)}0 0,38.71692
M28.58980,1.968882#{l='A%f %f 0 0 '%([70*w]*2)}0 #{c=r+6*w-32} 0A#{c} #{c} 0 0,0 #{-c} 0#{l}0 -9 44.65423'/>"

#p is the pattern variable, top row of twists has one twist so set to binary 00000010
p=2

#loop vertically and horizontally
m.times{|i|
 (i*2+1).times{|j|

   #leftshift p. if 3 digits inspected are 010 or 101
   (p>>j)%8%3==2&&

   #append to a, the common parts of a path...
   a<<s%[128*(j-i),r*3+r*i*4-r*m*8/3]+

   #...and the SVG for the front strand and left and right parts of the back strand (each strand has 2 borders)
"d='M-55,44.65423#{k}0 11.5,25.11473#{l}1 35.41020,1.968882
M-64,51.48786#{l}0 20.5,30.31089#{k}1 36.82830,13.17993
M-82.17170,-2.408529#{l}1 -11.5,25.11473#{k}0 0,38.71692
M-81.52984 8.35435#{k}1 -20.5,30.31089#{l}0 -9,44.65423
M9,44.65423#{k}0 81.52984,8.35435
M0,51.48786#{l}0 91.17169,13.17993'/>"}

#modify the pattern by xoring with 4 times itself for the next row
p^=p*4}

#output complete SVG of correct size with three copies of the finished pattern rotated through 0,120,240 degrees.
puts "<svg xmlns='http://www.w3.org/2000/svg' viewBox='#{-z} #{-z} #{e=2*z+1} #{e}' width='#{e}px' height='#{e}px'>"+
"<g transform='rotate(%d)'>#{a}</g>"*3%[0,120,240]+"</svg>"


Hexagonal Triangles! Your task: make a hexagonal triangle with side length n, where n is a positive whole number or 0.

First, let me define a hexagon:

 / \
|   |
 \ /

(Amazing ASCII art, right?)

Hexagons can be linked together by sharing sides:

 / \ / \
|   |   |
 \ / \ /

   / \
  |   |
 / \ /
|   |
 \ /

A hexagonal triangle is the following:

   / \
  |   |
 / \ / \
|   |   |
 \ / \ /

That hexagonal triangle has a side length of 2-- 2 hexagons are required to make one side. A hexagonal triangle with side-length 1 is just a single hexagon, and a hexagon with side-length 0 is empty.

More formally, a hexagonal triangle is a triangle made of hexagons linked by their sides. The top hexagon links to the two below it on its bottom two sides. The triangle in the bottom left links to the one to its right and top-right, and the one in the bottom right links to the ones on its left and upper left. There are hexagons in between the corner ones, connected by their opposite sides, and their number is n-2. The triangles are not filled.

More examples:

Side length 3:
     / \
    |   |
   / \ / \
  |   |   |
 / \ / \ / \
|   |   |   |
 \ / \ / \ /

Side length 4:
       / \
      |   |
     / \ / \
    |   |   |
   / \ / \ / \
  |   |   |   |
 / \ / \ / \ / \
|   |   |   |   |
 \ / \ / \ / \ /
(This triangle isn't really filled, the borders make it look like there is a hexagon in the middle, but there is not.)

Side length 5:
         / \
        |   |
       / \ / \
      |   |   |
     / \ / \ / \
    |   |   |   |
   / \ /     \ / \
  |   |       |   |
 / \ / \ / \ / \ / \
|   |   |   |   |   |
 \ / \ / \ / \ / \ /

Side length 6:
           / \
          |   |
         / \ / \
        |   |   |
       / \ / \ / \
      |   |   |   |
     / \ /     \ / \
    |   |       |   |
   / \ /         \ / \
  |   |           |   |
 / \ / \ / \ / \ / \ / \
|   |   |   |   |   |   |
 \ / \ / \ / \ / \ / \ /

Charcoal, 62 43 39 bytes

ＮβＦ³«Ｆ⁻β‹ι²« / \¶|   |¶ \ /Ｍ×²ι↑¿⁻¹ιＭ⁶←

Try it online! Edit: Saved some bytes thanks to @ASCII-only (not sure exactly how many as I also saved another 6 10 bytes but then needed to spend 4 bytes on a bugfix). Now using nested loops, which is what this should have been all along.


Is it a doubling sequence? A doubling sequence is an array of numbers where each subsequent number is at least twice the previous number.
Given an ordered list of numbers, determine if the numbers in the list (\$n_{x}\$) have the property that:
\$n_1 \times 2 \le n_2\$
\$n_2 \times 2 \le n_3\ ...\$
and so on until reaching the end of the list.
Input
A list of two or more numbers.
Output
Any distinct True or False value.
Examples:
[10,20,30] -> False
[10,20,40] -> True
[1,2,3] -> False
[1,2,4] -> True
[1,2,10] -> True
[1,1] -> False
[10,1] -> False

R, 27 26 bytes

all(diff(log2(scan()))>=1)

Try it online!

1 byte saved by Giuseppe.


Implement simplified kerning Introduction

Kerning means adjusting the spacing between the letters of a text.
As an example, consider the word Top written with the following three glyphs:

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

We could just fill the gaps between the glyphs with dots and be done with it, but the gaps somehow look too wide.
Instead, we slide the glyphs to the left so that they almost touch:

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

This looks much better!
Note how the bar of T is on top of the left border of o.
In this challenge, your task is to implement a simple kerning program for such rectangular glyphs.

The kerning process

Consider two rectangular 2D character arrays of . and # of the same shape.
In our simple kerning process, we first place the arrays side by side, with one column of .s in between.
Then, we move each # in the right array one step to the left, until some #s of the left and right array are orthogonally or diagonally adjacent.
The outcome of the kerning is the step before we introduce adjacent #s.
Your task is to implement this process.

Let's take an example:

Inputs:
..###
#....
#....
..##.

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

Process:
..###....#.
#........##
#.......###
..##......#

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

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

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

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

In the last array, we have new adjacent pairs of #s, so the second-to-last array is the result of the kerning process.

Input and output

For simplicity, you only need to handle kerning of two glyphs.
Your inputs are two rectangular 2D arrays, in one of the following formats:

2D arrays of integers, with 0 standing for . and 1 for #.
Multiline strings over .#.
Arrays of strings over .#.
2D arrays of the characters .#.

If the inputs are taken as a single string, you can use any reasonable delimiter.
However, the delimiter should go between the two arrays, meaning that you are not allowed to take the two inputs already paired row-by-row.

Your output is the result of the kerning process applied to these two arrays, which is a rectangular 2D array in the same format as the inputs.
You are allowed to add or remove any number of leading or trailing columns of .s, but the output must be rectangular and have the same height as the inputs.
It is guaranteed that the kerning process ends before the left edge of the second input slides over the left edge of the first input.

Rules and scoring

The lowest byte count in each programming language wins.
Standard code-golf rules apply.

Test cases

To help with copy-pasting, these test cases are given as lists of strings.

["#"] ["#"] -> ["#.#"]
["#.","..",".#"] ["##","..","##"] -> ["#..##",".....",".#.##"]
["..#","#..","#.."] ["...","..#","###"] -> ["..#..","#...#","#.###"]
["###.","##..","#...","...."] ["....","...#","..#.",".#.."] -> ["###..","##..#","#..#.","..#.."]
["..##...","#......","#......"] [".....##",".....##",".#...#."] -> ["..##..##","#.....##","#.#...#."]
["...#.",".....",".....",".....","....#"] [".....","....#","#....",".....","....."] -> ["...#..",".....#",".#....","......","....#."]
["..#..",".....",".....",".....","....#"] [".....","....#","#....",".....","....."] -> ["..#..","....#","#....",".....","....#"]
["######","#.....","#.....","#.....","######"] ["......",".....#",".#...#",".....#","......"] -> ["######..","#......#","#..#...#","#......#","######.."]
["######","#.....","#.....","#.....","######"] ["......","......",".#....","......","......"] -> ["######","#.....","#.#...","#.....","######"]
["#...#","#..#.","#.#..","##...","#.#..","#..#.","#...#"] ["...#.","..#..",".#...",".#...",".#...","..#..","...#."] -> ["#...#..#","#..#..#.","#.#..#..","##...#..","#.#..#..","#..#..#.","#...#..#"]

APL (Dyalog Classic), 40 39 bytes

-1 thanks to Erik the Outgolfer

{⌈⌿↑⍺(⍉(1-⌈/+⌿+∘×⍨2⌈/0,+/⌈\↑(⌽⍺)⍵)↑⍉⍵)}

Try it online!


Output the smallest powers of 2 with two identical sub-strings of digits n long For each integer n, 0 or higher, output the lowest power of 2 that has two identical sub-strings of n digits in decimal, and the two indices where the digit sub-strings start (0-based).

  n      Output      Proof (don't output this)
     0  =>  0 [0 1]        (_1 & 1_)
     1  =>  16 [0 4]      (65536 & 65536)
     1  =>  16 [1 2]      (65536 & 65536)
     2  =>  24 [0 6]      (16777216 & 16777216)
     2  =>  24 [2 3]      (16777216 & 16777216)

The possible outputs for the first three inputs are given above. When there is more than one output for a given input, either is acceptable. Only the digit positions will be different. Just output the numbers, the brackets are for clarity only. You don't need to output n.

Output a list of as many as you can find in one minute, or your code runs out of resources, whichever comes first. Please include the output with your answer. If the list is huge, just restrict it to the first and last 5. Your code must be able to find up to n = 9 in under a minute. I've written a Perl program that finds n = 9 after about 20 seconds, so this should be easy to do.

Your code doesn't need to halt itself. It is acceptable if you manually break out if it after a minute.

This is code-golf, so lowest number of bytes wins!

APL (Dyalog Extended), 68 bytes

'01'(0{x≢`∪x←⍺⍺,/⍺:⍺((⍺⍺+1)∇∇)⊃⎕←⍵,⊃a/⍨</¨⊢a←⍸∘.≡⍨x⋄(+⌂big⍨⍺)∇1+⍵})0

Try it online!
APL is not known for big integer arithmetic, infinite output, or interpreter speed (and using Extended incurs even more overhead), yet it outputs successfully up to n=9 barely under a minute.
How it works
The code is basically an infinitely running recursive operator. The left argument is the string representation of the power of 2, the right argument is the corresponding exponent (which was needed to meet the speed requirement), and the left operand is the current value of n.
{
  x←⍺⍺,/⍺          ⍝ Extract length-n segments of given number
  x≢`∪x:           ⍝ If it has duplicates...
  a←⍸∘.≡⍨x         ⍝   Construct the pairs of indices of equal slices
  ⊃a/⍨</¨⊢a        ⍝   Keep the ones (L,R) where L<R and take the first one
  ⊃⎕←⍵,...         ⍝   Concat with the exponent, print it, extract ⍵ back
  ⍺((⍺⍺+1)∇∇)...   ⍝   Continue running with n+1
  ⋄                ⍝ Otherwise...
  (+⌂big⍨⍺)∇1+⍵    ⍝   Recurse with next power of two, using same n implicitly
}
'01'(0{...})0  ⍝ Invoke the dop with starting values


Digital Sum Fibonacci We are all familiar with the Fibonacci sequence:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765

However, instead of, f(n) = f(n-1) + f(n-2) we'll be taking digital sum of the previous 2 entries.

The sequence should still start with 0, 1, after that the differences are rapidly apparent. This list is 0-indexed, you may use 1-indexed as well, state which you used.

f(0)  = 0
f(1)  = 1
f(2)  = 1   # 0 + 1
f(3)  = 2   # 1 + 1
f(4)  = 3   # 1 + 2
f(5)  = 5   # 2 + 3
f(6)  = 8   # 3 + 5
f(7)  = 13  # 8 + 5
f(8)  = 12  # 8 + 1 + 3
f(9)  = 7   # 1 + 3 + 1 + 2
f(10) = 10  # 1 + 2 + 7
f(11) = 8   # 7 + 1 + 0
f(12) = 9   # 1 + 0 + 8
f(13) = 17  # 8 + 9
f(14) = 17  # 9 + 1 + 7
f(15) = 16  # 1 + 7 + 1 + 7
f(16) = 15  # 1 + 7 + 1 + 6
f(17) = 13  # 1 + 6 + 1 + 5
f(18) = 10  # 1 + 5 + 1 + 3
f(19) = 5   # 1 + 3 + 1 + 0
f(20) = 6   # 1 + 0 + 5
f(21) = 11  # 5 + 6
f(22) = 8   # 6 + 1 + 1
f(23) = 10  # 1 + 1 + 8
f(24) = 9   # 8 + 1 + 0
f(25) = 10  # 1 + 0 + 9
f(26) = 10  # 9 + 1 + 0
f(27) = 2   # 1 + 0 + 1 + 0
(After this point it repeats at the 3rd term, 0-indexed)

Note: I didn't notice the repetition until I posted the challenge itself, and here I was thinking it'd be impossible to write another novel Fibonacci challenge.

Your task is, given a number n, output the nth digit of this sequence.

First 3 digits: [0,1,1],

24-digit repeated pattern: [2,3,5,8,13,12,7,10,8,9,17,17,16,15,13,10,5,6,11,8,10,9,10,10]

Hint: You may be able to exploit this repetition to your advantage.

This is code-golf, lowest byte-count is the winner.

BONUS: If you use the repetition in your answer, I will award the lowest byte-count answer that takes advantage of the repetition in the sequence a bounty of 100 points. This should be submitted as part of your original answer, after your original answer. See this post as an example of what I am talking about: https://codegolf.stackexchange.com/a/108972/59376

To qualify for this bonus your code must run in constant time (O(1)) with an explanation.

Bonus Winner: Dennis https://codegolf.stackexchange.com/a/108967/59376 < Dennis won.

Most Unique Implementation: https://codegolf.stackexchange.com/a/108970/59376
(Also will receive 100 points, finalized after correct answer is chosen)

JavaScript (ES6), 45 bytes

f=(n,x=0,y=1)=>n?f(n-1,y,(x%9||x)+(y%9||y)):x
<input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o>

x and y can't both be 9, since that would require the previous number to be 0, so their digital sum can't exceed 17. This means that the digital root for numbers greater than 9 is the same as the remainder modulo 9.


Define the finite field GF(9) \$GF(9)\$ or \$GF(3^2)\$ is the smallest finite field whose order isn't a prime or a power of two. Finite fields of prime order aren't particurlarly interesting and there are already challenges for \$GF(2^8)\$ (link) and \$GF(2^{64})\$ (link).

Challenge

First define nine elements of the field. These must be distinct integers from 0 to 255, or the one-byte characters their code points represent. State in your answer which representation you choose.

Then implement two binary operations, addition and multiplication, satisfying the field axioms:

Both operations must be commutative and associative.
Addition has the identity element \$0\$ and an additive inverse for each element.
Multiplication has the identity element \$1\$ and a multiplicative inverse for each element except \$0\$.
Multiplication distributes over addition: \$a·(b+c) = (a·b)+(a·c)\$

Addition and multiplication can be implemented as functions or programs taking two field elements and producing one field element.

Since the field is really small, you can test the axioms exhaustively to check your implementation or verify the addition and multiplication tables.

Mathematical construction

Elements of \$GF(3^2)\$ can be interpreted as polynomials of the form \$P(x)=a x+b\$ over \$GF(3)\$. (Addition and multiplication in \$GF(3)=\{0,1,2\}\$ are the standard integer operations modulo 3.)

Then addition in \$GF(3^2)\$ is simply the addition of two polynomials. Multiplication is defined by the product of two polynomials, reduced modulo a polynomial of degree 2 which is irreducible over \$GF(3)\$.

Example

Mapping polynomials to integers with \$n=3a+b\$ and using the irreducible polynomial \$x^2+1\$ yields the following addition and multiplication tables. Note that there are other possible isomorphisms of these tables.

+   0 1 2 3 4 5 6 7 8   *   0 1 2 3 4 5 6 7 8
   ------------------      ------------------
0 | 0 1 2 3 4 5 6 7 8   0 | 0 0 0 0 0 0 0 0 0
1 | 1 2 0 4 5 3 7 8 6   1 | 0 1 2 3 4 5 6 7 8
2 | 2 0 1 5 3 4 8 6 7   2 | 0 2 1 6 8 7 3 5 4
3 | 3 4 5 6 7 8 0 1 2   3 | 0 3 6 2 5 8 1 4 7
4 | 4 5 3 7 8 6 1 2 0   4 | 0 4 8 5 6 1 7 2 3
5 | 5 3 4 8 6 7 2 0 1   5 | 0 5 7 8 1 3 4 6 2
6 | 6 7 8 0 1 2 3 4 5   6 | 0 6 3 1 7 4 2 8 5
7 | 7 8 6 1 2 0 4 5 3   7 | 0 7 5 4 2 6 8 3 1
8 | 8 6 7 2 0 1 5 3 4   8 | 0 8 4 7 3 2 5 1 6

Test of distributivity using the tables above:

$$5 · (2 + 7) = 5 · 6 = 4$$
$$(5 · 2) + (5 · 7) = 7 + 6 = 4$$

Note that simply using addition and multiplication modulo 9 won't work.

Scoring

This is code golf. Your score is the sum of bytes of the functions (or programs) for addition and multiplication. Lowest number of bytes wins.

Haskell, 118 112 107 bytes

Here I use the numbers \$n= 0,1,2,\ldots,8\$ to represent the field elements. Internally these are converted to a list \$[a,b]\$ that represents a polynomial \$aX+b\$, (using \$a = \lfloor n/3 \rfloor\$ and \$b = n \mod 3 \$, or \$n=3a+b\$), and we then proceed using the usual arithmetic using these polynomials in \$(\mathbb  Z / 3\mathbb Z)[X]/(X^2+1)\$. In this case we have

$$(aX+b) + (cX+d) = (a+c)X + (b+d)$$

and similarly

$$\begin{align*}
(aX+b) \cdot (cX+d) &= acX^2+(ad+bc)X + bd
\\
& \equiv ac(-1) +(ad+bc)X + bd \mod X^2+1\\
& \equiv (ad+bc)X+(bd-ac)
\end{align*}$$

Thanks for -6 bytes @WheatWizard!

i x=[div x 3,x]                --conert integer to polynomial/list representation
j[a,b]=mod(a*3+mod b 3)9       --inverse of i
s=(.i).(j.).zipWith(+).i       --"sum"
m[a,b][c,d]=j[a*d+b*c,b*d-a*c] --core function of "product"
p=(.i).m.i                     --"product"

Try it online!


Wrap-Around Subsequences Introduction

In this challenge, your task is to find generalized subsequences of strings.
The subsequences are not necessarily contiguous, and they can also "wrap around" the string, going past its end and starting again from the beginning.
You'll want to minimize the number of wraps, though.

More formally, let u and v be any two strings, and k ≥ 0 an integer.
We say that u is a k-wrapping subsequence of v, if there are distinct indices i1, i2, ..., ilen(u) such that u == v[i1] v[i2] ... v[ilen(u)], and at most k of the indices ij satisfy ij > ij+1.
This means that u can be found inside v by going from left to right, choosing some of its characters on the way, and wrapping around at most k times (equivalently, doing at most k+1 sweeps across v).
Note that no character can be chosen more than once, even after a wrap-around, and that 0-wrapping subsequences are exactly the ordinary subsequences that we are all familiar with.

The Task

Your inputs are two non-empty alphanumeric strings u and v, and your output is the smallest integer k such that u is a k-wrapping subsequence of v.
If no such k exists, the output shall be -1.

Example

Consider the inputs u := xyzyxzzxyx and v := yxzzazzyxxxyz.
If we start looking for the characters of u in v in a greedy fashion, we will wrap around 3 times:

 yxzzazzyxxxyz
>─x─────y────z┐
┌─────────────┘
└y───────x────┐
┌─────────────┘
└──zz─────x─y─┐
┌─────────────┘
└──────────x──>

Thus the correct output is at most 3.
Note how the left-most character x is selected once, and then ignored on the second sweep, since it cannot be re-used.
However, there exists a shorter method with only 2 wrap-arounds:

 yxzzazzyxxxyz
>──────────xyz┐
┌─────────────┘
└yxzz────x────┐
┌─────────────┘
└───────y─x───>

It turns out that one wrap-around (that is, two sweeps) is not enough, so the correct output is 2.

Rules and Bonuses

You can write either a function or a full program, and you can also change the order of the inputs if needed.
The lowest byte count wins, and standard loopholes are disallowed.

There is a bonus of -10% for computing all of the test cases in under 10 seconds total. I will test unclear cases on my machine; my reference implementation in Python takes about 0.6 seconds. I have a 7-year old laptop with 1.86 GHz dual core CPU, which you may want to take into account.

Test Cases

"me" "moe" -> 0
"meet" "metro" -> -1
"ababa" "abaab" -> 1
"abaab" "baabaa" -> 1
"1c1C1C2B" "1111CCCcB2" -> 3
"reverse" "reserved" -> 2
"abcdefg" "gfedcba" -> 6
"xyzyxzzxyx" "yxzzazzyxxxyz" -> 2
"aasdffdaasdf" "asdfddasdfsdaafsds" -> 2

Pyth, 34 bytes

Mh+Smssm>.ukC,dtdfqGsm@HkT.PUHlG_1

This defines a function g, which takes two strings as parameter. Try it online: Pyth Compiler/Executor

This code is very inefficient. It has a time and memory complexity of len(v)!/(len(v)-len(u))!. It is not able to solve the longer test cases in under 10 seconds. (It also will crash very likely, since it will run out of memory.)

M                                    define g(G, H): return _
                          .PUHlG        all permutations of [0, 1, ..., len(H)-1] of length len(G)
                 fqGsm@HkT              filter the permutations which form the string G
    mssm>.ukC,dtd                       compute the number of wraps for each of the remaining permutations
  +S                            _1      sort the numbers and append -1
 h                                      return the first element


Make some Alphabet Rain Alphabet Rain

The Task:

The basic premise is to print out the input string and then repeat each character vertically, based on it's (0-indexed) position in the (case-insensitive) alphabet A-Z. A is at location 0 so is not repeated, e is at position 4 so is repeated 4 times, P is at position 15 so is repeated 15 times, ! is not in A-Z so is repeated 0 times, etc.

For clarity, anything that falls outside of the range B-Zb-z, for example digits or special characters, will not be repeated, and thus will only appear on the first line.

This is code-golf, so shortest solution in each language is the winner.

Input:

Input will be in the standard printable ASCII character set, from 32   up to 126 ~.
The input string will be 1 character long or longer.
There will not be any leading or trailing whitespace.
You can take take input as a string ("hello") or list of characters ( ["h", "e", "l", "l", "o"])

Examples:

Input of aaaa gives:

aaaa

Input of abcda gives:

abcda
 bcd
  cd
   d

Input of Programming Puzzles & Code Golf!, gives:

Programming Puzzles & Code Golf!
Progr mming Puzzles   Code Golf
Progr mming Puzzles   Code Golf
Progr mming Puzzles    ode Golf
Progr mming Puzzles    o e Golf
Progr mming Puzzl s    o   Golf
Progr mming Puzzl s    o   Gol
Pro r mmin  Puzzl s    o    ol
Pro r mmin  Puzzl s    o    ol
Pro r mm n  Puzzl s    o    ol
Pro r mm n  Puzzl s    o    ol
Pro r mm n  Puzzl s    o    ol
Pro r mm n  Puzz  s    o    o
Pro r    n  Puzz  s    o    o
Pro r       Puzz  s    o    o
Pr  r       Puzz  s
 r  r        uzz  s
 r  r        uzz  s
             uzz  s
             uzz
             uzz
              zz
              zz
              zz
              zz
              zz

Input of ~|[abc<0>cba]|~, gives:

~|[abc<0>cba]|~
    bc   cb
     c   c

Notes:

standard loopholes apply
output can be a list of strings, but:
extraneous trailing newlines are not allowed (single \n on final line is acceptable)
output can be a list of lists of characters, so long as it looks like it's raining characters
no leading newline
to our Nordic users who have a few extra letters in their "A-Z" alphabet, feel free to support them, but it's not part of the challenge

6502 machine code (C64), 113 bytes
00 C0 20 FD AE 20 9E AD 85 FB 20 A3 B6 A0 00 84 FC B1 22 99 6F C1 C9 41 90 14
C9 5B B0 04 E9 40 B0 0E C9 C1 90 08 C9 DB B0 04 E9 C0 B0 02 A9 00 99 6F C0 C5
FC 30 02 85 FC C8 C4 FB D0 D3 A9 00 99 6F C1 A0 C1 A9 6F 20 1E AB A9 0D 20 D2
FF A6 FC D0 01 60 C6 FC A0 00 B9 6F C1 F0 E6 BE 6F C0 D0 07 A9 20 99 6F C1 D0
05 CA 8A 99 6F C0 C8 D0 E7

Online demo
Usage: sys49152,"[string]", e.g. sys49152,"Programming Puzzles & Code Golf!".
Important: If the program was loaded from disk (like in the online demo), issue a new command first! This is necessary because loading a machine program trashes some C64 BASIC pointers.
Note: The C64 is by default in a mode without lowercase letters -- in order to be able to enter a mixed-case string, switch to lowercase mode first by pressing SHIFT+CBM.

Explanation
Here's a commented disassembly listing:
         00 C0       .WORD $C000        ; load address
.C:c000  20 FD AE    JSR $AEFD          ; consume comma
.C:c003  20 9E AD    JSR $AD9E          ; evaluate expression
.C:c006  85 FB       STA $FB            ; store string length
.C:c008  20 A3 B6    JSR $B6A3          ; free string
.C:c00b  A0 00       LDY #$00           ; initialize counter
.C:c00d  84 FC       STY $FC            ; and number of "extra" lines
.C:c00f   .copyloop:
.C:c00f  B1 22       LDA ($22),Y        ; load next character
.C:c011  99 6F C1    STA .outbuf,Y      ; store to buffer
.C:c014  C9 41       CMP #$41           ; compare with 'a'
.C:c016  90 14       BCC .zerocount     ; smaller -> no repetition
.C:c018  C9 5B       CMP #$5B           ; compare with 'z'
.C:c01a  B0 04       BCS .checkupper    ; larger -> check for uppercase
.C:c01c  E9 40       SBC #$40           ; subtract 'a' ('a' - 1 and carry)
.C:c01e  B0 0E       BCS .cl_storecount ; and jump to store in repeat count
.C:c020   .checkupper:
.C:c020  C9 C1       CMP #$C1           ; compare with 'A'
.C:c022  90 08       BCC .zerocount     ; smaller -> no repetition
.C:c024  C9 DB       CMP #$DB           ; compare with 'Z'
.C:c026  B0 04       BCS .zerocount     ; larger -> no repetition
.C:c028  E9 C0       SBC #$C0           ; subtract 'A' ('A' - 1 and carry)
.C:c02a  B0 02       BCS .cl_storecount ; and jump to store in repeat count
.C:c02c   .zerocount:
.C:c02c  A9 00       LDA #$00           ; store 0 ...
.C:c02e   .cl_storecount:
.C:c02e  99 6F C0    STA .repcount,Y    ; ... in repeat count
.C:c031  C5 FC       CMP $FC            ; compare with number of extra lines
.C:c033  30 02       BMI .cl_next       ; smaller -> go on with loop
.C:c035  85 FC       STA $FC            ; repeat count to number of extra lines
.C:c037   .cl_next:
.C:c037  C8          INY                ; next
.C:c038  C4 FB       CPY $FB            ; compare with string length
.C:c03a  D0 D3       BNE .copyloop      ; not yet reached? -> repeat
.C:c03c  A9 00       LDA #$00           ; terminate string in buffer
.C:c03e  99 6F C1    STA .outbuf,Y      ; with 0 byte
.C:c041   .outloop:
.C:c041  A0 C1       LDY #>.outbuf      ; output ...
.C:c043  A9 6F       LDA #<.outbuf      ; ...
.C:c045  20 1E AB    JSR $AB1E          ; ... string
.C:c048  A9 0D       LDA #$0D           ; and output ...
.C:c04a  20 D2 FF    JSR $FFD2          ; ... newline
.C:c04d  A6 FC       LDX $FC            ; load extra line count
.C:c04f  D0 01       BNE .ol_step       ; not zero -> go on
.C:c051  60          RTS                ; WE ARE DONE HERE ;)
.C:c052   .ol_step:
.C:c052  C6 FC       DEC $FC            ; decrease extra line count
.C:c054  A0 00       LDY #$00           ; initialize counter
.C:c056   .eraseloop:
.C:c056  B9 6F C1    LDA .outbuf,Y      ; load next character from buffer
.C:c059  F0 E6       BEQ .outloop       ; 0 byte? -> end of string, output
.C:c05b  BE 6F C0    LDX .repcount,Y    ; load repeat count for this characer
.C:c05e  D0 07       BNE .el_step       ; not 0 yet? -> jump to decrement
.C:c060  A9 20       LDA #$20           ; load code for space
.C:c062  99 6F C1    STA .outbuf,Y      ; store in current string position
.C:c065  D0 05       BNE .el_next       ; and jump to next loop iteration
.C:c067   .el_step:
.C:c067  CA          DEX                ; decrease repeat count ...
.C:c068  8A          TXA                ; ... and ...
.C:c069  99 6F C0    STA .repcount,Y    ; ... store back
.C:c06c   .el_next:
.C:c06c  C8          INY                ; increase counter ...
.C:c06d  D0 E7       BNE .eraseloop     ; and jump back to loop

.C:c06f   .repcount:
.C:c06f              .RES $100          ; 256 bytes for repeat count
.C:c16f   .outbuf:
.C:c16f              .RES $100          ; 256 bytes as buffer for output


Find The Rank Of A Word Definition
The rank of a word is defined as the position of the word when all the possible permutations (or arrangements) of its letters are arranged alphabetically, like in a dictionary, no matter if the words are meaningful or not.
Let us consider these two words - "blue" and "seen". To begin with, we would write all the possible arrangements of the letters of these words in alphabetical order:
"blue": "belu","beul","bleu","blue","buel","bule","eblu","ebul","elub","elbu","eubl",
        "eulb","lbeu","lbue","lebu","leub","lube","lueb","ubel","uble","uebl","uelb",
        "ulbe","uleb"
"seen": "eens","eesn","enes","ense","esen","esne","nees","nese","nsee","seen",
        "sene","snee"

Now let's look from the left and find the position of the words we need. We see that the word "blue" is at the 4th position and "seen" is at 10th position. So the rank of the word "blue" is 4, and that of "seen" is 10. This is the general way of calculating the rank of a word. Make sure you start counting from 1 only.
Task
Your task is to write a code to take any word as an input and display its rank. The rank should be the output.
Be careful about words containing repeated letters.
Examples
"prime" -> 94

"super" -> 93

"bless" -> 4

"speech" -> 354

"earth" -> 28

"a" -> 1

"abcd" -> 1

"baa" -> 3

You can assume the input to be completely in lowercase and the input will only contain alphabetical characters. Also if a blank space or an invalid string is entered, you may return anything.
Scoring
This is code-golf , so the shortest code wins!

Python 3, 71 bytes

lambda s:sum(t<=(*s,)for t in{*permutations(s)})
from itertools import*

Try it online!