Read a date in xkcd notation In his xkcd about the ISO 8601 standard date format Randall snuck in a rather curious alternative notation:

The large numbers are all the digits that appear in the current date in their usual order, and the small numbers are 1-based indices of the occurrences of that digit. So the above example represents 2013-02-27.

Let's define an ASCII representation for such a date. The first line contains the indices 1 to 4. The second line contains the "large" digits. The third line contains the indices 5 to 8. If there are multiple indices in a single slot, they are listed next to each other from smallest to largest. If there are at most m indices in a single slot (i.e. on the same digit, and in the same row), then each column should have be m+1 characters wide and left-aligned:

2  3  1  4
0  1  2  3  7
5     67    8

See also the companion challenge for the opposite conversion.

The Challenge

Given a date in xkcd-notation, output the corresponding ISO 8601 date (YYYY-MM-DD).

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

You may assume that the input is any valid date between years 0000 and 9999, inclusive.

There won't be any leading spaces in the input, but you may assume that the lines are padded with spaces to a rectangle, which contains at most one trailing column of spaces.

Standard code-golf rules apply.

Test Cases

2  3  1  4
0  1  2  3  7
5     67    8
2013-02-27

2  3  1     4
0  1  2  4  5
   5  67 8
2015-12-24

     1234
1    2
5678
2222-11-11

   1     3  24
0  1  2  7  8
57    6     8
1878-02-08

2   4   1   3
0   1   2   6
5       678
2061-02-22

      1 4 2 3
0 1 2 3 4 5 6 8
6 5 7         8
3564-10-28

1234
1
5678
1111-11-11

1 2 3 4
0 1 2 3
8 5 6 7
0123-12-30

CJam, 35 bytes

ll{1$e>}*](l+eeWf%$-8>Wf=\f=2/(o'-*

Try it here. It expects the input lines to be padded with spaces.

Explanation

ll reads two lines of input, and {1$e>}* performs a "scan" on the second one: it it takes all prefixes of its input and computes the maximum of each prefix. For the input line "0  1  2  7  8", this pushes "0001112227778". Our stack now looks like this:

"first line" '0 '0 '0 '1 '1 '1 ...

We need to re-capture the values into a list ourselves using ]; this captures our first line as well, so we pop it back out using (, to get

"0001112227778" "first line"

as expected.

eelee+ enumerates this line, then does the same for a third input line, and concatenates the results, leaving something like this on the top of the stack:

[[0 '5] [1 ' ] [2 ' ] [3 ' ] [4 ' ] [5 ' ] [6 ' ] [7 ' ] [8 '6] [9 '7] [10 '8] [11 ' ] [12 ' ]
 [0 '2] [1 ' ] [2 ' ] [3 ' ] [4 '4] [5 ' ] [6 ' ] [7 ' ] [8 '1] [9 ' ] [10 ' ] [11 ' ] [12 '3]]

Now our stack is ["0001112227778" X] where X is the enumerated list above.

We flip each pair in X (Wf%), sort the pairs lexicographically ($), and leave the last 8 pairs -8>. This gets us something like:

[['1 8] ['2 0] ['3 12] ['4 4] ['5 0] ['6 8] ['7 9] ['8 10]]

This works, because the sort places all the pairs with key ' (space) before all the digits in ascending order.

These are the "x-positions" of the characters 12345678 on the first and third lines: we only need to retrieve the characters from our (modified) second line that are vertically aligned with them.

To do this, we take each position (Wf=), index into the string we made earlier (\f=). We have "20610222" on the stack now: to add the dashes, first we split into segments of length two (2/), print the first segment without a newline ((o) and join the remaining segments with dashes ('-*).

EDIT: cool scan trick, Martin! Saved four bytes.

EDIT 2: saved two more bytes by replacing eelee+ with l+ee; this works, because the lines all have the same lengths, and list indexing in CJam is automatically modulo the list length, so the indices n+0, n+1, n+2... nicely map to 0, 1, 2...

EDIT 3: Martin saved another byte in the final step of the process. Nice!


Look and say sequence The look and say sequence is a basic form of run length encoding.

The sequence starts with the number 1 and each additional number encodes the number of digits that are repeated before each digit sequence. For example, "1" becomes "11", because there is one "1". Then "11" becomes "21", and so on.

The first few numbers are 1, 11, 21, 1211, 111221, 312211 and 13112221.

Write a program to output the first 20 numbers.

The catch is you may not use any number in your program, including other bases than base 10. You can only use letters and symbols. Also, the program can't directly contain the numbers (or fetch them from a web server, or from a file); it must actually compute them.

I will accept the answer which works and is the shortest; in case of a tie, vote counts will decide, and in case of a tie there, the winner will be chosen randomly.

Golfscript, 44 43 40 41 38 37 36 chars

Since the criterion now requires golfing, here's the golfed version:

!:^;n).+{[^\{^$^$={;\)}^if\}*].n@}*;

The original, ungolfed, version actually dealt with strings rather than abusing Golfscript's formatting conventions for dumping the stack to stdout at program termination:

# Assumes nothing passed to stdin, so input length is zero
,):$''+
{
    .puts
    # Convert to an array of [count char count char ...]
    [$\{.@.@={;\)\}{\$\}if}*]
    # Convert to an array of [[count char] [count char] ...]
    $)/
    # Form the next string
    ''\{(@\+\+}/
}
# Nineteen times. There are a *lot* of ways of generating the number nineteen
# but I like this one
$).?.)*(*


Fill in the Minesweeper clues Minesweeper is a popular puzzle game where you must discover which tiles are "mines" without clicking on those tiles. Each tile is either a mine (represented by *) or a clue, i.e. a number from 0 to 8 representing how many of the 8 neighboring tiles are mines. Your task today is to take a board containing the mines and fill in all of the clues. For example, look at the following 5x4 board, with 5 mines:

 *
*  *
  *
    *

After filling in the clues, the board will look like this:

2*211
*33*1
12*32
0112*

Details

You must write either a full-program or a function that takes in a grid of characters containing only spaces and asterisks and outputs another grid where each space is replaced with the number of adjacent mines (asterisks). Any of these are acceptable formats for your grids:

A string with newlines in it
A 2D list of characters/single character strings
A list of strings

You can assume the grid will be at least 1x1, although it is possible for it to be all mines or all spaces.

The input grid will always be padded with the appropriate number of spaces. As usual, this is code-golf, so standard loopholes apply and the shortest answer in bytes wins!

Sample IO

So that you can see the whitespace, I will show all sample IO with brackets around it.

Input:
[    * ]
[*     ]
[      ]
[      ]
[  **  ]
[ *  * ]

Output:
[1101*1]
[*10111]
[110000]
[012210]
[12**21]
[1*33*1]

Input:
[****]
[****]

Output:
[****]
[****]

Input:
[   ]
[   ]
[   ]
[   ]

Output:
[000]
[000]
[000]
[000]

Input:
[*   ]
[**  ]
[    ]
[   *]

Ouput:
[*310]
[**10]
[2221]
[001*]

Input:
[**    ]
[*    *]
[  *   ]
[      ]
[*     ]
[****  ]

Output:
[**1011]
[*4211*]
[12*111]
[121100]
[*43210]
[****10]

Input:
[     *    ]
[        * ]
[     *    ]
[**   ***  ]
[      *** ]
[          ]
[       ** ]
[  * *     ]
[*      ** ]
[       ** ]

Output:
[00001*1111]
[00002221*1]
[22102*4321]
[**102***31]
[221013***1]
[0000013542]
[0112111**1]
[12*2*12442]
[*212112**2]
[1100002**2]

MATL, 18 17 bytes

Thanks to @mbomb007 for a correction in the input of test case 6

32>t3Y6Z+-6b(48+c

Input is a 2D char array, in the format

[' *   '; '*  * '; '  *  '; '    *']

Try it online!

Test cases: 1,
 2, 3, 4, 5, 6.

Explanation

32>      % Input 2D char array implicitly. Transform it into a 2D logical
         % array with asterisk replaced by true and space by false
t        % Duplicate
3Y6      % Push [1 1 1; 1 0 1; 1 1 1]. This defines the neighbourhood
Z+       % 2D convolution, keeping size. Gives the number of neighbouring
         % mines for each position
-6       % Push -6
b        % Bubble up in stack
(        % Assign -6 to the entries indicated by the logical array, i.e.
         % to the positions that originally contained asterisks
48+      % Add 48. This transforms each number of neighbouring mines
         % into its ASCII code, and -6 into 42 (ASCII code of asterisk)
c        % Convert to char. Display implicitly


Make a PNG image with "Hello World!" with programming APIs, in the shortest code possible So, I want you to make a PNG image that says "Hello world!" and nothing else on a distinguishable background using only an image making API (eg ImageMagick) and return the image. Fewest characters win, as usual. Oh, and you can use any color text.

Bash + ImageMagick: 35 33
Default font, default text size, default colours:
convert label:Hello\ world! a.png

and here's the result:

Thanks to DigitalTrauma and sch for the help :-D


Plotting the Cornu spiral The Cornu Spiral can be calculated using Feynman's method for path integrals of light propagation. We will approximate this integral using the following discretisation.

Consider a mirror as in this image, where S is the light source and P the point where we collect light. We assume the light bounces in a straight ray from S to each point in the mirror and then to point P. We divide the mirror into N segments, in this example 13, labelled A to M, so that the path length of the light is R=SN+NP, where SN is the distance from S to mirror segment N, and similar for P. (Note that in the image the distance of points S and P to the mirror has been shortened a lot, for visual purposes. The block Q is rather irrelevant, and placed purely to ensure reflection via the mirror, and avoid direct light from S to P.)

For a given wave number k the phasor of a ray of light can be calculated as exp(i k R), where i is the imaginary unit. Plotting all these phasors head to tail from the left mirror segment to the right leads to the Cornu spiral. For 13 elements and the values described below this gives:

For large N, i.e. a lot of mirror segments, the spiral approaches the "true" Cornu spiral. See this image using various values for N:

Challenge

For a given N let x(n) be the x-coordinate centre of the n-th mirror segment (n = 0,1,2,...,N):

x(n) := n/N-0.5

Let SN(n) be the distance of S = (-1/2, 1000) to the n-th mirror segment:

SN(n) := sqrt((x(n)-(-1/2))^2 + 1000^2)

and similarly

NP(n) := sqrt((x(n)-1/2)^2 + 1000^2)

So the total distance travelled by the n-th light ray is

R(n) := SN(n) + NP(n)

Then we define the phasor (a complex number) of the light ray going through the n-th mirror segment as

P(n) = exp(i * 1e6 * R(n))

We now consider the cumulative sums (as an approximation to an integral)

C(n) = P(0)+P(1)+...+P(n)

The goal is now plotting a piecewise linear curve through the points (C(0), C(1), ..., C(n)), where the imaginary part of C(n) should be plotted against its real part.

The input should be the number of elements N, which has a minimum of 100 and a maximum of at least 1 million elements (more is of course allowed).

The output should be a plot or image in any format of at least 400×400 pixels, or using vector graphics. The colour of the line, axes scale etc are unimportant, as long as the shape is visible.

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

Please note that this is not an actual Cornu spiral, but an approximation to it. The initial path integral has been approximated using the Fresnel approximation, and the mirror is both not of infinite length and not containing an infinite number of segments, as well as mentioned it is not normalised by the amplitudes of the individual rays.

MATL, 29 26 25 bytes
Thanks to @Adriaan for 3 bytes off!
Q:qG/q1e3YytP+1e6j*ZeYsXG

Here's an example with input 365 366... because today is MATL's first birthday! (and 2016 is a leap year; thanks to @MadPhysicist for the correction).
Or try it in MATL online! (experimental compiler; refresh the page if it doesn't work).

Explanation
Q:q    % Input N implicitly. Push range [0 1 ... N] (row vector)
G/     % Divide by N, element-wise
q      % Subtract 1. This gives NP projected onto the x axis for each mirror element
1e3    % Push 1000. This is NP projected onto the y axis
Yy     % Hypotenuse function: computes distance NP
tP     % Duplicate, reverse. By symmetry, this is the distance SN
+      % Add. This is distance SNP for each mirror element (row vector)
1e6j   % Push 1e6*1i
*      % Multiply
Ze     % Exponential
Ys     % Cumulative sum
XG     % Plot in the complex plane


The answer to life, the universe, and ASCII-art Simple challenge: try to output the following text in as few bytes as you can:

       the        answer
      toli      fetheuniv
     ersea     nde     ver
    ything     the     ans
   wer tol     ife     the
  uni  ver           sean
 dev   ery         thin
gth    ean       swer
tolifetheuni    ver
seandeveryth   ing
       the     ans      wer
       tol     ifetheuniver
       sea     ndeverything

The original drawing contains 332 characters.

Rules

No input or an unused input.
Output can be in any reasonable format (string, list of strings, matrix of chars and so on).
You can use uppercase instead of lowercase for the drawing if your prefer so.
Trailing whitespaces and newlines allowed.
This is code-golf, so may the shortest program/function for each language win!

Notes

This has been identified as a possible duplicate of We're no strangers to code golf, you know the rules, and so do I. That question was about searching and replacing text. Here you have to draw a shape using a given text, and at least two of the current answers demonstrate that golfing languages can beat plain compression algorithms in this case.

Python 3, 224 220 219 215 211 194 bytes

Thanks to @TFeld for 1 5 bytes: if(j%27<1)*j instead of if j*(j%27<1) and simplified print statement.
Thanks to @Leaky Nun for 4 bytes:Inverting 0 and 1, did not require the padding by zeros 7*'0'
@Leaky nun saved 17 bytes with his awesome golfing skills(Thanks a lot!!!!): awesome use of modular indexing

i=j=0
k=int("OHZE5WCKDTW6JYMO1JNROAAJQVAN6F8KEO0SMKJM86XIBMCEH5FXXONZGBAVCN3689DS",36)
while k:j+=1;print(k%2*'theanswertolifetheuniverseandeverything'[i%39]or' ',end='\n'*(j%27<1));i+=k%2;k//=2

Try it online!

Explanation:

Uses base-36 compression to compress this binary number(new-line excluded)

111111100011111111000000111
111111000011111100000000011
111110000011111000111110001
111100000011111000111110001
111000100011111000111110001
110001100011111111111000011
100011100011111111100001111
000111100011111110000111111
000000000000111100011111111
000000000000111000111111111
111111100011111000111111000
111111100011111000000000000
111111100011111000000000000

We basically have two counters i and j. On encountering a 1 we print a space; Else if 0 is encountered we print next letter from the string and increase i. j increases for each 0 or 1. We also print new-lines whenever necessary i.e. when j%27<1 becomes true.


R[oman|everse] Polish Notation It is the year MDLXVII in a world in which the Roman Empire never fell, and the collapse into the dark ages never occurred. Due to the extended period of Pax Romana, the empire's economic stability enabled technology to progress at a rapid rate.

The Romans have begun to dabble with circuitry, and have invented an ingenious calculator that doesn't require the use of an "equals" button. They call it "Roman Polish Notation"

To make a calculation, they enter their operands first, then the operation.

For example, 100 + 11 * 20 would be C XI XX * +.

Additionally

The Romans have found that they often need to make multiple calculations at the same time, and would prefer for the method to return every value "on the stack" in some sort of array/list/tuple-like structure. (e.g. X I + X I - CC II + would return [11, 9, 202])

The challenge is to develop a calculator program capable of making these computations.

Clarification: Subtractive Notation is required. I hadn't realized it wasn't recognized feature in the Ancient Roman empire. The task was therefore ambiguous, and I apologize.

Minimum Guidelines

Your output will be in Arabic Numerals.
You only need to convert from Roman Numerals up to 5000.
You will need to support +, -, /, * operations (addition, subtraction, division, and multiplication).
Whether division is floating point based or integer based is implementation specific. Either works for this challenge.
Your output will need to support numbers up to 4 Billion.
Shortest answer overall, AND in each language wins. This is a Code Golf Challenge but I love the variety.

In the event of a tie, factors like support for roman numerals above 5000 or additional operations will be considered the earliest submission will win.

Python 2 + roman, 118 bytes

from roman import*
s=[]
for i in input().split():s+=[eval(s.pop(-2)+i+s.pop())if i in"+-/*"else`fromRoman(i)`]
print s

Demo
It cannot be tested online because of the module it makes use of, but you can see how  to run this here (a full program accepting input from STDIN – an expression with quotes – and printing the output to STDOUT – in the form of a list, the stack). Uses a slightly older version, because I won't bother to create a new GIF for only a few bytes:

To install the package, you can run the following in the Terminal / Command Line:
pip install roman


Make a finky syntax checker You are to make a program that can check the syntax of programs of its same language. For example, if you do it in python, it checks python syntax. Your program will receive a program on standard input, and verify whether or not its syntax is correct. If it is correct, output just "true" on standard output. If not, output just "false" on standard output.

Your program must be incorrect in one instance though. If fed its own source code, it will just output "false" on standard output. This is code golf, so shortest program wins!

Note: Although this isn't technically a quine, you must follow the quine rules, meaning you can't access your source code through the file system or whatever.

Note: You can't claim a program that could not be run due to a syntax error solves this challenge, since it needs to be runnable.

Ruby 2.0, 65 76 164 characters

eval r="gets p;$<.pos=0;`ruby -c 2>&0`;p$?==0&&$_!='eval r=%p'%r"

This uses Ruby's built-in syntax checker (ruby -c) to check the input's syntax, which means the code won't be evaluated.

Basic usage example:

ruby syntax.rb <<< foo
true
ruby syntax.rb <<< "'"
false
ruby syntax.rb < synxtax.rb # assumes the file was saved without trailing newline
false

Explanation

This solution is (was) based on the standard Ruby quine:

q="q=%p;puts q%%q";puts q%q

%p is the format specifier for arg.inspect, which can be compared to uneval: when evaling the string returned by arg.inspect, you (usually) get the original value again. Thus, when formatting the q string with itself as argument, the %p inside the string will be replaced with the quoted string itself (i.e. we get something like "q=\"q=%p;puts q%%q\";puts q%q").

Generalizing this type of quine leads to something like the following:

prelude;q="prelude;q=%p;postlude";postlude

This approach has one huge drawback though (at least in code-golf): All code needs to be duplicated. Luckily, eval can be used to get around this:

eval r="some code;'eval r=%p'%r"

What happens here is that the code passed to eval is stored inside r before eval is called. As a result, the full source code of the eval statement can be obtained with 'eval r=%p'%r. If we do this inside the evald code and ensure that the top level of our consists only of the one eval statement, that expression actually gives us the full source code of our program, since any additional code passed to eval is already stored inside r.

Side note: This approach actually allows us to write a Ruby quine in 26 characters: eval r="puts'eval r=%p'%r"

Now, in this solution the additional code executed inside eval consists of four statements:

gets p

First, we read all input from STDIN and implicitly save it into $_.

$<.pos=0

Then, we rewind STDIN so the input is available again for the subprocess we start in the next step.

`ruby -c 2>&0`

This starts Ruby in its built-in syntax checking mode, reading the source code from stdin. If the syntax of the supplied script (filename or stdin) is ok, it prints Syntax OK to its stdout (which is captured by the parent process), but in case of a syntax error, a description of the error is printed to stderr - which would be visible, so we redirect that into nirvana (2>&0) instead.

p$?==0&&$_!='eval r=%p'%r

Afterwards, we check the subprocess's exit code $?, which is 0 if the syntax was ok. Lastly, the input we read earlier ($_) is compared against our own source code (which, as I described earlier, can be obtained with 'eval r=%p'%r).

Edit: Saved 14 characters thanks to @histocrat!


Simplest Tiling of the Floor You should write a program or function which receives a string describing the floor as input and outputs or returns the area of the simplest meta-tiling which could create the given pattern of the floor.

The floor is a part of a square grid. Every square tile is colored either azure or black (represented by a and b in the input).

An example floor:

  aaaa
ababab
aaaaa

A meta-tiling

is built from an N by M rectangular meta-tile of azure and black squares
the used meta-tiles are identical up to translation (you cannot rotate or mirror them)
if the sides of two meta-tiles are connected they should connect along their whole length (i.e. meta-tiles tile the space in a grid-like fashion)

An example meta-tile:

ba
aa

and the meta-tiling created by it:

       .
       .
       .
    babababa
    aaaaaaaa
... babababa ...
    aaaaaaaa
    babababa
    aaaaaaaa
       .
       .
       .

This meta-tiling creates the upper shown floor as the left letters show:

       .
       .
       .
    ********
    ***aaaa*
... *ababab* ...
    *aaaaa**
    ********
    ********
       .
       .
       .

A meta-tiling is simpler than another if the area of its meta-tile is smaller. Our example has an area of 2*2 = 4 which is the smallest possible for the example floor. So the output should be 4 for the example.

Input

A string consisting of the characters a b space and newline containing at least one a or b.
The letters (ab) form one 4-connected (side-by-side connected) shape.
There will be no unnecessary spaces at the front of the rows i.e. there will be at least one row starting with a or b.
You can choose of two input format:

No unnecessary whitespace at the end of rows (as seen in the examples).
Spaces on the right side of the rows to make all rows the same length as the longest row.

Trailing newline is optional.

Output

A single integer, the area of the smallest possible meta-tile whose tiling contains the input floor.

Examples

Examples are delimited by dashes. The three parts of an example are input, output and one of the possible smallest meta-tiles.

a

1

a
-----------------
 aaaa
aaa
a

1

a
-----------------
aabaab
abaa
aaba

6

aab
aba
-----------------
aabaab
a  a a
aabab

18

aabaab
aaaaaa
aababa
-----------------
ba
aaab

8

baaa
aaab
-----------------
 aaaa
ababb
aaaa

10

aaaaa
ababb
-----------------
 a aa
ab ba
 aba

6

aa
ab
ba
-----------------
 aaaa
abab
aaaa

4

aa
ab
-----------------
ba
 ba
  b

4

ba
ab
-----------------
baa
aba
aab

9

baa
aba
aab
-----------------
 aaaa
aabaa
aaaa

6

aaa
aab

This is code golf so the shortest entry wins.

C - 208 bytes

w,q,n,m,r,g,u;t(char*f){for(w=0;f[w++]-10;);for(q=1;;q++)for(n=1;m=q/n,n<=q;++n)if(n*m==q){char t[q];bzero(t,q);r=q;for(g=0;f[g];++g){u=g/w%m*n+g%w%n;r=t[u]+f[g]-195?r:0;if(f[g]&64)t[u]=f[g];}if(r)return r;}}

Equivalent code before golfing:

#include <stdio.h>
#include <strings.h>

int t(char* f) {
    int w = 0;
    for ( ; f[w++] - 10; );

    for (int q = 1; ; q++) {
        char t[q];
        for (int n = 1; n <= q; ++n) {
            int m = q / n;
            if (n * m == q) {
                bzero(t, q);
                int r = q;
                for (int g = 0; f[g]; ++g) {
                    int u = g / w % m * n + g % w % n;
                    if (t[u] + f[g] == 195) {
                        r = 0;
                    }
                    if (f[g] & 64) {
                        t[u] = f[g];
                    }
                }
                if (r) {
                    return r;
                }
            }
        }
    }
}

The algorithm is fairly brute force, so it should be reasonably obvious how it works based on the code. Here are a few comments anyway:

Input is expected to have the form with trailing spaces so that all lines have the same length.
First loop finds the width by looking for first newline character.
Outer loop is over candidate meta-tile sizes q. Exits with a return when a meta-tile can cover the floor. Note that the loop does not need another exit condition since there is always a solution (worst case is size of input).
First nested loop and following if enumerates valid meta-tile width/height combinations for size q.
A character array matching the candidate meta-tile size is zero-initialized.
Inner loop iterates over all tiles in the floor.
u is the index in the meta-tile that corresponds to the floor tile.
If both floor tile and meta-tile tile are a or b and different (sum of a = 97 and b = 98 is 195), there is a mismatch, and the meta-tile size with the attempted dimensions will not work.
Otherwise, if the floor tile is a or b, the tile color is copied to the candidate meta-tile.
Returns size of meta-tile when successful match was made, i.e. if the attempted match was not marked as failed.

Test code used:

#include <stdio.h>

extern int t(char* s);

int main()
{
    printf("%d\n", t(
        "a\n"
    ));
    printf("%d\n", t(
        " aaaa\n"
        "aaa  \n"
        "a    \n"
    ));
    printf("%d\n", t(
        "aabaab\n"
        "abaa  \n"
        "aaba  \n"
    ));
    printf("%d\n", t(
        "aabaab\n"
        "a  a a\n"
        "aabab \n"
    ));
    printf("%d\n", t(
        "ba  \n"
        "aaab\n"
    ));
    printf("%d\n", t(
        " aaaa\n"
        "ababb\n"
        "aaaa \n"
    ));
    printf("%d\n", t(
        " a aa\n"
        "ab ba\n"
        " aba \n"
    ));
    printf("%d\n", t(
        " aaaa\n"
        "abab \n"
        "aaaa \n"
    ));
    printf("%d\n", t(
        "ba \n"
        " ba\n"
        "  b\n"
    ));
    printf("%d\n", t(
        "baa\n"
        "aba\n"
        "aab\n"
    ));
    printf("%d\n", t(
        " aaaa\n"
        "aabaa\n"
        "aaaa \n"
    ));
    return 0;
}

Output:

1
1
6
18
8
10
6
4
4
9
6


Is it a digit haiku? We can read 13576870234289 digit-by-digit in English, and it makes a haiku:

one three five seven
six eight seven zero two
three four two eight nine

We say it's a "digit haiku", because when read out like this, it's 5+7+5 syllables long, and no word is broken across a line.
For example, 111171111101111 is not a digit haiku, even though it has 17 syllables:

one one one one se-
-ven one one one one one ze-
-ro one one one one

Two-syllable digits (0 "zero" and 7 "seven") are not allowed to span the 5th-and-6th syllable positions, or the 12th-and-13th syllable positions. (Other than that, any 17-syllable digit string makes a digit haiku.)
All other digits beside 0 and 7 are one syllable long in English.
Task
Given a non-empty string of digits (or list of numbers) 0 through 9, decide whether it forms a digit haiku.

You can assume the string does not start with 0, and thus you're also permitted to take input as a number.

You can assume the input is at most 17 digits long. However, it may be more than 17 syllables.

This is code-golf: aim to write the shortest answer, measured in bytes.

Test cases
7767677677 -> True
13576870234289 -> True
123456789012345 -> True
11111111111111111 -> True
9 -> False
9876543210 -> False
11171111101111 -> False
111171111101111 -> False
998765432101234 -> False
77777777777777777 -> False

Retina 0.8.2, 25 bytes
0|7
_#
^.{5}\w.{6}\w.{4}$

Try it online! Link includes test cases. Explanation:
0|7
_#

Expand 0 and 7 into two syllables.
^.{5}\w.{6}\w.{4}$

Check that neither the 6th nor the 13th syllable is the second such syllable.


Make me a loaf of bread before I'm fired! Backstory

Not really real, sshh!

It all started one day when a coworker brought in a homemade loaf of bread for my boss's birthday.

My boss really liked this loaf of bread, and he wanted another. Unfortunately, my coworker has quit, so my boss needs me to give him another loaf.

The problem is, I have no idea how to make bread. So I told my boss that i'm not a chef and to look harder for someone who is.

He said, "Sure...but you lose your job if you can't make me a loaf."

Then I had an idea.

I would make him an ascii-art loaf with my coding skilz! He said yes, under 1 condition: "You must make it in under 351 bytes." Unfortunately for me, my best code golfing got me to 375 bytes. Uh oh.

Then my boss added 2 things: "You must give me that loaf in a week (4/13), and if you do so you get an increased salary. The lower the amount of bytes you use, the better salary. But remember, if you go over 349 you lose your job."

So I need your help in your language of choice to help me keep my job!

Rules

I was about to do a curl ... | sh on a TinyURL, but my boss told me that I can't use a list of loopholes. I probably could skirt the rules, but my job is at stake, so it's not a good idea.

What counts as a loaf

Your program or function must take 3 positive integers as input. If your language has a list or array, you can take a list or array of those numbers. You can also take them as arguments to a function or program, or a space-separated string of numbers to STDIN, a command-line or function argument, etc.

The first number is the width of your loaf

The second number is the height of your loaf.

The third number is the depth of your loaf.

Here's a loaf with a width of 3, a height of 2, and a depth of 1:

 /---\
/---\|
|   ||
|___|/

Looks wierd? Here's a 3x2x2:

  /---\
 /    |
/---\ |
|   | /
|___|/

How about a 3x3x3:

   /---\
  /    |
 /     |
/---\  |
|   |  /
|   | /
|___|/

A 4x1x2:

  /----\
 /     |
/----\ /
|____|/

I hope you understand! See my JS (ES6) answer below for an example.

Also see complete test cases

Notes:

Don't worry about valid input. All sizes will be positive integers.
You must accept any positive integers that your language can support.
If the numbers are so high your languages crashes from StackOverflow, maximum string length overflow, etc. that's OK.

Shortest answer in bytes wins!

Charcoal, 35 33 30 bytes
Saved 2 bytes thanks to @ASCII-only
Saved 3 bytes thanks to @Neil by rearranging the order in which the lines where drawn
ＮωＮηＮδ↓η↗→×_ω↑η←\←ω↗δ→/ω↓\↓η↙δ

Try it online!
This is my first try at Charcoal. I heard it was good at ascii-art, so I tried it out.
Explanation (outdated)
ＮωＮηＮδ                  # Take the width, height and depth as input
↗¹                        # Write 1 /
↗δ                        # Write depth times /
¶ω                        # Move the cursor down and write - width times
\                         # Write \
↙↓η                       # Move the cursor one down and one left, and then write | height times
↙δ                        # Write / depth times

Now the back part of the loaf is complete. Now comes the front face.
↑↑η                       # Go up and write | height times
←\                        # Write a \ and move 1 to the left
←ω                        # Write - width times
↓↓η                       # Go down and write | height times
↗Ｐ×_ω                    # Go northeast and write _ width times


Check if three letters can form a "Godel-Escher-Bach cube" This question is inspired by the cover of the book "Godel, Escher, Bach":

The challenge here is to write a function that tells if three given letters can produce a 3D sculpture that can be read from three sides.

For this exercise, the only letters you can use are 26 5px * 5px bitmaps:

Or in binary (A to Z):

01110  11110  01111  11110  11111  11111  11111  10001  11111  11111  10001  10000  10001  10001  01110  11110  01110  11110  01111  11111  10001  10001  10001  10001  10001  11111
10001  10001  10000  10001  10000  10000  10000  10001  00100  00100  10010  10000  11011  11001  10001  10001  10001  10001  10000  00100  10001  10001  10001  01010  01010  00010
10001  11110  10000  10001  11100  11110  10011  11111  00100  00100  11100  10000  10101  10101  10001  10001  10001  11111  01110  00100  10001  01010  10001  00100  00100  00100
11111  10001  10000  10001  10000  10000  10001  10001  00100  10100  10010  10000  10001  10011  10001  11110  10011  10010  00001  00100  10001  01010  10101  01010  00100  01000
10001  11110  01111  11110  11111  10000  11111  10001  11111  11100  10001  11111  10001  10001  01110  10000  01111  10001  11110  00100  01110  00100  01010  10001  00100  11111

The sculpture is formed by three letters in the following order:

letter one on top,
letter two on the left
letter three on the right
the bottom of letter one is bound to the top of the letter two.

Example:

Your function may accept as input three uppercase letters (three chars or three strings of one letter), and output a boolean (true/false or 0/1) telling if the corresponding sculpture can exist.

Example:

f("B","E","G") // true  (because if you "sculpt out" B on top + E on the left + G on the right, and watch the three sides of the sculpture, you'll see exactly B, E and G as they are defined)
f("B","G","E") // false (because if you "sculpt out" B on top + G on the left + E on the right, and watch the three sides of the sculpture, you won't see a complete G and a complete E. Their shapes bother each other)

NB: you may return true even if the sculpture contains "flying pixels" (cubes or group of cubes that are attached to nothing).

Standard loopholes apply.

More precisely, you can't use external input besides the three letters, and you can't hardcode the 17576 possible answers in your source code

Shortest answer in characters in any language wins!

Have fun :)

Mathematica 423

I added a section called "How blocking works".

Ungolfed

(*The binary data of the alphabet are stored as a single string in s. vars imports it and converts it into an array.)

vars=IntegerDigits[#,10,5]&/@Transpose[ImportString[s,"Table"]];
get[char_]:=(ToCharacterCode[char]-64)[[1]];
cube=Flatten[Table[{i,j,k},{i,5},{j,5},{k,5}],2];

(* character slice along axis *)
slice[char_,layer_,axis_,bit_]:=Insert[(Reverse@#),layer,axis]&/@Position[Reverse@vars[[get[char]]],bit]

(* cuboid assembly  *)
charBlocks[{char_,axis_,bit_}]:=Flatten[Table[slice[char,k,axis,bit],{k,5}],1]

(* letters are those whose HOLES should be sculped out of the full cube *)
sculpturePoints[letters_(*{char_,axis_,bit_}*)]:=Complement[cube,Union[Join@@(charBlocks/@letters(*{char,axis,bit}*))]];

collapse[letters_(*{char_,axis_,bit_}*),axis_]:=Union[Reverse/@(Delete[#,axis]&/@sculpturePoints[letters(*{char,axis,bit}*)])](*/.{x_,y_}\[RuleDelayed] {6-x,y}*)

vQ[l_]:=collapse[l,3]==collapse[{l[[1]]},3]\[And]collapse[l,2]==collapse[{l[[2]]},2]\[And]collapse[l,1]==collapse[{l[[3]]},1]

validQ@l_:= vQ[{{l[[1]],3,0},{l[[2]],2,0},{l[[3]],1,0}}]

perspective[letts_,view_:1]:=
Graphics3D[{AbsolutePointSize[10],Cuboid/@sculpturePoints[letts]},
ImageSize-> 120,
ViewPoint-> Switch[view,1,{0,0,\[Infinity]},2,{0,-\[Infinity],0},3,{\[Infinity],0,0},4,Top,5,Front,6,Right,True,{0,0,\[Infinity]}],
PlotLabel-> Switch[view,1,"top orthogonal view",2,"front orthogonal view",3,"right orthogonal view",4,"top close-up view",5,"front close-up view",6,"right close-up view"],
ImagePadding->10]

Example

Is the cube {"B", "G", "E"} valid? (i.e. Will the three letters project correctly onto the walls?)

validQ[{"B", "G", "E"}]

  False

Illustrations

The figures below show how BGE is rendered. The upper row of figures takes orthogonal perspectives, as if the viewer were positioned at infinite distances from the cube.
The lower row shows how the blocks would look from close up.  The 3D figures can be manually rotated to inspect precisely where the individual unit cubes are positioned.

A problem occurs with the letter "G". There is nothing connecting the serif to the rest of the letter.

pts = {{"B", 3, 0}, {"G", 2, 0}, {"E", 1, 0}}
GraphicsGrid@Partition[Table[perspective[pts, view], {view, 1, 6}], 3]

BEG, however, should work fine.

 validQ[{"B", "E", "G"}]

  True

pts2 = {{"B", 3, 0}, {"E", 2, 0}, {"G", 1, 0}}
GraphicsGrid@Partition[Table[perspective[pts2, view], {view, 1, 6}], 3]

How Does Blocking Work?

Please excuse me if this seems obvious, but perhaps some folks will want to visualize how
how letters interfere with each other, canceling their 3D pixels.

Let's follow what happens to the letter G, in the BGE cube rendering.

We'll be paying special attention to the voxel (3D pixel or unit cube) below. That is the pixel that disappears in the BGE cube.  It is the pixel corresponding to Row 4, Column 5 in the bit array and in the corresponding array plot.

In the x y plane, the pixel corresponds to the gray disk at point (5,2). But because we're going to work in 3D, we need to consider the 5 positions in the shaft from (5,1,2) to (5,5,2).  If any of those pixels survives sculpting by the letters B and E, we'll be able to see the pixel of interest in the 3D projection on the wall.

Letters interfere when pixels are removed from the solid block.  In the left, the black arrow represents the carving out of  pixels, corresponding to the bit at the bottom right; it has the value 0 for the letter B.  Carving out removes the pixel at (5,1,2), along with those directly above and below it. Four pixels remain to be accounted for.

But as the right pane shows, the letter E sculpts out the remaining pixels of interest, (5,2,2) (5,3,2), (5,4,2) and (5,5,2). (This is due to the fact that the letter E has bits equal to 0 in the fourth row, from column 2 through column 5.) As a result, not a single pixel remains among those that were needed to ensure shade at point (5,2) on the far wall (for the letter G).  Instead, there will be a bright spot corresponding to a hole in the letter G!  The cube BGE is no good because it incorrectly renders G.

Golfed  423 chars

The function h served the same role as validQ in the unGolfed code.
The rendering function, perspective, is not included because it does not contribute to, and is not required by, the challenge.

x=Reverse;q=Flatten;
g@c_:=(ToCharacterCode[c]-64)[[1]];
r[{c_,a_,b_}]:=q[Table[Insert[(x@#),k,a]&/@Position[x@(IntegerDigits[#,10,5]&/@
Transpose[ImportString[s,"Table"]])[[g[c]]],b],{k,5}],1]
p@l_:=Complement[q[Table[{i,j,k},{i,5},{j,5},{k,5}],2],Union[Join@@(r/@l)]];
w[l_,a_]:=Union[x/@(Delete[#,a]&/@p[l])]
v@l_:=w[l,3]==w[{l[[1]]},3]\[And]w[l,2]==w[{l[[2]]},2]\[And]w[l,1]==w[{l[[3]]},1]

h@l_:= v[{{l[[1]],3,0},{l[[2]],2,0},{l[[3]],1,0}}]


Tell Me about yourself Your task is to write a self referential program similar to a quine. The objective is to write a program that will generally print to stdout twice whatever the input is. But when it receives the input of "Tell me about your source" it should output its source (like a quine). Also if it receives the query "tell me about your length". It should output its length in utf-8 characters. Like always all standard loopholes are disabled. This is code golf in any language of your choosing.

Sample Input

2

Sample Output

4

Sample Input

Tell me about your source

Sample Output

x

Sample Input

Tell me about your length

Sample Output

1

Clarifications:
The input will always be valid your program is always going to receive valid input. Your code is not required to recognize invalid input.

Javascript - 93 92 89 bytes
Defines a function f. Not sure of a better way to return.
f=n=>{y="Tell me about your ";x="f="+f;return n==y+"source"?x:n==y+"length"?x.length:2*n}


Bitflip-resistant composite numbers Sometimes, when writing a program, you need to use a prime number for some reason or other (e.g. cryptography). I assume that sometimes, you need to use a composite number, too. Sometimes, at least here on PPCG, your program has to be able to deal with arbitrary changes. And in circumstances conveniently contrived to make an interesting PPCG question, perhaps even the numbers you're using have to be resistant to corruption…

Definitions

A composite number is an integer ≥ 4 that isn't prime, i.e. it is the product of two smaller integers greater than 1. A bitflip-resistant composite number is defined as follows: it's a composite positive integer for which, if you write it in binary in the minimum possible number of bits, you can change any one or two bits from the number, and the number is still composite.

Example

For example, consider the number 84. In binary, that's 1010100. Here are all the numbers which differ by no more than 2 bits from that:

0000100    4   2×2
0010000   16   4×4
0010100   20   4×5
0010101   21   3×7
0010110   22   2×11
0011100   28   4×7
0110100   52   4×13
1000000   64   8×8
1000100   68   4×17
1000101   69   3×23
1000110   70   7×10
1001100   76   4×19
1010000   80   8×10
1010001   81   9×9
1010010   82   2×41
1010100   84   7×12
1010101   85   5×17
1010110   86   2×43
1010111   87   3×29
1011000   88   8×11
1011100   92   4×23
1011101   93   3×31
1011110   94   2×47
1100100  100  10×10
1110000  112   8×14
1110100  116   4×29
1110101  117   9×13
1110110  118   2×59
1111100  124   4×31

The first column is the number in binary; the second column is the number in decimal. As the third column indicates, all of these numbers are composite. As such, 84 is a bitflip-resistant composite number.

The task

You must write one of the following three programs or functions, whichever makes the most sense for your language:

A program or function that takes a nonnegative integer n as input, and outputs the first n bitflip-resistant composite numbers.
A program or function that takes a nonnegative integer n as input, and outputs all bitflip-resistant composite numbers less than n (or if you prefer, less than or equal to n, i.e. you can choose whether n is included in the output if bitflip-resistant).
A program or function that takes no input, and outputs all bitflip-resistant composite numbers. (This must use an output mechanism capable of producing output while the program is still running, such as printing to stdout, a lazy list, or a generator; you can't just calculate the entire list and then print it.)

Test cases

Here are the first few bitflip-resistant composite numbers:

84, 184, 246, 252, 324, 342, 424, 468, 588, 636, 664, 670, 712, 730, 934, 958

Clarifications

It's only the numbers you produce that have to be resistant to bitflips. This isn't a task about making the program that finds them resistant to bitflips; use whatever numbers in the program itself that you like.
The numbers you output don't have to be resistant to a bitflip in the "leading zeroes"; imagine that the numbers will be stored in the minimum possible number of bits, and only those bits have to be immune to flipping. However, the initial 1 bits on the numbers you output do have to be immune to bitflips.
Use any algorithm you like that produces the right result; you aren't being marked on efficiency here.
If you can prove that there are finitely many bitflip-resistant composite numbers, then a) the restrictions on output format are lifted, and b) hardcoding the list will be allowed (although probably more verbose than just calculating it). This rule is mostly just for completeness; I don't expect it to be relevant.

Victory condition

This is code-golf, so as usual, shorter is better. Also as usual, the length of the program will be measured in bytes.


Are You the One? (Mastermind Derivative) I've got a tough one for you!

My girlfriend recently came across a new show on MTV (USA). It's a terrible show, and everyone on it is trashy, but the "game" is pretty interesting.  From Wikipedia:

  Are You The One? follows 20 people who are living together in Hawaii to find their perfect match. If the 10 men and 10 women are
  able to correctly choose all ten perfect matches in ten weeks, they
  will gain $1 million to split among them.

Now for the game portion (also from Wikipedia):

  Each episode the cast will pair up with who they believe their perfect
  match is to compete in a challenge. The winners of the challenge will
  go on a date, and have a chance to test their match in the truth
  booth. The cast members will choose one of the winning couples to go
  to the truth booth to determine if they are a perfect match or not.
  This is the only way to confirm matches. Each episode ends with a matching ceremony where the couples will be told how many perfect
  matches they have, but not which matches are correct.

TL;DR:  This is a Mastermind derivative ( M(10,10) to be specific). The rules of the game are as follows:

You start with 2 sets of 10, let's call them Set A:
{A,B,C,D,E,F,G,H,I,J} and Set 2: {1,2,3,4,5,6,7,8,9,10}
The computer creates a solution (not visible to you) in the form
of {A1,B2,C3,D4,E5,F6,G7,H8,I9,J10}, where the members in set A are
mapped 1-to-1 to set 2. Another example of a solution could be
{A2,B5,C10,D8,E1,F7,G6,H4,I9,J3}.
Before your first turn, you get to ask if a single, particular
pair of your choice is correct. Your question would be in the form
of {A1} (e.g. {C8}), and you receive either a 1 (meaning correct) or
0 (meaning your guess is incorrect).
Your first actual turn. You make your first guess in the form of
{A1,B2,C3,D4,E5,F6,G7,H8,I9,J10}, or any permutation of your choice.
Your guess cannot contain multiples of any item i.e. a guess of {A1,A2,A3,A4,A5,B6,B7,B8,B9,B10} is NOT a valid guess. After each
turn, the computer tells you the number of correct matches, but
NOT which matches are correct.
Repeat steps 3 and 4 until you get every match correct (i.e. a
response of 10), or until your 10 moves are up (whichever is
sooner). If you solve it before or on your 10th turn, you win $1
million. Otherwise, you lose, and some people (or letters and
numbers) go home alone to spend eternity with their 10 cats.

This is NOT a shortest code contest. The person who can solve a random matching in the least average number of guesses will be the winner. Clever game playing and calculation speed will also likely factor in. I am assuming the average number of turns will almost certainly be greater than 10, so the odds of you winning the $1 million prize (presumably paid by MTV, not me) is slim. Just how impossible is it for the cast to win the grand prize?

Note: Putting it in the {A1, B2, ...} format is not necessarily required. I simply used that form in the question to make it absolutely clear what the puzzle is. If you do not put it in this form, please just explain how to call it.

Good luck!

Python 2 (run faster if run using Pypy)

Believed to almost always guess the correct pairing in 10 rounds or lower

My algorithm is taken from my answer for mastermind as my hobby (see in Ideone). The idea is to find the guess which minimize the number of possibilities left in the worst case. My algorithm below just brute force it, but to save time, it just pick random guess if the number of possibilities left is larger than RANDOM_THRESHOLD. You can play around with this parameter to speed things up or to see better performance.

The algorithm is quite slow, on average 10s for one run if run using Pypy (if using normal CPython interpreter it's around 30s) so I can't test it on the whole permutations. But the performance is quite good, after around 30 tests I haven't seen any instance where it can't find the correct pairing in 10 rounds or lower.

Anyway, if this is used in real life show, it has plenty of time before the next round (one week?) so this algorithm can be used in real life =D

So I think it's safe to assume that on average this will find the correct pairings in 10 guesses or lower.

Try it yourself. I might improve the speed in the next few days (EDIT: it seems difficult to further improve, so I'll just leave the code as is. I tried only doing random pick, but even at size=7, it fails in 3 of the 5040 cases, so I decided to keep the cleverer method). You can run it as:

pypy are_you_the_one.py 10

Or, if you just want to see how it works, input smaller number (so that it runs faster)

To run a full test (warning: it'll take very long for size > 7), put a negative number.

Full test for size=7 (completed in 2m 32s):

...
(6, 5, 4, 1, 3, 2, 0): 5 guesses
(6, 5, 4, 2, 0, 1, 3): 5 guesses
(6, 5, 4, 2, 0, 3, 1): 4 guesses
(6, 5, 4, 2, 1, 0, 3): 5 guesses
(6, 5, 4, 2, 1, 3, 0): 6 guesses
(6, 5, 4, 2, 3, 0, 1): 6 guesses
(6, 5, 4, 2, 3, 1, 0): 6 guesses
(6, 5, 4, 3, 0, 1, 2): 6 guesses
(6, 5, 4, 3, 0, 2, 1): 3 guesses
(6, 5, 4, 3, 1, 0, 2): 7 guesses
(6, 5, 4, 3, 1, 2, 0): 7 guesses
(6, 5, 4, 3, 2, 0, 1): 4 guesses
(6, 5, 4, 3, 2, 1, 0): 7 guesses
Average count: 5.05
Max count    : 7
Min count    : 1
Num success  : 5040

If RANDOM_THRESHOLD and CLEVER_THRESHOLD are both set to a very high value (like 50000), it'll force the algorithm to find the optimal guess that minimizes the number of possibilities in the worst case. This is very slow, but very powerful. For example, running it on size=6 asserts that it can find the correct pairings in maximum 5 rounds.

Although the average is higher compared to using the approximation (which is 4.11 rounds on average), but it always succeeds, even more with one round left to spare. This further strengthen our hypothesis that when size=10, it should almost always find the correct pairings in 10 rounds or less.

The result (completed in 3m 9s):

(5, 4, 2, 1, 0, 3): 5 guesses
(5, 4, 2, 1, 3, 0): 5 guesses
(5, 4, 2, 3, 0, 1): 4 guesses
(5, 4, 2, 3, 1, 0): 4 guesses
(5, 4, 3, 0, 1, 2): 5 guesses
(5, 4, 3, 0, 2, 1): 5 guesses
(5, 4, 3, 1, 0, 2): 5 guesses
(5, 4, 3, 1, 2, 0): 5 guesses
(5, 4, 3, 2, 0, 1): 5 guesses
(5, 4, 3, 2, 1, 0): 5 guesses
Average count: 4.41
Max count    : 5
Min count    : 1
Num success  : 720

The code.

from itertools import permutations, combinations
import random, sys
from collections import Counter

INTERACTIVE = False
ORIG_PERMS = []
RANDOM_THRESHOLD = 100
CLEVER_THRESHOLD = 0

class Unbuffered():
    def __init__(self, stream):
        self.stream = stream

    def write(self, data):
        self.stream.write(data)
        self.stream.flush()

    def __getattr__(self, attr):
        self.stream.getattr(attr)
sys.stdout = Unbuffered(sys.stdout)

def init(size):
    global ORIG_PERMS
    ORIG_PERMS = list(permutations(range(size)))

def evaluate(solution, guess):
    if len(guess) == len(solution):
        cor = 0
        for sol, gss in zip(solution, guess):
            if sol == gss:
                cor += 1
        return cor
    else:
        return 1 if solution[guess[0]] == guess[1] else 0

def remove_perms(perms, evaluation, guess):
    return [perm for perm in perms if evaluate(perm, guess)==evaluation]

def guess_one(possible_perms, guessed_all, count):
    if count == 1:
        return (0,0)
    pairs = Counter()
    for perm in possible_perms:
        for pair in enumerate(perm):
            pairs[pair] += 1
    perm_cnt = len(possible_perms)
    return sorted(pairs.items(), key=lambda x: (abs(perm_cnt-x[1]) if x[1]<perm_cnt else perm_cnt,x[0]) )[0][0]

def guess_all(possible_perms, guessed_all, count):
    size = len(possible_perms[0])
    if count == 1:
        fact = 1
        for i in range(2, size):
            fact *= i
        if len(possible_perms) == fact:
            return tuple(range(size))
        else:
            return tuple([1,0]+range(2,size))
    if len(possible_perms) == 1:
        return possible_perms[0]
    if count < size and len(possible_perms) > RANDOM_THRESHOLD:
        return possible_perms[random.randint(0, len(possible_perms)-1)]
    elif count == size or len(possible_perms) > CLEVER_THRESHOLD:
        (_, next_guess) = min((max(((len(remove_perms(possible_perms, evaluation, next_guess)), next_guess) for evaluation in range(len(next_guess))), key=lambda x: x[0])
                               for next_guess in possible_perms if next_guess not in guessed_all), key=lambda x: x[0])
        return next_guess
    else:
        (_, next_guess) = min((max(((len(remove_perms(possible_perms, evaluation, next_guess)), next_guess) for evaluation in range(len(next_guess))), key=lambda x: x[0])
                               for next_guess in ORIG_PERMS if next_guess not in guessed_all), key=lambda x: x[0])
        return next_guess

def main(size=4):
    if size < 0:
        size = -size
        init(size)
        counts = []
        for solution in ORIG_PERMS:
            count = run_one(solution, False)
            counts.append(count)
            print '%s: %d guesses' % (solution, count)
        sum_count = float(sum(counts))
        print 'Average count: %.2f' % (sum_count/len(counts))
        print 'Max count    : %d' % max(counts)
        print 'Min count    : %d' % min(counts)
        print 'Num success  : %d' % sum(1 for count in counts if count <= size)
    else:
        init(size)
        solution = ORIG_PERMS[random.randint(0,len(ORIG_PERMS)-1)]
        run_one(solution, True)

def run_one(solution, should_print):
    if should_print:
        print solution
    size = len(solution)
    cur_guess = None
    possible_perms = list(ORIG_PERMS)
    count = 0
    guessed_one = []
    guessed_all = []
    while True:
        count += 1
        # Round A, guess one pair
        if should_print:
            print 'Round %dA' % count
        if should_print:
            print 'Num of possibilities: %d' % len(possible_perms)
        cur_guess = guess_one(possible_perms, guessed_all, count)
        if should_print:
            print 'Guess: %s' % str(cur_guess)
        if INTERACTIVE:
            evaluation = int(raw_input('Number of correct pairs: '))
        else:
            evaluation = evaluate(solution, cur_guess)
            if should_print:
                print 'Evaluation: %s' % str(evaluation)
        possible_perms = remove_perms(possible_perms, evaluation, cur_guess)

        # Round B, guess all pairs
        if should_print:
            print 'Round %dB' % count
            print 'Num of possibilities: %d' % len(possible_perms)
        cur_guess = guess_all(possible_perms, guessed_all, count)
        if should_print:
            print 'Guess: %s' % str(cur_guess)
        guessed_all.append(cur_guess)
        if INTERACTIVE:
            evaluation = int(raw_input('Number of correct pairs: '))
        else:
            evaluation = evaluate(solution, cur_guess)
            if should_print: print 'Evaluation: %s' % str(evaluation)
        if evaluation == size:
            if should_print:
                print 'Found %s in %d guesses' % (str(cur_guess), count)
            else:
                return count
            break
        possible_perms = remove_perms(possible_perms, evaluation, cur_guess)

if __name__=='__main__':
    size = 4
    if len(sys.argv) >= 2:
        size = int(sys.argv[1])
        if len(sys.argv) >= 3:
            INTERACTIVE = bool(int(sys.argv[2]))
    main(size)


Pretty-print my BQN Arrays Marshall Lochbaum's online BQN REPL has an interesting(and aesthetically pleasing) method of displaying arrays. Your task is to implement a version with simpler rules.
[2,[3],4,[[[6,[5],7]]]]

becomes:
┌─
· 2 ┌·    4 ┌·
    · 3     · ┌·
        ┘     · ┌─
                · 6 ┌·    7
                    · 5
                        ┘
                            ┘
                              ┘
                                ┘
                                  ┘

Rules for drawing

A singleton array has

┌·
·

as its top left corner.

A non-singleton array has

┌─
·

as its top left corner.
(In the actual BQN, this is used for rank-0, or "unit" arrays)

All arrays have

┘

as their bottom right corner.

Each element at a certain depth will be displayed at the same depth vertically.
For example, 2 and 4 are displayed 1 unit from the top since they are at depth 1.
Each further level of nesting depth moves 1 unit down in depth.
Numbers next to each other will be separated by a single space.

Other details

You may take a ragged numeric array in any way your language supports.
The input will only consist of integers and nested arrays containing integers.
If your language does not support arrays with depth, you may take a string/other equivalent that your language supports.
If your language's codepage does not contain the characters ┌ · ─ ┘, you can count them as 1 byte.
This is code-golf. Shortest answer in each language wins.
Since bacon strips are thin, your code must be thin and small as well.

Charcoal, 72 bytes
ＦＳ≡ι(«⊞υⅉＰ⌈┌´·↘→⊞υⅉ»)«≔⊕⊟υιＭ¹⁻ιⅉ┘Ｍ⁻ⅉ⊟υ↑¿υ⊞υ⌈⟦ι⊟υ⟧»,«↑≔ＫＤ⊕ⅈ←ι§≔ι⊖⌕ι┌¦─↘»ι

Try it online! Link is to verbose version of code. Uses lists rather than arrays because they're easier to input. Explanation:
ＦＳ≡ι

Switch over each character of the input as a string.
(«

For a (, ...
⊞υⅉ

... save the vertical position as the top margin, ...
Ｐ⌈┌´·↘→

... assume a single-element list, ...
⊞υⅉ

... and save the vertical position again, this time as the bottom margin.
»)«

For a ), ...
≔⊕⊟υι

... get the bottom margin of this list, plus 1, ...
Ｍ¹⁻ιⅉ

... move to that row, ...
┘

... close the list, ...
Ｍ⁻ⅉ⊟υ↑

... move to and forget the top margin of this list, ...
¿υ⊞υ⌈⟦ι⊟υ⟧

... and update the bottom margin of the containing list if necessary.
»,«

For a ,, ...
↑≔ＫＤ⊕ⅈ←ι

... grab the text on the previous row, ...
§≔ι⊖⌕ι┌¦─

... find the ┌ and change the character after it to a ─, ...
↘

... and move to the next column on the original row.
»ι

Otherwise, just output the current character.
Note that the · is in Charcoal's code page (so because it needs to be quoted it ends up costing me two bytes!) but the box-drawing characters are not. They would normally cost three bytes in Charcoal so as I use them four times I have subtracted 8 bytes from Charcoal's calculation.


Generate Menu Access Keys This is thematically similar to Generate keyboard shortcuts for a menu, but its actually a pretty different challenge.

Let's take PHPStorm's menu as an example:

New Project
New
Open Directory
Open
Open URL
New Project from Existing Files
Save As
Open Recent
Close Project
Rename Project

We need to assign a single-letter access keys for each of these menu items.  Typically we pick the first letter, but if you notice, many of the above menu items start with the same letter!

Therefore, we'd want to pick:

P -> New Project
N -> New
D -> Open Directory
O -> Open
U -> Open URL
F -> New Project from Existing Files
S -> Save As
E -> Open Recent  (We don't pick "R" here because "Rename Project" needs it)
C -> Close Project
R -> Rename Project

Therefore, for our list we need to maximize (in order of importance):

The number of access keys actually contained in the string.

["X" -> "New"] should be avoided unless its your only option.

The number of access keys that start a word.

["N"->"New", "P"->"New Project"] is better than ["E"->"New", "N"->"New Project"]

The number of access keys that start the sentence.

["N"->"New Project"] is better than ["P"->"New Project"]

Access keys are case-insensitive, so if your menu is ["Add", "add"], one of them will need to use D as its access key.

Input/output

You need to input a list of strings.  The strings will only contain alphabetic characters and spaces.  You can optionally input a single string with a delimiter for each of the lines.  You can assume there will be between 1 and 26 menu items (inclusive).

You need to output either:

A Key-value map, where the key is the access key letter, and the value is the string it maps to
A list of access key letters, where the Nth entry pairs with the Nth item in the list.

You can either return the objects themselves, or a reasonable string representation of them. Access key letters can be in any case.

Test Cases:

A                            -> A
Add,add                      -> A,D
Add To,Add                   -> T,A
Add To,Add Around,Add For    -> T,A,F
Add To,Flip To,Add For       -> T,F,A
Add,add,Dip,Around           -> A,D,I,R
Add,add,Dad                  -> A,B,D
Add,add,Dad,dad,ad dadad,B   -> A,C,D,E,Z,B
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,A,B,C -> A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,Add,Bz,Cx -> A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,Y,Z,X

Jelly, 41 bytes
e/€S;eḲ1ịⱮƊ}¥/€;=Ḣ¥/€µS
LØAœ!ż€³Œu¤ÇÐṀẎḢ€

Try it online!
This is really messy and also O(26^n) lol.
Explanation: literally just brute forces it ._.
-6 bytes thanks to caird coinheringaahing


Is the word coprime? Given a word, treat every letter as it's number in English alphabet (so a becomes 1, b becomes 2, z becomes 26 and so on), and check if all of them, including duplicates, are pairwise coprime.

The input is exactly one word of lowercase English letters. The output is the fact if the word is coprime: any truthy/falsey values, but only two variants of them. Standard loopholes are forbidden.

Test cases:

man: True
day: True (thanks to Ørjan Johansen)
led: False (l=12 and d=4 have gcd=4)
mana: True (though a occurs multiple times, 1 and 1 are coprimes)
mom: False (gcd(13,13)=13))
of: False (thanks to xnor; though 15∤6, gcd(15,6)=3)
a: True (if no pairs of letters, treat the word as coprime too)

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

Wolfram Language (Mathematica), 36 bytes

CoprimeQ@@LetterNumber@Characters@#&

Try it online!

Wolfram Language (Mathematica), 33 bytes

Thanks to Misha Lavrov for this three bytes shorter version.

CoprimeQ@@(ToCharacterCode@#-96)&

Try it online!


Is the input Bl lu ur rr ry? This is based off this challenge.

Given an input string, check whether the string is blurry.

What's a blurry string?

A blurry string is a string that's contained in the set of all blurrified pure-ASCII strings.

Take a non-blurrified pure-ASCII string abc as an example. You repeat every character of this twice:

aabbcc

And then insert spaces at every odd-even index.

a ab bc c

Then, remove the preceding 2 and succeeding 2 extra characters. If there isn't enough space left, ignore the abundant removing instructions.

ab bc

As an example, all of these strings are blurry (the empty line stands for an empty string):

Before  After
"a"   ->
"ab"  ->ab
"abc" ->ab bc
"abcd"->ab bc cd
...

(Before = the string before blurrification)
(After  = the string after blurrification,
i.e. the strings in the set of all blurry strings.)

Specification

The input string consists purely of printable ASCII characters. The only whitespace it will contain is the space character.
You don't have to remove extra characters before the check.
Your output can consist of any trailing whitespace, as long as it's possible to tell a truthy result from a falsy result.
It's noteworthy that the definition of "blurry" in this challenge is different than the previous challenge.

Test cases

Here is a program I use to check my test cases.

""          -> True
"ab"        -> True
"ab bc"     -> True
"aa aa"     -> True
"ab bc cd"  -> True
" b bc cd"  -> True
"ab bc c "  -> True
"a   c cd"  -> True
"        "  -> True

"a"         -> False
"abc"       -> False
"ab  bc  cd"-> False
"ab#bc#cd"  -> False
"abbccd"    -> False
"a ab bc cd"-> False
"a a ab b b"-> False
"ba cb dc"  -> False
"ba bc dc"  -> False
"FFaallssee"-> False
"a aa a"    -> False

Retina, 14 bytes
a`.((.) \2)*.|

Try it online!
Explanation
a forces the match to be on the entire string
.((.) \2)*. just means any character (.) followed by a captured group repeated 0 to many times ((...)*) of any character saved into a second captured group ((.)) followed by a space and the same character that was matched in the second capture group (\2). The final . just matches the last character
| allows the empty string to match by having an alternative match of the empty string


Create a Question Asker! Writing questions for programming puzzles is tiring and takes many minutes to do. This is where you come in. Your job is to write a program that randomly generates plausible-sounding (but not necessarily interesting) code golf questions.

Input: None

Output: One sentence code golf question (see sentence structure)

Guidelines: No hardcoding. The questions don't have to be valid, solvable, or nontrivial. Creativity is encouraged. Voting is based on variety and bonus to programs that can create interesting problems.

Samples:

Find the sum of every even number from 1 to 100.
Create a funny sentence without punctuation.
Draw a picture of a cat in 3D.

Sentence structure:

[verb] [noun goal] [of] [noun specific] [preposition] [noun restriction]

NetLogo
to go
  type one-of [ "Print" "Calculate" "Find" "Determine" "Output" ]
  type " the "
  type one-of [ "sum" "mean" "average" "median" "standard deviation" "product" "geometric mean"]
  type " of all "
  type one-of [ "prime" "composite" "even" "odd" "perfect" "abundant" "deficient" "square" "triangular" "cubic" "lucky" "friendly" "strictly non-palindromic" ]
  type " numbers from "
  type random 100
  type " to "
  type 100 + random 10000
  type one-of [ " (inclusive)." " (exclusive)." ]
end

Sample output (obtained randomly):
Find the product of all friendly numbers from 60 to 3112 (inclusive).


Make a minimal and maximal 2-digit number from digits of two 3-digit numbers Let's solve this user's homework; I think it's an interesting exercise!
Input
Two 3-digit natural numbers.
Outputs
Two 2-digit numbers. In each of the output numbers, one digit is taken from one input number, and the other from the other number. The choice is independent. The first output number should be the minimal possible to create using these constraints, and the second one should be the maximal such number (or vice versa).

Input numbers never have leading zeros; output numbers should also not have leading zeros.
Input and output can be encoded as numbers, strings, lists of digits, etc.

Examples (in format input - output):
123, 912 - 11, 93
888, 906 - 68, 98
100, 100 - 10, 11
222, 222 - 22, 22
123, 222 - 12, 32
798, 132 - 17, 93

Husk, 15 14 13 9 bytes
§,▼▲f←ṁP*

Try it online!
Takes two input arrays, outputs pair (min,max).
-1 byte from Dominic Van Essen.
-1 more byte from Dominic Van Essen (after some more struggling).
-4 bytes taking arrays of digits as input.
Explanation
§,▼▲f←ṁP*
        * cartesian product pairs of the inputs
      ṁP  map each to permuations, and flatten the list
    f←    remove elements where first digit is falsy(<10)
§,        create pair with
  ▼▲      minimum and maximum


Largest Product in MxN grid Given an MxN grid of numbers, find the greatest product of a length 4 subsequence in any row, column, or diagonal. Subsequences cannot wrap around (e.g. 5 1 2 3 in the row 1 2 3 4 5).

I/O can be anything reasonable: files, stdin/stdout, copy+pasting expressions/arguments, variables. (If I'm missing any esoteric I/O option, feel free to go ahead and post your solution anyways)

J, 26 chars

>./,4*/\"1(,|:,]/.,]/.@|.)

Just an expression to which a rank 2 array could be appended.

,|:,]/.,]/.@|. takes the rank 2 array and concatenates 4 intermediate rank 2 arrays, the input's identity, transposition, and obliques, respectively. Here I feel like there's an uncomfortable amount of redundancy, because there are 2 ]s, 3 ,s, and 2 /.s... I can't think of a way to refactor those out.

>./,4*/\"1 is just a straightforward maximum of each length 4 subsequence of each row of the newly made array, which of course corresponds to rows/columns/diagonals of the original.


Find all the numbers have this property, its double and its triple contain each digit from 1 to 9 exactly once 192 is such a number, together with its double (384) and triple (576) they contain each 1-9 digit exactly once. Find all the numbers have this property.

No input.

Output:

192 384 576
219 438 657
273 546 819
327 654 981

APL (20)

192 219 273 327∘.×⍳3

Just prints the numbers multiplied by 1, 2, and 3.

Without hardcoding (25)

{∧/1↓⎕D∊⍕k←⍵×⍳3:⎕←k}¨⍳400


Testing if a number is a square Write a GOLF assembly program that given a 64-bit unsigned integer in register n puts a non-zero value into register s if n is a square, otherwise 0 into s.

Your GOLF binary (after assembling) must fit in 4096 bytes.

Your program will be scored using the following Python3 program (which must be put inside the GOLF directory):

import random, sys, assemble, golf, decimal

def is_square(n):
    nd = decimal.Decimal(n)
    with decimal.localcontext() as ctx:
        ctx.prec = n.bit_length() + 1
        i = int(nd.sqrt())
        return i*i == n

with open(sys.argv[1]) as in_file:
    binary, debug = assemble.assemble(in_file)

score = 0
random.seed(0)
for i in range(1000):
    cpu = golf.GolfCPU(binary)

    if random.randrange(16) == 0: n = random.randrange(2**32)**2
    else:                         n = random.randrange(2**64)

    cpu.regs["n"] = n
    cpu.run()
    if bool(cpu.regs["s"]) != is_square(n):
        raise RuntimeError("Incorrect result for: {}".format(n))
    score += cpu.cycle_count
    print("Score so far ({}/1000): {}".format(i+1, score))

print("Score: ", score)

Make sure to update GOLF to the latest version with git pull. Run the score program using python3 score.py your_source.golf.

It uses a static seed to generate a set of numbers of which roughly 1/16 is square. Optimization towards this set of numbers is against the spirit of the question, I may change the seed at any point. Your program must work for any non-negative 64-bit input number, not just these.

Lowest score wins.

Because GOLF is very new I'll include some pointers here. You should read the  GOLF specification with all instructions and cycle costs. In the Github repository example programs can be found.

For manual testing, compile your program to a binary by running python3 assemble.py your_source.golf. Then run your program using python3 golf.py -p s your_source.bin n=42, this should start the program with n set to 42, and prints register s and the cycle count after exiting. See all the values of the register contents at program exit with the -d flag - use --help to see all flags.

Score: 27462
About time I'd compete in a GOLF challenge :D
    # First we look at the last 6 bits of the number. These bits must be
    # one of the following:
    #
    #     0x00, 0x01, 0x04, 0x09, 0x10, 0x11,
    #     0x19, 0x21, 0x24, 0x29, 0x31, 0x39
    #
    # That's 12/64, or a ~80% reduction in composites!
    #
    # Conveniently, a 64 bit number can hold 2**6 binary values. So we can
    # use a single integer as a lookup table, by shifting. After shifting
    # we check if the top bit is set by doing a signed comparison to 0.

    and b, n, 0b111111
    shl v, 0xc840c04048404040, b
    le q, v, 0
    jz no, q
    jz yes, n

    # Hacker's Delight algorithm - Newton-Raphson.
    mov c, 1
    sub x, n, 1
    geu q, x, 2**32-1
    jz skip32, q
    add c, c, 16
    shr x, x, 32
skip32:
    geu q, x, 2**16-1
    jz skip16, q
    add c, c, 8
    shr x, x, 16
skip16:
    geu q, x, 2**8-1
    jz skip8, q
    add c, c, 4
    shr x, x, 8
skip8:
    geu q, x, 2**4-1
    jz skip4, q
    add c, c, 2
    shr x, x, 4
skip4:
    geu q, x, 2**2-1
    add c, c, q

    shl g, 1, c
    shr t, n, c
    add t, t, g
    shr h, t, 1

    leu q, h, g
    jz newton_loop_done, q
newton_loop:
    mov g, h
    divu t, r, n, g
    add t, t, g
    shr h, t, 1
    leu q, h, g
    jnz newton_loop, q
newton_loop_done:

    mulu u, h, g, g
    cmp s, u, n
    halt 0
yes:
    mov s, 1
no:
    halt 0


Almost Illegal Strings, Mark II (Robbers) This is the robbers' thread for 'Almost Illegal Strings'.
See the cop's thread for information on participating. A section from the post is included here for convenience.

The Robbers' Challenge
Find an uncracked answer. Write a program in the language specified that contains as a contiguous substring the almost illegal string specified and does not error. Your program may not use any character in the set of banned characters, unless it is part of the almost illegal string. Your program does not need to be exactly what the cop had in mind. Post an answer to the robber's thread and leave a comment on the cops' answer to crack it.

Python 2, 7 bytes, cracks xnor's post

0xbin()

Try it online!
The answer is easy to understand if syntax highlighting for above snippet works correctly.
So bad. The syntax highlighting did work correctly. But SO changed their render library... Anyway, above code is:
0xb in ()


Circle intersection area Description :
Given x and y positions of two circles along with their radii, output the area of intersection of the two circle.

Input :
You will be given following input :
array 1 = x and y positions of circle a
array 2 = x and y positions of circle b
radius  = radii of the two congruent circles

Input method :
([12 , 20] , [20 , 18] , 12)     ---> two array and number
([12 , 20 , 20 , 18] , 12)       ---> array and a number
(12 , 20 , 20 , 18 , 12)         ---> all five numbers
('12 20' , '20 18' , 12)         ---> 2 strings and a number
('12 20 20 18' , 12)             ---> string and a number
('12 20 20 18 12')               ---> one string

Output :

A non-negative integer (no decimal) equal to area of intersection of two circles.

A string equal to the above mentioned integer.

Note :

Output must be >= 0, since area can't be negative.
In case of decimal round down to nearest integer

Examples :
([0, 0], [7, 0], 5)                   ---> 14

([0, 0], [0, 10], 10)                 ---> 122

([5, 6], [5, 6], 3)                   ---> 28

([-5, 0], [5, 0], 3)                  ---> 0

([10, 20], [-5, -15], 20)             ---> 15

([-7, 13], [-25, -5], 17)             ---> 132

([-12, 20], [43, -49], 23)            ---> 0

Winning criteria :
This is code-golf so shortest code in bytes for each language wins.

Suggestions :

Provide a TIO link so it can be tested.
Provide an explanation so others can understand your code

These are only suggestions and are not mandatory.

JavaScript (ES6), 72 bytes
Alternate formula suggested by @ceilingcat
Takes input as 5 distinct parameters (x0, y0, x1, y1, r).
with(Math)f=(x,y,X,Y,r)=>-(sin(d=2*acos(hypot(x-X,y-Y)/r/2))-d)*r*r*2>>1

Try it online!

JavaScript (ES7), 81 80 77 bytes
Saved 3 bytes thanks to @Neil
Takes input as 5 distinct parameters (x0, y0, x1, y1, r).
(x,y,X,Y,r,d=Math.hypot(x-X,y-Y))=>(r*=2)*r*Math.acos(d/r)-d*(r*r-d*d)**.5>>1

Try it online!
How?
This is based on a generic formula from MathWorld for non-congruent circles:
A = r².arccos((d² + r² - R²) / 2dr) +
    R².arccos((d² + R² - r²) / 2dR) -
    sqrt((-d + r + R)(d + r - R)(d -r + R)(d + r + R)) / 2

where d is the distance between the two centers and r and R are the radii.
With R = r, this is simplified to:
A = 2r².arccos(d / 2r) + d.sqrt((2r - d) * (2r + d)) / 2

And with r' = 2r:
A = (r'².arccos(d / r') + d.sqrt(r'² - d²)) / 2

Note: If d is greater than 2r, Math.acos() will return NaN, which is coerced to 0 when the right-shift is applied. This is the expected result, because d > 2r means that there's no intersection at all.


Primitive Roots of Unity Let z be a complex number. z is an nth primitive root of unity if for a certain positive integer n  and for any positive integer k < n .
Challenge
Write a full program or function that, given a positive integer n as input, outputs all of the nth primitive roots of unity. You may output them in polar form (e^θi or e^iθ, argument should be a decimal with at least 2 decimal places) or rectangular form (a + bi or a similar form, real and imaginary parts should also be decimals), and they may be outputted in your language's list/array format or as a string with the numbers separated by spaces or newlines. Built-ins that calculate the nth roots of unity or the nth primitive roots of unity are not allowed.
This is code-golf, so shortest code in bytes wins.
Sample Inputs and Outputs
6 -> e^1.05i, e^-1.05i # polar form
3 -> e^2.094395i, e^-2.094395i # any number of decimal places is OK as long as there are more than 2
8 -> 0.707 + 0.707i, 0.707 - 0.707i, -0.707 + 0.707i, -0.707 - 0.707i # rectangular form
1 -> 1 + 0i # this is OK
1 -> 1 # this is also OK
4 -> 0 + i, 0 - i # this is OK
4 -> i, -i # this is also OK

Jelly, 11 9 bytes
Thanks to @Dennis for -2 bytes!
Rg=1O÷H-*

I wanted to generate the numbers coprime to N by folding set difference over all of the roots of unity from 1 to N, but I couldn't figure out how so I used @Dennis's method.
Rg=1O÷H-*         Monadic chain:          6
R                 Range                   [1,2,3,4,5,6]
 g                Hook gcds with range    [1,2,3,2,1,6]
  =1              [gcds equal to one]     [1,0,0,0,1,0]
    O             Replicate indices       [1,5]
     ÷H           Divide by half of N     [1/3,5/3]
       -          Numeric literal: - by itself is -1.
        *         Take -1 to those powers [cis π/3,cis 5π/3]

Try it here. Valid in this version of Jelly, but may not be in versions after February 1, 2016.


Simple portmanteau with longest overlap I've been using a library called Djangular recently, which integrates Django and Angular.

After a while I thought 'Wouldn't it be fun to programmatically generate portmanteau?'

Here are some examples (e.g. testcases):

Django + Angular -> Djangular
Camel + Leopard -> Cameleopard
Spoon + Fork -> Spoork
Ham + Hammer -> Hammer

The general rule is to find the first common letter working backwards on first word, and working forwards on the last word. Not all portmanteau can be found this way though...

I've deliberately picked 'simple' ones to generate (for instance we're ignoring things like Zebra + Donkey = Zedonk, which is too arbitrary to generate programmatically - the correct behaviour).

Ties can be resolved eitherway - suppose you have cart + ante - both carte, (since t is the last common letter in the first word) and cante, (since a is the first common letter of the last word) are value.
Unfun loopholes are not allowed (including pulling 'solved' examples off wikipedia)

This is code golf, so shortest answer wins. I'll pick the winner a month from posting. Please post the output for all your code.

Python 3, 128 79 bytes

Let me know if I got anything wrong and critiques are always welcome.

def f(a,b):
    c=len(a)-1-a[::-1].find(b[1])
    if a[-1]==b[0]:return a[:-1]+b
    if a[c]==a[c-1]:c-=1
    return a[:c]+b[1:]

Called with f(word 1,word 2) and returns the portmanteau. Will throw an error if the inputs aren't compatible. Works for all test cases.

Edit:

If I've read the edits to this question correctly, this updated code should work

f=lambda a,b:a[:-1]+b if a[-1]==b[0] else a[:len(a)-1-a[::-1].find(b[1])]+b[1:]


Generate ASCII wilderness map Generate an ASCII wilderness map.

Example output:

................^^^^
..................^^
...^^^^........o....
.....^^^^...........
....................
........o....TT.....
..TTTT..............
TTTT.TTTT....~~~~~~.
..TT..........~~~~~~
....................

Anti-example (don't do this):

....................
...........T........
...^..........oo....
......^.............
....................
..............TT....
T.T.T.T.T........T..
.................T..
T.T.T.T.T..........T
..............TT...T

Rules:

Must be at least 20x10 characters in size
Must be different each run, i.e. random
Must contain continuous and varying shape areas of trees 'T', hills '^' and water '~', most of which should consist of more than 5 cells
The default, ground character is '.'
Must contain at least 2 villages 'o' that are usually not next to each other
Must not contain obvious patterns, such as rectangles or evenly spaced areas - "natural look" is the key
You don't need to explicitly check that the rules are followed (e.g. no need for anti-rectangle logic), but the great majority of the runs (say, 80%) must produce conforming results
With your submission, include an example output

Scoring:

Winner has lowest score from formula: code character count - votes

APL (99 76)

F←⍳S←10 20⋄'.T^~^To'[⊃7⌊1++/(⊂7×F∊{?S}¨⍳2),T×{F∊(?S)∘+¨+\{2-?3 3}¨⍳99}¨T←⍳3]

A bit longer than it needs to be (so that it gives better output) but I'll shorten it when the Golfscript answer comes in.

The GolfScript answer was posted so here's a shorter one. I thought of another (rather obvious, in hindsight) way to shorten it so that the output is not much worse than the original program, and it's even shorter than my original backup plan.

(In the old version, I had five bitfields that I was xor-ing with each other, now I have three that I am adding to each other.)

I have replaced the example output with output of the new version, of course.

Explanation:

F←⍳S←10 20: size is 20x10, F is a matrix where each element is its coordinates
{F∊(?S)∘+¨+\{2-?3 3}¨⍳99}¨T←⍳5: generate 3 bitfields, by starting at a random coordinate, and taking 99 random steps to a neighbouring field and then setting that bit on. 99 seems high but it often backtracks as it is random. This makes the maps for the areas.
(⊂7×F∊{?S}¨⍳2): Add in two villages.
⊃7⌊1++/: sum the areas, giving a matrix where each number represents a certain type. Cap it at 7, because the villages might appear in another area giving high numbers.
'.T^~^To'[...]: replace each number with the right character. There are 3 possibly overlapping fields so the highest possible value is 6. (3+3)

Example output:

....TTT.TTT...TTT.^^
...TT....TTT....T..^
....T....TT.......^^
...~..o..T..^^...^^.
...~.........^^^^^^^
...~~~~....^^..^^^..
~..~~~......^.^.^^^^
~~.~~~......^^.^^^..
~.~~~~........o.....
~~~~~~..............

and

.....o........~~..~~
..............~~~~~.
.^T.T..........~~.~.
^T~~TTTTTT.......~~~
~~~~TT.TT.T......~~~
^~^TTT....T.....~~~~
^^^^T.....T...T..~~.
^^^^.......TT.T.....
^^^^.........TT.....
^^^^.........o......

Old version:

F←⍳S←10 20⋄G←{F∊(?S)∘+¨+\{2-?3 3}¨⍳99}¨T←⍳5⋄'.T^~^To'[⊃7⌊1++/(⊂7×F∊{?S}¨⍳2),T×{(⊃⍵⌽G)∧~⊃∨/1↓⍵⌽G}¨T]


Challenge Ulamspiral The challenge

Get familiar with the Ulam spiral:

The aim is to print the spiral like in the picture above!

Rules

Write a function ulam(n)

where n is a odd positive integer and describes the size of the grid to print.

All non-primes numbers should be replaced with | horizontal and - vertical as in the picture above following the spiral. (Corner elements belongs to the vertical)

All numbers need to take the same amount of space visually and smaller numbers are right centered vertically:

1000
 100
  10

10 needs two spaces on the left and 100 needs one space left.
This property depends on the biggest number you have to calculate.

Example: (n=3)

 -  - 3
|     |
7   - 2
|
 -  -

The test for primes/sieve you have to write yourself.

Smallest byte code wins.

Bonus
- 25 if you can make it more pretty find some symbols so that - and | takes the same space (-25 more if you can find a pretty corner symbol) and the symbol should show the line where the spiral evolves.

Python 3 - 506 479 bytes

q=range
def p(n):
 for d in q(2,n//2+1):
  if n%d==0:return 0
 return 1
w=int(input());m=w**2;z=len(str(m))
def k(n):
 if n==1:return'-'*(z-1)+'>'
 if p(n):return str(n).zfill(z)
 return'.'*z
l=[k(n+1)for n in q(m)];s=[[0for n in q(w)]for n in q(w)];x=y=w//2;t=[n//2for n in q(2,w*w)];c=[[1,0],[0,-1],[-1,0],[0,1]];j=p=0
for r in t:
 d=c[p%4];p+=1;i=0
 while i<r and j<m:
  s[y][x]=l[j]+' ';x+=d[0];y+=d[1];i+=1;j+=1
s=[''.join(l)for l in s]
for l in s:print(l)

I am not sure if the byte count is correct.
Also, this can most likely be made shorter (I'm new to Python).

Right now I'm just substituting all non-primes with periods. You can change this to any character.

Note: You should only enter odd numbers as input, as otherwise the program breaks.

Furthermore, my function to determine whether a number is prime is the most primitive it can be, for the sake of less characters, so it is not efficient. Though it ran just fine on my computer with input values less than 100 in just under a second.

Note: Input values above 25 or 30 won't display correctly unless you have a ridiculously wide screen.


Indexing the Extended Fibonacci Numbers You've probably heard of Fibonacci numbers. Ya know, that integer sequence that starts with 1, 1, and then each new number is the sum of the last two?

1 1 2 3 5 8 13...

And so on. Challenges about Fibonacci numbers are pretty popular 'round here. But who says that the Fibonacci numbers have to start with 1, 1? Why couldn't they start with 0, 1? Alright, let's redefine them to start at 0:

0 1 1 2 3 5 8 13...

But... We don't have to stop there either! If we can add the last two numbers to get the next one, we could also subtract the first number from the second number to prepend a new number. So it could start with 1, 0:

1 0 1 1 2 3 5 8 13...

We can even end up with negatives:

-1 1 0 1 1 2 3 5 8 13...

And this series also goes on forever. I think it's interesting how it ends up kinda mirroring the regular Fibonacci numbers, just with every other number made negative:

13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13...

Let's call this series the "Extended Fibonacci Number", or EFN. Since there isn't really an obvious negative number to start this series on, we'll say that 0 shows up at 0, the regular Fibonacci numbers extend in to the positive indices, and the negative (half-negative?) Fibonacci numbers extend in to the negative indices, like so:

Indices: ...-7  -6 -5  -4 -3  -2 -1  0  1  2  3  4  5  6  7 ...
Values:  ...13  -8  5  -3  2  -1  1  0  1  1  2  3  5  8  13...

This leads into today's challenge:

  Given an integer N, return every index at which N appears in the EFN series.

Some random observations on this task:

1 appears more times in the EFN than any other number: [-1, 1, 2]. No number will appear in more than 3 places.
Every Fibonacci number > 1 will show up either once (3, 8, 21, etc.) or twice (2, 5, 13, etc.)

Rule Clarifications:

If abs(N) is not a Fibonacci number, it will never appear in the EFN series, so you must output nothing/an empty collection if possible, or if that is not possible in your language, you can output some constant non-numeric value.
If N appears at multiple places in the EFN, your output does not need to be sorted. Although each index must appear exactly once.
Although most sequence challenges allow you to choose whether you want to use 1-based or 0-based indexing, this challenge must use the indexing described (where 0 appears at 0).
You may take I/O through any standard format.

Test Cases

-13: []
-12: []
-11: []
-10: []
-9: []
-8: [-6]
-7: []
-6: []
-5: []
-4: []
-3: [-4]
-2: []
-1: [-2]
0: 0
1: [-1, 1, 2]
2: [-3, 3]
3: [4]
4: []
5: [-5, 5]
6: []
7: []
8: [6]
9: []
10: []
11: []
12: []
13: [-7, 7]

And some larger test cases:

89: [-11, 11]
1836311903: [46]
10000: []
-39088169: [-38]

As usual, shortest answer in bytes wins!

Haskell, 78 bytes

4 bytes saved thanks to nimi

a#b=a:b#(a-b)
f 0=[0]
f a=do{(i,x)<-zip[0..a*a+1]$0#1;[-i|x==a]++[i|abs x==a]}

Try it online!

First we set up (#), (#) takes two parameters, a and b, and returns the a list starting with a and followed by b#(a-b).  This creates an infinite list, but because Haskell is lazy we don't need to wory about it looping forever.  This essentially works backwards creating the Fibonacci sequence before a certain pair. For example (0#1) would be the list of all the Fibonacci numbers with negative index.

From here we make f.  f takes a argument a which is the number we are trying to find in the sequence.  Here we use do notation to do a list comprehension.  We start by taking the first a*a+1 elements of the list 0#11.  Since the function a*a+1 grows faster than the inverse of the Fibonacci sequence we can be sure that if we check within this bound we will find all the results.  This prevents us from searching an infinite list.  Then for each value x and index i, if x==a we found a in the negative half of the sequence so we return -i, and if abs x==a we return i as well because the absolute value of the negative half is the positive half so we found it there.

Since this makes the list [0,0] for 0 we hardcode the correct output for that one.

1: This trick is taken from Οurous' Clean answer.  The same speedup aplies here as there, replace a*a+1 with abs a+1 to save a lot of time.


Tips for golfing in Octave What general tips do you have for golfing in Octave? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Octave (e.g. "remove comments" is not an answer). Please post one tip per answer.

Once you know, that a is free of zero values, using nnz(a) spares you 2 chars compared to numel(a).
Prefer a(a==0) to a(find(a==0)).
~t is shorter than t==0 , and even ~~t is shorter than t!=0.
0*(1:n) is shorter than zeros(1,n)
Generally, || and && , unlike many other operators, scalarize the result when the first argument is a scalar. For matrices, only non-empty matrices without elements equal to zero have the logical value of true.

Hence, we can do 0||m instead of all(all(m)) for any matrix.

Try with 0||[1 1;1 0] and 0||[1 1;1 1] to convince yourself.
When you are using a builtin a number of times, do a function handle to spare characters eg. f=@find . For short function names at least 3 occurrences justify this, for long ones - even with two occurrences.
When a function is a single statement, prefer f=@(n)dosomething(n) notation to function r=f(n)r=dosomething(n);end one.
Unfortunately, global variables have to be declared both in global scope and in each function using them. But there is an exception: anonymous @(n)... functions "see" all variables from the scope where they are called from.
It's possible to do f(a=0,b=0) instead of a=0;b=0;f(a,b).
This seems undocumented feature, but the order of evaluation is from left to right (checked at v. 3.8.1), you can do zeros(a=n,b=a*a) to both create a n x n^2 matrix and store it's row and column number in a and b variables.
The operator precedence table is your friend. Don't do b=(a==0) since b=a==0 is the same.


Bit Manipulator/Reader Introduction

There are often times that we have challenges which require communication of some sort (such as in team KOTH), where density of information may be more important than density of code. There are a number of compression techniques that can allow us to convey more information in less space, but for simple data flags, sometimes flipping bits themselves can be a great way to achieve desired data density.

Challenge

Write a program or function in the language of your choice that can take an integer to be manipulated (must handle at least 32 bit), a start bit position (integer), a number of bits to manipulate (integer), and a manipulation mode (integer), and returns the original integer manipulated in the way specified below. In addition, write a second program or function that serves as a bit reader, taking in an integer, a start bit position (integer), and a number of bits to read (integer), and returns an integer consisting of just that group of bits shifted down, and every other bit as 0.

Some further details and rules are as follows:

The first argument will be an integer, signed or unsigned.
The second argument will be the bit position to start from (counting from least significant bit, zero-indexed).
The third argument will be the number of bits to be read/manipulated, moving up in bit significance from the start bit. If not given as an argument, the value should default to 1.
The fourth argument (manipulator only) will be the manipulation mode:

When passed a 0 or null value, the behavior will be to flip (xor) all of the specified bits (default if no value given).
When passed a positive value, the behavior will be to set all of the specified bits to 1.
When passed a negative value, the behavior will be to set all of the specified bits to 0.

The return value of the manipulator function should be the initial integer with the above bit manipulations applied.
The return value of the reader function should be the start bit shifted to the least significant bit, and every bit beyond the length of bits set to 0.
Assume that only valid input will be used. Don't worry about error handling.

The winner will be determined by the shortest sum of the length of both programs/functions. They will be selected in at least 7 days, or if/when there have been enough submissions. In the event of a tie, the answer that came earlier wins.

Examples

Here's a few examples of input and output that your code should be able to handle. I've golfed both functions in JavaScript that I can release if people want to test their results, but otherwise I'll probably wait a few days before I post it up.

Manipulator

F(0, 2) => 4 (0 => 100)

F(4, 2) => 0 (100 => 0)

F(0, 2, 4) => 60 (0 => 111100)

F(170, 2, 4, 0) => 150 (10101010 => 10010110)

F(170, 2, 4, 1) => 190 (10101010 => 10111110)

F(170, 2, 4, -1) => 130 (10101010 => 10000010)

F(0, 31) => (+/-)2147483648 (0 => 10000000000000000000000000000000)

Reader

F(0, 2) => 0 (0 => 0)

F(4, 2) => 1 (100 => 1)

F(60, 2, 4) => 15 (111100 => 1111)

F(170, 2, 4) => 10 (10101010 => 1010)

F((+/-)2147483648, 0, 32) => (+/-)2147483648 (10000000000000000000000000000000 => 10000000000000000000000000000000)

JavaScript (ES6), 75 bytes

Saved 4 bytes thanks to @Mwr247

Manipulator: (47 bytes)

(a,b,c=1,d=0,z=(1<<c)-1<<b)=>d?d<0?a&~z:a|z:a^z

Reader: (28 bytes)

(a,b,c=1)=>a>>b&(1<<c-1)*2-1

How it works

Manipulator

The first thing we need to do is figure out the number that has c bits set, starting at the bth bit. Possibly the best way to do this is z=(1<<c)-1<<b, which works like so:

b  c    1<<c     -1     <<b    z
2  1      10     01    0100    4
2  2     100    011   01100   12
2  3    1000   0111  011100   28
1  4   10000  01111  011110   30

Now we take into account d. For case 0, we flip the bits with a^z; for case 1, we set the bits to 1 with a|z; for case -1, we set the bits to 0 with a&~z.


Playing with robots for kids - Which letter will I reach? TL;DR: Given an array of chars and a robot in a starting position of the array, write an algorithm than can read a string with movements (F for "go forward", R for "rotate 90 degrees right" and L for "rotate 90 degrees left") and calculate the ending position of the robot. More details in the complete text.

We have at home a very simple programmable device for kids: a small vehicle with buttons to make the vehicle go forward, turn 90 degrees left or turn 90 degrees right. Something similar to this:

We also have a foam mat with letters like this:

The purpose of all this is to teach the kids both the alphabet and the rudiments of programming, all at once.

The challenge

Suppose we have randomly arranged our foam mat like this:

+---+---+---+---+---+---+---+
| E | R | L | B | I | X | N |
+---+---+---+---+---+---+---+
| O | A | Q | Y | C | T | G |
+---+---+---+---+---+---+---+
| F | W | H | P | D | Z | S |
+---+---+---+---+---+---+---+
    | K | V | U | M | J |
    +---+---+---+---+---+
            |   |
            +---+

Suppose also we have modified the vehicle so that when we program a "go forward" command, the vehicle goes forward exactly size of one square in the mat. So, if the vehicle is in the U square and goes north, it stops exactly in the P square.

The instructions are all given to the vehicle before it starts to move, and those are:

F: The vehicle goes forward into the next square.
R: The vehicle turns 90 degrees right in its place (no further movement).
L: The vehicle turns 90 degrees left in its place (no further movement).

Once the instructions are given, you can press the "GO" button and send the vehicle to a given position as it will follow every instruction in the given order. So, you can tell the kid to insert the needed instructions for the vehicle to go to a given letter.

You must write the shortest program/function that processes a string (input parameter) with a set of instructions and calculates the letter the vehicle stops over (output string).

Details:

The vehicle always starts at the blank square at the bottom, and facing north (towards the U square).
The input string will contain only the letters F, R, L and G (for the "go" button). You can use lowercase letters for the mat and the instructions, if you prefer so.
The algorithm must obey every instruction in the string before the first G (every instruction after that is ignored as the vehicle has started moving).
If the vehicle goes out of the mat at any given moment (even if the input string has not been completely processed), the algorithm must return the string Out of mat.
If not, the algorithm must return the letter the vehicle has stopped over. The starting point counts as a  char (or an empty string).

Examples:

Input: FFG
Output: P

Input: FRFRFG
Output: Out of mat

Input: RRFFG
Output: Out of mat

Input: FFFRFFLFG
Output: X

Input: FFFRFFLF
Output:      <-- Nothing or a whitespace (the robot has not started moving)

Input: FFFRRFFFG
Output:      <-- Nothing or a whitespace (the robot has returned to the starting point)

Input: RRRRRLFFFLFFRFRFGFFRRGRFF
Output: L    (Everything after the first G is ignored)

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

JavaScript (ES6), 194 176 169 163 bytes
Saved some bytes thanks to @Luke and @Arnauld.
s=>(p=35,d=3,t='ERLBIXN1OAQYCTG1FWHPDZS11KVUMJ11111 11',[...s].every(i=>i=='L'?d--:i>'Q'?d++:i<'G'?+t[p+=[1,8,-1,-8][d%4]]||!t[p]?p=1/0:p:0)?'':t[p]||'Out of mat')

Ungolfed:
s=>(
  p=35,
  d=3,
  t='ERLBIXN1OAQYCTG1FWHPDZS11KVUMJ11111 11',
  [...s].every(i=>i=='L'?d--:
                  i<'Q'?d++:
                  i<'G'?+t[p+=[1,8,-1,-8][d%4]]||!t[p]?p=1/0:p:
                  0
              )?'':
               t[p]||'Out of mat'
)

f=
s=>(p=35,d=3,t='ERLBIXN1OAQYCTG1FWHPDZS11KVUMJ11111 11',[...s].every(i=>i=='L'?d--:i>'Q'?d++:i<'G'?+t[p+=[1,8,-1,-8][d%4]]||!t[p]?p=1/0:p:0)?'':t[p]||'Out of mat')

console.log(f('FFG')); //P
console.log(f('FRFRFG')); //Out of mat
console.log(f('RRFFG')); //Out of mat
console.log(f('FFFRFFLFG')); //X
console.log(f('FFFRFFLF')); //(space)
console.log(f('FFFRRFFFG')); //(space)
console.log(f('RRRRRLFFFLFFRFRFGFFRRGRFF')); //L
console.log(f('FFFFFRRFG')); //Out of mat