Organize Your Christmas Party! Christmas is coming up, and this year you have been charged with organizing your family's christmas get-together. You have a list of foods you want be there, but before you assign foods to people, you need to know who's coming. So...

Challenge

Given an input of relative's names separated by commas or whatever (note that the names may have spaces in them, e.g. "Aunt Gertrude") and a list of meals including turkey, divide the meals among them equally, but saving the turkey and any extra for yourself, because you don't want to be unfair. In other words, if 6 people are coming and there are 10 meals, you have to do the turkey and 3 others, because 6 goes into 9 once, leaving 4 for you.
Input will never have more people than meals.

Full list of possible dishes  (Taken from Wikipedia)

Apple Cider
Boiled Custard
Candy canes
Champagne
Chocolate fudge
Christmas cookies
Cranberry sauce
Eggnog
Fish
Fruitcake
Gingerbread Men
Christmas ham
Hot buttered rum
Hot chocolate
Mashed potato
Mixed nuts
Oyster stew
Persimmon pudding
Apple pie
Pecan pie
Pumpkin pie
Sparkling cider
Stuffing
Sweet potato pie
Sweet potato casserole with marshmallow
Russian tea cakes
Tom and Jerry
Turkey

Here is a formatted version if you prefer:
["Apple Cider","Boiled Custard","Candy canes","Champagne","Chocolate fudge","Christmas cookies","Cranberry Sauce","Eggnog","Fish","Fruitcake","Gingerbread Men","Christmas Ham","Hot buttered rum","Hot chocolate","Mashed potato","Mixed nuts","Oyster stew","Persimmon pudding","Apple pie","Pecan pie","Pumpkin pie","Sparkling cider","Stuffing","Sweet potato pie","Sweet potato casserole with marshmallow","Russian tea cakes","Tom and Jerry","Turkey"]

Name format

Relative's names will take any of the following formats

Aunt x
Uncle x
Creepy Uncle x
Grandpa x
Grandma x
Cousin x
Mother-in-law x
Father-in-law x
Papa x
Nana x
x
x can be any 20 char or less combination of upper/lower case letters

I/O

Input can be taken in any reasonable, convenient format, but I will assume list if not otherwise specified: [relative a,b,c],[food x,y,z]

Output can also be in any reasonable convenient format, I personally prefer a list of lists You do not need to output the turkey or extra meals

Examples

["Aunt Gertrude", "Cousin Sally", "Grandpa Joe", "Creepy Uncle Rick"],["Sparkling Cider", "Pumpkin Pie", "Pecan Pie", "Oyster Stew", "Chocolate Fudge", "Turkey"] -> [["Aunt Gertrude","Sparkling Cider"],["Cousin Sally", "Pumpkin Pie"],["Grandpa Joe","Pecan Pie"],["Creepy Uncle Rick","Oyster Stew"]]

["Aunt getoFFmyLAWn","Grandpa Lipbalm","Cousin onlyplaysroblox","Papa losthisjob"],["Pumpkin pie","Sparkling cider","Stuffing","Sweet potato pie","Sweet potato casserole with marshmallow","Russian tea cakes","Tom and Jerry"] -> [['Aunt getoFFmyLAWn', 'Pumpkin pie'], ['Grandpa Lipbalm', 'Sparkling cider'], ['Cousin onlyplaysroblox', 'Stuffing'], ['Papa losthisjob', 'Sweet potato pie']]

As christmas is almost here, you don't have time to be planning more than needed, so use those code-golf skills and program up some lists!

Notes

No standard loopholes
If you have only a function, please provide code to call it as well
Please provide an explanation
Smallest byte count ~ 2-3 days after Christmas wins!

Jelly, 17 bytes

I went off-piste with the meals in my example without realising! It shouldn't matter I think, and looks tastier to my British eyes.

ḟ“Øẇ½»W¤s⁹L‘¤ṖZṖż

A dyadic link taking a list of foods (lists of characters) on the left and people (also lists of characters) on the right which returns a list containing a list per person containing a list of characters (their name) and a list of foods (each a list of characters).

e.g. (using "..." to represent a list of characters):

left = ["Champagne", "Turkey", "Stuffing", "Port", "Roast Potatoes", "Brussel Sprouts", "Parsnips", "Pigs In Blankets", "Gravy", "Steamed Vegetables", "Cheese Plate", "Christmas Pudding"]
right = ["Aunt Gertrude", "Cousin Sally", "Grandpa Joe"]

output = [[["Champagne", "Brussel Sprouts"],"Aunt Gertrude"],[["Stuffing", "Parsnips"],"Cousin Sally"],[["Port", "Pigs In Blankets"],"Grandpa Joe"]]

(leaving us with Turkey, Roast Potatoes, Gravy, Steamed Vegetables, and Christmas Pudding.)

Try it online! (The footer calls the dyadic link and then pretty prints the result)

How?

ḟ“Øẇ½»W¤s⁹L‘¤ṖZṖż - Link: foods, people
            ¤     - nilad followed by link(s) as a nilad:
         ⁹        -   chain's right argument, people
          L       -   length
           ‘      -   increment (add yourself to the cook count)
       ¤          - nilad followed by link(s) as a nilad:
 “Øẇ½»            -   compressed string = list of characters, ['T','u','r','k','e','y']
      W           -   wrap in a list                          [['T','u','r','k','e','y']]
ḟ                 - filter discard (from foods) if exists in that list (we cook any Turkey)
        s         - split (the resulting list of foods) into chunks (of number of cooks)
             Ṗ    - pop off the excess
              Z   - transpose to a list of fair shares
               Ṗ  - pop off our share
                ż - zip with people names (to provide the allocations)


Create an object whose state changes on assignment I find it deeply weird that this is possible in Ruby (I won't immediately say how):

obj = #code redacted

print obj.state # Some value.

LValue = obj

print obj.state # Different value!

Your challenge is to create code roughly of this form. Create an object and assign it to a variable. It should have some defined attribute (or deterministic, idempotent method) like state above, that changes after the object is assigned to a new identifier (LValue above), even if you still use the old identifier (obj above) to refer to it.

Edit for emphasis: state or the equivalent must be idempotent, so creating an accessor that modifies the value, or for any other reason returns different results when called several times in a row, isn't a valid solution. Or, more simply, it has to be the assignment that changes the state.

Any language with assignment is eligible, although there are probably some where there's no fully legitimate solution. I'll post my Ruby answer if nobody else gets it after a few days, and accept highest-voted answers on a rolling basis.

C++

This is trivial using the right tools.

#include <iostream>

using namespace std;

class Obj {
public:
   int state;

   Obj& operator= (Obj& foo) {
      foo.state++;
      this->state = foo.state - 2;
      return *this;
   }
};

int main() {
   Obj a, b, c, d;
   a.state = 3;
   b.state = 4;

   cout << a.state << " " << b.state << "\n";

   c = a;
   d = b;

   cout << a.state << " " << b.state << " " << c.state << " " << d.state << "\n";

   return 0;
}

Output:

3 4
4 5 2 3


How many bytes is it This time, we want render the count of bytes in a human readable way to user. Let's write a program (a full one or a function or other acceptable formats) to do this.

Input

An non-negative integer, in range \$0\leq n<2^{31}\$, which means n bytes.

Output

A string, the human friendly representation of n bytes.

Convention

If n is less than 1000, add B after n and output; otherwise...
Convert to a number less than 1000, plus one of these units: KiB, MiB, GiB; round the number to 3 figures
For more details of conversion, check out these testcases

Testcases

0 -> 0B
1 -> 1B
42 -> 42B
999 -> 999B
1000 -> 0.98KiB
1024 -> 1.00KiB
2018 -> 1.97KiB
10086 -> 9.85KiB
100010 -> 97.7KiB
456789 -> 446KiB
20080705 -> 19.2MiB
954437177 -> 910MiB
1084587701 -> 1.01GiB
1207959551 -> 1.12GiB
2147483647 -> 2.00GiB

Rules

This is code-golf, so shortest bytes win
Standard loopholes forbidden
You should output exactly the same to the testcase:

No white space or other symbols between number and units;
Use KiB, not KB, kib, or kb;
Leading or trailing white spaces are optional

JavaScript (ES6), 78 74 bytes

f=(n,i)=>n<999.5?i?n.toPrecision(n<1^3)+' KMG'[i]+'iB':n+'B':f(n/1024,-~i)
<input oninput=o.textContent=f(this.value)><pre id=o>

Edit: Saved 4 bytes thanks to @Arnauld.


I see your BIDMAS and raise you a BADMIS I see your BIDMAS and raise you a BADMIS

Challenge

Given a set of numbers with operators between them: "5 + 4 * 9 / 3 - 8", return all the possible results of the expression for every permutation of the order of basic operations: [/, *, +, -].

Rules

Standard loopholes forbidden
I/O

Input must be ordered with infix operations, but however that is easiest (string or array)
You are not required to support unary operators (e.g. "-3 * 8 / +2")
Integers can be replaced by floats for languages that implicitly parse type (e.g. 45 ⟶ 45.0)
Output must be all of the possible results of the expression, no specified format or order

All of the inputs are valid (e.g. do not need to deal with "7 / 3 + *"). This also means that you will never need to divide by zero.
Operators are all left-associative so "20 / 4 / 2" = "(20 / 4) / 2"
This is Code Golf so fewest number of bytes wins

Test Cases (With explanation)

"2 + 3 * 4" = [14, 20]

2 + (3 * 4)  ⟶  2 + (12) ⟶ 14
(2 + 3) * 4 ⟶ (5) * 4 ⟶ 20

"18 / 3 * 2 - 1" = [11, 2, 6]

((18 / 3) * 2) - 1 ⟶ ((6) * 2) - 1 ⟶ (12) - 1 ⟶ 11
(18 / 3) * (2 - 1) ⟶ (6) * (1) ⟶ 6
(18 / (3 * 2)) - 1 ⟶ (18 / (6)) - 1 ⟶ (3) - 1 ⟶ 2
18 / (3 * (2 - 1)) ⟶ 18 / (3 * (1)) ⟶ 6
18 / ((3 * 2) - 1) ⟶ 18 / 5 ⟶ 3.6

Test Cases (Without explanation)

"45 / 8 + 19 / 45 * 3" = [6.891666666666667, 18.141666666666666, 0.11111111111111113, 0.01234567901234568, 0.01234567901234568, 5.765740740740741]
"2 + 6 * 7 * 2 + 6 / 4" = [112 196 23 87.5]

JavaScript (V8),  118  112 bytes

Prints the results.

f=(s,x='',y=x,o='+-*/')=>[...o].map(v=>f(s.split(v).join(x+v+y),x+')',y+'(',o.replace(v,'')))|print(eval(y+s+x))

Try it online!

Or see the deduplicated results.


Implement arbitrary precision division Implement a function divide(int a, int b, int c) that prints the base 10 value of a/b. without using any floating point math nor BigInteger/BigDecimal or equivalent libraries whatsoever. At least c accurate characters within the set of 0123456789. must be printed, except for the (possible) exception in point 4 below.

a and b may be any 32 bit integers. Update: If, for golfing purposes, you would like to have input be 64 bit primitives that is okay, but you do not need to support the whole 64 bit range of data.
You do not need to check that c is positive (though hopefully your program does not crash) if it's not.
The minimum supported upper bound for c is 500. It is okay if your program does not support values of c above 500, but it is also okay if it does.
For numbers that divide evenly, it is your choice whether to print extra zeroes (based on the value of c) or nothing.
You do not need to be able to use the function to do any further tasks with the quotient, the only goal is printing.
For numbers between -1 and 1, it is your choice whether to print a leading 0. However, this is the only scenario where printing a leading zero is acceptable, and you may only print one such zero.
You may use any rounding / floor / ceil logic you prefer for the last decimal place.
For a negative answer, you must print a leading -. This does not count towards c. However, it is your choice if you wish to print  , +, or nothing for a positive answer.
Integer division and integer modulus are both allowed. However, keep in mind that you are restricted to primitives, unless you choose to implement your own BigInteger/BigDecimal library which counts against your code length.
You do not need to handle b being 0, though you can if you want. Your program may enter an infinite loop, or crash, if b=0, and you will not be penalized.
Slight rule change per comment. To make sure the playing field is level, while a and b are guaranteed to be 32 bit integers, you may use 64 bit long integers. If your chosen language goes beyond 64 bit integers as a primitive, you may not at any point use that functionality (pretend it is capped at 64 bits).
Another point that is unclear (it shouldn't change any of the current valid answers, though): while c may be interpreted as either the number of printed characters or the number of spaces after the decimal, your program must use c somehow in a relevant way to decide how many characters to print. In other words, divide(2,3,2) should be much shorter output than divide(2,3,500); it is not okay to print 500 characters without regard to c.
I actually don't care about the name of the function. d is okay for golfing purposes.

Input
Both a function call and reading from stdin are accepted. If you read from stdin, any character not in the set [-0123456789] is considered an argument delimiter.
Output
Characters to stdout as described above.
Example
for divide(2,3,5), all of the following are acceptable outputs:
0.666
0.667
.6666
.6667
 0.666
 0.667
 .6666
 .6667
+0.666
+0.667
+.6666
+.6667

Another example: for divide(371,3,5) the following are all acceptable outputs:
123.6
123.7
 123.6
 123.7
+123.6
+123.7
123.66666
123.66667
 123.66666
 123.66667
+123.66666
+123.66667

And for divide(371,-3,5) the following are are all acceptable:
-123.6
-123.7
-123.66666
-123.66667


Index of the row with most non-zero elements This is a simple one: Take a matrix of integers as input, and output the index of the row with the most non-zero elements. You may assume that there will only be one row with the most non-zero elements.

Test cases:

These are 1-indexed, you may choose if you want 0 or 1-indexed.

1
0
row = 1
---
0  -1
0   0
row = 1
---
1   1   0   0   0
0   0   5   0   0
2   3   0   0   0
0   5   6   2   2
row = 4
---
0   4   1   0
0   0  -6   0
0   1   4  -3
2   0   0   8
0   0   0   0
row = 3

MATL, 6 bytes

!gs&X>

Input is a matrix, with ; as row separator.

Try it online! Or verify all test cases.

Explanation

!     % Transpose
g     % Logical: convert non-zeros to 1
s     % Sum of each column, or sum of row if there's a single row
&X>   % Arg max. Implicitly display


Solve a matrix equation by Jacobi's method (Revised) Mathematical Background

Let A be an N by N matrix of real numbers, b a vector of N real numbers and x a vector N unknown real numbers. A matrix equation is Ax = b.

Jacobi's method is as follows: decompose A = D + R, where D is the matrix of diagonals, and R is the remaining entries.

if you make an initial guess solution x0,  an improved solution is x1 = inverse(D) * (b - Rx) where all multiplications are matrix-vector multiplication and inverse(D) is the matrix inverse.

Problem Specification

Input: Your complete program should accept as input the following data: the matrix A, the vector b, an initial guess x0, and an 'error' number e.
Output: The program must output the minimum number of iterations such that the latest solution differs by the true solution, by at most e. This means each component of the vectors in absolute magnitude differ by at most e. You must use Jacobi's method for iterations.

How the data is inputted is your choice; it could be your own syntax on a command line, you could take input from a file, whatever you choose.

How the data is outputted is your choice; it can be written to a file, displayed in the command line, written as ASCII art, anything, as long as it is readable by a human.

Further Details

You are not given the true solution: how you calculate the true solution is up to you entirely. You may solve it by Cramer's rule for example, or computing an inverse directly. What matters is that you have a true solution to be able to compare to iterations.

Precision is an issue; some people's 'exact solutions' for comparison may differ. For the purposes of this code golf the exact solution must be true to 10 decimal places.

To be absolutely clear, if even one component of your present iteration solution exceeds its corresponding component in the true solution by e, then you need to keep iterating.

The upper limit to N varies based on what hardware you're using and how much time you're willing to spend running the program. For the purposes of this code golf, assume maximum N = 50.

Preconditions

When your program is called, you are free to assume that the following holds at all times:

N > 1 and N < 51, i.e. you will never be given a scalar equation, always a matrix equation.
All inputs are over the field of real numbers, and will never be complex.
The matrix A is always such that the method converges to the true solution, such that you can always find a number of iterations to minimise the error (as defined above) below or equal to e.
A is never the zero matrix or the identity matrix, i.e. there is one solution.

Test Cases

A = ((9, -2), (1, 3)), b = (3,4), x0 = (1,1), e = 0.04

The true solution is (0.586, 1.138). The first iteration gives x1 = (5/9, 1), differing by more than 0.04 from the true solution, by at least one component. Taking another iteration we find, x2 = (0.555, 1.148) which differs by less than 0.04 from (0.586, 1.138). Thus the output is

2

A = ((2, 3), (1, 4)), b = (2, -1), x0 = (2.7, -0.7), e = 1.0

In this case the true solution is (2.2, -0.8) and the initial guess x0 already has error less than e = 1.0, thus we output 0. That is, whenever you do not need to make an iteration, you simply output

0

Submission Assessment

This is code golf, with all standard loopholes hereby disallowed. The shortest correct complete program (or function), i.e. lowest number of bytes wins. It is discouraged to use things like Mathematica which wrap up a lot of the necessary steps into one function, but use any language you want.

APL (Dyalog), 78 68 65 49 bytes

Exactly the type of problem APL was created for.
-3 thanks to Erik the Outgolfer. -11 thanks to ngn.
Anonymous infix function. Takes A b e as left argument and x as right argument. Prints result to STDOUT as vertical unary using 1 as tally marks, followed by 0 as punctuation. This means that even a 0-result can be seen, being no 1s before the 0.
{⎕←∨/e<|⍵-b⌹⊃A b e←⍺:⍺∇D+.×b-⍵+.×⍨A-⌹D←⌹A×=/¨⍳⍴A}

Try it online!
Explanation in reading order
Notice how the code reads very similarly to the problem specification:
{…} on the given A, b, and e, and and the given x,
 ⎕← print
 ∨/ whether there is any truth in the statement that
 e< e is smaller than
 |⍵- the absolute value of x minus
 b⌹ b matrix-divided by
 ⊃A b e the first of A, b, and e (i.e. A)
 ←⍺ which are the left argument
 : and if so,
  ⍺∇ recurse on
  D+.× D matrix-times
  b- b minus
  ⍵+.×⍨ x, matrix multiplied by
  A- A minus
  ⌹D the inverse of D (the remaining entries)
  ← where D is
  A× A where
  =/¨ there are equal
  ⍳ coordinates for
  ⍴A the shape of A (i.e. the diagonal)
Step-by-step explanation
The actual order of execution right-to-left:
{…} anonymous function where ⍺ is A b e and ⍵ is x:
 A b c←⍺ split left argument into A, b, and e
 ⊃ pick the first (A)
 b⌹ matrix division with b (gives true value of x)
 ⍵- differences between current values of x and those
 | absolute values
 e< acceptable error less than those?
 ∨/ true for any? (lit. OR reduction)
 ⎕← print that Boolean to STDOUT
 : and if so:
  ⍴A shape of A
  ⍳ matrix of that shape where each cell is its own coordinates
  =/¨ for each cell, is the vertical  and horizontal coordinates equal? (diagonal)
  A× multiply the cells of A with the that (extracts diagonal)
  ⌹ matrix inverse
  D← store in D (for Diagonal)
  ⌹ inverse (back to normal)
  A- subtract from A
  ⍵+.×⍨ matrix multiply (same thing as dot product, hence the .) that with x
  b- subtract that from b
  D+.× matrix product of D and that
  ⍺∇ apply this function with given A b e and that as new value of x


Shortest program that throws StackOverflow Error Write a program that throws a StackOverflow Error or the equivalent in the language used. For example, in java, the program should throw java.lang.StackOverflowError.

You are not allowed to define a function that calls itself or a new class(except the one containing main in java). It should use the classes of the selected programming language.

And it should not throw the error explicitly.

Befunge, 1

I don't know Befunge, but...

1

from Stack overflow code golf


Recover boolean cells from windowed sums Background
In Minesweeper, you will often encounter a horizontal or vertical wall of one's and two's (not yet revealed cells are marked as ?):
... 1 1 1 1 2 2 2 1 2 1 1 ...
... ? ? ? ? ? ? ? ? ? ? ? ...
... A B C D E F G H ...

It is equivalent to a problem of recovering zeros and ones in a boolean array when only windowed sums of size 3 are given, where a zero means a safe cell and a one means a mine:
A + B + C = 1
B + C + D = 1
C + D + E = 1
D + E + F = 2
E + F + G = 2
F + G + H = 2
...

If you focus on CDEF, you can logically determine that C should be zero and F should be one. If C were 1, it would mean D + E = 0, which is impossible due to D + E + F = 2. (Remember that all variables are booleans.)
Challenge
This challenge is an extension of this problem to arbitrary window size.
Given n windowed sums with window size k, recover the n+k-1 boolean cells in the original array as much as possible. It is possible that some cells cannot be determined by the given information; those cells should be marked as such in the output.
The input is the number k and an array (or any ordered collection) of n integers between 0 and k inclusive. The output is an array of zeros, ones, and unknowns, which can be represented as any three distinct values of your choice. You can assume the input is valid, n and k are at least 2, and it has at least one corresponding boolean array.
Standard code-golf rules apply. The shortest code in bytes wins.
Test cases
The output format uses ? for unknown.
k = 2

sums   =  0 0
answer = 0 0 0

sums   =  0 1 2 1 0
answer = 0 0 1 1 0 0

sums   =  1 1 1 1 1 1 1
answer = ? ? ? ? ? ? ? ?

sums   =  1 1 1 1 1 1 0 1 1
answer = 0 1 0 1 0 1 0 0 1 0

sums   =  1 1 2 1 1 1
answer = 1 0 1 1 0 1 0
---

k = 3

sums   =   1 1 1 2 2 2
answer = ? ? 0 ? ? 1 ? ?

sums   =   3 2 1 0 1 2 3
answer = 1 1 1 0 0 0 1 1 1

sums   =   1 1 1 2 2 2 2 1 1
answer = 1 0 0 1 0 1 1 0 1 0 0

sums   =   2 2 2 2 2 2 2 1
answer = 1 ? ? 1 ? ? 1 ? ? 0

sums   =   2 1 2
answer = 1 0 1 0 1
---

k = 4

sums   =    1 2
answer = 0 ? ? ? 1

sums   =    3 2 1
answer = 1 1 ? ? 0 0

sums   =    1 1 2 1 1
answer = 0 0 1 0 0 1 0 0

sums   =    1 1 2 2 2 3
answer = 0 0 ? ? 0 1 ? ? 1

Jelly, 23 18 bytes
L+’Ø.ṗ+⁴\⁼¥Ƈ⁸ZṢ€Q€

Try it online!
-5 bytes thanks to @Jonathan Allan
Uses [0,1] as ?, [0] as 0, and [1] as 1.
How?
Brute force of all possible boolean matrices.
L+’Ø.ṗ+⁴\⁼¥Ƈ⁸ZṢ€Q€
   Ø.               # [0,1]
     ṗ              # Cartesian power:
L+’                 # Length of answer = length of sums + k - 1
           Ƈ          # Filter by:
      +⁴\⁼¥             # n-wise overlapping sums are equal to
            ⁸           # the given sums
             Z      # Get the lists of all possibilities for each position (some binary list)
              Ṣ€    # Sort each possibility list (0s then 1s)
                Q€  # Take unique entries from every possibility ([0],[1],or [0,1])


Latin square compression A Latin square is a square that has no repeated symbols in the rows or columns:.

13420
21304
32041
04213
40132

And as many Sudoku players know, you don't need all of the numbers to deduce the remaining numbers.

Your challenge is to compress a Latin square into as few bytes as possible.  You need to provide one or two program(s) that compresses/decompresses.

Various info:

The numbers used will always be 0..N-1, where N is the length of the square's edge, and N<=25
On decompression, the latin square must be identical to the input.
Your program(s) should be able to (de)compress any latin square (within the maximum square size), not just the ones I've provided.  Compression ratios should be similar as well.
You must actually run the compression and decompressor to obtain your score (No end-of-universe runtimes)

The test cases can be found on github.  Your score is total size of compressed test cases.

EDIT: As of 20:07 on July 7th, I updated the test cases (in order to fix a generation issue).  Please rerun your program on the new test cases.  Thanks Anders Kaseorg.

Python, 1281.375 1268.625 bytes

We encode the Latin square one “decision” at a time, where each decision is of one of these three forms:

which number goes in row i, column j;
in row i, which column the number k goes in;
in column j, which row the number k goes in.

At each step, we make all the logical inferences we can based on previous decisions, then pick the decision with the smallest number of possible choices, which therefore take the smallest number of bits to represent.

The choices are provided by a simple arithmetic decoder (div/mod by the number of choices).  But that leaves some redundancy in the encoding: if k decodes to a square where the product of all the numbers of choices was m, then k + m, k + 2⋅m, k + 3⋅m, … decode to the same square with some leftover state at the end.

We take advantage of this redundancy to avoid explicitly encoding the size of the square.  The decompressor starts by trying to decode a square of size 1.  Whenever the decoder finishes with leftover state, it throws out that result, subtracts m from the original number, increases the size by 1, and tries again.

import numpy as np

class Latin(object):
    def __init__(self, size):
        self.size = size
        self.possible = np.full((size, size, size), True, dtype=bool)
        self.count = np.full((3, size, size), size, dtype=int)
        self.chosen = np.full((3, size, size), -1, dtype=int)

    def decision(self):
        axis, u, v = np.unravel_index(np.where(self.chosen == -1, self.count, self.size).argmin(), self.count.shape)
        if self.chosen[axis, u, v] == -1:
            ws, = np.rollaxis(self.possible, axis)[:, u, v].nonzero()
            return axis, u, v, list(ws)
        else:
            return None, None, None, None

    def choose(self, axis, u, v, w):
        t = [u, v]
        t[axis:axis] = [w]
        i, j, k = t
        assert self.possible[i, j, k]
        assert self.chosen[0, j, k] == self.chosen[1, i, k] == self.chosen[2, i, j] == -1

        self.count[1, :, k] -= self.possible[:, j, k]
        self.count[2, :, j] -= self.possible[:, j, k]
        self.count[0, :, k] -= self.possible[i, :, k]
        self.count[2, i, :] -= self.possible[i, :, k]
        self.count[0, j, :] -= self.possible[i, j, :]
        self.count[1, i, :] -= self.possible[i, j, :]
        self.count[0, j, k] = self.count[1, i, k] = self.count[2, i, j] = 1
        self.possible[i, j, :] = self.possible[i, :, k] = self.possible[:, j, k] = False
        self.possible[i, j, k] = True
        self.chosen[0, j, k] = i
        self.chosen[1, i, k] = j
        self.chosen[2, i, j] = k

def encode_sized(size, square):
    square = np.array(square, dtype=int)
    latin = Latin(size)
    chosen = np.array([np.argmax(square[:, :, np.newaxis] == np.arange(size)[np.newaxis, np.newaxis, :], axis=axis) for axis in range(3)])
    num, denom = 0, 1
    while True:
        axis, u, v, ws = latin.decision()
        if axis is None:
            break
        w = chosen[axis, u, v]
        num += ws.index(w)*denom
        denom *= len(ws)
        latin.choose(axis, u, v, w)
    return num

def decode_sized(size, num):
    latin = Latin(size)
    denom = 1
    while True:
        axis, u, v, ws = latin.decision()
        if axis is None:
            break
        if not ws:
            return None, 0
        latin.choose(axis, u, v, ws[num % len(ws)])
        num //= len(ws)
        denom *= len(ws)
    return latin.chosen[2].tolist(), denom

def compress(square):
    size = len(square)
    assert size > 0
    num = encode_sized(size, square)
    while size > 1:
        size -= 1
        square, denom = decode_sized(size, num)
        num += denom
    return '{:b}'.format(num + 1)[1:]

def decompress(bits):
    num = int('1' + bits, 2) - 1
    size = 1
    while True:
        square, denom = decode_sized(size, num)
        num -= denom
        if num < 0:
            return square
        size += 1

total = 0
with open('latin_squares.txt') as f:
    while True:
        square = [list(map(int, l.split(','))) for l in iter(lambda: next(f), '\n')]
        if not square:
            break

        bits = compress(square)
        assert set(bits) <= {'0', '1'}
        assert square == decompress(bits)
        print('Square {}: {} bits'.format(len(square), len(bits)))
        total += len(bits)

print('Total: {} bits = {} bytes'.format(total, total/8.0))

Output:

Square 1: 0 bits
Square 2: 1 bits
Square 3: 3 bits
Square 4: 8 bits
Square 5: 12 bits
Square 6: 29 bits
Square 7: 43 bits
Square 8: 66 bits
Square 9: 94 bits
Square 10: 122 bits
Square 11: 153 bits
Square 12: 198 bits
Square 13: 250 bits
Square 14: 305 bits
Square 15: 363 bits
Square 16: 436 bits
Square 17: 506 bits
Square 18: 584 bits
Square 19: 674 bits
Square 20: 763 bits
Square 21: 877 bits
Square 22: 978 bits
Square 23: 1097 bits
Square 24: 1230 bits
Square 25: 1357 bits
Total: 10149 bits = 1268.625 bytes


"Hello world!", repeating each character n times In your language of choice, write a program that outputs exactly Hello world!. Each character in your program must be repeated n times - you choose n.

For example, you might choose 2 for n. This means that every character used in your source code must be repeated that many times, or 0.

If I were to choose 3 for n, this program would be valid:

ab(b(b(aa)));;;

Rules:

You cannot use any external resources
No user input can be provided
You must output exactly Hello world!, no more, no less. Newlines are the exception, they are optional.
n must be >= 2, to keep things interesting
It's highly discouraged to use comments to accomplish your goal.

Popularity contest, ending in 14 days. Highest score answer at the end wins!


Build a perfect AI for the game 15 In the game 15, two players take turns selecting numbers from 1 to 9 (without choosing any number that either player has already selected). A player wins if he or she has three numbers that add up to 15. If all the numbers have been selected and no combination of either player's adds up to 15, then the game is a tie.

Your task is to build a function that takes the state of a game of 15 (represented in any form you like) and returns which number to move next, which will act as an AI to play the game with another player. You may assume that the position is legal (no player has more than one number more than the other player, and no player already has three numbers that add up to 15).

The AI must be perfect - that is, if it's given a winning position, it must force a win, and if it's given a non-losing position (a position where its opponent does not have a winning strategy), it must not allow its opponent to give it a losing position (which is possible, as 15 is a solved game).

The shortest code wins.

(note: I will accept the currently shortest answer and change it if a shorter answer appears.)

GolfScript (129 86 81 85 75 chars)

{:C[{.`{1$-\{+15\-}+%}:T+/}/10,1>C~+-:^{.{^T&}+C/,2<*T}/5^{1&}$][]*^&0=}:N;

Expected input format: [[int int ...][int int ...]] where the first list is my numbers and the second list is my opponent's numbers. For interactive testing, add ~N to the end of the script and supply a string in that format: e.g.

$ golfscript.rb 15.gs <<<"[[5][2 8]]"
9
$ golfscript.rb 15.gs <<<"[[2][5 8]]"
6

Heuristics:

If I can win this turn, do it
If opponent would win next turn, block
If I can force opponent to a square which prevents them from creating a fork, do it
5 is the only number which can contribute to winning in 4 ways, so grab it if available.
Favour evens over odds

Test framework:

{:Set;[1 5 9 1 6 8 2 4 9 2 5 8 2 6 7 3 4 8 3 5 7 4 5 6]3/{.Set&=},!!}:isWin;
{
    # Mine His
    .isWin{
        "Lost "@`@`++puts
    }{
        # If there are available moves, it's my move.
        # If I won before my move, I've still won after it.
        1$1$+,9<!!{
            # my move
            1$1$[\\]N 2$\+
            # Mine His Mine'
            .isWin!{
                # his move
                10,1>2$2$+-{
                    2$\+1$\
                    # Mine His Mine' Mine' His'
                    fullTest
                    # Mine His Mine'
                }/
            }*;
        }*;;
    }if
}:fullTest;
# I move first
'[][]fullTest'puts [][]fullTest
# He moves first
'[][1]fullTest'puts [][1]fullTest
'[][2]fullTest'puts [][2]fullTest
'[][5]fullTest'puts [][5]fullTest


Even or odd: three player It's a three players game, play with one hand.

At same time, each player show his hand with 0 to 5 fingers extended.

If all player show same kind of (even or odd) number, there is no winner. But else, the player showing different kind the two other win.

 P l a y e r s
A      B      C       Winner

Even   Even   Even    No winner
Odd    Odd    Odd     No winner
Even   Odd    Odd     Player A
Odd    Even   Even    Player A
Even   Odd    Even    Player B
Odd    Even   Odd     Player B
Odd    Odd    Even    Player C
Even   Even   Odd     Player C

The requested tool could use arguments (3 arguments as numeric between 0 and 5) or STDIN (3 values by line, separated by spaces).

There is no need to check input: Irregular input could produce unexpected output.

Arguments or values on line is given from left to right, from player A to player C.

Output must only contain A, B or C (capitalized) or the string no one (in lower case, with a regular space).

Tool may work only once or as a filter on all input lines.

Shortest code win.

APL (34 30)

(1⍳⍨+/∘.=⍨2|⎕)⊃'ABC',⊂'no one'

Explanation:

2|⎕: read a line of input, take the mod-2 of each number (giving a list, i.e. 1 0 1)
∘.=⍨: compare each element in the vector to each element in the vector, giving a matrix
+/: sum the rows of the matrix, giving for each element how many elements it was equal to. If there were two the same and one different, we now have a vector like 2 1 2 where the 1 denotes who was different. If they were all the same, we get 3 3 3.
1⍳⍨: find the position of the 1. If there is no 1, this returns one more than the length of the vector, in this case 4.
⊃'ABC',⊂'no one': display the string at the given index.


Self-displaying image Background

There are self-extracting .ZIP files. Typically they have the extension .EXE (and by executing the file they will be extracted) but when renaming them to .ZIP, you can open the file with some ZIP extracting software.

(This is possible because .EXE files require a certain header but .ZIP files require a certain trailer so it is possible to build a file that both has an .EXE header and a .ZIP trailer.)

Your task:

Create a program that creates "self-displaying" image files:

The program shall take some 64x64 image (at least 4 colors shall be supported) as input and some "combined" file as output
The output file of the program shall be recognized as image file by common image viewers
When opening the output file with the image viewer, the input image shall be displayed
The output file shall also be recognized as executable file for any operating system or computer type

(If a file for an uncommon operating system or computer is produced, it would be nice if an open-source PC emulator exists. However, this is not required.)
When executing the output file, the input image shall also be displayed
It is probable that renaming the file (for example from .PNG to .COM) is necessary
It is not required that the program and it's output file run on the same OS; the program may for example be a Windows program and output files that can be executed on a Commodore C64.

Winning criterion

The program that produces the smallest output file wins
If the size of the output file differs depending on the input image (for example because the program compresses the image), the the largest possible output file created by the program representing a 64x64 image with up to 4 colors counts

By the way

I had the idea for the following programming puzzle when reading this question on StackOverflow.

8086 MS-DOS .COM file / BMP, output file size = 2192 bytes

Encoder

The encoder is written in C. It takes two arguments: Input file and output file. The input file is a 64x64 RAW RGB image (meaning it is simply 4096 RGB triplets). Number of colours is limited to 4, so that the palette can be as short as possible. It is very straight-forward in its doings; it merely builds a palette, packs pixels pairs into bytes and glues it together with pre-made headers and the decoder program.

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

#define MAXPAL      4
#define IMAGESIZE   64 * 64

int main(int argc, char **argv)
{
    FILE *fin, *fout;
    unsigned char *imgdata = malloc(IMAGESIZE * 3), *outdata = calloc(IMAGESIZE / 2, 1);
    unsigned palette[MAXPAL] = {0};
    int pal_size = 0;

    if (!(fin = fopen(argv[1], "rb")))
    {
        fprintf(stderr, "Could not open \"%s\".\n", argv[1]);
        exit(1);
    }

    if (!(fout = fopen(argv[2], "wb")))
    {
        fprintf(stderr, "Could not open \"%s\".\n", argv[2]);
        exit(2);
    }

    fread(imgdata, 1, IMAGESIZE * 3, fin);

    for (int i = 0; i < IMAGESIZE; i++)
    {
        // BMP saves the palette in BGR order
        unsigned col = (imgdata[i * 3] << 16) | (imgdata[i * 3 + 1] << 8) | (imgdata[i * 3 + 2]), palindex;
        int is_in_pal = 0;

        for (int j = 0; j < pal_size; j++)
        {
            if (palette[j] == col)
            {
                palindex = j;
                is_in_pal = 1;
            }
        }

        if (!is_in_pal)
        {
            if (pal_size == MAXPAL)
            {
                fprintf(stderr, "Too many unique colours in input image.\n");
                exit(3);
            }

            palindex = pal_size;
            palette[pal_size++] = col;
        }

        // High nibble is left-most pixel of the pair
        outdata[i / 2] |= (palindex << !(i & 1) * 4);
    }

    char BITMAPFILEHEADER[14] = {
        0x42, 0x4D,                 // "BM" magic marker
        0x90, 0x08, 0x00, 0x00,     // FileSize
        0x00, 0x00,                 // Reserved1
        0x00, 0x00,                 // Reserved2
        0x90, 0x00, 0x00, 0x00      // ImageOffset
    };

    char BITMAPINFOHEADER[40] = {
        0x28, 0x00, 0x00, 0x00,     // StructSize
        0x40, 0x00, 0x00, 0x00,     // ImageWidth
        0x40, 0x00, 0x00, 0x00,     // ImageHeight
        0x01, 0x00,                 // Planes
        0x04, 0x00,                 // BitsPerPixel
        0x00, 0x00, 0x00, 0x00,     // CompressionType (0 = none)
        0x00, 0x00, 0x00, 0x00,     // RawImagDataSize (0 is fine for non-compressed,)
        0x00, 0x00, 0x00, 0x90,     // HorizontalRes
                                    //      db 0, 0, 0
                                    //      nop
        0xEB, 0x1A, 0x90, 0x90,     // VerticalRes
                                    //      jmp Decoder
                                    //      nop
                                    //      nop
        0x04, 0x00, 0x00, 0x00,     // NumPaletteColours
        0x00, 0x00, 0x00, 0x00,     // NumImportantColours (0 = all)
    };

    char DECODER[74] = {
        0xB8, 0x13, 0x00, 0xCD, 0x10, 0xBA, 0x00, 0xA0, 0x8E, 0xC2, 0xBA,
        0xC8, 0x03, 0x31, 0xC0, 0xEE, 0x42, 0xBE, 0x38, 0x01, 0xB1, 0x04,
        0xFD, 0x51, 0xB1, 0x03, 0xAC, 0xD0, 0xE8, 0xD0, 0xE8, 0xEE, 0xE2,
        0xF8, 0x83, 0xC6, 0x07, 0x59, 0xE2, 0xEF, 0xFC, 0xB9, 0x00, 0x08,
        0xBE, 0x90, 0x01, 0xBF, 0xC0, 0x4E, 0xAC, 0xD4, 0x10, 0x86, 0xC4,
        0xAB, 0xF7, 0xC7, 0x3F, 0x00, 0x75, 0x04, 0x81, 0xEF, 0x80, 0x01,
        0xE2, 0xEE, 0x31, 0xC0, 0xCD, 0x16, 0xCD, 0x20,
    };

    fwrite(BITMAPFILEHEADER, 1, 14, fout);
    fwrite(BITMAPINFOHEADER, 1, 40, fout);
    fwrite(palette, 4, 4, fout);
    fwrite(DECODER, 1, 74, fout);

    // BMPs are stored upside-down, because why not
    for (int i = 64; i--; )
        fwrite(outdata + i * 32, 1, 32, fout);

    fclose(fin);
    fclose(fout);
    return 0;
}

Output file

The output file is a BMP file which can be renamed .COM and run in a DOS environment. Upon execution, it will change to video mode 13h and display the image.

A BMP file has a first header BITMAPFILEHEADER, which contains among other things the field ImageOffset, which denotes where in the file the image data begins. After this comes BITMAPINFOHEADER with various de-/encoding information, followed by a palette, if one is used. ImageOffset can have a value that points beyond the end of any headers, allowing us to make a gap for the decoder to reside in. Roughly:

BITMAPFILEHEADER
BITMAPINFOHEADER
PALETTE
<gap>
IMAGE DATA

Another problem is to enter the decoder. BITMAPFILEHEADER and BITMAPINFOHEADER can be tinkered with to make sure they are legal machine code (which does not produce a non-recoverable state), but the palette is trickier. We could of course have made the palette artificially longer, and put the machine code there, but I opted to instead use the fields biXPelsPerMeter and biYPelsPerMeter, the former to make the code aligned properly, and the latter to jump into the decoder. These fields will of course then have garbage in them, but any image viewer I have tested with displays the image fine. Printing it might produce peculiar results, though.

It is, as far as I know, standard-compliant.

One could make a shorter file if the JMP instruction was put in one of the reserved fields in BITMAPFILEHEADER. This would allow us to store the image height as -64 instead of 64, which in the magical wonderland of BMP files means that the image data is stored the right way up, which in turn would allow for a simplified decoder.

Decoder

No particular tricks in the decoder. The palette is populated by the encoder, and shown here with dummy-values. It could be slightly shorter if it did not return to DOS upon a keypress, but it was not fun testing without that. If you feel you must, you can replace the last three instructions with jmp $ to save a few bytes. (Don't forget to update the file headers if you do!)

BMP stores palettes as BGR (not RGB) triplets, padded with zeroes. This makes setting up the VGA palette more annoying than usual. The fact that BMPs are stored upside-down only adds to the flavour (and size).

Listed here in NASM style:

Palette:
    db 0, 0, 0, 0
    db 0, 0, 0, 0
    db 0, 0, 0, 0
    db 0, 0, 0, 0

Decoder:
    ; Set screen mode
    mov ax, 0x13
    int 0x10

    mov dx, 0xa000
    mov es, dx

    ; Prepare to set palette
    mov dx, 0x3c8
    xor ax, ax
    out dx, al

    inc dx
    mov si, Palette + 2
    mov cl, 4
    std
pal_loop:
    push cx
    mov cl, 3
pal_inner:
    lodsb
    shr al, 1
    shr al, 1
    out dx, al
    loop pal_inner

    add si, 7
    pop cx
    loop pal_loop
    cld

    ; Copy image data to video memory
    mov cx, 64 * 64 / 2
    mov si, ImageData
    mov di, 20160
img_loop:
    lodsb
    aam 16
    xchg al, ah
    stosw
    test di, 63
    jnz skip
    sub di, 384
skip:
    loop img_loop

    ; Eat a keypress
    xor ax, ax
    int 0x16

    ; Return to DOS
    int 0x20

ImageData:


How to simplify ternary expressions in Javascript I have an expression that could be expressed as either of :

a += (A ? B ? x : C ? y : D : D);

a += (A && B ? x : A && C ? y : D);

where A,B,C are expressions of 5-10 bytes each, and x and y are single character literals (3-4 bytes). D is another chain of ternaries (without the branching problem).

I'm getting stuck trying to eliminate the duplication of D or A. If I was using if, it would be something like this:

if (A)
    if (B)
        x
    else if (C)
        y
else D

Obviously I could do ((z=A) && B ? x : z && C ? y : D)...but any other more creative suggestions?

The actual code looks something like:

if (r%4<2&&r>3&&c<22&&c>1)
    if ((i-r)%8==6)
        '\\'
    else if ((i+r)%8==1)
        '/'
else

D is something like:

(i+r) % 8 == 3 ? '/' :
    (c-r+16) % 8 == 4 ? '\\' :

If you know that x and y cannot contain falsy values, as your code examples suggest, you can do the following to eliminate duplicate evaluation of A or D:

a += A && (B && x || C && y) || D;

Demo code and test cases in the following snippet:

// return x
test(1,1,0); // A and B
test(1,1,1); // A and B (and C)

// return y
test(1,0,1); // A and C

// return D
test(0,0,0); //
test(0,0,1); // C
test(0,1,0); // B
test(0,1,1); // B and C
test(1,0,0); // A

function test(A, B, C) {
  var x = 'x', y = 'y', D = 'D';
  a = A && (B && x || C && y) || D;
  expected = (A && B ? x : A && C ? y : D);
  var ws = ' ';
  console.log(
    [
      A && 'A' || ws,
      B && 'B' || ws,
      C && 'C' || ws
    ].join(ws),
    ' ==> a = ' + a,
    a === expected ?
      'Passed' :
      'Failed, expected ' + expected
  );
}

Otherwise, if falsy values are possible, you could do this:

a += [D, x, y][A && (B && 1 || C && 2) || 0];

Demo code and test cases in the following snippet:

// return x
test(1,1,0); // A and B
test(1,1,1); // A and B (and C)

// return y
test(1,0,1); // A and C

// return D
test(0,0,0); //
test(0,0,1); // C
test(0,1,0); // B
test(0,1,1); // B and C
test(1,0,0); // A

function test(A, B, C) {
  var x = false, y = 0, D = '';
  A = !!A; B = !!B; C = !!C;
  a = [D, x, y][A && (B && 1 || C && 2) || 0];
  expected = (A && B ? x : A && C ? y : D);
  var ws = ' ';
  console.log(
    [
      A && 'A' || ws,
      B && 'B' || ws,
      C && 'C' || ws
    ].join(ws),
    ' ==> a = ' + xyD(a, x, y, D),
    a === expected ?
      'Passed' :
      'Failed, expected ' + xyD(expected, x, y, D)
  );
}

function xyD(result, x, y, D) {
  return result === x ? 'x' :
         result === y ? 'y' :
         result === D ? 'D' : '<error>' ;
}


Count the words in a text and display them The code should take input a text (not mandatory can be anything file, stdin, string for JavaScript, etc):

This is a text and a number: 31.

The output should contain the words with their number of occurrence, sorted by the number of occurrences in descending order:

a:2
and:1
is:1
number:1
This:1
text:1
31:1

Notice that 31 is a word, so a word is anything alpha-numeric, number are not acting as separators so for example 0xAF qualifies as a word. Separators will be anything that is not alpha-numeric including .(dot) and -(hyphen) thus i.e. or pick-me-up would result in 2 respectively 3 words. Should be case sensitive, This and this would be two different words,  ' would also be separator so wouldnand t will be 2 different words from wouldn't.

Write the shortest code in your language of choice.

Shortest correct answer so far:

grep and coreutils - 42 bytes

grep and coreutils  44  42

grep -io '[a-z0-9]*'|sort|uniq -c|sort -nr

Test:

printf "This is a text and a number: 31." |
grep -io '[a-z0-9]*'|sort|uniq -c|sort -nr

Results in:

  2 a
  1 This
  1 text
  1 number
  1 is
  1 and
  1 31

Update

Use case-insensitive option and shorter regex. Thanks Tomas.


Find every digit from the largest column Here's a relatively simple challenge for you:

Given a list of positive integers:

Line them up in a grid, and sum each column. For example, if the input was [123, 7, 49, 681], the grid would look like this:

 1  2  3
 7
 4  9
 6  8  1

And the sum of each column would be [18, 19, 4]:

 1  2  3
 7
 4  9
 6  8  1
 --------
 18 19 4

Find the maximum of these sums, which in this case would be 19, and then
Output every digit that is at the same index as this maximum column. In this case, that would be

2
9
8

You do not have to output these numbers in any particular order.
Note that there are only three outputs, even though we had 4 inputs. In the case of a tie, pick the earliest index. For example, if the input was [25, 223, 302], your grid is:

2  5
2  2  3
3  0  2
-------
7  7  5

You should output

2
2
3

You can print these numbers in any format you like. List format, newline separated, space separated, etc. You may not take the input as a 2D array of digits, e.g.

[[1, 2, 3],
[7],
[4, 9],
[6, 8, 1]

But other than that, you can take input as a list of strings, a list of digits, or any other reasonable format.

You may also assume that all inputs will be valid and contain at least two numbers.

As usual, the shortest answer in bytes wins!

Test IO:

#Input                      #Output
[1, 11, 111, 1111]      --> [1, 1, 1, 1]
[1, 12, 123]            --> [2, 2]
[987654321, 111]        --> [9, 1]
[111, 123456789]        --> [9]
[4, 8, 15, 16, 23, 42]  --> [4, 8, 1, 1, 2, 4]
[4, 8, 12, 26, 27, 38]  --> [2, 6, 7, 8]
[24, 53]                --> [2, 5]
[12, 304, 506]          --> [4, 6]
[30, 285, 121]          --> [0, 8, 2]

Haskell, 63 bytes

import Data.Lists
argmax sum.transpose.map(map(read.pure).show)

Usage example: argmax sum.transpose.map(map(read.pure).show) $ [12,304,506] -> [4,6].

How it works:

                     map                       -- for each number
                         map(read.pure).show   -- turn into list of digits
           transpose                           -- transpose the list of list
argmax sum                                     -- find the element with the
                                               -- largest sum


Pretty Printing Parentheses The worst part about long lines or code or math equations are the parentheses. Nobody wants to read through 2x(3y+4*abs(x^[2*e^x])-5{3(x+y)-5})!
So, the goal of this challenge is to make it at least slightly easier to read these parentheses-filled beasts! For the above math equation, the output should be:
2x (
  3y+4*abs (
    x^ [
      2*e^x
    ]
  )
  -5 {
    3 (
      x+y
    )
    -5
  }
)

A parenthesis is defined as either of these characters: ()[]{}. Indents should each be two spaces, and there should be one space of seperation between the expression and the parenthesis: 2x (, x^ [ as some examples.
I would like to debut the Atomic Code Golf metric in this question. Take out all separators in your code (()[]{}. ; to name some common ones), and then take the length of your program if every reserved word and operator were 1 character long. That is your program's score.  if x**(3.2)==b[3]:print x is 11 points: if|x|**|3|.|2|==|b|3|print|x, or ix*3.2=b3px. Any quick questions about the metric can be posted here; larger questions should be discussed in meta using the link above.
Lowest score wins. Good luck, have fun!

C, 139 137 chars, 67 tokens

i,n;                                                      // 2 tokens
main(c){                                                  // 2 tokens
        while(~(c=getchar()))                             // 5 tokens
                n=strchr("([{}])",c)?                     // 11 tokens
                        n=c%4!=1,                         // 7 tokens
                        i+=n*4-2,                         // 7 tokens
                        printf("\n%*s%c"+n,n?1:i,"",c)    // 15 tokens
                :                                         // 1 token
                        !printf("\n%*s%3$c"+!n*4,i,"",c); // 17 tokens
}

Logic:

Read until EOF (detect it because ~EOF==0).
If parenthesis, check open/close (for c in ")]}", c%4==1), update indentation (i), print with some whitespace.
If not, print the character, possibly prefixed by newline and indentation (n is true after parenthesis).


How many ways can a road cross a river? Imagine a straight river and a road that goes across the river n times through bridges. The road does not loop on itself and is infinitely long. This road would be considered an open meander. An open meander is an open curve, that does not intersect itself and extends infinitely at both ends, which intersects a line n times.

A valid meander may be described entirely by the order of the intersection points it visits.

The number of distinct patterns of intersection with n intersections a meander can be is the nth meandric number. For example, n = 4:

The first few numbers of this sequence are:

1, 1, 1, 2, 3, 8, 14, 42, 81, 262, 538, 1828, 3926, 13820, 30694, 110954...

This is OEIS sequence A005316.

Challenge

Write a program/function that takes a positive integer n as input and prints the nth meandric number.

Specifications

Standard I/O rules apply.
Standard loopholes are forbidden.
Your solution can either be 0-indexed or 1-indexed but please specify which.
This challenge is not about finding the shortest approach in all languages, rather, it is about finding the shortest approach in each language.
Your code will be scored in bytes, usually in the encoding UTF-8, unless specified otherwise.
Built-in functions that compute this sequence are allowed but including a solution that doesn't rely on a built-in is encouraged.
Explanations, even for "practical" languages, are encouraged.

Test cases

These are 0-indexed. Note that you need not handle numbers this big if your language cannot by default.

Input      Output

1          1
2          1
11         1828
14         30694
21         73424650
24         1649008456
31         5969806669034

In a few better formats:

1 2 11 14 21 24 31
1, 2, 11, 14, 21, 24, 31

Python 3, 208 188 187 184 180 177 171 bytes

lambda n:sum(all(i-j&1or(x<a<y)==(x<b<y)for(i,(a,b)),(j,(x,y))in d(enumerate(map(sorted,zip((0,)+p,p+(n,)))),2))for p in d(range(n)))
from itertools import*;d=permutations

Try it online!

Now 1-indexed (was previously 0-indexed but 1-indexing saved a byte due to a lucky quirk regarding the behavior of meanders).

Explanation

This may be the same as the link posted by Jenny_mathy, but I didn't end up reading the paper, so this is just the logic behind my method.

I will be using the following illustration provided on OEIS in order to visualize the results.

Each valid meander may be described entirely by the order of the intersection points it visits. This may be trivially observed in the image; the entry segment is always on the same side (otherwise the number would be double). We can represent the tendency of both the entry and exit segments to their respective infinities by simply adding to every order a point on either side - that is to say, the order (2, 1, 0) would become (-1, 2, 1, 0, 3).

With this in mind, the task is to find the number of orders, or permutations of the range up to n, which do not intersect with themselves. Intersections are only an issue between pairs of points for which the connecting segment lies on the same side. For any two pairs of consecutive points in a permutation whose segments share a side, whether or not they intersect is equivalent to whether one, and only one, of the points of one pair is between the two elements of the other pair. As such, we can determine if an order is valid by whether there are no pairs with one point contained by another pair with a segment on the same side.

Finally, having determined the validity of each permutations, the output of the function comes down to the number of permutations found to be valid.


Michael Crichton's Mousetrap In 1984, Michael Crichton wrote a security program in BASIC that was published in Creative Computing magazine. The program would ask the user to type a phrase of her choice, record the intervals between the keystrokes, then ask her to retype the phrase. If the timings differed by too much, the program would identify the user as an imposter.

Your assignment: create a version of Crichton's program in the language of your choice.

Rules:

Phrases for communicating with the user ("Please type the key phrase," "Please type the key phrase again," etc.) count as one byte each regardless of actual length. This is for user communication only, do not try to hide program code in the strings.
The pass/fail test should be based on the average absolute value of the percentage variances from the original intervals. If the strings don't match, either return fail or allow the user to try again, at your discretion.
The key phrase should not allow a null string. In the event the key phrase is too long for your string datatype, either truncate or disallow and start over, at your discretion.
The sensitivity of the test (the threshold for the pass/fail test) should be adjustable in the source code.
I originally provided a bonus of 20% of total byte count if your source code can be formatted to recognizably resemble a dinosaur. It has been pointed out that this is highly subjective and perhaps more appropriate for a popularity contest, so I have removed this bonus. However I still heartily encourage dinosaur formatting, and if you format your code to look like a dinosaur, you can deduct any purely cosmetic comments, linebreak or whitespace characters from your byte total.
Shortest byte count wins, subject to string-length and dinosaur formatting adjustments.

Note that my specification above does not exactly match the operation of Crichton's code, copies of which may be found online. Follow the spec, don't try to clone the original.

Ruby, 171 167 157 bytes

require'io/console';t=Time;f=->a{loop{x=t.now;STDIN.getch==?\r?break: a<<t.now-x};a};p"Please type the key phrase";f[r=[]];p"Please type the key phrase again";p r.zip(f[[]]).map{|x,y|(1-x/y).abs}.reduce(:+)/r.size>0.2

Outputs true if average variance is above 20%, otherwise outputs false.

Dinosaur ASCII art attempt:

(_=/\
  \ \
   \ \
    \ \              _...---..__
     \ \          .∕` #{t=Time} `\._
      \ \      .∕ #{z='io/console'} `\.
       \ \.__.∕  #{require z;s=STDIN} `\.
        \ #{p'1:';f=->a{loop{x=t.now;#   \.
         s.getch==?\r?break: a<<t.now-x;# `\.
          };a};f[r=[]];p'2:';p r.zip(f[[]])#\
           .map{|x,y|(1-x/y).abs}.reduce(:+)#|
            .fdiv(r.size)>0.2}###########\   \
            `-._    ,___...----...__,   ,__\  \
                |   |_|           |_|   |    \ \
                |___|               |___|      \\/)

Ungolfed:

require 'io/console' # so we can read one char at a time

t = Time

f = ->(a) {
  loop {
    x = t.now # record start time
    break if STDIN.getch == ?\r
    a << t.now - x # push (start time - end time) into array
  }
  a
}

puts "Please type the key phrase"
f[r = []]

puts "Please type the key phrase again"

# interweave timing arrays, compute variances, sum elements
# then divide by array length. Check to see if average
# is greater than threshold (0.2)
p r.zip(f[[]]).map { |x,y| (1-x/y).abs }.reduce(:+) / r.size > 0.2

require 'io/console' could be removed when run in some Ruby REPLs, as the library is already loaded.


Minecraft piston pushing In Minecraft, pistons are blocks that can move other blocks. However, they can only move at most twelve blocks, and won't work at all if any obsidian is in the way. Also, slime blocks are sticky and stick to other blocks, except for obsidian.
Your challenge
Take as input a 5x5 matrix or similar, containing one piston at the bottom, and output the result of the single piston pushing upwards, as 5x6. Input format should have five distinct values for obsidian, slime, other block, piston and empty space, here represented by O, S,B,P, and   respectively.
For example, say you start with
  B
  B
  B
  B
  P

Output the result, if the piston was activated, as 5x6:
  B
  B
  B
  B
  P

Note that the whole configuration with the piston is moved up, as long as it is legal
Testcases:

BBBBB
BBBBB
SSSSS
  S
  P
=>

BBBBB
BBBBB
SSSSS
  S
  P
Because 16 is too many blocks.

 SBS
 SBS
 SBS
 SBS
  P
=>
  B
 SBS
 SBS
 SBS
 SPS
Because slime sticks to blocks, but blocks don't stick to slime.
O
SSSSS
    S
    S
    P
=>
O
SSSSS
    S
    S
    P

Because the obsidian is in the way, the whole thing can't move.
S S S

S S S

S P S
=>

S S S

S S S
  P
S   S

The stray blocks stay where they are.

SSSSS
B S B
B S B
B S B
B P B
=>
SSSSS
B S B
  S
B S B
B P B
B   B
The slime pulls the first two blocks, but the rest stay in place.

 OSO
 OSO
 OSO
 OSO
 OPO
=>
  S
 OSO
 OSO
 OSO
 OPO
 O O
Slime doesn't stick to obsidian, so it's free to move.

Scoring
This is code-golf, the shorter the better!

J, 121 98 bytes
Takes in  POSB as digits 01234. Probably some microgolfs left, these long tacit definitions tend to get confusing. :-)
((0,~*)+0,(*-.))[(]*(2 e.*&,)<14>+/@,@])[(]*@+(2&<@[*[:+/((,-)=i.2)t]*3=[)+*@[*1(t=:|.!.0)])^:_=&1

Try it online!
How it works

=&1 Start a will-be-pushed bitmap with the piston
^:_ expand the bitmap until it does not expand further:
1(t=:|.!.0)] Push the bitmap upwards (non-wrapping, thus !.0)
*@[* but only if a non-space was pushed.
t]*3=[ Extend push of the will-be-pushed slimes towards
((,-)=i.2) all 4 direction
2&<@[*[:+ but only push slimes and blocks.
]*@+…+ OR old bitmap, slime pushes, and up pushes for the next iteration.
[(]*…) Set the final bitmap to 0 if …
(2 e.#~&,) There is an obsidian block in it
<14>+/@,@] or the sum (including the piston) is not less 14.
0,(*-.) Original map * not-pushed bitmap and an empty row above.
(0,~*) Original map * pushed bitmap and an empty row under.
+ Add both maps – as empty spaces are 0 they don't overlap.


Distributive on myself Background
We all know about distributivity, i.e. \$a(b+c) = ab + ac\$. This is a property on 2 different operations, namely addition and multiplication. But indeed, nothing can stop us from studying distributivity of 1 operation. In this challenge, you will be studying a kind of left-distributive operation.
Task
Given a positive integer \$N\$. Consider an operation \$p \star q\$ where \$p, q\in\{0, 1,\dots, N-1\}\$, such that \$ p \star 1 \equiv p + 1 \pmod N\$ and \$p \star (q \star r) = (p \star q) \star (p \star r)\$. In essence, you are making an \$N\times N\$ table. For instance, if \$N = 4\$, a possible \$\star\$ is:
⋆ q 0 1 2 3
p-+---------
0 | 0 1 2 3
1 | 0 2 0 2 ←
2 | 0 3 0 3
3 | 0 0 0 0
      ↑

Note that the marked column satisfies \$ p \star 1 \equiv p + 1 \pmod N\$. In this challenge, we are interested in the marked row. It seems to be periodic, and the challenge is to find its period. The smallest positive period for a sequence \$a_0, \dots , a_{N-1}\$, is defined to be the smallest positive integer \$k\$, such that \$k\$ divides \$N\$, and \$a_i = a_{i + k}\$, for \$i=0..(N-k-1)\$.
However, there may be many possible \$\star\$'s for a given \$N\$, or there may be none. So you need to compute the (smallest positive) periods for all of them.

Task: given a positive integer N, compute all the possible smallest positive periods of 1 ⋆ q. This is code-golf.

Details and clarifications
In the case N = 4, the given table turns out to be the only possible one, so you should output a list (or a set, etc.) consisting only of the number 2. But for N = 3, no operation satisfies all the requirements, so you can output an empty list, or 0, or some falsy value.
The smallest positive period will always be between 1 and \$N\$, if the sequence 1 ⋆ q (0 <= q < N) doesn't repeat at all, it is of period \$N\$.
N will range from 1 to \$2^{32}-1\$. So it is almost kolmogorov-complexity. But note that a formula or recurrence relation of this is unknown.
Test cases
In : N = 1
Out: [1]

In : N = 2
Out: [1]

In : N = 3
Out: []

In : N = 4
Out: [2]

Python 2, 115 bytes

This assumes that a \$\star\$ exists iff \$N\$ is an integer power of 2, including 1. I don't have a proof for it, but it is evident from the first few cases (and @att noted it in comments).
N=input()
f=lambda p,q:f(f(p,q-1),(p+1)%N)if p*q else q
print([i for i in range(1,N)if N%i+f(1,i)<1]+[N])[:N&N-1<1]

Try it online
188 bytes without assuming the power-of-2 condition.
N=input()
f=lambda p,q:f(f(p,q-1),(p+1)%N)if p*q else q
print([i for i in range(1,N)if N%i+f(1,i)<1]+[N])[:all(f(i%N,f(i/N%N,i/N/N%N))==f(f(i%N,i/N%N),f(i%N,i/N/N%N))for i in range(N**3))]

Try it online! (N from 1 to 10, simulates STDIN)
The short, recursive approach is slow since it repeats computation of many entries, so I've made an iterative, memoized approach which is much faster (quadratic in N) and can compute up to N=4096 within 60 seconds on TIO. This reveals a bit of a pattern (two 2s, two 4s, four 8s, four (?) 16s, etc.), but this needs confirmation before working into an answer.
How it Works
The algorithm assumes that \$\star\$ is unique, if it exists (proof below). It uses recursion, setting
\$p\star q=\begin{cases}
q, &p=0 \\
p+1 \mod n, &q=1 \\
(p \star (q-1 \mod n))\star (p+1 \mod n), &\text{otherwise}
\end{cases}\$
The first case (\$p=0\$) is Lemma 1 in the uniqueness proof: \$0\star q=q\$.
The second case (\$q=1\$) is given.
The third case has a simple proof despite its complex self (assuming addition and subtraction are mod \$N\$:
\begin{align*}
&p \star q\\
=&p \star ((q-1)+1) \\
=&p \star ((q-1)\star 1) \\
=&(p \star (q-1))\star(p\star 1) \\
=&(p \star (q-1))\star(p+1)
\end{align*}
This is enough to determine the unique \$\star\$ (Rationalization to myself that the proof was necessary: It shows that the third case will not recurse indefinitely).
The period is the minimum \$i\$ such that \$1\star (i+1) = 1\star 1 = 2\$. If this \$i\$ doesn't divide \$N\$, then it is not a period.
Ungolfed code:
# f(p,q,N) = p⋆q
def f(p,q,N):
    if p==0:
        return q
    if q==1:
        return (p+1)%N
    return f(f(p,(q-1)%N,N),(p+1)%N, N)

def period(N):
    if any(f(p,f(q,r,N),N) != f(f(p,q,N),f(p,r,N),N) for p in range(N) for q in range(N) for r in range(N)):
        # The f does not exist
        return []
    for i in range(1, N):
        # period is i if f(1,i+1)=f(1,1)=2
        if f(1,i+1,N) == 2:
            # might not be divisible, in which case it is not the period
            if N%i:
                return [N]
            return [i]

This could be sped up immensely by memoization utilizing \$ a \star 2 = a \star (1 \star 1) = (a\star 1)\star (a\star 1) = (a+1)\star(a+1) \$ and \$1 \star a = (1\star (a-1))\star 2\$.
Proof of Uniqueness of \$\star\$
For this section, we assume all addition/subtraction is mod \$N\$.
Lemma 1: For all \$a\$, \$0 \star a = a\$
Proof: Induction
Base case: \$a=1\$. Given since \$0\star 1=1\$.
Step: Assume this lemma holds for \$a=k\$. Then \begin{align*}
&0 \star (k + 1)\\
=&  0\star (k\star 1) \\
=& (0\star k)\star (0\star 1) \\
=& k \star 1 \\
=& k+1,
\end{align*}
so this holds for \$a=k+1\$. Since this addition is mod \$N\$, this will "wrap around" back to \$0\$, so it applies for \$a=0\$ too, not just \$a\geq 1\$
Theorem: If an operation \$\star\$ is valid for a given \$N\$, then it the unique \$\star\$ that is valid for that \$N\$.
Proof: We use strong induction to show that, for all \$0\leq a,b\leq N-1\$, \$a\star b\$ is uniquely determined by \$N\$. In addition, for each \$a\$ and \$b\$ in the same set, either (1) \$a\star b=0\$ or (2) \$a<a\star b<N\$

Base case: \$a\star b\$ is uniquely determined and equal to \$0\$ for \$a=N-1\$ and for all \$b\$.
We prove this base case with induction too.

Base case: \$b=1\$. We are given \$a\star 1=a+1\$, so \$(N-1)\star 1=0\$, uniquely determined.
Step: Given \$(N-1)\star b=0\$ for \$b=k\$, then
\begin{align*}
      &(N-1)\star (b+1)\\
      =&(N-1)\star (b\star 1)\\
      =&((N-1)\star b)\star((N-1)\star 1)\\
      =&0\star0 \\
      =&0,
    \end{align*}
where we use Lemma 1 to show \$0\star 0=0\$,
so \$(N-1)\star b\$ is uniquely determiend to be \$0\$.

Assume \$a\star b\$ is uniquely determined and either (1) or (2) hold for all \$k<a\leq N-1\$ and for all \$b\$. Then for \$a=k\$, we will show \$a\star b\$ is uniquely determined and either (1) or (2) hold for all \$b\$, again with induction.

Base case: \$k\star b\$ is uniquely determined and either (1) or (2) hold for \$b=1\$. This is trivial since \$k\star 1=k+1>k\$, so \$k\star 1\$ is unique and (2) holds

Step: Assume \$k\star b\$ is uniquely determined and either (1) or (2) hold for \$b=j\$. Then:
\begin{align*}
      &k\star (b+1)\\
      =&k\star (b\star 1)\\
      =&(k\star b)\star(k\star 1)\\
      =&(k\star b)\star(k+1)
    \end{align*}
If (1) holds, then \$k\star b=0\$, so \$k\star(b+1)=k+1>k\$ by Lemma 1. Thus \$k\star(b+1)\$ is uniquely determined and satisfies (2).
If (2) holds, then \$k<k\star b\leq N-1\$,so by the outer inductive assumption, \$k\star(b+1)=(k\star b)\star (k+1)\$ is uniquely determined and either (1) or (2) holds for it.
In either case, \$k\star(b+1)\$ is uniquely determined and either (1) or (2) hold for it, completing the inductive step.


Do I have permission? The Challenge

Given a string indicating the symbolic notation of UNIX permission of a file and its ownership (user ID and group ID), decide whether a given user A has permission to read / write / execute it.

Related.

Permissions in UNIX system

In UNIX, every file has three classes of permissions (user, group and others) and ownership, including which user and which group it belongs to.

The symbolic notation consists of ten characters. The first character is not important in this challenge. The remaining nine characters are in three sets of three characters, representing permissions of user, group and others class. Characters in each set indicates whether reading / writing / executing is permitted. If permitted, it will be r, w or x. Otherwise, it will be -.

Note that setuid, setgid and sticky bit may change the third character of each set to s, S, t or T. Here's a simple rule: if the character is lowercase letter, then the permission is set; otherwise, it is not.

(For the details of symbolic notation of permissions, please refer to here.)

Every user has its user ID, and every group has its group ID. All IDs will be non-negative integers. A user will belong to at least one group. If a user A want to get access to a file, the system will check their permissions as follows:

If the file belongs to user A, check the permissions of user class.
If the file doesn't belong to A, but A belongs to the group which the file belongs to, check the permissions of group class.
Otherwise, check the permissions of others class.

However, there is one exception: if the user ID is 0 (superuser), they have permission to do anything!

Specifications

Your program / function should take these as input in any reasonable format:

Permissions in symbolic notation.
User ID and group ID which the file belongs to.
The user ID of A, and a list of group IDs which A belongs to.
Type of access. You can use any three different one-digit or one-character values for read, write and execute.

Return / output a truthy value if A has permission to access the file, or a falsy value if not.
You can assume that the first character of the notation will always be - (regular file).
This is code-golf, so the shortest in bytes wins!

Test Cases

The format here is [permissions, user ID of file, group ID of file, user ID of A, group IDs of A, type(r/w/x)].

[-rwx------, 13, 15, 13, [15, 24], r]: True   # user
[-rwxr-xr-x, 13, 24, 24, [15, 24], w]: False  # group
[-rwxr-Sr-T, 13, 15, 24, [15, 35], x]: False  # group
[-rwsr-xr-t, 13, 15, 24, [24, 35], x]: True   # others
[----------, 13, 15, 0, [0, 1, 2], r]: True   # superuser
[----------, 13, 15, 1, [0, 1, 2], r]: False  # others
[----rwxrwx, 13, 15, 13, [15, 24], r]: False  # user

JavaScript (ES6), 61 51 50 bytes

Takes 6 distinct parameters as input, in the order described in the challenge. Expects the last parameter to be 1 for read, 2 for write or 3 for execute. Returns 0 or 1.

(p,u,g,a,G,P)=>!a|p[u-a?6-3*G.includes(g)+P:P]>'Z'

Test cases

let f =

(p,u,g,a,G,P)=>!a|p[u-a?6-3*G.includes(g)+P:P]>'Z'

//            p             u   g   a   G          P
console.log(f('-rwx------', 13, 15, 13, [15, 24],  1)) // True  (user)
console.log(f('-rwxr-xr-x', 13, 24, 24, [15, 24],  2)) // False (group)
console.log(f('-rwxr-Sr-T', 13, 15, 24, [15, 35],  3)) // False (group)
console.log(f('-rwsr-xr-t', 13, 15, 24, [24, 35],  3)) // True  (others)
console.log(f('----------', 13, 15,  0, [0, 1, 2], 1)) // True  (superuser)
console.log(f('----------', 13, 15,  1, [0, 1, 2], 1)) // False (others)
console.log(f('----rwxrwx', 13, 15, 13, [15, 24],  1)) // False (user)


Help me play the Trumpet The trumpet is a valved aerophone instrument, usually pitched in B♭. The sound is made when the player vibrates their lips to displace air inside the instrument. That vibration is acquired by setting one's mouth in a specific way, called the embouchure. Different embouchures, with tighter or looser lips, produce different pitches.

Furthermore, each valve in the trumpet also changes the pitch of the instrument. When depressed, a valve closes a path inside the tubing of the instrument, making the air flow through a longer path, thus lowering the pitch of the original sound. For the purposes of this challenge, we'll consider the standard, B♭ trumpet, in which the first valve lowers the pitch by a full step, the second lowers the pitch by a half-step, and the third lowers the pitch by one and a half step.

The Challenge

Your challenge is to create a program or function that, given two inputs embouchure and valves, determines the pitch of the note being played.

For the purposes of this challenge, the notes will follow the sequence:

B♭, B, C, C♯, D, E♭, E, F, F♯, G, G♯, A.

Rules

I/O can be taken/given in any reasonable method.
Standard loopholes apply.
You're allowed to use b and # instead of ♭ and ♯ if you wish to.
Input for valves can be taken as a list of depressed valves (1, 3) or a boolean list (1, 0, 1).
This is code-golf, so shortest code in each language wins.

Test Cases:

Valves in these test cases is given as a boolean list, where 0 means depressed and 1 means pressed.

Embouchure:    Valves:   Output:
B♭             0 0 0     B♭
B♭             0 1 0     A
B♭             1 0 1     F
C♯             0 0 1     B♭
C♯             1 1 1     G
E♭             1 0 0     C♯
G              0 1 1     E♭
G♯             1 0 0     F♯
G♯             0 0 1     F
G              1 0 0     F
F♯             1 0 0     E
D              1 0 1     A
A              1 1 1     E♭
E              1 1 0     C♯
E              0 0 1     C♯

Disclaimer: I'm not much of a musician yet, so I do apologize for any butchering I might've made on the test cases. Corrections are appreciated.

Python 3 2, 125 119 81 bytes

lambda e,f,s,t,n=2*'A G# G F# F E Eb D C# C B Bb'.split():n[n.index(e)+2*f+s+3*t]

Try it online!

Saved a lot of bytes thanks to Jonathan Allan.

My original solution (in Python 3):

n=2*'Bb B C C# D Eb E F F# G G# A'.split()
e,f,s,t=str(input()).split()
print(n[n.index(e,9)-2*int(f)-int(s)-3*int(t)])

Try it online!

Saved 6 bytes thanks to @HyperNeutrino.

Explanation

First, I make an array of notes, but doubled in length so I don't have to worry about looping around from Bb to A.

Then, I take input in the following format (for example):

Bb 1 0 1

I then find the index of the starting note using n.index(e,9) (the 9 is there to make sure that I start well in the middle of the (doubled) list. I calculate the desired offset with the expression:

2*int(f) - int(s) - 3*int(t)

Where f is the first valve, s is the second valve, and t is the third.

Finally, it simply prints the note found in the list by subtracting the offset from the starting index.


Print a Negative of your Code Consider a square of printable ASCII characters (code points 0x20 to 0x7E) for side length N, like the following (here, N = 6):

=\
 g \
7
m+y "g
  L ~
e> PHq

We also require each row and each column to contain at least 1 space and 1 non-space character. (The above example satisfies this.)

We define the negative of such a square, to be a square of the same size, where each space is replaced with a non-space and vice versa. E.g., the following would be a valid negative of the above example:

  1234
a b cd
 ZYXWV
   !
{} [ ]
  ?

The choice of non-space characters is irrelevant (as long as they are from the printable ASCII range).

The Challenge

You're to write a program, with square source code with side length N > 1, which prints a negative of itself to STDOUT. Trailing spaces have to be printed. You may or may not print a single trailing newline.

The usual quine rules also apply, so you must not read your own source code, directly or indirectly. Likewise, you must not assume a REPL environment, which automatically prints the value of each entered expression.

The winner is the program with the lowest side length N. In the event of a tie, the submission with the fewest non-space characters in the source code wins. If there's still a tie, the earliest answer wins.


Extended Domino Dots Introduction

Classes have started! And so does the boredom. I decided to doodle in my notebook and started to draw some dots in (IMO) an aesthetically pleasing way. I came up with these numbers:

based on these conditions:
Given (n, m)
1) There must be n dots
2) All dots must lie on an m by m lattice
3) The position of the dots must minimize the spread* from the top left corner
4) The configuration of the dots must be diagonally symmetric as pictured:

*Spread (in this context) is defined as the sum of the distances from the top left dot position (whether or not there is a dot there). For example, the spread of the example above is 0 + 1 + 2 + 1 + √2 + 2 + 2√2 = 6 + 3√2

The Challenge

Come up with an algorithm using that uses natural numbers n and m (where it will always be that n <= m^2) to generate a configuration of dots that follow all the rules above.

Input can be received via STDIN, command-line argument, or function parameter.

Output the pattern to STDOUT or return a string with newlines. Any two different characters may be used in the output.
(e.g.

110
100
000

is the same as

**-
*--
---

Shortest Code in Bytes Wins

Example

STDIN: 6 3
STDOUT:

***
**_
*__

The Challenge has Ended!!!

After seven days I decided to declare the winner, but first some special awards!
Fastest code goes to... orlp with his submission in Pyth !
Slowest code goes to... orlp with his submission in Pyth !
Most straightforward code goes to... orlp with his submission in Pyth !
Most confusing code goes to... orlp with his submission in Pyth !
Longest Code goes to... orlp with his submission in Pyth !

And last but not least

Shortest code goes to......... orlp with his submission in Pyth !

Congratulations!

Pyth, 37 bytes

jc:*d*QQiRQhos.aMNf.Am}_dTT.c^UQ2vzNQ

Slow solution. Generates all possible pairs of [0, m), generate all possible n-combinations of those pairs (without repetition). Filter each combination of pairs such that if P is in the combination, so is reverse(P). This guarantees diagonal symmetry. Sort by the sum of distances to the origin. Decode the pairs of numbers as base-m numbers, giving a list of indices. Create a string of spaces except for those indices, putting quotation marks instead. Finally chop into m pieces and join by newlines. Creates outputs like such:

""""
"""
""
"


Your very own "for" instruction, redux Inspired by Sygmei's question, I'm interested in finding out what languages can "do this properly".

Your task is to write a "for loop" function / macro / instruction. The arguments should be:

an initializer
a test
an increment
a body

All of these are "pieces of code" and should be able to access variables in the context of the call. The body should be able to include multiple statements.

The aim is to have the fewest lexical tokens excluding comments, except that #define and friends (using a dumb preprocessor) are worth 50, and eval and friends (taking a string argument) are worth 100. Feel free to make your code readable with comments, whitespace and meaningful names.

You should include a "test harness" which is not counted towards length.

The C version definitely won't win:

// the do {...} while (0) idiom enables a code block to be a single C statement, so it can safely be followed by a semicolon
#define my_for(init, test, inc, body) do {  \
    init; \
    while (test) { \
        body; \
        inc; \
    } \
} while (0)

// test harness:
#include <stdio.h>

main()
{
    int i, total;
    my_for((i=1, total=0), i<=3, ++i, {printf("%d\n", i); total=total+i;});
    printf("total: %d\n", total);
}

Edit to add: the meaning of "lexical token" depends on your language. Here's how the scoring breaks down for my C version:

//[...]: 0
#define: 1 occurrence, 50 points
my_for: 1
(: 3
init: 2
,: 3
test: 2
inc: 2
body: 2
): 3
do: 1
{: 2
\: 6
;: 3
while: 2
}: 2
0: 1

TOTAL: 85

Python, 11 26 tokens:

def f(n, t, i, l):
    n()
    while t():
        l()
        i()

This is my first time doing atomic-code-golf, so forgive me if I got the token counting wrong.

EDIT: Hugh Allen informed me that I got the token counting wrong.


Motorcycle gear checker! Some of you may be familiar with the way that a motorcycle shifts. But for those who don't, It looks like this

6

5

4

3

2

N

1

Now I want to know what gear I am in after performing a few up and down shifts.
 The program should work from neutral.

Sample input:

V^^

Sample output:

2

As you can see I downshifted once from N to 1 and upshifted twice to 2nd gear.

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

Note: The input can be any 2 characters. Can be U and D for up and down or whatever you want it has to be a string. You cannot shift beyond 1st or 6th gear. If you are in 6th and upshift again it will stay in 6th. Good luck!

JavaScript (ES6), 49 48 47 46 bytes

Expects:

1 for down
7 for up

f=([c,...s],g=2)=>c?f(s,g-c&7||g):'1N'[--g]||g

Formatted and commented

f = (                   // f is a recursive function which takes:
  [c,                   // - c = next character in input string
      ...s],            // - s = remaining characters
  g = 2                 // - g = current gear, with default = neutral = 2
) =>                    //
  c ?                   // if there's still a character to process:
    f(                  //   do a recursive call with:
      s,                //     - the remaining characters
      g - c & 7 ||      //     - the updated gear if it is valid
      g                 //       or the previous gear if not
    )                   //
  :                     // else:
    '1N'[--g] ||        //   decrement g and output '1' for g = 0, 'N' for g = 1,
    g                   //   or simply the corresponding digit for other values

Gears are mapped as follows:

g MOD 8 = 0 1 2 3 4 5 6 7
          ---------------
gear    = X 1 N 2 3 4 5 6       (where 'X' is an invalid state)

Which allows us to easily check the validity of the current gear with:

(g & 7) != 0

Demo

f=([c,...s],g=2)=>c?f(s,g-c&7||g):'1N'[--g]||g

console.log(f(''))
console.log(f('1'))
console.log(f('11'))
console.log(f('17777'))
console.log(f('1777777771'))


GottaFix for WannaCrypt? Warning
The answers to this challenge test for a specific version of the patch that helps stop WannaCrypt/WannaCry attacks. Depending on your operating system, you may have a different patch. The best way to protect yourself is to make sure your PC is fully up to date and be careful when opening attachments and web links.

Introduction
I like to think programmers are inherently good people, even if some aren't so nice, so lets help people make sure they are protected with the MS17-010 patch.
Challenge
Your challenge is to write a full program or function that returns a truthy or falsey value depending on if the MS17-010 patch is installed on the current operating system.
Input and Output
Input: No input required
Output: A truthy or falsey value (Indicate which is used for each case).
An error/exception can be considered a falsey value.
Rules

Your code should run (and output correctly) on at least one windows operating system for which the patch is available, but doesn't have to run on every operating system (Please state any limitations).
Standard loopholes apply
This is code-golf, so the submission with the least amount of bytes wins!

PowerShell 2.0, 24 20 16 bytes
hotfix KB4012212

-4 bytes thanks to @whatever by removing  -id.
-4 bytes thanks to @DankoDurbić by changing get-hotfix to hotfix.
KB4012212 is the patch for Windows 7. This can be replaced with any KB-code from the linked page of the patch.
Will return the Source, Description, HotFixID, InstalledBy and InstalledOn information when it's installed as truthy value, and will give an error if it's unable to find it as falsey value.
Here is an example of both a truthy and falsey output (so KB4012212 is installed on my machine, but KB4012215 is not):


Count the Closed Polygons Input:

An NxM grid or multi-line string (or other reasonable input-format), containing only printable ASCII (unicode range [32,126]).

Output:

The amount of closed polygons of the same character that can be found, with two special rules:

Spaces are wildcards and can be used (multiple times) for any character
o, O, and 0 are counted as closed polygons themselves

Challenge rules:

(Anti-)Diagonal connections between the same characters (or spaces) are included to form closed polygons.
You cannot go over other characters (except for the wild-card spaces). (I.e. in the first test case/example below, you cannot form two triangles with the A's by going over the x.) So all characters used for a closed polygon should be connected (horizontally, vertically, and/or (anti-)diagonally).
Polygons are at least three characters (excluding the single characters o, O, 0).
Lines of adjacent characters are not closed polygons.
The same characters cannot be used for multiple polygons, excluding wildcard spaces.
Wildcard spaces cannot be counted as o, O, or 0.
Three or more spaces alone cannot form a closed polygon. It should always have at least one non-space (and non o/O/0) character.
Input can be in any reasonable format. Can be a character-matrix, new-line delimiter string, string-array, character-array with added integer width, etc.
The inputs will always be an N by M rectangle (or square), so no weird input-shapes
Since the same characters cannot be used more than once and we want to have as many closed polygons, using multiple characters to form two (or more) closed polygons instead of one larger polygon is of course the intended goal in the counting (which is also why closed polygons formed by o, O, or 0 will never be counted, since they are already closed polygons individually).
Uppercase and lowercase letters are of course counted as individual characters.

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code (i.e. TIO).
Also, adding an explanation for your answer is highly recommended.

Examples / Test Cases:

Input:

AAAw
AxA4
'AoQ

Output: 2, because these polygons can be formed:

Input:

1822uaslkoo
12*2sl ljoo
a* 0a91)j$*
()*#J9dddj*
*Q#ID dJj!"
*UJD SO&*93

Output: 12, because these polygons can be formed:

Note that:
- The yellow one below is not a polygon, because the o's are already counted as separated polygons
- The purple and brown ones aren't closed
- The red, grey, green, and light-blue use one or more non-space characters that were already used for other closed polygons

Input (dimensions are 2x4):

3  3
  2

Output: 3, because these polygons can be formed:

Input:

AAAA
AAAA
AAxA

Output: 3, because these polygons can be formed:

Of course other polygons are possible here, but no more than 3. Here another valid example with 3 polygons:

Input:

0QoO

Output: 3, because these polygons can be formed:

Input:

W w
 Ww

Output: 3, because these polygons can be formed:

Note that the top layer space is used for all three polygons. Here are the three polygons individually highlighted:

Input:

W W
 WW

Output: 3, because the same three polygons as in the previous test can be formed. So no, it's not 2 with these two polygons:

Input:

abcdQefg
hQiQjQQk
QlQmnopQ
QqrstQQu
QvQQQwxy
QQz0QQQQ

Output: 3, because these polygons can be formed:

Python 2, 714 737 821 bytes

-23 bytes thanks to Kevin Cruijssen

M=input()
m=''.join(M)
def P(L):
 if len(L)<2:yield[L];return
 for p in P(L[1:]):
	for n,s in enumerate(p):yield p[:n]+[[L[0]]+s]+p[n+1:]
	yield[[L[0]]]+p
h,w,R,C=len(M),len(M[0]),0,[-1,0,1]
K=[(i,j)for i in range(h)for j in range(w)]
Z=[(i,j)for i,j in K if' '==M[i][j]]
from networkx import*
for l in set(m):
 G,S=[],[]
 if l in'oO0':R+=m.count(l);continue
 for I in K:
  i,j=I
  for p in C:
	for q in C:
	 X=x,y=i+p,j+q
	 if X in K and X!=I and set(M[i][j]+M[x][y])<=set(' '+l):G+=[(I,X)];S+=[I,X]
 B=0
 for L in P(list(set(S))):
  b=0
  for p in L:
	for i,j in p:
	 if' '!=M[i][j]:
		try:find_cycle(from_edgelist([(I,X)for I,X in G if I in p+Z and X in p+Z]));b+=1
		except:1
		break
	if b>B:B=b
 R+=B
print R

Try it online!

For each letter A (except  o, O, and 0) the code build a graph representing the adjacency of the different occurrences of letter A and space in the initial given matrix. Then it computes the set of semi-separated cycles covering the graph when maximizing the number of cycles (separation is based only on the letter A, the same space can be used for several cycles).
The code passes all tests.
Input: the list of lines of the matrix.
More explanation and golfing coming soon.


Fizz Buzz for Turtles Problem Description

Imagine you're a turtle on a grid.  You're given two numbers f and b, and you're facing east. You perform a march across the grid, counting each of the cells you encounter, according to the following rules:

By default, you write the count to the cell you're in, then walk forward.
If the count is divisible by f, you write F to the cell you're in, then turn right, then walk forward.
If the count is divisible by b, you write B to the cell you're in, then turn left, then walk forward.
If the count is divisible by both f and b, you write FB to the cell you're in, then walk forward.
If you reach a square you've already been to, you stop.

For example, following these rules using f = 3 and b = 5 will generate a pattern like this:

    F 28 29 FB  1  2  F
   26                 4
 F  B                 B  F
23                       7
22                       8
 F  B                 B  F
   19                11
    F 17 16 FB 14 13  F

The challenge

Write a program or function that accepts two numbers as input, corresponding to f and b, and produces as output the pattern for these numbers given by the rules above.

Formatting requirements:

Each cell is two characters wide
Cell contents are right aligned within these two characters
Cells on the same row are delimited by a space
The first column of cells must contain a non-empty cell
All rows must contain non-empty cells
Trailing whitespace is not required, but allowed
However, the total width of each row must not exceed 3 times the number of non-empty columns

Your code must work for provided test cases.

Standard loopholes are disallowed.

This is code golf; shortest answer in bytes wins.

Test cases

(f=3, b=5 case repeated here as a courtesy convenience).

f=3, b=5 ->
    F 28 29 FB  1  2  F
   26                 4
 F  B                 B  F
23                       7
22                       8
 F  B                 B  F
   19                11
    F 17 16 FB 14 13  F

f=4, b=10 ->
 F 25 26 27  F
23          29
22        1  2  3  F
21                 5
FB                 6
19                 7
18           B  9  F
17          11
 F 15 14 13  F

f=3, b=11 ->
 F 16 17  F
14       19
13     1  2  F
 F  B        4
   10        5
    F  8  7  F

f=5, b=9 ->
    F 41 42 43 44  1  2  3  4  F
   39                          6
   38                          7
   37                          8
 F  B                          B  F
34                               11
33                               12
32                               13
31                               14
 F 29 28  B              B 17 16  F
         26             19
          F 24 23 22 21  F

f=5, b=13 ->
    F 31 32 33 34  F
   29             36
   28        1  2  3  4  F
   27                    6
 F  B                    7
24                       8
23                       9
22              B 12 11  F
21             14
 F 19 18 17 16  F


Generate a Brainf_ck program that outputs a string of given length Your friend is trying to break into a vault that has a peculiar locking system: it requires a certain number of gentle knocks in a particular spot. Your friend discovered the number (which is in the range 1...99999) and possesses a gadget that produces the required knocks. However, the gadget is a Brainfuck interpreter! So your friend needs to feed it a Brainfuck program, which, obviously, should be as short as possible (the gadget's I/O is slow).

Your task is to help him! Write a program or a subroutine, in any language, that accepts as input a number N, and outputs a Brainfuck program, which takes no input and outputs a string of printable ASCII characters (excluding the space character - codes in the range 33...126) of length N.

Example: for input 10, the output might be

+++++++++++++++++++++++++++++++++..........

(but I am sure it can be shortened!)

Your score will be the sum of lengths of your outputs for the following values of N (they are random numbers):

55
68
15
28
841
838
522
846
4898
9004
9363
3810
13230
67175
37231
44701

Oh, and you will be transmitting your code (the generator program) to your friend by Twitter. So make sure it's 140 characters or less!

P.S. The Brainfuck language has many variants. Let's assume the tape is infinite in both directions (or "circular and large enough"), and the cells have 32-bit int capacity (finite and able to hold numbers up to 99999). Also, no wrapping: when a cell overflows, the machine self-destructs!


Help Sam understand chess For this challenge, you will be writing a program or function which outputs (or prints) (in a reasonable format, i.e single string or an array of lines) a chess board which indicates all the possible moves of a piece given an empty board.

There are 5 chess pieces (for this challenge a pawn may be ignored):

Bishop (Moves diagonally any number of squares)
Rook (Moves orthogonally any number of squares)
Queen (Moves diagonally or orthogonally any number of squares)
KNight (Moves in an L shape, i.e. two in one dimension, and one in the other)
King (Moves one step orthogonally or diagonally)

Your submission will take in three inputs: the row of the chess piece, the column of the chess piece, and the type of piece (as a character or integer).

Say we call drawBoard(4,4,'N') for the Knight using 0-indexing, the output will be as follows:

........
........
...M.M..
..M...M.
....N...
..M...M.
...M.M..
........

where the '.' and 'M' can be replaced accordingly with printable ascii characters of your choice.

Sample outputs as follows for other piece types. (Note all of these are called with input of 4,4 and are 0-indexed).

King:

........
........
........
...mmm..
...mKm..
...mmm..
........
........

Rook:

....m...
....m...
....m...
....m...
mmmmRmmm
....m...
....m...
....m...

Sam does not mind 1-based indexing, or even indexing following chess algebraic notation. However, your code must be as small as possible so Sam has enough space to think about his chess with the code next to him.

Sam has also realized that outputs will be accepted regardless of trailing or preceding whitespace (before and after input and each line)

Ruby, 125
anonymous function, prints to stdout.
RevB: golfed, but a bug fix brought it back to the same length as before.
->x,y,z{72.times{|i|v=y-i/9;u=x-i%=9
e=u*u+v*v
$><<(i<8?e<1?z:[r=0==v*u,b=u*u==v*v,b|r,3>e,5==e]["RBQKN"=~/#{z}/]??*:?.:$/)}}

Prints each of the 64 squares + 8 newlines = 72 characters individually.
Relies on e, the square of the Euclidean distance between the current square and the given coordinates for checking king moves and knight moves (and also for printing the piece value z when the Euclidean distance is zero.)
Ungolfed in test program
f=->x,y,z{                         #x,y,character
  72.times{|i|                     #8 rows of (8 chars + newline) = 72 chars
    v=y-i/9;                       #vertical diff between y coord and current square
    u=x-i%=9                       #horizontal diff between x coord and current square. note i%=8
    e=u*u+v*v                      #square of euclidean distance
    $><<(                          #$> is stdout. send to it....
      i<8?                         #if not the newline column,
        e<1?z:                       #if the euclidean distance is 0, print the symbol for the piece, else
        [r=0==v*u,                   #TRUE if v or u is 0 (rook)
        b=u*u==v*v,                  #TRUE if abs(u)==abs(v) (bishop)
        b|r,                         #TRUE if either of the above are true (queen)
        3>e,                         #TRUE if e == 1 or 2 (king)
        5==e                         #TRUE if e == 5 (knight)
        ]["RBQKN"=~/#{z}/]??*:?.:    #select value from array corresponding to piece and print * or . accordingly
      $/                           #if newline column, print a newline
    )
  }
}

x=gets.to_i
y=gets.to_i
z=gets.chomp
f[x,y,z]


Lets make a triangle Most people are familiar with Pascal's triangle.

    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

Pascal's triangle is an automaton where the value of a cell is the sum of the cells to the upper left and upper right.  Now we are going to define a similar triangle.  Instead of just taking the cells to the upper left and the upper right we are going to take all the cells along two infinite lines extending to the upper left and upper right.  Just like Pascal's triangle we start with a single 1 padded infinitely by zeros and build downwards from there.

For example to calculate the cell denoted with an x

   1
  1 1
 2 2 2
4 5 5 4
   x

We would sum the following cells

   .
  . .
 2 . 2
. 5 5 .
   x

Making our new cell 14.

Task

Given a row number (n), and distance from the left (r) calculate and output the rth non-zero entry from the left on the nth row. (the equivalent on Pascal's triangle is nCr).  You may assume that r is less than n.

This is code-golf, the goal is to minimize the number of bytes in your solution.

Test cases

0,0 -> 1
1,0 -> 1
2,0 -> 2
4,2 -> 14
6,3 -> 106

Here's the first couple rows in triangle form:

                  1
                1   1
              2   2   2
            4   5   5   4
          8  12  14  12   8
       16  28  37  37  28  16
     32  64  94  106 94  64  32
   64  144 232 289 289 232 144 64
 128 320 560 760 838 760 560 320 128

Jelly, 18 17 bytes

SṚ0;+Sṭ
1WWÇ⁸¡ṪṙḢ

Uses 0-based indexing.

Try it online!

How it works

1WWÇ⁸¡ṪṙḢ  Main link. Arguments: n, r

1          Set the return value to 1.
 W         Wrap; yield [1].
  W        Wrap; yield [[1]].
           This is the triangle with one row.
   Ç⁸¡     Call the helper link n times.
           Each iteration adds one row to the triangle.
      Ṫ    Tail; take the last array, i.e., the row n of the triangle.
       ṙ   Rotate row n r units to the left.
        Ḣ  Head; take the first element, i.e., entry r of row n.

SṚ0;+Sṭ    Helper link. Argument: T (triangle)

S          Take the column-wise sums, i.e., sum the ascending diagonals of the
           centered triangle, left to right.
 Ṛ         Reverse the array of sums. The result is equal to the sums of the
           descending diagonals of the centered triangle, also left to right.
  0;       Prepend a 0. This is required because the first element of the next row
           doesn't have a descending diagonal.
     S     Take the column-wise sum of T.
    +      Add the ascending to the descending diagonals.