Domination problem in chess Given an mxm chess board, find a minimum number of pieces of the given kind and place them on a chess board in such a way that all squares are either occupied or attacked by at least one piece.

Input

The input consists of two parameters: m, the number of squares on each side; and a letter which indicates which piece to use, according to the following key: King, Queen, Rook, Bishop, kNight. For example, an input of 8 B means that you have to find a solution for an 8x8 board with bishops.

The input will always consist of a positive integer and a valid letter. You may choose to implement a program which takes input either as command-line arguments or separated by a space on stdin; or to implement a named function/verb which takes two parameters.

Output

The output should be a chess board in the following format:

........
.....Q..
..Q.....
....Q...
......Q.
...Q....
........
........

This is a solution for the input 8 Q. Each line is separated by a newline.

Note that every valid input has a solution.

Other points

Standard loopholes are not acceptable. In particular, since your program must handle any input, it is not sufficient to hard-code the answer for small inputs.

The particular case of this problem where Queens are used has been the subject of some investigation, and the number of Queens required for square boards is in the Online Encyclopaedia of Integer Sequences as A075324. However, that probably doesn't help you for inputs larger than 18 Q, and doesn't give you the layout for smaller cases.

As a performance constraint to prevent pure brute-force approaches, the code should output a result for 18 Q in a reasonable time (approximately 6 hours).

This is a fun problem, and I'm sad that it has no solution, so I made my own!

Requires arguments in the form M P where M is the size of the board and P is the code for the piece

Java - S.java - 1359 Characters

public class S{int s;String p;String e=".";String b;String t;int c;public static void main(String[]args){new S(args);}S(String[] a){s=Integer.parseInt(a[0]);p=a[1];b="";int i;if(p.equals("P")){String r="P";for(i=1;i<s;i++)r+=e;r+="\n";for(i=0;i<s;i+=3){a(r);f(p);a(r);}m(0);}if(p.equals("B")){for(i=0;i<s-1;i++){if(s/2==i)f(p);f(e);}}if(p.equals("N")){for(i=0;i<s;i+=5){f(e);f(e);f("N");f(e);f(e);}m(0);if(s%5==2|s%5==1){m(1);f(p);}}if(p.equals("R")){f(p);for(i=1;i<s;i++)f(e);}if(p.equals("K")){String k="";for(i=0;i<s;i+=3)k+=".K.";k=k.substring(0,s-1);k+=(s%3==0)?e:"K";k+="\n";for(i=0;i<s;i+=3){f(e);a(k);f(e);}m(1);if(s%3==0)f(e);else a(k);}if(p.equals("Q"))for(i=0;i<s*s;i++){try{q(i,0,new String[s][s]);}catch(Exception e){}b=t;}System.out.println(b);}void q(int d,int g,String[][] o) throws Exception{int u=0;int i;if(g==s*s|u>c){if(u<=c){c=u;t="";for(i=0;i<s;i++){for(int j=0;j<s;j++)t+=o[i][j];t+="\n";}}throw new Exception();}int r=(d/s)%s;int c=d%s;if(o[c][r]==null){for(i=0;i<s;i++){try{o[c-r+i][i]=(o[c-r+i][i]==null)?e:o[c-r+i][i];}catch(Exception e){}try{o[i][r+c-i]=(o[i][r+c-i]==null)?e:o[i][r+c-i];}catch(Exception e){}o[i][r]=(o[i][r]==null)?e:o[i][r];o[c][i]=(o[c][i]==null)?e:o[c][i];}o[c][r]="Q";u++;}q(d+1,g+1,o);}void m(int d){b=b.substring(0,(s+1)*(s-d));}void a(String d){b+=d;}void f(String f){for(int i=0;i<s;i++){b+=f;}b+="\n";}}

(Pawns are attacking from left to right)

I couldn't find any proof of the minimum of any domination problem, but my Queen's solver at 8 solves with 5 queens and the others don't seem to be doing too badly (18 queens at 25x25). Someone will have to beat my other solutions to disprove them as minimums. That probably won't be hard!

Here is my de-golfed solution, for anyone interested. It's a bit of a mess... My first thought for doing the Queen's solver was to use backtracking, but I got lazy.

Java - SimpleChessSolver.java - 3496 Characters
(There was once a version which had a whole bunch of different classes, to represent the board, squares, pieces... But it quickly got out of control and was renamed ComplicatedChessSolver.java)

public class SimpleChessSolver {
int size;
String piece;
String period = ".";
String board;
String bestBoard;
int bestCount;

    public static void main(String[] args) {
        new SimpleChessSolver(args);
    }

    SimpleChessSolver(String[] args){
        size = Integer.parseInt(args[0]);
        piece = args[1];
        board = "";
        int index;
        if (piece.equals("P")){
            String periods = "P";
            for (index = 1; index < size; index++){
                periods += period;
            }
            periods += "\n";
            for (index = 0; index < size; index += 3){
                addString(periods);
                fillRow(piece);
                addString(periods);
            }
            trimToSize(0);
        }
        if (piece.equals("B")){
            for (index = 0; index < size - 1; index++){
                if (size/2 == index){
                    fillRow(piece);
                }
                fillRow(period);
            }
        }
        if (piece.equals("N")){
            for (index = 0; index < size; index += 5){
                fillRow(period);
                fillRow(period);
                fillRow("N");
                fillRow(period);
                fillRow(period);
            }
            trimToSize(0);
            if (size%5 == 2 || size%5 == 1){
                trimToSize(1);
                fillRow(piece);
            }
        }
        if (piece.equals("R")){
            fillRow(piece);
            for (index = 1; index < size; index++){
                fillRow(period);
            }
        }
        if (piece.equals("K")){
            String kings = "";
            for (index = 0; index < size; index += 3){
                kings += ".K.";
            }
            kings = kings.substring(0, size - 1);
            kings += (size%3 == 0) ? period : "K";
            kings += "\n";
            for (index = 0; index < size; index += 3){
                fillRow(period);
                addString(kings);
                fillRow(period);
            }
            trimToSize(1);
            if (size%3 == 0) {
                fillRow(period);
            }
            else {
                addString(kings);
            }
        }
        if (piece.equals("Q")){
            for (index = 0; index < size*size; index++){
                System.out.println(bestBoard);
                System.out.println("BlankLine\n");
                try {
                    queenSolve(index, 0, new String[size][size]);
                }
                catch (Exception e) {}
            }
            System.out.println("Final Answer");
            board = bestBoard;
        }

        System.out.println(board);
    }

    void queenSolve(int start, int depth, String[][] board2D) throws Exception {
        int currentCount = 0;
        int index;
        if (depth == size*size || currentCount > bestCount){
            if (currentCount <= bestCount){
                bestCount = currentCount;
                bestBoard = "";
                for (index = 0; index < size; index++){
                    for (int jdex = 0; jdex < size; jdex++){
                        bestBoard += board2D[index][jdex];
                    }
                    bestBoard += "\n";
                }
            }
            throw new Exception();
        }
        int row = (start / size) % size;
        int col = start % size;
        if (board2D[col][row] == null){
            for (index = 0; index < size; index++){
                try{
                    board2D[col - row + index][index] = (board2D[col - row + index][index] == null) ? period : board2D[col - row + index][index];
                } catch (ArrayIndexOutOfBoundsException e) {}
                try{
                    board2D[index][row + col - index] = (board2D[index][row + col - index] == null) ? period : board2D[index][row + col - index];
                } catch (ArrayIndexOutOfBoundsException e) {}
                board2D[index][row] = (board2D[index][row] == null) ? period : board2D[index][row];
                board2D[col][index] = (board2D[col][index] == null) ? period : board2D[col][index];
            }
            board2D[col][row] = "Q";
            currentCount++;
        }
        queenSolve(start + 1, depth + 1, board2D);
    }

    void trimToSize(int additionalTrim){
        board = board.substring(0, (size + 1) * (size - additionalTrim));
    }

    void addString(String toAdd){
        board += toAdd;
    }

    void fillRow(String filler){
        for (int index = 0; index < size; index++){
            board += filler;
        }
        board += "\n";
    }

}

How it works
Other than the queens, the other solutions are very simple. The Knights, Rooks, and Bishops can all be solved by putting a straight line in the correct place. Rooks cover their whole rank, so it works to just put a line anywhere on the board. A row of knights will cover four parallel rows, two in each direction. If there is a row of bishops on approximately (+/- 0.5) the middle row, they can cover every square. A row of pawns covers the parallel rows to their immediate left and right except for the bottom square, so I put a pawn on that square to occupy it. Kings can only cover the 3x3 squares around them, so I just stick Kings such that their squares don't overlap, with overlapping kings added if I need to fill out a size%3 != 0 board.

Queens is a little trickier. My algorithm, which may not be the best, iterates over the board, so that it starts on every square, then puts a queen there. It fills in periods for every square that queen covers, then walks along the board until it finds a square not already occupied by a Q or a period. As I said, this produces the current minimum for a 8x8 board (5 Queens) and I couldn't find a reference for any other board size.


Primitive Pythagorean Triples (related)

A Pythagorean Triple is a list (a, b, c) that satisfies the equation a2 + b2 = c2.

A Primitive Pythagorean Triple (PPT) is one where a, b, and c are all coprime (i.e., the only common divisor between the three elements is 1). For example, the (3, 4, 5) right triangle is a famous Primitive Pythagorean Triple.

The Challenge

Given input n, output the nth PPT. Or,
Given input n, output the first n PPTs.

There are multiple ways to order these PPTs to form a well-ordered list, to determine which is the nth. You can choose any ordering you want, so long as you can prove (informally is fine) that your algorithm can generate every possible unique PPT. For example, your code should not output both (3,4,5) and (4,3,5) since those are duplicates of the same triple -- one or the other, please.

Similarly, whether your code is zero- or one-indexed is fine, so long as you state which you're using.

Examples

For the examples below, I'm using one-indexing, outputting the nth PPT, and ordering by smallest c, then smallest a, then smallest b.

n | output
1 | (3, 4, 5)
2 | (5, 12, 13)
5 | (20, 21, 29)
12| (48, 55, 73)

Rules

The input and output can be given in any convenient format.
In your submission, please state how your entries are ordered, and whether your entries are 0-indexed or 1-indexed.
Your chosen ordering cannot create duplicates.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
If possible, please include a link to an online testing environment so other people can try out your code!
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Jelly, 27 25 bytes
2 bytes thanks to Jonathan Allan.
²IH;Pµ;ÆḊ
+2ḶḤ‘Œcg/ÐṂÇ€Ṣḣ

Try it online!
Outputs the first n 1-indexed triples [b, a, c], sorted by increasing b and then a.
Uses the algorithm from Wikipedia:

This generates all primitive triples for all unique coprime pairs of odd integers m > n > 0.
Explanation
+2ḶḤ‘Œcg/ÐṂÇ€Ṣḣ    Main link. Argument: n
+2                   Add 2 to n, to get enough results.
  Ḷ                  Get integers [0, 1, ..., n+1].
   Ḥ                 Double to get [0, 2, ..., 2n+2].
    ‘                Increment to get [1, 3, ..., 2n+3].
     Œc              Get all ordered pairs [[1, 3], [1, 5], ..., [2n+1, 2n+3]].
       g/            GCD of each pair.
         ÐṂ          Grab the pairs with minimal GCD (which is 1).
           Ç€        Call the helper link on each pair to get the triples.
             Ṣ       Sort the triples first by a, then by b, then by c.
              ḣ      Get the last n.

²IH;Pµ;ÆḊ    Helper link. Argument: pair [m, n]
²              Square to get [m², n²].
 I             Increments: get [m²-n²].
  H            Halve: get [(m²-n²)/2], i.e. [b].
    P          Product: get mn, i.e. a.
   ;           Append to get [b, a].
     µ         Begin a new monadic chain with argument [b, a].
       ÆḊ      Get the length of the vector, i.e. c.
      ;        Append to get [b, a, c].


Minimally Making Change This problem is an extension of what happens to me on a regular basis: I have to have $1.00 in coins and have to be able to give change to somebody. I discovered rather quickly that the ideal coins to have were 3 quarters, 1 dime, 2 nickels, and 5 pennies. This is the smallest number of coins (11 total) that allows me to make any number of cents 1-99.
The Challenge
Write a program that, given an integer input \$x\$ between 2 and 100 (inclusive), outputs the smallest arrangements of coins that does both of the following:

The total value of the coins is \$x\$ cents.
You can use those same coins to make every number of cents less than \$x\$.

Rules

This is code-golf so shortest code (in bytes) wins.
Standard loopholes are forbidden
The output can be a list, a four-digit number, or any reasonable representation of the number of coins needed. These coins must be in either ascending or descending order but they do not need to be clearly denoted, only consistently formatted.

In other words, all of the following are valid: [1, 2, 3, 4] [1 2 3 4] 4321 1 2 3 4 1P 2N 3D 4Q PNNDDDQQQQ. Simply state somewhere whether your output is listed in ascending or descending order; it must be the same order for all outputs.

In the case that an optimal solution has none of a given coin, your output must contain a "0" (or other similar character, so long as it is used exclusively and consistently for "0"). This rule does not apply if you use the PNDQ or QDNP format.
The only coins that exist are the penny, nickel, dime, and quarter, being worth 1, 5, 10, and 25 cents respectively.
An arrangement of coins is considered "smaller" than another if the total number of coins is less; all coins are weighted equally.

Test Cases
x      Output (Ascending four-digit number)

2      2000
3      3000
4      4000
5      5000
6      6000
7      7000
8      8000
9      4100
10     5100
11     6100
12     7100
13     8100
14     4200
15     5200
16     6200
17     7200
18     8200
19     4110
20     5110
21     6110
22     7110
23     8110
24     4210
25     5210
26     6210
27     7210
28     8210
29     4120
30     5120
31     6120
32     7120
33     8120
34     4220
35     5220
36     6220
37     7220
38     8220
39     4130
40     5130
41     6130
42     7130
43     8130
44     4230
45     5230
46     6230
47     7230
48     8230
49     4211
50     5211
51     6211
52     7211
53     8211
54     4121
55     5121
56     6121
57     7121
58     8121
59     4221
60     5221
61     6221
62     7221
63     8221
64     4131
65     5131
66     6131
67     7131
68     8131
69     4231
70     5231
71     6231
72     7231
73     8231
74     4212
75     5212
76     6212
77     7212
78     8212
79     4122
80     5122
81     6122
82     7122
83     8122
84     4222
85     5222
86     6222
87     7222
88     8222
89     4132
90     5132
91     6132
92     7132
93     8132
94     4232
95     5232
96     6232
97     7232
98     8232
99     4213
100    5213

JavaScript (ES6), 57 bytes
A significantly shorter version suggested by @tsh, who managed to get rid of the edge case \$n<9\$.
Returns an array of 4 integers in reverse order (quarters to pennies).

n=>[z=(n-=x=(n-4)%5+4)/25-.7|0,(n=n/5-5*z-1)/2|0,n%2+1,x]

Try it online!

Original version, 73 bytes
Returns an array of 4 integers.

n=>n<9?[n,0,0,0]:[x=4-~n%5,y=(z=n/25-.96|0)+(n-=x)/5&1||2,n/5-y-z*5>>1,z]

Try it online!


Sort the distinct elements of a list in descending order by frequency Write a function which takes a list or array, and returns a list of the distinct elements, sorted in descending order by frequency.

Example:

Given:

["John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John"]

Expected return value:

["Doe","Harry","John","Dick"]

APL (14)

{∪⍵[⍒+⌿∘.≡⍨⍵]}

This is a function that takes a list, e.g.:

      names
 John  Doe  Dick  Harry  Harry  Doe  Doe  Harry  Doe  John
      {∪⍵[⍒+⌿∘.≡⍨⍵]} names
 Doe  Harry  John  Dick

Explanation:

∘.≡⍨⍵: compare each element in the array to each other element in the array, giving a matrix
+⌿: sum the columns of the matrix, giving how many times each element occurs
⍒: give indices of downward sort
⍵[...]: reorder ⍵ by the given indices
∪: get the unique elements


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

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

using System.IO;

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

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

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

Get cracking! :)

PowerShell v2+, 10 bytes

for(){1>1}

Simply loops infinitely with an empty for loop. Each iteration, we output the integer 1 (implicitly converted to a string) with the > redirect operator, which overwrites the file named 1 in the local directory.


Dynamically Create Boxes The Challenge:

Draw a rectangle of ASCII boxes: []

The Rules:

Takes a width and a height input

You can assume both of these are numbers

Must produce a string with newline characters, \n

Examples:

2, 2:

[][]
[][]

2, 3:

[][]
[][]
[][]

Fewest Bytes wins.

SOGL, 5 bytes
Ƨ[]*∙

Simple:
Ƨ[]    push "[]"
   *   multiply horizontally (repeating width times)
    ∙  get an array with input (height) items of that
       implicitly output the array joined with newlines


Determine Superabundance A superabundant number is an integer n that sets a new upper bound for its ratio with the divisor sum function σ. In other words, n is superabundant if and only if, for all positive integers x that are less than n:

$$\frac{\sigma(n)}n>\frac{\sigma(x)}x$$

For a few of the values:

n   σ(n)   σ(n)/n   superabundant
1   1      1.0000   yes
2   3      1.5000   yes
3   4      1.3333   no
4   7      1.7500   yes
5   6      1.2000   no
6   12     2.0000   yes
7   8      1.1429   no
8   15     1.8750   no
9   13     1.4444   no

A longer list of these (for test cases) can be found at OEIS A004394.

One highly recommended negative test case (if your interpreter can handle it) is 360360, because it ties with the last superabundant number.

Challenge

Your program should take in a single positive integer, and output a truthy or falsey value representing whether that integer is superabundant.

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

Jelly, 7 bytes
Æs÷$ÞṪ=

Try it online!
Jelly, 8 bytes
Æs÷$ÐṀ⁼W

Try it online!
Test Suite!
Explanation

Æs÷$ÐṀ⁼W ~ Full program (monadic).

    ÐṀ   ~ Keep the elements with maximal link value (auto-rangifies).
Æs       ~ Divisor sum.
  ÷$     ~ Divide by the current element.
      ⁼W ~ Check equality with the input wrapped into a singleton.
         ~ (for integers like 360360)


Make a picture into a sliding puzzle Summary
The goal of this challenge is to create an undone image-version of a 15-puzzle / sliding puzzle also called taquin in french.
Details:
Given an input composed of:

an image,
an integer n,
an other integer r,

your program, or function, or anything else that fits, must output the same image (i.e. same size and format) as the input, but that underwent the following process:

divide the image into n² rectangles,
remove one of those rectangles, randomly,
move a random number of contiguous rectangles from the line/column affected by point (2.) so the hole created is filled and another one is generated in this line/column. This number can be 0 if the blank is in a corner or an edge.

Repeat (3.) r times.
Clarifications:

If you moved rectangles from the line in step (3.), you must move rectangles from the column the in the next repetition,
if you moved rectangles left-to-right in a line-step, they must be moved right-to-left in the next line-step, same for top-to-bottom and bottom-to-top concerning columns,
you may assume that n will be chosen so it divides the lengths of the sides of the picture.

A last point:
An animated .gif showing the whole process are very welcomed.
I propose to use the following picture (which is 1024x768), with n=16 and r=100 as a model, you can use any other picture (as long as it's relevant and complies with SE's rules, of course).
Note that standards loopholes policies apply.
This is code-golf, so the shorter submission wins !

Since an example was requested, here is one, made "by hand", with n=4 and r=1
Steps 1 and 2

Step 3 : line-wise, 2 rectangles to the left

Mathematica, 246 bytes
ImageAssemble@(n=Nest)[k=RandomInteger;q=Reverse;({t,r}=1~k~2;q[o=n[q/@#&,#,r]&@*(n[#&,#,t]&)])[o@#/.{a___,b:_~RepeatedNull~k[Position[o@#,i][[1,2]]-1],i,c___}:>{a,i,b,c}]&,MapAt[(i=#~ImageAdd~1)&,#~ImagePartition~Scaled[1/#2],{1,#2}~k~2],#3]&

Anonymous function. Contains U+F3C7, corresponding to Mathematica's Transpose operator. This function takes an Image object and returns an Image object.
Sample Animation, with n=16 and r=100
After 5000 iterations:
(click image for larger version)
Explanation
Initialization
n=Nest

Store the Nest function (repeating operation) in n.
k=RandomInteger;q=Reverse;

Store the RandomInteger function in k, and Reverse function in q.
Splitting the image
#~ImagePartition~Scaled[1/#2]

Partition the input image into (second input)^2 tiles.
{1,#2}~k~2

Generate two RandomIntegers between 1 and the second input. This selects a random tile.
MapAt[(i=#~ImageAdd~1)&, ..., {1,#2}~k~2]

Make that tile white. Store it in i.
Moving Tiles
{t,r}=1~k~2

Generate two random integers from 0 to 1, and store them in t and r, respectively. This randomly selects direction.
o=n[q/@#&,#,r]&@*(n[#&,#,t]&)

Define function o: the composition of

a function transposing the input t times.
a function reversing each row r times.

o@#
Apply o to the input.
Position[o@#,i][[1,2]]

Find the column of i (white image).
k[ ... -1]

Subtract one and find a random integer between 0 and that number. This randomly chooses how many tiles to move.
o@#/.{a___,b:_~RepeatedNull~ ... ,i,c___}:>{a,i,b,c}

When the said number of tiles occur before an i (white image), switch their places.
(... q[o= ... ])[ ... ]

Reverse the o function and apply that to the result of above operation. This un-reverses and un-transposes the image.
Looping and Image Assembly
(n=Nest)[ ... ,#3]

Repeat the above process (third input) times.
ImageAssemble@

Put the images together.


Transpose a 3x3 matrix across the anti-diagonal Write a program which takes a 3x3 matrix on stdin and prints its transpose along the anti-diagonal to stdout. You may assume that all elements of the matrix will be integers. Columns are space-separated and rows are newline-separated.

Example

Input:

1 2 3
3 4 5
1 2 3

Output:

3 5 3
2 4 2
1 3 1

Input:

1 2 3
4 5 6
7 8 9

Output:

9 6 3
8 5 2
7 4 1

APL - 7
⌽⍉⌽3 3⍴

Example input:
⌽⍉⌽3 3⍴1 2 3 3 4 5 1 2 9
> 9 5 3
  2 4 2
  1 3 1

ngn APL demo


Roman Numeral-like Code Generator Background
Roman numeral is a simple number system with the following properties:

Each symbol in the system maps to a specific value. (e.g. I = 1, V = 5, X = 10, C = 100)
The value of a Roman numeral can be evaluated as follows:

First, find all occurrences of adjacent pairs of symbols where a strictly smaller-valued symbol comes first (e.g. IV, XC). Each such pair is evaluated as the backward difference of two values (e.g. IV = 5 - 1 = 4).
Then, interpret the remaining symbols as-is and sum all values in it.
MMCMXCIV = M + M + CM + XC + IV
         = 1000 + 1000 + (1000 - 100) + (100 - 10) + (5 - 1)
         = 2994

Task
Your job is to write a function/program \$F\$ that takes a positive integer \$n\$ and generates a code fragment \$F(n)\$ (not necessarily in the same language). The outputted code fragments must have the following properties:

\$F(n)\$ as a full program must output the number \$n\$.
\$F(a)+\!\!\!+\,F(b)\$ as a program (where \$+\!\!+\$ means concatenation) must output \$a+b\$ if \$a≥b\$, \$b−a\$ otherwise.
This must extend to any number of code fragments emitted by your program in the way that \$b−a\$ cases take precedence (think of an arithmetic expression with +s and -s, but the two sides of -s are flipped and it has higher precedence than +).

You do not need to consider the cases where three consecutive input numbers are strictly increasing (the equivalent arithmetic expression has two consecutive -s).

Your score is the byte count of \$F\$. Shortest code in bytes wins.
Example
If \$F(10)\$ outputs the code fragment ABC, and \$F(3)\$ outputs the code fragment xyz:

The program ABC should output 10.
The program xyz should output 3.
The program ABCxyz should output 13.
The program xyzABC should output 7.
The program ABCABCABC should output 30.
The program ABCABCxyzxyzABCxyzxyzABC should output 40, since
[10, 10, 3, 3, 10, 3, 3, 10] => 10 + 10 + 3 + (10-3) + 3 + (10-3) = 40

Additionally, if \$F(8)\$ outputs the code fragment ****:

The program ABC****xyz should output 10 + 8 + 3 = 21.
The program ****ABCxyz should output (10-8) + 3 = 5.
The program xyz********ABC should output (8-3) + (10-8) = 7.
You do not need to consider the program xyz****ABC, which contains three consecutive strictly increasing numbers (3, 8, 10).

Bash, 54 48 bytes
-6 bytes by adapting Dominic van Essen's output-prevention trick
printf ":|:
((s+=p<$1?$1-2*p:$1))
p=$1
echo \$s"

This assumes the program must not have any excess output, which turns out to be one of the tricker parts. I expect one of the golfing languages that will output by default at the end of the program would do best here.
Try it online!
Explanation
Example output for 3 concatenated with output for 10 (the concatenated program outputs 7):
:|:
((s+=p<3?3-2*p:3))
p=3
echo $s:|:
((s+=p<10?10-2*p:10))
p=10
echo $s

:|: prevents any echo from a previous fragment from outputting
s is the sum value so far (implicitly 0 at the start of the program)
p is the previous value

Each fragment assumes that the current value is not less than the next value, and thus adds it to the sum. It also checks whether the previous fragment was wrong to assume this (ie. the previous value was less than the current value), and if so corrects the sum by subtracting double the previous value.


Chunk + Enumerate a list of digits I have a list of decimal digits:

4, 4, 4, 7, 7, 9, 9, 9, 9, 2, 2, 2, 4, 4

The list of decimal digits are known as items. We can form "chunks" from these items by grouping together identical and adjacent numbers. I want to assign each chunk a unique number, starting from 1, and increasing by 1 in the order the chunks appear in the original list. So, the output for the given example would look like this:

1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5

Input format

A list of digits. (0-9) You may use your language built-ins to read this list however you want. Encoding: ASCII

Output format

A series of decimal numbers, separated by a delimiter. Your program must always use the same delimiter. The delimiter must be longer than 0 bits. Encoding: ASCII

Standard loopholes apply.

Python 3.8 (pre-release), 41 bytes

lambda l,n=0:[n:=n+(l!=(l:=x))for x in l]

Try it online!

Praise the magic walrus := of assignment expressions.

Python 2, 42 bytes

n=0
for x in input():n+=x!=id;id=x;print n

Try it online!


Implement true string addition Many languages allow strings to be "added" with +.  However this is really concatenation, a true addition would follow the group axioms:

It is closed (the addition of any two strings is always a string)
It is associative ( (a + b) + c = a + (b + c))
There is an identity (∃e : a + e = a)
Every element has an inverse (∀a : ∃b : a + b = e)

(concatenation violates the 4th group axiom)

So my task to you is to implement a true string addition, that is a function that takes two sequences of bytes representing strings and returns a third such that your function satisfies all the group axioms on sequences of  bytes.

It must work on all sequence of bytes representing strings including those with null bytes.

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

Python 3, 177 170 163 130 bytes

lambda a,b:s(d(a)^d(b))
def s(n,x=0,s=''):
 while n:n-=1;s+=chr(n%256);n>>=8
 return s
def d(n,c=0):
 while s(c)!=n:c+=1
 return c

Try it online!

-14 bytes thanks to notjagan

-33 bytes thanks to Leaky Nun (and switched endianness)

I have no business trying to golf anything in Python, but I didn't want to use Lua since this method needs large exact integers to work on reasonable length stings. (Note: the algorithm is still Really Slow when ramping up the string length.) This is mostly just to provide an answer ;)

Each string is self-inverse, and the empty string is the identity. This simply performs xor under a simple bijection between strings and non-negative integers. s is a helper function that computes the bijection (one way only), and d is the inverse.

Non-slow version (148 bytes, courtesy of Leaky Nun):

lambda a,b:s(d(a)^d(b))
def s(n,x=0,s=''):
 while n:n-=1;s=chr(n%256)+s;n>>=8
 return s
def d(n,c=0):
 while n:c=c*256+ord(n[0])+1;n=n[1:]
 return c

Try it online!

I'm going to hijack this for a group-theory primer as well.

Any right inverse is a left inverse: inv(a) + a = (inv(a) + a) + e = (inv(a) + a) + (inv(a) + inv(inv(a))) = inv(a) + (a + inv(a)) + inv(inv(a)) = (inv(a) + e) + inv(inv(a)) = inv(a) + inv(inv(a)) = e

This also means that a is an inverse of inv(a).

Any right identity is a left identity: e + a = (a + inv(a)) + a = a + (inv(a) + a) = a

The identity is unique, given other identity f: e = e + f = f

If a + x = a then x = e: x = e + x = (inv(a) + a) + x = inv(a) + (a + x) = inv(a) + a = e

Inverses are unique, if a + x = e then: x = e + x = (inv(a) + a) + x = inv(a) + (a + x) = inv(a) + e = inv(a)

Following the proofs should make it fairly easy to construct counterexamples for proposed solutions that don't satisfy these propositions.

Here's a more natural algorithm I implemented (but didn't golf) in Lua. Maybe it will give someone an idea.

function string_to_list(s)
  local list_val = {}
  local pow2 = 2 ^ (math.log(#s, 2) // 1) -- // 1 to round down
  local offset = 0
  list_val.p = pow2
  while pow2 > 0 do
    list_val[pow2] = 0
    if pow2 & #s ~= 0 then
      for k = 1, pow2 do
        list_val[pow2] = 256 * list_val[pow2] + s:byte(offset + k)
      end
      list_val[pow2] = list_val[pow2] + 1
      offset = offset + pow2
    end
    pow2 = pow2 // 2
  end
  return list_val
end

function list_to_string(list_val)
  local s = ""
  local pow2 = list_val.p
  while pow2 > 0 do
    if list_val[pow2] then
      local x = list_val[pow2] % (256 ^ pow2 + 1)
      if x ~= 0 then
        x = x - 1
        local part = ""
        for k = 1, pow2 do
          part = string.char(x % 256) .. part
          x = x // 256
        end
        s = s .. part
      end
    end
    pow2 = pow2 // 2
  end
  return s
end

function list_add(list_val1, list_val2)
  local result = {}
  local pow2 = math.max(list_val1.p, list_val2.p)
  result.p = pow2
  while pow2 > 0 do
    result[pow2] = (list_val1[pow2] or 0) + (list_val2[pow2] or 0)
    pow2 = pow2 // 2
  end
  return result
end

function string_add(s1, s2)
  return list_to_string(list_add(string_to_list(s1), string_to_list(s2)))
end

The idea is basically to split the string based on the power-of-two components of its length, and then treat these as fields with a missing component representing zero, and each non-missing component representing numbers from 1 up to 256^n, so 256^n+1 values total. Then these representations can be added component-wise modulo 256^n+1.

Note: This Lua implementation will have numeric overflow problems for strings of sizes greater than 7. But the set of strings of length 7 or less is closed under this addition.

Try it online!


Recursion bracketed; or Dyck words generation We already have challenges to check if a string of brackets is fully matched and to count the number of balanced strings. It remains for us to generate these strings, but it will not be so easy…

A Dyck word is a string, of length 2n, consisting of n opening and n closing parentheses (( and )) fully matched (that is to say: for all prefixes of the string, the number of opening parentheses is greater than or equal to the number of closing ones).

It is interesting to note that the number of different Dyck words of length 2n is equal to the (n + 1)-th Catalan number.

It’s pretty straightforward to write a program that generates these words with a recursive function. But the goal here is to do the same thing without.

Challenge

Write a full program or function that takes a positive integer, n, using stdin or an acceptable alternative, and outputs all the different Dyck words of length 2n. The words can appear in any order and each must be separated from each other by a line break. Moreover, your program should not use recursive functions (see details below).

Rules

The output of your program should only contain Dyck words of length 2n, separated by line breaks. Each word must appear only once.
Your program must work at minimum for inputs 0 to 15.
You may not write recursive functions, neither direct (a function that calls itself) nor indirect (e.g. a function f that calls another function g that calls function f). That being said, you can still use the standard functions of your language without worry of how they work internally.
Similarly, your program should not call itself.
You may not use non-standard librairies.
Your program may not read or write files.
Your program must be able to run in a reasonable time for 0 ≤ n ≤ 15 (hence, naively generate all arrangements is probably not a good idea). Let’s say less than 20 minutes with a memory limit of 4 GB (my reference implementation in C manages n = 15 in less than 5 seconds).
All standard loopholes are forbidden.

As usual in code-golf, the shortest code in bytes wins. But if you have found an interesting way to achieve this challenge in your language, please do not hesitate.

Test I/O

For this input:

3

The output could be (any other order is correct too):

((()))
()()()
(()())
(())()
()(())

C99, 105 bytes

i,j,s;f(n){for(char a[31]={};++i%(1<<2*n);s||puts(a))for(j=s=0;~s&&j<2*n;)s+=1-(a[j]=40+(i>>j++)%2)%2*2;}

Iterates over all strings of 2n parentheses.

With piped output and compiler flag -O3, input n = 15 takes roughly 15.5 seconds on my machine. Memory consumption is 1.2 MB.

Test it on Ideone.


Pascal's Fibonacci Triangle What do you get when you cross Pascal's Triangle and the Fibonacci sequence? Well, that's what you have to find out!
Task
Create a triangle that looks like this:
          1
        1   1
       2  2  2
    3   5  5   3
  5  10  14  10  5
8  20  32  32  20  8

Basically, instead of each cell being the sum of the cells above it on the left and right, you also need to add the cell on the left above the cell on the left and the cell on the right above the cell on the right.
This is A036355.
You may choose to do one of the following:

Output the \$n\$th row (indexed as you wish)
Output the first \$n\$ rows
Output all rows infinitely

Rules

Each row may be represented as a string separated by some character that is not a digit or an ordered collection of numbers. You do not need to align the triangle like I did in the example.
If you choose to output multiple rows, you need either an ordered list of rows, or a string that uses a different separator than the one you use within rows.
Please specify which task you chose in your answer, along with the input (if applicable) and output format.
You can receive input and output through any of the standard IO methods.
This is code-golf, so shortest code in bytes wins!

Bounty
As Scala is the language of the month, I will be giving a 50 rep bounty for any Scala answers to this question (not just if you're a first-time user). If multiple Scala answers are posted, I will be happy to put a bounty on a different Scala answer of yours instead.

Python 2, 73 72 69 bytes
-1 byte thanks to dingledooper!
-3 bytes thanks to Sisyphus!
Prints the rows indefinitely.

c=a=[0]
b=[1]
while 1:print b;a,b=b,map(sum,zip(c*2+a,a+c*2,c+b,b+c))

Try it online!


What's the day today (or other dates)? Task

Write a program or a function that calculates a week-day name of a date which a user inputs.

Input & Output

Input is a string, YYYYMMDD.

Example of input values:

20110617 : June 17, 2011
19040229 : February 29, 1904
06661225 : December 25, 666
00000101 : January 1, 0
99991231 : December 31, 9999

You may assume that all inputs are valid. Note that year zero is valid.

Output is an integer between 0 and 6. Each integer represents a week-day name. You can decide freely which integer represents a week-day name, like this one

0 : Monday
1 : Tuesday
2 : Wednesday
...
6 : Sunday

(in order) or this one

0 : Monday
1 : Wednesday
2 : Sunday
...
6 : Saturday

(not in order).

Test Cases

Input     Week-day   Output ([0..6 -> Monday..Sunday] is used in this example.)

20110617  Friday     4
19500101  Sunday     6
22220202  Saturday   5
19000228  Wednesday  2
19000301  Thursday   3
19450815  Wednesday  2
19040229  Monday     0
19040301  Tuesday    1
17760704  Thursday   3
20000228  Monday     0
20000229  Tuesday    1
20000301  Wednesday  2
20121223  Sunday     6
00000401  Saturday   5
66660606  Wednesday  2
59161021  Saturday   5

Restriction

You must not use any kind of function/class/... which are related to timestamp or date, like Date class in Java/JavaScript/ActionScript, or getdate function in PHP.

You should use Gregorian calender, which is used by many people now.

Of course, shortest code wins. If two code have same length, then the code with highest votes wins.

(Due: When there's more than 5 codes which has more than (or equal) +1 votes.)

PHP - 101 97 103 125 characters

Sakamoto Algorithm
0 = Sunday

Code
<?php fscanf(STDIN,"%4d%2d%2d",$y,$m,$d);@$a=a032503514624;$y-=$m<3;$z=$y+1;echo($y+$y/4%$z-$y/100%$z+$y/400%$z+$a[$m]+$d)%7;

Note
Unfortunately, due to PHP's dynamic, weak typing, the Sakamoto algorithm doesn't function properly without explicitly flooring each division operation.


Convert number to a base where its representation has most "4"s Inspired by this. There is a number, given as either integer, string or array of digits (your choice). Find the base in which the representation of the number will have most "4"s and return that base.

Number    Result
624        5
444       10
 68       16

restrictions:

The base returned should not be greater than the input.
numbers less than or equal to abs(4) should not be considered valid input, so undefined returns are acceptable

APL (31 19)

Now tests all possible bases.

⊃⍒{+/4=K⊤⍨K⍴⍵}¨⍳K←⎕

Explanation:

⍳K←⎕: read user input, store in K. Make a list from 1 to K, which are the bases to try.
{...}¨: for each of these, run the following function
K⊤⍨K⍴⍵: encode K into that base giving a list of digits (as numbers) per base. Use K digits (a big overestimate, but it doesn't matter because the unused ones will all be zero anyway).
4=: see which of these are equal to 4
+/: sum these, now we know how many fours per base
⊃⍒: give the indices of the list if it were sorted downwards, so the index of the biggest one is at the front. Take the first item of this list.


Python 2, 61 51 bytes

lambda n:sorted({~(i%n)*~(i/n)for i in range(n*n)})

Thanks to xnor for shortening some syntax.


Define a field with 256 elements A field in mathematics is a set of numbers, with addition and multiplication operations defined on it, such that they satisfy certain axioms (described in Wikipedia; see also below).

A finite field can have pn elements, where p is a prime number, and n is a natural number. In this challenge, let's take p = 2 and n = 8, so let's make a field with 256 elements.

The elements of the field should be consecutive integers in a range that contains 0 and 1:

-128 ... 127
0 ... 255
or any other such range

Define two functions (or programs, if that is easier), a(x,y) for abstract "addition", and m(x,y) for abstract "multiplication", such that they satisfy the field axioms:

Consistency: a(x,y) and m(x,y) produce the same result when called with same arguments
Closedness: The result of a and m is an integer in the relevant range
Associativity: for any x, y and z in the range, a(a(x,y),z) is equal to a(x,a(y,z)); the same for m
Commutativity: for any x and y in the range, a(x,y) is equal to a(y,x); the same for m
Distributivity: for any x, y and z in the range, m(x,a(y,z)) is equal to a(m(x,y),m(x,z))
Neutral elements: for any x in the range, a(0,x) is equal to x, and m(1,x) is equal to x
Negation: for any x in the range, there exists such y that a(x,y) is 0
Inverse: for any x≠0 in the range, there exists such y that m(x,y) is 1

The names a and m are just examples; you can use other names, or unnamed functions. The score of your answer is the sum of byte-lengths for a and m.

If you use a built-in function, please also describe in words which result it produces (e.g. provide a multiplication table).

Python 2, 11 + 45 = 56 bytes

Addition (11 bytes):

int.__xor__

Multiplication (45 bytes):

m=lambda x,y:y and m(x*2^x/128*283,y/2)^y%2*x

Takes input numbers in the range [0 ... 255]. Addition is just bitwise XOR, multiplication is multiplication of polynomials with coefficients in GF2 with Russian peasant.

And for checking:

a=int.__xor__
m=lambda x,y:y and m(x*2^x/128*283,y/2)^y%2*x

for x in range(256):
    assert a(0,x) == a(x,0) == x
    assert m(1,x) == m(x,1) == x

    assert any(a(x,y) == 0 for y in range(256))

    if x != 0:
        assert any(m(x,y) == 1 for y in range(256))

    for y in range(256):
        assert 0 <= a(x,y) < 256
        assert 0 <= m(x,y) < 256
        assert a(x,y) == a(y,x)
        assert m(x,y) == m(y,x)

        for z in range(256):
            assert a(a(x,y),z) == a(x,a(y,z))
            assert m(m(x,y),z) == m(x,m(y,z))
            assert m(x,a(y,z)) == a(m(x,y), m(x,z))


1, 2, 3, 14... or is it 15? A well known song by the Irish rock band U2 starts with the singer Bono saying "1, 2, 3, 14" in Spanish ("uno, dos, tres, catorce").

There are various theories as to the significance of those numbers. Apparently the official explanation is "we drank too much that night". But there's a more interesting hypothesis: Bono is referring to some integer sequence from OEIS, such as

A107083:

  Integers k such that 10^k + 31 is prime.
  1, 2, 3, 14, 18, 44, 54, ...

In an interview, when asked the inevitable question "why 14", Bono admitted he was a bit tired of that number. The journalist suggested "15" instead, and in that night's concert the lyrics were indeed changed into "1, 2, 3, 15". (The story can be read here, in Spanish). Quite likely the journalist took inspiration from

A221860:

  Indices k such that prime(k) - k is a power of 2, where prime(k) is the k-th prime.
  1, 2, 3, 15, 39, 2119, 4189897, ...

The challenge

Write two programs in the same language. The first should take an input n and output the n-th term of A107083, or the first n terms. Similarly, the second should output the n-th term of A221860, or the first n terms.

The score is the sum of lengths of the two programs, in bytes, plus the square of the Levenshtein distance between the byte representations of the two programs.

If a character encoding is used such that each character corresponds to one byte, this script can be used to measure Levenshtein distance.

For example, if the two programs are abcdefgh and bcdEEfg, the score is 8 + 7 + 4^2 = 31.

Lowest score wins.

Aditional rules

The output can be 1-based or 0-based, independently for each sequence (so it is allowed if one of the programs is 1-based and the other is 0-based).
Each program can, consistently but independently of the other, either output the n-th term or the first n terms.
Programs or functions are allowed, independently for each sequence.
Input and output means and format are flexible as usual. Standard loopholes are forbidden.

Jelly, 16 + 16 + 1² = 33

A107083

⁵*+31ÆḍÆNB>/
1Ç#

Try it online!

A221860

⁵*+31ÆạÆNB>/
1Ç#

Try it online!

How it works

1Ç#           Main link. Argument: n

1             Set the return value to 1.
 Ç#           Call the helper link with arguments k, k + 1, k + 2, ... until n of
              them return a truthy value. Return the array of n matches.

⁵*+31ÆḍÆNB>/  Helper link. Argument: k

⁵*            Yield 10**k.
  +31         Yield 10**k + 31.
     Æḍ       Count the proper divisors of 10**k + 31.
              This yields c = 1 if 10**k + 31 is prime, an integer c > 1 otherwise.
       ÆN     Yield the c-th prime.
              This yields q = 2 if 10**k + 31 is prime, a prime q > 2 otherwise.
         B    Binary; yield the array of q's digits in base 2.
          >/  Reduce by "greater than".
              This yields 1 if and only if the binary digits match the regex /10*/,
              i.e., iff q is a power of 2, i.e., iff 10**k + 31 is prime.

⁵*+31ÆạÆNB>/  Helper link. Argument: k

     Æ        Unrecognized token.
              The token, as well as all links to its left, are ignored.
       ÆN     Yield p, the k-th prime.
      ạ       Take the absolute difference of k and p, i.e., p - k.
         B    Binary; yield the array of (p - k)'s digits in base 2.
          >/  Reduce by "greater than".
              This yields 1 if and only if the binary digits match the regex /10*/,
              i.e., iff p - k is a power of 2.


Recreate the classic snake Game The challenge is to create the classic Snake game using as few bytes as possible.

Here are the requirements:

The game must be implemented in a typical 2-dimensional layout. The snake should be able to grow significantly within the bounds of the map (this really means, don't make your map too small, use your discretion here).
A user may move the snake using keys of your choosing, however, the snake cannot double back on itself (e.g. if it is going West it cannot go East without first going North or South). A snake ought to be able to travel in all 4 directions: up, down, left, right (North, South, West, East).
Snake starts off as length 1, each time it eats a "food" object it grows +1 in length
Food objects are randomly placed in locations other than those occupied by the snake
If the Snake hits itself or a wall the game is ended
When the game has been ended the literal "Score: [score]" is displayed where [score] is the number of food items eaten during the game. So, for example, if the snake has eaten 4 "foods" (and therefore has a length of 5) when the game ends, "Score: 4" will be printed.
No compression algorithms unless they are explicitly defined in your code.

Here's my solution, 908 Bytes, Python 2.7

import random as r
import curses as c
def g(s,w,l):
 while 1:
  p=[r.randrange(0,w),r.randrange(0,l)]
  for l in s:
   if l==p:continue
  return p
s=[]
d=[0,1]
p=k=n=0
e=100
v={65:[-1,0],66:[1,0],68:[0,-1],67:[0,1]}
z=c.initscr()
w,l=z.getmaxyx()[0],z.getmaxyx()[1]
c.noecho()
z.clear()
x=g(s,w,l)
s.append([w/2,l/2])
z.nodelay(1)
q=lambda h,i:range(h,len(i))
while k!=101:
 k=z.getch()
 if k in v and not (d[0]==(v[k][0]*-1) and d[1]==(v[k][1]*-1)):d=v[k]
 f=[0,0]
 for i in q(0,s):
  if i == 0:
   f=[s[i][0],s[i][1]]
   s[i][0]+=d[0]
   s[i][1]+=d[1]
  else:s[i],f=f,s[i]
 if s[0]==x:
  n+=1
  s.append(f)
  x=g(s,w,l)
 z.clear()
 if s[0][0]>=w or s[0][1]>=l or s[0][0]<0 or s[0][1]<0:break
 for i in q(1,s):
  if s[0] == s[i]: k = 101
 for i in q(0,s):z.addch(s[i][0],s[i][1],"X")
 z.addch(x[0],x[1],"O")
 z.move(0,0)
 z.refresh()
 if d[1]!=0:c.napms(e/2)
 else:c.napms(e)
c.endwin()
print 'Score: %s'%n

Ruby 1.9 + SDL (341 324 316)

Here's a first attempt at a Ruby version using the SDL library.  I can save 6 characters if I'm allowed to load the SDL library using -rsdl on the command line instead of the require statement.

require'sdl'
f=o=d=3
s=SDL::Screen.open l=32,l,0,0
r=*0..l*l
loop{f==o ?f=(r-$*).sample: $*.shift
/yU/=~"#{e=SDL::Event.poll}"&&(v=e.sym%4)&&d+v!=3&&d=v
$><<"Score #{$*.size}"&&exit if$*.index(n=o+[-1,-l,l,1][d])||n<0||n>=l*l||d%3<1&&n/l!=o/l
$*<<o=n
r.map{|i|s[i%l,i/l]=[[f,*$*].index(i)?0:255]*3}
s.flip
sleep 0.1}

The snake segments and food pieces are represented using black pixels, the grid size is currently 32*32.  You can control with the arrow keys (or any keys really, the keycode mod 4 indexes the direction array [LEFT, UP, DOWN, RIGHT]).  I think there's definitely room for improvement here, especially in the death-checking IF statement.

I've vastly improved this over the previous version, hopefully it more closely matches the spirit of the question now.  There's one thing I need to fix to comply with the spec, which is that food can currently spawn inside the tail. Fixed!

Prints the score to stdout after the game is completed.


Let's make Diet Haskell Haskell has tuples that can be written as

(a,b,c)

However this is just syntactic sugar for

(,,)a b c

In general an n tuple can be formed with n-1 ,s between (...) followed by its elements separated by spaces.  For example the 7-tuple, (1,2,3,4,5,6,7) can be formed by

(,,,,,,)1 2 3 4 5 6 7

Since Haskell does not have 1-tuples they cannot be formed.  You will also not be held responsible for empty tuples.

Nested tuples can be formed using parens to override the order of operations.

((1,2),3) == (,)((,)1 2)3

As part of our pursuit to remove all syntactic sugar from Haskell  I am going to ask you to write a program that removes syntactic sugar from Haskell's tuples as well.

Your program should take a tuple, an array, or a string representing a sugary tuple and should output a string representing a "sugar-free" tuple.  Input tuples will only ever contain positive integers or other tuples.

Since we are golfing here your output should be short.  It should not contain unnecessary

Spaces.  Spaces should be used only to separate arguments of a tuple functions and should not appear after a ) or before a (
Parentheses.  Parentheses should be used only when forming tuple functions or when nesting tuples.

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

Test cases

(1,2)     -> (,)1 2
(1,2,3)   -> (,,)1 2 3
((1,2),3) -> (,)((,)1 2)3
(1,2,3,4) -> (,,,)1 2 3 4
(1,(2,3)) -> (,)1((,)2 3)
(10,1)    -> (,)10 1

Haskell, 169 148 bytes

init.tail.fst.([]%)
p:k="(,"
l%('(':r)|(y,x:s)<-[]%r,m<-y:l=last$m%(p:s):[(p:p:(l>>k)++x:foldl(\r x->x++[' '|x>k,r>k]++r)[x]m,s)|x<',']
l%r=lex r!!0

Try it online! Takes the tuple as a string. init.tail.fst.([]%) is the anonymous main function. Bind it to e.g. f and use like f "(3,(14,1),4,7)", which yields "(,,,)3((,)14 1)4 7".

Why is the input not provided as a Haskell tuple, you ask? Because Haskell is strongly typed, a tuple (1,2) has type (Int,Int)1 and a tuple (1,(2,3)) has type (Int,(Int,Int)). Thus a function which accepts the first kind of tuple can not be applied to the second kind, and especially there can be no function which takes an arbitrary tuple2.

Explanation:

p:k="(," is a short way to assign p to '(' and k to ",".
(%) is the recursive parsing and converting function. The first argument is a list of already parsed tuple entries, the second argument is the remainder of the original string. Each call returns a tuple of the current converted tuple (as a string and enclosed in brackets) and the remainder of the string.

l%('(':r) If the string starts with an opening bracket, we need to parse a new tuple entry.
(y,x:s)<-[]%r We recursively apply % and get a tuple entry y and the remaining string splitted into the next character x and the rest of the string s.
m<-y:l We add the new entry y to the current list of already found entries l and call the result m.
The next character x is now either a comma , or a closing bracket ). The last$ <B> :[ <A> |x<','] is just a shorter way of writing if x == ')' then <A> else <B>.
So if a , is next, we need to recursively parse the next entry: m%(p:s) We prepend an opening bracket in order to end up in the right case and pass the list of already found entries m.
If otherwise x == ')', we finished the current tuple and need to do the required transformation: (p:p:(l>>k)++x:foldl(\r x->x++[' '|x>k,r>k]++r)[x]m,s)

p:p:(l>>k)++x: If we have found n entries, then m has n elements and y, the list before adding the most recently found element, has n-1 entries. This comes in handy as we need n-1 , for an n element tuple and l>>k works on lists as "concatenate the list k with itself as many times as y has elements". Thus this first part yields some string like "((,,,)".
foldl(\r x->x++[' '|x>k,r>k]++r)[x]m concatenates the elements of m (in reverse order, because by adding new entries to the front m itself was constructed in reverse order) while adding only spaces in between two elements if they are both numbers: [' '|x>k,r>k] we check if the current entries x and r are numbers by lexicographically comparing them to "," - if they are not numbers, they are already a tuple representation enclosed in brackets, and '(' < ',' holds.

If the pattern match l%('(':r) right at the beginning fails, then we end up on the last line: l%r=lex r!!0. This means we need to parse a number and return the number and the remainder of the string. Luckily there is the lex function which does exactly that (It parses the next valid Haskell token, not just numbers). However the resulting tuple is wrapped into a list, so we use !!0 to get the first element of the list.

init.tail.fst.([]%) is the main function which takes a string and applies % with an empty list to it. E.g. for an input "(1,2)", , applying ([]%) yields ("((,)1 2)",""), so the outer tuple and brackets need to be removed. fst gets the first element of the tuple, tail removes the closing bracket and init the opening one.

Edit: Many thanks to @Ørjan Johansen for golfing a total of 21 bytes!

1 Actually, the type is (Num t1, Num t) => (t, t1), but that's a diferent story.

2 Ignoring polymorphic functions like id, which cannot actually work with their input.


Quiz Program Compiler A fun programming exercise is to write a program that quizzes the user from a set list of questions and answers. However, this task goes a level beyond that.

Your task

Write a program/func/etc. that takes two lists: A list of questions and a list of answers.
Output a program that quizzes the user.
The output program should ask each question on a separate line, which each question with a colon and space at the end like, What is 2+2:.
After the user answers all the questions, output a newline, and then one on each line, questions correct, questions wrong, and percentage calculation (rounded to 2 decimal places) as such (the brackets are user input):

What is the meaning of life, the universe, and everything: <42>
Am I awesome(Yes/No): <No>
What is 2+2: <4>

Number Correct: 2
Number Wrong: 1
Score: 2 / 3 * 100 = 66.67%

Scoring

You are scored on the size of your compiler program.
This is code-golf so shortes code in bytes wins!
Bonus: Score *.9 if you implement a flag in your compiler that makes the output program randomize question order.

CJam, 105 99 bytes

{{": "+ol}%.=_:+\,:LX$-X$LX$e2Ld/]"
Number Correct: %d
Number Wrong: %d
Score: %d / %d * 100 = %.2f%%"e%}

This defines an anonymous function.

The code is 110 bytes long and qualifies for the × 0.9 randomization bonus.

Test run

$ cat qna.cjam
[
  [
    "42"
    "Yes"
    "4"
  ]

  [
    "What is the meaning of life, the universe, and everything"
    "Am I awesome(Yes/No)"
    "What is 2+2"
  ]
]

{zmrz~{": "+ol}%.=_:+\,:LX$-X$LX$e2Ld/]"
Number Correct: %d
Number Wrong: %d
Score: %d / %d * 100 = %.2f%%"e%}

~

$ cjam qna.cjam
What is 2+2: 4
Am I awesome(Yes/No): No
What is the meaning of life, the universe, and everything: 42

Number Correct: 2
Number Wrong: 1
Score: 2 / 3 * 100 = 66.67%


Find the shortest route on an ASCII road You want to find the length shortest path between two points, on an 2d ASCII "map". The roads are made up of + characters, and the two endpoints are represented by #s (not counted in the length). This road can be arranged in any way, and any other characters can be ignored. You can assume the endpoints will always connect to each other through roads.

Examples:

Output: 1

#+#

Output: 5

   #+
+   +
++++++
   +
   #

Output: 8

++++#+++
+      +
+      +
++#+++++

Output: 4

#+++
++++
+++#

Output: 2

+++++
+   +
+#  +
+++#+
   +
 +++

Undefined output:

##

#   +++#
+    +

#+++#
    +
    +
    #

#++
  +

Rules:

You can take input as a 2d array, matrix, string separated by newlines, etc.
Output should be a number
Can be a snippet, function, or full program
You can represent one endpoint with a different character if necessary

Python 3, 163 bytes

def f(g,s=[]):w=len(g[0])+1;k=' '.join(g)+w*' ';*p,x=s or[k.find('#')];return' '<k[x]and{x}-{*p}and[min(f(g,s+[x+a])or len(k)for a in(-1,1,-w,w)),len(p)]['+'<k[x]]

Try it online!

Uses # for start and @ for end. Finds all paths along + and returns the shortest. Each path ends when either a space is encountered, the range is outside the box or a previous position is visited.


My daughter's alphabet The other day we were writing sentences with my daughter with a fridge magnet letter. While we were able to make some(I love cat), we didn't have enough letters to make the others (I love you too) due to an insufficient amount of letters o (4)

I then found out that while one set included 3 e letters it had only 2 o letters. Probably inspired by http://en.wikipedia.org/wiki/Letter_frequency this would still not reflect the actual situation "on the fridge".

Problem

Given the text file where each line contains a "sample sentence" one would want to write on the fridge, propose an alphabet set with minimum amount of letters but still sufficient to write each sentence individually.

Note: ignore cases, all magnet letters are capitals anyway.

Input

The file contain newline separated sentences:

hello
i love cat
i love dog
i love mommy
mommy loves daddy

Output

Provide back sorted list of letters, where each letter appears only as many times to be sufficient to write any sentence:

acdddeghillmmmoostvyy

(thanks, isaacg!)

Winner

Shortest implementation (code)

UPDATED: Testing

I have created an extra test and tried with various answers here:

https://gist.github.com/romaninsh/11159751

GolfScript, 28 / 34 chars

n/:a{|}*{a{.[2$]--}%*$-1=}%$

The 28-character program above assumes that all the input letters are in the same case.  If this is not necessarily so, we can force them into upper case by prepending {95&}% to the code, for a total of 34 chars:

{95&}%n/:a{|}*{a{.[2$]--}%*$-1=}%$

Notes:

For correct operation, the input must include at least one newline.  This will be true for normal text files with newlines at the end of each line, but might not be true if the input consists of just one line with no trailing newline.  This could be fixed at the cost of two extra chars, by prepending n+ to the code.
The uppercasing used in the 34-character version is really crude — it maps lowercase ASCII letters to their uppercase equivalents (and spaces to NULs), but makes a complete mess of numbers and most punctuation.  I'm assuming that the input will not include any such characters.
The 28-character version treats all input characters (except newlines and NULs) equally.  In particular, if the input contains any spaces, some will also appear in the output; conveniently, they will sort before any other printable ASCII characters.  The 34-character version, however, does ignore spaces (because it turns out I can do that without it costing me any extra chars).

Explanation:

The optional {95&}% prefix uppercases the input by zeroing out the sixth bit of the ASCII code of each input byte (95 = 64 + 31 = 10111112).  This maps lowercase ASCII letters to uppercase, spaces to null bytes, and leaves newlines unchanged.
n/ splits the input at newlines, and :a assigns the resulting array into the variable a.  Then {|}* computes the set union of the strings in the array, which (assuming that the array has at least two elements) yields a string containing all the unique (non-newline) characters in the input.
The following { }% loop then iterates over each of these unique characters.  Inside the loop body, the inner loop a{.[2$]--}% iterates over the strings in the array a, removing from each string all characters not equal to the one the outer loop is iterating over.

The inner loop leaves the ASCII code of the current character on the stack, below the filtered array.  We make use of this by repeating the filtered array as many times as indicated by the ASCII code (*) before sorting it ($) and taking the last element (-1=).  In effect, this yields the longest string in the filtered array (as they all consist of repeats of the same character, lexicographic sorting just sorts them by length), except if the character has ASCII code zero, in which case it yields nothing.
Finally, the $ at the end just sorts the output alphabetically.


Print a Wavy String Line-by-Line Challenge
Write a program or function that takes in a string s and integer n as parameters. Your program should print (or return) the string when transformed as follows:
Starting in the top-left and moving down and to the right, write s as a wave of height n. Then, from top to bottom, combine each row as a string (without spaces).
Example
Given the string "WATERMELON" and a height of 3:
The wave should look like this:
W   R   O
 A E M L N
  T   E

Then, combine the rows from top to bottom:
WRO
AEMLN
TE

So, your program should return the string "WROAEMLNTE"
Likewise, "WATERMELON" with height 4 should produce the following wave:
W     E
 A   M L
  T R   O
   E     N

Your program should then return the string "WEAMLTROEN"
Rules
Input
Input can be taken in any reasonable format. The string can be in any case you prefer. You may assume that 0 < n <= s.length
Output
Output should consist only of the transformed string (whether returned or printed to STDOUT), plus any trailing newlines.
Scoring
This is code-golf, so shortest answer in bytes wins! Standard loopholes are not allowed.
Test Cases
Input                        Output

programmingpuzzles, 5 ->     piermnlsomgzgapzru
codegolf, 3           ->     cgoeofdl
elephant, 4           ->     enlatehp
1234567, 3            ->     1524637
qwertyuiop, 1         ->     qwertyuiop

MATL, 16 bytes

Zv3L)t?yn:)2$S}i

Try it online! Or verify all test cases.

Explanation

Consider inputs 5, 'programmingpuzzles'.

Zv     % Input, implicit: number n. Symmetric range
       % STACK: [1 2 3 4 5 4 3 2 1]
3L     % Push [1 -1+1j]. When used as an index, this means 1:end-1
       % STACK: [1 2 3 4 5 4 3 2 1], [1 -1+1j]
)      % Index. Removes last element
       % STACK: [1 2 3 4 5 4 3 2]
t      % Duplicate
       % STACK: [1 2 3 4 5 4 3 2], [1 2 3 4 5 4 3 2]
?      %   If non-empty and non-zero
       %   STACK: [1 2 3 4 5 4 3 2]
  y    %   Implict input: string s. Duplicate from below
       %   STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2], 'programmingpuzzles'
  n    %   Number of elements
       %   STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2], 18
  :    %   Range
       %   STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2], [1 2 3 ··· 17 18]
  )    %   Index modularly
       %   STACK: 'programmingpuzzles', [1 2 3 4 5 4 3 2 1 2 3 4 5 4 3 2 1 2]
  2$S  %   Two-input sort: stably sorts first input as given by the second
       %   STACK: 'piermnlsomgzgapzru'
}      % Else. This branch is entered when n=1. The stack contains an empty array
       %   STACK: []
  i    %   Take input
       %   STACK: [], [], 'programmingpuzzles'
       % End, implicit
       % Display stack, implicit. Empty arrays are not displayed


Triangular Manhattan Distance The Manhattan distance on a regular grid is the number of orthogonal steps one needs to take to reach one cell from another. Orthogonal steps are those that go through the edges of the grid cells (as opposed to the corners, which would give us the Chebyshev distance).
We can define a similar distance on other grids, for example the triangular grid. We can address the individual cells in the grid with the following indexing scheme, where each cell contains an x,y pair:
    ____________________________________...
   /\      /\      /\      /\      /\
  /  \ 1,0/  \ 3,0/  \ 5,0/  \ 7,0/  \
 / 0,0\  / 2,0\  / 4,0\  / 6,0\  / 8,0\
/______\/______\/______\/______\/______\...
\      /\      /\      /\      /\      /
 \ 0,1/  \ 2,1/  \ 4,1/  \ 6,1/  \ 8,1/
  \  / 1,1\  / 3,1\  / 5,1\  / 7,1\  /
   \/______\/______\/______\/______\/___...
   /\      /\      /\      /\      /\
  /  \ 1,2/  \ 3,2/  \ 5,2/  \ 7,2/  \
 / 0,2\  / 2,2\  / 4,2\  / 6,2\  / 8,2\
/______\/______\/______\/______\/______\...
\      /\      /\      /\      /\      /
 \ 0,3/  \ 2,3/  \ 4,3/  \ 6,3/  \ 8,3/
  \  / 1,3\  / 3,3\  / 5,3\  / 7,3\  /
   \/______\/______\/______\/______\/___...
   /\      /\      /\      /\      /\
  .  .    .  .    .  .    .  .    .  .
 .    .  .    .  .    .  .    .  .    .

Now the Manhattan distance on this grid is again the minimal number of steps across edges to get from one cell to another. So you can move from 3,1 to 2,1, 4,1 or 3,2, but not to any other triangle, since those would be crossing points rather than edges.
For instance, the distance from 2,1 to 5,2 is 4. The shortest path is generally not unique, but one way to make the distance in 4 steps is:
2,1 --> 3,1 --> 3,2 --> 4,2 --> 5,2

The Challenge
Given two coordinate pairs x1,y1 and x2,y2 from the above addressing scheme, return the Manhattan distance between them.
You may assume that all four inputs are non-negative integers, each less than 128. You may take them in any order and arbitrarily grouped (four separate arguments, a list of four integers, two pairs of integers, a 2x2 matrix, ...).
You may write a program or a function and use any of the standard methods of receiving input and providing output.
You may use any programming language, but note that these loopholes are forbidden by default.
This is code-golf, so the shortest valid answer – measured in bytes – wins.
Test Cases
Each test case is given as x1,y1 x2,y2 => result.
1,2 1,2 => 0
0,1 1,1 => 1
1,0 1,1 => 3
2,1 5,2 => 4
0,0 0,127 => 253
0,0 127,0 => 127
0,0 127,127 => 254
0,127 127,0 => 254
0,127 127,127 => 127
127,0 127,127 => 255
75,7 69,2 => 11
47,58 36,79 => 42
77,9 111,23 => 48
123,100 111,60 => 80
120,23 55,41 => 83
28,20 91,68 => 111
85,107 69,46 => 123
16,25 100,100 => 159
62,85 22,5 => 160
92,26 59,113 => 174
62,22 35,125 => 206

JavaScript (ES6), 84 78 bytes

Saved 6 bytes thanks to Neil

(a,b,c,d,x=a>c?a-c:c-a,y=b>d?b-d:d-b,z=x>y?x:y)=>y+z+(x+z&1?a+b+(b>d)&1||-1:0)

Test cases

let f =

(a,b,c,d,x=a>c?a-c:c-a,y=b>d?b-d:d-b,z=x>y?x:y)=>y+z+(x+z&1?a+b+(b>d)&1||-1:0)

console.log(f(  1,  2,  1,  2)); // => 0
console.log(f(  0,  1,  1,  1)); // => 1
console.log(f(  1,  0,  1,  1)); // => 3
console.log(f(  2,  1,  5,  2)); // => 4
console.log(f(  0,  0,  0,127)); // => 253
console.log(f(  0,  0,127,  0)); // => 127
console.log(f(  0,  0,127,127)); // => 254
console.log(f(  0,127,127,  0)); // => 254
console.log(f(  0,127,127,127)); // => 127
console.log(f(127,  0,127,127)); // => 255
console.log(f( 75,  7, 69,  2)); // => 11
console.log(f( 47, 58, 36, 79)); // => 42
console.log(f( 77,  9,111, 23)); // => 48
console.log(f(123,100,111, 60)); // => 80
console.log(f(120, 23, 55, 41)); // => 83
console.log(f( 28, 20, 91, 68)); // => 111
console.log(f( 85,107, 69, 46)); // => 123
console.log(f( 16, 25,100,100)); // => 159
console.log(f( 62, 85, 22,  5)); // => 160
console.log(f( 92, 26, 59,113)); // => 174
console.log(f( 62, 22, 35,125)); // => 206

Initial recursive solution, 100 88 81

Saved 12 bytes thanks to ETHproductions
Saved 7 bytes thanks to Neil

f=(a,b,c,d,e=b==d|a+b+(b>d)&1)=>a-c|b-d&&f(e?a+1-2*(a>c):a,e?b:b+1-2*(b>d),c,d)+1

How it works

Although it still essentially applies to the current version, the following explanation more specifically refers to the initial version:

f=(a,b,c,d)=>b-d?a+b+(b>d)&1?f(a+1-2*(a>c),b,c,d)+1:f(a,b+1-2*(b>d),c,d)+1:Math.abs(a-c)

Going from (x0, y) to (x1, y) is trivial because we can go across lateral edges all the way from the source triangle to the target one. The Manhattan distance in this case is | x0 - x1 |.

The tricky part is the vertical steps. To go from row y0 to row y1, we have to take these two parameters into account:

The orientation of the current triangle
Whether y0 is less or greater than y1

The orientation of a triangle is given by the parity of x + y:

if it's even, the triangle is up-pointing
if it's odd, the triangle is down-pointing

We can go downwards from an up-pointing triangle (useful when y0 < y1) and upwards from a down-pointing triangle (useful when y0 > y1).

By combining the orientation of the triangle with the comparison between y0 and y1, we get the formula x + y0 + (y0 > y1 ? 1 : 0) whose result is even if we can go in the desired direction and odd if not.

If we can't reach the next row directly, we first need to get a correct alignment by updating x:

if x is not yet equal to x1, we definitely want to move in the correct direction, so we increment it if x is less than x1 and we decrement it if x is greater than x1
if x already equals x1, we can either increment or decrement it

Test cases

f=(a,b,c,d)=>b-d?a+b+(b>d)&1?f(a+1-2*(a>c),b,c,d)+1:f(a,b+1-2*(b>d),c,d)+1:Math.abs(a-c)

console.log(f(  1,  2,  1,  2)); // => 0
console.log(f(  0,  1,  1,  1)); // => 1
console.log(f(  1,  0,  1,  1)); // => 3
console.log(f(  2,  1,  5,  2)); // => 4
console.log(f(  0,  0,  0,127)); // => 253
console.log(f(  0,  0,127,  0)); // => 127
console.log(f(  0,  0,127,127)); // => 254
console.log(f(  0,127,127,  0)); // => 254
console.log(f(  0,127,127,127)); // => 127
console.log(f(127,  0,127,127)); // => 255
console.log(f( 75,  7, 69,  2)); // => 11
console.log(f( 47, 58, 36, 79)); // => 42
console.log(f( 77,  9,111, 23)); // => 48
console.log(f(123,100,111, 60)); // => 80
console.log(f(120, 23, 55, 41)); // => 83
console.log(f( 28, 20, 91, 68)); // => 111
console.log(f( 85,107, 69, 46)); // => 123
console.log(f( 16, 25,100,100)); // => 159
console.log(f( 62, 85, 22,  5)); // => 160
console.log(f( 92, 26, 59,113)); // => 174
console.log(f( 62, 22, 35,125)); // => 206


"As we travel the universe..." You'll be given the name of one of the 20 biggest objects in the Solar System. Your task is to return an approximation of its radius, expressed in kilometers.

This is a code-challenge where your score consists of the length of your code (in bytes) multiplied by a penalty ratio \$\ge 1\$, based on your worst approximation. Therefore, the lowest score wins.

"As we travel the universe" is the last line of the song Planet Caravan by Black Sabbath, also later covered by Pantera.

The Solar System objects

Source: Wikipedia

NB: The rank is given for information only. The input is the name of the object.

  n | Object   | Radius (km)
----+----------+-------------
  1 | Sun      |   696342
  2 | Jupiter  |    69911
  3 | Saturn   |    58232
  4 | Uranus   |    25362
  5 | Neptune  |    24622
  6 | Earth    |     6371
  7 | Venus    |     6052
  8 | Mars     |     3390
  9 | Ganymede |     2634
 10 | Titan    |     2575
 11 | Mercury  |     2440
 12 | Callisto |     2410
 13 | Io       |     1822
 14 | Moon     |     1737
 15 | Europa   |     1561
 16 | Triton   |     1353
 17 | Pluto    |     1186
 18 | Eris     |     1163
 19 | Haumea   |      816
 20 | Titania  |      788

Or as copy-paste friendly lists:

'Sun', 'Jupiter', 'Saturn', 'Uranus', 'Neptune', 'Earth', 'Venus', 'Mars', 'Ganymede', 'Titan', 'Mercury', 'Callisto', 'Io', 'Moon', 'Europa', 'Triton', 'Pluto', 'Eris', 'Haumea', 'Titania'
696342, 69911, 58232, 25362, 24622, 6371, 6052, 3390, 2634, 2575, 2440, 2410, 1822, 1737, 1561, 1353, 1186, 1163, 816, 788

Your score

Let \$R_n\$ be the expected radius of the \$n^{th}\$ object and let \$A_n\$ be the answer of your program for this object.

Then your score is defined as:

$$S=\left\lceil L\times\max_{1\le i \le20}\left({\max\left(\frac{A_i}{R_i},\frac{R_i}{A_i}\right)^2}\right)\right\rceil$$

where \$L\$ is the length of your code in bytes.

Example:

If the size of your code is \$100\$ bytes and your worst approximation is on the Moon with an estimated radius of \$1000\$ km instead of \$1737\$ km, then your score would be:

$$S=\left\lceil 100\times{\left(\frac{1737}{1000}\right)^2}\right\rceil=302$$

The lower, the better.

Recommended header for your answer:

Language, 100 bytes, score = 302

You can use this script to compute your score (first line = code length, next 20 lines = your outputs, from Sun to Titania).

Rules

You may take the name of the object in either full lowercase, full uppercase or exactly as described above (title case). Other mixed cases are not allowed.
The input is guaranteed to be one of the 20 possible names.
You may return either integers or floats. In both cases, the penalty must be computed directly with these values (not rounded values in case of floats).
You must return positive values.
Empty programs are not allowed.

PowerShell, 3 bytes, score 3637

2e4

Try it online!

Very naive, boring, implementation; just returns 20000 no matter the input. Experimentation with things like special-casing the sun or using floating-point values instead of 2 all resulted in worse scores because the length of code increased enough to offset any size-comparison gains.


Find the Translation Table Given two strings, find the translation table (substitution cipher) between the two, if the translation is not possible, output false. The answer must be minimized and created from left-to-right. The first character to be translated between words must be the first in the translation table. In addition to this, any letter that is not translated (in the same place as it was originally), should NOT be in the translation table.
Probably most easily defined through examples:
Valid Cases
"bat", "sap" => ["bt","sp"]

Notice the ordering, an output of ["tb","ps"] is not valid for this challenge.
"sense", "12n12" => ["se","12"]

Notice how the n isn't translated because it is a 1 to 1 relation.
"rabid", "snail" => ["rabd","snal"]

Notice how the i isn't translated because it is a 1 to 1 relation.
"ass", "all" => ["s","l"]

A is not included, it stays the same, s can map to l due to pattern match.
"3121212", "ABLBLBL" => ["312","ABL"]

Matches pattern perfectly.
Falsy Cases
"banana", "angular" => false

(not the same length, impossible).
"animal", "snails" => false

(each character can only be used ONCE on each side of the translation).
"can","cnn" => false

(n is implicitly used in translation, therefore, defining a translation table with n->a would be invalid)
Thusly, [aimal,sails] is an invalid answer, making this falsy.
"a1", "22" => false

See "caveats", this is listed as falsy. In this case, it's because a and 1 cannot both map to 2. (Each character can only be used ONCE on each side of the translation).

This answer seems to be a good benchmark: https://codegolf.stackexchange.com/a/116807/59376
If you have questions about the functionality of two unlisted word pairs, defer to this implementation.

I/O rules

Input may be as a 2 element array or as 2 separate inputs.
Output can be as an array or newline/space delimited, similar to how I have it shown.
False output may be 0, -1 or false. Erroring/Empty output is also fine.
You are guaranteed that a will not equal b and neither a nor b will be empty.
a and b are printable-ASCII-only sequences of letters.

Caveats

Translations must occur from left to right, see example 1.
You must not output characters that remain the same.
Your program may only take in two strings a and b.
Each character can only be used ONCE on each side of the translation. This is what makes the translation from snails to animals impossible.
Recursive replaces should not occur. Example of recursive replace: "a1","22"->[a1,12] where a is first replaced by a 1, then both resultant 1's are replaced with 2's. This is not correct, assume all translations occur independent of each other, meaning this is falsy. Meaning: "a1" with translation table of [a1,12] evaluates to 12 (not 22)

PHP >=7.1, 130 Bytes

18 Bytes saved by @Titus

for([,$x,$y]=$argv;a&$o=$y[$i];)$o==($p=$x[$i++])?:$k[$c[$p]=$o]=$p;echo$y==strtr($x,$c)&$x==strtr($y,$k)?join($k)." ".join($c):0;

Testcases

Expanded

for([,$x,$y]=$argv;a&$o=$y[$i];)
$o==($p=$x[$i++])?:$k[$c[$p]=$o]=$p; # if char string 1 not equal char string 2 make key=char1 value=char2 and key array
echo$y==strtr($x,$c) # boolean replacement string 1 equal to string 2
    &$x==strtr($y,$k) # boolean replacement string 2 equal to string 1
    ?join($k)." ".join($c) # output for true cases
:0; #Output false cases

PHP >=7.1, 148 Bytes

prints 0 for false Output true as string

for([,$x,$y]=$argv;a&$o=$y[$i];$i++)$x[$i]==$o?:$c[$x[$i]]=$o;echo$y==strtr($x,($f=array_flip)($k=$f($c)))&$x==strtr($y,$k)?join($k)." ".join($c):0;

Testcases

Expanded

for([,$x,$y]=$argv;a&$o=$y[$i];$i++)
$x[$i]==$o?:$c[$x[$i]]=$o; # if char string 1 not equal char string 2 set key=char1 value=char2
echo$y==strtr($x,($f=array_flip)($k=$f($c))) # boolean replacement string 1 equal to string 2
&$x==strtr($y,$k) # boolean replacement string 2 equal to string 1
    ?join($k)." ".join($c) # output for true cases
:0; #Output false cases

PHP >=7.1, 131 Bytes

The second answer can be shorted to this if associative arrays are allowed

prints 0 for false Output true as associative array instead of string

for([,$x,$y]=$argv;a&$o=$y[$i];$i++)$x[$i]==$o?:$c[$x[$i]]=$o;print_r($y==strtr($x,($f=array_flip)($f($c)))&$x==strtr($y,$k)?$c:0);

Testcases

PHP >=7.1, 227 Bytes

prints 0 for false

[,$x,$y]=$argv;echo strlen($x)==strlen($y)?strtr($x,$c=array_filter(($f=array_flip)($z=$f(array_combine(($p=str_split)($x),$p($y)))),function($v,$k){return$k!=$v;},1))==$y&$x==strtr($y,$z)?join(array_keys($c))." ".join($c):0:0;

Testcases

Expanded

[,$x,$y]=$argv; #
echo strlen($x)==strlen($y) #compare string lengths
?strtr($x,  # replace function
$c=array_filter( # filter
($f=array_flip)($z=$f( # # remove doubles like in testcase: a1 => 22
    array_combine(($p=str_split)($x),$p($y))  # replacement array keys string 1 values string 2
))
    ,function($v,$k){return$k!=$v;},1)) # remove all keys that equal to values in array
    ==$y # boolean replacement string 1 equal to string 2
&$x==strtr($y,$z) # boolean replacement string 2 equal to string 1
?join(array_keys($c))." ".join($c) # output for true cases
    :0 # Output if replacement from string 1 is not equal to string 2
:0; #Output for different lengths


Hide the Needle in the Haystack (Cops) This is part of a cops-and-robbers challenge. Go here for the robbers' part.

The Cops' Challenge

You should write a program or function in a language of your choice, which outputs the string Haystack. However, it must be possible to remove some subset of characters from your program (without reordering the rest), such that the resulting string is also a valid program in the same language, which prints Needle instead. Both programs/functions may optionally print a single trailing newline (independently of each other), but nothing else.  Output is case sensitive and must follow the exact casing provided.

Your goal, of course, is to hide the "needle" very well. But note that your submission can be cracked with any valid solution, not just the one you intended.

Please include in your answer:

The language (and version if relevant) of your submission.
The size of the Haystack program in bytes.
The Haystack program itself.
The output method if it's not STDOUT.
If possible, a link to an online interpreter/compiler for your chosen language.

Your submission may be either a program or function, but not a snippet and you must not assume a REPL environment. You must not take any input, and you may output via STDOUT, function return value or function (out) parameter.

Both programs/functions have to complete within 5 seconds on a reasonable desktop machine and need to be deterministic. You must not use built-ins for hashing, encryption or random number generation (even if you seed the random number generator to a fixed value).

In the interest of fairness, there must be a freely available interpreter or compiler for your chosen language.

An answer is cracked if the Needle program is found.  If your answer has not been cracked for 7 days, you may reveal the intended Needle program in your answer, which renders your submission safe. As long as you don't reveal your solution, it may still be cracked by robbers, even if the 7 days have already passed. The shortest safe Haystack program (measured in bytes) wins.

Examples

Here are a couple of simple examples in different languages:

Ruby

Haystack: puts 1>0?"Haystack":"Needle"
Delete:        XXXXXXXXXXXXXXX
Needle:   puts "Needle"

Python 2

Haystack: print "kcatsyaHeldeeN"[-7::-1]
Delete:          XXXXXXXX        XX
Needle:   print "eldeeN"[::-1]

Note that the subset of removed characters doesn't have to be contiguous.

Uncracked Submissions

Haystack, 84 bytes, Cracked

0\\1-c\
//
?10F17+c8F+4+cd8F+3+c6-c1+c,c2+c8+c|
 0   \1++c,c|
F/c++2F8
c\8F+2+cd

Try it online!

This looks (to me) rather convoluted but if you find the right subset it's a bit too easy... oh well, just to get us started :P


Hide one message inside another Your task is to hide a small message or string inside a larger block of text. To do so, you must hide the message as capital letters inside the larger

For the quoted test:

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut convallis porta varius. Donec loBortis adipiscing dolor ac Euismod. Ut Mincidunt eY cursus nunc pulVinar, eu mAttis nibh tincidunt. PhaseLlus sEd molestie sapieN. InTeger congue maurIs in Nisi faucibus, at aliquam ligula consEctetur. Quisque laoreet turpis at est cursus, in consequat.

(Emboldened text only to highlight where the letters are)

The secret text reads:

BE MY VALENTINE

You choose how to spread the words out, and should error if you try to hide a string inside another that won't fit either from length or lack of required characters.

Assume the input is plain text, where the first letter of each sentence may be capitalised or not (those can be lower cased or ignored, but should not be part of the secret message, for clarity).

You'll get -10 points for writing a second program that recovers the hidden message from a block of text. In this eventuality your score is the average of the two, minus the 10 bonus points.

E.g. If the Message hiding code is 73 characters, and the recovery one is 80, your score is:

(73+80)/2-10=66.5

Ruby, (69+35)/2-10 = 42

a=gets
$><<gets.gsub(/./){a[0]!=$&?$&:a.slice!(0).upcase}
1/0if a>?\n

Takes input on STDIN, first line is the message to hide, second line is the text block.  Assumes the secret message is lower-case.  Example input:

codegolf
You'll get -10 points for writing a second program that recovers the hidden message from a block of text. In this eventuality your score is the average of the two, minus the 10 bonus points.

Example output:

You'll get -10 points for writing a seCOnD program that rEcovers the hidden messaGe frOm a bLock oF text. In this eventuality your score is the average of the two, minus the 10 bonus points.

Here's the program to obtain the secret back from the output (again, provided on STDIN):

$><<gets.scan(/(?<!^|\. )[A-Z]/)*''

One caveat here is that Ruby's lookbehind expressions have to be fixed width, so this code only works for text where the periods are followed by exactly one space.  Suggestions welcome!


Test a number for narcissism A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number of digits.
For example, take \$153\$ (3 digits):

\$1^3 + 5^3 + 3^3 = 153\$

\$1634\$:

\$1^4 + 6^4 + 3^4 + 4^4 = 1634 = 1 + 1296 + 81 + 256 = 1634\$

The Challenge:
Your code must take input from the user and output True or False depending upon whether the given number is a Narcissistic Number.
Error checking for text strings or other invalid inputs is not required. 1 or 0 for the output is acceptable. Code that simply generates a list of Narcissistic Numbers, or checks the user input against a hardcoded list, does not qualify.
OEIS A005188

APL (15)

∆≡⍕+/(⍎¨∆)*⍴∆←⍞

Outputs 1 if true and 0 if false.

Explanation:

∆←⍞: read a line (as characters), store in ∆
(⍎¨∆)*⍴∆: evaluate each character in ∆ and raise it to the power ⍴∆
∆≡⍕+/: see if the input equals the string representation of the sum of these


Make some Prime Squares! What is a Prime Square?
A Prime Square is a square where all four edges are different prime numbers.
But which ones?
And how do we construct them?
Here is an example of a 4x4 Prime Square
1009
0  0
3  0
1021

First we start from the upper left corner. We are working clockwise.
We pick the smallest prime number having 4 digits which is 1009.
Then we need the smallest prime number having 4 digits, which starts with a 9. This is 9001
The third (4-digits) prime number must have 1 as its last digit (because 9001 ends with 1)
and also be the smallest 4-digit prime with this property that has not been used before as an edge.
This prime number is 1021
The fourth prime number must have 4 digits, start with a 1 (because 1009 starts with a 1) and end with a 1 (because 1021 starts with a 1)
The smallest 4-digit prime number with this property that has not been used before as an edge is 1031
Your TASK
You will be given an integer n from 3 to 100
This number will be the dimensions of the n x n square
Then you must output this square exactly in the form of the following test cases
Test Cases
n=3
Output

101
3 0
113

n=5
Output

10007
0   0
0   0
9   0
10061

n=7
Output

1000003
0     0
0     0
0     0
0     0
8     1
1000037

n=10
Output

1000000007
0        0
0        0
0        0
0        0
0        0
0        0
1        0
8        0
1000000021

n=20
Output

10000000000000000051
0                  0
0                  0
0                  0
0                  0
0                  0
0                  0
0                  0
0                  0
0                  0
0                  0
0                  0
0                  0
0                  0
0                  0
0                  0
0                  0
0                  0
9                  8
10000000000000000097

Input and output can be given by any convenient method.
You can print it to STDOUT or return it as a function result.
Either a full program or a function are acceptable.
Any amount of extraneous whitespace is acceptable, so long as the numbers line up appropriately
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

EDIT
This is possible for all n
Here are the primes for n=100
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000289
9000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000091
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000711
1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002191

And for those of you that you don't think this is possible [here are ALL the test cases][1]

05AB1E, 64 63 56 53 48 46 bytes

°ÅPIùćÐ4FˆθUKD.ΔθyXÅ?yXÅ¿)¯gè}ÐNĀiR}¦}I¯JŽ9¦SΛ

-1 byte thanks to @Mr.Xcoder
-5 bytes thanks to @Grimy.

Try it online. (Times out for \$n>4\$. Here the slightly faster 53 bytes version which times out for \$n>7\$ instead.)

Explanation:

°                 # Raise the (implicit) input to the power 10
 ÅP               # Get a list of primes within the range [2, n^10]
   Iù             # Only keep those of a length equal to the input
ć                 # Extract the head; push the remainder-list and first prime separately
 Ð                # Triplicate this first prime
4F                # Loop 4 times:
  ˆ               #  Add the (modified) prime at the top of the stack to the global array
  θU              #  Pop and store the last digit of the prime in variable `X`
  K               #  Remove this prime from the prime-list
  D               #  Duplicate the prime-list
   .Δ             #  Find the first prime `y` in the prime list which is truthy for:
     θ            #   Get the last digit of prime `y`
     yXÅ?         #   Check if prime `y` starts with variable `X`
     yXÅ¿         #   Check if prime `y` ends with variable `X`
     )            #   Wrap the three results above into a list
      ¯g          #   Get the amount of items in the global array
        è         #   And use it to index into these three checks
                  #   (Note that only 1 is truthy for 05AB1E, so the `θ` basically checks
                  #    if the last digit of prime `y` is 1)
    }Ð            #  Triplicate the found prime
      NĀi }       #  If the loop index is 1, 2, or 3:
         R        #   Reverse the found prime
      ¦           #  And then remove the first digit of the (potentially reversed) prime
}                 # After the loop:
 I                # Push the input as length
 ¯J               # Push the global array joined together to a single string
 Ž9¦S             # Push compressed integer 2460 converted to a list of digits: [2,4,6,0]
 Λ                # Draw the joined string in the directions [2,4,6,0] (aka [→,↓,←,↑])
                  # of a length equal to the input
                  # (which is output immediately and implicitly as result)

See this 05AB1E tip of mine (section How to compress large integers?) to understand why Ž9¦ is 2460. And see this 05AB1E tip of mine to understand how the square is output with the Λ Canvas builtin.

The relevant code for printing the Canvas in a square is: NĀiR}¦ and I¯JŽ9¦SΛ. Let's take n=4 as example. The primes it will find with the rest of the code are [1009,9001,1021,1031]. The first code-part mentioned in this paragraph will save them as this instead: [1009,"001","201","301"]. The second code part of this paragraph will then use the Canvas builtin Λ with options:
- \$a\$ (side-length) = I: the input
- \$b\$ (string to print) = ¯J: the global array joined together (so "1009001201301" for n=4)
- \$c\$ (direction) = Ž9¦S: the directions [2,4,6,0], which will be [→,↓,←,↑] respectively


The shortest way of getting rid of these numbers This is a simple game of getting rid of those damn numbers.

You start with the numbers from 1 to 19, written in a grid of 9 by 3:

1 2 3 4 5 6 7 8 9
1 1 1 2 1 3 1 4 1
5 1 6 1 7 1 8 1 9

You may notice that the number 10 is missing, this because the number zero would be hard to get rid of later on.

The two rules are:

If you find a pair of two numbers such that (a) they are equal OR (b) they add up to 10, you can eliminate both of them.
What is a valid pair? Either, they directly follow each other (ignoring any eliminated numbers, potentially continuing in the next row, but not connecting the last with the first row) when going left-to-right through the rows,
or they directly follow each other when going top-to-bottom through the columns (ignoring any eliminated numbers, not continuing in any following columns).

Small example:

2 9 1 2
3 4 5 6

Here, we can remove the pair (9, 1) as the sum is ten:

2 x x 2
3 4 5 6

Now we can remove (2, 2) as they are adjacent:

x x x x
3 4 5 6

Now, nothing else can be eliminated.

If nothing can be eliminated anymore, you will copy all remaining numbers to the bottom and continue.

Example. Starting with:

 1 2 3 4 5 6 7 8 X
 X X 1 2 1 3 1 4 1
 5 X X X 7 X 8 X X
 1 X X X X X X X X
 X X X X X X X 2 X
 4 5 X X 4 X 5 6 X
 8

we get:

 1 2 3 4 5 6 7 8 X
 X X 1 2 1 3 1 4 1
 5 X X X 7 X 8 X X
 1 X X X X X X X X
 X X X X X X X 2 X
 4 5 X X 4 X 5 6 X
 8 1 2 3 4 5 6 7 8
 1 2 1 3 1 4 1 5 7
 8 1 2 4 5 4 5 6 8

You have won the game when all numbers are eliminated.

The shortest solution in terms of moves (either an elimination or a "copy remainder") wins this challenge.

If you can prove your solution to be the shortest possible (for example by doing exhaustive BFS), you get extra points.
Tell us about your crazy optimizations you used to make this fit into memory!
Showing us your code that you used to get to your solution is highly recommended.

Further examples of valid pairs:

1 X 2
3 4 5
X 6 7
 Here, only (4,6) is a valid pair to eliminate, as they add up to ten and are directly adjacent in a column (ignoring all Xs in between).

1 X X
X X X
X X 9
 The only valid pair is (1, 9), as they are directly adjacent row-wise (ignoring the many eliminated numbers in between).


The world ends in ed Taken straight from the ACM Winter Programming Contest 2013. You are a person who likes to take things literally. Therefore, for you, the end of The World is ed; the last letters of "The" and "World" concatenated.

Make a program which takes a sentence, and output the last letter of each word in that sentence in as little space as possible (fewest bytes). Words are separated with anything but letters from the alphabet (65 - 90, 97 - 122 on the ASCII table.) That means underscores, tildes, graves, curly braces, etc. are separators. There can be more than one seperator between each word.

asdf jkl;__zxcv~< vbnm,.qwer| |uiop -> flvmrp
pigs, eat dogs; eat Bob: eat pigs -> ststbts
looc si siht ,gnitirw esreveR -> citwR
99_bottles_of_beer_on_the_wall -> sfrnel

ed, 35 characters

s/[a-zA-Z]*\([a-zA-Z]\)\|./\1/g
p
Q

So, the world ends in ed. As I like to be too literal, I decided to write to write the solution with ed - and apparently it is actually a programming language. It's surprisingly short, even considering many shorter solutions already exist in this thread. It would be nicer if I could use something other than [a-zA-Z], but considering ed isn't a programming language, it's actually good enough.

First, I would like to say this only parses the last line in file. It would be possible to parse more, just type , at beginning of two first lines (this specified "everything" range, as opposed to standard last line range), but that would increase code size to 37 characters.

Now for explanations. The first line does exactly what Perl solution does (except without support for Unicode characters). I haven't copied the Perl solution, I just invented something similar by coincidence.

The second line prints last line, so you could see the output. The third line forces quit - I have to do it, otherwise ed would print ? to remind you that you haven't saved the file.

Now for how to execute it. Well, it's very simple. Just run ed with the file containing test case, while piping my program, like that.

ed -s testcase < program

-s is silent. This prevents ed from outputing ugly file size at beginning. After all, I use it as a script, not editor, so I don't need metadata. If I wouldn't do that, ed would show file size that I couldn't prevent otherwise.


Create an unlimited counterstring A counterstring is some sort of self-describing test data that is used in software testing. Not sure it was actually invented by James Bach, but I know it from there.

The idea is as follows: the test data contains many asterisk (*). The number in front of the asterisk tells you how long the test data is at that point. If you need to know a position in the test data that is not an asterisk, find the last asterisk, look at the number before and add the number of digits that follow.

The sequence starts like this:

2*4*6*8*11*14*17*20*23*
             ^

As you can see, the marked asterisk is at position 14.

If a file happens to be truncated as follows

[...]2045*20

then you can derive that there is a limit of 2047 characters somewhere (2045 where the asterisk is plus 2 for 2 and 0).

It's your task to create the shortest (this is code-golf) program that outputs (std::out or file or whatever) an arbitrary long test string of that format. The length in characters is given as argument. The program shall support up to 2 GB test data (input value 2147483647 characters).

"Dangerous" positions in the 2 GB file:

8*11*
98*102*
998*1003*
9998*10004*
99998*100005*
999995*1000003*
9999995*10000004*
99999995*100000005*
999999995*1000000006*

This should answer @Leaky Nun's question if there is a decision to make between 995*999* and 995*1000* or similar: no.

The end of the 2 GB file with input value 2147483647 is:

2147483640*2147483

Haskell, 60 58 bytes

As a function we get:

f=length.show
iterate(\n->1+n+(f$n+1+f n))2>>=(++"*").show

Full program, 72 70 bytes

This outputs an infinite counterstring to STDOUT:

f=length.show
main=putStr$iterate(\n->1+n+(f$n+1+f n))2>>=(++"*").show

Inputting the length requires 20 additional bytes:

main=interact(\j->take(read j)$iterate(\n->1+n+(f$n+1+f n))2>>=(++"*").show)

This works up to your approximately your RAM size, since Haskell defaults numeric integral types to Integer.


Implement the iOS 11 Calculator iOS 11 has a bug that makes the result of 1+2+3 to be 24. This is related to the animation speed, but anyway:

The task is to make 1 + 2 + 3 == 24. But only that. So you should provide a function that correctly sums most sequences but returns 24 when the arguments are 1, 2 and 3 in any order.

Example inputs:

1 2 => 3
3 4 => 7
1 2 3 4 5 6 7 8 9 => 45
3 2 1 => 24
2 1 3 => 24
1 1 => 2
1 2 3 => 24
40 2 => 42
1 2 2 4 => 9
1 2 3 4 1 2 3 => 16
1 => 1
1 23 => 24
0 1 2 => 3
3 2 3 => 8

Input can be in any format as long as your code accepts any number of arguments.

Support for negative numbers isn't required (all non negative numbers are required to work, that includes 0)
We assume correct input

Differences from another similar question: "What do you get when you multiply 6 by 9? (42)":

In this case your function is required to accept any number of arguments. The old question specifies exactly 2.
In this case order doesn't matter, while the old question specified that order 6 9 is required and 9 6 should be evaluated correctly.

05AB1E, 9 bytes

Os{3LQi4*

Explanation:

Os{         Get the sum of the input, and then get the sorted input list
     Qi     If it is equal to...
   3L       [1, 2, 3]
       4*   Then multiply the sum by four.

Try it online!