Golf Me a Random Dubstep of the Day List Aside of nursing my child, Vitsy, and dabbling in the art of code golf, I also am an avid dubstep fan, listening to all the new dubstep that Monstercat puts out as regularly as I can. I also share a random dubstep of the day, though not regularly, in the Nineteenth Byte. This last bit is what this challenge relates to; so, without further ado, let me get to what you actually need to think about:

The Challenge

You must generate a randomly sorted list of songs from this playlist in the following format:

<Title> - <Artist>: <link to the video>

Rules

The output list must update with the playlist provided, or every byte used counts as 2 (your score would be double your byte count).
The output list must have no repeats.
The output list must be given in the specified format.
The output list must have all of the videos listed in the playlist provided.
You may not use builtins for array shuffling (such as Collections.shuffle(List<?> x) from Java)
You may not use the YouTube builtin shuffle mechanism (as this is not random).
There are no limits on runtime.

Example Output

Division - Ephixa: https://www.youtube.com/watch?v=M1mPFWhgYUM&list=PLF5C76212C58C464A&index=95
Wanna Know You (ft. Holly Drummond) - Direct: https://www.youtube.com/watch?v=6QWQfzYMJTs&list=PLF5C76212C58C464A&index=24
Edge of the World (feat. Becko) - Razihel & Xilent: https://www.youtube.com/watch?v=P0dQ55ZgNkw&index=4&list=PLF5C76212C58C464A
... until the final video ...
Way Too Deep - Grabbitz: https://www.youtube.com/watch?v=4T28WgVqdrA&index=8&list=PLF5C76212C58C464A

It may be worth perusing the YouTube API, but parsing the page with the playlist on it might save you some time.

JavaScript, 532 536 538 582 bytes

Thanks to @ӍѲꝆΛҐӍΛПҒЦꝆ and @Quill for a whole bunch of bytes.

I did do a couple of things here which may not be 100% to the spec - If they aren't admissible please tell me and I'll fix them:

I shortened the YouTube URL
The shuffle is VERY weak, and is not considered in any way close to
random.
There's a bit of whitespace due to the join.

I'd like to start by saying, to any JavaScript developers out there: I'm so sorry.

New version alternates captures to reduce on regex byte cost and strips some URL length, but sacrifices on alerts. Now instead of 3, you get like 20. Unfortunately the https on the URL's seem to be required or the page won't load, though that may be my setup :/.

This could possibly be improved with proper XML parsing and loops instead of weird recursion things with calls to other functions. I had fun taking advantage of the fact that XMLHttpRequest causes synchronous execution.

d="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLF5C76212C58C464A&key={REALLY SUPER LONG GOOGLE API KEY HERE}",h=[];o=l=>{x=new XMLHttpRequest,x.open("GET",l,!1),x.send(0),j=x.responseText;y=`nextPageToken": "`;e(j)
j.includes(y)&&(q=j.split(y)[1].split('"')[0],o(d+"&pageToken="+q));h.sort(b=>.5-Math.random());alert(h.join `
`)}
e=v=>{for(r=/(title": "(.*)\[)|(oId": "(.*)")/g;null!==(m=r.exec(v));)a=m[2]+": https://youtu.be/"+r.exec(v)[4],z="] - ",a.includes(z)&&(a=a.split(z)[1]),h.push(a)}
o(d)

Replace the {REALLY SUPER LONG GOOGLE API KEY HERE} with your 39 character long YouTube API key.

Ungolfed:

//Define base URL, sacrificing speed and pages for bytes
d = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLF5C76212C58C464A&key={REALLY SUPER LONG GOOGLE API KEY HERE}";
h = [];
o = l => {
    //Grab API data
    x = new XMLHttpRequest();
    x.open("GET", l, false);
    x.send(0);
    j = x.responseText;
    //Set up a split since we use it twice
    y = `nextPageToken": "`;
    //At this point, jump off to the other function to deal with the output
    e(j);
    //If there are multiple pages of results, as we only get a couple from each API call to save bytes with URL's
    if (j.includes(y)) {
        //Get the ID for the next page
        q = j.split(y)[1].split("\"")[0];
        //Call again with an added parameter
        o(d + "&pageToken=" + q)
    }
    //Taking advantage of XMLHttpRequest forcing this as synchronous, so all the above happens first
    //Bad shuffle
    h.sort(b => .5 - Math.random())
    alert(h.join `
        `);
}
e = v => {
    //Regex for titles/ID's - Grabbitz doesn't fit the "[Genre] - Song - Artist" mould so we need a slightly longer regex
    r = /(title": "(.*)\[)|(oId": "(.*)")/g;
    //Since we know there's one title to one video, we can run them both at the same time
    while ((m = r.exec(v)) !== null) {
        //Build the string
        a = m[2] + ": https://youtu.be/" + r.exec(v)[4];
        z = "] - ";
        //That Grabbitz edge case ruining my day again, I'm glad it's a good track...
        if (a.includes(z)) {
            a = a.split(z)[1];
        }
        h.push(a);
    }
}
o(d)


Implement Shamir's Secret Sharing reconstruction Shamir's secret sharing scheme is a simple way of protecting a secret by splitting it into several parts needed to reconstruct it.

Your task is to implement Shamir's Secret Sharing reconstruction over the Finite Field defined by the prime 1928049029. If you have any doubts about what this means, just ask or see Finite Field & Finite Field Arithmetic in wikipedia (more resources below).

Input

Input is done using stdin. First comes an integer k, then k lines follow. Each of these lines contains a pair of integers x y that represent a secret. In other words f(x) = y in the original polynomial that was used to construct the secrets.

The number of secrets given is always enough to construct the corresponding secret.

Output

Output to stdout the reconstructed secret.

Examples

Input:

5
1 564797566
2 804114535
4 1354242660
6 1818201132
7 503769263

Output:

1234

Input:

7
1 819016192
2 1888749673
3 1737609270
4 365594983
5 1628804870
6 1671140873
7 492602992

Output:

456457856

Resources

Wikipedia article

Paper

Finite field Source: Wikipedia

Finite field arithmetic Source: Wikipedia

Lagrange polynomial Source: Wikipedia

Chapter on Finite field arithmetic

bash, 271 chars

r(){
[ ${1/0/} ]&&{ r $(($2%$1)) $1;((t=u,u=v-$2/$1*u,v=t));}
}
read
((N=1928049029,n=0))
while read x[$n] y[$n]
do((n++))
done
for((i=n;z=(z+l)%N,i--;))do
for((j=n,l=y[i];j--;))do
((u=0,v=1,d=x[j]-x[i],M=N+d))
r M N
[ ${d/0/} ]&&((l=l*x[j]%N*(u+N)%N))
done
done
echo $z

The newlines could be replaced in most cases with semicolons, but I don't think there's any unnecessary whitespace.

(I hadn't realised before today that bash's integers are 64-bit - very helpful).

For bash the recursive GCD (exploiting global state) seems to be more compactible than the iterative one. This is mostly straightforward; the interesting trick is [ ${d/0/} ]&&foo which is effectively if [ $d -ne 0 ];then foo;fi


Making Squared Words The Challenge

Your task is to create a program that takes any given string input, and outputs the input in a squared format. Empty strings should return an empty string.

Examples

Given the input:

golf

Your program should output:

golf
o  l
l  o
flog

Input:

123

Output:

123
2 2
321

Input:

a

Output:

a

Input:

Hello, world!

Output (notice the space between the , and w - the gap is not just a newline):

Hello, world!
e           d
l           l
l           r
o           o
,           w

w           ,
o           o
r           l
l           l
d           e
!dlrow ,olleH

Scoring

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

Charcoal, 7 5 bytes

θ‖Ｏ↙↘

Try it online! Link is to verbose version of code. Edit: Saved 2 bytes thanks to @CarlosAlejo. Explanation:

θ       Print the input string, making the top row
 ‖Ｏ     Reflect with overlap...
   ↙    ... down and left, to create the left side
    ↘   ... down and right, to create the bottom and right sides

(Multiple directions to the Reflect command run consecutively rather than simultaneously.)


Do I have a prime twin? An Integer is prime if and only if it is positive and has exactly 2 distinct divisors: 1 and itself. A twin prime pair is made of two elements: p and p±2, that are both prime.
You will be given a positive integer as input. Your task is to return a truthy / falsy depending on whether the given integer belongs to a twin pair, following the standard decision-problem rules (the values need to be consistent).
Test Cases

Truthy (Twin Primes): 3, 5, 7, 11, 13, 17, 19, 29, 31, 41, 43

Falsy (not Twin Primes): 2, 15, 20, 23, 37, 47, 97, 120, 566

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

Brachylog, 9 8 bytes
ṗ∧4√;?+ṗ

Try it online!
Explanation
ṗ           Input is prime
 ∧          And
  4√        A number whose square is 4 (i.e. -2 or 2)
    ;?+     That number + the Input…
       ṗ    …is prime


Chinese Checkers longest move In Chinese Checkers, a piece can move by hopping over any other piece, or by making a sequence of such hops. Your task is to find the longest possible sequence of hops.
Input
A sequence of 121 zeroes or ones, each representing a place on a board. A zero means the place is empty; a one means the place is occupied. Positions are listed from left to right; top to bottom. For example, the input of this setup would be
1011110011000001000000000000000000000000100000000001000000000000000000000000000001000000000000000000000001000001100111111

Explanation:

The top-most place is occupied by a green piece, so the first digit in the input is 1. The second row has one empty position and then one occupied position, so 01 comes next. The third row is all occupied, so 111. The fourth row has two empty and two occupied spaces (going left to right), so 0011. Then comes five 0's, a 1, and seven 0's for the next row, and so on.

Like in that setup, there is a corner pointing straight up. There may be any number of pieces on the board (from 1 to 121). Note that pieces of different colors are not represented differently.
Output
The maximum length of a legal hop, using any piece on the board. You may not visit the same place more than once (including the starting and ending positions). However, you may hop over the same piece more than once. If there is no legal hop, output 0. Do not consider whether there exists a legal non-hop move.
For example, the output to the setup described above is 3.
Input and output may be done through stdin and stdout, through command-line arguments, through function calls, or any similar method.
Test Cases
Input:
0100000010000000000000000100000000000000000000000000000001010010000000000000000000000101000000000000000000100000000100001

Output: 0 (no two pieces are next to each other)

Input:
0000000000111100000000011100000000011000000000100000000000000000000000000000000000000000000000000000000000000000000000000

Output: 1 (initial setup for one player in top-left corner)

C,262 260
Golfed code (debugging code and unnecessary whitespace removed. Changed from input via stdin to input via command line, and took advantage of the opportunity to declare variable i there. Latest edit: code moved into brackets of for loops to save two semicolons.)
t[420],j,l,x,y;f(p,d){int z,q,k;for(k=6;k--;t[q]&!t[p+z]?t[q]=0,f(q,d+1),t[q]=1:0)z="AST?-,"[k]-64,q=p+z*2;l=d>l?d:l;}main(int i,char**s){for(i=840;i--;x>3&y>5&x+y<23|x<13&y<15&x+y>13?i>420?t[i-420]=49-s[1][j++]:t[i]||f(i,0):0)x=i%20,y=i/20%21;printf("%d",l);}

Explanation
This relies on a 20x21 board which looks like this, initially filled with zeroes when the program starts (this ASCII art was generated by a modified version of the program, and as the i loop counts downwards, zero is in the bottom right corner):
....................
....................
...............#....
..............##....
.............###....
............####....
.......#############
.......############.
.......###########..
.......##########...
.......#########....
......##########....
.....###########....
....############....
...#############....
.......####.........
.......###..........
.......##...........
.......#............
....................
....................

Loop i runs through this board twice, using x and y to calculate whether a square actually belongs to the checkerboard or not (this requires 6 separate inequalities in x and y.)
If it does, the first time round it fills the squares, putting a 0 (falsy) for a 1 (occupied) and a 1 (truthy) for a 0 (unoccupied). This inversion is important, because all out-of-bounds squares already contain a 0, which means they resemble occupied squares and it is clear they can't be jumped into, without the need for a specific check.
The second time round, if the square is occupied (contains 0) it calls the function f that searches for the moves.
f searches recursively in the 6 possible directions encoded by +/-1 (horizontal), +/-20 (vertical) and +/-19 (diagonal) encoded in the expression "AST?-,"[k]-64. When it finds a hit, it sets that cell to a 0 (occupied) before calling itself recursively, then sets it back to 1 (empty) when the function is returned. The cell value must be changed before the recursive call to prevent hopping into that cell more than once.
Ungolfed code
char s[999];                           //input string.
t[420],i,j,l,x,y;                      //t=board. i=board counter, j=input counter. l=length of longest hop found so far.

f(p,d){                                //p=position, d= recursion depth.
  //printf("%d,%d ",p,d);              //debug code: uncomment to show the nodes visited.
  int k,z,q;                           //k=counter,z=displacement,q=destination
  for(k=6;k--;)                        //for each direction
    z="AST?-,"[k]-64,                  //z=direction
    q=p+z*2,                           //q=destination cell
    t[q]&!t[p+z]?                      //if destination cell is empty (and not out of bounds) and intervening cell is full
      t[q]=0,f(q,d+1),t[q]=1           //mark destination cell as full, recurse, then mark it as empty again.
      :0;
  l=d>l?d:l;                           //if d exceeds the max recorded recursion depth, update l
}

main(){
  gets(s);                             //get input
  for(i=840;i--;)                      //cycle twice through t
    x=i%20,                            //get x
    y=i/20%21,                         //and y coordinates
    x>3&y>5&x+y<23|x<13&y<15&x+y>13?   //if they are in the bounds of the board
      i>420?
        t[i-420]=49-s[j++]             //first time through the array put 0 for a 1 and a 1 for a 0 ('1'=ASCII49)
        :t[i]||f(i,0)                  //second time, if t[i]=0,call f().
       //,puts("")                     //puts() formats debug output to 1 line per in-bounds cell of the board
      :0;
  printf("%d",l);                      //print output
}


Is this a valid variable name? Objective
Write a program or function that checks if a variable name is valid and output 1 or True if it is valid, 0.5 if it is valid but starts with an underscore (_), and 0 or False if it is not valid.
Rules

A variable name in most languages is valid if it begins with an underscore or letter (a-z, A-Z, _) and the rest of the characters are either underscores, letters, or numbers. (a-z, A-Z, 0-9, _)
Output 1 or True if the variable name is valid and 0 or False if not valid.
However, it is not good practice to start a variable with an underscore, so return 0.5 if it starts with an underscore and the name is valid.

Test Cases
Input
abcdefghijklmnop
Output
1
Input
_test_
Output
0.5 (starts with an underscore)
Input
123abc
Output
0 (starts with a number)
Input
A_b1C_23
Output
1
Input
_!
Output
0 (not 0.5 because it's not valid)
Input
magical pony1
Output
0 (no spaces)
Standard loopholes apply.
This is code-golf, so shortest code wins.
Bonus: -10% if your program/function outputs 0 for an empty string("").

JavaScript (ES6), 37 - 10% = 33.3 bytes

Saved 4 bytes thanks to @edc65

Saved 5.6 bytes thanks to @Mateon

s=>!/^\d|\W|^$/.test(s)/-~(s[0]=='_')


Create the least compressible picture "A picture is worth a thousand words"—so the old saying goes. The average word is about four characters long, so a picture conveys 4kB of information. But how much entropy, rather than information, can a picture convey?

Your task is to generate an image, exactly 4,000 bytes in size, with the highest entropy possible. You may use any language, libraries, or image format you choose, and you may output to the console or to a file so long as you upload your image here.

Scoring

Your score is the compression ratio (4000 ÷ compressed size) when your image is compressed with GNU tar version 1.28 and gzip version 1.6, using the DEFLATE algorithm and default settings — specifically, the command tar -czvf out.tar.gz image. The smallest compression ratio wins.

0.9514747859 (4204-byte output)

Note: the image above is not the actual file I used, but it is the image.

Here is a hexdump of the file: https://gist.github.com/pommicket/cf2982e8ecf09a4de89d3a849526c64b

The file is in the netpbm format, and can be generated with this C code:

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

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "Please pass in seed.\n");
        return EXIT_FAILURE;
    }
    srand(atoi(argv[1]));
    FILE *fp = fopen("image.pgm", "w");
    int width = 2, height = 1993;
    fprintf(fp, "P5 %d %d 255 ", width, height);
    for (int i = 0; i < width * height; i++) {
        fputc(rand() & 0xFF, fp);
    }
    fclose(fp);
    return 0;
}

The random seed must be passed into the program. After trying some seeds, I got one which produced a 4204 byte gzipped file. As Nnnes pointed out, tar will include metadata in the file, so your results might differ from mine.

netpbm isn't supported everywhere, but it works with imagemagick's convert (so just do convert image.pgm image.png to turn it into a png).

Why this image/format?

A file which consists of entirely random bytes is very hard to compress (in fact, any possible compression algorithm will do on average, no better than not compressing for random files). The content of the actual file is just P5 2 1993 followed by 3986 random bytes, which is why gzip has such a hard time compressing it.


The Double-Castle Numbers™ Introduction

A double-castle number™ is a positive integer number that has a pattern of $$\underbrace{a\cdots a}_{m\text{ }a\text{s}}b\underbrace{a\cdots a}_{m\text{ }a\text{s}}b\underbrace{a\cdots a}_{m\text{ }a\text{s}}\underbrace{a\cdots a}_{n\text{ }a\text{s}}b\underbrace{a\cdots a}_{n\text{ }a\text{s}}b\underbrace{a\cdots a}_{n\text{ }a\text{s}}$$
Where \$m>0\$, \$n>0\$ and \$a-b=1\$ are all non-negative integers, when represented in an integer base \$B\$ where \$B\ge2\$. It is so named because a bar chart representing the base-\$B\$ digits of such a number resembles two castles of the same height place- side by side.

For example, \$7029\$* is a double-castle number because when represented in base 2 it becomes \$1101101110101_2\$, which can be split into \$11011011\$ and \$10101\$.

This is the case when \$m=2\$, \$n=1\$, \$a=1\$, \$b=0\$ and \$B=2\$.

\$305421994212\$ is also a double-castle number because when represented in base 8 it becomes \$4343444344344_8\$, which can be split into \$43434\$ and \$44344344\$.

This is the case when \$m=1\$, \$n=2\$, \$a=4\$, \$b=3\$ and \$B=8\$.

For \$a>=10\$, \$a\$ should be treated as a single base-\$B\$ "digit" with the value of \$a\$ in base-10. \$206247763570426655730674346\$ is a double-castle number in base-16, whose representation in base-16 is \$\text{AA9AA9AAAAAA9AAAA9AAAA}_{16}\$. Here, \$a=10\$ but is treated as a single digit \$(10)_{16}=\text{A}_{16}\$.

This is the case when \$m=2\$, \$n=4\$, \$a=10\$, \$b=9\$ and \$B=16\$.

Challenge

Write a program or function that, given integers \$m>0\$, \$n>0\$, \$1\le a<B\$ and \$B\ge2\$, calculate the corresponding double-castle number™ and output it in base-10.

Test Cases

The input below are in base-10, but in the case say when \$a=11\$ and \$B=12\$ the input should be understood as \$B_{12}\$.

m, n, a,  B  => Output
1, 1, 1,  2  => 693
2, 1, 1,  2  => 7029
1, 2, 3,  4  => 62651375
1, 2, 4,  8  => 305421994212
1, 4, 7,  10 => 7676777776777767777
2, 4, 8,  16 => 164983095594247313234036872
2, 4, 10, 16 => 206247763570426655730674346

Winning Condition

This is a code-golf challenge, the shortest submission in each language wins. No standard loopholes allowed.

*7029 comes from my ID minus it written reversed.

Python 2, 83 81 79 72 bytes

-9 bytes thanks to @ovs!
-2 bytes thanks to @dingledooper!

m,n,a,B=input()
r=0
for s in n,m+n,m,m:r+=B**n;n-=~s
print~-B**n/~-B*a-r

Try it online!

Calculate aaaa...aaa in base B, then subtract 1 at the appropriate digits.


Lottery Ball Problem A woman works at a lottery ball factory.  She's instructed to open up a lottery ball creation kit composed of 1 red rubber ball and n strips of digits from 0 through 9.

She's instructed to do the following:

Starting with 1, write the current number on the ball using the digits available on the n strips.
Put unused digits into a bowl where they can be used later for when she runs out of available digits in step 1.
Open up another lottery ball creation kit and continue to step 1 for the next number.

The question is, at what number will she arrive at before she runs out of digits to write the number?  Edited: Given n where n is the number of digit strips from 0 through 9 provided in each lottery ball creation kit, write a program that can solve this (not trivially) in the least amount of time.

Edit:  Additional notes - 6 and 9 are different numbers.  Assume there are no limits to the number of digits that can be pasted on the ball.

Hint:  If she counted in base 2 rather than base 10, how would that change the result and would that be easier to calculate?  What could you derive from solutions in base 2?


A Euro-iginal Sequence Given a positive integer n output the n-th number of the euro-iginal sequence.

Calculating the Sequence

This sequence is equal to OEIS A242491.

A number is part of said sequence if the number can be made up by using as many different euro coins or notes, but only one of each. Note that you don't have to consider cents.

Example:

6 would be in the sequence, as it can consist of a 1-euro coin and a 5-euro-note.

4 would NOT be in the sequence, as it can't be formed with the given requirements.

To give everyone an overview, heres a list with euro values you have to consider:

  1€, 2€, 5€, 10€, 20€, 50€, 100€, 200€, 500€

Note that this sequence only ranges from 0 (yes, 0 is included!) to 888.

Here are the first 15 elements of this sequence:

0, 1, 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 15, 16, 17, ...

Test Cases

Input -> Output

2 -> 1
6 -> 6
21 -> 25
33 -> 50

Jelly, 7 bytes

b8d4ḅ5Ḍ

Try it online!

How it works

b8d4ḅ5Ḍ  Main link. Argument: n (integer)

b8       Convert n from integer to base 8.
  d4     Divmod each base-8 digit by 4, mapping the digit d to [d / 4, d % 4].
    ḅ5   Convert the quotient-remainder pairs from base 5 to integer, mapping
         [d / 4, d % 4] to (d / 4 * 5 + d % 4).
         The last two steps establish the following mapping for octal digits.
             0 -> [0, 0] -> 0
             1 -> [0, 1] -> 1
             2 -> [0, 2] -> 2
             3 -> [0, 3] -> 3
             4 -> [1, 0] -> 5
             5 -> [1, 1] -> 6
             6 -> [1, 2] -> 7
             7 -> [1, 3] -> 8
      Ḍ  Convert the resulting array of digits from decimal to integer.


Write the shortest program that generates the most compiler warnings and errors The challenge:

Write a very short program that, when compiled, creates the most amount of compiler warnings and errors. It can be written in any programming language.

Scoring:

The score is determined by this equation: errors_and_warnings_length/code_length. Highest score wins.

Example:

The C# program class is 5 chars long and generates 3 warnings, which is a score of (1/5)*3 = 0.6.

EDIT:

Because of some confusion, programs have to be at least 1 char long. Otherwise it would get a score of infinity.

GCC, score 2200 / 36 ≈ 4.5 × 1058

#include __FILE__
#include __FILE__

I have not actually finished compiling this code, but based on testing and simple mathematics, it should produce a total of 2200 #include nested too deeply errors.

Of course, the program is trivially extensible.  Adding a third line brings the score up to 3200 / 54 ≈ 4.9 × 1093.  Four lines give 4200 / 72 ≈ 3.6 × 10118, and so on.


Turtle Graphics Program Most of you have probably heard of the famous Turtle Graphics program, initially made popular by Logo.  This challenge is to implement a Turtle Graphics program in your language of choice.

Rules:

Rule one is that when the pen is in the down state, it must draw in both the square the turtle leaves and the square the turtle enters.  This is what would happen in real life, so that is what your program should do.
Rule two is the turtle must include these 10 commands, which can be represented in the input as you like:

  RESET - resets board to blank - turtle position is default.

  UP and DOWN - these two commands set the pen/eraser state.

  RIGHT and LEFT - these two commands turn the turtle in the specified direction.

  FORWARD - advances turtle to next square.

  DRAW and ERASE - these commands set the turtle to drawing and erasing, respectively.

  DISPLAY - displays board.

  POSITION - prints turtle's x/y coordinate on the board.

  STOP, which stops drawing, displays the board, and terminates the program after the user enters any input.

The floor must be 20x20.  You can use vectors, arrays, or anything you like to represent it.
You must stop the turtle and display an error message if the turtle hits the wall.
Default turtle position is 0,0 facing right.

Scoring:

This program will use standard atomic-code-golf scoring rules with a few modifications to try to allow industry programming languages, such as Java and C++, to compete.

Imports, includes, usings and other similar statements do not score anything.
Loop header statements each only score one point.  All other statements add the full number of characters in the statement to the score.

Example:

These statements do not score:

#include <iostream>
import java.util.Scanner;

def inputCommand():
string inputCommand(){}

These statements score only one point:

for(int i = 0; i < 9; i++){}
for i in range(0,10):
while(true){}
while x in y:

These statements score the full number of their characters:

string n;
i = 9;

switch(d) {
  case i:
    break;
  default:
    break;
}

return x;

cout<<'example';
cin>>s;
System.out.println()
print('example')

If you have any questions or comments, please let me know in the comments.

JavaScript, one point

for (s='                    ',
    reset=function(){a=s.split(/./).map(function(){return s.split(/(?=.)/)}); x=0; y=0; dx=1; dy=0; pen='#'; down=1;},
    display=function(){console.log(a.map(function(x){return x.join('')}).join('\n'))},
    position=function(){console.log(x, y)},
    draw=function(){a[y][x]=down?pen:a[y][x]},
    forward=function(){draw(); x+=dx; y+=dy; (y<0||y>19||x<0||x>19) && (console.log('Hit wall')||(dx?(x-=dx):(y-=dy))); draw();},
    turn=function(d){nx=-1*(!dx)*d*dy; dy=(!dy)*d*dx; dx=nx;},
    reset();
    ((p=prompt()) != 'STOP') || display();
    (p == "RESET") && reset(),
    (p == "DISPLAY") && display(),
    (p == "POSITION") && position(),
    (p == "DRAW") && (pen='#'),
    (p == "ERASE") && (pen=' '),
    (p == "UP") && (down=0),
    (p == "DOWN") && (down=1),
    (p == "RIGHT") && turn(1),
    (p == "LEFT") && turn(-1),
    (p == "FORWARD") && forward()
);

Sorry, I couldn't resist.


Hack g-code.js parser Here you can see g-code parser, written in JavaScript to use in microcontroller (like espruino). But you can run it in browser, because it don't use any specific features.

function gcode(str){
  //Removes comment, parses command name and args
  const [,f,args] = (str.match(/^([GM]\d+) ([^;]+)/) || [,"",""]);
  //A1.2 B43 C -> {A: 1.2, B: 42, C: 0}
  eval(f+"({"+args.replace(/(\w)([\d\.]*)/g,"$1: $2+0,")+"})");
}
const G1 = console.log;
gcode(prompt("crackme"));

When you pass G1 X3 Y4.53 Z42 to gcode(), it runs G1({X: 3, Y: 4.53, Z: 42}). As you can see, it uses eval, protected by regexp. But despite of this, you can attack this function and cause remote code execution. Your goal is to run alert("pwned"). This is code golf, so shortest working input wins

112 bytes

G1 $:(ƒ=(Τ,$=+[])=>Τ[$]?Τ[$]+ƒ(Τ,++$+'5'[+[]]*(Τ[$]==':')):'')[ƒ('constructor')](ƒ('alert("pwned")'))()

function gcode(str){
  //Removes comment, parses command name and args
  const [,f,args] = (str.match(/^([GM]\d+) ([^;]+)/) || [,"",""]);
  //A1.2 B43 C -> {A: 1.2, B: 42, C: 0}
  eval(f+"({"+args.replace(/(\w)([\d\.]*)/g,"$1: $2+0,")+"})");
}
const G1 = console.log;

payload = `G1 $:(ƒ=(Τ,$=+[])=>Τ[$]?Τ[$]+ƒ(Τ,++$+'5'[+[]]*(Τ[$]==':')):'')[ƒ('constructor')](ƒ('alert("pwned")'))()`;
gcode(payload);

Each ƒ (U+0192), Τ (U+03A4) cost 2 bytes, they are not as same as ASCII f, T.

The gcode function will keep any /\W/ characters as is. So, we just need to use these characters to write some logic here. The idea is basically based on how JSF**k works. We construct the codes like this:

(()=>{})["constructor"]('alert("pwned")')

We need string literal "constructor" and alert("pwned"). But gcode convert "constructor" to "c: +0,o: +0,n: +0,....r: +0". So we need to convert the string back. We use this function to do the convert:

ƒ=(Τ,$=+[])=>Τ[$]?Τ[$]+ƒ(Τ,++$+'5'[+[]]*(Τ[$]==':')):''

Τ is the text inputed, $ is index. We first initialize $ to 0 using +[]. Then we output the character at the index position, and check if next character is ":", if so we skip the following 5 characters.

Thanks to l4m2, saves few bytes.


Implement the named labels for assembly Let's assume we've got an imaginary assembler. The assembler supports numerical labels. An infinite loop example:

:1
    jmp 1

Your task is, to write a preprocessor for this assembler supporting named labels (instead of numerical ones; with up to 8 characters in length), so the label name is replaced to it's numerical value.

The assembler uses a dot (.) to express a character constant, for example:

mov dl, .A

Will store ASCII(65) - 'A', in the register dl. The assembler supports string constants in double quotes too:

:20
db "Hello, world!"

So, to sum things up, you need to be aware of character constants, and the fact that you can't perform any substitution inside quote-enclosed strings.

The label declaration character and reference character is up to your choice, but for the sake of completness I will use a $ to refer to a label, and @ to denote a label.

The label' number might be any natural number not equal to zero.

You may assume that assembly on the input is perfectly valid.

Let's look at a few examples:

@loop
    jmp $loop

:1
    jmp 1

jmp $skip
mov dl, .@
@skip
cmp dl, .$

jmp 1
mov dl, .@
:1
cmp dl, .$

@x
db "$a @b"
@a
    jmp $a
    @b
        jmp $b

:1
db "$a @b"
:2
    jmp 2
    :3
        jmp 3

This is a code golf, so the smallest answer wins. Standard rules and loopholes apply.

You can safetly assume that the user won't use numerical labels anymore, and the labels contain just A-Za-z letters.

Label declaration and reference character has to be different.

JavaScript (ES6), 96 bytes
Uses @label for a declaration and %label for a reference.

s=>s.replace(o=/^\s*@(.+)/gm,(_,s)=>':'+(o[s]=++n),n=0).replace(/".*?"|%(\w+)/g,(s,x)=>x?o[x]:s)

Try it online!
Commented
(alternate slash characters are used below to prevent the SE syntax highligter from going mad)
s =>                  // s = input string
  s.replace(          // 1st pass:
    o =               //   assign the regex object to o; we'll use it to store the labels
    ∕^\s*@(.+)∕gm,    //   look for [start] + [optional whitespace] + '@' + [label]
    (_, s) =>         //   replace with:
      ':' +           //     ':' + label ID
      (o[s] = ++n),   //     increment n and store the label in o
    n = 0             //   start with n = 0
  )                   // end of replace()
  .replace(           // 2nd pass:
    ∕".*?"|%(\w+)∕g,  //   look for either ".*?" (non-greedily) or %label
    (s, x) =>         //   replace with:
      x ? o[x]        //     o[label] if x is defined,
        : s           //     or the original string otherwise
  )                   // end of replace()


Enumerate all palindromic numbers (in decimal) between 0 and n Given a non-negative integer n, enumerate all palindromic numbers (in decimal) between 0 and n (inclusive range). A palindromic number remains the same when its digits are reversed.

The first palindromic numbers (in base 10) are given here:

  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101,
  111, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212, 222, 232, 242,
  252, 262, 272, 282, 292, 303, 313, 323, 333, 343, 353, 363, 373, 383,
  393, 404, 414, 424, 434, 444, 454, 464, 474, 484, 494, 505, 515, ...

This is a code golf with the prize going to fewest characters. The palindromic numbers should be output one per line to stdout. The program should read n from the commandline or stdin.

Perl 5.10, 29 (or 39) characters

say for grep$_==reverse,0..<>

Needs the say feature enabled. 29 chars if you consider that to be free,  otherwise 39 to add use 5.010;. Argument on STDIN.

Perl, 35 characters

#!perl -l
print for grep $_==reverse,0..<>

using the old perlgolf convention that #!perl is not counted but any flags following it are.

Perl, 36 characters

print$_,$/for grep $_==reverse,0..<>

If none of the others qualify.


Scramble words while preserving their outlines This is much more advanced than How to randomize letters in a word and Cambridge Transposition because of the rule about which letters may be swapped with which. A simple regex will not suffice here.

It is well known that a text can still be read while the innards of its words have been scrambled, as long as their first and last letters plus their overall outlines remain constant. Given a printable Ascii+Newline text, scramble each word according to these rules:

Scrambling must be (pseudo) random.
A word is a sequence of the Latin characters, A through Z.
Only initial letters will ever be uppercase.
The first and last letters must stay untouched.
When scrambling, only letters within one of the following groups may exchange places:

acemnorsuvwxz
bdfhkl
gpqy
it
j (stays in place)

Example

  Srcmable wrods while psrrnveieg their oeiltnus

  It is well known that a txet can still be read while the inrands of its wrods have been srcambled, as long as their fisrt and last letters plus their ovaerll ontliues raemin canstnot. Given a patnirlbe Acsii+Nwnliee txet, samrclbe ecah word anoccdirg to these relus:

  Smncrbliag must be (pusedo) rondam.
  A wrod is a seqencue of the Latin chreratacs, A thurogh Z.
  Only iniital lrttees will eevr be uppcsaere.
  The fisrt and lsat lettres must stay uctoenhud.
  When sarnclbimg, only letters wihtin one of the fwllnoiog guorps may ecxhange plaecs:

  aneusvrowxmcz
  bhkfdl
  gqpy
  it
  j (stays in plcae)

  Emxaple

Jelly, 80 74 bytes

-2 bytes by moving from czar + vex + mow + sun to czar + vexes + unmown (the repeated es and ns are not a problem)
-1 byte using Tị rather than ȦÐf
-1 byte using Œle€Øa rather than i@€ØB>⁵
-2 bytes by reconfiguring the layout a little

Tị
TẊị⁹ż@œp
e€ç⁸F
W;“HọƊṘ€.`]HɲøƁḤ0ẉlfrøj⁷»Ḳ¤ç/
Ḣ,ṪjÇḟ0
Œle€Øað¬œpÇ€ÑżœpÑ¥

A full program taking a character list (or Python formatted string), which prints the result of the scrambling.

Try it online!

A huge amount of difficulty for Jelly here it seems (either that or I have missed a trick, which has been known to happen!) This will surely be beaten by languages with better string manipulation like Retina(no random functionality) or 05ab1e.

How?

Tị - Link 1, get truthy items: list a
T  - truthy indexes of a
 ị - index into a

TẊị⁹ż@œp - Link 2, selective shuffle: list a, list b
T        - truthy indexes of a (those indexes that may be shuffled in b)
 Ẋ       - random shuffle
   ⁹     - link's right argument, b
  ị      - index into (gets the shuffled values)
      œp - partition b at truthy indexes of a
    ż@   - zip with reversed @rguments (place shuffled values - yields a list of lists)

e€ç⁸F - Link 3, value selective shuffle: list a, list b
e€    - c exists in b? for €ach c in a (1s where b has shuffle-able characters, else 0s)
   ⁸  - link's left argument, a
  ç   - call the last link (2) as a dyad
    F - flatten the result (from the yielded list of lists to one list)

W;“HọƊṘ€.`]HɲøƁḤ0ẉlfrøj⁷»Ḳ¤ç/ - Link 4, perform all shuffles on a word's innards: list x
W                             - wrap x in a list
                          ¤   - nilad followed by link(s) as a nilad:
  “HọƊṘ€.`]HɲøƁḤ0ẉlfrøj⁷»     -   compression of s(bdfhkl)+d( czar)+d(vexes)+d(unmown)+s( gpqy)+d( ti)
                              -     where d() looks up a word in Jelly's dictionary and s() adds a string to the compressed output.
                         Ḳ    -   split on spaces: ["bdfhkl","czarvexesunmown","gpqy","ti"]
                           ç/ - reduce by last link (3) as a dyad (shuffles by each in turn)

Ḣ,ṪjÇḟ0 - Link 5, shuffle a word: list w
Ḣ       - head w (yields the leftmost character and modifies w)
  Ṫ     - tail w (yields the rightmost character and modifies w)
 ,      - pair
        -   Note: head and tail yield 0 when w is empty, so ['a'] -> ["a",0] and [] -> [0,0]
    Ç   - call the last link (4) as a monad (with the modified w)
   j    - join
     ḟ0 - filter discard zeros (thus single or zero letter words pass through unchanged)

Œle€Øað¬œpÇ€ÑżœpÑ¥ - Main link: list s
Œl                 - convert s to lowercase, say t
    Øa             - lowercase alphabet, say a
  e€               - c exists in a? for €ach c in t
      ð            - dyadic chain separation (call that u)
       ¬           - not (vectorises across u), say v
        œp         - partition s at truthy indexes of v (extract words, plus empty lists from within strings of non-alphabetic characters)
          Ç€       - call the last link (5) as a monad for €ach (shuffle their innards)
            Ñ      - call the next link (1) as a monad (only keep the actual words)
                 ¥ - last two links as a dyad:
              œp   -   partition s at truthy indexes of u (get the non-words, plus empty lists from within strings of alphabetic characters)
                Ñ  -   call the next link (1) as a monad (only keep actual non-words)
             ż     - zip together
                   - implicit print


Repeating terms of a given sentence Program
Write a program to display repeating terms of a given sentence.
Explanation
The program must output the repeating terms of two or more letters from the given input (input is a sentence separated by spaces without any punctuation except the full-stop indicating the end.)  Repeated terms may not span across or include a space. For example, if input is the sentence "I am an ameture mathemagician" the output must be am, ma, an. (note that "em" is not a valid output as it is separated by space).
Repeated terms may overlap with each other. For example if the input is "ababa", the output should include "aba", even though the two instances of it overlap.
ababa
aba
  aba

Example
Input:

International competitions are better than intercollege ones.

Output:

Inter, ti, er, tion, io, on, ion, tio, co, on, .......etc
(t, l must not be included as they are 1 letter.) (Upper lower Cases do not matter)

Test cases
aabcde cdec -> cde, cd, de

aab aacab -> aa, ab

aaa aabcaaa ababa -> aaa, aa, ab, aba, ba

abababa-> ab, aba, abab, ababa, ba, bab, baba

Winning Criterion
code-golf

JavaScript (ES10), 99 bytes

s=>new Set([...s].map((q,i,a,j=i)=>a.map(_=>s.lastIndexOf(q+=s[++i])>j&!/ /.test(q)?q:[])).flat(2))

Try it online!


Distinct Reversible Primitive Binary Necklaces Introduction - What is a necklace?

A necklace is something that OEIS people are obsessed with. The OEIS challenge has like 5 necklace sequences.

A binary necklace of length n is a loop with n beads that are either 0 or 1. Two necklaces are the same if one can be rotated to become the other, and two reversible necklaces are the same if one can be rotated, reversed, or reversed and rotated to become the other.

A primitive necklace is one that cannot be expressed as more than one copy of a string of beads chained together. Note that the copies must be assembled all in the same order (no reversing) for a necklace to be considered non-primitive.

For example, let's take a look at this necklace: 0 1 1 0 1 1. It is not primitive because it can be expressed as 0 1 1 repeated twice. 0 1 0 1 1 is primitive.

0 1 1 0 is primitive because 0 1 and 1 0 are not considered the same string. This necklace is equivalent to 1 1 0 0 because it can be rotated left one bead to become this one, but not equivalent to 0 1 0 1 (which isn't primitive by the way).

Challenge

Given an non-negative integer n, return the number of distinct reversible primitive binary necklaces of length n. Input and output as a single integer each.

The first few terms of this sequence are 1, 2, 1, 2, 3, 6, 8, 16, 24, 42, 69, 124, 208, 378, 668, 1214, 2220, 4110, 0-indexed.

This is OEIS A001371

Reference Implementation in Python 3 - quite slow

Python 2, 178 171 139 137 bytes

lambda n:sum(1-any(i>int(b[j::-1]+b[:j:-1],2)or j*(i>=int(b[j:]+b[:j],2))for j in range(n))for i in range(2**n)for b in[bin(i+2**n)[3:]])

Try it online! Edit: Saved 7 21 bytes thanks to @HalvardHummel.


Is this string a square? A string is considered to be square if the following conditions are met:

Each line has the same number of characters
The number of characters on each line is equal to the number of lines.

Your task is to write a program or function which determines whether or not a given input string is a square.

You may require input to be delimited by your choice of LF, CR, or CRLF.

The newline character(s) are not considered part of the line's length.

You may require there to be or to not be a trailing newline in input, which doesn't count as an additional line.

Input is a string or 1D char array; it is not a list of strings.

You may assume input is non-empty and only contains printable ASCII, including spaces.

You must output a truthy value for square strings and a falsy one for other strings.

Truthy test cases:

foo
bar
baz

.

.s.
.ss
.s.
(s represents space)

ss
ss
(s represents space)

aaaaa
aaaaa
aaaaa
aaaaa
aaaaa

Falsy test cases:

..
.

.

.

....

....

4444
333
22

333
333

abc.def.ghi

Note extra blank lines in some of the falsy cases.

This is code-golf - fewest bytes wins!

Python 2, 52 bytes

x=input().split('\n')
print{len(x)}==set(map(len,x))

Try it online! or Try all test cases


Multiplicative undelta Let us define the "multiplicative deltas" of values \$[\; a_0, \cdots a_N, \;]\$ as:

$$
[\; a_1 / a_0, \cdots, a_{i+1} / a_i, \cdots, a_N / a_{N-1} \;]
$$

The reverse operation - namely "multiplicative undelta" - returns values such that the above operation results in the given values.

Example

Given values \$[\; 1, 5, 3, 2 \;]\$ a general solution to the "multiplicative undelta" operation is:

$$
[\;
 a_0,
 \quad \underset{a_1}{\underbrace{a_0 \cdot 1}},
 \quad \underset{a_2}{\underbrace{a_1 \cdot 5}},
 \quad \underset{a_3}{\underbrace{a_2 \cdot 3}},
 \quad \underset{a_4}{\underbrace{a_3 \cdot 2}}
 \;]
$$

A particular solution can be obtained by setting \$a_0\$ to any value other than zero, for example by setting \$a_0 := 1 \$ we would get:

$$
[\; 1, 1, 5, 15, 30 \;]
$$

Challenge

Your task for this challenge is to implement the operation "multiplicative undelta" as defined above.

Rules

Inputs are:

a non-zero value \$a_0\$
a non-empty list/array/vector/... of non-zero "multiplicative deltas"

Output is a list/array/vector/... of values such that the first element is \$a_0\$ and for which the "multiplicative deltas" are the input.

Note: If your language has no support of negative integers you may replace non-zero by positive.

Test cases

2 [21] -> [2,42]
1 [1,5,3,2] -> [1,1,5,15,30]
-1 [1,5,3,2] -> [-1,-1,-5,-15,-30]
7 [1,-5,3,2] -> [7,7,-35,-105,-210]
2 [-12,3,-17,1311] -> [2,-24,-72,1224,1604664]
-12 [7,-1,-12,4] -> [-12,-84,84,-1008,-4032]
1 [2,2,2,2,2,2,2,2] -> [1,2,4,8,16,32,64,128,256]

Haskell, 8 bytes

scanl(*)

Try it online!


Shorten text with Run Length Encoding Shorten (or not) text using run length encoding

Input:

heeeello
woooorld

Output:

1h4e2l1o
1w4o1r1l1d

Read lines from stdin.
Print to stdout.
Stderr is of course discarded.
Assume there are hidden testcases (no embedding of the output)
Input/Output as ASCII
Any language is accepted

Perl: 46 → 36 or 27 characters

perl -pe's|((.)\2*)|@x=split//,$1;@x.$x[0]|eg'

All hail @ardnew for coming up with the idea of using the tr///c operator to count the number of characters in the matched string instead of splitting:

perl -pe's|((.)\2*)|$1=~y///c.$2|eg'

Degolfed:

while(defined($_ = <>)) {
  $_ =~ s{((.)\2*)}           # match 1 or more consecutive identical non-newlines
         {
           ($1 =~ y///c )     # count the number of characters in $1
           .                  # and concatenate it
           $2                 # with the first matched character
         }eg;                 # execute substitution, match "global"
  print $_;                   # print the modified line
}

Usage:

$ perl -pe's|((.)\2*)|$1=~y///c.$2|eg' infile

or via STDIN

$ perl -pe's|((.)\2*)|$1=~y///c.$2|eg'
heeeello

prints

1h4e2l1o


BLUEREDGOLDEGGSFEATHERSFEATHERS There's a little-known secret in Banjo-Kazooie that you can interleave the three Cheato codes on the Treasure Trove Cove Sandcastle floor and it will still recognize all of them. So you could, for instance, enter BLUREEGOLDDFFEEGEAATHTHEEGSRSRS, activating BLUEEGGS, REDFEATHERS, and GOLDFEATHERS all at once.
Challenge
Your task is to take a list of cheat codes and a code entry and determine which of the codes are activated.
A code entry is valid if and only if some substring of the entry can spell out a subset of the cheat codes by assigning letters one at a time to exactly one word in order until all codes are exactly filled in. For example, applying this to the above code entry:
BLUREEGOLDDFFEEGEAATHTHEEGSRSRS

BLU_E________E_G_________GS____
___R_E___D_F__E__A_TH__E___RS__
______GOL_D_F___E_A__TH_E____RS

Other Assumptions

Both cheats and entries will contain only uppercase letters A-Z.
Each code in the input list will appear only once.
If two cheat codes share a prefix or a suffix, their shared letters must still appear twice to be counted, thus REDGOLDFEATHERS would, for the purposes of this challenge, only return GOLDFEATHERS.
Each code entry can only contain one matching substring.
If it is ambigous how a code-matching substring could be chosen, choose the one that starts the earliest and is the longest match for that particular starting point.
The order of matched codes returned does not matter.
If it is ambiguous which code could be used, prefer cheat codes that appear earlier in the code list.
A substring does not match if some of the letters inside it cannot be assigned to a cheat code. For instance BLUEXEGGS does not match any cheat codes.
If no codes are matched, you may return an empty list or any falsy value.

Note that this may not necessarily be consistent with the nuances of the game`s implementation
Example Test Cases
Codes:
  BLUEEGGS

Entry: BLUEEGGS

Result:
  BLUEEGGS

Codes:
  BLUEEGGS
  REDFEATHERS
  GOLDFEATHERS

Entry: BANJOGOLDBLUREEDFEATHEERGGSSKAZOOIE

Result:
  BLUEEGGS
  REDFEATHERS

Codes:
  BLUEEGGS
  REDFEATHERS
  GOLDFEATHERS

Entry: KAZOOIEBLUREEGOLDDFFEEGEAATHTHEEGSRSRSBANJO

Result:
  BLUEEGGS
  REDFEATHERS
  GOLDFEATHERS

Codes:
  BLUEEGGS
  REDFEATHERS
  GOLDFEATHERS

Entry: BANJOKAZOOIE

Result: <falsy>

Codes:
  CAT
  DOG

Entry: CCADOGATT

Result:
  DOG
(The substring may not contain the same code twice)

Codes:
  COG
  ATE
  CAT
  DOG

Entry: CDCOAGTE

Result:
  DOG
  CAT
(Match the earliest and longest substring)

Codes:
  ACE
  BDF
  ABC
  DEF

Entry: ABCDEF

Result:
  ACE
  BDF
(Prefer matching codes earlier in the list)

Rules/Scoring
Standard procedure for code golf applies. I/O can use any convenient format. Fewest bytes wins.

Brachylog, 25 bytes

hsS&t⊇.g;Sz{∋ʰ}ᵐhᵍ{tᵐc}ᵐp

Try some of the faster test cases online!

Extremely slow brute force, that I haven't verified on the longer test cases yet. It wouldn't surprise me if a clever implementation of a smarter algorithm turns out considerably shorter. Takes input as a list [entry,codes] through the input variable and outputs through the output variable if it succeeds. Seems to comply fully with the spec to the extent to which I've tested it at all.

The exact nature of the brute force is that for every substring of the entry (until there's a match), it tries every subset of the codes until it's possible to assign one code to each letter of the substring such that the letters assigned to each code taken in order form that code. The worst case complexity, where the worst case is failure, is something vaguely along the lines of \$O(x^22^yy^x)\$ with \$x\$ the length of the entry and \$y\$ the number of codes.


Restricted memory optimization The edit (or Levenshtein) distance between two strings is the minimal number of single character insertions, deletions and substitutions needed to transform one string into the other. If the two strings have length n each, it is well known that this can be done in O(n^2) time by dynamic programming. The following Python code performs this calculation for two strings s1 and s2.

def edit_distance(s1, s2):
    l1 = len(s1)
    l2 = len(s2)

    matrix = [range(l1 + 1)] * (l2 + 1)
    for zz in range(l2 + 1):
      matrix[zz] = range(zz,zz + l1 + 1)
    for zz in range(0,l2):
      for sz in range(0,l1):
        if s1[sz] == s2[zz]:
          matrix[zz+1][sz+1] = min(matrix[zz+1][sz] + 1, matrix[zz][sz+1] + 1, matrix[zz][sz])
        else:
          matrix[zz+1][sz+1] = min(matrix[zz+1][sz] + 1, matrix[zz][sz+1] + 1, matrix[zz][sz] + 1)
    return matrix[l2][l1]

In this task you have to get as close are you can to computing the edit distance but with a severe memory restriction. Your code is allowed to define one array containing 1000 32-bit integers and this is to be the only temporary storage you use in your computation.  All variables and data structures are to be contained in this array. In particular, you would not be able to implement the algorithm above as for strings of length 1000 as it would require you to store at least 1,000,000 numbers. Where your language doesn't naturally have 32 bit integers (for example Python) you simply need to make sure you never store a number larger than 2^32-1 in the array.

You may read in the data using any standard library of your choice without worrying about the memory restrictions in that part. In order to make the competition fair for the main part of your code, you may only use operations that are functionally equivalent to those in the C programming language and cannot use any external libraries.

To be extra clear, the memory to store the input data or used by your language's interpreter, JVM etc. does not count towards your limit and you may not write anything to disk.  You must assume the input data is read-only when in memory so you can't reuse that to gain more working space.

What do I have to implement?

Your code should read in a file in the following format. It will have three lines. The first line is the true edit distance. The second is string 1 and the third is string 2.   I will test it with the sample data at https://bpaste.net/show/6905001d52e8 where the strings have length 10,000 but it shouldn't be specialised for this data. It should output the smallest edit distance it can find between the two strings.

You will also need to prove your edit distance actually comes from a valid set of edits. Your code should have a switch which turns it into a mode that may use more memory (as much as you like) and outputs the edit operations that give your edit distance.

Score

Your score will be the (optimal edit distance/divided by the edit distance you find) * 100.  To start things off, notice that you can get a score by just counting the number of mismatches between the two strings.

You can use any language you like which is freely available and easy to install in Linux.

Tie break

In the case of a tie-break, I will run your code on my Linux machine and the fastest code wins.

C++   75.0
The program is designed to work with arbitrary text strings. They can be of any different lengths as long as neither exceeds 13824 characters. It uses 1,897 16-bit integers, which is equivalent to 949 32-bit integers. At first I was writing it in C, but then realized there was no function for reading a line.
The first command-line argument should be a filename. If a second argument exists, a summary of the edits is printed. The first line in the file is ignored while the second and third are the strings.
The algorithm is a doubly blocked version of the usual algorithm. It performs basically the same number of operations, but is of course much less accurate, since if a common subsequence gets split over the edge of a block, much of the potential savings are lost.
#include <cstring>
#include <inttypes.h>
#include <iostream>
#include <fstream>

#define M 24
#define MAXLEN (M*M*M)
#define SETMIN(V, X) if( (X) < (V) ) { (V) = (X); }
#define MIN(X, Y) ( (X) < (Y) ? (X) : (Y) )

char A[MAXLEN+1], B[MAXLEN+1];
uint16_t d0[M+1][M+1], d1[M+1][M+1], d2[M+1][M+1];

int main(int argc, char**argv)
{

    if(argc < 2)
        return 1;

    std::ifstream fi(argv[1]);

    std::string Astr, Bstr;
    for(int i = 3; i--;)
        getline(fi, i?Bstr:Astr);
    if(!fi.good()) {
        printf("Error reading file");
        return 5;
    }
    if(Astr.length() > MAXLEN || Bstr.length() > MAXLEN) {
        printf("String too long");
        return 7;
    }

    strcpy(A, Astr.c_str());
    strcpy(B, Bstr.c_str());

    uint16_t lA = Astr.length(), lB = Bstr.length();
    if(!lA || !lB) {
        printf("%d\n", lA|lB);
        return 0;
    }
    uint16_t nbA2, nbB2, bA2, bB2, nbA1, nbB1, bA1, bB1, nbA0, nbB0, bA0, bB0; //block, number of blocks
    uint16_t iA2, iB2, iA1, iB1, jA2, jB2, jA1, jB1; //start, end indices of block

    nbA2 = MIN(M, lA);
    nbB2 = MIN(M, lB);
    for(bA2 = 0; bA2 <= nbA2; bA2++) {
        iA2 = lA * (bA2-1)/nbA2,  jA2 = lA * bA2/nbA2;
        for(bB2 = 0; bB2 <= nbB2; bB2++) {
            if(!(bA2|bB2)) {
                d2[0][0] = 0;
                continue;
            }
            iB2 = lB * (bB2-1)/nbB2,  jB2 = lB * bB2/nbB2;
            d2[bA2][bB2] = ~0;
            if(bB2)
                SETMIN(d2[bA2][bB2], d2[bA2][bB2-1] + (jB2-iB2));
            if(bA2)
                SETMIN(d2[bA2][bB2], d2[bA2-1][bB2] + (jA2-iA2));

            if(bA2 && bB2) {
                nbA1 = MIN(M, jA2-iA2);
                nbB1 = MIN(M, jB2-iB2);
                for(bA1 = 0; bA1 <= nbA1; bA1++) {
                    iA1 = iA2 + (jA2-iA2) * (bA1-1)/nbA1, jA1 = iA2 + (jA2-iA2) * bA1/nbA1;
                    for(bB1 = 0; bB1 <= nbB1; bB1++) {
                        if(!(bA1|bB1)) {
                            d1[0][0] = 0;
                            continue;
                        }
                        iB1 = iB2 + (jB2-iB2) * (bB1-1)/nbB1, jB1 = iB2 + (jB2-iB2) * bB1/nbB1;
                        d1[bA1][bB1] = ~0;
                        if(bB1)
                            SETMIN(d1[bA1][bB1], d1[bA1][bB1-1] + (jB1-iB1));
                        if(bA1)
                            SETMIN(d1[bA1][bB1], d1[bA1-1][bB1] + (jA1-iA1));

                        if(bA1 && bB1) {
                            nbA0 = jA1-iA1;
                            nbB0 = jB1-iB1;
                            for(bA0 = 0; bA0 <= nbA0; bA0++) {
                                for(bB0 = 0; bB0 <= nbB0; bB0++) {
                                    if(!(bA0|bB0)) {
                                        d0[0][0] = 0;
                                        continue;
                                    }
                                    d0[bA0][bB0] = ~0;
                                    if(bB0)
                                        SETMIN(d0[bA0][bB0], d0[bA0][bB0-1] + 1);
                                    if(bA0)
                                        SETMIN(d0[bA0][bB0], d0[bA0-1][bB0] + 1);
                                    if(bA0 && bB0)
                                        SETMIN(d0[bA0][bB0], d0[bA0-1][bB0-1] + (A[iA1 + nbA0 - 1] != B[iB1 + nbB0 - 1]));
                                }
                            }
                            SETMIN(d1[bA1][bB1], d1[bA1-1][bB1-1] + d0[nbA0][nbB0]);
                        }
                    }
                }

                SETMIN(d2[bA2][bB2], d2[bA2-1][bB2-1] + d1[nbA1][nbB1]);
            }
        }
    }
    printf("%d\n", d2[nbA2][nbB2]);

    if(argc == 2)
        return 0;

    int changecost, total = 0;
    for(bA2 = nbA2, bB2 = nbB2; bA2||bB2; ) {
        iA2 = lA * (bA2-1)/nbA2,  jA2 = lA * bA2/nbA2;
        iB2 = lB * (bB2-1)/nbB2,  jB2 = lB * bB2/nbB2;
        if(bB2 && d2[bA2][bB2-1] + (jB2-iB2) == d2[bA2][bB2]) {
            total += changecost = (jB2-iB2);
            char tmp = B[jB2];
            B[jB2] = 0;
            printf("%d %d deleted {%s}\n", changecost, total, B + iB2);
            B[jB2] = tmp;
            --bB2;
        } else if(bA2 && d2[bA2-1][bB2] + (jA2-iA2) == d2[bA2][bB2]) {
            total += changecost = (jA2-iA2);
            char tmp = B[jA2];
            A[jA2] = 0;
            printf("%d %d inserted {%s}\n", changecost, total, A + iA2);
            A[jA2] = tmp;
            --bA2;
        } else {
            total += changecost = d2[bA2][bB2] - d2[bA2-1][bB2-1];
            char tmpa = A[jA2], tmpb = B[jB2];
            B[jB2] = A[jA2] = 0;
            printf("%d %d changed {%s} to {%s}\n", changecost, total, B + iB2, A + iA2);
            A[jA2] = tmpa, B[jB2] = tmpb;
            --bA2, --bB2;
        }
    }

    return 0;
}


Keep PPCG running in Game of Life Conways' Game of Life is a well known cellular automaton "played" on an infinite grid, filled with cells that are either alive or dead. Once given an initial state, the board evolves according to rules indefinitely. Those rules are:

Any live cell with 2 or 3 living neighbours (the 8 cells immediately around it) lives to the next state
Any dead cell with exactly 3 living neighbours becomes a living cell
Any other cell becomes a dead cell

Consider the following initial state:

That is, PPCG made up of living cells. Each letter is in a \$4×6\$ bounding box, with a single empty column of cells between boxes, for a total bounding box of \$19×6\$
After 217 generations, it reaches the following states:

From this point onwards, it is a "fixed state". All structures on the board are either still lifes or oscillators, so no meaningful change will occur.
Your task is to improve this.

You may place up to 50 live cells in the \$5\times10\$ highlighted area, such that, when run, it takes more than 217 generations to reach a "fixed state". The answer with the highest number of generations wins, with ties being broken by the fewest number of placed living cells.
For the purposes of this challenge, a "fixed state" means that all structures on the board are either still lifes or oscillators. If any spaceships or patterns of infinite growth are generated, the board will never reach a "fixed state" and such cases are invalid submissions.
For example, this initial configuration takes 294 generations to reach a fixed state (this), so is a valid submission with a score of 294:

Preloaded testable version, with the \$5\times10\$ box fully filled in.

2986 2320 1228 generations
I wrote a rudimentary Python script for Golly to generate random 5x10 patterns until it encountered one whose population was fixed, and whose bounding box was not too large (as would be expected of soups containing spaceships, as spaceships expand the bounding box as they travel). Here was what it came up with after about 50,000 patterns investigated, and I suspect this is not maximal. If anyone wants to continue this search by using my script, it's located below the pattern.

RLE of solution:
# 2986 generations
x = 19, y = 20, rule = B3/S23
3o2b3o3b3o2b3o$o2bobo2bobo4bo$o2bobo2bobo4bo$3o2b3o2bo4bob2o$o4bo4bo4b
o2bo$o4bo5b3o2b2o5$7bobobo$7b2ob2o$8bo2bo$11bo$10b2o$7bo2bo2$8b4o$7bo$
7bo3bo!

Python script, to be run in Golly from File > Run Script (not golfed). You will need to paste/draw in the PPCG pattern and select the 5x10 rectangle first.
import golly as g
from glife import rect, pattern

g.setrule("B3/S23") #set the rule to Conway's Life
soupcount = 0 #create a counter for # of soups processed

while True:
    pop = 0
    g.randfill(50) #randomly fill the 5x10 selection
    g.run(2400) #run the pattern for 2400 generations
    if g.getrect()[2] * g.getrect()[3] < 40000: #after 2400 generations, if the bounding box is small
        pop = g.getpop() #check to make sure the population is not the same (pattern is not static)
        g.run(120)
        if g.getpop() != pop:
            g.run(9880) #after 9880 more generations, if the bounding box is still small
            if g.getrect()[2] * g.getrect()[3] < 40000: #check to make sure the population is the same (pattern is static)
                pop = g.getpop()
                g.run(120)
                if g.getpop() == pop:
                    g.reset() #if so, break the loop and return the pattern
                    break
    g.reset() #repeat the loop and generate a new pattern if the pattern does not satisfy the conditions
    soupcount += 1
    g.show(str(soupcount)) #continually show the # of soups processed to make sure the program isn't dead

RLEs of old solutions:
#C 2320 generations
x = 19, y = 20, rule = B3/S23
3o2b3o3b3o2b3o$o2bobo2bobo4bo$o2bobo2bobo4bo$3o2b3o2bo4bob2o$o4bo4bo4b
o2bo$o4bo5b3o2b2o5$7bo3bo$7b3o$10bo2$7bo$7bo2bo$7bo$7b2o$7bo3bo$7b2o2b
o!

#C 1228 generations, found manually with Ctrl+5
#C to continually generate random 5x10 patterns
x = 19, y = 17, rule = B3/S23
3o2b3o3b3o2b3o$o2bobo2bobo4bo$o2bobo2bobo4bo$3o2b3o2bo4bob2o$o4bo4bo4b
o2bo$o4bo5b3o2b2o5$7b5o$7bobobo$7b2obo$8bob2o$8b4o$8bo2bo$7bobo!


Polyglot self-interpreter time Your task is to make a program which interprets the language it is run in, but also works in many languages.

Let's say you make a Brainfuck-Underload self-interpreglot, as it will be called. Run in Brainfuck, this program should be a Brainfuck interpreter; run in Underload, it should be a Underload interpreter.

Your program should work like the hypothetical given above: given a list of languages L1, L2, L3, L4... up to Ln, it should be an L1 interpreter in L1, an L2 interpreter in L2, an L3 interpreter in L3, up to being an Ln interpreter in Ln.

Your program can handle errors in any way. However, it must never output to STDERR (or closest equivalent) if the input given for interpretation has no errors.

It must output to STDOUT (or closest equivalent) and take input from STDIN (or again, closest equivalent).

You can choose any interpretation of a given language, e.g. if your polyglot works in Brainfuck, it can interpret Brainfuck with finite or unbounded tape. You must specify what interpretations you choose to use for each language.

Programs must have at least 2 characters for this challenge to prevent empty programs from competing.

Functions such as exec and eval are allowed.

Only a Turing-complete subset of a language has to be interpreted.

Different languages have to be interpreted, not different language versions.

Your score is C/(L^3), where C is code length, computed in bytes with UTF-8 encoding, and L is the amount of languages. The lowest score wins: if two winning answers have the same score the one posted earlier wins.

Have fun.

Jelly, 05AB1E, GolfScript 8 bytes, score = \$\frac 8 {27} \approx 0.296\$

.Vq;~
ɠV

Try it online Jelly!

Try it online 05AB1E!

Try it online GolfScript!

In all cases, takes a program in the relevant language from STDIN and executes it, with any output going to STDOUT.


Get the lowest possible pylint score within 128 bytes of python pylint has no lower bound on the scores it will give your code. It uses the following metric to score code, with the maximum score being 10:

10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)

With python 3.6, try and write a program that:

Outputs "Hello World" when run from the command line (i.e. python script.py), and no other output.
Gets the lowest possible score from pylint, with default settings (i.e. pylint script.py)
Is strictly less than or equal to 128 bytes in size.


Digital Clock Matches Puzzle There are many puzzles with matches that involve adding, removing, or moving a certain number of matches to create new numbers or shapes. This is like that with a digital clock.

Given a valid time on a 12-hour digital clock, output the digit that requires moving the fewest lines to make it so every visible digit on the clock becomes that digit. If more than one digit is the minimum, output them all. If it is impossible to make every digit the same, output -1 or a falsy value other than 0 (you'll get a lot of these).

The clock digits look like this:

  |
  |
 _
 _|
|_
 _
 _|
 _|

|_|
  |
 _
|_
 _|
 _
|_
|_|
 _
  |
  |
 _
|_|
|_|
 _
|_|
 _|
 _
| |
|_|

Test Cases:

Input: 123

Clock Display:

       _   _
  | :  _|  _|
  | : |_   _|

Output: 4

Explanation: The display for 1:23 requires a total of 12 lines to be drawn. Therefore, for every digit to be the same, each digit would have to have 4 lines. The only digit that has 4 lines is 4. Therefore, the answer has to be 4.

Input: 1212

Clock Display:

     _        _
  |  _| :  |  _|
  | |_  :  | |_

Output: -1

Explanation: The display for 12:12 requires 14 lines. 14 divided by 4 is not an integer, therefore it is impossible for every digit to be the same.

Input: 654

Clock Display:

 _     _
|_  : |_  |_|
|_| :  _|   |

Output: 5

Explanation: The total number of lines is 15. 15 divided by 3 is 5, so each digit must have 5 lines. The only digits that have 5 lines are 2,3, and 5. The answer is 5 because it only requires 2 moves to make every digit 5. Simply move the line at the bottom left of the 6 to the bottom of the 4, then you have:

 _     _
|_  : |_  |_|
 _| :  _|  _|

Then, as you can see, all you need to do is move the line at the top right of the digit that was originally 4 to the top, and you get 5:55. To make every digit a 2 or 3 would require more than 2 moves.

Input: 609

Clock Display:

 _     _   _
|_  : | | |_|
|_| : |_|  _|

Output: 609 (6,0,9 or [6,0,9] also ok).

Explanation: 6, 0, and 9 are the only digits that have 6 lines. As such, they are also the only possible solutions. It's not hard to see that it would take two moves to make any of these the only digit. Therefore, you output all three digits.

Notes:

Although the input time must be valid, the output time does not (e.g. 999 as an output is OK.)
I am very flexible with input. You can require a leading 0. You can use a number with a decimal point. You can use a string. You can use an array. You can have a parameter for every digit.

Julia, 160 157 154

x->(c=count_ones;l=[119;36;93;109;46;107;123;37;127;111];m=l[x+1];n=map(a->c(a)==mean(map(c,m))?sum(map(b->c(a$b),m)):1/0,l);find(n.==minimum(n).!=1/0)-1)

This is a lambda function. Assign it to a variable to call it. Accepts a vector of integers in range 0-9 of any length and returns a (possibly empty) vector of results.

Test cases

julia> clock = x->(c=co...        # assign function to variable
(anonymous function)

julia> clock([1 2 3])
1-element Array{Int64,1}:
 4

julia> clock([1 2 1 2])
0-element Array{Int64,1}

julia> clock([6 5 4])
1-element Array{Int64,1}:
 5

clock([6 0 9])
3-element Array{Int64,1}:
 0
 6
 9

Explanation

Enumerate the seven segments and represent them as a bit vector.

+---+                     +-0-+
|   |      Enumerate      1   2
+---+   >  the seven  >   +-3-+
|   |      segments       4   5
+---+                     +-6-+

Example: 1 (segments 2 + 5 enabled) becomes 36 (bits 2 + 5 set).
Here are the representations for digits 0-9.

l=[119;36;93;109;46;107;123;37;127;111];
m=l[x+1];

We can use the digit as index to get it's bit vector representation. +1 because of 1-based indexing in julia.

The function c=count_ones; counts the number of 1-bits in an integer. We assign an alias because we need it more often.

The full program, somewhat ungolfed:

x->(
  c=count_ones;
  l=[119;36;93;109;46;107;123;37;127;111];
  m=l[x+1];
  n=map(a->c(a)==mean(map(c,m))?sum(map(b->c(a$b),m)):1/0,l);
  find(n.==minimum(n).!=1/0)-1
)

Now, the last two lines in detail:

mean(map(c,m)) calculates the average number of lines per input digit.

n=map(a->...,l) loops over the vector representation of all digits.

If the number of lines of our current digit a is unequal to the average linecount of the input, return inf.

c(a)==mean(map(c,m))?...:1/0

If not, return the sum of the Hamming Distances between our current and all input digits.

sum(map(b->c(a$b),m))

We now have a vector n of length 10 representing the numbers 0-9 that gives us the total number of additions/deletions we have to perform to tranform all input digits to that number, or inf, if such a transformation is impossible without changing the number of lines.

find(n.==minimum(n).!=1/0)-1

Finally, output the locations (0-based) of all minima that are not inf.


Vampire Compatibility A little known fact about vampires is that they must drink the blood of victim that has a compatible donor blood type.  The compatibility matrix for vampires is the same as the regular red blood cell donor/recipient matrix.  This can be summarized by the following American Red Cross table

Type    You Can Give Blood To    You Can Receive Blood From
A+      A+, AB+                  A+, A-, O+, O-
O+      O+, A+, B+,AB+           O+, O-
B+      B+, AB+                  B+, B-, O+, O-
AB+     AB+                      everyone
A-      A+, A-, AB+, AB-         A-, O-
O-      everyone                 O-
B-      B+, B-, AB+, AB-         B-  O-
AB-     AB+, AB-                 AB-, A-, B-, O-

Challenge

Write a function or program that takes a blood type as input and outputs two lists:

the unordered list of types that may receive donation of the input type
the unordered list of types that may give donation to the input type

If you write a function, then please also provide a test program to call that function with a few examples, so I can easily test it.  In this case, the test program would not count towards your score.

Input

Input must be a string representing exactly one of the 8 possible red blood cell types O− O+ A− A+ B− B+ AB− AB+.  Input may be given via the normal methods (STDIN, command-line args, function args, etc).

If any other input is given then the program/function must return empty output or throw an error.  Normally strict input-checking is not great in code-golf questions, but I felt given the life-death implications of getting blood types wrong that I should add this rule.

Output

Output will be two human-readable lists of blood types in whatever format is suitable for your language.  In the special cases where one of the output list contains all 8 types, this list may optionally be replaced with a single item list containing everyone.

Normal output will go to one of the normal places (STDOUT, function return, etc).

Other rules

Standard loopholes are banned
You may use whatever pre-existing 3rd party libraries you need, so long as they are not designed explicitly for this purpose.

Examples

For input AB-, the two output lists would be: {AB+, AB-}, {AB-, A-, B-, O-}
For input AB+, the two output lists would be: {AB+}, {O−, O+, A−, A+, B−, B+, AB−, AB+} or {AB+}, {everyone}

Personal note: Please consider donating blood if you are able to.  Without the transfusion I received a few years ago, I might not be here today, so I feel very grateful towards those who are able to donate!

Clip, 69

*cTx\{fFx`Tf[tFtx}T`[Fx[y!VVx"O-"Vy"O-"}[TC"A+ B+ AB+ O+ A- B- AB- O-

Input: AB-

Output: {{"AB+", "AB-"}, {"A-", "B-", "AB-", "O-"}}

Explanation

A blood type x can give to y if all of x's antigens are included in y. The program defines the function F as whether x can give to y, and T as the list of types.

*cTx                 .- If T contains x (the input)         -.
    \                .- Print                               -.
     {             ` .- a list of                           -.
      fFx`T          .- filter each t in T with F(x,t)      -.
           f[tFtx}T  .- filter each t in T with F(t,x)      -.

[Fx[y              } .- F is a function of x and y          -.
     !V              .- all letters of ... are included in ...   -.
       Vx"O-"        .- x, with O and - removed             -.
             Vy"O-"  .- y, with O and - removed             -.

[TC"A+ B+ AB+ O+ A- B- AB- O-   .- T is the list of types -.


What an Odd Function Your task here will be to implement a function1 that forms a permutation on the positive integers (A bijection from the positive integers onto themselves).  This means that each positive integer should appear exactly once in the permutation.  The catch is your function should have a larger probability of outputting an odd number than an even number.

Now this may seem strange or impossible.  Surely there are just as many odd numbers as even numbers?  And while this intuition is correct for finite sets it actually does not hold for infinite sets.  For example take the following permutation:

1 3 2 5 7 4 9 11 6 13 15 8 17 19 10 21 23 12 25 27 14 29 31 16 33 35 18 37 39 20 41 43 22 45 47 24 49 51 26 53 55 ...

If you take any subsection of the sequence with size greater than \$1\$ you will have at least as many odd numbers as even numbers, thus it seems that the probability of any random term being odd is greater than that of being even.  You will also note every number odd or even number will eventually appear in the sequence and can only appear once.  Thus the sequence is a true permutation.

Definition of Probability

To avoid confusion or ambiguity I am going to clearly lay out what is meant by probability in this question.

Let us say we have a function \$f\$.  The probability of a number being odd will be defined as the limit of ratio odd members of the set to the size of the set \$f\{1\dots n\}\$ as \$n\$ tends towards infinity.

$$\lim_{n\rightarrow \infty}\dfrac{\left|\{x : x \in \{1\dots n\}, \mathrm{odd}(f(x))\}\right|}{n}$$

For example the aforementioned function would have a probability of being odd of \$2/3\$.

This is code-golf so answers will be scored in bytes with less bytes being better.

Extra Challenges

Here are some fun ideas to play around with and perhaps try to implement.  These are just for fun and do not affect scoring in any way. Some of these are not even valid solutions to this challenge, and an answer which only includes solutions to challenges 2 or 3 is not a valid answer, and is liable to be deleted.

Write a permutation with an odd probability of \$1\$. (this is possible)
Write a permutation that has more odd numbers than even numbers in \$f\{1\dots n\}\$ for any \$n\$ but has a odd probability of \$1/2\$.
Write a permutation that has no defined probability (that is there is no limit).

1: Here function will mean program or function.  It is just a piece of code that takes input and produces output.

Jelly, 7 bytes

Æf^<¥4P

Swaps 2s and 3s in the input's prime factorization. The probability of odds is 2/3.

Try it online!

How it works

Æf^<¥4P  Main link. Argument: n

Æf       Compute all prime factors of n, with duplicates.
    ¥4   Combine the two links to the left into a dyadic chain and call it with
         right argument 4.
   <       Compare each prime factor with 4. Yields 1 for 2 and 3, 0 otherwise.
  ^        Bitwise XOR the results with the corresponding prime factors.
         This maps 2 to 3, 3 to 2, and all other primes to themselves.
      P  Take the product of the resulting primes.


Linear dependences over the field with two elements The \$d\$-dimensional vector space \$\mathbb{F}_2^d\$ over the field with two elements \$\mathbb{F}_2\$ is the set of vectors of \$d\$ bits. Addition of vectors is bitwise xor. A linear dependence is a set of vectors whose total (xor them all together) is \$0\$. Every set of \$d+1\$ vectors in \$\mathbb{F}_2^d\$ contains a linear dependence. We will represent the elements of \$\mathbb{F}_2^d\$ as the integers \$0\$ through \$2^{d}-1\$ using the binary expansion.

Task

Input: a positive integer \$d\$ and a list of \$d+1\$ positive integers between \$1\$ and \$2^{d}-1\$. You may assume that the list is sorted and you may assume that the entries are distinct.

Output: A nonempty subset of the \$d+1\$ numbers whose bitwise xor is zero.

Scoring:

This is code golf so shortest answer in bytes wins.

Examples:

Input: (3, [1,3,4,7])
Output: [3, 4, 7]

In binary, these are 001, 011, 100, and 111. We see that 100 xor 011 xor 111 = 000. In this case this is the only solution, so we must output [3, 4, 7].

Test cases:

Input: (3, [1,3,4,7])
Output: [3, 4, 7]

Input: (4, [1, 2, 6, 10, 30])
Output: Behavior undetermined because 30 > 15 = 2^4 - 1.

Input: (5, [3, 5, 6, 9, 14])
Output: [3, 5, 6]

Input: (5, [4, 8, 10, 12, 14])
Output: [4, 8, 12] or [4, 10, 14], or [8, 10, 12, 14].

Input: (6, [4, 15, 17, 21, 49, 51, 57])
Output: [4, 17, 21]

Input: (6, [1, 7, 8, 15, 39, 55, 57])
Output: [7, 8, 15] or [1, 15, 55, 57] or [1, 7, 8, 55, 57]

Input: (6, [13, 14, 24, 33, 35, 36, 63])
Output: [13, 14, 24, 36, 63]

Input: (6, [10, 11, 25, 28, 40, 59, 62])
Output: [10, 25, 40, 59] or [10, 28, 40, 62], or [25, 28, 59, 62]

Input: (6, [1, 3, 5, 11, 19, 32, 63])
Output: [1, 3, 5, 11, 19, 32, 63]


Is this a winning *Frustration* configuration? Frustration is a solitaire card game which is played by calling out the sequence:

“Ace”, “Two”, “Three”, ... , "Nine", "Ten", “Jack”, “Queen”, “King”, “Ace”, “Two”, etc.

With each call, you simultaneously flip over a card from a shuffled deck of 52 cards. You win the game if you get through the entire deck without ever calling out the rank of the card being flipped over.

Challenge

Given a string or list of characters representing an ordered deck of cards, return "Truthy" if the deck is a winning Frustration configuration, and return "Falsy" otherwise

Input

Input will be a single string (or a list of characters, or a list of codepoints) consisting solely of the following 13 characters (you may choose to take the letters as uppercase or lowercase):

A 2 3 4 5 6 7 8 9 T J Q K

Each character will be repeated 4 times in the input. An example of a valid input is:

A23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQK

You may assume that the input is always valid (ie. it will contain exactly 52 characters and the 13 characters mentioned above will be repeated exactly 4 times each)

Output

Output one of two distinct "Truthy" and "Falsy" values. The values you choose must be consistent (ie. different "Truthy" inputs must produce the same "Truthy" output and different "Falsy" inputs must produce the same "Falsy" output)

Examples

The input KA23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQ would be a winning Frustration configuration (hence a "Truthy" input) because none of the cards in the sequence match the name called out when flipping that card over.

The input 2K3A456789TJQKA23456789TJQKA23456789TJQKA23456789TJQ would not be a winning Frustration configuration (hence a "Falsy" input) because the 3rd card flipped over matches the name called out when flipping it (3).

Test Cases (one per line)

Truthy

KA23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQ
2A2A2AKQKQK3Q456789345678934567893456789A2JJJJTQKTTT
KQJT98675432AKQJT98675432AKQJT98675432AKQJT98675432A
55667987TAQK8TAQK8TAQK8TAQK325476979965432JJJJ234234
JAK3TTJAK3TT33KAA2456789456789456789222456789JJQQQKQ

Falsy

A23456789TJQKA23456789TJQKA23456789TJQKA23456789TJQK
2A2A2AKQKQKQ3456789345678934567893456789A2JJJJTQKTTT
KQJT98765432AKQJT98765432AKQJT98765432AKQJT98765432A
8TAQK8TAQK8TAQK8TAQK234567999765432JJJJ2342345566797
JAK3TTJAK3TT33KAA2456789456789456789222456789JJQQQQK

Scoring

This is code-golf. Shortest answer in bytes wins

Python 2, 45 42 bytes

-5 bytes thanks to @ovs

lambda s:all(map(cmp,s,'A23456789TJQK'*4))

Try it online!