Convert a percentage to a "simple" ratio You run a political website, and have determined that people have a better intuitive understanding when the chance of winning or losing an election is expressed as a ratio ("5 in 7") than when it is expressed as a percentage ("71%").

But you also don't want to display confusing ratios like "58 in 82", you'd like them to be more easily understood, even if they aren't quite as precise.

So, given a percentage between 0.1% and 99.9%, return the closest "easy-to-understand" ratio "x in y", using the following rules:

Most values (see exceptions below) should return the closest ratio out of 10 or lower. 55% should return "5 in 9", not "11 in 20".
Ratios should be reduced to their lowest terms. 65% should return "2 in 3", not "4 in 6".
Values under 10% should return the closest ratio of the form "1 in n" where n is one of (10,12,15,20,30,40,50,60,70,80,90,100). For example,  6% should return "1 in 15".
Values over 90% should return the closest ratio of the form "n-1 in n" where n is one of (10,12,15,20,30,40,50,60,70,80,90,100). For example, 98.7% should return "79 in 80".
Values under 1% should return "<1 in 100"
Values over 99% should return ">99 in 100"

Or, to think about it another way, your program should return the closest ratio from the following possible outputs (I've included their approximate values for your convenience):

<1 in 100
 1 in 100  = 1.00%
 1 in 90   = 1.11%
 1 in 80   = 1.25%
 1 in 70   = 1.43%
 1 in 60   = 1.67%
 1 in 50   = 2.00%
 1 in 40   = 2.50%
 1 in 30   = 3.33%
 1 in 20   = 5.00%
 1 in 15   = 6.67%
 1 in 12   = 8.33%
 1 in 10   = 10.00%
 1 in 9    = 11.11%
 1 in 8    = 12.50%
 1 in 7    = 14.29%
 1 in 6    = 16.67%
 1 in 5    = 20.00%
 2 in 9    = 22.22%
 1 in 4    = 25.00%
 2 in 7    = 28.57%
 3 in 10   = 30.00%
 1 in 3    = 33.33%
 3 in 8    = 37.50%
 2 in 5    = 40.00%
 3 in 7    = 42.86%
 4 in 9    = 44.44%
 1 in 2    = 50.00%
 5 in 9    = 55.56%
 4 in 7    = 57.14%
 3 in 5    = 60.00%
 5 in 8    = 62.50%
 2 in 3    = 66.67%
 7 in 10   = 70.00%
 5 in 7    = 71.43%
 3 in 4    = 75.00%
 7 in 9    = 77.78%
 4 in 5    = 80.00%
 5 in 6    = 83.33%
 6 in 7    = 85.71%
 7 in 8    = 87.50%
 8 in 9    = 88.89%
 9 in 10   = 90.00%
 11 in 12  = 91.67%
 14 in 15  = 93.33%
 19 in 20  = 95.00%
 29 in 30  = 96.67%
 39 in 40  = 97.50%
 49 in 50  = 98.00%
 59 in 60  = 98.33%
 69 in 70  = 98.57%
 79 in 80  = 98.75%
 89 in 90  = 98.89%
 99 in 100 = 99.00%
>99 in 100

Other stipulations:

Numeric input can be in the range of 0.1 to 99.9 or in the range of 0.001 to 0.999, whichever is more convenient. You must handle at least 3 significant digits.
You must output a ratio ("3 in 4"), not the equivalent fraction ("3/4").
If there are two ratios equally close to the input, your program can return either one. 7.5% could return "1 in 12" or "1 in 15".
Leading/trailing white space and/or new lines are fine

Examples:

Input  :   Output
 0.5   :  <1 in 100
 1.0   :   1 in 100
 1.5   :   1 in 70
 7.5   :   1 in 15  or  1 in 12 (either is acceptable)
 9.2   :   1 in 10
13.1   :   1 in 8
29.2   :   2 in 7
29.3   :   3 in 10
52.7   :   1 in 2
52.8   :   5 in 9
72.0   :   5 in 7
73.9   :   3 in 4
88.8   :   8 in 9
90.8   :   9 in 10
94.2   :  19 in 20
98.7   :  79 in 80
98.9   :  89 in 90
99.0   :  99 in 100
99.1   : >99 in 100

This is a code-golf challenge, shortest code in each language wins.

(Similar to, but not duplicate of: Convert a decimal to a fraction, Closest fraction, Approximate floating point number with n-digit precision)

T-SQL, 385 bytes
SELECT TOP 1IIF(i>.99,'>',IIF(i<.01,'<',''))+n+' in '+d
FROM t,(SELECT ISNULL(PARSENAME(value,2),'1')n,PARSENAME(value,1)d FROM
STRING_SPLIT('100,90,80,70,60,50,40,30,20,15,12,10,9,8,7,6,5,2.9,4,2.7,3.10,3,3.8,2.5,3.7,4.9,2,5.9,4.7,3.5,5.8,2.3,7.10,5.7,3.4,7.9,4.5,5.6,6.7,7.8,8.9,9.10,11.12,14.15,19.20,29.30,39.40,49.50,59.60,69.70,79.80,89.90,99.100',','))m
ORDER BY ABS(i-ABS(n)/d)

Input is via pre-existing table t with numeric field i, per our IO standards.
That input table is joined with an in-memory table parsed from a string via STRING_SPLIT (which separates rows) and PARSENAME (which separates numerator and denominator via .).
The table is sorted by distance from the input value i, and returns the top row, formatted appropriately.


Print the Super Collatz numbers The Collatz Sequence (also called the 3x + 1 problem) is where you start with any positive integer, for this example we will use 10, and apply this set of steps to it:

if n is even:
    Divide it by 2
if n is odd:
    Multiply it by 3 and add 1
repeat until n = 1

10 is even, so we divide by 2 to get 5. 5 is odd, so we multiply by 3 and add 1 to get 16. 16 is even, so cut it in half to get 8. Half of 8 is 4, half of 4 is 2, and half of 2 is 1. Since this took us 6 steps, we say that 10 has a stopping distance of 6.

A Super Collatz number is a number whose stopping distance is greater then the stopping distance of every number smaller than it. For example, 6 is a Super Collatz number since 6 has a stopping distance of 8, 5 has a stopping distance of 5, 4 has 2, 3 has 7, 2 has 1 and 1 has 0. (A006877 in the OEIS) You must take a number n as input, and output out all the Super Collatz numbers up to n.

Rules

Full Program or function is acceptable.
You can not precompute or hard-code the Super Collatz sequence.
You can take input in any reasonable format.
Output can be returned as a list from the function, or printed to STDOUT or a file. Whichever is most convenient.
Invalid inputs (non-numbers, decimals, negative numbers, etc.) result in undefined behavior.

Sample ungolfed python

def collatzDist(n):
    if n == 1:
        return 0
    if n % 2 == 0:
        return 1 + collatzDist(n / 2)
    return 1 + collatzDist((n * 3) + 1)

n = input()

max = -1
superCollatz = []
for i in range(1, n + 1):
    dist = collatzDist(i)
    if dist > max:
        superCollatz.append(i)
        max = dist

print superCollatz

Sample IO:

#in       #out
 4     --> 1, 2, 3
 50    --> 1, 2, 3, 6, 7, 9, 18, 25, 27
 0     --> invalid
 10000 --> 1, 2, 3, 6, 7, 9, 18, 25, 27, 54, 73, 97, 129, 171, 231, 313, 327, 649, 703, 871, 1161, 2223, 2463, 2919, 3711, 6171

Also here are the first 44 Super Collatz numbers:

1, 2, 3, 6, 7, 9, 18, 25, 27, 54, 73, 97, 129, 171, 231, 313, 327, 649, 703, 871, 1161, 2223, 2463, 2919, 3711, 6171, 10971, 13255, 17647, 23529, 26623, 34239, 35655, 52527, 77031, 106239, 142587, 156159, 216367, 230631, 410011, 511935, 626331, 837799

Python 2, 104 bytes

c=lambda x:x>1and 1+c([x/2,x*3+1][x%2])
lambda n:[1]+[x for x in range(2,n)if c(x)>max(map(c,range(x)))]

c is a helper function that calculates the Collatz distance for a given integer. The unnamed lambda is the main function, which computes the super Collatz numbers up to (but not including) the input.


Convert a Point of the Compass to Degrees I came up with this challenge independently, but it turns out to be the inverse to this challenge by Doorknob. As I really like his spec, I decided to steal large parts of it instead of cooking up my own explanations.

The Challenge

Given the abbreviation of one of the 32 points on the compass, print the corresponding degrees. Feel free to skip ahead to the table below if you're not interested in an explanation of the 32 points.

Here is the full compass:

By Denelson83 (Own work) [GFDL or CC-BY-SA-3.0], via Wikimedia Commons

Each direction is 11.25 (360 / 32) degrees farther than the previous. For example, N (north) is 0 degrees, NbE (north by east) is 11.25 degrees, NNE (north-northeast) is 22.5 degrees, etc.

In detail, the names are assigned as follows:

0 degrees is N, 90 degrees is E, 180 degrees is S, and 270 degrees is W. These are called cardinal directions.
The halfway points between the cardinal directions are simply the cardinal directions they're between concatenated. N or S always go first, and W or E always are second. These are called ordinal directions. The ordinal and cardinal directions together form the principal winds.
The halfway points between the principal winds are the directions they're between concatenated. Cardinal directions go first, ordinal second. These are called half winds.
The halfway points between principal and half winds are the adjacent principal wind "by" the closest cardinal direction away from the principal wind. This is denoted with a b. These are called quarter winds.

This results in the following chart:

#   Degrees  Abbrv.  Name
1   0        N       North
2   11.25    NbE     North by east
3   22.5     NNE     North-northeast
4   33.75    NEbN    Northeast by north
5   45       NE      Northeast
6   56.25    NEbE    Northeast by east
7   67.5     ENE     East-northeast
8   78.75    EbN     East by north
9   90       E       East
10  101.25   EbS     East by south
11  112.5    ESE     East-southeast
12  123.75   SEbE    Southeast by east
13  135      SE      Southeast
14  146.25   SEbS    Southeast by south
15  157.5    SSE     South-southeast
16  168.75   SbE     South by east
17  180      S       South
18  191.25   SbW     South by west
19  202.5    SSW     South-southwest
20  213.75   SWbS    Southwest by south
21  225      SW      Southwest
22  236.25   SWbW    Southwest by west
23  247.5    WSW     West-southwest
24  258.75   WbS     West by south
25  270      W       West
26  281.25   WbN     West by north
27  292.5    WNW     West-northwest
28  303.75   NWbW    Northwest by west
29  315      NW      Northwest
30  326.25   NWbN    Northwest by north
31  337.5    NNW     North-northwest
32  348.75   NbW     North by west

Here is a more detailed chart and possibly better explanation of the points of the compass.

Your task is to take as input one of the 32 abbreviations from the third column and output the corresponding degrees in the second column.

You may assume that input will always be exactly one of those 32 strings (and you may optionally but consistently expect a single trailing newline). Output should also be given exactly as listed above, although trailing zeroes are allowed. You may optionally output a single trailing newline.

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

This is code golf, so the shortest answer (in bytes) wins.

Ruby, 118 106
Thanks to Martin Büttner for 12 bytes saved.
This is currently the same length regardless of whether it's a function or a program.
lambda function
->s{n=4
d=0,0
s.chars{|e|c="SWNE".index e
c ?d[c%2]+=c/2*2*n-n :n=1}
(Complex(*d).arg*5.1).round%32*11.25}

program
n=4
d=0,0
gets.chars{|e|c="SWNE".index e
c ?d[c%2]+=c/2*2*n-n :n=1}
p (Complex(*d).arg*5.1).round%32*11.25

This is a cartesian walk through the points. The characters NSEW add or subtract 4 from the x and y coordinates stored in d[]. After a b (or any symbol other than NSEW) is encountered, this is reduced to 1.
The x and y data is then treated as a complex number to extract the angular argument. This is multiplied by 16/PI=5.1 . Although there are some geometrical errors in the approach, rounding this angle is sufficient to give the correct number -15..+16. Modulo is used to correct this to 0..31 (in Ruby % always returns positive.) Finally the result is multiplied by 11.25.


Find all Number Relations Inspired by: Find an Unrelated Number

Challenge

Given two positive integers as input, output the mathematical operations that can be used on those inputs to generate every number from 1 to n inclusive where n is the smallest prime greater than the sum of the two inputs. If the number cannot be generated using the list of mathematical operations below, the output for that number should indicate that it is "unrelated".

For example, for the inputs 2 and 3, n=7 so one valid output would be
Subtraction, Modulus, Bitwise OR, Unrelated, Addition, Multiplication, Unrelated
(see Output section below for clarification on valid outputs)

(If Erik the Outgolfer's answer is valid, the last term will always be unrelated.)

Operations that must be considered are:

Addition        (a + b)
Subtraction     (a - b) and (b - a)
Multiplication  (a * b)
Division        (a / b) and (b / a)
Modulus         (a % b) and (b % a)
Bitwise OR      (a | b)
Bitwise XOR     (a ^ b)
Bitwise AND     (a & b)

In cases where an operation would lead to a non-integer (such as 2/3), always floor. So 2/3=0 and 3/2=1.

Exponentiation is not included because it is never required. a**b and b**a will always be larger than 2(a+b)-2 (which is (probably) the largest possible n) except for the cases a=1|b=1 or a=b=2. The cases a=b=1 and a=b=2 have valid solutions that do not use exponents: * and /|U+U, respectively. For the rest of the cases where a=1,b>1, a**b=1 which can also be found with a%b and b**a=b which can also be found with b*a.

Concatenation is not included because it was shown to always be larger than n.

Input

2 positive integers.
Standard I/O methods are accepted. Standard loopholes are forbidden.
You can assume the input will always be within a valid range for your given language.

Output

A list or array of the mathematical operations that can be used with the inputs to generate every number from 1 to n inclusive where n is the smallest prime larger than the sum of the two inputs. (You do not need to output the value of n.)

Output can be in any format valid for your language so long as it is clearly understood. For instance, it can be an array where each value is a separate operation, a string with a delimiter between each value, or even just a solid string where each character is a different value.

You can use any character(s) so long as each possible result has a unique representation. For instance, +-*/%|^&U will work and so will 123456789, UNRELATID, and CODEgolf!. You are advised to include a legend or explanation of how the output can be read.

If more than one operation can be used to generate a given number, you may output any one of them. Do not output all of them.

Testcases

Input  |   n  |   Example Valid Output
-----------------------------------------
2, 3   |   7  |   Subtraction, Modulus, Bitwise OR, Unrelated, Addition, Multiplication, Unrelated
2, 3   |   7  |   -%|U+*U
2, 3   |   7  |   2579139
1, 1   |   3  |   [*,+,U]
6, 6   |  13  |   ["/","U","U","U","U","&","U","U","U","U","U","+","U"]
6,12   |  19  |   U/U&U-UUU^UUU|UUU+U
12,6   |  19  |   U/U&U-UUU^UUU|UUU+U
7,11   |  19  |   /U&-UU%UUUU^UU|UU+U
7,15   |  23  |   %/UUUU%-UUUUUU|UUUUUU+U  (2nd value is a floor divide)

(I can easily add more test cases if someone finds an interesting one.)

I think the test case outputs are all valid but I've been known to mistakes. Please tell me if you spot one.

Scoring

This is code-golf so fewest bytes wins!

JavaScript (ES6), 134 bytes
(a,b)=>eval("for(t=a+b,i=0;i=i<t;)for(++t;t%++i;);for(q=n='';n++<t;)[...'+-*/%^&|>'].every(o=>n^eval(a+(p=o)+b)&&n^eval(b+o+a)),q+=p")

Using the standard symbols for operations in JavaScript, except for unrelated that is >
Less golfed
(a,b)=>
{
  // find the smallest prime greater than the sum of a and b
  for (t = a + b, i = 0; i < t; )
    for(i=1, ++t; t % ++i; );

  // loop from 1 to t
  // accumulate output in q
  for(q='', n = 0; n++ < t; )
  {
    // try all binary operators
    // to avoid error in 'eval', I need a binary operator for 'unrelated', so I choose '>'
    [...'+-*/%^&|>'].every( // every terminates early if the result is false
      o => (
        p = o,
        n ^ eval(a+o+b) && n ^ eval(b+o+a)
      )
      // using xor to check for equality, the result is cast to integer
      // eventually flooring the division result
    )
    q += p
  }
  return q
}

Test

F=
(a,b)=>eval("for(t=a+b,i=0;i=i<t;)for(++t;t%++i;);for(q=n='';n++<t;)[...'+-*/%^&|>'].every(o=>n^eval(a+(p=o)+b)&&n^eval(b+o+a)),q+=p")

console.log(2,3,F(2,3))
console.log(1,1,F(1,1))
console.log(6,6,F(6,6))
console.log(6,12,F(6,12))
console.log(7,15,F(7,15))


Array combinatoric comparison Introduction

You may remember sudoku, where there can only be one of each number in each row, column and block of nine.
The general idea is that if the array contains but one element, you can submit that as a deterministic solution. If there are already filtered arrays (by rows, columns and 3×3 blocks) the remainder can still be deterministic.
Where

a=[1,2];
b=[1,3];
c=[2,3];
d=[1,2,3,4]

d should be reduced to [4] as it apparently cannot be anything else.

Challenge

Provide a sniplet that compares n arrays.
For every X, if only X numbers appear at least once in a set of X arrays, then all those X numbers should be removed from each array not in the set.
The elements are integer numbers ranging [1, n].

Winning criterion

Lowest character count.

"I'm too young to die" version

9 arrays at most, 9 elements at most.

Test Cases

  [1,2]; [2,3]; [1,3]; [1,2,3,4]
  [1,2,3]; [2,3,4]; [1,5,6]; [2,3]; [1,4]; [1,2,3,4,6]

  Test outputs

  [1,2]; [2,3]; [1,3]; [4]
  [1,2,3]; [2,3,4]; [5]; [2,3]; [1,4]; [6]

Pyth: 37 29 28 bytes

um?d|-lHl{sHsmg{kdH-dsHGtyQQ

Input is a list of lists like [[1,2], [2,3], [1,3], [1,2,3,4]]. Try it online: Pyth Compiler/Executor

Explanation:

um?d|-lHl{sHsmg{kdH-dsHGtyQQ
u                          Q  G = input array
u                       tyQQ  For each H in powerset(input):
 m                     G        G = [            ...        for d in G]
  ?d               -dsH             [d if ... else d-sum(H) for d in G]
     -lHl{sH                        len(H)-len(set(sum(H)))!=0
    |                                     or
            smg{kdH                 sum(d is subset of k for k in H)>0


Minimal Centrosymmetrization Topically related.

Objective: Given a matrix of positive integers \$M\$, output the smallest centrosymmetric matrix which contains \$M\$ (this matrix may contain non-positive integers as well).

A centrosymmetric matrix is a square matrix with rotational symmetry of order 2—i.e. it remains the same matrix after rotating it twice. For example, a centrosymmetric matrix has the top-left element the same as the bottom-right, and the element above the center the same as the one below the center. A useful visualization can be found here.

More formally, given a matrix \$M\$, produce a square matrix \$N\$ such that \$N\$ is centrosymmetric and \$M\subseteq N\$, and there is no other square matrix \$K\$ such that \$\dim K<\dim N\$.

\$A\$ is a subset of \$B\$ (notation: \$A\subseteq B\$) if and only if each value \$A_{i,j}\$ appears at index \$B_{i+i^\prime,j+j^\prime}\$ for some pair of integers \$(i^\prime, j^\prime)\$.

Note: some matrices have multiple solutions (e.g. [[3,3],[1,2]] being solved as [[2,1,0],[3,3,3],[0,1,2]] or [[3,3,3],[1,2,1],[3,3,3]]); you must output at least one of the valid solutions.

Test cases

input
example output

[[1, 2, 3],
 [4, 5, 6]]
[[1, 2, 3, 0],
 [4, 5, 6, 0],
 [0, 6, 5, 4],
 [0, 3, 2, 1]]

[[9]]
[[9]]

[[9, 10]]
[[9, 10],
 [10, 9]]

[[100, 200, 300]]
[[100, 200, 300],
 [  0,   0,   0],
 [300, 200, 100]]

[[1, 2, 3],
 [4, 5, 4]]
[[1, 2, 3],
 [4, 5, 4]
 [3, 2, 1]]

[[1, 2, 3],
 [5, 6, 5],
 [3, 2, 1]]
[[1, 2, 3],
 [5, 6, 5],
 [3, 2, 1]]

[[4, 5, 4],
 [1, 2, 3]]
[[3, 2, 1],
 [4, 5, 4],
 [1, 2, 3]]

[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
 [1, 1, 1, 9, 9, 9, 9, 9, 9, 9],
 [1, 1, 1, 9, 9, 9, 9, 9, 9, 9],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 1]]
[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9],
 [1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9],
 [1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 1, 1, 1],
 [9, 9, 9, 9, 9, 9, 9, 9, 9, 1, 1, 1],
 [9, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]

Brachylog, 12 bytes

ṁ↔ᵐ↔?aaᵐ.&≜∧

Try it online!

Contrary to most Brachylog answers, this takes the input through the Output variable ., and outputs the result through the Input variable ? (confusing, I know).

Explanation

ṁ              We expect a square matrix
 ↔ᵐ↔?          When we reverse the rows and then the matrix, we get the initial matrix back
    ?a         Take an adfix (prefix or suffix) of that square matrix
      aᵐ       Take an adfix of each row of that adfix matrix
        .      It must be the input matrix
         &≜    Assign values to cells which are still variables (will assign 0)
           ∧   (disable implicit unification between the input and the output)

8 bytes, gives all valid matrices

Technically, this program also works:

ṁ↔ᵐ↔?aaᵐ

But this will leave as variables the cells which can take any value (they show as _XXXXX, which is an internal Prolog variable name). So technically this is even better than what is asked, but I guess it's not what the challenge asks for.


Turn a string inside out A balanced string is a string of parentheses () so that every parenthesis is can be matched with another one.  More rigorously they are the strings spanned by this grammar:

S → (S)S | ε

We can turn a string "inside out" by:

Switching all occurrences of ( and ) with each other
Moving characters from the front of the string to the back until the string is balanced again.

Lets do an example.

We start with the balanced string:

(()(())())

We then switch the parens to make

))())(()((

Then move characters from the front of the string to the back of the string until the string is balanced.

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

Thats our result!

Note that some strings can be turned inside out in multiple ways, for example the string

(()())

When turned inside out can be either:

()(())

or

(())()

However every string has at least one solution.

Task

Write a program to take a balanced string as input and output that string turned inside out.  In cases where there may be multiple valid outputs you need only output one of them.  You may use a different brace type (<>,[] or {}) if you so wish.

This is a code-golf competition so you should aim to minimize your size of your source code, as measured by bytes.

Test Cases

(()())     -> ()(()), (())()
(()(())()) -> (()(())())
((())())() -> (()(()()))

Haskell, 124 120 119 117 113 110 109 106 105 104 101 98 bytes

4 bytes saved thanks to bartavelle!

3 bytes saved thanks to Zgarb

1 byte saved thanks to Peter Taylor

Here's a solution I worked out in Haskell.  Its ok right now pretty good thanks to some help I received, but I'm looking to make this shorter, so feedback/suggestions are appreciated.

until(!0)g.map d
_!1=1<0
('(':a)!x=a!(x-1)
(_:a)!x=a!(x+1)
_!_=1>0
g(a:b)=b++[a]
d '('=')'
d _='('

Try it online!

Explanation

This program defines 4 functions,  the first (!) determines if a string is balanced.  Its defined as follows:

_!1=1<0
('(':a)!x=a!(x-1)
(_:a)!x=a!(x+1)
_!_=1>0

This check assumes that the input has an equal number of open and close parens thanks to a suggestion from Peter Taylor.

The next g will rotate the string once.

g(a:b)=b++[a]

Then we have d which simply takes a paren and mirrors it

d '('=')'
d _='('

Finally we have the function we are concerned with. Here we use a pointfree representation of until(!0)g composed with map d, which maps d to the input and applies g until the result is balanced.  This is the exact process described in the question.

until(!0)g.map d


Coding a recursive function for highest possible input Challenge
You are given the following function:-  which is the same as:-

with the base cases q(r, b, L) = 1 whenever r ≤ L, q(r, 0, L) = 0, if r > L and  q(r, 0, L) = 1, if r ≤ L.
Your task is to code a program that takes r as input, and outputs the value of q(r, r - L, L) for all L taking integer values from 1 to (r-1), where r is any nonnegative integer.
Example 1
Input

Enter the value of r: 2

Output

q(2,1,1) = 0.3333333333

Example 2
Input

Enter the value of r: 3

Output

q(3,2,1) = 0.1
q(3,1,2) = 0.5

Winning criterion
The code that can correctly output q(r, r-L, L) for all L taking integer values from 1 to (r-1), for the highest value of r, in less than 300 seconds. In case of a tie, the code with lesser runtime will be considered. As this is a runtime-based challenge, I shall test all submissions on my machine.

Java

I've applied some algebraic transformation and dynamic programming.

public class CodeGolf42234 {
    public static void main(String[] args) {
        int r = Integer.parseInt(args[0]);
        for (int L = 1; L < r; L++) System.out.println(qDouble5(r, r-L, L));
    }

    private static double qDouble5(int _r, int _b, int L) {
        double[][] q = new double[_r+1][_b+1];
        for (int r = 0; r <= L; r++) {
            for (int b = 0; b < q[r].length; b++) q[r][b] = 1;
        }
        for (int r = L + 1; r < q.length; r++) {
            for (int b = 1 + (r - L - 1)/L; b < q[r].length; b++) {
                double sum = 0, m = 1;
                for (int k = 0; k <= L; k++) {
                    sum += m * q[r-k][b-1];
                    m = m * (r - k) / (r + b - 1 - k);
                }
                q[r][b] = sum * b / (r + b);
            }
        }
        return q[_r][_b];
    }
}


Out-of-Control Rounding Errors Background

You have recently been hired by a small accounting firm.
The world of accounting is somewhat foreign to you, so you're not sure whether you are following all the professional guidelines.
In particular, you don't know when you should round all those numbers, and in which direction, so most of the time you just wing it and hope for the best.

Input

Your input is a single string that represents a simple calculation.
It contains some number of nonnegative integers delimited by the characters +-*/.
The string reads from left to right, and the normal precedence rules are ignored, so "23+1*3/4" means "start with 23, add 1, multiply by 3, and divide by 4", the result being 18.
The input will not contain numbers that start with 0 (except 0 itself), nor a division by zero.

Output

At each stage of the calculation, you can either round the result up or down to the nearest integer, or keep it as it is.
Finally, you round either up or down to obtain a integer result.
Your output is the list of integers that may result from such a calculation, sorted and without duplicates.

Rules

You can write either a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.

Test Cases

"42" -> [42]
"2+0+4-0" -> [6]
"23+1*3/4" -> [18]
"5/2" -> [2,3]
"5/2+7/3*6-1" -> [17,18,19,23]
"23/2/2*30-170/3" -> [-7,-6,-2,-1,0,1,3,4]
"1/3*2*2*2*2*2*2" -> [0,16,20,21,22,24,32,64]
"1/3*9" -> [0,3,9]

J, 84 bytes

Starting from a 1 element list the function keeps all the possible intermediate numbers in the list by evaling the next expression and adding it's up and down rounded copies.

Will golf further and add explanation tomorrow.
Can't find obvious ways to golf it more.

f=.3 :'/:~~.<.>((,>.,<.)@".@(":@],''x'',;@[))&.>/|.(>@{.;_2<\}.);:y rplc''/'';''%'''

Passes all the tests.

Usage:

   f '1/3*2*2*2*2*2*2'
0 16 20 21 22 24 32 64
   f '1/3*9'
0 3 9

Try it here.


Get rid of whitespace on otherwise empty lines Ah, yet another of my selfish uses of this Stack.
Being a Chromebook owner, I'm a frequent user of the Ace IDE, the editor used by Cloud9. It has lots of tools for dealing with excess whitespace, but it notably lacks one: clearing empty lines.
Your mission today is, given an input from a place I can copy-paste to [;)], output something identical, save all spaces and tabulators on otherwise empty lines.
I'll give some examples, with #s representing whitespace characters to be removed.

INPUT 1:
if (this.Color !== 'blue') {
##
  this.Color = 'blue';
}

OUTPUT:
if (this.Color !== 'blue') {
[empty line]
  this.Color = 'blue';
}

INPUT 2:
function outputSomething(times) {
  for (var iter = 0; iter < times; iter++) {
    console.log('"# # " represents a tabulator');
    // This is a comment
# #
}}

OUTPUT:
function outputSomething(times) {
  for (var iter = 0; iter < times; iter++) {
    console.log('"# # " represents a tabulator');
    // This is a comment
[empty line]
}}

INPUT 3:
var x = 'Do you prefer spaces or tabs?';
var y = 'I\'m using both here. Sue me.';
# # ####
console.log(x + ' ' + y);

OUTPUT:
var x = 'Do you prefer spaces or tabs?';
var y = 'I\'m using both here. Sue me.';
[empty line]
console.log(x + ' ' + y);

You may process the input however you like. Output wherever, so long as I can copy-paste from it [;)].
Standard loopholes apply, shortest answer in bytes wins!

Retina, 5 bytes

%G`\S

Try it online!

A not so obvious approach rewards us with a better score :)

Explanation

G indicates this as a Grep stage, keeping only those lines where a match to the regex given (\S, matches non-space characters) can be found. If it wasn't for the starting % this would completely remove lines instead of just "emptying" them.

The % is a modifier which applies the stage once to each line and then joins the results with newlines: in our case this means that the empty string returned by Grep for whitespace-only lines will become an empty line in the result.


Tribute to John Conway: Collatz in FRACTRAN John Horton Conway was a brilliant mathematician. Among his contributions were three Turing-complete esolangs: Game of Life (esolangs wiki), FRACTRAN (esolangs wiki), and Collatz function (esolangs wiki).

Because we did an extremely amazing job around GoL, it is time for the challenge with the other two.

Background

A FRACTRAN program consists of an ordered list of fractions. The program starts by taking a single integer as input. Each iteration of the program, it searches the list for the first fraction such that multiplying the number by that fraction produces another integer. It then repeats this process with the new number, starting back at the beginning of the list. When there is no fraction on the list that can be multiplied with the number, the program terminates and gives the number as the output.

A Collatz sequence is defined as the following: given a positive integer \$n\$,

$$
\begin{align}
a_0 &= n \\
a_{i+1} &= \begin{cases}
a_i/2,  & \text{if $a_i$ is even} \\
3a_i+1, & \text{if $a_i$ is odd}
\end{cases}
\end{align}
$$

It is conjectured that, for every positive integer \$n\$, the sequence eventually reaches 1.

Task

Write a FRACTRAN program that takes \$p^n\$ as input (for a prime \$p\$ of your choice) and halts if and only if the Collatz sequence starting at \$n\$ reaches 1.

You may see Avi F. S.'s COLLATZGAME as an example. Also, TIO has an implementation of FRACTRAN, so you can test your program with it. (Enter the starting number in the Arguments section; it accepts base-exponent form e.g. 2^27 as well as plain integer form.)

The shortest program in terms of the number of fractions wins.

9 8 7 fractions

$$\frac{5}{4}, \frac{63}{22}, \frac{14}{55}, \frac{66}{35}, \frac{1}{7}, \frac{2}{3}, \frac{44}{5}$$

Takes input as \$3^n\$.

Try it online!

How it works

The first transition is

$$3^n \xrightarrow{\frac{2}{3}} 2 \cdot 3^{n - 1},$$

which we will consider the “real” representation of the number \$n\$, because some intermediate control flows will bypass the above transition.

If \$n = 1\$, the program now halts immediately.

If \$n = 2k\$ is even, we have

$$\begin{multline*}
2 \cdot 3^{2k - 1}
\xrightarrow{\frac{2}{3}}
2^2 \cdot 3^{2k - 2}
\xrightarrow{\frac{5}{4}}
3^{2k - 2} \cdot 5
\xrightarrow{\left(\frac{2}{3} \cdot \frac{2}{3} \cdot \frac{5}{4}\right)^{k - 1}}
5^k
\xrightarrow{\frac{44}{5}}
2^2 \cdot 5^{k - 1} \cdot 11
\\
\xrightarrow{\frac{5}{4}}
5^k \cdot 11
\xrightarrow{\frac{14}{55}}
2 \cdot 5^{k - 1} \cdot 7
\xrightarrow{\left(\frac{66}{35} \cdot \frac{5}{4} \cdot \frac{14}{55}\right)^{k - 1}}
2 \cdot 3^{k - 1} \cdot 7
\xrightarrow{\frac{1}{7}}
2 \cdot 3^{k - 1},
\end{multline*}$$

which represents \$\frac{n}{2}\$.

If \$n = 2k + 1\$ is odd, we instead have

$$\begin{multline*}
2 \cdot 3^{2k}
\xrightarrow{\left(\frac{2}{3} \cdot \frac{5}{4} \cdot \frac{2}{3}\right)^k}
2 \cdot 5^k
\xrightarrow{\frac{44}{5}}
2^3 \cdot 5^{k - 1} \cdot 11
\xrightarrow{\frac{5}{4}}
2 \cdot 5^k \cdot 11
\\
\xrightarrow{\frac{63}{22}}
3^2 \cdot 5^k \cdot 7
\xrightarrow{\left(\frac{66}{35} \cdot \frac{63}{22}\right)^k}
3^{3k + 2} \cdot 7
\xrightarrow{\frac{1}{7}}
3^{3k + 2}
\xrightarrow{\frac{2}{3}}
2 \cdot 3^{3k + 1},
\end{multline*}$$

which represents \$3k + 2 = \frac{3n + 1}{2}\$, which is two steps ahead of \$n\$.


N-bit Variation on Subset-Sum For another challenge I am writing, I need to verify that test cases are solveable with bounded integers. Specifically, I need to verify the following, for a non-empty array of integers A and an integer bit width n:

All integers a in A satisfy -2**(n-1) <= a < 2**(n-1) (representable with n-bit two's complement integers).
The length of A is less than 2**n.
The sum of A satisfies -2**(n-1) <= sum(A) < 2**(n-1).
All combinations of elements in A satisfy all of the above conditions.

Naturally, I've decided to outsource this problem to you!

Given an array of integers A and a positive integer bit width n, verify that A satisfies the conditions above.

Test Cases

[0, 0, 0], 2: True
[0, 0, 0, 0], 2: False (violates #2)
[1, 2, 3, 4, 5], 8: True
[1, 2, 3, 4, 5], 2: False (violates all conditions)
[1, 2, 3, 4, 5], 5: True
[-3, 4, 1], 4: True
[10, 0, -10], 4: False (violates #1 and #4)
[27, -59, 20, 6, 10, 53, -21, 16], 8: False (violates #4)
[-34, 56, 41, -4, -14, -54, 30, 38], 16: True
[-38, -1, -11, 127, -35, -47, 28, 89, -8, -12, 77, 55, 75, 75, -80, -22], 7: False (violates #4)
[-123, -85, 6, 121, -5, 12, 52, 31, 64, 0, 6, 101, 128, -72, -123, 12], 12: True

Reference Implementation (Python 3)

#!/usr/bin/env python3
from itertools import combinations
from ast import literal_eval

def check_sum(L, n):
  return -2**(n-1) <= sum(L) < 2**(n-1)

def check_len(L, n):
  return len(L) < 2**n

def check_elems(L, n):
  return all(-2**(n-1) <= a < 2**(n-1) for a in L)

A = literal_eval(input())
n = int(input())
OUTPUT_STR = "{}, {}: {}".format(A, n, "{}")

if not (check_elems(A, n) and check_len(A, n) and check_sum(A, n)):
  print(OUTPUT_STR.format(False))
  exit()

for k in range(1, len(A)):
  for b in combinations(A, k):
    if not check_sum(b, n):
      print(OUTPUT_STR.format(False))
      exit()

print(OUTPUT_STR.format(True))

Try it online!

Wolfram Language (Mathematica), 40 bytes

Max[x=2Tr/@Subsets@#,-x-1,Tr[1^#]]<2^#2&

Try it online!

Condition 1 is implied by checking condition 3 for all subsets, including the one-element ones. So we take the max of

twice the sum of each subset,
one less than twice the negative of the sum of each subset, and
the length of the whole set

and check if that's less than 2^#2 (where #2 is the bit-width input).

At the cost of only 6 more bytes, we can replace Subsets@# with GatherBy[#,Arg], which is much more efficient because it computes only the two worst-case subsets: the subset of all nonnegative values, and the subset of all negative values. (This works because Arg has a value of 0 on the former and π on the latter.)


Let's Play Hide and Seek! The user will hide, and the computer will try to find them.

First, the program will take an input, for the size of the grid. Like 5x5, 10x10, 15x15, etc. The grid won't always be a perfect square.

The grid is sort of like a chessboard:

_______________________________
|     |     |     |     |     |
| A1  |     |     |     |     | A
|_____|_____|_____|_____|_____|
|     |     |     |     |     |
|     | B2  |     |     |     | B
|_____|_____|_____|_____|_____|
|     |     |     |     |     |
|     |     | C3  |     |     | C
|_____|_____|_____|_____|_____|
|     |     |     |     |     |
|     |     |     | D4  |     | D
|_____|_____|_____|_____|_____|
|     |     |     |     |     |
|     |     |     |     | E5  | E
|_____|_____|_____|_____|_____|
   1     2     3     4     5

Now, the user will pick a square, such as B2 (without telling the computer)

The computer will start guessing squares. If it picks the correct square, the user will respond with y. If not, they will input the direction their tile is from the one picked (N, NE, E, SE, S, SW, W).

So if the user picked B2, and the computer guessed C3, the user would input NW.

Here is an example of the outputs and inputs:

Grid?
5x5

C3?
NW

C2?
N

B2?
y

Scoring:

This will be scored a little differently than a normal challenge.

The winner is the program that takes lowest number of guesses  (on average) it takes to guess the correct square. The test cases to be averaged will be all of the possible squares in a 5x5 and then in a 10x10.

However, it must also work with every pattern of grid up to 26 rows (i.e. 5x8, 6x2, 20x5, etc.).

Please include a way for it to be tested, such as a JSFiddle.

And lastly, in case of a tie, the shortest program wins.

Python 3.6, 466 398 392 bytes, minimax

x, y = 1, 1
w, h = [int(x) for x in input('Grid?\n').split('x')]

def split_factor(a, b):
    N = b-y
    W = a-x
    S = h+~N
    E = w+~W
    return max(1, N, W, S, E, N*W, S*W, S*E, N*E)

def move(a, b):
    *Z, = zip([a, x, a, a+1, x, x, a+1, a+1],
              [y, b, b+1, b, y, b+1, b+1, y],
              [1, a-x, 1, w+x+~a, a-x, a-x, w+x+~a, w+x+~a],
              [b-y, 1, h+y+~b, 1, b-y, h+y+~b, h+y+~b, b-y])
    return Z[['N', 'W', 'S', 'E', 'NW', 'SW', 'SE', 'NE'].index(d)]

d = ''
while d != 'y':
    print()
    splits = {(a, b): split_factor(a, b) for a in range(x, x+w) for b in range(y, y+h)}
    a, b = min(splits, key=splits.get)
    d = input(f'{a}{"ABCDEFGHIJKLMNOPQRSTUVWXYZ"[b]}?\n')
    x, y, w, h = move(a, b)

Input and output should be in the form shown in the example. This finds the square with the minimal "split factor"--which is the largest remaining area that can result from the player's answer (i.e. NW, E, y, etc.)--and guesses that. Yes, that's always the center of the remaining area in this game, but this technique of minimizing the worst-case will work more generally in similar games with different rules.

Unreadable version:

x=y=d=1
w,h=map(int,input('Grid?\n').split('x'))
while d!='y':print();s={(a,b):max(b-y,h+y+~b)*max(w+x+~a,a-x)for a in range(x,x+w)for b in range(y,y+h)};a,b=min(s,key=s.get);d=input(f'{a}{chr(64+b)}?\n');*z,=zip([a+1,x,a+1,x,a,a,a+1,x],[b+1,b+1,y,y,b+1,y,b,b],[w+x+~a,a-x,w+x+~a,a-x,1,1,w+x+~a,a-x],[h+y+~b,h+y+~b,b-y,b-y,h+y+~b,b-y,1,1]);x,y,w,h=z[~'WENS'.find(d)or-'NWNESWSE'.find(d)//2-5]


Sample space of n consecutive coin flips Taking a positive integer n as input, print the sample space of n consecutive coin flips. The coin is fair, with two sides H and T, each with probability 0.5.
For example,
Input - 3
Output -
HHH
HHT
HTH
HTT
THH
THT
TTH
TTT

Rules

Standard loopholes apply
You may print the elements out of order, but all of them should be present.
You may use any form of output, as long as heads and tails are displayed as 'H' and 'T', and all elements are distuinguishable.

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

Jelly, 4 bytes
⁾HTṗ

A monadic Link accepting a non-negative integer which yields a list of characters.
Try it online! (footer calls the Link and joins with newline characters)
How?
⁾HTṗ - Link: integer, n
⁾HT  - list o characters = ['H', 'T']
   ṗ - (that) Cartesian power (n)


How many ways to write numbers as sums of squares? Task
Given two integers \$d\$ and \$n\$, find the number of ways to express \$n\$ as a sum of \$d\$ squares. That is, \$n = r_1^2 + r_2^2 + ... + r_d^2\$, such that \$r_m\$ is an integer for all integers \$1 ≤ m ≤ d\$. Note that swapping two different values (e.g. \$r_1\$ and \$r_2\$) is considered different from the original solution.
For instance, the number 45 can be written as a sum of 2 squares 8 different ways:
$$\begin{align}
& 45 \\
& = (-6)^2 + (-3)^2 \\
& = (-6)^2 + 3^2 \\
& = (-3)^2 + (-6)^2 \\
& = (-3)^2 + 6^2 \\
& = 3^2 + (-6)^2 \\
& = 3^2 + 6^2 \\
& = 6^2 + (-3)^2 \\
& = 6^2 + 3^2
\end{align}$$
Rules

Built-in solutions are allowed but non-competing (ahem, Mathematica)
Standard loopholes are also forbidden.
The inputs may be reversed.

Example I/O
In:   d, n

In:   1, 0
Out:  1

In:   1, 2
Out:  0

In:   2, 2
Out:  4

In:   2, 45
Out:  8

In:   3, 17
Out:  48

In:   4, 1000
Out:  3744

In:   5, 404
Out:  71440

In:   11, 20
Out:  7217144

In:   22, 333
Out:  1357996551483704981475000

This is code-golf, so submissions using the fewest bytes win!

Python 3, 125 bytes

n,d=eval(input())
W=[1]+[0]*n
exec("W=[sum(-~(j>0)*W[i-j*j]for j in range(int(i**.5)+1))for i in range(n+1)];"*d)
print(W[n])

Try it online!

Finishes the last testcase in 0.078 s. Naive complexity is O(d n 2).


Polycops and Robbers (Cops' Thread) This is the cops' thread, the robbers' thread is here
A polyglot is a program, that without modification, can run in multiple languages.

Allowed languages
Any language that was made before the challenge and isn't made for the purpose of the challenge, it is allowed, though discouraged, to use languages that are easy to recognize

Cops' Challenge
To write a non-empty program that does one of the following tasks:

Adds two numbers from STDIN
Prints "Hello, World!"
Prints the first 20 terms of the Fibonacci sequence

Then, list the languages it works in (it must do the same thing in all languages). When you first post your answer, it is vulnerable, and robbers will try to find more languages it works in other than the ones you specified. If any robber finds a language, they comment on your question saying they cracked it. You should then edit your question saying it got cracked and list the languages you were missing.

If a week passes by and nobody cracked your submission, you can mark it as safe, no robbers can crack it.

Winning
Most upvoted safe answer is the winner.

Extra rules
Cops must know there is a language that the program runs in other than the ones they wrote, so that there's a guarantee that all answers are possible to crack.
And as always, standard loopholes apply.

Wow, cracked by Jo King while I'm still typing the explanations lol

'<?php '//'; #@ SPELL,WITH,ME, ,H,E,L,L,O, ,W,O,R,L,D,"'Hello, World!'"
$a = "'Hello, World!'";
if ([])
 console.log($a);
else {
 for ($i = 1; $i < strlen($a) - 1; $i++)
  echo($a[$i]);
}
// ?>'

Prints 'Hello, World!' (with single quotes) in both JavaScript and PHP. This should be an easy one to solve.
How this works
'<?php '//'; #@ SPELL,WITH,ME, ,H,E,L,L,O, ,W,O,R,L,D,"'Hello, World!'"
JS treats this line as a string '<?php ' followed by a // comment, and PHP prints ' (outside the tag, so literally), then starts the script with open tag, and a string '//', then a # comment.
$a = "'Hello, World!'";
Both JS and PHP defines the variable a to be the string "'Hello, World!'".
if ([])
 console.log($a);

In JS, since [] is consider truly, console.log($a) is executed and this prints out the string `"'Hello, World!'".
else {
 for ($i = 1; $i < strlen($a) - 1; $i++)
  echo($a[$i]);
}

In PHP, since [] is consider falsy, the for loop is executed and this prints out the characters Hello, World! (notice the absence of quotes) subsequently.
// ?>'
In JS this is a comment, but in PHP the close tag ends the script and the ' after the tag is printed out literally.

Yes, the remaining language is Befunge-93.
'<?php '//'; #@ SPELL,WITH,ME, ,H,E,L,L,O, ,W,O,R,L,D,"'Hello, World!'"
< redirects the IP to the end of the line, then "'Hello, World!'" is pushed in reversed order. After that the 15 ,s are used to output the characters (in normal order because of the double reversal). Finally @ terminates the program.


Construct a companion matrix You have a number of polynomials who are lonely, so make them some companions (who won’t threaten to stab)!

For a polynomial of degree n,  there is an n by n companion cube matrix for it. You need to make a function that accepts a list of coefficients for a polynomial in either ascending (a + bx +cx^2 + …) or descending (ax^n + bx^(n-1) + cx^(n-2)+…) order (but not both) and output the companion matrix.

for a polynomial c0 + c1x + c2x^2 + ... + cn-1x^(n-1) + x^n,
its companion matrix is

     (0, 0, 0, ..., -c0  ),
     (1, 0, 0, ..., -c1  ),
     (0, 1, 0, ..., -c2  ),
     (...................),
     (0, 0, ..., 1, -cn-1)

note that the coefficient for x^n is 1. For any other value, divide all the rest of the coefficients by x^n's. Additionally, the 1's are offset from the diagonal.

If the language you’re using already contains a function or module that does this, you can’t use it – you must write your own.

For instance, if you had 4x^2 – 7x + 12, the coefficients in ascending order are (12, -7, 4) and descending order (4, -7, 12). The function or program should output [(0, -3.0), (1, 1.75)] for either order. Specify which order your code accepts. Minimum polynomial should be a quadratic. Coefficients are restricted to real numbers.

Below are examples – your output does not have to match the pretty formatting but it should output the rows (in the ()) of the matrix in order.

Ascending order:

input:
    [3., 7., -5., 4., 1.]
output:
    [(0, 0, 0, -3.),
     (1, 0, 0, -7.),
     (0, 1, 0,  5.),
     (0, 0, 1, -4.)]

input:
    [-4., -7., 13.]
output:
    [(0, 0.30769231),
     (1, 0.53846154)]

input:
    [23., 1., 92., 8., -45., 88., 88.]
output:
    [(0, 0, 0, 0, 0, -0.26136364),
     (1, 0, 0, 0, 0, -0.01136364),
     (0, 1, 0, 0, 0, -1.04545455),
     (0, 0, 1, 0, 0, -0.09090909),
     (0, 0, 0, 1, 0,  0.51136364),
     (0, 0, 0, 0, 1, -1.        )]

Descending order:

input:
    [1., 4., -5., 7., 3.]
output:
    [(0, 0, 0, -3.),
     (1, 0, 0, -7.),
     (0, 1, 0,  5.),
     (0, 0, 1, -4.)]

input:
    [13., -7., -4.]
output:
    [(0, 0.30769231),
     (1, 0.53846154)]

input:
    [88., 88., -45., 8., 92.,1., 23.]
output:
    [(0, 0, 0, 0, 0, -0.26136364),
     (1, 0, 0, 0, 0, -0.01136364),
     (0, 1, 0, 0, 0, -1.04545455),
     (0, 0, 1, 0, 0, -0.09090909),
     (0, 0, 0, 1, 0,  0.51136364),
     (0, 0, 0, 0, 1, -1.        )]

Dennis wins with 20 bytes!

CJam, 32 31 28 bytes

0q~)f/f-_,(_,\0a*1+fm<~]W%z

Try it online

This takes the input in ascending order, using the CJam list format. Sample input:

[-4.0 -7.0 13.0]

Explanation:

0     Push a 0 for later sign inversion.
q~    Get and interpret input.
)     Pop off last value.
f/    Divide all other values by it.
f-    Invert sign of values.
_,    Get count of values, which corresponds to n.
(     Decrement by 1.
_,    Create list of offsets [0 1 ... n-1] for later.
\     Swap n-1 back to top.
0a*   Create list of n-1 zeros.
1+    Append a 1. This is the second-but-last column [0 0 ... 0 1].
fm<   Apply rotation with all offsets [0 1 ... n-1] to column.
~     Unwrap the list of 0/1 columns.
]     Wrap all columns
W%    Invert their order from last-to-first to first-to last.
z     Transpose to get final matrix.
`     Convert to string for output.


All your base palindromic belong to us Generate the sequence number of bases in which n is a palindrome (OEIS A126071).

Specifically, the sequence is defined as follows: given a number n, express it in base a for a = 1,2, ..., n, and count how many of those expressions are palindromic. "Palindromic" is understood in terms of reversing the base-a digits of the expression as atomic units (thanks, @Martin Büttner). As an example, consider n= 5:

a=1: the expression is 11111: palindromic
a=2: the expression is 101: palindromic
a=3: the expression is 12: not palindromic
a=4: the expression is 11: palindromic
a=5: the expression is 10: not palindromic

Therefore the result for n=5 is 3. Note that OEIS uses bases 2, ..., n+1 instead of 1, ..., n (thanks, @beaker). It's equivalent, because the expressions in base 1 and n+1 are always palindromic.

The first values of the sequence are

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

Input is a positive integer n. Output is the first n terms of the sequence.

The program should theoretically work (given enough time and memory) for any n up to limitations caused by your default data type in any internal computations.

All functions allowed. Lowest number of bytes wins.

Pyth, 13 bytes
mlf_ITjLdSdSQ

The brevity of this is mostly due to the Invaluable "Invariant" command.
msf_ITjLdSdSQ       implicit: Q=input
m         d         map lambda d over
           SQ       Inclusive range 1 to Q
      jLdSd         Convert d to all the bases between 1 and d
  f                  filter lambda T:
   _IT                 is invariant under reverse
 l                  number that are invariant under reverse

If True is an acceptable output for 1, msm_IjdkSdSQ (12 bytes) works.
Try it here.


Build a program that creates a minimal one-ohm resistor diagram for a given resistance You are a contractor for a company who designs electrical circuits for the various products they make. One day, the company accidentally gets a huge shipment of one-ohm resistors and absolutely nothing else, and give you the task of putting them to good use in the newest products they're making.

Your task is to build a program that takes a positive rational number as input, in the following form:

a / b

and return a resistor diagram with the exact given resistance, that uses as few one-ohm resistors as possible.

Your resistor diagram will consist of:

The number N, to denote how many SPTs there are. (I will describe an SPT below.)
N lines, each containing two numbers A and B representing numbered electrodes on a circuit board, followed by one SPT.
One line containing two numbers P and Q denoting which two electrodes to measure the resistance between.

An SPT is a "series-parallel tree", a way to describe a series-parallel circuit in a tree format.

A valid SPT is either:

The number 1, representing a single resistor.
S( ), enclosing a number followed by zero or more P( ) SPTs.
P( ), enclosing a number followed by zero or more S( ) SPTs.

Examples of valid SPTs:

1 <- has a resistance of 1
S(1) <- equivalent to 1 and P(1)
S(2, P(3)) <- has a resistance of 7/3, using 5 resistors
P(1, S(2), S(3), S(4, P(2))) <- has a resistance of 18/37, using 12 resistors

Examples of invalid SPTs:

2 <- the two resistors are in an unknown configuration. Use P(2) or S(2) instead.
P(2, P(1)) <- use P(3) instead.
P(4, P(1, S(3), S(2))) <- use P(5, S(3), S(2)) instead.

Specifications

Your program must work for any numerator and denominator up to 150 000.

Your program's source code, excluding any imported standard or third-party libraries, must not exceed one megabyte (1,048,576 bytes) total.

Your program will be tested on a specific, randomly chosen set of 10,000 fractions (to be determined at a later date), and scored on how few resistors it requires to build all 10,000 circuits. The program that uses the fewest resistors is the winner.

Testing data

The input

3 / 8

might return

1
1 2 S(0, P(8), P(4))
1 2

to represent a series of 8 resistors and then 4 resistors in parallel. This may not be the optimal solution; but for the purposes of this problem, it is valid output.

The input

5 / 6

might return:

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

to represent a cube of one-ohm resistors with vertices numbered 1 through 8, having its resistance measured between opposite corners. Of course it is possible to just do S(P(2), P(3)) using just five resistors, but this is an example of how the notation is used to represent non-series-parallel diagrams.

For series-parallel circuits with few resistors, the resistances which can be created with n resistors but not with fewer are the numbers on the nth level of the Stern-Brocot tree. (This breaks later on, with 5/6 = 1/2 + 1/3 apparently a minimal counterexample).

Instead of mapping from position in the Stern-Brocot tree to an S-P expression, it turns out to be much more convenient to use the Calkin-Wilf tree; its nodes at a given depth are permutations of the Stern-Brocot tree's nodes at that depth, but it has a different parent-child relationship: the left child of m/n is m/(m+n) = (1^-1 + (m/n)^-1)^-1 = P(1, m/n), and the right child of m/n is (m+n)/n = 1 + m/n = S(1, m/n).

GolfScript

# Parse input
'/'/' '*~
# Stack: numerator denominator
{
    # numerator denominator
    1$1$<{
        # n/d is less than 1, so parent is n/(d − n) and we're looking at Parallel
        ', P('@@.2$/@@1$%
        # ', P(' d/n n d%n
    }{
        # n/d >= 1, so parent is (n - d)/d and we're looking at Series
        ', S('@@1$1$/@2$%@
        # ', S(' n/d n%d d
    }if
    # Loop until we get to 0/1 or 1/0
    1$1$*
}do;;
# Stringify
]''*
# Trim leading ', '
2>.
# Close the parentheses
'('/,(')'*+
# Add the boilerplate
'1
0 1 '\'
0 1'


Cubify This! A lesson in grayscale... er... color... er... whatever Being a big fan of the Rubik's cube and of cool art, I've been working on combining the two together to do some really cool stuff. Basically solving miniature Rubik's cubes to form rudimentary pixels in the formation of Rubik's cube art. Examples of such art can be seen via this link: http://google.com/search?q=rubik%27s+cube+art

Now, the purpose of this Code Golf is to create code that accepts an image as input, and then converts it in the following manner:

The image is initially reduced to web-safe grayscale colors. The reason behind this is because we need to isolate the web-safe grayscale palette (i.e. 000000, 333333, 666666, 999999, CCCCCC, and FFFFFF). An algorithm on the colorimetric method of converting to grayscale is available at: http://en.wikipedia.org/wiki/Grayscale#Colorimetric_.28luminance-preserving.29_conversion_to_grayscale, should you wish to use that as inspiration.

One would then render out the grayscale to the appropriate colors. To break it down quickly:
000000 will refer to Rubik's blue, 333333 will refer to Rubik's red, 666666 will refer to Rubik's green, 999999 will refer to Rubik's orange, CCCCCC will refer to Rubik's yellow, and FFFFFF will refer to Rubik's white.

I would rather that your resulting code can render from the photo's palette straight to Rubik's colors. The two-stage method from converting to web-safe grayscale and then to the corresponding Rubik's palette is just to give you an idea on the logic behind the process, but if it is easier for you to do this, by all means do so.

The actual RGB values for the Rubik's palette must correspond to the following:

Red: #C41E3A
Green: #009E60
Blue: #0051BA
Orange: #FF5800
Yellow: #FFD500
White: #FFFFFF

To give you an example, I have cropped Abraham Lincoln's head from the following picture: , and rendered the algorithm to produce the following:

The grid is there so that you can see how each individual miniature Rubik's cube would have to be configured to make up the image. The true size of the resulting image is 45 pixels by 45 pixels, meaning (45/3) * (45/3) = 15 * 15 = 225 miniature Rubik's cubes would be used to make this image. I am not expecting you to present the resulting image with a grid as I have.

So this is what's required:

The image to be processed by this algorithm must be x pixels wide by y pixels high, such that x and y are multiples of 3. This is to aid with the ease of rendering as part of a Rubik's cube mosaic. If your image is quite large, reducing it to something around the 45 x 45 to 75 x 75 or thereabouts in dimensions prior to processing is advised. Bear in mind, this resizing component is OPTIONAL.
The image needs to be converted to the sextacolored Rubik's cube palette to create the mosaic.
The resulting image needs to be a valid graphic file after processing. To prove your code works, run it against an image of one of the presidents of the United States of America, or a well known Hollywood celebrity. I have already used Abraham Lincoln in my example, so this president can no longer be used. Ensure that you provide the language you have used, the byte count as well as the president/celebrity used to test your code, including before and after shots...
Each entry must have a unique president/celebrity as their test case. I will not accept duplicates. This will ensure that duplicate results are not used to test different code entries. It's all very well to say that your code works, it's another thing to prove it.

5. Shortest code wins.

I'm changing this to a popularity contest... I'd rather see who can do this without having to compete on byte count... So I'll award this along with a bounty after the 28th of February, 2014.

Imagemagick (108)

Version: ImageMagick 6.8.7-7 Q16 x86_64 2013-11-27

The following call:

$ convert -resize 75x75 -fx "q=p.intensity;q<1/6?#0051BA:q<2/6?#C41E3A:q<3/6?#009e60:q<4/6?#ff5800:q<5/6?#FFD500:#FFF" input output

where input and output have to be modified for the input and output filename.

I only counted the chars between -resize and #FFF", if you think this is invalid feel free to comment.

I used Lenna as image (she appeared in a Playboy, and anyone doing that should count as a Hollywood celebrity, right?)

Input:

Output:

$ convert -resize 75x75 -fx "q=p.intensity;q<1/6?#0051BA:q<2/6?#C41E3A:q<3/6?#009e60:q<4/6?#ff5800:q<5/6?#FFD500:#FFF" Lenna.png LennaRubik.png

Output enlarged:

Notes: according to the imagemagick docs you cannot have more than one conditional operator in a statement, but the call still seems to work fine, so probably this was fixed and the docs were just not updated.

Running identify on the result image (to show the colors are indeed fine):

$ identify -verbose LennaRubik.png
  (...)
  Colors: 6
  Histogram:
       338: (  0, 81,186) #0051BA srgb(0,81,186)
      1652: (  0,158, 96) #009E60 srgb(0,158,96)
      1187: (196, 30, 58) #C41E3A srgb(196,30,58)
      1674: (255, 88,  0) #FF5800 srgb(255,88,0)
       706: (255,213,  0) #FFD500 srgb(255,213,0)
        68: (255,255,255) #FFFFFF white
  (...)

If you think Lenna doesn't count as a proper celebrity, here is Bruce Willis:


Output the next kana Japanese kana characters correspond to a single sound in the Japanese language. With the exception of ん (n), every other kana consists of a consonant part and a vowel part. There is a natural ordering to Japanese kana, a sort of "alphabetical order", which is typically arranged in a 10 by 5 table:

   |   a    i    u    e    o
-----------------------------
*  |   a    i    u    e    o
k  |  ka   ki   ku   ke   ko
s  |  sa   si   su   se   so
t  |  ta   ti   tu   te   to
n  |  na   ni   nu   ne   no
h  |  ha   hi   hu   he   ho
m  |  ma   mi   mu   me   mo
y  |  ya        yu        yo
r  |  ra   ri   ru   re   ro
w  |  wa                  wo

This ordering is called gojuuon, or "fifty sounds", even though some of the fifty cells in the table are in fact empty.

The challenge

Input will be any of the listed kana above, with the exception for wo. Your program or function should output the next kana along in left-to-right, top-to-bottom reading order, e.g:

Input       Output
------------------
a     ->    i
i     ->    u
o     ->    ka
ke    ->    ko
so    ->    ta
ni    ->    nu
ya    ->    yu
yu    ->    yo
wa    ->    wo
wo    ->    (undefined behaviour)

With the exception of an optional single trailing newline, there should be no leading or trailing whitespace in the output.

This is code-golf, so the goal is to minimise program size, in bytes.

Additional notes

In order to keep things simple, this challenge uses Nihon-shiki romanisation. Hepburn romanisation is more common, but has a few kinks which make things more annoying for golf (e.g. si becomes shi, hu becomes fu).
Kana do exist for the empty spots (see Japanese SE), but they were either non-standard or are now obsolete.

Retina, 54 53 bytes

T`au`ie`y.
wa
we
T`\oeuia`ao
T`ko`stn\hmyr\w`.a
^a
ka

Try it online.

Explanation

Wooo, showing off even more features from today's 0.7.2 release. :) (The release predates this challenge by about 7 hours.)

T`au`ie`y.

This is a transliteration which replaces a with i and u with e, but only in matches of y.. The purpose of that is to treat ya and yu like yi and ye, respectively, in order to skip the gaps.

wa
we

Replace wa with we to skip that gap as well.

T`\oeuia`ao

Here is the new feature. When rotating sets of characters, the "from" and "to" set in a transliteration are usually almost identical. So now we've got o (without a backslash) to refer to the other set, which allows us to get rid of some duplication. The \o just stands for a literal o in that case. So the two sets expand to:

oeuia
aoeuia

The extraneous a in the second set is ignored and the vowels are replaced cyclically as expected.

T`ko`stn\hmyr\w`.a

This does the same thing for the consonants, but using o in the first set (just because we can...). h and w need escaping because they are character classes. The expanded sets are:

kstnhmyrw
stnhmyrw

The .a restricts this operation to syllables that end in a, i.e. those that wrap to the next line of the table.

^a
ka

Finally, we replace a single a with ka, because that case cannot be handled by the previous transliteration.


Straight Chain Alk*nes without Order This is much like my earlier challenge, except, this time, order doesn't matter.

A straight-chain alk*ne is defined as a sequence of carbon atoms connected by single (alkane), double (alkene), or triple bonds (alkyne), (implicit hydrogens are used.) Carbon atoms can only form 4 bonds, so no carbon atom may be forced to have more than four bonds. A straight-chain alk*ne can be represented as a list of its carbon-carbon bonds.

These are some examples of valid (not necessarily distinct) straight-chain alk*nes:

[]       CH4              Methane
[1]      CH3-CH3          Ethane
[2]      CH2=CH2          Ethene
[3]      CH≡CH            Ethyne
[1,1]    CH3-CH2-CH3      Propane
[1,2]    CH3-CH=CH2       Propene
[1,3]    CH3-C≡CH         Propyne
[2,1]    CH2=CH-CH3       Propene
[2,2]    CH2=C=CH2        Allene (Propadiene)
[3,1]    CH≡C-CH3         Propyne
[1,1,1]  CH3-CH2-CH2-CH3  Butane
...

While these are not, as at least one carbon atom would have more than 4 bonds:

[2,3]
[3,2]
[3,3]
...

Two straight-chain alk*nes, p and q are considered equivalent if p is q reversed, or p is q.

[1] = [1]
[1,2] = [2,1]
[1,3] = [3,1]
[1,1,2] = [2,1,1]
[1,2,2] = [2,2,1]

Your task is to create a program/function that, given a positive integer n, outputs/returns the number of valid straight-chain alk*nes of exactly n carbon atoms in length.

Specifications/Clarifications

You must handle 1 correctly by returning 1.
Alk*nes like [1,2] and [2,1] are NOT considered distinct.
Output is the length of a list of all the possible alk*nes of a given length.
You do not have to handle 0 correctly.

Test Cases:

1 => 1
2 => 3
3 => 4
4 => 10
5 => 18
6 => 42

This is code golf, so the lowest byte count wins!

JavaScript (ES6), 107 bytes

A=n=>n>9?2*A(n-1)+3*A(n-2)+3*A(n-7)+A(n-8)-5*A(n-3)-A(n-4)-2*A(n-6)-A(n-9):[0,1,3,4,10,18,42,84,192,409][n]

Recursive solution, using the recurrence relation that was pointed out in the comments of the question. Execution time rises much quicker than the input (complexity of O(9^N) if I'm not mistaken), so be careful with values higher than 20.


Balance chemical equations! Bernd is a high school student who has some problems in chemistry. In class he has to design chemical equations for some experiments they are doing, such as the combustion of heptane:

  C7H16 + 11O2 → 7CO2 + 8H2O

Since mathematics isn't exactly Bernd's strongest subject, he often has a hard time finding the exact ratios between the pro- and educts of the reaction. Since you are Bernd's tutor, it is your job to help him! Write a program, that calculates the amount of each substance needed to get a valid chemical equation.

Input

The input is a chemical equation without amounts. In order to make this possible in pure ASCII, we write any subscriptions as ordinary numbers. Element names always start with a capital letter and may be followed by a minuscule. The molecules are separated with + signs, an ASCII-art arrow -> is inserted between both sides of the equation:

Al+Fe2O4->Fe+Al2O3

The input is terminated with a newline and won't contain any spaces. If the input is invalid, your program may do whatever you like.

You may assume, that the input is never longer than 1024 characters. Your program may either read the input from standard input, from the first argument or in an implementation defined way at runtime if neither is possible.

Output

The output of your program is the input equation augmented with extra numbers. The number of atoms for each element must be the same on both sides of the arrow. For the example above, a valid output is:

2Al+Fe2O3->2Fe+Al2O3

If the number for a molecule is 1, drop it. A number must always be a positive integer. Your program must yield numbers such that their sum is minimal. For instance, the following is illegal:

40Al+20Fe2O3->40Fe+20Al2O3

If there is no solution, print

Nope!

instead. A sample input that has no solution is

Pb->Au

Rules

This is code-golf. The shortest code wins.
Your program must terminate in reasonable time for all reasonable inputs.

Test Cases

Each test case has two lines: An input and a correct output.

C7H16+O2->CO2+H2O
C7H16+11O2->7CO2+8H2O

Al+Fe2O3->Fe+Al2O3
2Al+Fe2O3->2Fe+Al2O3

Pb->Au
Nope!

C, 442 505 chars

// element use table, then once parsed reused as molecule weights
u,t[99];

// molecules
char*s,*m[99]; // name and following separator
c,v[99][99]; // count-1, element vector

i,j,n;

// brute force solver, n==0 upon solution - assume at most 30 of each molecule
b(k){
    if(k<0)for(n=j=0;!n&&j<u;j++)for(i=0;i<=c;i++)n+=t[i]*v[i][j]; // check if sums to zero
    else for(t[k]=0;n&&t[k]++<30;)b(k-1); // loop through all combos of weights
}

main(int r,char**a){
    // parse
    for(s=m[0]=a[1];*s;){
        // parse separator, advance next molecule
        if(*s==45)r=0,s++;
        if(*s<65)m[++c]=++s;
        // parse element
        j=*s++;
        if(*s>96)j=*s+++j<<8;
        // lookup element index
        for(i=0,t[u]=j;t[i]-j;i++);
        u+=i==u;
        // parse amount
        for(n=0;*s>>4==3;)n=n*10+*s++-48;
        n+=!n;
        // store element count in molecule vector, flip sign for other side of '->'
        v[c][i]=r?n:-n;
    }
    // solve
    b(c);
    // output
    for(i=0,s=n?"Nope!":a[1];*s;putchar(*s++))s==m[i]&&t[i++]>1?printf("%d",t[i-1]):0;
    putchar(10);
}

Run as:

./a.out "C7H16+O2->CO2+H2O"
./a.out "Al+Fe2O4->Fe+Al2O3"
./a.out "Pb->Au"

Results:

C7H16+11O2->7CO2+8H2O
8Al+3Fe2O4->6Fe+4Al2O3
Nope!


Random spanning tree of a rectangular grid Significantly harder version of Spanning tree of a rectangular grid.

Background

A spanning tree (Wikipedia) of an undirected graph is a subgraph that is a tree which includes all of the vertices of the original graph. The following is an example of a spanning tree of a 4-by-4 grid graph.

Task

Given two positive integers w and h, output a randomly generated spanning tree of the grid graph which has w vertices horizontally and h vertices vertically. Your program/function should be able to generate every possible spanning tree with nonzero probability.

One possible algorithm to solve this task is random minimum spanning tree, which calculates the minimum spanning tree of the given graph with randomized edge weights.

Input and output

The input is two positive integers w and h.

The output is a representation of a spanning tree. You can choose any representation that can describe such a graph without ambiguity, which includes (but is not limited to):

ASCII-formatted grid
A standard graph structure, e.g. adjacency matrix, adjacency list, incidence matrix...
A list of pairs of numbered vertices

Please specify the output format in your submission.

Scoring & winning criterion

The standard code-golf rules apply. The shortest valid submission in bytes wins.

Example I/O

w=3, h=2

ASCII grid

+-+-+
| |
+ +-+

Adjacency matrix

0 1 0 1 0 0
1 0 1 0 1 0
0 1 0 0 0 0
1 0 0 0 0 0
0 1 0 0 0 1
0 0 0 0 1 0

List-of-vertex-pairs representation

[(0, 1), (0, 3), (1, 2), (1, 4), (4, 5)]

or

[((0, 0), (0, 1)),
 ((0, 0), (1, 0)),
 ((0, 1), (0, 2)),
 ((0, 1), (1, 1)),
 ((1, 1), (1, 2))]

w=1, h=1

The graph is a single vertex with no edges, and its only spanning tree is the graph itself.

Wolfram Language (Mathematica), 146 bytes

Block[{c,g=GridGraph@{##}},Graph[Range[1##],Join@@Reap[Do[c@n/._c:>#0[Sow[#<->n];n],{n,RandomSample@AdjacencyList[g,c@#=#]}]&@1][[2]],Options@g]]&

Try it online!

Based on my answer to the question Maze Generation.

Returns a Graph object.

For example, w = 20, h = 20 gives:


How strong are nonary numbers? You are given a nonary (base 9) non-negative integer consisting of the digits 0 through 8 as usual. However the number of digits in this number (with no leading zeros) is a prefect square.

Because of this, the number can be arranged in a square grid (with the reading order still preserved).

Example with 1480 (1125 base 10):

14
80

Now let every digit in such a nonary grid indicate a motion to another grid space (with periodic boundary conditions):

432
501
678

This is saying that

0 = stay still
1 = move right
2 = move right and up
3 = move up
...
8 = move right and down

So, if in the 1480 grid you start at the 4, you then move up (remember pbc) and left to the 8, which means you move right and down back to the 4, starting a cycle with period 2.

In general this process is continued until you get to a 0 or a cycle is noticed. (A 0 is considered a cycle with period 1.)

In the case of 1480, the period eventually reached at each of the 4 starting digits is 2 2 2 1 respectively.

For a larger grid these numbers might be larger than 8, but we can still use them as "digits" in a new nonary number (simply the coefficients of 9^n as if they were digits):

2*9^3 + 2*9^2 + 2*9 + 1 = 1639 (base 10) = 2221 (base 9)

We will call this the strength of the original nonary number. So the strength of 1480 is 1639 (base 10) or, equivalently, 2221 (base 9).

Challenge

Write the shortest program that tells whether the strength of a nonary number is greater than, less than, or equal to the nonary number itself. (You do not necessarily need to compute the strength.)

The input will be a non-negative nonary number that contains a square number of digits (and no leading zeros besides the special case of 0 itself). It should come from the command line or stdin.

The output should go to stdout as:

G if the strength is larger than the original number (example: 1480 -> strength = 2221)
E if the strength is equal to the original number (example: 1 -> strength = 1)
L if the strength is less than the original number (example: 5 -> strength = 1)

Fun Bonus Challenge:
Whats the highest input you can find that is equal to its strength? (Is there a limit?)

Python 296
Not actually too inefficient, it only checks as many digits as it needs to.
n=raw_input();s=int(len(n)**.5);t=0
for i in range(s**2):
    l=[]
    while i not in l:l.append(i);c=n[i];i=(i%s+(-1 if c in'456'else 1 if c in'218'else 0))%s+((i/s+(-1 if c in'432'else 1 if c in'678'else 0))%s)*s
    t=t*9+len(l)-l.index(i)
print'EGL'[cmp(t,long(n,9))]

As for numbers equal to their strength, I think the only solutions are, for every N x N square up to N=8 a square containing N in every space. My thinking is that since every number in a loop must be the same number (the length of the loop) each loop would have to be all in one direction. This of course means that the loop's size must be N (and each element must be N). I'm pretty sure that this logic can be applied to squares and loops of any size, meaning there are no squares equal to their strength other than the first 8.


Count rectangle intersections The Challenge
Given an arbitrary amount of rectangles, output the total count of intersections of those when drawn in a 2D plane.
An intersection here is defined as a point P which is crossed by two lines which are orthogonal to each other and are both not ending in P.
Example
Each rectangle here is denoted by a 2-tuple with the coordinates of the upper left corner first and the coordinates of the bottom right corner second.

[(-8,6),(-4,-2)]
[(-4,9),(4,3)]
[(2,10),(14,4)]
[(1,7),(10,-6)]
[(7,4),(10,2)]
[(5,2),(9,-4)]
[(-6,-4),(-2,-6)]

Those rectangles create 6 intersections, which has to be your output.

As you can see in the image above, touching rectangles will not create intersections here and are not counted.
You can encode the rectagles in any format you want. Make it clear which format you use.
If multiple rectangles intersect at the same point, it only counts as one intersection.
The coordinates will always be integers.
There won't be any duplicate rectangles in the input.
You will always get at least one rectangle as input.
You may not use any builtins which solve this problem directly. Additionally you may not use builtins that solve equations. All other builtins are allowed.
The output has to be a single integer indicating the intersection count.

Rules

Function or full program allowed.
Default rules for input/output.
Standard loopholes apply.
This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Test cases
Same format as in the example above. The rectangles are wrapped in a list.

[[(-8,6),(-4,-2)],[(-4,9),(4,3)],[(2,10),(14,4)],[(1,7),(10,-6)],[(7,4),(10,2)],[(5,2),(9,-4)],[(-6,-4),(-2,-6)]] -> 6
[[(-2,2),(6,-4)]] -> 0
[[(-12,10),(-8,6)],[(-14,6),(-10,2)],[(-10,6),(-6,2)]] -> 0
[[(-4,10),(6,2)],[(-2,8),(4,3)],[(1,6),(8,4)],[(2,11),(5,5)]] -> 10
[[(8,2),(12,-2)],[(10,0),(14,-4)]] -> 2
[[(0,2),(2,0)],[(0,1),(3,0)]] -> 1
[[(-10,-2),(-6,-6)],[(-6,-2),(-2,-6)],[(-8,-4),(-4,-8)]] -> 3

Happy Coding!

JavaScript (ES6), 186 bytes

a=>a.map(([a,b,c,d])=>h.push([b,a,c],[d,a,c])&v.push([a,b,d],[c,b,d]),h=[],v=[])|h.map(([d,a,e])=>v.map(([c,f,b])=>a<c&c<e&b<d&d<f&t.every(([a,b])=>a-c|b-d)&&t.push([c,d])),t=[])|t.length

Splits each rectangle into its component lines, then intersects the horizontal and vertical lines, building up a list of intersections to avoid duplicates.


Unreliable data stream Your challenge is to golf a program that mimics a data transmission stream. Your program should read input from stdin and output it directly to stdout. To make the problem more interesting, the output stream is 'faulty', and must meet several requirements:

There should be a 10% chance that each character is shifted +1 ascii code (ex 'a' becomes 'b', '9' becomes ':'), etc.
The input and output should only cover printable ascii values ('!' through '~', decimal 33 through decimal 126, inclusive).  If the random +1 occurs on a '~' (decimal 126), a '!' (decimal 33) should be output instead.
If three characters are randomly shifted in a row, the program should output "ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR" (trailing newline optional) and halt execution.

To simplify the problem, here are a few other criteria:

You can assume the input will always be valid; that is, it will only contain values '!' through '~'.
The program should continue on until three characters are randomly shifted in a row; it's safe to assume that EOF will never occur.
The randomness must differ across runs; if your random number generator needs to be seeded to get an unique result each run, then your code needs to seed it.
You must write a program, not a function.
You must take input from stdin and write output to stdout.
You may not use any external libraries or resources.
Your code must have a freely available and working intrepreter or compiler.

Standard code-golf rules apply.  Winner is whoever has the shortest program posted two weeks from now (Thursday, Feb 20th, 2014).

C, 168 characters

i;main(c){for(srand(&c);i++<3;putchar(rand()%10?i=0,c:c-126?c+1:33))c=getchar();
puts("ERROR CODE 4625: UNRECOVERABLE ERROR, PLEASE CONTACT YOUR SYSTEM ADMINISTRATOR");}

This solution's seeding of the PRNG takes advantage of the fact that modern OSes change the stack's location in memory on each run, as a basic measure against stack-smashing exploits.


What are my chess moves? Chess is a game with 6 different types of pieces that can move in different ways:

Pawns - They can only move up or capture diagonally (also forward). Capturing a piece behind them or beside them is illegal. The only exception is en passant. For this challenge, if  a pawn reaches the 8th rank (or row), assume it becomes a queen.
Bishops - They move diagonally and the squares they travel on will always have the same color (i.e if the square the bishop is currently on is white, the bishop can't move to a darker square for  instance).
Knights - They move pretty awkwardly. They can move two spaces up/down then one space to the right/left or two spaces right/left then on space up/down.
Rooks - They can only move in straight lines, up or down or left or right.
Queens - They can move diagonally like a bishop or in straight lines like a rook
Kings - They can only move to squares they are touching (including diagonals).

This chess.com link to clarify the above. A chessboard and its coordinates are shown below:

So given an entirely empty chessboard except for one piece and the inputs -- the piece's type and its current position, what are the piece's legal moves?

Examples

Input: Rook a8
Output: a1 a2 a3 a4 a5 a6 a7 b8 c8 d8 e8 f8 g8 h8

Input: Pawn a2
Output: a4 a3

Input: Pawn a3
Output: a4

Input: Knight a1
Output: c2 b3

Input: Bishop h1
Output: a8 b7 c6 d5 e4 f3 g2

Input: King b2
Output: c2 c3 c1 b3 b1 a1 a2 a3

Input: Queen h1
Output: a8 b7 c6 d5 e4 f3 g2 h2 h3 h4 h5 h6 h7 h8 a1 b1 c2 d1 e1 f1 g1

Rules and Specifications

A legal move is defined as a move in which the piece can go to while being on the board. So a rook at a1 can go to a8 (moving to the right) but not to b2 since you can't get there with a straight line (only possible in two or more moves)
Pawns will never be in the first or eighth rank (it would then be another piece). If a pawn is in the second rank, it can move up two spaces (not for captures). Otherwise, it can only move forward a square.
Notation for Queening a pawn is not needed
Capitalization does not matter though the letter must come before and attached to the number
The acceptable moves must be separated in some way (i.e commas, spaces, different lines, in a list)
Always assume that the bottom left corner is a1 and you are playing as White
The input can be a single string (i.e rooka3 or Rook a3 or rook a3 or Rook A3) is acceptable and can be in any order (i.e the position before the type like A3 rook). Multiple strings are also acceptable.

Winning Criteria

Shortest code wins!

JavaScript (ES6), 256 ... 229 227 bytes

Takes input as two strings (p, s), where p is the case-insensitive name of the piece and s is the source square. Returns a space-separated list of destination squares.

f=(p,s,i=128)=>i--?f(p,s,i)+([x=255,x<<8,2,x,195,60][P=(I=parseInt)(p,32)*5&7]>>i/8&((d=i%8)<(S=(x=I(s,18)-181)/18|x%18*16,P>2?8:P<2|S>23||2))&!((S+=I('gfh1eivx'[i>>4],36)*(i&8?d+1:~d))&136)?'abcdefgh'[S&7]+(S+16>>4)+' ':''):''

How it works

Piece name decoding

The name of the piece p is converted to an integer P by parsing it in base 32, multiplying the result by 5 and isolating the 3 least significant bits: parseInt(p, 32) * 5 & 7

 Piece    | As base 32 |        * 5 | & 7
----------+------------+------------+----
 "king"   |     674544 |    3372720 |  0
 "knight" |  695812669 | 3479063345 |  1
 "pawn"   |        810 |       4050 |  2    NB: 'pawn' is parsed as 'pa', because 'w'
 "queen"  |   28260823 |  141304115 |  3        is not a valid character in base 32
 "rook"   |     910100 |    4550500 |  4
 "bishop" |  388908825 | 1944544125 |  5

In addition to being a perfect hash, a good thing about this formula is that all sliding pieces (Queen, Rook and Bishop) appear at the end of the list, which allows to identify them with a simple P > 2.

Source square decoding

The source square s is converted to an integer S by parsing it in base 18 and converting the result to 0x88 coordinates.

That leads to the following board representation:

     a    b    c    d    e    f    g    h
8  0x70 0x71 0x72 0x73 0x74 0x75 0x76 0x77
7  0x60 0x61 0x62 0x63 0x64 0x65 0x66 0x67
6  0x50 0x51 0x52 0x53 0x54 0x55 0x56 0x57
5  0x40 0x41 0x42 0x43 0x44 0x45 0x46 0x47
4  0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37
3  0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27
2  0x10 0x11 0x12 0x13 0x14 0x15 0x16 0x17
1  0x00 0x01 0x02 0x03 0x04 0x05 0x06 0x07

Directions encoding

There are 16 possible directions: 4 along ranks and files, 4 along diagonals and 8 for the knights.

As hexadecimal:                     As decimal:

      +0x1F       +0x21                    +31         +33
+0x0E +0x0F +0x10 +0x11 +0x12        +14   +15   +16   +17   +18
      -0x01 [SRC] +0x01                     -1  [SRC]   +1
-0x12 -0x11 -0x10 -0x0F -0x0E        -18   -17   -16   -15   -14
      -0x21       -0x1F                    -33         -31

Therefore, the list of directions that a piece can move towards can be encoded as a 16-bit bitmask.

Bit:    |   F   E   D   C   B   A   9   8   7   6   5   4   3   2   1   0 | As
Vector: | +33 -33 +31 -31 +18 -18 +14 -14  +1  -1 +17 -17 +15 -15 +16 -16 | decimal
--------+-----------------------------------------------------------------+--------
King    |   0   0   0   0   0   0   0   0   1   1   1   1   1   1   1   1 | 255
Knight  |   1   1   1   1   1   1   1   1   0   0   0   0   0   0   0   0 | 65280
Pawn    |   0   0   0   0   0   0   0   0   0   0   0   0   0   0   1   0 | 2
Queen   |   0   0   0   0   0   0   0   0   1   1   1   1   1   1   1   1 | 255
Rook    |   0   0   0   0   0   0   0   0   1   1   0   0   0   0   1   1 | 195
Bishop  |   0   0   0   0   0   0   0   0   0   0   1   1   1   1   0   0 | 60

The absolute values of the direction vectors can be stored in base 36:

[16, 15, 17, 1, 14, 18, 31, 33][n] <==> parseInt('gfh1eivx'[n], 36)

Formatted and commented

f = (p, s, i = 128) =>                     // given a piece p, a square s and a counter i
  i-- ?                                    // if i is >= 0:
    f(p, s, i) + (                         //   do a recursive call to f()
      [ x = 255, x << 8, 2, x, 195, 60 ][  //   take the direction bitmask for:
        P = (I = parseInt)(p, 32) * 5 & 7  //   P = piece index in [0 .. 5]
      ] >> i / 8 & (                       //   and test the bit for the current direction
        (d = i % 8) < (                    //   d = current move distance - 1
          S = (x = I(s, 18) - 181) / 18 |  //   S = source square in
              x % 18 * 16,                 //       0x88 representation
          P > 2 ? 8 : P < 2 | S > 23 || 2  //   compare d with the maximum move range for
        )                                  //   this piece
      ) ?                                  //   if the above test passes:
        (                                  //     we add to S:
          S += I(                          //       the absolute value of the vector of
            'gfh1eivx'[i >> 4], 36         //       the current direction,
          ) *                              //       multiplied by
          (i & 8 ? d + 1 : ~d)             //       the move distance with the vector sign
        ) & 136 ?                          //     if the result AND'd with 0x88 is not null:
          ''                               //       this is an invalid destination square
        :                                  //     else:
          'abcdefgh'[S & 7] +              //       it is valid: convert it back to ASCII
          (S + 16 >> 4) + ' '              //       and append a space separator
      :                                    //   else:
        ''                                 //     this is an invalid move
    )                                      //   end of this iteration
  :                                        // else:
    ''                                     //   stop recursion

Test cases

f=(p,s,i=128)=>i--?f(p,s,i)+([x=255,x<<8,2,x,195,60][P=(I=parseInt)(p,32)*5&7]>>i/8&((d=i%8)<(S=(x=I(s,18)-181)/18|x%18*16,P>2?8:P<2|S>23||2))&!((S+=I('gfh1eivx'[i>>4],36)*(i&8?d+1:~d))&136)?'abcdefgh'[S&7]+(S+16>>4)+' ':''):''

console.log(f('Rook',   'a8'));
console.log(f('Pawn',   'a2'));
console.log(f('Pawn',   'a3'));
console.log(f('Knight', 'a1'));
console.log(f('Bishop', 'h1'));
console.log(f('King',   'b2'));
console.log(f('Queen',  'h1'));


Check if a matrix is a Toeplitz matrix You will be given a two-dimensional array and a number and you are asked to find whether the given matrix is Toeplitz or not.

Input Format:

You will be given a function which will take two-dimensional matrix as argument.

Output Format:

Return 1 from the function if the matrix is Toeplitz, else return -1.

Constraints:

3 < n,m < 10,000,000

where n is the number of rows while m will be the number of columns.

Sample Test Case:

Sample Input :
4
5
6 7 8 9 2
4 6 7 8 9
1 4 6 7 8
0 1 4 6 7

Sample Output :
1

Scoring

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

Mathematica, 42 bytes

2Boole[#==ToeplitzMatrix[#&@@@#,#&@@#]]-1&

Mathematica doesn't have a built-in to check whether something is a Toeplitz matrix, but it does have a built-in to generate one. So we generate one from the first column (#&@@@#) and the first row (#&@@#) of the input and check whether it's equal to the input. To convert the True/False result to 1/-1 we use Boole (to give 1 or 0) and then simply transform the result with 2x-1.


Find the result of some assignment statements In this challenge, the goal is to find the values of some variables after a number of assignments are done. An example input:

a = 5
b = 4
c = a = b
a = 2
b = a

This would result in:
a = 2
b = 2
c = 4

Each statement will be one of the following:

A variable name ([a-z_]+)
A numeric value ([0-9]+)
An assignment operation, with a variable name on the left and a statement on the right

You may assume that the input will be a list of statements, formatted however you want. Variable names will have differing lengths (if you need a hard value to gold within, assume 16 chars max).
Note that statements can contain more or less than one assignment (such as a, 23, or a = b = c = 4), and that variables can appear that are never assigned to. Assume no undefined variables are used as values in an assignment (such as a = undefined_variable), and that no variable will be on both sides of an assignment (such as a = a or a = a = 1).
You can take input any way you wish (such as a string with a character to delimit statements, a list formatted as [["a", 5], ["b", "a"]], etc.), and output can be in any consistent format (such as a hash map of names to values, or a list of values in the order that the variables first appeared).
Test cases:
a = 5                     -> a = 5
b = 512, c = a = 2        -> a = 2, b = 512, c = 2
def, 2, e = 8, 101        -> e = 8
                          ->
a                         ->
fgh = 4, i = 3, fgh = i   -> fgh = 3, i = 3
j = k = l = m = n = 14    -> j = 14, k = 14, l = 14, m = 14, n = 14
s = t = u = 6, t = v = 7  -> s = 6, t = 7, u = 6, v = 7
o = 3, o = p              -> [undefined]
q = r                     -> [undefined]
w = w = 2                 -> [undefined]
x = 4, x = x              -> [undefined]

This is code-golf, so shortest answer per language wins!

APL (Dyalog Unicode), 22 bytes

{n⊣⍵{0::0⋄⍵⍎⍺}¨n←⎕NS⍬}

Try it online!
Takes a list of statements in the form of a←b←3, and returns a namespace which is essentially a hashmap of variable names to values. You can't print all the contents of it directly, but you can inspect individual variables like ns.somevar or list all names using ns.⎕NL ¯2.
Oh, and APL doesn't have any alphanumeric-only keywords!
{n⊣⍵{0::0⋄⍵⍎⍺}¨n←⎕NS⍬}  ⍝ ⍵: list of statements
               n←⎕NS⍬   ⍝ Create an empty namespace
   ⍵{        }¨         ⍝ For each statement...
          ⍵⍎⍺           ⍝ Try executing the statement inside the namespace
     0::0⋄              ⍝ ignoring any errors (undefined name)
 n⊣                     ⍝ Return the populated namespace


Draw A Reuleaux Triangle! The Reuleaux triangle is the shape formed by the intersection of three circles, with each circle passing through the others' centers. Regardless of rotation, a Reuleaux triangle's width will always equal the radius of the circles:

Image: Wolfram MathWorld

Write a program that takes a width r as input and displays a Reuleaux triangle of that width (in pixels).

You must display the shape in isolation, i.e. solid-filled, un-stroked, and over a solid-filled background.

code-golf - Shortest program in bytes wins.

JavaScript + HTML, 164 158 + 13 = 171 bytes

w=+prompt(f=(x,y)=>x*x+y*y<w*w);C.width=C.height=w*2;for(y=-w;++y<w;)for(x=-w;++x<w;)f(x,y)&f(w-x,y)&f(w/2-x,y-w*.866)&&C.getContext`2d`.fillRect(x+w,y+w,1,1)
<canvas id=C>

I don't know why I enjoy answering these mathy drawing challenges with <canvas> so much...


Fast Topswops calculation From AZSPCS:

Suppose you have a deck containing n cards. Each card contains a number from 1 to n, and each number appears on exactly one card. You look at the number on the top card -- let's says it's k -- and then reverse the order of the top k cards. You continue this procedure -- reading the top number and then reversing the corresponding number of cards -- until the top card is 1.

Write the fastest program to compute the number of reversals for a given deck. Note that if you are participating in the contest you are not allowed to post your code (and thus I will not post my code yet).


Is this a consecutive-prime/constant-exponent number? A while ago, I had a look at the prime factorization of 27000:

27000 = 23 × 33 × 53

There are two special things about that:

consecutive-prime: The primes are consecutive: 2 is the 1st prime, 3 is the 2nd prime, 5 is the 3rd prime.
constant-exponent: The exponent is the same for every prime (always 3)

Mathematically expressed:

An integer x is a consecutive-prime/constant-exponent number if there exist strictly positive integers n, k, m such that x = pnm × pn+1m × ... × pn+km, where pj is the j-th prime

Your task is to test if a positive integer fulfills these conditions.
Input:
A positive integer > 1, in any reasonable form.
Output:
One of two values, at least one of which has to be constant, indicating whether the input is a consecutive-prime/constant-exponent number.
Edge cases:

primes are truthy, as the factorization for prime p is p1
other numbers that can be written as pm where p is a prime are also truthy.

Rules:

Standard loopholes apply.
No worries about integer overflow, but numbers up to 255 must work.
Shortest code in bytes wins.

Test cases:
Truthy:
2
3
4
5
6
7
8
9
11
13
15
27000
456533

Falsy:
10
12
14
72
10000000

Here is a python script generating some test cases.
The fact that I accepted an answer does not mean that the challenge is over; the winner can still change!

05AB1E, 4 bytes

Ó0ÛË

Try it online!

Explanation

Ó     # get a list of prime exponents
 0Û   # remove leading zeroes
   Ë  # all remaining elements are equal


How long ago was this? The Rules

Each submission must be a full program.

The program must take input as two comma-separated dates in the form YYYY-MM-DD, and print the number of days that has passed since the second date to STDOUT as if today was the first date (if the second date would be in the future, output a negative number) plus an optional trailing newline, and nothing else. Assume both dates are in the Gregorian calendar.

The program must not write anything to STDERR.
Note that there must be an interpreter so the submission can be tested.

Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.

This is code-golf, so shortest code wins

Examples
Input:
2015-12-03,2015-12-01
Output:
2
Input:
2015-12-03,2014-12-01
Output:
367
Input:
2015-12-03,2013-12-03
Output:
730

Bash + GNU utilities, 37

tr , \\n|date -f- +%s|dc -e??-86400/p

tr replaces the comma with a newline.  date reads the newline separated dates and outputs the number of seconds since the Unix epoch that the passed-in date represents.  These numbers are then put on the dc stack.  Then its a simple matter of subtraction and divide by (24*60*60).  In this case, dc stack-based RPN arithmetic evaluation is better than bc or bash $( ), mostly because the subraction-before-division needs no parentheses.

Input via STDIN:

$ echo 2015-12-3,2015-12-1 | ./longago.sh
2
$ echo 2015-12-3,2014-12-1 | ./longago.sh
367
$ echo 2015-12-3,2013-12-3 | ./longago.sh
730
$


Maintain diagonal symmetry when placing N items on a square grid Write a program that takes in two non-negative integers S and N in that order. S represents the side length of a square grid of . characters. N represents the number of those .'s that need to be changed to x's. You may assume N is no greater than S squared.
Your program needs to output this S×S square of .'s and N x's but the requirement is that the square must always have a diagonal line of symmetry from its top left to its bottom right. Any grid arrangement is valid output as long as it has this symmetry.
For example, if S is 3 and N is 4 here are several grids that have this diagonal symmetry and would be valid output:
x.x
...
x.x

x..
.xx
.x.

...
.xx
.xx

The following grids however would not be valid:
.x.
xxx
...
(lacks diagonal symmetry)

..x
xx.
.x.
(has diagonal symmetry but not from the top left to the bottom right)

x.x
.x.
x.x
(incorrect number of x's)

This is code golf so the shortest program in bytes wins!
Details:

A trailing newline after the grid is fine.

You may use any two distinct printable-ASCII characters in place of . and x if you prefer.

If you prefer you may even output a binary-matrix instead of a string.

When N is 0 the output will be a pure S×S square of .'s with no x's.

When S is 0 the output will be an empty string (or single trailing newline).

The output does not need to be deterministic, as long as it is always guaranteed to be valid.

More Examples:
Not all valid arrangements are listed for each example input. Your output might look different yet still be valid.
S = 0, N = 0
[empty string]

S = 1, N = 0
.

S = 1, N = 1
x

S = 2, N = 0
..
..

S = 2, N = 1
x.
..

..
.x

S = 2, N = 2
x.
.x

.x
x.

S = 2, N = 3
xx
x.

.x
xx

S = 2, N = 4
xx
xx

S = 3, N = 2
x..
.x.
...

..x
...
x..

S = 4, N = 1
....
.x..
....
....

S = 4, N = 5
x..x
.x..
..x.
x...

xxx.
x...
x...
....

S = 5, N = 23
xxxxx
xxxxx
xxxxx
xxx.x
xxxx.

xxxxx
xxxxx
xxxxx
xxxx.
xxx.x

S = 7, N = 13
...x...
...x...
...x...
xxxxxxx
...x...
...x...
...x...

xxxxxxx
x......
x......
x......
x......
x......
x......

Python 2, 116 113 112 101 bytes

lambda s,n:[[[n>i<s-(s+n&1),[i*~-i+2*j,j*~-j+2*i][i<j]<n-s][j!=i]for j in range(s)]for i in range(s)]

Try it online!
Input: 2 integers s and n
Output: A 2D list of True and False, representing x and . respectively.
Explanation
The strategy is to put as many xs on the diagonal as possible.

If \$s\$ and \$n\$ has the same parity, then we can fill \$min(s,n)\$ diagonal squares.
If \$s\$ and \$n\$ has different parity, then we can fill \$min(s-1,n)\$ diagonal squares.

The remaining xs can be split symmetrically between the 2 triangular half of the grid. For the bottom triangle, we fill from top to bottom, where each row is filled left to right. The upper triangle mirrors the bottom triangle (fill left to right, each column from top to bottom)
Thus, we can determine if a square is filled just based on its indices \$(i,j)\$:

If \$i=j\$ (the square is on the diagonal), then that square is filled if \$i<n\$ and \$i<s-t\$, where \$t\$ is 0 or 1 depending on whether \$s\$ and \$n\$ have the same or different parity.
The following snippet evaluates to True or False if the diagonal square should be filled or not.

[n>i<s-(s+n&1), ...case when square is not diagonal... ][j!=i]

If \$i>j\$ (the square is in lower triangle), then the number of squares in the lower triangle before this square (in fill order) is \$m = \frac{i(i-1)}{2} + j\$. Thus if this square is filled, then the number of squares filled before it is \$2m = i(i-1)+2j\$. We need to make sure that \$2m<n-s\$, otherwise the diagonal cannot be filled to the maximum.
Similarly, if \$i>j\$, then we fill if \$j(j-1)+2i<n-s\$.
The following snippet evaluates to True or False if the non-diagonal square is filled or not:

[i*~-i+2*j,j*~-j+2*i][i<j]<n-s

Combined together, this big expression evaluates to whether a square \$(i,j)\$ should be filled:
[n>i<s-(s+n&1),[i*~-i+2*j,j*~-j+2*i][i<j]<n-s][j!=i]

Thanks @ovs for saving 4 bytes in a previous solution!