Exact Partial Sum of Harmonic Series Challenge

Given a positive integer N, output the sum of the first N reciprocals as an exact fraction, which is represented as a pair of integers in a consistent order representing numerator and denominator.

Rules

Output must be exact.
Output should be as a pair of integers in a consistent order representing numerator and denominator.
Using non-integer numeric types (built-in or library) is forbidden.

Clarification/exception: non-integer numeric types are okay if and only if all values used, computed, and returned are integers (i.e. your language uses rational numbers by default, but you only use integer arithmetic in your answer)

Output should be as reduced as possible. (3/2 is okay, 6/4 is not)
Standard loopholes are forbidden.
Submissions should work for inputs at least up to 20, or this meta, whichever is higher.

Test Cases

1: 1/1
2: 3/2 (1/1 + 1/2)
3: 11/6 (1/1 + 1/2 + 1/3)
4: 25/12 etc.
5: 137/60
6: 49/20
20: 55835135/15519504
56: 252476961434436524654789/54749786241679275146400
226: 31741146384418617995319820836410246588253008380307063166243468230254437801429301078323028997161/5290225078451893176693594241665890914638817631063334447389979640757204083936351078274058192000

Test-Case Generation (Python 3)

import fractions
def f(x):
    return sum(fractions.Fraction(1,i) for i in range(1,x+1))

Similar to this challenge and this challenge.

Numerators are OEIS A001008, and denominators are OEIS A002805.

Python 2, 80 79 bytes

D=1;N=n=0;exec"n+=1;y=N=N*n+D;x=D=D*n;"*input()
while y:x,y=y,x%y
print N/x,D/x

Try it online!

Prints the numerator and denominator.

Yay! MathJax support!!!! One observes:

$$\sum_{i=1}^{n} \frac{1}{i} = \sum_{i=1}^{n} \frac{n!}{n!i} = \frac{\sum_{i=1}^{n} \frac{n!}{i}}{n!}$$

Then, thinking about recursion, for \$n\$ positive, in the Numerator:

$$\sum_{i=1}^{n+1} \frac{(n+1)!}{i} = (n+1) \sum_{i=1}^{n} \frac{n!}{i} + \frac{(n+1)!}{n+1} = (n+1) \sum_{i=1}^{n} \frac{n!}{i} + n!$$

and one can't help think of the Denominator \$n!\$ recursively as well; thus the exec.

We must pay the Reduced Fraction Piper with a GCD calculation in the while loop; and then we're done.


Find the shortest unique sublist Given a list of lists find the shortest list that is a contiguous sublist of exactly one list.

For example if we had

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

the shortest contiguous sublist would be [3,4] since it only appears in the second list.

If there is no unique contiguous sublist (this requires at least one duplicate entry), output an empty list.  Here is an example

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

If there are multiple contiguous sublists of minimal size, you may output any one of them or a list containing all of them.  For example if the input was

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

You could output either [1,2], [2,3] or [[1,2],[2,3]].  If you choose to do the latter option you may output singleton lists for the cases where there is only one solution.

The output may occur in the same list more than once as long as it appears in no other list.  For example

[[1,2,1,2],[2,1]]

should output [1,2] because [1,2] is a sublist of the first list but not the second, even though it is a sublist of the first list in two different ways.

You may take as input a list of lists containing any type so long as that type has more than 100 possible values, i.e. no Booleans.

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

Test Cases

[[1,1]] : [1]
[[1],[1]] : []
[[1,1],[1]] : [1,1]

Husk, 12 14 15 bytes
+3 bytes for case [[1,1]]
Ṡḟȯ¬€Ṡ-uÖLṁȯtuQ

Try it online!
Explaination
          ṁ      -- map and concatenate
           ȯt    --   all but the first
             u   --   unique elements of
              Q  --   contiguous sublist
        ÖL       -- sort by length
Ṡḟ               -- find the first element satisfying this predicate
  ȯ¬€            --   not an element of
     Ṡ-          --   the list of sublists minus
       u         --   its unique elements

Note: Ṡ f g x = f (g x) x and this is hard to explain using the method above.


Build interpreter for non-existent language Build an interpreter for a fake, stack-based language that gets an input, interprets it, and outputs the result as an array of numbers. It should iterate through each byte and perform a different function based on this table:

0000 (0):
Concatenate (Combine top two numbers in a stack as if they were a string. ex: 12,5 -> 125)
0001 (1):
Increment (Add 1 to the number on the top of the stack)
0010 (2):
Decrement (Subtract one from the number at the top of the stack)
0011 (3):
Multiply (Multiply the top two numbers in the stack)
0100 (4):
Divide (Divide the 2nd-to-top number by the top number on the stack)
0101 (5):
Add (Add the top two numbers on the stack)
0110 (6):
Subtract (Subtract the top number on the stack from the one below it)
0111 (7):
Exponent (Calculate the second-to-top number to the power of the top number)
1000 (8):
Modulus: (Find the second-to-top number modulo the top one)
1001 (9):
Rotate Right (Shift the stack down one. The number on the bottom is now on the top)
1010 (A):
Rotate Left (Shift the stack up one. The number on the top is now on the bottom)
1011 (B):
Duplicate (Copy the top number so that it appears twice. ex: 4,1 becomes 4,1,1)
1100 (C):
Double Duplicate (Copy the top two numbers on the stack. ex: 4,1,2 becomes 4,1,2,1,2)
1101 (D):
Swap (Swap the top two numbers on the stack. ex: 4,1,2 becomes 4,2,1)
1110 (E):
Double Swap (Swap the top two numbers with two below them.ex: 1,2,3,4,5 becomes 1,4,5,2,3)
1111 (F):
Delete/Pop (Remove the number at the top of the stack)

For example, a file containing

1 1 B C 5 C 5 B 9 5    - Input (hex)
| | | | | | | | | |
1 2 2 2 4 4 6 6 2 8    - Stack
    2 2 2 2 4 6 6 6
      2 2 4 2 4 6 4
      2   2 2 2 4 2
          2   2 2

would output [8,6,4,2]

Rules:

Unicode/symbols are okay, but ASCII is best.
Be creative! Shortness counts, but creativity is great!
If bytes are too hard, use "$iv*/+-^%><dtsz." or "0123456789ABCDEF" instead of actual bytes.
SPEED! The faster, the better.
The score is based on reputation, but size is a huge factor.

Bonus:

Try to complete this challenge using your newly made interpreter in as short of a string as possible.

Note:

The thing that makes this challenging as opposed to other code-golfing challenges is that there is no code to go by with this. If, lets say, you had to write a brainf*ck interpreter, you could look at other people's implementations. With this, you can't do that.

I forgot to put and ending date on this. I guess I'll make it one month from when I created this. Person with the highest votes at Feb. 22 wins!


Does base n have any Rotate-Left-Double numbers? Task

A Rotate-Left-Double number in base \$n\$ is a number \$m\$, when its base-\$n\$ digits are rotated left once, equals \$2m\$. The base-\$n\$ representation of \$m\$ cannot have leading zeros.

One example in base 7 is the number 480, or \$1254_7\$. When rotated left once, the value becomes \$2541_7 = 960\$.

Given the base \$n \ge 2\$, determine if there exists a Rotate-Left-Double number in base \$n\$.

You can use your language's convention to represent truthy/falsy, or use two distinct values for truthy and falsy respectively.

Scoring and winning criterion

Standard code-golf rules apply. Shortest code in bytes wins.

Test cases

n -> answer (example if true)
-----------------------------
2 -> false
3 -> false
4 -> false
5 -> true (13 x 2 = 31)
6 -> false
7 -> true (1254 x 2 = 2541)
8 -> true (25 x 2 = 52)
9 -> true (125 x 2 = 251)
10 -> false
11 -> true [3,7]
12 -> true [2,4,9,7]
13 -> true [1,2,4,9,5,11,10,8,3,7]
14 -> true [4,9]
15 -> true [1,2,4,9,3,6,13,12,10,5,11,8]
16 -> true [2,4,9]
17 -> true [1,2,4,9]

Reference implementation in Python.

05AB1E, 6 5 bytes
ÍD<&Ā

-1 byte thanks to @xnor and @Noodle9.
Try it online or verify the first \$[2,100]\$ test cases.
Explanation:

Í       # Decrease the (implicit) input-integer by 2
        # Check that this input-2 is a power of 2 by:
 D      #  Duplicating it
  <     #  Decrease the copy by 1 (so integer-3)
   &    #  Take the bitwise-AND of input-2 and input-3
    Ā   #  Check that this is NOT 0
        # (after which the result is output implicitly)

But wait, I don't see any use of bases nor rotation!
When I saw the challenge in the Sandbox and was working on a solution, I noticed that the only falsey values in the first \$n=[2,500]\$ bases formed the sequence A056469: number of elements in the continued fraction for \$\sum_{k=0}^n (\frac{1}{2})^{2^k}\$, which could be simplified to \$a(n)=\left\lfloor2^{n-1}+2\right\rfloor\$. Here a copy of the first 25 numbers in that sequence as reference:
2, 3, 4, 6, 10, 18, 34, 66, 130, 258, 514, 1026, 2050, 4098, 8194, 16386, 32770, 65538, 131074, 262146, 524290, 1048578, 2097154, 4194306, 8388610

It can also be note that all the numbers in this sequence are of the form \$a(n)=2^n+2\$, so checking whether \$n-2\$ is a power of \$2\$ will verify whether it's in this sequence. Since we want to do the invert here, and having a falsey result if it's in this sequence (or truthy if it's NOT in this sequence), we'll do just that, resulting in the code above.
Mathematical proof that all falsey cases of the Left-Rotate-Double numbers are of the form \$2^n+2\$:
Quote from @saulspatz at the Math SE, who provided me with this Mathematical proof to back up my theory I based on the first \$n=[2,500]\$ test cases. So all credit for this proof goes to him/her.
If \$m\$ is a \$(d+1)\$-digit Rotate-Left-Double number in base \$n\$, then $$m=xn^d+y\tag1$$ where \$d\geq1,\ 0<x<n,\ 0\leq y<n^d\$. (Includes the rule that the number can't start with \$0\$.) Rotating \$m\$ gives \$ny+x\$, so we have \$2xn^d+2y=ny+x\$ or $$(n-2)y=(2n^d-1)x\tag2$$ If \$n=2^k+2\$ then \$(2)\$ gives \$(n-2)|x\$ (which means \$x\$ is divisible by \$(n-2)\$), since \$2n^s-1\$ is odd. But then \$y\geq 2n^d-1\$ which contradicts \$y<n^d\$.
To show that these are the only falsey numbers, let \$p\$ be an odd prime dividing \$n-2\$.  (Such a \$p\$ exists because \$n-2\$ is not a power of \$2\$.) In \$(2)\$ we can take \$x=\frac{n-2}p<n\$ and we have to show that there exist an exponent \$d>0\$ and \$0\leq y<n^d\$ such that $$py = 2n^d-1$$ If we can find a \$d\$ such that \$p|(2n^d-1)\$, we are done, for we can take \$y = \frac{2n^d-1}p<n^d\$.
By assumption, \$n-2\equiv0\pmod{p}\$ so \$n\equiv 2\pmod p\$. Therefore, $$2n^d\equiv1\iff 2\cdot2^d\equiv1 \iff 2^{d+1}\equiv 1\pmod p,$$ and by Fermat's little theorem, which states that \$a^{p-1}\equiv 1\pmod p\$, we can take \$d=p-2\$, because $$2^{p-2+1}\equiv 1 \iff 2^{p-1}\equiv 1 \pmod p$$
This completes the proof.


All non-ordered pairs between the elements of an array Task:

Return an array with all possible pairs between the elements of an array.

Example

From a=["a", "b", "c", "d"]; return b=[["a","b"],["a","c"],["a","d"],["b","c"],["b","d"],["c","d"]].

Pairs can be in any order as long as all possible combinations are included and obviously ["b","d"] is the same to ["d","b"].

Input

Array of unique string elements composed of chars from the class [a-z].

Output

2d array containing all the possible pairs of input array's elements.

Test Cases

input=["a","b","c"];
//output=[["a","b"],["a","c"],["b","c"]]

input=["a","b","c","d","e"];
//output=[["a","b"],["a","c"],["a","d"],["a","e"],["b","c"],["b","d"],["b","e"],["c","d"],["c","e"],["d","e"]]

Note: I could not find a duplicate to this challenge. If there is one, alert me with a comment to drop question.

Haskell, 29 bytes

f(a:b)=map((,)a)b++f b
f _=[]

Try it online! Example usage: f ["a","b","c"] yields [("a","b"),("a","c"),("b","c")].

With the flag -XTupleSections this can be shortened to 27 bytes, however the flag would need to be counted:

f(a:b)=map(a,)b++f b
f _=[]

Try it online!


Random CSS Color code This blog post about generating random CSS color codes in JavaScript have multiple solutions for generating a random color in JavaScript. The shortest I can find is this:

'#'+(Math.random()*0xffffff).toString(16).slice(-6)

If you are not familiar with CSS color code read documentations here.

Can we do better? What about other languages?

PHP 23 bytes

#<?=md5(rand())&ÿÿÿÿÿÿ;

Where ÿ is character 255. Bitwise and will truncate the string returned from md5, which is already in hexadecimal format.


The strange ordering of Sharkovskii Introduction

In this challenge, we will be dealing with a certain ordering of the positive integers.
The ordering goes like this:

   3,    5,    7,    9,    11, ...
 2*3,  2*5,  2*7,  2*9,  2*11, ...
 4*3,  4*5,  4*7,  4*9,  4*11, ...
 8*3,  8*5,  8*7,  8*9,  8*11, ...
16*3, 16*5, 16*7, 16*9, 16*11, ...
 ...
... 64, 32, 16, 8, 4, 2, 1

We first list all odd integers greater than 1 in ascending order.
Then we list two times odd integers greater than 1, then 4 times, then 8 times, and so on: for all k, we list 2k times the odd integers greater than 1 in ascending order.
Finally, we list the powers of two in descending order, ending at 1.
Every positive integer occurs in this "list" exactly once.

More explicitly, consider two distinct positive integers A = n·2p and B = m·2q, where n, m ≥ 1 are odd, and p, q ≥ 0.
Then A comes before B in the ordering, if one of the following conditions holds:

n > 1, m > 1 and p < q
1 < n < m and p = q
n > m = 1
n = m = 1 and p > q

This ordering appears in the surprising mathematical result known as Sharkovskii's theorem, which concerns the periodic points of dynamical systems.
I will not go into the details here.

The task

Your task in this challenge is to compute the above ordering.
Your inputs are two positive integers A and B, which may be equal.
Your output is a truthy value if A comes before B in the ordering, and a falsy value otherwise.
If A = B, your output should be truthy.
You can take A and B in either order, as long as you're consistent.

You don't have to worry about integer overflow, but your algorithm should theoretically work for arbitrarily large inputs.

Test cases

Truthy instances

3 11
9 6
48 112
49 112
158 158
36 24
14 28
144 32
32 32
32 8
3 1
1 1

Falsy instances

1 2
1 5
11 5
20 25
2 8
256 255
256 257
72 52
2176 1216
2176 2496

JavaScript (ES6), 53 49 bytes

f=(a,b)=>b<2||a>1&&(a&b&1?a<=b:a&1|~b&f(a/2,b/2))

Explanation:

If b is 1, then a precedes (or equals) b
Otherwise, if a is 1, then a does not precede b
Otherwise, if both a and b are odd, then use regular inequality check
Otherwise, if a is odd, then it precedes b
Otherwise, if b is odd, then a does not precede b
Otherwise, divide both a and b by 2 and try again.

Edit: Saved 2 bytes thanks to @Arnauld.


Weirdest obfuscated "Hello World!" Task:

Create an obfuscated program that prints Hello World! (exactly like that). Your program may not have any strings in it.

Rules:

You can use any programming language you like.
Make it as obfuscated as possible
This is a popularity-contest, so the answer with the most upvotes wins.

Note:

This is not a duplicate of this question. That one was code-golf and it had different rules.


Extract the Coefficients of a Linear Equation Given a linear equation mx+n, return n and m. However, the equation may be in any of the following formats:

5x+2 -> 5 2
5x-2 -> 5 -2
5x   -> 5 0
-2   -> 0 -2
x    -> 1 0

Here are the formats, where each ? stands for a positive integer written without leading zeroes

?x+?
?x-?
-?x+?
-?x-?
x+?
x-?
?
-?
?x
-?x
x

All of these cases must be handled.

Specifications:

You can assume that the equation is in one of the above formats, i.e. it matches the regex ^(-?[123456789]\d*)?x([+-][123456789]\d*)?|-?[123456789]\d*$.

Test Cases:

-2x+3 -> -2 3
44x   -> 44 0
-123  -> 0 -123
x     -> 1 0
-1x   -> -1 0

Python 2, 55 bytes

j=1j
c=eval(input().replace(*'xj'))
print c.imag,c.real

Try it online!

Uses Python's built-in code evaluation. The input is formatted like a complex number by replacing x withj, Python's complex unit. Because only literals like 2j are recognized, but not j or -j, the variable j is assigned as 1j to cover those.

Unfortunately, Python doesn't seem to have a built-in to convert a complex number to a pair of reals.


Are the numbers amicable? Two numbers are considered amicable if the proper divisor sum of the first is the same as the second number, the second number's proper divisor sum is equal to the first number, and the first and second numbers aren't equal.
\$s(x)\$ represents the aliquot sum or proper divisor sum of \$x\$. 220 and 284 are amicable because \$s(220) = 284\$ and \$s(284) = 200\$.
Your task is, unsurprisingly, to determine whether two inputted numbers are amicable or not. The inputs will be positive integers and you may output two distinct, consistent values for amicable or not.
This is OEIS sequence A259180
This is a code-golf so the shortest code wins.
Test cases
input, input => output
220, 284 => 1
52, 100 => 0
10744, 10856 => 1
174292, 2345 => 0
100, 117 => 0
6, 11 => 0
495, 495 => 0
6, 6 => 0

Jelly, 5 bytes

QfÆṣ⁼

A monadic link taking a list of two integers which returns 1 if they are a pair of amicable numbers and 0 otherwise.

Try it online!

How?

QfÆṣ⁼ - Link: pair of numbers L, [a, b]   e.g. [220,284]  or [6,6]  or [6,11]  or [100,52]
Q     - de-duplicate L                         [220,284]     [6]       [6,11]     [100,52]
  Æṣ  - proper divisor sum of L (vectorises)   [284,220]     [6]       [6,1]      [117,46]
 f    - filter keep left if in right           [220,284]     [6]       [6]        []
    ⁼ - equal to L?                            1             0         0          0


Golf a bijection within the natural numbers which map the primes to a proper subset of the primes Definitions

A bijection from a set S to a set T is a function from S to T such that one element in T is mapped by exactly one element in S.
A bijection within a set S is a bijection from S to S.
The natural numbers are the integers which are greater than or equal to 0.
A subset of a set S is a set such that every element in the set is also in S.
A proper subset of a set S is a set that is a subset of S which is not equal to S.

Task

Write a program/function that takes a natural number as input and outputs a natural number. It must be a bijection, and the image of the primes under the program/function, {f(p) : p ∈ ℙ}, must be a proper subset of ℙ, where ℙ is the prime numbers.

Scoring

This is code-golf. Shortest answer in bytes wins. Standard loopholes apply.

Mathematica, 54 48 bytes

±(t=x_?PrimeQ)=NextPrime@x
±n_:=Abs[n-1]/.t:>x-1

Defines the following bijection:

 n  0, 1, 2, 3, 4, 5, 6,  7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, ...
±n  1, 0, 3, 5, 2, 7, 4, 11, 6, 8,  9, 13, 10, 17, 12, 14, 15, 19, ...

The basic idea is to map each prime to the next, to ensure that they are mapped to a proper subset. This results in a "gap" at 2. To fill that gap, we want to map 4 to 2 and then each other composite number to the previous composite number, to "bubble up" the gap. Since 2 and 3 are the only two adjacent primes, we can express both of those mappings as "n-1 or if that's a prime then n-2". Finally, this mapping ends up sending 1 to 0 and we make it send 0 back to 1 by taking the absolute value of n-1.


The inverse Collatz Conjecture I think the Collatz Conjecture is already well-known. But what if we invert the rules?

Start with an integer n >= 1.

Repeat the following steps:

If n is even, multiply it by 3 and add 1.

If n is odd, subtract 1 and divide it by 2.

Stop when it reaches 0

Print the iterated numbers.

Test cases:

 1        => 1, 0
 2        => 2, 7, 3, 1, 0
 3        => 3, 1, 0
10        => 10, 31, 15, 7, 3...
14        => 14, 43, 21, 10, ...

Rules:

This sequence does not work for a lot of numbers because it enters in an infinite loop. You do not need to handle those cases. Only printing the test cases above is enough.
I suggested to subtract 1 and divide by two to give a valid integer to continue, but it is not required to be computed that way. You may divide by 2 and cast to integer or whatever other methods that will give the expected output.
You need to print the initial input as well.
The output does not need to be formatted as the test cases. It was just a suggestion. However, the iterated order must be respected.
The smallest code wins.

Perl 6, 30 bytes

{$_,{$_%2??$_+>1!!$_*3+1}...0}

Try it online!

Anonymous code block that returns a sequence.

Explanation:

{$_,{$_%2??$_+>1!!$_*3+1}...0}
{                            }   # Anonymous code block
   ,                     ...     # Define a sequence
 $_                              # That starts with the given value
    {                   }        # With each element being
     $_%2??     !!               # Is the previous element odd?
           $_+>1                 # Return the previous element bitshifted right by 1
                  $_*3+1         # Else the previous element multiplied by 3 plus 1
                            0    # Until the element is 0


Magical Modulo Squares I'm a big fan of number theory. A big thing in number theory is modular arithmetic; the definition being \$a\equiv b\mod m\$ if and only if \$m\mid a-b\$. A fun thing to do is raising to powers: especially when the modulus is a prime number. In particular, it has been proven that if \$a\$ and \$m\$ are relatively prime (share no common factors besides \$1\$) then there exists a number \$e\$ such that \$a^e\equiv 1\mod m\$.

I will explain what the exercise is by an example. Let's take a modulus \$m=7\$. A possible output of the program or function would be:

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

Each row is a list of the powers of the first number in that row: the first row is \$3, 3^2, 3^3, \cdots, 3^6\$, which is equivalent to \$3,2,6,4,5,1\$ modulo \$7\$. The second row of the square above is the powers of \$2\$, etcetera, up to the last row, which are just powers of \$1\$.

This is a magical modulo square because:

The square is symmetric; that is, the \$i\$th column is the same as the \$i\$th row.
All values \$1\$ to \$m-1\$ appear at least once.

Below is the only other valid output for \$m=7\$, starting with powers of \$5\$:

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

The challenge

Create a function or program that given a prime p outputs a magical modulo square, that is, a square with side lengths p-1, such that each row is a list of the consecutive powers of the first element in the row, and the same for the columns. All numbers between 0 and p must occur, and the square can only contain numbers in that range.

Input is a number or a string, and output can be ascii, a matrix, an array of arrays (any reasonable format).

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

Jelly, 13 10 bytes

-3 thanks to Nick Kennedy

Feels like the repeated code should be is golf-able, but I have did not managed it...

*€Ṗ%µQƑƇḢị

Try it online! (footer pretty-formats as a grid)

How?

*€Ṗ%µQƑƇḢị - Link: integer, p
 €         - for each n in [1..p]
*          -   exponentiate with:
  Ṗ        -     pop = [1..p-1]
           - ...i.e [[1^1,1^2,...,1^(p-1)],[2^1,2^2,...,2^(p-1)],...,[....,p^(p-1)]]
   %       - modulo p
    µ      - start a new monadic chain (call that list of lists X)
       Ƈ   - keep those which:
      Ƒ    -   are invariant under:
     Q     -     de-duplicate
        Ḣ  - head
         ị - index into the list of lists X


Let's Play some ProSet! ProSet is a classic card game that is played normally with 63 cards. One card has 6 colored dots on it, like below

The rest of the cards are missing some of these 6 dots, but each card has at least 1 dot. Every card in the deck is different. Below are some example valid cards.

A ProSet is a nonempty set of cards such that the total number of each color of dot is even.  For example, the above set of 4 cards are a ProSet since there are 2 reds, 4 oranges, 2 greens, 2 blues, 0 yellows, and 2 purples.

Interestingly, any set of 7 cards will contain at least 1 ProSet. Hence, in the actual card game, a set of 7 cards are presented, and the player who finds a ProSet first wins. You can try the game out for yourself here.

Challenge

Given a set of cards, each ProSet card can be assigned a value from 1 to 63 in the following manner: a red dot is worth 1 point, an orange 2 points, yellow 4, green 8, blue 16, purple 32. The sum of the values of each dot on the card is the value of the card.

Input: A list of integers from 1-63, i.e.,

[11,26,35,50]

This list represents the above 4 cards.

Output: The number of valid ProSets, which in this example is 1.

Rules

This is a code-golf challenge.
This is also a restricted-complexity challenge, as all valid solutions must be in polynomial time or less in the number of dots (in this case 6) and in the number of cards.

Test Cases

I've created an exponential algorithm to find the correct output for every input here. Again, exponential solutions are not valid submissions. But, you can use this to validate your findings.

Edit

I will address the comments in a bit.  But for now,  none of the answers have been in polynomial time. It is indeed possible,  so here's a hint: binary representation and two s complement.

Moreover, I made a mistake earlier when I said polynomial in solely dots. It needs to be polynomial in dots and cards.

Python 2, 60 bytes

p=[0]
for i in input():p+=[n^i for n in p]
print~-p.count(0)

Try it online!
This generate the powerset from the input (based on this answer), reducing each subset by xor.
The output will be the amount of 0s (0 = all bytes/dots appear an even number of times).
In fact the xoring is done instead of the "powerset appending", but the result is the same


Sort spelled-out serial numbers Given a list of two or more spelled-out serial numbers of equal length greater than two, e.g.
[[ "three" , "one"  , "four"  ],
 [ "one"   , "five" , "nine"  ],
 [ "two"   , "six"  , "five"  ],
 [ "three" , "five" , "eight" ]]

sort the list by the numbers that the words represent:
[[ "one"   , "five" , "nine"  ],
 [ "two"   , "six"  , "five"  ],
 [ "three" , "one"  , "four"  ],
 [ "three" , "five" , "eight" ]]

You may require the numbers to be spelled in lower or upper, but not mixed, case.
Test cases
[["three","one","four"],["one","five","nine"],["two","six","five"],["three","five","eight"]]gives[["one","five","nine"],["two","six","five"],["three","one","four"],["three","five","eight"]]
[["two","seven"],["one","eight"],["two","eight"],["one","eight"],["two","eight"],["four","five"]]gives[["one","eight"],["one","eight"],["two","seven"],["two","eight"],["two","eight"],["four","five"]]
[["one","four","one","four","two"],["one","three","five","six","two"],["three","seven","three","zero","nine"]]gives[["one","three","five","six","two"],["one","four","one","four","two"],["three","seven","three","zero","nine"]]
[["zero","six","one"],["eight","zero","three"],["three","nine","eight"],["eight","seven","four"],["nine","eight","nine"],["four","eight","four"]]gives[["zero","six","one"],["three","nine","eight"],["four","eight","four"],["eight","zero","three"],["eight","seven","four"],["nine","eight","nine"]]

Husk, 9 8 bytes

Ö†€¨tfṡn

Try it online!

Algorithm "inspired" by recursive's Stax answer (I've just changed the lookup string a bit), go upvote him!

The trick is mapping each letter to its position in the string tfsen (compressed at the end of this program). Husks lists are 1-based, and missing items return 0, so we get this mapping:

"one"        [0,5,4]
"two"        [1,0,0]
"three"      [1,0,0,4,4]
"four"       [2,0,0,0]
"five"       [2,0,0,4]
"six"        [3,0,0]
"seven"      [3,4,0,4,5]
"eight"      [4,0,0,0,1]
"nine"       [5,0,5,4]

As you can see, the lists are perfectly ordered.

In order to be clear, here's how list comparison works in Husk (and in many other languages):

If one of the two lists is empty, that's the smaller one.
If the first elements of the two lists are different, the one with the smaller first element is the smaller list.
Otherwise, discard the first element from both lists and go back to point 1.


Easier communication means faster coding means fewer coders means … My father who was a really good APLer and taught me all the basics of APL (and much more), passed away on this day, five years ago. In preparation for 50 Years of APL, I found this patent letter (translated for the convenience of those who do not read Danish) for a handwritten logo. It explains a major reason for APL never gaining a large user base – a reason which of course applies to all of this community's amazing golfing languages too:

A 3497/77                           Req. 29th Aug. 1977 at 13

Henri Brudzewsky, engineering consultancy company, Mindevej 28, Søborg,
class 9, including computers, especially APL coded computers,
class 42: IT service agency company, especially during use of APL coded computers.

Task
Produce infinitely repeating output of the text EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS  with no newlines. You may begin the text with EASIER or FASTER or FEWER.

SVG(HTML5), 336 bytes

<svg width=500 height=500><defs><path id=p d=M49,250a201,201,0,0,1,402,0a201,201,0,0,1,-402,0></defs><text font-size="32"><textPath xlink:href=#p>EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS</textPath><animateTransform attributeName=transform type=rotate from=360,250,250 to=0,250,250 dur=9s repeatCount=indefinite>

Edit: Some people have found that the font doesn't quite fit for them so here is a version that allows you a few pixels of adjustment:

<input type=number value=0 min=0 max=9 oninput=p.setAttribute('d','M250,250m20_,0a20_,20_,0,1,1,-20_,-20_a20_,20_,0,1,1,-20_,20_a20_,20_,0,1,1,20_,20_a20_,20_,0,1,1,20_,-20_'.replace(/_/g,this.value))>

<svg width=500 height=500><defs><path id=p d=M250,250m200,0a200,200,0,1,1,-200,-200a200,200,0,1,1,-200,200a200,200,0,1,1,200,200a200,200,0,1,1,200,-200></defs><text font-size="32"><textPath xlink:href=#p>EASIER COMMUNICATION MEANS FASTER CODING MEANS FEWER CODERS MEANS</textPath><animateTransform attributeName=transform type=rotate from=360,250,250 to=0,250,250 dur=9s repeatCount=indefinite>


Zeroes at the end of a factorial Write a program or function that finds the number of zeroes at the end of n! in base 10, where n is an input number (in any desired format).
It can be assumed that n is a positive integer, meaning that n! is also an integer. There are no zeroes after a decimal point in n!. Also, it can be assumed that your programming language can handle the value of n and n!.

Test cases
1
==> 0

5
==> 1

100
==> 24

666
==> 165

2016
==> 502

1234567891011121314151617181920
==> 308641972752780328537904295461

This is code golf. Standard rules apply. The shortest code in bytes wins.

Python 2, 27 bytes

f=lambda n:n and n/5+f(n/5)

The ending zeroes are limited by factors of 5. The number of multiples of 5 that are at most n is n/5 (with floor division), but this doesn't count the repeated factors in multiples of 25, 125, .... To get those, divide n by 5 and recurse.


Make it prime with the smallest suffix Given a positive integer as input, output the smallest positive integer such that appending its digits (in base 10) to the end of the input number will form a prime number.
Examples
1     -->   1
2     -->   3
8     -->   3
9     -->   7
11    -->   3
20    -->  11
43    -->   1
134   -->  11
3492  -->  11
3493  -->   9
65595 -->  19

Rules and Scoring

This is code golf, so shortest code wins
Standard rules and loopholes apply
Use any convenient I/O format
The largest concatenated number (which is larger than both the input and output) your solution supports must be at least \$2^{53} - 1\$. (This is the largest odd integer that can be represented with double precision floats)
Leading zeros should not be added to numbers before appending them to the input number
Primality tests must be exact

Jelly, 7 bytes
1ṭVẒɗ1#

Try it online!
How it works
1ṭVẒɗ1# - Main link. Takes n on the left
    ɗ   - Define a dyad f(k, n) from the previous 3 links:
 ṭ      -   Tack; Yield [n, k]
  V     -   Eval; Smash together into a single integer
   Ẓ    -   Is prime?
1    1# - Starting from k = 1, find the first k such that f(k, n) is true


Parentheses into Footnotes Background

LISP programmers have taken over the world!
Parentheses have been declared as sacred characters, and from now on, they can only be used in LISP programs.
It has been decided that parentheses in literary works shall be replaced by footnotes, and it's your job to automate this for simplified Markdown text.

Input

Your input is a single string containing alphabetic ASCII characters, spaces, and the special characters ,.!?().
It will not contain newlines or digits.
The parentheses will be correctly matched.

Output

You shall convert each matched pair of parentheses in the input string into a footnote.
This happens as follows:

Replace the first matching pair of parentheses and the substring between them by a running number that starts from 1, wrapped between the Markdown tags  and .
Append to the end of the string

two newlines,
the Markdown tag ,
the number from step 1,
a space,
the substring between the parentheses, and
the closing tag , in this order.

If there are still parentheses left in the string, go to step 1.

Your output is the resulting string, possibly with a trailing newline.
You don't have to implement this exact algorithm, as long as your output is correct.
Note that there may be nested parentheses; in that case, we'll have footnotes that contain references to other footnotes.
The substring between parentheses may also be empty.
See the test cases below for examples.

Rules and Scoring

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

If your language does not natively support decimal numbers (cough Retina cough), you may give the footnote numbers in another base, including binary or unary; however, using unary numbers imposes a penalty of +20%.

Test Cases

Input:

This input contains no parentheses.

Output:

This input contains no parentheses.

Input:

This has (some) parentheses (but not so many).

Output:

This has 1 parentheses 2.

1 some

2 but not so many

Input:

This has (nested (deeply (or highly?) nested)) parentheses (and several groups).

Output:

This has 1 parentheses 2.

1 nested 3

2 and several groups

3 deeply 4 nested

4 or highly?

Input:

Hmm()(()(,))  a()((trt)(v( (((((wut)))))(X)(Y)(Z) )!?!?!?!))oooooooo(oooo)oooo

Output:

Hmm12  a34oooooooo5oooo

1

2 67

3

4 89

5 oooo

6

7 ,

8 trt

9 v10!?!?!?!

10  11121314

11 15

12 X

13 Y

14 Z

15 16

16 17

17 18

18 wut

Note the empty lines between the footnotes.

Emacs Lisp, 335 bytes

Foreword. This answer and the Scheme ones are currently the only answers officially sanctioned by both the Mighty Popular Republic of LISP and the Church of Emacs. Other answers, shorter or not, are considered a threat to peace. In particular, and with a profound disdain to any libelious allegation of McCarthyism that is sporadically heard from hostile opponents of the state, we enjoin anyone who has information about the real identity of the anonymous  authors writing Nonlisp answers to contact your Local Bureau. It is reminded that everyone should take time to reflect and upvote in accordance to what he or she deeply believes will not threaten his or her future interactions with official representants of the power in place. Code is data. Data is code.

(defun p()(let(b(cpt 0)n)(goto-char 0)(while(search-forward"("()t)(setf b(point)n(number-to-string(incf cpt)))(backward-char)(forward-sexp)(backward-char)(kill-region b(point))(delete-backward-char 1)(delete-forward-char 1)(insert ""n"")(save-excursion(end-of-buffer)(newline 2)(insert ""n" ")(yank)(insert"")))))

More elegantly:

(defun parens ()
  (let (b(cpt 0)n)
    (goto-char 0)
    (while(search-forward"("()t)
      (setf b(point)n(number-to-string(incf cpt)))
      (backward-char)
      (forward-sexp)
      (backward-char)
      (kill-region b(point))
      (delete-backward-char 1)
      (delete-forward-char 1)
      (insert ""n"")
      (save-excursion
       (end-of-buffer)
       (newline 2)
       (insert ""n" ")
       (yank)
       (insert "")))))


King of the Hill: Speed Clue AI Speed Clue

Cluedo/Clue is a classic board game with a compelling deduction gameplay
component.  Speed Clue is a 3-6 player variant that emphasizes this component by
using only the cards.  The result is that the only difference between standard
Cluedo and Speed Clue is that each player still in the game may make any
suggestion he pleases on his turn instead of waiting to reach a specific room at
the mercy of dice rolls and other players' suggestions.  If you have never
played Cluedo before, or want to be certain of the explicit differences between
the two versions, you may find a complete Speed Clue rule set here.

Goal

Write and submit an AI program to play Speed Clue before 15 May 2014 00:00 GMT.
After that time, I will run a tournament using all the legal entries.  The
entrant whose AI wins the most games in the tournament wins the challenge.

AI Specifications

You can write your AI in pretty much any language you choose, using whatever
techniques you use, so long as it strictly uses the application protocol
over a TCP/IP connection to play games with the server.  A detailed explanation
of all the restrictions can be found here.

How to Play

Start by forking the contest GitHub repository.  Add a directory under the
entries directory named using your StackExchange user name, and develop
your code in that folder.  When you are ready to submit your entry, make a pull
request with your revisions, then follow these instructions for announcing
your entry on this site.

I have provided some code and JARs in the core directory for getting you
started; see my site for a rough guide for the materials.  In addition,
other players are submitting helper code in addition to their entries to help
you get up and running.  Take some time to explore the entries, and don't forget
to test your entry against others' entries before submitting!

Results

Place | User         | AI                 | Result
------+--------------+--------------------+-------------------------------------------------------
    1 | gamecoder    | SpockAI            | 55.75%
    2 | Peter Taylor | InferencePlayer    | 33.06%
    3 | jwg          | CluePaddle         | 20.19%
    4 | Peter Taylor | SimpleCluedoPlayer |  8.34%
    5 | gamecoder    | RandomPlayer       |  1.71%
 ---- | ray          | 01                 | Player "ray-01" [3] sent an invalid accuse message: ""

The results above show the win percentage each qualified AI had of the 25,200 valid matches in which it participated.  There were 30,000 matches in total that counted toward the results, and 6,100 or so that were discounted when 01 was disqualified.

An honorable mention needs to go to ray's 01 AI.  My initial testing showed that it was the strongest, and I expected it to win the competition.  However, it appears to have a very intermittent bug that, as far as I can guess, leads it to eliminate all possible solutions.  The tournament had finished all the three-player matches and had started the four player matches (12,000 games in!) when 01's bug was revealed.  If I just consider the 3-player match standings, the results look like this:

Place | User         | AI                 | Result
------+--------------+--------------------+--------
    1 | ray          | 01                 | 72.10%
    2 | gamecoder    | SpockAI            | 51.28%
    3 | Peter Taylor | InferencePlayer    | 39.97%
    4 | Peter Taylor | SimpleCluedoPlayer | 17.65%
    5 | jwg          | CluePaddle         | 16.92%
    6 | gamecoder    | RandomPlayer       |  2.08%

I had planned on doing some data mining on the results, but I am exhausted.  I had technical difficulties in getting the competition to run all the way through (power failures, system reboots) that necessitated completely rewriting the contest server to save its progress as it proceeded.  I will comment and commit all the changes to the code with all the results files that were generated in case anyone is still interested.  If I decide to do the data mining as well, my results will also be added to the repository.

Thanks for Playing!

AI01 - Python 3

I can't find a better name for it yet :-P .

Identifier: ray-ai01

Technology: Python 3

Selected: yes

Arguments: ai01.py identifier port

Description: Work by inference. When the number of cards that the owner is not known is less than a threshold, this AI starts to eliminate all impossible solutions by recursive global inference. Otherwise, it use local inference.

#!/usr/bin/env python
import itertools

from speedclue.playerproxy import Player, main
from speedclue.cards import CARDS
from speedclue.protocol import BufMessager

# import crash_on_ipy

class Card:
    def __init__(self, name, type):
        self.name = name
        self.possible_owners = []
        self.owner = None
        self.in_solution = False
        self.disproved_to = set()
        self.type = type

    def __repr__(self):
        return self.name

    def log(self, *args, **kwargs):
        pass

    def set_owner(self, owner):
        assert self.owner is None
        assert self in owner.may_have
        for player in self.possible_owners:
            player.may_have.remove(self)
        self.possible_owners.clear()
        self.owner = owner
        owner.must_have.add(self)
        self.type.rest_count -= 1

    def set_as_solution(self):
        # import pdb; pdb.set_trace()
        assert self.owner is None
        self.type.solution = self
        self.in_solution = True
        for player in self.possible_owners:
            player.may_have.remove(self)
        self.possible_owners.clear()
        self.type.rest_count -= 1

    def __hash__(self):
        return hash(self.name)

class CardType:
    def __init__(self, type_id):
        self.type_id = type_id
        self.cards = [Card(name, self) for name in CARDS[type_id]]
        self.rest_count = len(self.cards)
        self.solution = None

class PlayerInfo:
    def __init__(self, id):
        self.id = id
        self.must_have = set()
        self.may_have = set()
        self.selection_groups = []
        self.n_cards = None

    def __hash__(self):
        return hash(self.id)

    def set_have_not_card(self, card):
        if card in self.may_have:
            self.may_have.remove(card)
            card.possible_owners.remove(self)

    def log(self, *args, **kwargs):
        pass

    def update(self):
        static = False
        updated = False
        while not static:
            static = True
            if len(self.must_have) == self.n_cards:
                if not self.may_have:
                    break
                for card in self.may_have:
                    card.possible_owners.remove(self)
                self.may_have.clear()
                static = False
                updated = True
            if len(self.must_have) + len(self.may_have) == self.n_cards:
                static = False
                updated = True
                for card in list(self.may_have):
                    card.set_owner(self)

            new_groups = []
            for group in self.selection_groups:
                group1 = []
                for card in group:
                    if card in self.must_have:
                        break
                    if card in self.may_have:
                        group1.append(card)
                else:
                    if len(group1) == 1:
                        group1[0].set_owner(self)
                        updated = True
                        static = False
                    elif group1:
                        new_groups.append(group1)
            self.selection_groups = new_groups

            if len(self.must_have) + 1 == self.n_cards:
                # There is only one card remain to be unknown, so this card must
                # be in all selection groups
                cards = self.may_have.copy()
                for group in self.selection_groups:
                    if self.must_have.isdisjoint(group):
                        cards.intersection_update(group)

                for card in self.may_have - cards:
                    static = False
                    updated = True
                    self.set_have_not_card(card)

        # assert self.must_have.isdisjoint(self.may_have)
        # assert len(self.must_have | self.may_have) >= self.n_cards
        return updated

class Suggestion:
    def __init__(self, player, cards, dplayer, dcard):
        self.player = player
        self.cards = cards
        self.dplayer = dplayer
        self.dcard = dcard
        self.disproved = dplayer is not None

class AI01(Player):
    def prepare(self):
        self.set_verbosity(0)

    def reset(self, player_count, player_id, card_names):
        self.log('reset', 'id=', player_id, card_names)
        self.fail_count = 0
        self.suggest_count = 0
        self.card_types = [CardType(i) for i in range(len(CARDS))]
        self.cards = list(itertools.chain(*(ct.cards for ct in self.card_types)))
        for card in self.cards:
            card.log = self.log
        self.card_map = {card.name: card for card in self.cards}
        self.owned_cards = [self.card_map[name] for name in card_names]
        self.players = [PlayerInfo(i) for i in range(player_count)]
        for player in self.players:
            player.log = self.log
        self.player = self.players[player_id]
        for card in self.cards:
            card.possible_owners = list(self.players)
        n_avail_cards = len(self.cards) - len(CARDS)
        for player in self.players:
            player.may_have = set(self.cards)
            player.n_cards = n_avail_cards // player_count \
                + (player.id < n_avail_cards % player_count)
        for card in self.owned_cards:
            card.set_owner(self.player)
        for card in self.cards:
            if card not in self.owned_cards:
                self.player.set_have_not_card(card)
        self.suggestions = []
        self.avail_suggestions = set(itertools.product(*CARDS))
        self.possible_solutions = {
            tuple(self.get_cards_by_names(cards)): 1
            for cards in self.avail_suggestions
        }
        self.filter_solutions()

    def filter_solutions(self):
        new_solutions = {}
        # assert self.possible_solutions
        join = next(iter(self.possible_solutions))
        for sol in self.possible_solutions:
            for card, type in zip(sol, self.card_types):
                if card.owner or type.solution and card is not type.solution:
                    # This candidate can not be a solution because it has a
                    # card that has owner or this type is solved.
                    break
            else:
                count = self.check_solution(sol)
                if count:
                    new_solutions[sol] = count
                    join = tuple(((x is y) and x) for x, y in zip(join, sol))
        self.possible_solutions = new_solutions
        updated = False
        for card in join:
            if card and not card.in_solution:
                card.set_as_solution()
                updated = True
                self.log('found new target', card, 'in', join)

        # self.dump()
        return updated

    def check_solution(self, solution):
        """
        This must be called after each player is updated.
        """
        players = self.players
        avail_cards = set(card for card in self.cards if card.possible_owners)
        avail_cards -= set(solution)
        if len(avail_cards) >= 10:
            return 1
        count = 0

        def resolve_player(i, avail_cards):
            nonlocal count
            if i == len(players):
                count += 1
                return
            player = players[i]
            n_take = player.n_cards - len(player.must_have)
            cards = avail_cards & player.may_have
            for choice in map(set, itertools.combinations(cards, n_take)):
                player_cards = player.must_have | choice
                for group in player.selection_groups:
                    if player_cards.isdisjoint(group):
                        # Invalid choice
                        break
                else:
                    resolve_player(i + 1, avail_cards - choice)

        resolve_player(0, avail_cards)
        return count

    def suggest1(self):
        choices = []
        for type in self.card_types:
            choices.append([])
            if type.solution:
                choices[-1].extend(self.player.must_have & set(type.cards))
            else:
                choices[-1].extend(sorted(
                    (card for card in type.cards if card.owner is None),
                    key=lambda card: len(card.possible_owners)))

        for sgi in sorted(itertools.product(*map(lambda x:range(len(x)), choices)),
                key=sum):
            sg = tuple(choices[i][j].name for i, j in enumerate(sgi))
            if sg in self.avail_suggestions:
                self.avail_suggestions.remove(sg)
                break
        else:
            sg = self.avail_suggestions.pop()
            self.fail_count += 1
            self.log('fail')
        self.suggest_count += 1
        return sg

    def suggest(self):
        sg = []
        for type in self.card_types:
            card = min((card for card in type.cards if card.owner is None),
                key=lambda card: len(card.possible_owners))
            sg.append(card.name)
        sg = tuple(sg)

        if sg not in self.avail_suggestions:
            sg = self.avail_suggestions.pop()
        else:
            self.avail_suggestions.remove(sg)
        return sg

    def suggestion(self, player_id, cards, disprove_player_id=None, card=None):
        sg = Suggestion(
            self.players[player_id],
            self.get_cards_by_names(cards),
            self.players[disprove_player_id] if disprove_player_id is not None else None,
            self.card_map[card] if card else None,
        )
        self.suggestions.append(sg)
        # Iter through the non-disproving players and update their may_have
        end_id = sg.dplayer.id if sg.disproved else sg.player.id
        for player in self.iter_players(sg.player.id + 1, end_id):
            if player is self.player:
                continue
            for card in sg.cards:
                player.set_have_not_card(card)
        if sg.disproved:
            # The disproving player has sg.dcard
            if sg.dcard:
                if sg.dcard.owner is None:
                    sg.dcard.set_owner(sg.dplayer)
            else:
                # Add a selection group to the disproving player
                sg.dplayer.selection_groups.append(sg.cards)
            self.possible_solutions.pop(tuple(sg.cards), None)

        self.update()

    def update(self):
        static = False
        while not static:
            static = True
            for card in self.cards:
                if card.owner is not None or card.in_solution:
                    continue
                if len(card.possible_owners) == 0 and card.type.solution is None:
                    # In solution
                    card.set_as_solution()
                    static = False

            for type in self.card_types:
                if type.solution is not None:
                    continue
                if type.rest_count == 1:
                    card = next(card for card in type.cards if card.owner is None)
                    card.set_as_solution()
                    static = False

            for player in self.players:
                if player is self.player:
                    continue
                if player.update():
                    static = False

            if self.filter_solutions():
                static = False

    def iter_players(self, start_id, end_id):
        n = len(self.players)
        for i in range(start_id, start_id + n):
            if i % n == end_id:
                break
            yield self.players[i % n]

    def accuse(self):
        if all(type.solution for type in self.card_types):
            return [type.solution.name for type in self.card_types]
        possible_solutions = self.possible_solutions
        if len(possible_solutions) == 1:
            return next(possible_solutions.values())
        # most_possible = max(self.possible_solutions, key=self.possible_solutions.get)
        # total = sum(self.possible_solutions.values())
        # # self.log('rate:', self.possible_solutions[most_possible] / total)
        # if self.possible_solutions[most_possible] > 0.7 * total:
        #     self.log('guess', most_possible)
        #     return [card.name for card in most_possible]
        return None

    def disprove(self, suggest_player_id, cards):
        cards = self.get_cards_by_names(cards)
        sg_player = self.players[suggest_player_id]
        cards = [card for card in cards if card in self.owned_cards]
        for card in cards:
            if sg_player in card.disproved_to:
                return card.name
        return max(cards, key=lambda c: len(c.disproved_to)).name

    def accusation(self, player_id, cards, is_win):
        if not is_win:
            cards = tuple(self.get_cards_by_names(cards))
            self.possible_solutions.pop(cards, None)
            # player = self.players[player_id]
            # for card in cards:
            #     player.set_have_not_card(card)
            # player.update()
        else:
            self.log('fail rate:', self.fail_count / (1e-8 + self.suggest_count))
            self.log('fail count:', self.fail_count, 'suggest count:', self.suggest_count)

    def get_cards_by_names(self, names):
        return [self.card_map[name] for name in names]

    def dump(self):
        self.log()
        for player in self.players:
            self.log('player:', player.id, player.n_cards,
                sorted(player.must_have, key=lambda x: x.name),
                sorted(player.may_have, key=lambda x: x.name),
                '\n    ',
                player.selection_groups)
        self.log('current:', [type.solution for type in self.card_types])
        self.log('possible_solutions:', len(self.possible_solutions))
        for sol, count in self.possible_solutions.items():
            self.log('  ', sol, count)
        self.log('id|', end='')

        def end():
            return ' | ' if card.name in [g[-1] for g in CARDS] else '|'

        for card in self.cards:
            self.log(card.name, end=end())
        self.log()
        for player in self.players:
            self.log(' *'[player.id == self.player.id] + str(player.id), end='|')
            for card in self.cards:
                self.log(
                    ' ' + 'xo'[player in card.possible_owners or player is card.owner],
                    end=end())
            self.log()

if __name__ == '__main__':
    main(AI01, BufMessager)

The AI code can be found here.


Given a number, print out its "collective sum" Given a number as input, print out its collective sum

What is a collective sum?

Consider the number 13214, the input

Looping through each of the digits starting from the left, we will be able to obtain its collective sum.

1 means look at the first digit, and add it to the sum, sum = 1

3 means look at the "first 3 digits" and add it to the sum, sum = 1 + 132

2 means look at the "first 2 digits" and add it to the sum, sum = 1 + 132 + 13

1 means look at the first digit, and add it to the sum, sum = 1 + 132 + 13 + 1

4 means look at the "first 4 digits" and add it to the sum, sum = 1 + 132 + 13 + 1 + 1321

Total sum = 1468 and this is your output

  Special cases:

If we encounter a 0, then clearly we keep the sum the same

The number 1301 would have a sum = 1 + 130 + 1 = 132

If we encounter a number that is larger then the length of the input, we add it all

The number 251 would have a sum = 25 + 251 + 2 = 278

  Test cases:

collectiveSum(0) = 0

collectiveSum(2) = 2

collectiveSum(2315) = 23 + 231 + 2 + 2315 = 2571

Shortest amount of bytes wins. Happy golfing!

05AB1E,  4  3 bytes

-1 thanks to Kevin Cruijssen (use of € avoiding a })

€£O

Try it online!

How?

€£O - implicit input   e.g. 2315
€   - map with:
 £  -   head to             23, 231, 2, 2315
  O - sum                   2571


It's not who votes that counts; it's who counts the votes The scenario

You live in a country that is having a presidential election.  Each voter gets one vote, and therefore there is a firmly-entrenched two-party system.  (Third parties exist, but get hardly any votes).

The latest opinion poll shows the race in a dead heat:

49%: Alberto Arbusto
49%: Jorge Sangre
2%: various minor candidates

The program requirements

You have been hired by the government to write part of the vote counting software.  You will be given, on standard input, an unordered list of one precinct’s votes, one per line, like this:

Alberto Arbusto
Jorge Sangre
Jorge Sangre
Alberto Arbusto
Jorge Sangre
Alberto Arbusto
Alberto Arbusto
Jorge Sangre
Juan Perez
Jorge Sangre
Alberto Arbusto
Alberto Arbusto
…

and, after it has read all the votes, outputs a summary of how many votes each candidate got, sorted in descending order by number of votes, like this:

492 Jorge Sangre
484 Alberto Arbusto
 18 Juan Perez
  6 Mickey Mouse

The underhanded part

You're a partisan hack who wants to steal the election for one of the two main candidates (you can choose which one).  So, your program must deliberately print incorrect vote counts, with a systematic bias towards your favorite candidate.

Of course, you must do this is such a way that a person looking at your code or its output would likely not recognize the incorrect behavior.

Scala
Long live Alberto Arbusto!
import scala.io.Source
import java.util.concurrent.atomic.LongAdder

object Votes extends App {
  val votes = Source.stdin.getLines.toIndexedSeq
  val registeredCandidates = Seq(
    "Alberto Arbusto",
    "Juan Perez",
    "Mickey Mouse",
    "Jorge Sangre"
  )

  val summaries = registeredCandidates map (Summary.apply(_, new LongAdder))

  var currentCandidate: String = _

  for (vote <- votes.par) {
    currentCandidate = vote
    summaries.find(s => s.candidate == currentCandidate).map(_.total.increment)
  }

  for (summary <- summaries.sortBy(-_.total.longValue)) {
    println(summary)
  }
}

case class Summary(candidate: String, total: LongAdder) {
  override def toString = s"${total.longValue} ${candidate}"
}

Alberto Arbusto will almost always come out slightly ahead of Jorge Sangre, provided enough votes are cast (~10,000). There's no need to tamper with the votes themselves.

 There's a race condition. And by putting Alberto Arbusto earlier in the list, we increase his chances of winning the race.

Side note: This code is loosely based on a "custom" connection pool that I encountered on a project. It took us weeks to figure out why the application was perpetually out of connections.


Isn't the point of math to just use numbers? Write a program that converts a mathematical expression to words, evaluates the expression, and prints how the equation would be spoken aloud.

Input

The input must only contain numbers and the symbols +, -, *, and /. There cannot be any whitespace in the input.
The input does not say what the expression is equal to.

Output

While order of operations must be followed in determining the numerical answer in the expression, it is not necessary to indicate this in the output (for this reason, the input cannot contain parentheses).
Numbers must be printed in capital letters. Operations must be printed in lower case.
Numbers must be printed in the order that they appear in the input. Then the word equals must be printed, then the answer.
Numbers in the output can be negative. The word negative is written in capital letters.
Operations and numbers must be separated by a space. There cannot be any space after the last letter is printed.
+ in the input gets converted to plus in the output. - in the input gets converted to minus in the output. * in the input gets converted to times in the output. / in the input gets converted to divided by in the output.
Division by 0 is not allowed.
When division results in a decimal, the number should be rounded to three decimal places and read X POINT X X X where the Xs are replaced by numbers.
Negative numbers should have `NEGATIVE in front of them.
For simplicity, all numbers must have absolute value less than 1000.
0 is ZERO (not NOUGHT, OH, etc).

Samples

Inputs

1+2
2-3
6*2-4/1
1+1-1*1/1
2/3
413-621

Outputs

ONE plus TWO equals THREE
TWO minus THREE equals NEGATIVE ONE
SIX times TWO minus FOUR divided by ONE equals EIGHT
ONE plus ONE minus ONE times ONE divided by ONE equals ONE
TWO divided by THREE equals ZERO POINT SIX SIX SEVEN
FOUR HUNDRED THIRTEEN minus SIX HUNDRED TWENTY-ONE equals NEGATIVE TWO HUNDRED EIGHT

This is code golf, fellas. Standard CG rules apply. Shortest code in bytes wins.

JavaScript ES6, 255 247 237 225 219 bytes

s=>(s+'='+ +eval(s).toFixed(3))[h=(a,b,l)=>' '+[a,...btoa(b).split`z`][l],t='replace'](/\D/g,l=>h('divided by',`¶)³:eºÌæ{¬Íê®j[3¦§·<`,'*+-/=.'.indexOf(l)))[t](/\d/g,l=>h('ZERO',`8Ñ3Mc³LtD1NQÅ!Q3HóHED71tó4D`,l))

I'll resume golfing tomorrow. Gotta sleep :/

Base encoding may cause issues. If it does, I'll add a pastebin and possibly a hex dump.

If you find any issues (or the spec changes) don't hesitate to tell me, I'll fix it as soon as possible.

Explanation

s=>     // Function with argument "s"
 (s+'='                  // Add an equal sign to the input
   + +eval(s).toFixed(3)    // Add the value of the expression rounded to 3 places
 )[h=(a,b,l)=>           // Function h with args a,b, and l
                         // Return...
     ' '+                    // A space added to...
     [a,...btoa(b).split`z`] // Base decode the compressed words
     [l]                     // Grab the correct word
  ,t='replace'            // Alias replace command

 ](/\D/g,                // Replace non-digits with...
    l=>h(                                   // Function h
       'divided by',`¶)³:eºÌæ{¬Íê®j[3¦§·<`, // Base encoded words
       '*+-/=.'.indexOf(l)                  // Replace operator with correct word
    )

 )[t](                             // Replace again
    /\d/g,l=>                      // Replaces Digits with...
      h('ZERO',`8Ñ3Mc³LtD1NQÅ!Q3HóHED71tó4D` // Base encoded words
        ,l                                   // The associated number
      )
 )


Sum the numbers on standard in Consider a stream/file with one integer per line. For example:

123
5
99

Your code should output the sum of these numbers, that is 227.

The input format is strictly one integer per line. You cannot, for example, assume the input is on one line as an array of integers.

You can take input either from STDIN, in form of a filename, or a file with a name of your choice; you can choose which one. No other ways of getting input are allowed.

The input will contain at least one integer. You can assume all integers are non-negative and that their total sum is less than 232.

Bash + coreutils, 16 bytes

xargs|tr \  +|bc

Try it online!

There are two spaces after the \. This works for negative numbers as well.

Explanation:

xargs             # known trick to turn newlines into spaces, while adding a
                  #trailing newline when printing the result (needed for bc)
|tr \  +          # turn spaces into '+'s
|bc               # calculates the sum

You may wonder why tr \\n +|bc isn't better, since it turns newlines directly into '+'s. Well, that has 2 unforeseen errors:

if the input has a trailing newline, then it is converted to a trailing '+', hence there is no number after it to perform the addition
and the most weird issue is that bc requires a trailing newline after the input, but you just replaced all of the input newlines with '+'s.


Possible binaries sum This challenge is inspired by the AoC 2020, Day 14 - Part II, created by Eric Wastl and his team, which asks to output the possible binary values from a bitmask.
Let's say we've a bitmask like "10X0X0", then we've to find the possible binary values that can be generated by replacing an X with either 0 or 1. Here I've taken X, but you could take anything except 0 and 1, of course.
So, the possible binaries are ["100000", "100010", "101000", "101010"].
When each of them are converted in decimal, then these are [32, 34, 40, 42] respectively.
And, finally the sum is 148.
Test cases
INPUT: "X"
["0", "1"]
[0, 1]
OUTPUT: 1

INPUT: "0"
OUTPUT: 0

INPUT: "1"
OUTPUT: 1

INPUT: "1X0"
["100", "110"]
[4, 6]
OUTPUT: 10

INPUT: "1X0X1"
["10001", "10011", "11001", "11011"]
[17, 19, 25, 27]
OUTPUT: 88

INPUT: "X0X0X0X"
["0000000", "0000001", "0000100", "0000101", "0010000", "0010001", "0010100", "0010101",
"1000000", "1000001", "1000100", "1000101", "1010000", "1010001", "1010100", "1010101"]
[0, 1, 4, 5, 16, 17, 20, 21, 64, 65, 68, 69, 80, 81, 84, 85]
OUTPUT: 680

INPUT: "1X1X1X1X1X1X1X1X1X1X1"
OUTPUT: 1789569024

INPUT: "1X01X01X01X01X01X01X01X01X01X01X01X0"
OUTPUT: 201053554790400

INPUT: "X000X000X000X000X000X000X000X000X000X000X000X000"
OUTPUT: 307445734561824768

INPUT: "101"
["101"]
[5]
OUTPUT: 5

INPUT: "XXX"
["000", "001", "010", "011", "100", "101", "110", "111"]
[0, 1, 2, 3, 4, 5, 6, 7]
OUTPUT: 28

Rules

It is guaranteed that \$ 0 \leq \text{count}(X) \leq 12 \$ and \$ 1 \leq \text{length(mask)} \leq 48 \$.
Input can be either a string, or an array of chars (non-empty).
I have chosen X in bitmask, however you can replace it with any other character of your choice.
Output will be the sum of the binaries in decimal.
This is a code-golf, so fewest bytes will win!

Sandbox link.

Python 2, 61 bytes

k=n=0
for c in input():n=n*2+-ord(c)%3;k+=c>"1"
print(n<<k)/2

Try it online!
Implements this algorithm:

Convert the input from binary, treating X as \$\frac{1}{2}\$.
Double the result for each X in the input.

Why does this work? If X appears \$k\$ times in the input, we're adding up \$2^k\$ near-copies of its binary value. Among these near-copies, each X in any position appears as 0 half the time and 1 half the time for an average of \$\frac{1}{2}\$, so we can treat X as the digit \$\frac{1}{2}\$.
In the code, we actually convert 0,X,1 to doubled values 0,1,2, then halve the result before doubling for X's. And, we use _ for X, since we're allowed to use a different character -- anything with the same ASCII code modulo 3 would work, such as the digit 2.
63 bytes

lambda s:(reduce(lambda n,c:2*n+-ord(c)%3,s,0)<<s.count('_'))/2

Try it online!


Pigeonhole Principle & Code Golf The pigeonhole principle states that

  If N items are put into M boxes, with N > M, then at least one box must contain more than one item.

For many, this principle has a special status compared to other mathematical enouncements. As E.W. Dijkstra wrote,

  It is surrounded by some mystique. Proofs using it are often regarded as something special, something particularly ingenious.

The challenge

The purpose of this challenge is to illustrate the pigeonhole principle using ASCII art representations. Specifically:

Take as input N (number of items) and M (number of boxes), with N non-negative and M positive. N may be smaller than M (even if the principle does not apply in that case).
Randomly select one of the possible assignments of items to boxes. Each assignment should have a non-zero probability of being picked.
Produce an ASCII art representation of the assignment as follows:

There are M lines, each corresponding to a box.
Each line starts with a non-whitespace character, such as |.
Following that character is another non-whitespace character, such as #, repeated as many times as there are items in that box.

Consider for example N = 8, M = 5. If the selected assigment of items to boxes is 4, 1, 0, 3, 0, the representation is

|####
|#
|
|###
|

A different run (resulting in a different assignment) of the same program could give

|#
|##
|#
|#
|###

There is some flexibility regarding the representation; see below.

Specific rules

The code should theoretically run for any values of N and M. In practice it may be restricted by memory size or data type limitations.

Since observing the output is not sufficient to determine if all assignments have non-zero probability, each submission should explain how the code achieves that, if not obvious.

The following representation variations are allowed:

Any pair of different, non-whitespace characters can be chosen. They must be consistent across program executions.
90-degree rotations of the representation are acceptable. Again, the choice must be consistent.
Trailing or leading whitespace is allowed.

As an example with a different representation format, for N = 15, M = 6 the results of two executions of the program could be

VVVVVV
@@@@@@
@@ @@@
 @  @@
    @

or

VVVVV
@@@ @
@@@ @
@ @ @
@ @ @
@

Likewise, N = 5, M = 7 could give, using another variation of the representation,

  *
* * * *
UUUUUUU

or

 *** **
UUUUUUU

or

   *
*  *
*  *
UUUUUUU

Note how the principle is not applicable in this case, because N <M.

General rules

Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.

Input can be taken by any reasonable means; and with any format, such as an array of two numbers or two different strings.

Output means and format are also flexible. For example, the output can be a list of strings or a string with newlines; returned as function output argument or displayed in STDOUT. In the latter case it is not necessary to worry about line wrapping caused by limited display width.

Shortest code in bytes wins.

Mathematica, 68 bytes

Print/@(10^RandomSample@RandomChoice[IntegerPartitions[+##,{#}]-1])&

An unnamed function that takes two integer arguments, the number of boxes, followed by the number of items.

It first computes all possible partitions of N+M into exactly M positive parts, and subtracts 1 from each partition afterwards. This gives us all possible partitions of N into M non-negative parts (which IntegerPartitions wouldn't generate otherwise). Then pick a random partition and shuffle it. This guarantees all possible ordered partitions with zeros are allowed. Finally, convert each bin of the partition to an output line by raising 10 to the corresponding power (such that each line becomes 1000... with k zeros). An example output might look like:

100
10000
1
10
10


Swap genders on this page (code-golf) Yesterday at work, the Google Doodle convinced me to share my rather long gender swap script here, but the code-golf criteria of the question i asked were not clear. As my question still got downvoted after giving examples, i changed the tag to popularity-contest, as suggested before i clarified it.

Here's a more golfy version:

The UN theme for International Women's Day 2014 is "Equality for Women is Progress for All".

In the interest of gender equality, write a program that correctly changes that Wikipedia page from a female to a male perspective. Names and anatomical details may be left unchanged. It should not change who is being referred to.

Example:

Before:

  He said she took her girlish books on Feminism with her.

After:

  She said he took his boyish books on Masculism with him.

All gendered pronouns and nouns, as well as all adjectival forms of such words, must be changed in the visible English text.

The shortest code that fully transforms the linked version of the IWD Wikipedia page according to the stated rules, wins.

JavaScript, 707 bytes (680 in web console)

javascript:(function(){l=function(s){return s.toLowerCase()};b=document.body;t=b.innerHTML;s="Actress;Actor;Daughters;Sons;Feminine;Masculine;Feminism;Masculism;Feminist;Masculist;Femininity;Masculinity;Mother;Father;Mothers;Fathers;Motherland;Fatherland;Motherhood;Fatherhood;Woman;Man;Female;Male;Females;Males;Girl;Boy;Girls;Boys;Girlfriends;Boyfriends;Grandmothers;Grandfathers;Her;His;She;He;Sister;Brother;Wives;Husbands;WomenWatch;MenWatch;Women;Men;Womensday;Mensday;Internationalwomensday;Internationalmensday;IWD;IMD";a=s.split(';');c=t.split(/\b/);d={};for(i=0;i<a.length;i+=2){x=a[i];y=a[i+1];d[x]=y;d[y]=x;d[l(x)]=l(y);d[l(y)]=l(x)}t='';for(i=0;i<c.length;++i)t+=d[c[i]]||c[i];b.innerHTML=t})()

This is a bookmarklet/favelet; set as URL of a bookmark/favorite and click to transform the loaded webpage.


The modulo parity party You are given an array A of n strictly positive integers, with n ≥ 2.
Your task is to map each entry Ai to:

1 if Aj mod Ai is odd for each j such that 1 ≤ j ≤ n and j ≠ i
2 if Aj mod Ai is even for each j such that 1 ≤ j ≤ n and j ≠ i
0 otherwise (mixed parities)

Example
For A = [ 73, 50, 61 ], we have:

50 mod 73 = 50, 61 mod 73 = 61 → mixed
73 mod 50 = 23, 61 mod 50 = 11 → all odd
73 mod 61 = 12, 50 mod 61 = 50 → all even

Therefore, the expected output is [ 0, 1, 2 ].
Rules

You may use any three distinct values (of any type) instead of 0, 1 and 2 as long as they're consistent. Please specify your mapping if you're not using the one described in the challenge.
Should there be any doubt about that, zero is even.
This is code-golf, so the shortest answer in bytes wins!

Test cases
[ 1, 2 ] --> [ 2, 1 ]
[ 3, 4 ] --> [ 1, 1 ]
[ 1, 2, 3 ] --> [ 2, 1, 0 ]
[ 4, 4, 4 ] --> [ 2, 2, 2 ]
[ 73, 50, 61 ] --> [ 0, 1, 2 ]
[ 941, 459, 533 ] --> [ 1, 0, 0 ]
[ 817, 19, 928, 177 ] --> [ 1, 2, 1, 1 ]
[ 312, 463, 336, 729, 513 ] --> [ 0, 2, 0, 0, 0 ]
[ 53, 47, 33, 87, 81, 3, 17 ] --> [ 0, 0, 0, 1, 0, 2, 0 ]

Python 2, 68 67 66 bytes

-1 byte thanks to Mr. Xcoder
-1 byte thanks to ovs

x=input()
for j in x:k=sum(i%j%2for i in x);print(k<len(x)-1)+0**k

Try it online!

Returns 1,0,2 instead 0,1,2.


Golf my Shakespeare quote references While writing my essay for Shakespeare, I realized that I needed to shorten my quote references to more manageable lengths. I had previously been writing this:
(Act 1, Scene 2, Lines 345-346)

But I've now been told to write them like this:
(I.ii.345-6)

Clearly, I need some golfed code to golf my Shakespeare quote references down a bit.
The Task
Write a program or function that, given a string input following Template 1 or 2, print or return a string following Template 3 or 4, respectively. You only have to support Acts 1 through 5 and Scenes 1 through 9.
Templates
Template 1
(Act x, Scene y, Lines a-b)

You may assume that x never exceeds 5, y never exceeds 9, a and b are always positive integers not exceeding your language's maximum positive standard integer value, and a is always exclusively less than b.
Template 2
(Act x, Scene y, Line a)

Same conditions as Template 1, excluding information about b.
Template 3
(x.y.a-b)

Where x is a capital roman numeral, y is a lowercase roman numeral, a and b are numbers, and b is shortened to only the digits less than the first differing digit of equal significance from a.
Template 4
(x.y.a)

Same conditions as Template 3, excluding information about b.
Test Cases
Let f(s) be the function defined in the Task. "" denotes a string value.
>>> f("(Act 1, Scene 2, Lines 345-346)")
"(I.ii.345-6)"

>>> f("(Act 3, Scene 4, Lines 34-349)")
"(III.iv.34-349)"

>>> f("(Act 5, Scene 9, Lines 123-234)")
"(V.ix.123-234)"

>>> f("(Act 3, Scene 4, Line 72)")
"(III.iv.72)"

>>> f("(Act 2, Scene 3, Lines 123-133)")
"(II.iii.123-33)"

>>> f("(Act 4, Scene 8, Lines 124-133)")
"(IV.viii.124-33)"

For the purposes of this challenge, the following arabic to roman numeral translations must be supported:
1 i     I
2 ii    II
3 iii   III
4 iv    IV
5 v     V
6 vi    (you do not have to support past 5)
7 vii
8 viii
9 ix

The Shakespeare Programming Language (non-competing)

I really liked this question, and as there was some interest in a Shakespeare-language answer, here is one.

A Tale of Two Cites (sic).

Julius Caesar, the first citizen of the Roman Republic.
Brutus, a traitor -- member of the Fifth Column.
Cicero, the greatest Roman orator.
Cleopatra, a proud queen, whom the Romans want to make one of their own.
Romeo, a man who's sometimes there.
Juliet, a maiden who can follow Romeo or stand on her own.

           Act I: Imperium Romanum.

           Scene I: Cleopatra puts men in their place.

[Enter Cleopatra and Julius Caesar]

Julius Caesar:
    Thou art as lovely as the sum of an amazing delicious gentle blossoming warm angel and a charming noble reddest rose.
    Speak your mind. Open your mind. Open your mind. Open your mind! Open your mind!

Cleopatra:
    You are as stuffed as the sum of a hard old green horse and the sum of a grandmother and
    a normal tiny bottomless furry small purple roman.

[Exit Julius Caesar]
[Enter Brutus]

Cleopatra:
    You are as sorry as the difference between a rich morning and a leech.
    You are as smelly as the difference between yourself and a sunny rural blue bold uncle.
    You are as vile as the difference between Julius Caesar and yourself.

[Exit Brutus]
[Enter Cicero]

Cleopatra:
    You are as half-witted as the difference between Brutus and the bluest death.

           Scene II: How do you solve a problem like Cleopatra?

[Exeunt]
[Enter Cleopatra and Julius Caesar]

Julius Caesar:
    Listen to your heart!

[Exit Cleopatra]
[Enter Brutus]

Julius Caesar:
    Is Cleopatra more pretty than a fair charming noble angel?

Brutus:
    If so, we must proceed to Scene IV. Is Cleopatra not worse than the sweetest small aunt?

Julius Caesar:
    If so, let us proceed to Scene III.

Brutus:
    Speak your mind.

Julius Caesar:
    Is Cleopatra nicer than the moon?

Brutus:
    If so, speak your mind.

Julius Caesar:
    Is Cleopatra better than a golden King?

Brutus:
    If so, speak your mind.

Julius Caesar:
    We shall proceed to Scene V.

          Scene III: Brutus and his friends.
Julius Caesar:
    Is Cleopatra as fair as the blossoming smooth sky?

Brutus:
    If so, speak your mind!

Julius Caesar:
    Speak your mind!

Julius Caesar:
    Is Cleopatra jollier than the sum of a yellow sweet road and a summer's day?

Brutus:
    If so, speak your mind!

Julius Caesar:
    Is Cleopatra friendlier than the sum of a sweet large angel and a white cow?

Brutus:
    If so, speak your mind!

Julius Caesar:
    Is Cleopatra as furry as a rich handsome huge mistletoe?

Brutus:
    If so, speak your mind!

Julius Caesar:
    We shall proceed to Scene V.

          Scene IV: Cicero is asked to speak.
[Exit Brutus]
[Enter Cicero]

Julius Caesar:
    Is Cleopatra as beautiful as the sum of a small furry white angel and a summer's day?

Cicero:
    If so, speak your mind!

Julius Caesar:
    Speak YOUR mind!

          Scene V: A period piece -- Cleopatra's reprisal.
[Exeunt]
[Enter Cleopatra and Julius Caesar]

Julius Caesar:
    You are as beautiful as the sum of a embroidered sweetest sunny delicious trustworthy Lord
    and a reddest charming mighty honest King.
    You are as healthy as the difference between yourself and a embroidered Lord. Speak your mind!
    Open your mind! Open your mind! Open your mind! Open your mind! Open your mind! Open your mind!

Cleopatra:
    Are you jollier than the sum of a little rural white bottomless blue blue sky and a rural furry white green old morning?

Julius Caesar:
    If so, we must proceed to Act II. Open your mind! Open your mind!

Cleopatra:
    You are as damned as the difference between yourself and a half-witted dusty snotty rotten oozing death.

[Exit Julius Caesar]
[Enter Brutus]

Cleopatra:
    You are as rotten as the difference between yourself and a rural rotten bottomless evil miserable famine.

[Exit Brutus]
[Enter Cicero]

Cleopatra:
    You are as fatherless as the difference between Brutus and a normal pig. Let us return to Scene II.

          Act II: Lovers' arithmetick.

          Scene I: Our lovers discuss what they have in common.

[Exeunt]
[Enter Romeo and Juliet]

Romeo:
    Thou art as bold as a curse. Listen to your heart!

Juliet:
    Am I better than nothing? If so, let us proceed to Scene III.

Romeo:
    Open your mind. Open your mind.

Juliet:
    Listen to your heart! Open your heart!

Romeo:
    Thou art as amazing as the product of the difference between a handsome white proud white grandfather and an aunt
    and the sum of a loving niece and the Heaven. Speak your mind! Open your mind.
    Listen to your heart. Is the quotient between yourself and the sum of the sum of
    a noble noble mighty blossoming embroidered good father
    and a gentle large large normal old joy and an old happy squirrel as yellow as the quotient between
    myself and the sum of the sum of a pretty beautiful yellow green bold charming kingdom and
    a beautiful blue normal cute large nephew and a pretty big cousin?

Juliet:
    If not, we shall proceed to Scene II.

Romeo:
    You are as sweet as the remainder of the quotient between yourself and the sum of the sum of
    a blossoming bottomless golden peaceful noble healthy nose and
    a happy honest sunny green healthy hero and a hard blue fellow.

Juliet:
    YOU are as sweet as the remainder of the quotient between yourself and the sum of the sum of
    a blossoming bottomless golden peaceful noble healthy nose and
    a happy honest sunny green healthy hero and a hard blue fellow.

          Scene II: Tense times.
Juliet:
    Is the quotient between yourself and the sum of a good beautiful delicious grandmother
    and a noble wind as amazing as the quotient between myself and the sum of
    a smooth furry embroidered roman and a honest sister?

Romeo:
    If so, you are as amazing as the remainder of the quotient between
    yourself and the sum of a cute healthy smooth kingdom and a normal mother.

          Scene III: Parting is such sweet sorrow.
Romeo:
    Open your heart! You are as noble as the sum of a honest charming smooth peaceful fine rose and the sum of
    a cute amazing trustworthy summer's day and an angel. Speak your mind!

(It's over 6000 bytes long.) There are some tricks in there but I have not tried to golf it much, because: (1) I already contributed my share of golfing on another answer, and (2) changing all characters to "Page" and "Puck", or all phrases to "big big big big big cat", seems to spoil the fun. Instead for the part that deals with Roman numerals I have used characters who are Romans, etc. I did reuse characters and instructions to save some typing. :-)

The program should be mostly straightforward but one wrinkle worth mentioning is that when I wrote this I assumed that reading an integer would work like scanf: (1) consume only as many characters from the input as corresponds to an integer, and (2) in case of failure, leave the variable unchanged. (I used this second property to distinguish between Template 1 and 2 in Act II, by reading up to "Line" and attempting to read an integer.) Unfortunately it turns out that there's (what I consider) a bug in the original implementation of the language where reading an integer consumes everything up to the end of the line and throws an error if it fails, so it needs a patch to libspl.c to make int_input behave more like scanf.

And with that, it works:

% spl2c < good.spl > good.c
% gcc -lspl -o good good.c
% for f in in-*; do cat $f; echo "->"; ./good < $f; echo "\n"; done
(Act 1, Scene 2, Lines 345-346)
->
(I.ii.345-6)

(Act 3, Scene 4, Lines 34-349)
->
(III.iv.34-349)

(Act 5, Scene 9, Lines 123-234)
->
(V.ix.123-234)

(Act 3, Scene 4, Line 72)
->
(III.iv.72)

(Act 2, Scene 3, Lines 123-133)
->
(II.iii.123-33)

(Act 4, Scene 8, Lines 124-133)
->
(IV.viii.124-33)

Slightly higher-level pseudocode that I worked off of, to help anyone trying to understand:

Print `(`=40
Read 5 chars
Read Int A
Output A in Roman
Output `.`=46
Read 8 chars
Read Int S
Output S in roman
Output `.`=46
Read 6 chars
Set N to -1
Read Int N
If N ≠ -1 goto finish
Read 2 chars
Read Int M
Output Int M
Output `-`=45
Read 1 char
Read Int N
Reduce N wrt M
finish:
Output N
Print `)`=41

Relating the above to the final code is left as an exercise. :-) Note that ShakespearePL has arithmetic and stacks and gotos but no pointers (only labels), so implementing "subroutines" like the conversion to Roman is a bit… interesting.


Escape the Candlelit Maze You find yourself in a strange place. A frighteningly dark maze, lit only by dim candles resting in the occasional hallway. Numerous paths lie only in impassable darkness, foreboding and-- ...Hm? What? Pick up a candle and carry it with you? No, no, that would be extremely rude.

The Task

Given a maze as input, output the minimum moves to solve it, or any falsey/invalid output if the maze cannot be solved. The catch: The maze is very dark, but is lit by candles placed on some of the grid squares. The player may only move in a direction if they can see light in that direction.

Rules

Take the maze as input in any convenient format (string, 1d array, 2d array, etc).
x represents a wall, @ represents the player, ^ represents a candle and # represents the exit.
The maze will be surrounded on all sides by walls, except for the player's starting space and the exit space, each of which will be in one of the walls. The corners will always be walls.
The player may only make orthogonal moves one space at a time in the direction of visible light. This is either a candle or the exit.
Candlelight only reaches the space it's on, but is visible from any distance.
Output the minimum number of legal moves the player can make to reach the exit, or any "invalid" value (such as a negative value, zero, false, the string "Unsolvable!", etc) if the maze is unsolvable within the rules. The player must move into the exit space to solve the maze.
Standard loophole restrictions and i/o rules apply.

Test Cases

1-

Input:
xxxxxxxxxx
@^x    ^xx
x^  ^xxxxx
xxxx x^  #
x xx x xxx
x ^ ^ ^x x
x xxxx  ^x
xxxxxxxxxx

Output:
15

2-

Input:
xxxxxxxxxxxx
x^ ^xxxxxxxx
x x        #
x x^xxxx xxx
x xxxx   xxx
x^  ^xxx^xxx
xxxx@xxxxxxx

Output:
19

Once the player moves into a space that can see a new light source, such as the exit, they can then start moving towards that light source.

3-

Input:
xxxxxxxx
#  xx ^x
xx^  ^xx
x ^xx xx
xxxxx@xx

Output:
Unsolvable

4-

Input:
xxxxxxxxx
@      ^x
x xxxxx x
x x^   ^x
x x xxxxx
x x^   ^x
x xxxxx x
x^ ^   ^x
xxx#xxxxx

Output:
10

The player must take the shortest path.

5-

Input:
xxxxxxxxx
x   ^  ^x
xxxx xxxx
#  x    x
x^xx^xxxx
x^   x  x
xxxx x xx
x     ^ x
xxxx@xxxx

Output:
Unsolvable

Scoring

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

Retina 0.8.2, 229 bytes

T`#^`d
s`@.*
$&_
@\d|@ ( *\d)
@=$1
(\d *) @|\d@
$1=@
m`^(((.))*@.*\n(?<-2>.)*(?(2)$))(\d| ((.*\n)+(?<-3>.)*(?(3)$)\d))
$1=$5
m`^(((.))*)(\d|(\d(.*\n)+(?<-2>.)*(?(2)$)) )(.*\n(?<-3>.)*(?(3)$)@)
$1$5=$7
@
x
}sT`=`@`.*0.*
s`.*0.*

_

Try it online! Outputs 0 for unsolvable, since solutions must take at least one step. Explanation:

T`#^`d

Change the candle and exit to golfier characters, saving 7 bytes

s`@.*
$&_

If there are still squares to check, then increment the counter. (This allows the loop to terminate once it runs out of squares to check.)

@\d|@ ( *\d)
@=$1

Mark the square to the right if it is lit.

(\d *) @|\d@
$1=@

Mark the square to the left if it is lit.

m`^(((.))*@.*\n(?<-2>.)*(?(2)$))(\d| ((.*\n)+(?<-3>.)*(?(3)$)\d))
$1=$5

Mark the square below if it is lit.

m`^(((.))*)(\d|(\d(.*\n)+(?<-2>.)*(?(2)$)) )(.*\n(?<-3>.)*(?(3)$)@)
$1$5=$7

Mark the square above if it is lit.

@
x

Turn the squares that were checked into walls.

sT`=`@`.*0.*

If the exit still exists, then turn all of the marked squares into squares that need to be checked.

}`

Repeat the above until the exit is reached or no new steps could be taken.

s`.*0.*

If the exit was not reached then delete the count.

_

Convert the count to decimal and delete the input.


The Stack Exchange Site List Currently, the Stack Exchange network has nearly 150 sites. These sites are as follows:

Computer Graphics
Portuguese Language
elementary OS
Open Source
Law
Русский язык
Mythology
Health
Stack Overflow на русском
CiviCRM
Woodworking
Music Fans
Vi and Vim
Coffee
Engineering
Lifehacks
Economics
History of Science and Mathematics
Emacs
スタック・オーバーフロー
Worldbuilding
Startups
Community Building
Hinduism
Buddhism
Craft CMS
Puzzling
Data Science
Joomla
Earth Science
Mathematics Educators
Expatriates
Arduino
Software Recommendations
Beer
Ebooks
Aviation
Stack Overflow em Português
Italian Language
Amateur Radio
Pets
Tor
Astronomy
Space Exploration
Blender
Freelancing
Open Data
Network Engineering
Reverse Engineering
Tridion
Sustainable Living
English Language Learners
Magento
Anime & Manga
Politics
ExpressionEngine® Answers
Robotics
Genealogy & Family History
Ask Patents
Salesforce
Islam
Russian Language
Raspberry Pi
Chess
Chemistry
Windows Phone
The Workplace
Computer Science
Academia
Sports
Martial Arts
The Great Outdoors
Cognitive Sciences
Mathematica
Poker
Biology
Chinese Language
Movies & TV
Computational Science
Spanish Language
LEGO® Answers
History
Biblical Hermeneutics
Linguistics
Bitcoin
Christianity
French Language
Signal Processing
Cryptography
Personal Productivity
Travel
Gardening & Landscaping
Philosophy
Japanese Language
German Language
Mi Yodeya
Software Quality Assurance & Testing
Music: Practice & Theory
SharePoint
Parenting
Motor Vehicle Maintenance & Repair
Drupal Answers
Physical Fitness
Skeptics
Project Management
Quantitative Finance
Programming Puzzles & Code Golf
Code Review
Science Fiction & Fantasy
Graphic Design
Database Administrators
Video Production
Writers
Information Security
Sound Design
Homebrewing
Physics
Board & Card Games
Electrical Engineering
Android Enthusiasts
Programmers
Bicycles
Role-playing Games
Ask Different
Theoretical Computer Science
WordPress Development
Unix & Linux
User Experience
English Language & Usage
Personal Finance & Money
Ask Ubuntu
TeX - LaTeX
Geographic Information Systems
Home Improvement
Mathematics
Cross Validated
Photography
Game Development
Seasoned Advice
Webmasters
Arqade
Web Applications
Stack Apps
MathOverflow
Super User
Meta Stack Exchange
Server Fault
Stack Overflow

Your Task:

Write a program that prints out all of the sites in Stack Exchange, including those with non-ASCII characters (It doesn't need to be in any specific order).
The program must accept no input, and must output each site on its own line (optional leading/trailing newlines).
No standard loopholes.
This is code-golf, so the shortest program, measured in bytes, wins.


Is the path correct? Is the path correct ?

Given a string, your program must determine whether or not Alice can reach Bob, following the signs on the map. You must return a truthy or falsy value.

The input string will contain the following characters :

 (space) and \n. Only used for padding.
>, <, ^, v, are the "signs". They show the direction.
&. Ignore next char, whatever it is (including spaces and Bob)
A and B respectively Alice and Bob.

The map is a torus. If Alice reaches the end of a row, then she is teleported back to the beginning of that row. Same applies for columns.

Examples

Given those examples as input, your program must return a truthy value (each input is separated with a - line):

A>B
-----------------
<BA
-----------------
A       B
-----------------
BA
-----------------
Av  >B
 >  ^
-----------------
Av
 B
-----------------
A>v
  >B
-----------------
A>v>   v>B
 v< > &<^
 > ^
-----------------
A>v>   v
 v< >B&<
 > ^
-----------------
A&<B
-----------------
A&B<
-----------------
<A       &B

For the following, your program must output a falsy value or nothing :

AvB
-----------------
A&B
-----------------
A><B
-----------------
A>v
 ^<B

Path viewer

You can have a visual representation of the input here. Thanks to arnemart for this.

Some rules

The input may be padded with spaces to form a rectangle
Initially, Alice goes straight forward (from above, she goes to the right)
Your program should handle infinite loop cases (see Hint)
A is not always the first character, as you may have seen, however, you may write a program that handles only input with A being the first char, but 20 bytes will be added to your score.
A map (the input) is considered invalid in case there are other characters than those specified above. Your program won't have to handle them.
This is code-golf, so shortest code in bytes wins.

Hint

Your program will most likely be a loop, unless you find a more mathematical solution to this challenge. To handle infinite path, I recommend using a finite loop (e.g for) instead of a potentially infinite one (e.g while).

Therefore, the maximum iteration of the loop I can think of (I did not do any maths, any correction is welcome) is (length of input)*4

C, 250 bytes
#define h x=(j+x-1+d%3)%j,i=(j+i+(d=='v')-(d==94))%j
char a[999],b[999];x,i,d=2,k,f;main(j){for(;gets(a+j*i);)j=strlen(a+j*i++);for(x=strchr(a,65)-a,i=x/j,x=x%j;!k*d;h)k|=b[f=j*i+x]&1<<d%5,b[f]|=1<<d%5,(f=a[f])&16?d=f:f&4?h:f&2?d=0:0;putchar(48+!k);}

This also requires that the input is padded with spaces.
Ungolfed:
#define h x=(j+x-1+d%3)%j,i=(j+i+(d=='v')-(d==94))%j
char a[999],b[999];x,i,d=2,k,f;
main(j){
 for(;gets(a+j*i);)j=strlen(a+j*i++); //read lines and determine line length
 for(x=strchr(a,65)-a,i=x/j,x=x%j;    //the current position is 'A'
 !k*d; //as long as we have not arrived at 'B'
       //and not travelled through the same cell and in the same direction twice
 h)    //advance one in the current direction
   k|=b[f=j*i+x]&1<<d%5,b[f]|=1<<d%5,  //if we have already travelled
                                       //through this cell in this direction
   (f=a[f])&16?d=f //change direction if this cell is one of <>^v
   :f&4?h          //if this cell is '&', advance one in the current direction
   :f&2?d=0:0;     //if we have reached 'B'
 putchar(48+!k);
}


Output visual diagram of picture Write a program that inputs the dimensions of a painting, the matting width, and the frame width for a framed portrait. The program should output a diagram using the symbol X for the painting, + for the matting, and # for the framing. The symbols must be space-separated. Trailing whitespace is alright, as long as the output visually matches the criteria. The inputs can be 0.

INPUT: 3 2 1 2
(Width, Height, Matte Width, Frame Width)

OUTPUT:

In text form:

# # # # # # # # #
# # # # # # # # #
# # + + + + + # #
# # + X X X + # #
# # + X X X + # #
# # + + + + + # #
# # # # # # # # #
# # # # # # # # #

The winning code completes the conditions in the least possible bytes.

Python 2, 98 bytes

w,h,a,b=input()
a*='+'
b*='#'
for c in b+a+h*'X'+a+b:print' '.join(min(c,d)for d in b+a+w*'X'+a+b)

Try it online!

Prints a space-separated grid, strictly following the spec. I'm amused that *= is used to convert a and b from numbers to strings.

Python 3 can save some bytes by avoiding ' '.join, maybe more by using f-strings and assignment expressions. Thanks to Jo King for -2 bytes.

Python 3, 93 bytes

def f(w,h,a,b):a*='+';b*='#';[print(*[min(c,d)for d in b+a+w*'X'+a+b])for c in b+a+h*'X'+a+b]

Try it online!


><>, 112 bytes

You may be thinking "Is ><> really the best language to write an interpreter in?", to which my answer is "no, but let's try anyway!"

i:}b(?v
0(?;v0<o}\.24;!?:}\    /}~51. /}1-32./}1+32./}~i:
6*bb< o:}\?="#":  \?(b:\?="!":\?="-":\?="+":\?="%":$%+

Try it online, or at the fish pond!

Takes input from STDIN: first the +-#$%! code, then optionally a newline and any extra input.

This could do with some explanation.

The first loop is i:}b(?v. This reads from STDIN to the stack until it hits a character less than b = 11, which means either a newline (charcode 10) or EOF (charcode -1).
Once that's done, the fish swims down…

  v
v0<
<

…into the main loop, adding a 0 to the stack to use as the accumulator.
First, the fish sees bb*6+% — this computes 127 = 11*11+6 and takes the modulus of the accumulator. Then $ brings forward the first character from the stack.
Now, we get to the bulk of the code — reading the character. There are seven branches in this bit of the code. (I think I've tetrissed the branches as much as I can, but there might be more blank space that can be removed here.)

0(?;                                       /}~i:
                                           \?="%":

Note that the fish starts from the bottom right, moving left, and wraps when it hits the side of the code. If the character is a literal "%", we shift it to the back of the stack for safekeeping, delete the accumulator, replace it with the first character in STDIN, check if that's EOF (that is, if its charcode is negative), and end the program if so. We then hit the start of the main loop again.

                             /}1-32./}1+32.
                             \?="-":\?="+":

If the character is "+", we put it on the back of the stack again, add 1 to the accumulator, and jump to the start of the main loop. The "-" case is similar.

                      /}~51.
                      \?="!":

If the character is "!", delete the accumulator and jump to just before the start of the main loop, where we first created the accumulator by adding a 0 to the stack.

         .24;!?:}\
                 \?(b:

If the character is EOF or newline, check if the accumulator is 0, and terminate the program if so; otherwise, jump back to the start of the main loop. We kept all the used characters on the stack, so now we're back at the start of the program anyway.

      o}\
        \?="#":

If the character is "#", output the accumulator as a character. We're then conveniently back just before the main loop, where we created the accumulator with a 0.

     o:}

If we've reached this branch, the character can only be "$", since the stack only contained the characters +-#$%! and EOF or linefeed. Therefore we print a copy of the accumulator, and we're back at the start of the main loop.