The Path Of The Wildebeest Golf a program or function which gives the \$n^{\text{th}}\$ location of the wildebeest who starts at square \$1\$ on an infinite chessboard which is numbered in an anti-clockwise square spiral, where the wildebeest always visits the lowest numbered square she can reach that she has not yet visited.

Inspiration: The Trapped Knight and OEIS A316667.

Edit: This sequence is now on the OEIS as A323763.

The code may produce the \$n^{\text{th}}\$ location, the first \$n\$ locations, or generate the sequence taking no input.

Feel free to give her location after (or up to) \$n\$ leaps instead, but if so please state this clearly in your answer and make sure that an input of \$n=0\$ yields 1 (or [1] if appropriate).

This is code-golf, so the aim is to produce working code in as few bytes as possible in your chosen language.

Note: the wildebeest becomes trapped (much like the knight does at his \$2016^{\text{th}}\$ location, square \$2084\$, and the camel does at his \$3723^{\text{rd}}\$, square \$7081\$) at her \$12899744968^{\text{th}}\$ location on square \$12851850258\$. The behaviour of your code may be undefined for \$n\$ larger than this. (Thanks to Deadcode for the C++ code that found this!)

Detail

The board looks like the below, and continues indefinitely:

101 100  99  98  97  96  95  94  93  92  91
102  65  64  63  62  61  60  59  58  57  90
103  66  37  36  35  34  33  32  31  56  89
104  67  38  17  16  15  14  13  30  55  88
105  68  39  18   5   4   3  12  29  54  87
106  69  40  19   6   1   2  11  28  53  86
107  70  41  20   7   8   9  10  27  52  85
108  71  42  21  22  23  24  25  26  51  84
109  72  43  44  45  46  47  48  49  50  83
110  73  74  75  76  77  78  79  80  81  82
111 112 113 114 115 116 117 118 119 120 121

A wildebeest is a "gnu" fairy chess piece - a non-standard chess piece which may move both as a knight (a \$(1,2)\$-leaper) and as a camel (a \$(1,3)\$-leaper).
As such she could move to any of these locations from her starting location of \$1\$:

  .   .   .   .   .   .   .   .   .   .   .
  .   .   .   .  35   .  33   .   .   .   .
  .   .   .   .  16   .  14   .   .   .   .
  .   .  39  18   .   .   .  12  29   .   .
  .   .   .   .   .  (1)  .   .   .   .   .
  .   .  41  20   .   .   .  10  27   .   .
  .   .   .   .  22   .  24   .   .   .   .
  .   .   .   .  45   .  47   .   .   .   .
  .   .   .   .   .   .   .   .   .   .   .

The lowest of these is \$10\$ and she has not yet visited that square, so \$10\$ is the second term in the sequence.

Next she could move from \$10\$ to any of these locations:

  .   .   .   .   .   .   .   .   .   .   .
  .   .   .   .   .   .  14   .  30   .   .
  .   .   .   .   .   .   3   .  29   .   .
  .   .   .   .   6   1   .   .   .  53  86
  .   .   .   .   .   .   . (10)  .   .   .
  .   .   .   .  22  23   .   .   .  51  84
  .   .   .   .   .   .  47   .  49   .   .
  .   .   .   .   .   .  78   .  80   .   .
  .   .   .   .   .   .   .   .   .   .   .

However, she has already visited square \$1\$ so her third location is square \$3\$, the lowest she has not yet visited.

The first \$100\$ terms of the path of the wildebeest are:

1, 10, 3, 6, 9, 4, 7, 2, 5, 8, 11, 14, 18, 15, 12, 16, 19, 22, 41, 17, 33, 30, 34, 13, 27, 23, 20, 24, 44, 40, 21, 39, 36, 60, 31, 53, 26, 46, 25, 28, 32, 29, 51, 47, 75, 42, 45, 71, 74, 70, 38, 35, 59, 56, 86, 50, 78, 49, 52, 80, 83, 79, 115, 73, 107, 67, 64, 68, 37, 61, 93, 55, 58, 54, 84, 48, 76, 43, 69, 103, 63, 66, 62, 94, 57, 87, 125, 82, 118, 77, 113, 72, 106, 148, 65, 97, 137, 91, 129, 85

The first \$11\$ leaps are knight moves so the first \$12\$ terms coincide with A316667.

JavaScript (Node.js),  191 ... 166  164 bytes

Saved 2 bytes thanks to @grimy.

Returns the \$N\$th term.

n=>(g=(x,y)=>n--?g(Buffer('QPNP1O?O@242Q3C3').map(m=c=>g[i=4*((x+=c%6-2)*x>(y+=c%7-2)*y?x:y)**2,i-=(x>y||-1)*(i**.5+x+y)]|i>m||(H=x,V=y,m=i))&&H,V,g[m]=1):m+1)(1,2)

Try it online! or See a formatted version

How?

Spiral indices

In order to convert the coordinates \$(x,y)\$ into the spiral index \$I\$, we first compute the layer \$L\$ with:

$$L=\max(|x|,|y|)$$

Which gives:

$$\begin{array}{c|ccccccc}
&-3&-2&-1&0&+1&+2&+3\\
\hline
-3&3&3&3&3&3&3&3\\
-2&3&2&2&2&2&2&3\\
-1&3&2&1&1&1&2&3\\
0&3&2&1&0&1&2&3\\
+1&3&2&1&1&1&2&3\\
+2&3&2&2&2&2&2&3\\
+3&3&3&3&3&3&3&3
\end{array}$$

We then compute the position \$P\$ in the layer with:

$$P=\begin{cases}
2L+x+y&\text{if }x>y\\
-(2L+x+y)&\text{if }x\le y
\end{cases}$$

Which gives:

$$\begin{array}{c|ccccccc}
&-3&-2&-1&0&+1&+2&+3\\
\hline
-3&0&1&2&3&4&5&6\\
-2&-1&0&1&2&3&4&7\\
-1&-2&-1&0&1&2&5&8\\
0&-3&-2&-1&0&3&6&9\\
+1&-4&-3&-2&-3&-4&7&10\\
+2&-5&-4&-5&-6&-7&-8&11\\
+3&-6&-7&-8&-9&-10&-11&-12
\end{array}$$

The final index \$I\$ is given by:

$$I=4L^2-P$$

NB: The above formula gives a 0-indexed spiral.

In the JS code, we actually compute \$4L^2\$ right away with:

i = 4 * (x * x > y * y ? x : y) ** 2

And then subtract \$P\$ with:

i -= (x > y || -1) * (i ** 0.5 + x + y)

Moves of the wildebeest

Given the current position \$(x,y)\$, the 16 possible target squares of the wildebeest are tested in the following order:

$$\begin{array}{c|cccccccc}
&-3&-2&-1&x&+1&+2&+3\\
\hline
-3&\cdot&\cdot&9&\cdot&11&\cdot&\cdot\\
-2&\cdot&\cdot&8&\cdot&10&\cdot&\cdot\\
-1&7&6&\cdot&\cdot&\cdot&12&13\\
y&\cdot&\cdot&\cdot&\bullet&\cdot&\cdot&\cdot\\
+1&5&4&\cdot&\cdot&\cdot&14&15\\
+2&\cdot&\cdot&2&\cdot&0&\cdot&\cdot\\
+3&\cdot&\cdot&3&\cdot&1&\cdot&\cdot
\end{array}$$

We walk through them by applying 16 pairs of signed values \$(dx,dy)\$. Each pair is encoded as a single ASCII character.

 ID | char. | ASCII code | c%6-2 | c%7-2 | cumulated
----+-------+------------+-------+-------+-----------
  0 |  'Q'  |     81     |   +1  |   +2  |  (+1,+2)
  1 |  'P'  |     80     |    0  |   +1  |  (+1,+3)
  2 |  'N'  |     78     |   -2  |   -1  |  (-1,+2)
  3 |  'P'  |     80     |    0  |   +1  |  (-1,+3)
  4 |  '1'  |     49     |   -1  |   -2  |  (-2,+1)
  5 |  'O'  |     79     |   -1  |    0  |  (-3,+1)
  6 |  '?'  |     63     |   +1  |   -2  |  (-2,-1)
  7 |  'O'  |     79     |   -1  |    0  |  (-3,-1)
  8 |  '@'  |     64     |   +2  |   -1  |  (-1,-2)
  9 |  '2'  |     50     |    0  |   -1  |  (-1,-3)
 10 |  '4'  |     52     |   +2  |   +1  |  (+1,-2)
 11 |  '2'  |     50     |    0  |   -1  |  (+1,-3)
 12 |  'Q'  |     81     |   +1  |   +2  |  (+2,-1)
 13 |  '3'  |     51     |   +1  |    0  |  (+3,-1)
 14 |  'C'  |     67     |   -1  |   +2  |  (+2,+1)
 15 |  '3'  |     51     |   +1  |    0  |  (+3,+1)

We keep track of the minimum encountered value in \$m\$ and of the coordinates of the corresponding cell in \$(H,V)\$.

Once the best candidate has been found, we mark it as visited by setting a flag in the object \$g\$, which is also our main recursive function.

On the first iteration, we start with \$x=1\$ and \$y=2\$. This ensures that the first selected cell is \$(0,0)\$ and that it's the first cell to be marked as visited.


Non-Palindromic Polyglot Boggle Introduction

The number 101 is a palindrome, since it reads the same backwards and forwards. The number 105 is not. However, 105 in base eight is written as 151, which is palindromic. On the other hand, 103 is not a palindrome in any base from 2 to 101. Hence, 103 is strictly non-palindromic.

The precise definition is: A nonnegative integer n is strictly non-palindromic if it is not a palindrome in any base between 2 and n-2, inclusive.

The first few strictly non-palindromic numbers are 0, 1, 2, 3, 4, 6, 11, 19, 47, 53, 79, 103, 137, 139, 149, 163, 167, 179, 223, 263, 269... (A016038)

Write a full program that takes a number x from STDIN and prints the xth strictly non-palindromic number. For example, the input 5 would produce the output 4.

Challenge

The challenge is to write multiple (one or more) programs, each solving this task in a different language.

Then, you must put all of the programs in a rectangular grid of characters. The programs can be accessed Boggle-style. That is, go from one character to a neighboring character (including diagonally), never using the same character more than once.

For example, the following grid:

abc
bdc

includes the words abc, ccd, bbad, and bcdb, but not ac, bdd, bcb, or cbbc.

Each program must be found in the grid using these rules. However, you may use the same character in multiple programs.

Score

Your score is the number of characters in the grid, divided by the number of programs. Lowest score wins!

Rules

Two languages are considered different if they usually go by different names, ignoring version numbers. For example, C and C++ are different, but Python 2 and Python 3 are the same.
The characters in the grid must all be from printable ASCII, i.e., from  to ~, code points 20 through FE.
Each program must consist only of printable ASCII, plus newlines. When inserting a program into the grid, replace each newline with a space.

A space in the grid may represent a space in one program and a newline in another.

The grid must be a rectangle.
Not every character needs to be used in a program.

19x2 = 38, 2 programs, Score: 26 19.5 19

Here is the board:

-:\~{.,><1\b_W%}}g}
1Wq{)_2W{$ase.=,do*

This contains the following programs:

CJam (27 bytes)

Wq~{{)_,2>W<{1$\b_W%=},}g}*

Test it here.

These are the characters of the board used for this code:

   ~{ ,><1\b_W%}}g}
 Wq{)_2W{$    =,  *

GolfScript (34 bytes)

-1:W\~{{).,2>W<{1$\base.W%=},}do}*

Test it here.

These are the characters of the board used for this code:

-:\~{.,><1\b W%}} }
1W {) 2W{$ase.=,do*


Solve quadratic equation using only 3 variables and arithmetic Write function which solves equation of degree less than or equal to 2 (ax^2 + bx + c = 0).

Input

Function should get 3 parameters - floating point numbers which are coefficients of this equation. Coefficients may be zero (that means function must able to solve bx + c = 0 and c = 0 too).
Coefficients are between -1000 and 1000 with 3 significant decimal digits but maximum 3 digits after comma, for example, 999. or 3.14 or 0.233 but not 1001 or 0.0123.

Rules

You may use only + - * / % & | xor ~ && || ! < > >= <= == != << >> operators
No built-in functions (that means no square root or power or similar functions)
No variables except 3 function parameters
You can't use complicated expressions - only statements of the form a = b @ c or a = @ b are allowed (@ - any allowed operator and a, b, c - any variables, may be same or constants)
No loops, recursion, goto's, custom types
Casts and type conversion between integral data types are allowed
Using features of dynamic typing (changing floating point number to array/object/something else that is not number) is not allowed
If's are allowed with one or none operators in condition (if (a) {...} else {...} or if (a==b) {...} else {...}). Note that if itself and its condition scores separately
You may use try{}catch{}

Output

Output should be passed by reference to input variables, if your language doesn't have such feature, you anyway should put result to input variables and print their values
In variable a - number of real roots - 0, 1, 2, 3 (value greater than 2 stands for infinitely many roots)
In variables b and c - 1st and 2nd roots (if none or infinitely many roots than any values, if one root then c - any value)
Note that 2 equal roots is not the same as 1 root
Precision should be at least 3 significant decimal digits

Score

Score is [number of operators] + [number of if's]. Assignment operators have score 0.
Answer with lowest score wins.
In case of same score answer with greater precision wins. If precision is same then first answer wins.
if(a != 0) and if(a == 0) has score 1 (instead of 2) because if(a) or if(a)else{} can be used, however not all languages support it.
For each catch{} +2 to score
Use of 1 temporary variable of numeric type is +20 to score.

Hybrid of iterative approaches; score: 62

I originally posted an answer which purely used Newton-Raphson; however, in the cases of large b and c this requires a lot of iterations. Consider only the most interesting quadratics: those which have two solutions. If we normalise them to the form x^2 + bx + c = 0 then we can plot the number of iterations required for various approaches as a function of b and c. For example, we can modify the continued fraction route to get the direct approach:

c = -c;
a = b * 0.5;
while (loopCount-- > 0) { // This loop would be unrolled in the final solution
    a = a + b;
    a = c / a;
}
// Roots are a and -c/a

That gives a loop count diagram of

2236...................6322
2224n.................n4222
22236.................63222
22224n...............n42222
222236...............632222
222224m.............m422222
2222236.............6322222
2222224j...........j4222222
22222234P.........P43222222
22222223d.........d32222222
222222222t.......t222222222
2222222225Z.....Z5222222222
22222222219/////91222222222
/////////////./////////////
222222222*********222222222
222222222*********222222222
22222222***********22222222
22222223***********32222222
2222223*************3222222
2222224*************4222222
222223***************322222
222224***************422222
22223*****************32222
22224*****************42222
2223*******************3222
2224*******************4222
223*********************322

where c is negative in the first row and increases downwards, b increases from left to right, * means negative discriminant, / means only one root was within tolerance in 62 iterations, . means no root was within tolerance in 62 iterations, and numbers are in base-62 with digits 0-9a-zA-Z. This is pretty decent for a certain range, but fails completely for another range.

bmarks' original implementation is similar to (but not the same; this is a reimplementation from the continued fraction):

a = b;
while (loopCount-- > 0) {
    a = c / a;
    a = b - a;
}
// Roots are -a, -c/a (which is better than a-b)

with loop count diagram

1117...................7111
1112n.................n2111
11117.................71111
11112n...............n21111
111117...............711111
111112m.............m211111
1111117.............7111111
1111112j...........j2111111
11111115Q.........Q51111111
11111111d.........d11111111
111111113u.......u311111111
1111111116/...../6111111111
1111111111a/////a1111111111
1111111111111.1111111111111
111111111*********111111111
111111111*********111111111
11111111***********11111111
11111112***********21111111
1111111*************1111111
1111112*************2111111
111111***************111111
111113***************311111
11111*****************11111
11113*****************31111
1111*******************1111
1113*******************3111
111*********************111

My naïve N-R was quite bad, but the really interesting thing to note about it is where the worst areas are:

njfdcccccccccccccccccccdfjn
njgcbbbbbbbbbbbbbbbbbbbcgjn
njgc9999999999999999999cgjn
njgc9777777777777777779cgjn
njgc9666666666666666669cgjn
njgc9544444444444444459cgjn
njgc9521111111111111259cgjn
njgc9534444444444444359cgjn
njgc9535555555555555359cgjn
njgc9536777777777776359cgjn
njgc9536888888888886359cgjn
njgc9536899999999986359cgjn
njgc95368aaaaaaaaa86359cgjn
njgc95368aaaaaaaaa86359cgjn
njgc95368*********86359cgjn
njgc95369*********96359cgjn
njgc9536***********6359cgjn
njgc9536***********6359cgjn
njgc953*************359cgjn
njgc954*************459cgjn
njgc95***************59cgjn
njgc94***************49cgjn
njgc9*****************9cgjn
njgc8*****************8cgjn
njgc*******************cgjn
njgb*******************bgjn
njf*********************fjn

So the thing to do is to hybridise. For the areas where it's good, I use the continued fraction; for the rest, I use N-R, but I've done some optimisation: I've experimentally found two cutoffs and three initial values which converge in 5 iterations to a worst-case mixed error abs(value - correct_value) / (1 + abs(correct_value) of 0.000052. (Thanks to Martin Büttner for the idea of doing a case split). The final loop count (mixing the two cases into one diagram) is:

111555555555555555555555111
111233333333333333333332111
111133333333333333333331111
111125555555555555555521111
111115555555555555555511111
111112333333333333333211111
111111333333333333333111111
111111255555555555552111111
111111144444444444441111111
111111112111111111111111111
111111113222222222211111111
111111111333333333111111111
111111111444444444111111111
111111111111111111111111111
111111111*********111111111
111111111*********111111111
11111111***********11111111
11111112***********21111111
1111111*************1111111
1111112*************2111111
111111***************111111
111113***************311111
11111*****************11111
11113*****************31111
1111*******************1111
1113*******************3111
111*********************111

and the code is

solve_quad(&float a, &float b, &float c) {
    float t; // 20 points
    if (a != 0) { // 21
        if (c == 0) {
            // x(x+b) = 0
            b = -b; // 22
            a = 2;
        }
        else {
            // Normalise so that we're solving x^2 + bx + c = 0 and have `a` free to use
            // Hereon, mentions of b and c in comments refer to these normalised values.
            b = b / a; // 22
            c = c / a; // 23

            // Three cases:
            //   b^2 < 4c: negative determinant, no solutions
            //   b^2 < -4c: use Newton-Raphson
            //   Otherwise: use the continued fraction method that bmarks was the first to post

            a = b / 2; // 24
            a = a * a; // 25
            if (a < c) { // 26
                a = 0;
            }
            else {
                t = a + c; // 27
                if (t < 0) { // 28
                    c = a - c; // 29, c holds the determinant

                    // Carefully optimised case split:
                    if (c < 0.05) // 30
                        a = 0.025;
                    else if (c < 250) // 31
                        a = 2;
                    else a = 193;

                    t = c / a; a = a + t; a = a / 2; // 34
                    t = c / a; a = a + t; a = a / 2; // 37
                    t = c / a; a = a + t; a = a / 2; // 40
                    t = c / a; a = a + t; a = a / 2; // 43
                    t = c / a; a = a + t; a = a / 2; // 46

                    // At this point a ~= sqrt(determinant)
                    t = b / 2; // 47
                    a = a + t; // 48
                    t = t * t; // 49
                    c = t - c; // 50
                    // At this point a ~= b/2 + sqrt(determinant) and c holds its original value
                }
                else {
                    a = b;

                    a = c / a; a = b - a; // 52
                    a = c / a; a = b - a; // 54
                    a = c / a; a = b - a; // 56

                    // At this point a ~= b/2 + sqrt(determinant)
                }

                b = -a; // 57
                c = c / b; // 58
                a = 2;
            }
        }
    }
    else {
        // bx + c = 0
        if (b != 0) { // 59
            a = 1;
            c = -c; // 60
            b = c / b; // 61
        }
        else {
            // c = 0
            if (c != 0) a = 0; // 62
            else a = 3;
        }
    }
}


Shortest self-analyzing program Oh, <PROGRAM NAME HERE>, tell me how many character '<CHARACTER HERE>'/s are there in your body.

I do not think it a dupe to this. That question asks for printing a list directly but this one requires some input that will cause problem.

Your work is to write a quine-like program/function that takes an input of one character, and respond with a number telling how many times that character occurs in your program. Comments, indents, trailing spaces, line feeds all count.

The range of acceptable input MUST cover all characters the language you are using can accept (not as string literals or comments) and all characters with lesser index in Unicode. For exmaple, Javascript and Python 3 accept Unicode characters for variable name, then it MUST allow Unicode input. For some stack processing languages, there are characters like ‘Ȯß, so part of the non-ASCII input MUST also be acceptable.

For example, if your program is in pure ASCII and only LF

foo(bar,baz)#there is a space->
    do things

The inputs and outputs should be:

\n -> 1
\r -> 0
\t -> 0
 -> 9
a -> 4
b -> 2
( -> 1
) -> 1
\x01 through \x09 -> 0
＋(U+FF0B) -> undefined behaviour (you can even destroy everything or delete the program itself furiously)

The program with least characters wins.

Python, 172 chars
lambda a:'-mbda#l.fn()+1: \\\'i'.find(a)+1#\\\\\\\\\\\\\\((((((((())))))))))fffffffbd####lllll......nnnnnnnn+1+1+1+1+1+1+1+1+1+1+11:::::::::::::              '''''''''''''''iiiiiiiiiiiiiiiii

Using str.find()+1 to generate 0 for any character not in program.
Using comment for complement.


Make Zero From First 'n' Numbers Challenge

The challenge is to write a code that takes a positive integer 'n' as an input and displays all the possible ways in which the numbers from 1 - n can be written, with either positive or negative sign in between, such that their sum is equal to zero. Please remember that you may only use addition or subtraction.

For example, if the input is 3, then there are 2 ways to make the sum 0:

 1+2-3=0
-1-2+3=0

Note that, the numbers are in order, starting from 1 till n (which is 3 in this case). As it is evident from the example, the sign of the first number can also be negative, so be careful.

Now, 3 was pretty much simple. Let us list all the ways when we consider the number 7.

 1+2-3+4-5-6+7=0
 1+2-3-4+5+6-7=0
 1-2+3+4-5+6-7=0
 1-2-3-4-5+6+7=0
-1+2+3+4+5-6-7=0
-1+2-3-4+5-6+7=0
-1-2+3+4-5-6+7=0
-1-2+3-4+5+6-7=0

So here, we have got a total of 8 possible ways.

Input And Output

As stated before, the input would be a positive integer. Your output should contain all the possible ways in which the numbers give a sum of zero. In case there is no possible way to do the same, you can output anything you like.

Also, you can print the output in any format you like. But, it should be understandable. For example, you may print it as in the above example. Or, you may just print the signs of the numbers in order. Otherwise, you can also print '0's and '1's in order, where '0' would display negative sign and '1' would display positive sign (or vice versa).

For example, you can represent 1+2-3=0 using:

1+2-3=0
1+2-3
[1,2,-3]
++-
110
001

However, I would recommend using any of the first three formats for simplicity.
You can assume all the inputs to be valid.

Examples

7 ->

 1+2-3+4-5-6+7=0
 1+2-3-4+5+6-7=0
 1-2+3+4-5+6-7=0
 1-2-3-4-5+6+7=0
-1+2+3+4+5-6-7=0
-1+2-3-4+5-6+7=0
-1-2+3+4-5-6+7=0
-1-2+3-4+5+6-7=0

4 ->

 1-2-3+4=0
-1+2+3-4=0

2 -> -

8 ->

 1+2+3+4-5-6-7+8=0
 1+2+3-4+5-6+7-8=0
 1+2-3+4+5+6-7-8=0
 1+2-3-4-5-6+7+8=0
 1-2+3-4-5+6-7+8=0
 1-2-3+4+5-6-7+8=0
 1-2-3+4-5+6+7-8=0
-1+2+3-4+5-6-7+8=0
-1+2+3-4-5+6+7-8=0
-1+2-3+4+5-6+7-8=0
-1-2+3+4+5+6-7-8=0
-1-2+3-4-5-6+7+8=0
-1-2-3+4-5+6-7+8=0
-1-2-3-4+5+6+7-8=0

Scoring

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

Haskell, 42 bytes

f n=[l|l<-mapM(\i->[i,-i])[1..n],0==sum l]

Try it online!


A Mnemonic for Remembering 23940 The major system is a mnemonic device for converting numbers into words so they can be memorized more easily.
It is based on how words sound phonetically, but to keep things simple for the challenge we'll only be concerned with how words are spelled. This means there will be some incorrect conversions, but that's alright.

To convert a number into a word using our simplified major system:

Replace each 0 with s or z. (Some could be s and some could be z. Same goes below.)
Replace each 1 with t or d or th.
Replace each 2 with n.
Replace each 3 with m.
Replace each 4 with r.
Replace each 5 with l.
Replace each 6 with j or sh or ch.
Replace each 7 with k or c or g or q.
Replace each 8 with f or v.
Replace each 9 with p or b.
Add the letters aehiouwxy anywhere in any amounts to make a real English word, if possible.
The only exception is that h may not be inserted after an s or c.

The number may actually be any string of the digits 0-9 (no decimals or commas or signs).
The word can only contain the lowercase letters a-z.

Examples
The number 32 must be converted as ?m?n?, where ? represents any finite string made from the letters aehiouwxy (a string from the free monoid if you prefer). There are many ways this could be made into a real English word: mane, moon, yeoman, etc.
The number 05 could be converted as ?s?l? or ?z?l?. Some possibilities are easily, hassle, and hazel. The word shawl is not allowed because h may not be placed after s; it would be incorrectly read as 65.
Challenge
Write a program or function that takes in a string of the digits 0-9 and finds all the words that it could be converted into using the simplified major system mnemonic.
Your program has access to a word list text file that defines what all the "real" English words are. There is one lowercase a-z word on each line of this file, and you may optionally assume it has a trailing newline. Here is a list of real words you can use for testing. You can assume this word list file is called f (or something longer) and lies in any convenient directory.
For a 35 byte penalty (add 35 to your score) you may assume the word list is already loaded into a variable as a list of strings. This is mainly for languages that can't read files, but any submission may take advantage of it.
Your program must output all the words in the word list that the input number can be converted to. They should be printed to stdout (or similar), one per line (with an optional trailing newline), or they can be returned as a list of strings if you chose to write a function. The word list is not necessarily alphabetized and the output doesn't need to be either.
If there are no possible words then the output (or the list) will be empty. The output is also empty if the empty string is input.
Take input via stdin, command line, or as a string argument to a function. The word list, or its file name, should not be part of the input, only the digit string.
You are only matching single words in the word list, not sequences of words. The word noon would probably be one of the results for 22, but the word sequence no one wouldn't.
Test Cases
Suppose this is the word list:
stnmrljkfp
zthnmrlshqfb
asatanamaralajakafapa
aizxydwwwnhimouooraleshhhcavabe
zdnmrlshcvb
zdnmrlshchvb
sthnmrlchgvb
shthnmrlchgvb
bob
pop
bop
bopy
boppy

The input 0123456789 should give all the long words except zdnmrlshchvb and shthnmrlchgvb:
stnmrljkfp
zthnmrlshqfb
asatanamaralajakafapa
aizxydwwwnhimouooraleshhhcavabe
zdnmrlshcvb
sthnmrlchgvb

The input 99 should give:
bob
pop
bop
bopy

(The output words may be in any order.)
Scoring
The shortest submission in bytes wins. Tiebreaker goes to the submission posted first.
Nifty related site: numzi.com.

Perl, 87 84

open A,f;"@ARGV"eq s/[cs]h/j/gr=~y/stnmrljkfpzdcgqvb\0-z/0-90177789/dr&&print for<A>

Takes input in as the command line parameter:

$perl m.pl 23940

Can be made somewhat shorter if the word list would be allowed on the standard input:

$perl -lnE'INIT{$;=pop}$;eq s/[cs]h/j/gr=~y/stnmrljkfpzdcgqvba-z/0-90177789/dr&&say' 99 <f


Best Scoring Boggle Board I was interested in seeing the answers to this (now defunct) question, but it has never been corrected/improved.

Given a set of 6-sided Boggle dice (configuration stolen from this question), determine in two minutes of processing time which board configuration will allow for the highest possible score. (i.e. which dice in which location with which side up allows for the largest scoring word pool?)

OBJECTIVE

Your code should run for no more than 2 minutes (120 seconds). At that time, it should automatically stop running and print the results.
Final challenge score will be the average Boggle score of 5 runs of the program.

In the event of a tie, the winner will be whichever algorithm found more words.
In the event there is still a tie, the winner will be whichever algorithm found more long (8+) words.

RULES/CONSTRAINTS

This is a code challenge; code length is irrelevant.
Please refer to this link for a word list (use ISPELL "english.0" list - the SCOWL list is missing some pretty common words).

This listing may be referred to/imported/read in your code any way you wish.
Only words matched by the regex ^([a-pr-z]|qu){3,16}$ will be counted. (Only lowercase letters, 3-16 characters, qu must be used as a unit.)

Words are formed by linking adjacent letters (horizontal, vertical, and diagonal) to spell words out in the correct order, without using a single die more than once in a single words.

Words must be 3 letters or longer; shorter words will earn no points.
Duplicated letters are acceptable, just not dice.
Words that span the edges/cross over from one side of the board to the other are not allowed.

The final Boggle (not challenge) score is the total of the point values for all the words that are found.

The point value assigned for each word is based on the length of the word. (see below)
Normal Boggle rules would deduct/discount words found by another player. Assume here no other players are involved and all found words count towards the total score.
However, words found more than once in the same grid should only be counted once.

Your function/program must FIND the optimal arrangement; simply hard-coding a predetermined list won't do.
Your output should be a 4x4 grid of your ideal game board, a list of all the found words for that board, and the Boggle score to match those words.

DIE CONFIGURATION

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

STANDARD BOGGLE SCORING TABLE

Word length => Points
<= 2 - 0 pts
   3 - 1
   4 - 1
   5 - 2
   6 - 3
   7 - 5
>= 8 - 11 pts
*Words using the "Qu" die will count the full 2 letters for their word, not just the 1 die.

EXAMPLE OUTPUT

A  L  O  J
V  U  T  S
L  C  H  E
G  K  R  X

CUT
THE
LUCK
HEX
....

140 points

If any further clarification is needed, please ask!

C, averaging 500+ 1500 1750 points

This is a relatively minor improvement over version 2 (see below for notes on previous versions). There are two parts. First: Instead of selecting boards randomly from the pool, the program now iterates over every board in the pool, using each one in turn before returning to the top of the pool and repeating. (Since the pool is being modified while this iteration occurs, there will still be boards that get chosen twice in a row, or worse, but this is not a serious concern.) The second change is that the program now tracks when the pool changes, and if the program goes for too long without improving the pool's contents, it determines that the search has "stalled", empties the pool, and starts over with a new search. It continues to do this until the two minutes are up.
I had initially thought that I would be employing some kind of heuristic search to get beyond the 1500-point range. @mellamokb's comment about a 4527-point board led me to assume that there was plenty of room for improvement. However, we are using a relatively small wordlist. The 4527-point board was scoring using YAWL, which is the most inclusive wordlist out there -- it's even bigger than the official US Scrabble wordlist. With this in mind, I re-examined the boards my program had found and noticed that there appeared to be a limited set of boards above 1700 or so. So for example, I had multiple runs that had discovered a board scoring 1726, but it was always the exact same board that was found (ignoring rotations and reflections).
As another test, I ran my program using YAWL as the dictionary, and it found the 4527-point board after about a dozen runs. Given this, I am hypothesizing that my program is already at the upper limit of the search space, and therefore the rewrite I was planning would introduce extra complexity for very little gain.
Here is my list of the five highest-scoring boards my program has found using the english.0 wordlist:
1735 :  D C L P  E I A E  R N T R  S E G S
1738 :  B E L S  R A D G  T I N E  S E R S
1747 :  D C L P  E I A E  N T R D  G S E R
1766 :  M P L S  S A I E  N T R N  D E S G
1772:   G R E P  T N A L  E S I T  D R E S

My belief is that the 1772 "grep board" (as I've taken to calling it), with 531 words, is the highest-scoring board possible with this wordlist. Over 50% of my program's two-minute runs end with this board. I've also left my program running overnight without it finding anything better. So if there is a higher-scoring board, it would likely have to have some aspect that defeats the program's search technique. A board in which every possible small change to the layout causes a huge drop in the total score, for example, might never be discovered by my program. My hunch is that such a board is very unlikely to exist.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>

#define WORDLISTFILE "./english.0"

#define XSIZE 4
#define YSIZE 4
#define BOARDSIZE (XSIZE * YSIZE)
#define DIEFACES 6
#define WORDBUFSIZE 256
#define MAXPOOLSIZE 32
#define STALLPOINT 64
#define RUNTIME 120

/* Generate a random int from 0 to N-1.
 */
#define random(N)  ((int)(((double)(N) * rand()) / (RAND_MAX + 1.0)))

static char const dice[BOARDSIZE][DIEFACES] = {
    "aaeegn", "elrtty", "aoottw", "abbjoo",
    "ehrtvw", "cimotu", "distty", "eiosst",
    "delrvy", "achops", "himnqu", "eeinsu",
    "eeghnw", "affkps", "hlnnrz", "deilrx"
};

/* The dictionary is represented in memory as a tree. The tree is
 * represented by its arcs; the nodes are implicit. All of the arcs
 * emanating from a single node are stored as a linked list in
 * alphabetical order.
 */
typedef struct {
    int letter:8;   /* the letter this arc is labelled with */
    int arc:24;     /* the node this arc points to (i.e. its first arc) */
    int next:24;    /* the next sibling arc emanating from this node */
    int final:1;    /* true if this arc is the end of a valid word */
} treearc;

/* Each of the slots that make up the playing board is represented
 * by the die it contains.
 */
typedef struct {
    unsigned char die;      /* which die is in this slot */
    unsigned char face;     /* which face of the die is showing */
} slot;

/* The following information defines a game.
 */
typedef struct {
    slot board[BOARDSIZE];  /* the contents of the board */
    int score;              /* how many points the board is worth */
} game;

/* The wordlist is stored as a binary search tree.
 */
typedef struct {
    int item: 24;   /* the identifier of a word in the list */
    int left: 16;   /* the branch with smaller identifiers */
    int right: 16;  /* the branch with larger identifiers */
} listnode;

/* The dictionary.
 */
static treearc *dictionary;
static int heapalloc;
static int heapsize;

/* Every slot's immediate neighbors.
 */
static int neighbors[BOARDSIZE][9];

/* The wordlist, used while scoring a board.
 */
static listnode *wordlist;
static int listalloc;
static int listsize;
static int xcursor;

/* The game that is currently being examined.
 */
static game G;

/* The highest-scoring game seen so far.
 */
static game bestgame;

/* Variables to time the program and display stats.
 */
static time_t start;
static int boardcount;
static int allscores;

/* The pool contains the N highest-scoring games seen so far.
 */
static game pool[MAXPOOLSIZE];
static int poolsize;
static int cutoffscore;
static int stallcounter;

/* Some buffers shared by recursive functions.
 */
static char wordbuf[WORDBUFSIZE];
static char gridbuf[BOARDSIZE];

/*
 * The dictionary is stored as a tree. It is created during
 * initialization and remains unmodified afterwards. When moving
 * through the tree, the program tracks the arc that points to the
 * current node. (The first arc in the heap is a dummy that points to
 * the root node, which otherwise would have no arc.)
 */

static void initdictionary(void)
{
    heapalloc = 256;
    dictionary = malloc(256 * sizeof *dictionary);
    heapsize = 1;
    dictionary->arc = 0;
    dictionary->letter = 0;
    dictionary->next = 0;
    dictionary->final = 0;
}

static int addarc(int arc, char ch)
{
    int prev, a;

    prev = arc;
    a = dictionary[arc].arc;
    for (;;) {
        if (dictionary[a].letter == ch)
            return a;
        if (!dictionary[a].letter || dictionary[a].letter > ch)
            break;
        prev = a;
        a = dictionary[a].next;
    }
    if (heapsize >= heapalloc) {
        heapalloc *= 2;
        dictionary = realloc(dictionary, heapalloc * sizeof *dictionary);
    }
    a = heapsize++;
    dictionary[a].letter = ch;
    dictionary[a].final = 0;
    dictionary[a].arc = 0;
    if (prev == arc) {
        dictionary[a].next = dictionary[prev].arc;
        dictionary[prev].arc = a;
    } else {
        dictionary[a].next = dictionary[prev].next;
        dictionary[prev].next = a;
    }
    return a;
}

static int validateword(char *word)
{
    int i;

    for (i = 0 ; word[i] != '\0' && word[i] != '\n' ; ++i)
        if (word[i] < 'a' || word[i] > 'z')
            return 0;
    if (word[i] == '\n')
        word[i] = '\0';
    if (i < 3)
        return 0;
    for ( ; *word ; ++word, --i) {
        if (*word == 'q') {
            if (word[1] != 'u')
                return 0;
            memmove(word + 1, word + 2, --i);
        }
    }
    return 1;
}

static void createdictionary(char const *filename)
{
    FILE *fp;
    int arc, i;

    initdictionary();
    fp = fopen(filename, "r");
    while (fgets(wordbuf, sizeof wordbuf, fp)) {
        if (!validateword(wordbuf))
            continue;
        arc = 0;
        for (i = 0 ; wordbuf[i] ; ++i)
            arc = addarc(arc, wordbuf[i]);
        dictionary[arc].final = 1;
    }
    fclose(fp);
}

/*
 * The wordlist is stored as a binary search tree. It is only added
 * to, searched, and erased. Instead of storing the actual word, it
 * only retains the word's final arc in the dictionary. Thus, the
 * dictionary needs to be walked in order to print out the wordlist.
 */

static void initwordlist(void)
{
    listalloc = 16;
    wordlist = malloc(listalloc * sizeof *wordlist);
    listsize = 0;
}

static int iswordinlist(int word)
{
    int node, n;

    n = 0;
    for (;;) {
        node = n;
        if (wordlist[node].item == word)
            return 1;
        if (wordlist[node].item > word)
            n = wordlist[node].left;
        else
            n = wordlist[node].right;
        if (!n)
            return 0;
    }
}

static int insertword(int word)
{
    int node, n;

    if (!listsize) {
        wordlist->item = word;
        wordlist->left = 0;
        wordlist->right = 0;
        ++listsize;
        return 1;
    }

    n = 0;
    for (;;) {
        node = n;
        if (wordlist[node].item == word)
            return 0;
        if (wordlist[node].item > word)
            n = wordlist[node].left;
        else
            n = wordlist[node].right;
        if (!n)
            break;
    }

    if (listsize >= listalloc) {
        listalloc *= 2;
        wordlist = realloc(wordlist, listalloc * sizeof *wordlist);
    }
    n = listsize++;
    wordlist[n].item = word;
    wordlist[n].left = 0;
    wordlist[n].right = 0;
    if (wordlist[node].item > word)
        wordlist[node].left = n;
    else
        wordlist[node].right = n;
    return 1;
}

static void clearwordlist(void)
{
    listsize = 0;
    G.score = 0;
}

static void scoreword(char const *word)
{
    int const scoring[] = { 0, 0, 0, 1, 1, 2, 3, 5 };
    int n, u;

    for (n = u = 0 ; word[n] ; ++n)
        if (word[n] == 'q')
            ++u;
    n += u;
    G.score += n > 7 ? 11 : scoring[n];
}

static void addwordtolist(char const *word, int id)
{
    if (insertword(id))
        scoreword(word);
}

static void _printwords(int arc, int len)
{
    int a;

    while (arc) {
        a = len + 1;
        wordbuf[len] = dictionary[arc].letter;
        if (wordbuf[len] == 'q')
            wordbuf[a++] = 'u';
        if (dictionary[arc].final) {
            if (iswordinlist(arc)) {
                wordbuf[a] = '\0';
                if (xcursor == 4) {
                    printf("%s\n", wordbuf);
                    xcursor = 0;
                } else {
                    printf("%-16s", wordbuf);
                    ++xcursor;
                }
            }
        }
        _printwords(dictionary[arc].arc, a);
        arc = dictionary[arc].next;
    }
}

static void printwordlist(void)
{
    xcursor = 0;
    _printwords(1, 0);
    if (xcursor)
        putchar('\n');
}

/*
 * The board is stored as an array of oriented dice. To score a game,
 * the program looks at each slot on the board in turn, and tries to
 * find a path along the dictionary tree that matches the letters on
 * adjacent dice.
 */

static void initneighbors(void)
{
    int i, j, n;

    for (i = 0 ; i < BOARDSIZE ; ++i) {
        n = 0;
        for (j = 0 ; j < BOARDSIZE ; ++j)
            if (i != j && abs(i / XSIZE - j / XSIZE) <= 1
                       && abs(i % XSIZE - j % XSIZE) <= 1)
                neighbors[i][n++] = j;
        neighbors[i][n] = -1;
    }
}

static void printboard(void)
{
    int i;

    for (i = 0 ; i < BOARDSIZE ; ++i) {
        printf(" %c", toupper(dice[G.board[i].die][G.board[i].face]));
        if (i % XSIZE == XSIZE - 1)
            putchar('\n');
    }
}

static void _findwords(int pos, int arc, int len)
{
    int ch, i, p;

    for (;;) {
        ch = dictionary[arc].letter;
        if (ch == gridbuf[pos])
            break;
        if (ch > gridbuf[pos] || !dictionary[arc].next)
            return;
        arc = dictionary[arc].next;
    }
    wordbuf[len++] = ch;
    if (dictionary[arc].final) {
        wordbuf[len] = '\0';
        addwordtolist(wordbuf, arc);
    }
    gridbuf[pos] = '.';
    for (i = 0 ; (p = neighbors[pos][i]) >= 0 ; ++i)
        if (gridbuf[p] != '.')
            _findwords(p, dictionary[arc].arc, len);
    gridbuf[pos] = ch;
}

static void findwordsingrid(void)
{
    int i;

    clearwordlist();
    for (i = 0 ; i < BOARDSIZE ; ++i)
        gridbuf[i] = dice[G.board[i].die][G.board[i].face];
    for (i = 0 ; i < BOARDSIZE ; ++i)
        _findwords(i, 1, 0);
}

static void shuffleboard(void)
{
    int die[BOARDSIZE];
    int i, n;

    for (i = 0 ; i < BOARDSIZE ; ++i)
        die[i] = i;
    for (i = BOARDSIZE ; i-- ; ) {
        n = random(i);
        G.board[i].die = die[n];
        G.board[i].face = random(DIEFACES);
        die[n] = die[i];
    }
}

/*
 * The pool contains the N highest-scoring games found so far. (This
 * would typically be done using a priority queue, but it represents
 * far too little of the runtime. Brute force is just as good and
 * simpler.) Note that the pool will only ever contain one board with
 * a particular score: This is a cheap way to discourage the pool from
 * filling up with almost-identical high-scoring boards.
 */

static void addgametopool(void)
{
    int i;

    if (G.score < cutoffscore)
        return;
    for (i = 0 ; i < poolsize ; ++i) {
        if (G.score == pool[i].score) {
            pool[i] = G;
            return;
        }
        if (G.score > pool[i].score)
            break;
    }
    if (poolsize < MAXPOOLSIZE)
        ++poolsize;
    if (i < poolsize) {
        memmove(pool + i + 1, pool + i, (poolsize - i - 1) * sizeof *pool);
        pool[i] = G;
    }
    cutoffscore = pool[poolsize - 1].score;
    stallcounter = 0;
}

static void selectpoolmember(int n)
{
    G = pool[n];
}

static void emptypool(void)
{
    poolsize = 0;
    cutoffscore = 0;
    stallcounter = 0;
}

/*
 * The program examines as many boards as it can in the given time,
 * and retains the one with the highest score. If the program is out
 * of time, then it reports the best-seen game and immediately exits.
 */

static void report(void)
{
    findwordsingrid();
    printboard();
    printwordlist();
    printf("score = %d\n", G.score);
    fprintf(stderr, "// score: %d points (%d words)\n", G.score, listsize);
    fprintf(stderr, "// %d boards examined\n", boardcount);
    fprintf(stderr, "// avg score: %.1f\n", (double)allscores / boardcount);
    fprintf(stderr, "// runtime: %ld s\n", time(0) - start);
}

static void scoreboard(void)
{
    findwordsingrid();
    ++boardcount;
    allscores += G.score;
    addgametopool();
    if (bestgame.score < G.score) {
        bestgame = G;
        fprintf(stderr, "// %ld s: board %d scoring %d\n",
                time(0) - start, boardcount, G.score);
    }

    if (time(0) - start >= RUNTIME) {
        G = bestgame;
        report();
        exit(0);
    }
}

static void restartpool(void)
{
    emptypool();
    while (poolsize < MAXPOOLSIZE) {
        shuffleboard();
        scoreboard();
    }
}

/*
 * Making small modifications to a board.
 */

static void turndie(void)
{
    int i, j;

    i = random(BOARDSIZE);
    j = random(DIEFACES - 1) + 1;
    G.board[i].face = (G.board[i].face + j) % DIEFACES;
}

static void swapdice(void)
{
    slot t;
    int p, q;

    p = random(BOARDSIZE);
    q = random(BOARDSIZE - 1);
    if (q >= p)
        ++q;
    t = G.board[p];
    G.board[p] = G.board[q];
    G.board[q] = t;
}

/*
 *
 */

int main(void)
{
    int i;

    start = time(0);
    srand((unsigned int)start);

    createdictionary(WORDLISTFILE);
    initwordlist();
    initneighbors();

    restartpool();
    for (;;) {
        for (i = 0 ; i < poolsize ; ++i) {
            selectpoolmember(i);
            turndie();
            scoreboard();
            selectpoolmember(i);
            swapdice();
            scoreboard();
        }
        ++stallcounter;
        if (stallcounter >= STALLPOINT) {
            fprintf(stderr, "// stalled; restarting search\n");
            restartpool();
        }
    }

    return 0;
}

Notes for version 2 (June 9)
Here's one way to use the initial version of my code as a jumping-off point. The changes to this version consist of less than 100 lines, but tripled the average game score.
In this version, the program maintains a "pool" of candidates, consisting of the N highest-scoring boards that the program has generated so far. Every time a new board is generated, it is added to the pool and the lowest-scoring board in the pool is removed (which may very well be the board that was just added, if its score is lower than what's already there). The pool is initially filled with randomly generated boards, after which it keeps a constant size throughout the program's run.
The program's main loop consists of of selecting a random board from the pool and altering it, determining this new board's score and then putting it into the pool (if it scores well enough). In this fashion the program is continually refining high-scoring boards. The main activity is to make stepwise, incremental improvements, but the size of the pool also allows the program to find multi-step improvements that temporarily make a board's score worse before it can make it better.
Typically this program finds a good local maximum rather quickly, after which presumably any better maximum is too distant to be found. And so once again there's little point to running the program longer than 10 seconds. This might be improved by e.g. having the program detect this situation and start a fresh search with a new pool of candidates. However, this would net only a marginal increase. A proper heuristic search technique would likely be a better avenue of exploration.
(Side note: I saw that this version was generating about 5k boards/sec. Since the first version typically did 20k boards/sec, I was initially concerned. Upon profiling, however, I discovered that the extra time was spent managing the wordlist. In other words, it was entirely due to the program finding so many more words per board. In light of this, I considered changing the code to manage the wordlist, but given that this program is only using 10 of its allotted 120 seconds, such an optimization would be very premature.)
Notes for version 1 (June 2)
This is a very, very simple solution. All it does it generate random boards, and then after 10 seconds it outputs the one with the highest score. (I defaulted to 10 seconds because the extra 110 seconds permitted by the problem specification typically doesn't improve the final solution found enough to be worth waiting for.) So it's extremely dumb. However, it has all the infrastructure to make a good starting point for a more intelligent search, and if anyone wishes to make use of it before the deadline, I encourage them to do so.
The program starts by reading the dictionary into a tree structure. (The form isn't quite as optimized as it could be, but it's more than good enough for these purposes.) After some other basic initialization, it then begins generating boards and scoring them. The program examines about 20k boards per second on my machine, and after about 200k boards the random approach starts to run dry.
Since only one board is actually being evaluated at any given time, the scoring data is stored in global variables. This allows me to minimize the amount of constant data that has to be passed as arguments to the recursive functions. (I'm sure this will give some people hives, and to them I apologize.) The wordlist is stored as a binary search tree. Every word found has to be looked up in the wordlist, so that duplicate words aren't counted twice. The wordlist is only needed during the evaulation process, however, so it's discarded after the score is found. Thus, at the end of the program, the chosen board has to be scored all over again, so that the wordlist can be printed out.
Fun fact: The average score for a randomly-generated Boggle board, as scored by english.0, is 61.7 points.


Print "Hey Jude" from The Beatles Your task is to write a program which prints following four verses extracted from the lyrics from The Beatles' song "Hey Jude" (© Sony/ATV Music Publishing LLC):

Hey Jude, don't make it bad\n
Take a sad song and make it better\n
Remember to let her into your heart\n
Then you can start to make it better\n
\n
Hey Jude, don't be afraid\n
You were made to go out and get her\n
The minute you let her under your skin\n
Then you begin to make it better\n
\n
Hey Jude, don't let me down\n
You have found her, now go and get her\n
Remember to let her into your heart\n
Then you can start to make it better\n
\n
Hey Jude, don't make it bad\n
Take a sad song and make it better\n
Remember to let her under your skin\n
Then you'll begin to make it\n
\n

BUT

The only input you are allowed to use to construct these four verses is this list of tokens:

"Hey Jude, don't"
" make it bad"
" be afraid"
" let me down"
"Take a sad song and make it better"
"You"
" were made to go out"
" and get her"
" have found her, now go"
"Remember to"
"The minute you"
" let her"
" into your heart"
" under your skin"
"Then"
" you"
" can start"
"'ll"
" begin"
" to make it"
" better"

Note that some tokens have a space preceded and that enclosing quotes are not part of the tokens. You are free to use any format for the list and to rearrange the order of the tokens.

Your generated output has to exactly match the above four verses. Note that\n is used for newlines and an extra newline is added after each verse. You can use this file (MD5: 4551829c84a370fc5e6eb1d5c854cbec) to check your output against.

You can use following railroad diagram to understand the structure of the verses (each element represents a token):

Shortest code in bytes wins. Happy golfing.

JavaScript (ES6), 108 bytes
a=>`01
4
9bc
efgjk

02
567
abd
efijk

03
587
9bc
efgjk

01
4
9bd
efhij

`.replace(/./g,n=>a[parseInt(n,36)])

Try it online!

Alternate version, 114 bytes
A slightly better compression, but sadly ruined by the larger decompression code.
a=>`835fc3cbbd3
84db3db4bbdb3
85cd1cc3cbbd3
835fc4bbcb3

`.replace(/./g,n=>a[n='0x'+n,i=n%8&&n%8-2+i]+[`
`[n>>3]])

Try it online!


Format microseconds as hours:minutes:seconds, etc The following is inspired by a question that came up on Stack Overflow today.

Given a number of microseconds, 0 <= n <= 86400000000 (e.g. 12345678900), output a formatted string hh:mm:ss:000:000, e.g. 03:25:45:678:900.

          0 -> '00:00:00:000:000'
12345678900 -> '03:25:45:678:900'
86400000000 -> '24:00:00:000:000'

I have a solution in Python in 209 bytes, but can it go lower?

Python 2, 82 79 bytes

n=input()
o=""
for k in[1000]*2+[60]*3:o=":%0*d"%(k%7/2,n%k)+o;n/=k
print o[1:]

Builds the string, iterating through a series of divmods. The only fancy bit is the %7/2, which maps 1000 -> 3 and 60 -> 2.


Partitioning Digits into Distinct Integers Given a sequence of base-10 digits, output the longest list of integers that contains all the digits exactly once, in the order in which they appeared in the input, without repeating any integers.

Examples

Input: 12345
Output: [1, 2, 3, 4, 5]

Input: 12123
Output: [1, 2, 12, 3]

Input: 10010
Output: [100, 1, 0]

Input: 35353
Output: [35, 3, 53] or [3, 5, 353]

Input: 988382
Output: [9, 88, 3, 8, 2]

Rules

Use any convenient formats for input and output
You must support input sequences of up to 10,000 digits long.
You must support integers of 18 decimal digits or more (This will fit in 64-bit integers, though you may want work with strings anyway)
You may assume that the input given can be made into a sequences where the 18-digit number requirement is possible.
If there is more than one possible longest sequence, you may output any one of them.
Numbers in the output sequence may not be zero-padded.
Zero is a valid element, but it can, of course, only be used once in the output.
There is no time or complexity requirement.
Shortest code wins.

Jelly, 14 bytes

ŒṖḌD$ƑƇḌQƑƇLÞṪ

Try it online!

A monadic link taking a list of base-10 digits and returning a list of integers.

Added a byte (and switched to numbers) because of the zero padding issue.

Added 5 bytes to fix a further issue with zeros pointed out by @KevinCruijssen - thanks!

Explanation

ŒṖ             | Partitions of list
  ḌD$ƑƇ        | Keep only those invariant when converted to integers and back to lists of digits
       Ḍ       | Convert from lists of lists of lists of decimal digits to lists of lists of integers
        QƑƇ    | Keep only those invariant when uniquified
           LÞ  | Sort by ascending length
             Ṫ | Tail


Test if a string is parenthesly balanced We call a parens group the open paren (, its matching close paren ) and everything inside them.
A parens group or string is called parenthesly balanced if it contains either nothing or only 2 parenthesly balanced parens groups.
For example:
The string   "(()())()"      is parenthesly balanced
              (    )()       Because it contains exactly 2 parenthesly balanced parens groups
               ()()          The left one is parenthesly balanced because it contains 2 parenthesly balanced parens groups (balanced because they are empty). The right one is parenthesly balanced because it contains nothing.

Likewise:
The string   "(()(()))()"    is not parenthesly balanced
              (      )()     Because it contains a parens group that is not parenthesly balanced: the left one
               ()(  )        The left one is not balanced because it contains a parens group that is not balanced: the right one
                  ()         The right one is not balanced because it only contains one balanced group.

So, a parenthesly balanced string or parens group should either:

Contain nothing at all.
Or contain only and exactly 2 parenthesly balanced parens groups. It should contain nothing else.

Task:
Your task is to write a function or program that checks if a given string is a parenthesly balanced one or not.
Input:
Input will be a string or list of characters or something similar. You can assume that the string will only consist of the characters '(' and ')'. You can also assume that each open paren ( will have its matching close paren ), so don't worry about strings like "(((" or ")(" or "(())("...
Note: As mentioned by @DigitalTrauma in his comment bellow, it's ok to subtitute the () combo by other characters (such as <>, [], ...), if it's causing additional work like escaping in some languages
Output:
Anything to signal whether the string is parenthesly balanced or not (true or false, 1 or 0, ...). Please include in your answer what your function/program is expected to yield.
Examples:
""                                        => True
"()()"                                    => True
"()(()())"                                => True
"(()(()(()())))(()())"                    => True
"(((((((()())())())())())())())()"        => True
"()"                                      => False
"()()()"                                  => False
"(())()"                                  => False
"()(()(())())"                            => False
"(()())(((((()())()))())())"              => False
"()(()()()())"                            => False
"()(()(()())()())"                        => False

The last two examples really made a difference!
Best of luck!

Japt v2, 20 bytes

V="()"V¥iU1 eViV²1 V

Test it online!

Everyone misunderstood the challenge at first and though that each pair of parentheses had to contain an even number of sub-pairs, when in fact the challenge actually asks for 0 or 2 sub-pairs. So here's my revised answer, using the same technique as before.

We can still solve the challenge with recursive replacement. The thing is, instead of just removing all occurrences of ()(), we need to make sure that there's nothing else in the same wrapper besides the ()() (in other words, no ()()()() or anything like that). We can do this by recursively replacing (()()) with ().

The new problem is that the input itself does not have one pair of outer parentheses (as that would make it not a parenthesly balanced string), forcing us to wrap it in an extra pair to fully reduce it. Finally, the end result for balanced strings is now () instead of the empty string, so we check for equality rather than just taking logical NOT of the output.


Mad Libs number sequences My robot for generating Mad Libs-style sequence challenges has gone rogue! To defeat it, I need you to write code that can solve all the challenges it can crank out.

Your input is three selections for the blanks A, B, C, each from (1,2,3), specifying the sequence challenge to solve, and the number \$n\$ that's the input to the challenge.

Challenges

Given a positive integer \$n\$, output (A) ________

  A:
    (1) the \$n\$'th
    (2) whether \$n\$ is a
    (3) the smallest number above \$n\$ that's a

positive (B) _______

  B:
  (1) Fibonacci number
  (2) triangular number
  (3) multiple of 3

whose base-10 representation (C) _______

  C:
  (1) starts and ends with the same digit.
  (2) is in sorted order.
  (3) doesn't have any 1's.

Example

Given selections (A, B, C) = (3, 1, 1) and n=13, the challenge is "Given a positive integer \$n\$, output (A3) the smallest number above \$n\$ that's a positive (B1) Fibonacci number whose base-10 representation (C1) starts and ends with the same digit." With input n=13, the Fibonacci numbers bigger than \$13\$ start out as \$21, 34, 55, 89, ...\$, and the first one starting and ending with the same digit is is 55. So you should output 55.

Details

You may take the fill-in-the-blank selections one-indexed (1, 2, 3) or zero-indexed (0, 1, 2).
Note that we're restricting the sequences to positive values, so none of them contain zero. They start as

Fibonacci: \$1, 1, 2, 3, ...\$
Triangular: \$1, 3, 6, 10, ...\$
Multiple of 3: \$3, 6, 9, 12, ...\$

For choice A1, outputting the \$n\$'th element, \$n\$ is one-indexed. So, the n=1 Fibonacci number is 1, the n=2 Fibonacci number is also 1, n=3 gives 2, and so on.
For deciding whether n is in the sequence (A2), you may use any two consistent outputs decision-problem-style.
You may assume that each sequence has an infinite number of terms meeting each condition C, and not worry about what happens with machine overflows and the like.
For C2, digits in sorted order can have "ties", such as 377.

Test cases

Here are all outputs for every combination with n=10, as (A,B,C), n: result. For these, we use one-indexed selections, and for A2 we use 1/0 for True/False

(1, 1, 1), 10: 165580141
(1, 1, 2), 10: 89
(1, 1, 3), 10: 987
(1, 2, 1), 10: 1431
(1, 2, 2), 10: 78
(1, 2, 3), 10: 276
(1, 3, 1), 10: 222
(1, 3, 2), 10: 36
(1, 3, 3), 10: 42
(2, 1, 1), 10: 0
(2, 1, 2), 10: 0
(2, 1, 3), 10: 0
(2, 2, 1), 10: 0
(2, 2, 2), 10: 0
(2, 2, 3), 10: 0
(2, 3, 1), 10: 0
(2, 3, 2), 10: 0
(2, 3, 3), 10: 0
(3, 1, 1), 10: 55
(3, 1, 2), 10: 13
(3, 1, 3), 10: 34
(3, 2, 1), 10: 55
(3, 2, 2), 10: 15
(3, 2, 3), 10: 28
(3, 3, 1), 10: 33
(3, 3, 2), 10: 12
(3, 3, 3), 10: 24

The first 10 outputs, n=1 to n=10, for each challenge combination are:

(1, 1, 1): 1, 1, 2, 3, 5, 8, 55, 17711, 63245986, 165580141,
(1, 1, 2): 1, 1, 2, 3, 5, 8, 13, 34, 55, 89,
(1, 1, 3): 2, 3, 5, 8, 34, 55, 89, 233, 377, 987,
(1, 2, 1): 1, 3, 6, 55, 66, 171, 595, 666, 1081, 1431,
(1, 2, 2): 1, 3, 6, 15, 28, 36, 45, 55, 66, 78,
(1, 2, 3): 3, 6, 28, 36, 45, 55, 66, 78, 253, 276,
(1, 3, 1): 3, 6, 9, 33, 66, 99, 111, 141, 171, 222,
(1, 3, 2): 3, 6, 9, 12, 15, 18, 24, 27, 33, 36,
(1, 3, 3): 3, 6, 9, 24, 27, 30, 33, 36, 39, 42,
(2, 1, 1): 1, 1, 1, 0, 1, 0, 0, 1, 0, 0,
(2, 1, 2): 1, 1, 1, 0, 1, 0, 0, 1, 0, 0,
(2, 1, 3): 0, 1, 1, 0, 1, 0, 0, 1, 0, 0,
(2, 2, 1): 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
(2, 2, 2): 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
(2, 2, 3): 0, 0, 1, 0, 0, 1, 0, 0, 0, 0,
(2, 3, 1): 0, 0, 1, 0, 0, 1, 0, 0, 1, 0,
(2, 3, 2): 0, 0, 1, 0, 0, 1, 0, 0, 1, 0,
(2, 3, 3): 0, 0, 1, 0, 0, 1, 0, 0, 1, 0,
(3, 1, 1): 2, 3, 5, 5, 8, 8, 8, 55, 55, 55,
(3, 1, 2): 2, 3, 5, 5, 8, 8, 8, 13, 13, 13,
(3, 1, 3): 2, 3, 5, 5, 8, 8, 8, 34, 34, 34,
(3, 2, 1): 3, 3, 6, 6, 6, 55, 55, 55, 55, 55,
(3, 2, 2): 3, 3, 6, 6, 6, 15, 15, 15, 15, 15,
(3, 2, 3): 3, 3, 6, 6, 6, 28, 28, 28, 28, 28,
(3, 3, 1): 3, 3, 6, 6, 6, 9, 9, 9, 33, 33,
(3, 3, 2): 3, 3, 6, 6, 6, 9, 9, 9, 12, 12,
(3, 3, 3): 3, 3, 6, 6, 6, 9, 9, 9, 24, 24,

JavaScript (ES6),  158 ... 145  144 bytes
Takes input as (a,b,c,n), with \$a\$, \$b\$ and \$c\$ 0-indexed.

(a,b,c,n)=>(g=x=>[(d=[...x+''],i+=C=![d[0]-x%10,d+''>d.sort(),/1/.test(x)][c])>n,x>=n,x>n&C][a]?a-1?x:C&x==n:g([y,x+y,x+3][b],y+=b||x))(i=0,y=1)

Try it online!
Commented
(a, b, c, n) => (              // given the challenge parameters ...
  g = x =>                     // g is a recursive function taking the current value x
    [                          // this is the array for A
      (                        //   a = 0:
        d = [...x + ''],       //     d[] = array of digits in x
        i += C =               //     increment i if C is true
          ![                   //     set C if the condition is false:
            d[0] - x % 10,     //       c = 0: the 1st and the last digits are not equal
            d + '' > d.sort(), //       c = 1: the digits are not in sorted order
            /1/.test(x)        //       c = 2: there's a '1' in x
          ][c]                 //     pick the relevant condition for C
      ) > n,                   //     exit if i is greater than n
      x >= n,                  //   a = 1: exit if x is greater than or equal to n
      x > n & C                //   a = 2: exit if x is greater than n and C is true
    ][a]                       // pick the relevant condition for A
    ?                          // if we're done:
      a - 1 ? x                //   if a is not equal to 1, return x
            : C & x == n       //   otherwise, test whether C is true and x is equal to n
    :                          // else:
      g(                       //   do a recursive call:
        [                      //     update x:
          y,                   //       b = 0: x = y (Fibonacci)
          x + y,               //       b = 1: x += y (triangular numbers)
          x + 3                //       b = 2: x += 3 (multiples of 3)
        ][b],                  //     pick the relevant update for B
        y += b || x            //     if b = 0, add x to y (for Fibonacci)
                               //     otherwise, add b to y (we actually just need to
                               //     add 1 for triangular numbers; for multiples of 3,
                               //     y is ignored anyway)
      )                        //   end of recursive call
)(i = 0, y = 1)                // initial call to g with x = i = 0 and y = 1


Number Spiral Problem A number spiral is an infinite grid whose upper-left square has number 1. Here are the first five layers of the spiral:

Your task is to find out the number in row y and column x.

Example:

Input: 2 3
Out  : 8
Input: 1 1
Out  : 1
Input: 4 2
Out  : 15

Note:

Any programming language is allowed.
This is a code-golf challenge so shortest code wins.
Best of Luck!

Source: https://cses.fi/problemset/task/1071

C (gcc),  44  43 bytes

f(x,y,z){z=x>y?x:y;z=z*z-~(z%2?y-x:x-y)-z;}

Try it online!

The spiral has several "arms":

12345
22345
33345
44445
55555

The position \$(x, y)\$ is located on arm \$\max(x, y)\$ (assigned to variable z). Then, the largest number on arm \$n\$ is \$n^2\$, which alternates between being in the bottom left and top right position on the arm. Subtracting \$x\$ from \$y\$ gives the sequence \$-n+1, -n+2, \ldots, -1, 0, 1, \ldots, n-1, n-2\$ moving along arm \$n\$, so we choose the appropriate sign based on the parity of \$n\$, adjust by \$n-1\$ to get a sequence starting at 0, and subtract this value from \$n^2\$.

Thanks to Mr. Xcoder for saving a byte.


Is this Tic-Tac-Toe board valid? Challenge

Given a tic-tac-toe board in any format, determine if it is valid or not. If a board can be the result of a tic-tac-toe game, then it is valid. For example, this board is valid:X O X
O X O
X O XOn the contrary, this board is invalid:

X X X
X X O
O O O

Input

A full (9/9) tic tac toe board (the outcome, not the game).

Rules

The input format must be able to depict all 512 possible input boards. It must be specified, along with the instructions to create it if it is obscure/unclear. You must state the marks of the board individually though.
There must be two possible outputs, one for validity and one for invalidity.
You can assume the board does not have empty spots.

Test cases

Valid:

X O X
O X O
X O X

X O X
X O X
O X O

X O O
O O X
O X X

O X O
X O X
O X O

Invalid:

X X X
X X X
X X X

O O O
O O O
O O O

X X X
O O O
X X X

O O O
O O X
X X X

X X O
O X O
O O X

A little help?

A board is considered valid (for this challenge) if and only if the following two conditions hold:

There are 5 X and 4 O, or 4 X and 5 O. For example,
X X X
O X O
X X Xis considered invalid, because there are 7 Xs and 2 Os.
Only the player with 5 marks has won, or none of them have won. For example,
X X X
O O O
O O Xis considered invalid, since either the row of Os or the row of Xs will be formed first. The two players can't have their turn simultaneously.

The current winner is...

...ais523's Jelly answer, at an astounding 26 bytes!

JavaScript (ES6), 88 87 bytes

s=>(a=[...s]).sort()[5]-a[3]&[7,56,73,84,146,273,292,448].every(j=>j&i,i=`0b`+s^~-a[4])

Takes input as a string of 9 0 and 1 characters and returns 1 for valid, 0 for invalid. We sort the characters into order. If the middle three characters are now the same then the board is invalid as there are too many of one piece. Otherwise, we convert the original board into binary, flipping the bits if there are more 0s than 1s. At this point the board is valid if 0 does not have a line of three, so we simply test all eight lines via an array of bitmasks. Edit: Saved 1 byte thanks to @ETHproductions.


Number of surjections Task

Given 2 positive integers n and k, where n > k, output the number of surjections from a set of n distinguishable elements to a set of k distinguishable elements.

Definition

A function f: S → T is called a surjection if for every t∈T there is s∈S such that f(s) = t.

Example

When n=3 and k=2, the output is 6, since there are 6 surjections from {1,2,3} to {1,2}:

1↦1, 2↦1, 3↦2
1↦1, 2↦2, 3↦1
1↦1, 2↦2, 3↦2
1↦2, 2↦1, 3↦1
1↦2, 2↦1, 3↦2
1↦2, 2↦2, 3↦1

Testcases

n k output
5 3 150
8 4 40824
9 8 1451520

Reference

OEIS A019538

Scoring

This is code-golf. Shortest answer in bytes wins.

Standard loopholes apply.

Jelly, 5 4 bytes

ṗṬML

This is an O(kn) brute force solution.

Try it online!

How it works

ṗṬML  Main link. Left argument: k. Right argument: n.

ṗ     Cartesian power; yield the list of all n-tuples over {1, ..., k}.
      Each tuple represents a (not necessarily surjective) function from
      {1, ..., n} to {1, ..., k}.
 Ṭ    Apply the "untruth" atom to each tuple.
      Ṭ maps a list of indices to an array with 1's at those indices, and exactly
      as many zeroes as needed to build the array.
      Examples:
           [1, 2, 3, 3, 3] -> [1, 1, 1]
           [1, 3, 5]       -> [1, 0, 1, 0, 1]
           [2, 6, 2, 4, 4] -> [0, 1, 0, 1, 0, 1]
  M   Yield all indices of maximal elements, i.e., all indices of [1] * k.
   L  Take the length.


Percentage of work days in a month Given a year and a month, find out the percentage of work days in said
month. Work days are Monday through Friday with no regard to holidays or
other special things. The Gregorian calendar is used.

Input

A year and month in ISO 8601 format (YYYY-MM). The year always has four
digits, the month always has two digits. The given year will not be before
1582.

Output

Output is the percentage of work days (according to above definition) in
the given month, rounded to a whole number. No percent sign or fractional
digits follow.

Sample 1

Input                Output

2010-05              68

Sample 2

Input                Output

2010-06              73

Sample 3

Input                Output

1920-10              68

Sample 4

Input                Output

2817-12              68

A week has passed, an answer has been accepted. For the curious, the sizes of the submissions we got in our contest:

  129 – Z shell
  174 – VB.NET
  222 – C
  233 – C
  300 – C

As well as our own (unranked) solutions:

    75 – PowerShell
    93 – Ruby
  112 – Bourne shell

64-bit Perl, 67 68

Perl 5.10 or later, run with perl -E 'code here' or perl -M5.010 filename

map{$d++,/^S/||$w++if$_=`date -d@ARGV-$_`}1..31;say int.5+100*$w/$d

Concessions to code size:

locale-sensitive: it counts as work days the days whose date output don't start with a capital S.  Run under LC_ALL=C if in doubt.
output is pure and well-formatted, but there's "garbage" on stderr on months shorter than 31.  2> /dev/null if upset.
for some reason, my version of date considers 2817-12 an invalid month.  Who knew, GNU new apocalypse is due! Requires a 64 bit build of date for dates after 2038.  (Thanks Joey)


Am I being run backwards? Your task is to write a program, function, or snippet that will output one value if run forward, and another if run backward. The program must run without errors.

The output can be any two distinct values, of the same data type. For example, 1 and 3, true and false, or 't' and 'f'. In languages without a concept of data types, such as brainf*** or text, any distinct values are allowed.

This is a code golf challenge, shortest answer per language wins. Note that snippets are allowed (so something like 1-2 is valid, but don't expect any upvotes).

Python 3, no comments or string literals, 106 bytes

x=quit
y=x.__class__
y.__add__=print
y.__pos__=x
x+x++x+x
x=__sop__.y
tnirp=__dda__.y
__ssalc__.x=y
tixe=x

I've never liked how comments and string literals let you "turn off" most of your language's syntax in challenges like this, so I wanted to see how far I could golf things without using either comments or string literals. This is what I came up with.

Since I don't have any way to disable the syntactical significance of parentheses, I cannot use the function call operator. Any attempt to do so would result in the reversed code having a closing parenthesis before the first opening parenthesis, which is invalid outside a comment or string literal. I also can't use def or container literals (aside from unparenthesized tuples), and my access to language features is in general extremely restricted.

One thing I can do is take advantage of Python's operator overloading to call functions implicitly. My ability to define any classes or functions is extremely limited, but fortunately, there are enough tools lying around in the built-in namespace for me to use. Most built-ins don't let me perform the attribute assignment I need to redefine their operator overloads, but (unless Python is run with one of the flags that disables site importing) the auto-imported site module adds quit and exit objects to the built-ins. These objects are instances of non-C classes, so I can reassign their operator overloads.

Setting __add__ to print lets me use addition to print things, and setting __pos__ to quit or exit lets me use the unary + operator to abort the program before the rest of the code runs. Without setting __pos__, I would need a bunch of additional code to make sure the "backwards" part of the code can find all the variables and attributes it needs to not fail. With __pos__, I only need to make sure the "backwards" code is still syntactically valid.

Forward, the code prints

Use quit() or Ctrl-D (i.e. EOF) to exit

Backward, the code prints

Use exit() or Ctrl-D (i.e. EOF) to exit

(The messages are slightly different on Windows.)

I also tried to figure out a way to do this by defining my own class instead of messing with quit.__class__. I got as far as the following:

if.1j:adbmal=1j
class ton:adbmal
a=lambda:j1.fi
j1=a
a.__dict__=a.__globals__

class ton:adbmal is one of the very few combinations of class name and class body such that the class statement is syntactically valid backward. tressa, led, labolg, tropmi, and esiar would also have been valid class names (with a different class body, such as not fi), but ton is the only one where the reversed name can be part of an expression, giving the most flexibility.

if.1j:adbmal=1j assigns a value to adbmal to make the class body succeed, while still being syntactically valid backward.

The stuff with a and j1 lets me use j1.ton to refer to my ton class, which is still a valid expression backward.

At this point, I got stuck. I couldn't figure out how to get my class out of j1.ton and into a more useful variable. I can't assign attributes on j1.ton and still have valid syntax backward, so I can't set operator overloads. I also wanted to set builtins.__build_class__ to my class so I could abuse the class statement to construct instances without the function call operator, but trying to put j1.ton on the right side of an assignment produces invalid syntax backward.

If I had been able to name my class something like fi or tpecxe, I could have used tricks like b:j1.fi to get the class into an annotation and then a.__dict__=__annotations__ to get it into a.b, but I couldn't find any way to get the class statement and the annotation tricks to hook up. Anything that was compatible with the class statement was incompatible with the annotation tricks.

(You might wonder why I didn't abuse builtins.__build_class__ to call an existing function directly, like print. I couldn't figure out a way to do that and have the output be deterministic, and I wanted deterministic output.)


Most common elements of a list in Python This is a tips question for golfing in Python, which is on topic for main.

I'm looking for the shortest way to get all of the most common elements of a list in Python, in the shortest way possible. Here's what I've tried, assuming the list is in a variable called l:

from statistics import*
mode(l)

This throws an error if there are multiple modes.

max(l,key=l.count)

This only returns 1 item, I need to get all the elements of greatest count.

from collections import*
Counter(l).most_common()

This returns a list of tuples of (element, count), sorted by count. From this I could pull all the elements whose corresponding count is equal to the first, but I don't see a way to golf this much better than:

from collections import*
c=Counter(l).most_common()
[s for s,i in c if i==c[0][1]]

I am sure there is a shorter way!

Also, if it can be done without variable assignment or multiple uses of l, I can keep the rest of the code as a lambda expression to save more bytes.

Edit: Per @Uriel's suggestion, we can do:

{s for s in l if l.count(s)==l.count(max(l,key=l.count))}

And I can alias list.count for a few bytes:

c=l.count;{s for s in l if c(s)==c(max(l,key=c))}

@Uriel pointed out that we can get a couple more bytes with map:

c=l.count;{s for s in l if c(s)==max(map(c,l))}

How about this one?

c=l.count;{x for x in l if c(x)==max(map(c,l))}

Enclose in [*...] to get a list.


Concatenate lists of strings item-wise in Python This is a tips question for golfing in python.

Suppose you have two lists of strings, and you want to concatenate the corresponding entries from each list. E.g. with a=list("abcd") and b=list("1234"), calculate ["a1","b2","c3","d4"].

This is trivial in array-based programming languages, where operations generally apply memberwise to lists. For example, in my golfing language Pip, the code is simply a.b. But in Python, it's not so easy.

The Pythonic way is probably to use zip and a list comprehension (25 chars):

[x+y for x,y in zip(a,b)]

Another method is map with a lambda function (23):

map(lambda x,y:x+y,a,b)

The following is the shortest I've come up with (21):

map("".join,zip(a,b))

Is there any shorter method?

Assume that the lists are the same length and that some kind of iterable is all that's needed (so a map object is fine in Python 3).

20 chars

map(str.__add__,a,b)

Uses the build-in method string addition method __add__ that is invoked by + on strings in place of your anonymous function lambda x,y:x+y.


Two roads diverged in a yellow wood (part 2) This is the second in a series, the third is Two roads diverged in a yellow wood (part 3)

This is based on Two roads diverged in a yellow wood (part 1), a previous challenge of mine. It was fairly well received, but it was also fairly trivial (a Java answer in 52 bytes!) So I made something more complex...

The inspiration

This challenge is inspired by Robert Frost's famous poem, "The Road Not Taken":

  Two roads diverged in a yellow wood,
  And sorry I could not travel both
  And be one traveler, long I stood
  And looked down one as far as I could
  To where it bent in the undergrowth;

  ...2 paragraphs trimmed...

  I shall be telling this with a sigh
  Somewhere ages and ages hence:
  Two roads diverged in a wood, and I —
  I took the one less traveled by,
  And that has made all the difference.

Notice the second to last line, I took the one less traveled by,. Your goal is to find the road least travelled by in your string input. You must output one of 2 values that are distinct from each other that signal which way you should turn to take the road less traveled by. Once the road forks (the trail of hexagons changes to numbers) you are at the intersection. From there, there will be 2 paths made up of digits. The path whose digits has the lowest sum will be the road not taken. Note that the road not taken may have a larger path but a lower path sum. Here are some examples / test cases from a program that prints "left" or "right" for the path not taken:

 1     2
  1   2
   1 2
    #
    #
    #
left (3 < 6)

 1     2
  2   2
   1 1
    #
    #
    #
left (4 < 5)

 12    2
  11  2
   1 1
    #
    #
    #
right (6 > 5)

 99   989
  99  89
  99 99
  99 99
    #
    #
    #
   #
left (72 < 79)

1111 1110
 001 111
  11 11
  11 11
    #
   ##
  ##
 ##
left (9 < 10) (Note: 1111 is interpreted as 1+1+1+1=4, not 1111=1111)

1       1
 0     1
  1   1
  1   1
  1   1
  1   1
   1 1
    #
    #
    #
     #
      #
left (6 < 7)

1   1
 0   1
  1   1
  1   1
  1   1
  1   1
   1 1
    #
    #
    #
     #
      #
left (6 < 7)

Things to assume & remember

There will always be 2 paths. No more, no less.
You can take input from STDIN one line at a time, a string containing LF characters, or a string containing a literal backslash and a n. If you need input in any other way, ask for approval in the comments.
You don't have to worry about invalid input or tied paths. Those will never be inputted to your program / function.
The input can be of any length in width or height, less than the string limit of your language.
There will never be a # and a number in the same line.
All digits in the path are positive integers 0 to 9.
Input or output with a trailing newline is allowed.
See my JS ES6 answer below for an example.
There will always be at least 1 space between the 2 paths.
The 2 paths will always have the same height for each map, but may be different on other maps.
If you are confused about a specific test case, please tell me.
1111 is interpreted as 1+1+1+1=4, not 1111=1111. The map is a series of one-digit numbers, not numbers of arbitrary length.
This is code-golf, so the shortest answer in bytes wins!
Standard loopholes forbidden

If you have any questions about this challenge, ask me in the comments, and good luck!

Retina, 28 bytes

\d
$*
%r`1\G
-
Os`.
+`-1

1+

Try it online!

Prints 0 for left and 1 for right. Assumes that there are not trailing spaces on any lines.

Explanation

\d
$*

Convert each digit N to a run  of N ones.

%r`1\G
-

One each line (%), match consecutive (\G)  ones from the end (r) and replace each of them with - (i.e. turn the right branch into -s).

Os`.

Sort all characters, so that all -s are directly in front of all 1s.

+`-1

Repeatedly cancel a pair of - and 1.

1+

Try to match at least one 1 (if so, there were more weights in the left path).


Pad a file with zeros Your task today will be to take an existing file and append zeros to it until it reaches a certain size.

You must write a program or function which takes the name of a file in the current directory f and a number of bytes b. While maintaining the original content of f, you must write zeroes (null bytes, not ascii 0s) to the end so that its new size is b bytes.

You may assume that f only has alphanumeric ascii in its name, that you have full permissions over it, that it initially is not larger than b, but may be as large as b, and that there is infinite free disk space.

You may not assume f is nonempty, or that it does not already contain null bytes.

Other existing files should not be modified and new files should not exist after execution ends.

Test Cases

Contents of f | b  | Resulting contents of f
12345         | 10 | 1234500000
0             | 3  | 000
[empty]       | 2  | 00
[empty]       | 0  | [empty]
123           | 3  | 123

Bash + coreutils, 13

truncate -s$@

Input from the command-line - the first parameter is the file size and the second is the filename.
From man truncate:

If a FILE is shorter, it is extended and the extended part (hole) reads as zero bytes.

Try it online.


Numbering Hierarchical Outlines Write a program that takes in a string where every line consists of the character 0 indented by some number of spaces. The top line is not indented and every other line will be indented by at most one more space than the line just before it.
No lines will have trailing spaces but you may optionally assume there is a single trailing newline.
For example, the input might look something like this:
0
 0
  0
  0
 0
0
 0
 0
 0
  0
0
 0
  0
  0

Your task is to number it like a hierarchical outline, using increasing positive integers as the line headers. This would be the output for the example:
1
 1
  1
  2
 2
2
 1
 2
 3
  1
3
 1
  1
  2

Note how every hierarchical indentation level has its own set of increasing numbers, even if they only go up to one.
In the output, there should be no trailing spaces, but there may optionally be a single trailing newline.
Write a full program that takes the input string via stdin or command line, or write a function that takes the string in as an argument. Print the result or return it as a string.
The shortest code in bytes wins.
Examples
If the empty string is input, the empty string should be output.
The next most trivial example is the input
0

which should become
1

Large example - Input:
0
 0
  0
 0
  0
 0
  0
  0
   0
   0
    0
     0
     0
     0
     0
    0
   0
    0
    0
  0
0
 0
  0
 0
  0
  0
  0
  0
  0
  0
  0
  0
  0
  0
  0
   0
    0
     0
  0
   0
0
0
0
 0
  0
   0
    0
     0
      0
      0
     0
    0
   0
  0
 0
  0
  0
   0
   0
0
0

Output:
1
 1
  1
 2
  1
 3
  1
  2
   1
   2
    1
     1
     2
     3
     4
    2
   3
    1
    2
  3
2
 1
  1
 2
  1
  2
  3
  4
  5
  6
  7
  8
  9
  10
  11
   1
    1
     1
  12
   1
3
4
5
 1
  1
   1
    1
     1
      1
      2
     2
    2
   2
  2
 2
  1
  2
   1
   2
6
7

Python 2, 77

S={'0':0}
for w in input().split('\n'):S[w]+=1;S[' '+w]=0;print w[:-1]+`S[w]`

Like Sp3000's answer, but with a dictionary. The dict S stores the current number for each nesting level '0', ' 0', '  0' and so on. For each line in the input, increment the corresponding nesting level, and reset the nesting level one higher to 0.


type in a random mess of capital letters SOMe PEOPle lIkE tO TYpE iN A LoGiCAL MAnNER, WITh CapITals aT tHe bEGiNnIng Of ThE SENtENCE and smaLl LETTErS EVeRYWHErE eLsE. NOT Us. NOt Us. Your joB iS to tAkE A SenTEncE Of A
LL SMAlL LeTTeRS, And rANDOmly ChAnGe sOMe to caPiTAl. ThiS iS a Code gOLF so tHE SmaLleST coDE WIll win.

the input will always be small letters and spaces with punctuation only.

random meaning running the code multiple times will always yield different results.

test cases for this will be hard since it involves random elements.

here is a shitty example with python

https://onlinegdb.com/Hy0_gEEKH

Python 3, 59 bytes

i=input()
while i:print(end={i,i.upper()}.pop()[0]);i=i[1:]

Try it online!

-4 bytes thanks to Chas Brown

Uses set.pop() to randomize.


Print strings without sharing characters Edit: Allowed to reuse whitespaces.

Your task is to write n programs (or functions, or bodies of functions without using parameters or the function names) in the same language. The kth program should output the (cardinal) number k in standard English in lowercase (with an optional trailing newline). So the first program should output one, the second should output two, etc. For a number having two parts, they should be separated by a hyphen like twenty-one.

But no two programs in your submission can share non-whitespace characters or whitespace characters doing useful works. For example, if your first program is just "one", then none of " o n and e can be used again in your other programs.

You can use whitespace characters (spaces, newlines and tabs) in two or more programs, if they only serve as separators or indentation and don't do anything by themselves. So you can't reuse them in the Whitespace language, and you can't use them in strings in more than one program.

You can only use printable ASCII characters, tabs, and newlines (including CR and LF). Every program must contain at least 1 character.

Your score is the sum of 1/program size^1.5. Highest score wins. You can use this Stack Snippet (or this CJam code) to calculate your score:

function updatescore(a){var l=a.value.split("\n"),s=0;for(var i=0;i<l.length;i++){var t=l[i].length;t-=t&&l[i][t-1]=="\r";if(t)s+=Math.pow(t,-1.5);}document.getElementById('result').textContent=s;}
<textarea id="input" placeholder="Put your code here, one per line." style="width:100%;height:150px;box-sizing:border-box" oninput="updatescore(this)" onpropertychange="updatescore(this)"></textarea>
Your score: 0

CJam, 0.24075

Programs

BA1]100cf|
"two"
{hree}`W<7a.-
N)92+_9+_6+_2~+
S(84^I^U$F^X$G^Y$(
's'i'x

Thanks to @user23013 for his suggestion to use ' for six.

Output, length, score, used characters

one    10  0.03162          01       AB         ]    c f         |
two     5  0.08944  "                                     o  tw
three  13  0.02133        -.     7  <        W     `a e h  r    { }
four   15  0.01721      )+    2 6  9      N       _                ~
five   18  0.01309   $ (       4  8    FGI SU XY ^
six     6  0.06804    '                                  i  s  x

Verify the results yourself in the CJam interpreter.


Compute the Resistance of a 4 Band Color Coded Resistor Resistors commonly have color coded bands that are used to identify their resistance in Ohms. In this challenge we'll only consider the normal 4-band, tan, axial-lead resistors. We'll express them as:
xyzt

Where x is the first band for the first significant figure, y is the second band for the second significant figure, z the third band for the multiplier, and t is the fourth band for the tolerance.
Each of xyzt represents a letter that abbreviates the color of the band:
K = Black
N = Brown
R = Red
O = Orange
Y = Yellow
G = Green
B = Blue
V = Violet
A = Gray
W = White
g = Gold
s = Silver
_ = None

So, for example, NKOg is some particular resistor.
The resistance can be calculated with the help of this table:

As the table suggests:

x and y can be any letters except g, s, and _.
z can be anything except _.
We'll restrict t to only be g, s, or _.

(Here's a handy resistance calculator that deals with exact same set of resistors we are.)
The resistance is 10 * x + y times the z multiplier, to a tolerance of the t percentage.

For example, to calculate the resistance of NKOg, we see that:

N means Brown for 1.
K means Black for 0.
O means Orange for 103.
g means Gold for ±5%.

So the resistance is (10*1 + 0)*10^3 → 10000 Ω ±5%.

Challenge
Write a program or function that takes in a 4 character string of the form xyzt and prints or returns the resistance in the form [resistance] Ω ±[tolerance]%.

The resistor may be "upside-down", i.e. in the reverse order tzyx. For example, both NKOg and gOKN should produce 10000 Ω ±5%.
The resistance is always in plain ohms, never kilohms, megohms, etc.
Ω may be replaced with ohms, e.g. 10000 ohms ±5%.
± may be replaced with +/-, e.g. 10000 Ω +/-5%.
Having trailing zeros to the right of a decimal point is fine. (e.g. 10000.0 Ω +/-5%)
You can assume input is always valid (x and y never gs_; z never _; t only gs_).
All 10×10×12×3 = 3600 possible resistors (2×3600 possible inputs) need to be supported even if some color band combinations aren't produced in real life.

The shortest code in bytes wins.
Examples

gOKN → 10000 ohms +/-5%
KKR_ → 0 Ω +/-20%
ggKN → 1 ohms ±5%
ggGO → 3.5 Ω ±5%
ssGO → 0.350 Ω ±10%
GOOs → 53000 ohms +/-10%
YAK_ → 48.0 ohms +/-20%
_WAV → 78000000000 Ω ±20%
gBBB → 66000000.000 ohms ±5%
_RYR → 2400.00 ohms ±20%

Iff you enjoy my challenges, consider checking out Block Building Bot Flocks!

CJam, 59 58 56 50 bytes

r_W%e>"sgKNROYGBVAW"f#2f-~A*+A@#*" Ω ±"@[KA5]='%

Try it online in the CJam interpreter.


I'm not the language you're looking for! Isn't it annoying when you find a piece of code and you don't know what language it was written in? This challenge attempts to somewhat solve this.

Challenge

You will have to write a program that when run in two different languages, will output the string:

This program wasn't written in <language program compiled/interpreted in>, it was built for <other language the program can be run in>!

In the output, language names should have official capitalization. eg: CJam, C++
Neither program should take any input from the user.
When run in both languages, output should be to stdout or equivalent.
There should be no output to stderr in either program.
You may use comments in either language.
Two different versions of the same language count as different languages.

If this is done, the program should output the major version number, and if running on two different minor versions, should report the minor version also.
You should not use prebuilt version functions (this includes variables that have already been evaluated at runtime).

Example output:

Perl and Ruby:

Perl: This program wasn't written in Perl, it was built for Ruby!
Ruby: This program wasn't written in Ruby, it was built for Perl!

Python and C:

Python: This program wasn't written in Python, it was built for C!
C: This program wasn't written in C, it was built for Python!

Python 2 and Python 3:

Python 2: This program wasn't written in Python 2, it was built for Python 3!
Python 3: This program wasn't written in Python 3, it was built for Python 2!

Python 2.4 and Python 2.7:

Python 2.4: This program wasn't written in Python 2.4, it was built for Python 2.7!
Python 2.7: This program wasn't written in Python 2.7, it was built for Python 2.4!

This is code golf so the shortest code in bytes wins.

C89/C99, 171 152 136 114 111 107 105 bytes

Thanks at @Hurkyls, @Qwertiys, @jimmy23013 and @MD XF for your hints.

golfed version:

c;main(){c=-4.5//**/
-4.5;printf("This program wasn't written in C%d, it was built for C%d!",90-c,98+c);}

ungolfed version:

c;

main()
{
    c = -4.5//**/
    -4.5;
    printf("This program wasn't written in C%d, it was built for C%d!",90-c,98+c);
}

Little description:

C versions previous C99 just had the multiline comment like this:

/*foo*/

with C99 the single line comment was introduced. like this:

//foo

so if you compile a line like this:

c =-4.5//**/
-4.5;

the for the c99 compiler compiling-related code would be:

c = -4.5 -4.5;

while the for a c89 compiler relevant code would be:

(as the first / isn't part of a comment and therfor treat as operator)

c = -4.5 / -4.5;


Make a random drum loop Do randomly generated drum loops sound good?

A drum loop is a \$5\times 32\$ matrix \$A\$ of \$1\$s and \$0\$s such that

\$A_{1,1}=A_{1,17}=A_{2,9}=A_{2,25}=1\$,
for each \$i\$, the \$i\$th row has exactly \$f(i)\$ different \$1\$s, where \$ f(1)=3, f(2)=2, f(3)=6, f(4)=8, f(5)=5\$,
for each \$j\equiv 1\bmod 4\$, the \$j\$th column has exactly one \$1\$, and
for each \$j\not\equiv 1\bmod 4\$, the \$j\$th column has at most one \$1\$.

Here, the rows provide instructions for each of five drums, with each column representing a beat. In particular, the first row corresponds to a kick, while second row corresponds to a snare.

Write the shortest code that draws a matrix uniformly from the set of drum loops.

Feel free to use your code to draw a random drum loop, implement the drum loop on this website, and then post a link to your creation in your post. (Note that we only use the first 5 rows of this online beat maker.)

Edit 1: To be clear, we are using 1-based indexing: the row indices are \$\{1,\ldots,5\}\$ and the column indices are \$\{1,\ldots,32\}\$.

Edit 2: Judging by the current submissions, the answer to my original question appears to be "yes": randomly generated drum loops do sound good. Here are links to the current examples:

Random drum loop by @Arnauld
Random drum loop by @tom
Random drum loop by @KevinCruijssen

C (gcc), 413 394 389 379 378 360 342 327 307 299 298 293 bytes

#define F;for(b[8]=b[v=24]=3,n=0;n
#define B,b[n]==
a[]=L"14444448888888822222",b[32],r[24],n,k,j,t=20,v;main(i){srand(&i)F<v;*b=b[16]=1)r[n++]=n/3-~n F<4;a[k]=a[t])b[i=4+n++*8]=a[k=rand()%t--]-48 F<16;r[j]=r[v])b[r[j=rand()%v--]]=a[n++]-48 F<32;n++)printf("%d%d%d%d%d\n"B 1 B 3 B 4 B 8 B 2);}

Try it online!

#define F;for(b[8]=b[v=24]=3,n=0;n
#define B,b[n]==
a[]=L"14444448888888822222",b[32],r[24],n,k,j,t=20,v;main(i){srand(time(0))F<v;*b=b[16]=1)r[n++]=n/3-~n F<4;a[k]=a[t])b[i=4+n++*8]=a[k=rand()%t--]-48 F<16;r[j]=r[v])b[r[j=rand()%v--]]=a[n++]-48 F<32;n++)printf("%d%d%d%d%d\n"B 1 B 3 B 4 B 8 B 2);}

try it online -earlier algorithm 307 bytes

Many thanks to @ceilingcat for more byte savings (360 to 342 - then 342 to 328 and 327 to 307 - then modified algorithm from 328 to 299 and 298 to 293).

Compiles ok without #include<stdio.h> using the -w compiler flag, thanks to @Arnaud for pointing this out.

As written it generates a fresh sequence each time. If we are allowed manual intervention of a new number in srand to generate a different drum sequence with say srand(6); then we can save 16 bytes.

Thanks to @Arnaud who made asked the question about generating the transpose matrix, which is what this program does. Thanks also for suggesting the change from int to char for a[20] that saves 15 bytes. Also thanks for @Post Rock Garf Hunter who figured out a way to remove white space near the Bs and then saved more bytes fixing up the #defines so that F is included in R. `#define' tokens often seem to need whitespace so they are cleanly identified.

This code works on tio.run, but elsewhere may need to include time.h.

How the program works

logic:

setup
4 sounds are fixed (at 1,9,17,25)
remaining sounds to be distributed randomly are in a[20]
b[32] holds output - one cell for each beat (1 to 32, but in C of course 0 to 31)
4 of the b cells must have something (at 5,13,21,29)
remaining sounds randomly scattered to empty cells
r[24] holds list of empty cells (2,3,4, 6,7,8 etc. in C 0,1,2, 4,5,6 etc.)
execute
put in 4 fixed sounds
choose random sound from a to put in each of 4 cells with sounds
choose random cell from r to put in random sound from remaining a sounds (simplification to algorithm is possible here by putting remaining sounds one by one from 1 to 16 (or 0 to 15) in a random cell, but this gave more bytes..., but now thanks to @ceilingcat this is now smaller see tio.run link for details)
print result

this is a long version of the code without the #define and other space savers to show the logic, but with small differences e.g. in final version a is char * not int *

#include<stdio.h>
#include<stdlib.h>
int main()
{
  int a[20]={1,4,4,4,4,4,4,8,8,8,8,8,8,8,8,2,2,2,2,2},
    b[32]={},r[24],n,k,j,t=20,v=24;
  time_t q;srand(time(&q));
//random initialization

  for(n=0;n<24;n++n=0;n<v;n++)r[n]=n+n/3+1;
// set up r with list of cells that don't definitely have sound 012,456 etc.

  b[0]=b[16]=1;b[8]=b[24]=16;
//put in fixed sounds

  for (n=0;n<4;n++)
    {k=rand()%t--;b[4+n*8]=a[k];a[k]=a[t];}
//choose a random sound from a to put in each of 4 cells that must  have sound
// each sound selected is then replaced by the sound at the end of the list
// and the length of the list is reduced by one

  for (n=0;n<16;n++)
    {k=rand()%t--;j=rand()%v--;b[r[j]]=a[k];a[k]=a[t];r[j]=r[v];}
// random cell from remaining `r` cells and random sound are selected
// again after selection from list final item replaces selected and length
// reduced by one

  for (n=0;n<32;n++)
    {printf("%d%d%d%d%d\n",(b[n]==1),(b[n]==16),(b[n]==4),(b[n]==8),(b[n]==2));}
 // print out 0 and 1 from logical tests to print transpose matrix
  return 0;
}