Machine Learning Golf: Multiplication I'd like to propose a different kind of golfing challenge to this community:

(Artificial) Neural Networks are very popular machine learning models that can be designed and trained to approximate any given (usually unknown) function. They're often used to solve highly complex problems that we don't know how to solve algorithmically like speech recognition, certain kinds of image classifications, various tasks in autonomous driving systems, ... For a primer on neural networks, consider this excellent Wikipedia article.

As this is the first in what I hope to be a series of machine learning golf challenges, I'd like to keep things as simple as possible:

In the language and framework of your choice, design and train a neural network that, given \$(x_1, x_2)\$ calculates their product \$x_1 \cdot x_2\$ for all integers \$x_1, x_2\$ between (and including) \$-10\$ and \$10\$.

Performance Goal

To qualify, your model may not deviate by more than \$0.5\$ from the correct result on any of those entries.

Rules

Your model

must be a 'traditional' neural network (a node's value is calculated as a weighted linear combination of some of the nodes in a previous layer followed by an activation function),
may only use the following standard activation functions:

\$\textrm{linear}(x) = x\$,
\$\textrm{softmax}(\vec{x})_i = \frac{e^{x_i}}{\sum_j e^{x_j}}\$,
\$\textrm{selu}_{\alpha, \beta}(x) = \begin{cases}
\beta \cdot x & \text{, if } x > 0 \\
\alpha \cdot \beta (e^x -1 ) & \text{, otherwise}
\end{cases}\$,
\$\textrm{softplus}(x) = \ln(e^x+1)\$,
\$\textrm{leaky-relu}_\alpha(x) = \begin{cases}
x & \text{, if } x < 0 \\
\alpha \cdot x & \text{, otherwise}
\end{cases}\$,
\$\tanh(x)\$,
\$\textrm{sigmoid}(x) = \frac{e^x}{e^x+1}\$,
\$\textrm{hard-sigmoid}(x) = \begin{cases}
0 & \text{, if } x < -2.5 \\
1 & \text{, if } x > 2.5 \\
0.2 \cdot x + 0.5 & \text{, otherwise}
\end{cases}\$,
\$e^x\$

must take \$(x_1, x_2)\$ either as a tupel/vector/list/... of integers or floats as its only input,
return the answer as an integer, float (or a suitable container, e.g. a vector or list, that contains this answer).

Your answer must include (or link to) all code necessary to check your results -- including the trained weights of your model.

Scoring

The neural network with the smallest number of weights (including bias weights) wins.

Enjoy!

21 13 11 9 weights

This is based on the polarization identity of bilinear forms which in the one dimensional real case reduces to the polynomial identity:

$$ x\cdot y = \frac{(x+y)^2 - (x-y)^2}{4}$$

So y1 just computes [x+y, x-y] using a linear transformation, and y3 is just the absolute value of y1 as a preprocessing step for the next one: Then the "hard" part is computing the squares which I will explain below, and after that just computing a difference and scaling which is again a linear operation.

To compute the squares I use an exponential series \$s\$ which should be accurate for all integers \$\{0,1,2,\ldots,20\}\$ within around \$0.5\$. This series is of the form

$$ \text{approx_square}(x) = \sum_{i=0}^2 w_i \exp(0.0001 \cdot i \cdot x)$$

where I just optimized for the weights W2 (\$=(w_i)_i\$). This whole approximation comprises again just two linear transformations with an exponential activation sandwiched in between. This approach results in a maximal deviation of about 0.02.

function p = net(x)
% 9 weights
one = 1;
mone =-1;
zero = 0;
fourth = 0.25;
W1 = [1e-4, 2e-4];
W2  = [-199400468.100687;99700353.6313757];
b2 = 99700114.4299316;
leaky_relu = @(a,x)max(a*x,x);

% Linear
y0 = [one, one; one, mone] * x;

% Linear + ReLU
y1 = mone * y0;
y2 = [leaky_relu(zero, y0), leaky_relu(zero, y1)];

% Linear
y3 = y2 * [one; one];

% Linear + exp
y4 = exp(y3 * W1);

% Linear + Bias
y5 =  y4 * W2 + b2;

% Linear
y6 = [one, mone]*y5;
p = y6 * fourth;

end

Try it online!


Determine the Widest Valley Imagine we get a slice of some mountainous region, this would result in a shape similar to this:

4                   _
3   _    _       __/ \
2  / \__/ \    _/     \_   /
1 /        \  /         \_/
0           \/
  12322223210012233343221112

As we can see, we can represent this (to a certain degree) with a sequence of integers.

For the purpose of this challenge we define a valley as a contiguous subsequence where the values initially are decreasing and from some point on they are increasing. More formally for a sequence \$(a_i)_{i=1}^n\$ a valley will be indices \$1 \leq s < r < t \leq n\$ for which the following holds:

the valley's start and endpoint are the same: \$a_s = a_t\$
the valley starts and ends once the region gets lower: \$a_s > a_{s+1} \land a_{t-1} < a_t\$
the valley is not flat: \$a_s \neq a_r \land a_r \neq a_t\$
the valley initially decreases: \$\forall i \in [s,r): a_i \geq a_{i+1}\$
the valley will at some point increase: \$\forall j \in [r,t): a_j \leq a_{j+1}\$

Now we define the width of such a valley as the size of the indices \$[s,t]\$, ie. \$t-s+1\$.

Challenge

Given a height-profile (sequence of non-negative integers), your task is to determine the width of the widest valley.

Example

Given the height-profile [1,2,3,2,2,2,2,3,2,1,0,0,1,2,2,3,3,3,4,3,2,2,1,1,1,2], we can visualize it as before:

4                   _
3   _    _       __/ \
2  / \__/ \    _/     \_   /
1 /        \  /         \_/
0           \/
  12322223210012233343221112
    aaaaaa             ccccc
         bbbbbbbbb

Note how the second valley [3,2,1,0,0,1,2,2,3] does not extend further to the right because the left-most point is \$3\$ and not \$4\$. Furthermore we don't add the remaining two \$3\$s because we require that the endpoint is higher up than the second-last point.

Therefore the width of the widest valley is \$9\$.

Rules

Input will be a sequence of non-negative (sorry Dutch people) integers

you can assume that there is always at least one valley

Output will be the size of the widest valley as defined above

Testcases

[4,0,4] -> 3
[1,0,1,0,1] -> 3
[1,0,2,0,1,2] -> 4
[13,13,13,2,2,1,0,1,14,2,13,14] -> 4
[1,2,3,2,2,2,2,3,2,1,0,0,1,2,2,3,3,3,4,3,2,2,1,1,1,2] -> 9
[3,2,0,1,0,0,1,3] -> 4

Python 2, 120 115 89 87 86 152 149 bytes

lambda a:max(r-l+1for l,v in e(a)for r,w in e(a)if max(a[l+1:r]+[0])<v==w*any(s(a[l:i])[::-1]+s(a[i:r])==a[l:r]for i,_ in e(a)));e=enumerate;s=sorted

Try it online!


Count arrays that are really unique This is a follow up to Count arrays that make unique sets . The significant difference is the definition of uniqueness.

Consider an array A of length n. The array contains only positive integers.  For example A = (1,1,2,2).  Let us define f(A) as the set of sums of all the non-empty contiguous subarrays of A. In this case f(A) = {1,2,3,4,5,6}.  The steps to produce f(A)  are as follows:

The subarrays of A are (1), (1), (2), (2), (1,1), (1,2), (2,2), (1,1,2), (1,2,2), (1,1,2,2). Their respective sums are 1,1,2,2,2,3,4,4,5,6. The set you get from this list is therefore {1,2,3,4,5,6}.

We call an array A unique if there is no other array B of the same length such that f(A) = f(B), except for the array A reversed. As an example, f((1,2,3)) = f((3,2,1)) = {1,2,3,5,6} but there is no other array of length 3 that produces the same set of sums.

Task

The task, for a given n and s is to count the number of unique arrays of that length.  You can assume that s is between 1 and 9. You only need to count arrays where the elements are either a given integer s or s+1. E.g. if s=1 the arrays you are counting only contain 1 and 2.  However, the definition of uniqueness is with respect to any other array of the same length. As a concrete example [1, 2, 2, 2] is not unique as it gives the same set of sums as [1, 1, 2, 3].

You should count the reverse of an array as well as the array itself (as long as the array is not a palindrome of course).

Examples

s = 1, the answers for n = 2,3,4,5,6,7,8,9 are:

4, 3, 3, 4, 4, 5, 5, 6

For s = 1, the unique arrays of length 4 are

(1, 1, 1, 1)
(2, 1, 1, 2)
(2, 2, 2, 2)

s = 2, the answers for n = 2,3,4,5,6,7,8,9 are:

4, 8, 16, 32, 46, 69, 121, 177

An example of an array that is not unique with s = 2 is:

(3, 2, 2, 3, 3, 3).

This has the same set of sums as both of: (3, 2, 2, 2, 4, 3) and (3, 2, 2, 4, 2, 3).

s = 8, the answers for n = 2,3,4,5,6,7,8,9 are:

4, 8, 16, 32, 64, 120, 244, 472

Score

For a given n, your code should output the answer for all values of s from 1 to 9. Your score is the highest value of n for which this completes in one minute.

Testing

I will need to run your code on my ubuntu machine so please include as detailed instructions as possible for how to compile and run your code.

Leaderboard

n = 13 by Christian Sievers in Haskell (42 seconds)

Haskell
import Control.Monad (replicateM)
import Data.List (tails)
import qualified Data.IntSet as S
import qualified Data.Map.Strict as M
import qualified Data.Vector.Unboxed as V
import Data.Vector.Unboxed.Mutable (write)
import System.Environment (getArgs)
import Control.Parallel.Strategies

orig:: Int -> Int -> M.Map S.IntSet (Maybe Int)
orig n s = M.fromListWith (\ _ _ -> Nothing)
               [(sums l, Just $! head l) |
                   l <- replicateM n [s, s+1],
                   l <= reverse l ]

sums :: [Int] -> S.IntSet
sums l = S.fromList [ hi-lo | (lo:r) <- tails $ scanl (+) 0 l, hi <- r ]

construct :: Int -> Int -> S.IntSet -> [Int]
construct n start set =
   setmax `seq` setmin `seq` setv `seq`
   [ weight r | r <- map (start:) $ constr (del start setlist)
                                           (V.singleton start)
                                           (n-1)
                                           (setmax - start),
                r <= reverse r ]
  where
    setlist = S.toList set
    setmin = S.findMin set
    setmax = S.findMax set
    setv = V.modify (\v -> mapM_ (\p -> write v p True) setlist)
                    (V.replicate (1+setmax) False)

    constr :: [Int] -> V.Vector Int -> Int -> Int -> [[Int]]
    constr m _ 0 _ | null m    = [[]]
                   | otherwise = []
    constr m a i x =
         [ v:r | v <- takeWhile (x-(i-1)*setmin >=) setlist,
                 V.all (V.unsafeIndex setv . (v+)) a,
                 let new = V.cons v $ V.map (v+) a,
                 r <- (constr (m \\\ new) $! new) (i-1) $! (x-v) ]

del x [] = []
del x yl@(y:ys) = if x==y then ys else if y<x then y : del x ys else yl

(\\\) = V.foldl (flip del)

weight l = if l==reverse l then 1 else 2

count n s = sum ( map value [ x | x@(_, Just _) <- M.toList $ orig n s]
                      `using` parBuffer 128 rseq )
  where
    value (sms, Just st) = uniqueval $ construct n st sms
    uniqueval [w] = w
    uniqueval _   = 0

main = do
  [ n ] <- getArgs
  mapM_ print ( map (count (read n)) [1..9]
                    `using` parBuffer 2 r0 )

The orig function creates all the lists of length n with entries s or s+1, keeps them if they come before their reverse, computes their sublist sums and puts those in a map which also remembers the first element of the list. When the same set of sums is found more than once, the first element is replaced with Nothing, so we know we don't have to look for other ways to get these sums.
The construct function searches for lists of given length and given starting value that have a given set of sublist sums. Its recursive part constr follows essentially the same logic as this, but has an additional argument giving the sum the remaining list entries need to have. This allows to stop early when even the smallest possible values are too big to get this sum, which gave a massive performance improvement. Further big improvements were obtained by moving this test to an earlier place (version 2) and by replacing the list of current sums by a Vector (version 3 (broken) and 4 (with additional strictness)). The latest version does the set membership test with a lookup table and adds some more strictness and parallelization.
When construct has found a list that gives the sublist sums and is smaller than its reverse, it could return it, but we are not really interested in it. It would almost be enough to just return () to indicate its existence, but we need to know if we have to count it twice (because it is not a palindrome and we'll never handle its reverse). So we put 1 or 2 as its weight into the list of results.
The function count puts these parts together. For each set of sublist sums (coming from orig) that was unique amongst the lists containing only s and s+1, it calls value, which calls construct and, via uniqueval, checks if there is only one result. If so, that is the weight we have to count, otherwise the set of sums was not unique and zero is returned. Note that due to lazyness, construct will stop when it has found two results.
The main function handles IO and the loop of s from 1 to 9.
Compiling and Running
On debian this needs the packages ghc, libghc-vector-dev and libghc-parallel-dev. Save the program in a file prog.hs and compile it with ghc -threaded -feager-blackholing -O2 -o prog prog.hs. Run with ./prog <n> +RTS -N where <n> is the array length for which we want to count the unique arrays.


Unfolding an integer Given the functions

L: (x, y) => (2x - y, y)
R: (x, y) => (x, 2y - x)

and a number N generate a minimal sequence of function applications which take the initial pair (0, 1) to a pair which contains N (i.e. either (x, N) or (N, y)).

Example: N = 21. The minimal sequence is of length 5, and one such sequence is

          (  0,  1)
1. L ---> ( -1,  1)
2. L ---> ( -3,  1)
3. R ---> ( -3,  5)
4. L ---> (-11,  5)
5. R ---> (-11, 21)

Write the shortest function or program you can which generates a minimal sequence in O(lg N) time and O(1) space. You may output / return a string in either application order (LLRLR) or composition order (RLRLL), but document which.

Ruby, 55 or 39 characters
f=->n{(n>0?n-1:-n).to_s(2).tr'01',n>1?'LR':n<0?'RL':''}

The function returns the function sequence in composition order.
Usage:
puts f[21]     # RLRLL
puts f[-6]     # LLR

Edit: If we allow recursion (which violates the O(1) memory constraint but such does any function since the return value itself is O(lg n)) we can shrink the code to 39 characters.
f=->n{n<n*n ?f[(n-1)/2+1]+'RL'[n%2]:''}


number of answers and comments Write a software that prints on stdout the number of answers and the number of comments(visible and collapsed of question and answers) of this question/page.

Your script must run with this page closed when it starts.

Expected example output:

A12C40

Where A stands for Answers and C for Comments.

Perl, 91 96  92 chars
$_=`curl -sL qr.net/_9`;s/<[^>]+nt="(.+)/$c+=$1/ge;say"A",s/<td.*"ans//g,C,$c+s/<tr.*"com//g

Some stuff just to break solutions of others ha ha ha :-P
show 93 more comments

href
nt="99" (ha ha crash @Fez Vrasta)
a
,show 99show 99 ha ha
href
href
href
ha ha haha :-D
jeeez, just broke my own answer! I discovered that one of the above tricks, which I thought does nothing, will start working after this answer is not edited for some time! So your solutions will work only for some time. That's why you had seen +1 more answer in your solutions..  It's a timed bomb! My answer is already prone to it :-) Aaah, found a way how to launch it NOW...


All different functions For functions \$f, g: \{0,1\}^n \rightarrow \{0,1\} \$, we say \$f \sim g\$ if there's a permutation of \$1,2,3,...,n\$ called \$i_1,i_2,i_3,...,i_n\$ so that \$f(x_1,x_2,x_3,...,x_n) = g(x_{i_1},x_{i_2},x_{i_3},...,x_{i_n})\$. Therefore, all such functions are divided in several sets such that, for any two functions \$f, g\$ in a same set, \$f \sim g\$; for any two functions \$f, g\$ in different sets, \$f \not\sim g\$. (Equivalence relation) Given \$n\$, output these sets or one of each set.

Samples:

0 -> {0}, {1}
1 -> {0}, {1}, {a}, {!a}
2 -> {0}, {1}, {a, b}, {!a, !b}, {a & b}, {a | b}, {a & !b, b & !a}, {a | !b, b | !a}, {a ^ b}, {a ^ !b}, {!a & !b}, {!a | !b}

You can output the function as a possible expression(like what's done in the example, but should theoretically support \$n>26\$), a table marking outputs for all possible inputs (truth table), or a set containing inputs that make output \$1\$.

Shortest code win.

J, 62 bytes

f=:3 :'~.(2#~2^y)([:<@~.@/:~((i.@!A.i.)y)|:(y#2)$])@#:i.2^2^y'

Try it online!

-3 bytes for anonymous function (removing f=:)

For each boolean function (truth table), generate its equivalence class, then remove duplicates.


Mathematical Combination Write a program that takes an input such as:
n,k

which then computes:
$$\binom n k = \frac {n!} {k!(n-k)!}$$
and then prints the result.

A numerical example:
Input:
5,2

Internal computation:
$$\frac {5!} {3!\times2!}$$
Printed Output:
10

I'd like to see an answer that beats my python solution of 65 characters, but all languages are obviously welcome.
Here's my solution:
n,k=input();f=lambda x:+(x<2)or x*f(x-1);print f(n)/(f(k)*f(n-k))

Edit:
I admit that this question is from the codegolf website mathematical combination puzzle.  I know that my answer may look like not much progress can be made on it, but the leaders of this puzzle have solved it in nearly half as many characters.

C 96

With I/O (which takes about 34 chars). Added a couple of newlines to make it readable.

main(a,b,c,d){scanf("%d,%d",&a,&b);
d=a-b;for(c=1;a>b;){c*=a--;}for(;d;)
{c/=d--;}printf("%d",c);}

Now if you'll excuse me, I have an ASCII n choose k rocket to catch.

    d;main(a
   ,         b
  ,           c
 )  int        a
 ;   {scanf    (
 (   "%d %d"   )
 ,   &a,  &b   )
 ;   d    =a   -
 b   +     b   -
 b   *     1   ;
 a             -
 a  ;for    (  c
 =  1;a>   b   ;
 )  {c=   c    *
 (  (a-- )     )
 ;  }for(      b
 =  b + 1      ;
 d  ;    )     {
 c  =     c    /
 (  d--    )   ;
  }           {
  }           {
   }         (
  printf("%d",c)
 )      ;       }
/*     *  *   * *\
 * * X   * 8 * * |
|     *      *    \
*/    //       *  */


Print the "even" permutations of symmetric group Sn in cyclic notation THE TASK

DEFINITIONS

Consider the points {1,2,3,4,5} and all their permutations. We can find the total number of possible permutations of these 5 points by a simple trick: Imaging filling 5 slots with these points, the first slot will have 5 possible numbers, the second 4 (as one has been used to fill the first slot) the third 3 and so on. Thus the total number of Permutations is 5*4*3*2*1; this would be 5! permutations or 120 permutations. We can think of this as the symmetric group S5, and then Symmetric Group Sn would have n! or (n*n-1*n-2...*1) permutations.

An "even" permutation is one where there is an even number of even length cycles. It is easiest to understand when written in cyclic notation, for example (1 2 3)(4 5) permutes 1->2->3->1 and 4->5->4 and has one 3 length cycle (1 2 3) and one 2 length cycle (4 5). When classifying a permutation as odd or even we ignore odd length cycles and say that this permutation [(1 2 3)(4 5)] is odd as it has an odd number {1} of even length cycles.
Even examples:

(1)(2 3)(4 5) = two 2 length cycle | EVEN |
(1 2 3 4 5) = no even length cycles | EVEN | * note that if no even length cycles are present then the permutation is even.

Odd Examples:

(1 2)(3 4 5) = one 2 length cycle | ODD |
(1)(2 3 4 5) = one 4 length cycle | ODD |

As exactly half of the permutations in any Symmetric Group are even we can call the even group the Alternating Group N, So as S5 = 120 A5 = 60 permutations.

NOTATION

Permutations should, for this at least, be written in cyclic notation where each cycle is in different parenthesis and each cycle goes in ascending order. For example (1 2 3 4 5) not (3 4 5 1 2). And for cycles with a single number, such as: (1)(2 3 4)(5) the single / fixed points can be excluded meaning (1)(2 3 4)(5) = (2 3 4). But the identity {the point where all points are fixed (1)(2)(3)(4)(5)} should be written as () just to represent it.

THE CHALLENGE

I would like you to, in as little code possible, take any positive integer as an input {1,2,3,4...} and display all the permutations of the Alternating Group An where n is the input / all the even permutations of Sn. For example:

Input = 3
()
(1 2 3)
(1 3 2)

and

Input = 4
()
(1 2)(3 4)
(1 3)(2 4)
(1 4)(2 3)
(1 2 3)
(1 3 2)
(1 2 4)
(1 4 2)
(1 3 4)
(1 4 3)
(2 3 4)
(2 4 3)

And as with in the examples I would like for all cycles of one length to be elided, and as for the identity: outputs of  nothing, () {not only brackets but with whatever you are using to show different permutations} or id are acceptable.

EXTRA READING

You can find more information here:

https://en.wikipedia.org/wiki/Permutation
https://en.wikipedia.org/wiki/Alternating_group

GOOD LUCK

And as this is codegolf whoever can print the Alternating Group An's permutations in the shortest bytes wins.

Mathematica, 84 49 31 bytes

GroupElements@*AlternatingGroup

Composition of two functions. Outputs in the form {Cycles[{}], Cycles[{{a, b}}], Cycles[{{c, d}, {e, f}}], ...} representing (), (a b), (c d)(e f), ....


Interactive Lights Off game Intro

I guess most people are familiar with the game Lights Off, but in case someone isn't, here is a short description:

  You start with an NxN grid where each cell in the grid is a light. For this example N=5. There are 2 ways the game can start: either all of the lights are on, or some lights are off. The goal is to turn off all of the lights. If you toggle a light, the lights left, right, above and below it will toggle with it.

All Lights on

O O O O O
O O O O O
O O O O O
O O O O O
O O O O O

Toggled cells

Toggled(0,0) | Toggled(1,2)| Toggled(2,4)
X X O O O    |  O O X O O  |  O O O O O
X O O O O    |  O X X X O  |  O O O O X
O O O O O    |  O O X O O  |  O O O X X
O O O O O    |  O O O O O  |  O O O O X
O O O O O    |  O O O O O  |  O O O O O

Task

Make an interactive game of Lights Off with as little code as possible.

Requirements

There is a setup phase and a play phase.

The setup phase takes user input to determine the grid size (minimum size of 5) and whether the grid starts with all of the lights on. If the grid should not start with all of the lights on, lights must be selected randomly to start off: at least 1 and at most 20% of the lights.

In the play phase, the grid is displayed to the user and moves are taken as input. The application could use a windowed GUI with lights toggled by clicking, or a text UI which takes typed input of the coordinates of the cell to toggle.

When the user reaches a solved state (all lights off), the application must notify them that they have solved the puzzle, and show how many moves it took.

The use of external resources is not allowed.

If there is anything unclear or missing please let me know :)

Related questions

Lights Out - Find the solution asks for a computer-generated solution given the input
Lights Off! is more similar to this one, but non-interactive

C++, 564 bytes

#include <iostream>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;int main(){int n,p,s=0,y,i=0,b;cin>>n>>b;if(n<5)n=5;vector<int>m(n*n,1);srand(time(0));if(b)for(int&c:m)c=rand()<RAND_MAX/6;for(;i<n*n;i++)cout<<m[i]<<(-~i%n?"":"\n");while(find(m.begin(),m.end(),1)!=m.end()){cin>>p>>y;p+=y*n;if(p<0||p>=n*n)continue;m[p]=!m[p];if(p%n)m[p-1]=!m[p-1];if(p%n+1<n)m[p+1]=!m[p+1];if(p>=n)m[p-n]=!m[p-n];if(p+n<n*n)m[p+n]=!m[p+n];for(i=0;i<n*n;i++)cout<<m[i]<<(-~i%n?"":"\n");s++;}cout<<"Solved in "<<s<<" steps."<<endl;}

In setup phase, the user should input the grid size first. Then if the grid should starts with all of the lights on, the user should input 0; otherwise 1.

In play phase, the user should input the 0-based coordinates of the cell to toggle until all lights off.

Original code:

#include <iostream>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
int main() {
    int n, p, s = 0, y, i = 0, b;
    cin >> n >> b;
    if(n < 5) n = 5;
    vector<int> m(n * n, 1);
    srand(time(0));
    if (b) for (int& c : m) c = rand() < RAND_MAX / 6;
    for (; i < n * n; i++) cout << m[i] << (-~i % n ? "" : "\n");
    while (find(m.begin(), m.end(), 1) != m.end()) {
        cin >> p >> y;
        p += y * n;
        if (p < 0 || p >= n * n) continue;
        m[p] = !m[p];
        if (p % n) m[p - 1] = !m[p - 1];
        if (p % n + 1 < n) m[p + 1] = !m[p + 1];
        if (p >= n) m[p - n] = !m[p - n];
        if (p + n < n * n) m[p + n] = !m[p + n];
        for (i = 0; i < n * n; i++) cout << m[i] << (-~i % n ? "" : "\n");
        s++;
    }
    cout << "Solved in " << s << " steps." << endl;
}


Perl 5, 130 bytes

print$e=("+"."-"x10)x3 ."+
";printf"|$_.exe%4s |%-10s|%-9s |
$e",$|--&&$@++<9?("$@0%","#"x$@,leeching):("","#"x10,seeding)for a..z

Try it online!

I expect that there are a few bytes that can be golfed, but I've ran out of inspiration.

Short explanations:
$e contains the separation line (+----------+----------+----------+); its construction is straight forward (("+"."-"x10)x3 ."+\n").
Then, I loop over the characters from a to z:
Every time, print "|$_.exe%4s |%-10s|%-9s |\n$e; this is a standard printf with placeholders for strings (%s) and left-padded strings (%-9s).
if $|--&&$@++<9 is true ($| is a special variable that contains either 0 or 1, and decrementing it toggles its value), then the percentage is not 100%, and the three values in the print are "$@0%","#"x$@,leeching ($@0% is actually just $@ . "0" . "%" - remember that $@ was incremented earlier), otherwise, the three values are "","#"x10,seeding).


letter combinations to make words Find the combination of N number of letters that make up the most words of length N.

For example:

n r u  ->  run, urn
dstu -> dust, stud
(these are just examples, not the best combination of 3,4 length sets of letters)

The challenge in the case is to start with length N=3 and end at N=11. Which combination of letters gives you the most words and what are those words?

For the contest, please use this word list. It contains 71,193 words.  Please also let us know the time (in seconds) and CPU type/speed that you are using.

Ruby, 116 97 92 characters
9.times{|n|p IO.read('w').split.group_by{|s|s.chars.sort}.max_by{|k,v|k.size!=n+3?0:v.size}}

The wordlist is expected in the file w in the local directory. Program runs less than a second.
Output:
[["A", "E", "T"], ["ATE", "EAT", "ETA", "TAE", "TEA"]]
[["A", "E", "L", "S"], ["ALES", "ELSA", "LEAS", "LESA", "SALE", "SEAL"]]
[["A", "E", "L", "S", "T"], ["LEAST", "SLATE", "STAEL", "STALE", "STEAL", "TALES", "TEALS", "TESLA"]]
[["A", "C", "E", "R", "S", "T"], ["CARETS", "CASTER", "CATERS", "CRATES", "REACTS", "RECAST", "TRACES"]]
[["A", "D", "E", "E", "G", "N", "R"], ["ANGERED", "DERANGE", "ENRAGED", "GRANDEE", "GRENADE"]]
[["A", "E", "G", "I", "L", "N", "R", "T"], ["ALERTING", "ALTERING", "INTEGRAL", "RELATING", "TRIANGLE"]]
[["A", "A", "C", "E", "I", "N", "R", "S", "T"], ["ASCERTAIN", "CARTESIAN", "SECTARIAN"]]
[["A", "D", "I", "I", "M", "N", "N", "O", "O", "T"], ["ADMONITION", "DOMINATION"]]
[["A", "C", "G", "H", "I", "I", "L", "M", "O", "R", "T"], ["ALGORITHMIC", "LOGARITHMIC"]]


A Complementary Quine Write a quine that outputs the complement of the source code from the smallest containing power of two. Here's an example:

IN : source
OUT: \r\x11\x0b\x0e\x1d\x1b

The largest code point in the string "source" is the letter u, which is 117. The smallest containing power of 2 would be 128, so all the code points are taken as complements from 128.

s: 128 - 115 = 13. Code point 13 is a carriage return.
o: 128 - 111 = 17. Code point 17 is "device control 1"
u: 128 - 117 = 11. Code point 11 is a vertical tab.

And et cetera. Here's another example:

IN : R¡Ṡ
OUT: ᾮὟƠ

The largest code point is the character Ṡ, which is 7776. The smallest containing power of 2 is 2^13 (8192), so each character is complemented from 8192.

All of the standard loopholes apply. A program must consist of some explicit data or code. A variable containing some data by default would be considered implicit data, and therefore not allowed.

If your language inevitably outputs a trailing newline, it can be disregarded.

Retina, 2 1 byte

P

Outputs

0

Explained

P actually has no special meaning in retina, but retina treats it like a regex against the input, and counts the matches. As there's no input, there's no matches, so it returns 0, which is the exact inverse of this.

Try it online!

This is using an older version of Retina, which outputs a newline with the zero. This is not the case in the latest version.


Tips for golfing in VBScript What general tips do you have for golfing in VBScript? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to VBScript. Please post one tip per answer.

Thanks to Marcog for the original idea. :)

Use an empty variable instead of ""

Uninitialized variables are set to a special value: empty.  When empty is cast to a string it becomes "".

Contrived example (using z instead of ""):

s=InputBox(z)
For i=1To 5
    For j=1To i
        r=r&s
    Next
    MsgBox r
    r=z
Next

For numeric types Empty is 0, and for booleans it is false.  This can cut down on initialization code.

a=inputbox("Enter Starting Value")
b=a
while done=0
    i=i+1
    b=b*2
    done=(b>10000 or i>10)
wend
msgbox "Your "&a&" rabbit(s) have turned into "&b&" rabbit(s) in "&i&" years."


Robbers - square times square root Task: Crack the scrambled code for multiplying the square root of an integer n by the square of it!
You must post a comment in the cops' thread with a link to your working source, mentioning clearly that you have Cracked it. In your answer's title, you must include the link to the original answer.
Rules:

You may only change the order of the characters in the original source.
Safe answers cannot be cracked anymore.
The other rules mentioned in the cops' thread
Please edit the answer you crack

WINNER: Emigna - 10 submissons (had some trouble counting)
Honorable mentions: Notjagan, Plannapus, TEHTMI

JavaScript (ES7), Neil

_26_=>_26_**6.25**.5

The hard part, of course, was figuring out what to do with all the extra characters.  (And also not posting this solution in the wrong thread, like I accidentally did at first.  Oopsie...)


Towering Cistercian representation SE Sandbox Link, Codidact Sandbox Link
Inspired by this video.
Given a positive integer, draw its Cistercian representation as ascii art.

The Challenge
Cistercian numerals are a decimal-based number representation system which use simple line based drawings to represent 4-digit numerals. Their structure is as follows:
     Tens|Units
         |
Thousands|Hundreds

The digits are represented as follows (in the units place):
1   ⌷ 2   ⌷ 3   ⌷ 4   ⌷ 5   ⌷ 6    ⌷ 7    ⌷ 8    ⌷ 9    ⌷ 0
___ ⌷     ⌷     ⌷     ⌷ ___ ⌷    . ⌷ ___. ⌷    . ⌷ ___. ⌷
    ⌷     ⌷ \   ⌷   / ⌷   / ⌷    | ⌷    | ⌷    | ⌷    | ⌷
    ⌷     ⌷  \  ⌷  /  ⌷  /  ⌷    | ⌷    | ⌷    | ⌷    | ⌷
    ⌷ ___ ⌷   \ ⌷ /   ⌷ /   ⌷    ' ⌷    ' ⌷ ___' ⌷ ___' ⌷

(all of these are 4 rows in height.)
As you can see, there are some repeating patterns within the symbols:
5 → 4 + 1
7 → 6 + 1
8 → 6 + 2
9 → 6 + 1 + 2

In order to represent a general Cistercian number, you will have to place the digits in the correct place for their value.
They should be mirrored horizontally if they are on the left.
They should be mirrored vertically if they are on the bottom i.e. the lines should be reversed, \ and / should be swapped, and . and ' should be swapped. Here's how they should look.
The fun part is when you stack a Cistercian representation on top of another one to accommodate more digits e.g.:
  T|U
   |
 Th|H
   |
Hth|Tth
   |
 TM|M

like a tower of sorts.
You will need to stack as many 4 part towers as the number requires, and you will need to prepend 0's to the input if it's length is not a multiple of 4.
Hence, given an input number, say, 12345, you should get the following:
00012345 → 5432,1000
which turns into:
4|5
 |
2|3
 |
0|1
 |
0|0

which becomes:
    |___
 \  |  /
  \ | /
   \|/
    |
    |
    |
    |
 ___|  /
    | /
    |/
    |
    |
    |
    |
    |
    |___
    |
    |
    |
    |
    |
    |
    |
    |
    |
    |
    |

Note that this is created by making two towers for the 4 digit numbers 2345 and 0001, stacking them, and adding a link of 4 | characters between them.
Scoring
This is code-golf. Shortest answer in each language wins.

JavaScript (Node.js), 265 bytes
f=n=>n?`01238888765${n<1e4?4:48888}`.replace(e=/\d/g,y=>`4567|3210
`.replace(e,x=>"_ \\/.'|"[q=y/2&2|x>3,y&8?1:(k='40321123'[j=~~('0x'+(1e6+'1023405671567899AB99A899CB99C')[y%4+~-(n/10**q%10)*4])]^x%4?2045>>j&1:'0122233346545'[j])^0xCC6600>>k*4+q&1]))+f(n/1e4|0):''

Try it online!
Encoding
Each digit pattern is a 4x4 matrix consisting of 7 distinct characters. Each character is encoded as a single decimal digit from 0 to 6:
0: "_"
1: " "
2: "\"
3: "/"
4: "."
5: "'"
6: "|"

All matrices are built with 13 distinct rows, encoded as a single hexadecimal digit from 0 to C:
0: 1111 for "    "
1: 0001 for "___ "
2: 2111 for "\   "
3: 1211 for " \  "
4: 1121 for "  \ "
5: 1131 for "  / "
6: 1311 for " /  "
7: 3111 for "/   "
8: 1114 for "   ."
9: 1116 for "   |"
A: 1115 for "   '"
B: 0004 for "___."
C: 0005 for "___'"

So, each matrix is fully described by a sequence of 4 hexadecimal digits. For instance, the matrix for 7 is encoded as B99A:
B99A -> 0004 -> "___."
        1116    "   |"
        1116    "   |"
        1115    "   '"

The leading sequence is 0000 and is omitted. The other sequences are stored as:
1e6 + '1023405671567899AB99A899CB99C'

which expands to:
0      1    2    3    4    5    6    7    8    9
(0000) 1000 0001 0234 0567 1567 899A B99A 899C B99C

Each matrix row is made of a 'background' character appearing 3 times and a 'foreground' character appearing only once (or not at all). So the rows can be encoded as:

the position of the 'foreground' character (0 for rightmost to 3 for leftmost, or 4 if none)
the 'background' character (which is always either 0 for "_" or 1 for " ")
the 'foreground' character

This is summarized in the following table:
 ID | string | digits | FG position | BG char. | FG char.
----+--------+--------+-------------+----------+----------
  0 | "    " |  1111  |      4      |    1     |    0
  1 | "___ " |  0001  |      0      |    0     |    1
  2 | "\   " |  2111  |      3      |    1     |    2
  3 | " \  " |  1211  |      2      |    1     |    2
  4 | "  \ " |  1121  |      1      |    1     |    2
  5 | "  / " |  1131  |      1      |    1     |    3
  6 | " /  " |  1311  |      2      |    1     |    3
  7 | "/   " |  3111  |      3      |    1     |    3
  8 | "   ." |  1114  |      0      |    1     |    4
  9 | "   |" |  1116  |      0      |    1     |    6
  A | "   '" |  1115  |      0      |    1     |    5
  B | "___." |  0004  |      0      |    0     |    4
  C | "___'" |  0005  |      0      |    0     |    5
----+--------+--------+-------------+----------+----------
                             |           |          |
                             |           |          +--> stored as "0122233346545"
                             |           +-------------> stored as the bit mask 2045
                             +-------------------------> stored as "40321123"


Minimal Fresh Substrings Thanks @NathanMerrill for allowing me to post this! The following is entirely his wording from this sandbox post (deleted):

We define a "Fresh" substring as a substring that is different from any other substring that starts earlier.

For example, if I take the string "abababc" and split it: ["ab","ab","a","bc"], the first and the last substring are fresh, but the middle two are not, because they can be found earlier in the string.

For this challenge, you need create a list of the smallest possible fresh substrings for each position in the string.  If there are no fresh substrings, output and empty list or empty string, etc.

For example, if you were passed "ABABCBA", you should return ["A","B","ABC","BC","C"].

Test Cases:

ABABCBA          A,B,ABC,BC,C,   // ABC instead of AB because there is an AB earlier in the string
AAAAAAA          A,,,,,,
ABCDEFG          A,B,C,D,E,F,G
ABDBABDAB        A,B,D,BA,ABDA,BDA,DA,,
ACABCACBDDABADD  A,C,AB,B,CAC,ACB,CB,BD,D,DA,ABA,BA,AD,,

The empty items are not mandatory.

PHP, 141 bytes

for($r=[];$i<$l=strlen($a=$argn);$i++)for($t=1;$t;$t*=$t<$l)in_array($s=substr($a,$i,$t),$r)|strpos($a,$s)<$i?$t++:$r[]=$s.$t="";print_r($r);

Try it online!


Function/macro that returns true if one of its arguments contains a call to itself Write a function (or macro) that returns true if and only if at least one of its arguments contains a call to the function itself and false otherwise.

For example:
int a=function(); //a==false
int b=function(0); //b==false
int c=function(function(0)); //c==true
int d=function(3*function(1)+2); //d==true (weakly-typed language)
bool e=function(true||function(1)); //e==true (strongly-typed language)

EDIT: The function/macro may call other auxiliary function/macros.

EDIT 2: The function must take at least one argument, unless the language used behaves like C, where a function that takes no arguments may still be called with arguments nonetheless.

Mathematica...

...was made for this.

SetAttributes[f, HoldAll]
f[x___] := ! FreeQ[Hold@x, _f]

f[]             (* False *)
f[0]            (* False *)
f[f[0]]         (* True *)
f[3 f[1] + 2]   (* True *)
f[True || f[1]] (* True *)

Everything is an expression, and an expression has a Head and a number of elements. So 1+2 is actually Plus[1,2], and {1,2} is actually List[1,2]. This means we can match any expression for the head we're interested in - in this case the function f itself.

All we need to do is find a way to prevent Mathematica from evaluating the function arguments before the function is called, such that we can analyse the expression tree within the function. What's what Hold and HoldAll is for. Mathematica itself uses this to all over the place to provide special cases for certain implementations. E.g. if you call Length[Permutations[list]] it will never actually create all those permutations and waste loads of memory, but instead realise that it can simply compute this as Length[list]!.

Let's look at the code above in detail, using the last call f[True || f[1]] as an example. Normally, Mathematica will evaluate function arguments first, so this would simply short-circuit and call f[True]. However we have set

SetAttributes[f, HoldAll]

This instructs Mathematica not to evaluate the arguments, so the FullForm of the call (i.e. the internal expression tree, without any syntactic sugar) is

f[Or[True,f[1]]]

And the argument will actually be received by f in this form. The next issue is that, within f, as soon as we use the argument, Mathematica will again try to evaluate it. We can suppress this locally with Hold@x (syntactic sugar for Hold[x]). At this point we've got a handle on the original expression tree and do with it whatever we want.

To look for a pattern in an expression tree we can use FreeQ. It checks that a given pattern is not found in the expression tree. We use the patter _f, which matches any subexpression with head f (exactly what we're looking for). Of course, FreeQ returns the opposite of what we want, so we negate the result.

One more subtlety: I've specified the argument as x___, which is a sequence of 0 or more elements. This ensures that f works with any number of arguments. In the first call, f[] this means that Hold@x will simply become Hold[]. If there were multiple arguments, like f[0,f[1]], then Hold@x would be Hold[0,f[1]].

That's really all there is to it.


Build a Killer Sudoku Solver You thought regular sudoku was hard, now try Killer Sudoku!

In the game of Killer Sudoku, you aren't given any numbers at all. Instead, you're given regions that are said to add up to a certain number. Consider the following example, from Wikipedia:

And its solution:

The program you write will take a format consisting of a sequence of 81 letters representing regions, followed by a sequence of numbers. Then each number in the sequence represents the sum of the numbers in each of the letter regions, starting from "A", "B", etc.

It will then output a sequence of 81 digits representing the solution.

For example, the example puzzle above would have the following input:

AABBBCDEFGGHHCCDEFGGIICJKKFLMMINJKOFLPPQNJOORSPTQNUVVRSTTQWUUXXSYZWWaaXXSYZWbbbcc
3 15 22 4 16 15 25 17 9 8 20 6 14 17 17 13 20 12 27 6 20 6 10 14 8 16 15 13 17

And the resulting output would be:

215647398368952174794381652586274931142593867973816425821739546659428713437165289

You may assume that the input is valid, and that the regions will always appear in order by A, B, ..., Y, Z, a, b, ..., z.

(Shortest code that works wins.)

GolfScript, 138 characters
n%~[~]:N;1/:P.&:L;9..*?{(.[{.9%)\9/}81*;]:§;L{.`{\~@@=*}+[P§]zip%{+}*\L?N==}%§9/..zip+\3/{{3/}%zip{{+}*}%}%{+}*+{.&,9=}%+1-,!{§puts}*.}do;

This is a killer sudoku solver in GolfScript. It expects input on STDIN in two rows as given in the example above.
Please note: Since the puzzle description does not make any restrictions on execution time I preferred small code size over speed. The code tests all 9^81 grid configurations for a solution which may take some time on a slow computer ;-)


Draw a network of nodes There is a network of up to 26 nodes (named A to Z or a to z as per your wish). Every pair of nodes may be connected or disconnected. A node may be connected to at most 4 other nodes. Your task is to draw the network in a 2D diagram. Input will be given such that this task is possible (see more constraints in output section).

Format

Input

Pairs of letters (A to Z or a to z as per your wish). They are not sorted in any order.
Optional - number of pairs

Output

An ASCII drawing that shows the actual links between the nodes. Nodes are given by a to z or A to Z. Use - for horizontal links and | for vertical links. Links may be of any (non-zero) length but they should be straight horizontal/vertical lines that do not bend. Spaces can be added provided they don't disfigure the picture.

You may not use built-ins that help in layout of the graph. Other graph-related built-ins may be allowed (though solutions without built-ins would be more appreciated). Shortest code wins.

Sample data

Input

A B
B F
B L
F K
L K
K R
K S
R P
S J
S P
J A
T V
V N

Output

A - B - F   T - V
|   |   |       |
|   L - K - R   N
|       |   |
J ----- S - P

Input

H C
G H
A B
B F
B C
F G
C D
D A

Output

A - B ----- F
|   |       |
D - C - H - G

CJam, 142
You didn't ask for an optimal, deterministic or fast solution, so here you go:
qN%Sf%::c_s_&:Aff#:E;{A{;[DmrDmr]2f*}%:C;E{Cf=~.-:*}%0m1{E{Cf=$~1$.-_:g:T\:+,1>\ff*\f.+T0="-|"=f+~}%CA.++:L2f<__&=!}?}gS25*a25*L{~2$4$=\tt}/N*

Try it online
This generates random coordinates for each letter and tests if the layout is acceptable (edge letters lining up and no intersections), until it is. It gets mind-numbingly slow as you add more edges.
The two D letters in the code specify the maximum x and y coordinates; I picked D (=13) because I think it should be sufficient for all cases, feel free to prove me wrong. But you can change them to other values to speed up the program, e.g. the 2nd example should finish within a minute or two if you use 3 and 4 instead.


Drawing a tree from an array Given a possibly nested, non-empty array of single-digit positive integers (not guaranteed unique), output the ASCII-art representation as a tree, using the box-drawing characters ┌ ┴ ┐ ─ │ ┬ ┼. (These were copied from Code Page 437, but you can use any equivalent representation).

Every integer of the array should be a leaf of the tree. Elements the same level deep in the array should be present at the same level of the tree. All elements should be separated by enough whitespace to be distinct (up to you to determine how wide, minimum of one space between).

For example, given array [[1, [2]], [3, [4, 5]]], output the following tree

 ┌─┴─┐
┌┴┐ ┌┴─┐
1 │ 3 ┌┴┐
  2   4 5

For array [1, 2, 3] the tree could look like

┌─┼─┐
1 2 3

But the array [[1, 2, 3]] would look like

  │
┌─┼─┐
1 2 3

While the array [1, [1, [1, [1]]]] could look like

 ┌─┴┐
 1 ┌┴─┐
   1 ┌┴┐
     1 │
       1

As a more complicated example, [1, [[[2, 3], 4], 5]] could be

┌┴───┐
1  ┌─┴┐
 ┌─┴┐ 5
┌┴┐ 4
2 3

or several other variations.

Input and output can be given by any convenient method.
You can print it to STDOUT or return it as a function result.
Either a full program or a function are acceptable.
Any amount of extraneous whitespace is acceptable, so long as the characters line up appropriately.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Python 3, 400 393 390 bytes

L=len
S,*K=' ┴┼│123456789'
def T(x):
 try:return[str(x+0)]
 except:
  z=[*map(T,x)];q=max(map(L,z))
  for p in z:p+=[S*L(p[0])]*(q-L(p))
  b=[S.join(a)for a in zip(*z)];t=b[0];l=L(t);s=0;e=L(z);r=[S]*l
  if e<2:return['│'.center(l),*b]
  for i in range(l):
   if t[i]in K:s+=1;r[i]='┬┌┐'[(s<e)-(s>1)]
   elif 0<s<e:r[i]='─'
  c=l//2;r[c]=K[r[c]=='┬'];return[''.join(r),*b]

Returns a list of strings from top to bottom.

EDIT 1: Trimmed 7 bytes by avoiding duplication of ┴┼ (net save of 2 bytes), cutting out 0 from the one string, changing how drawing characters are selected from ┬┌┐ (use < instead of ==), and replacing a L(z) I missed with e

EDIT 2: -2 bytes thanks to ovs and -1 byte thanks to Kevin Cruijssen

Try it online!

Ungolfed

def layer(item):
    if isinstance(item, int):
        return [str(item)]
    else:
        subs = [layer(sub) for sub in item]
        longest = max(map(len, subs))
        for sub in subs:
            sub += [' ' * len(sub[0])] * (longest - len(sub))
        below = [' '.join(l) for l in zip(*subs)]
        top = below[0]
        l = len(top)
        if len(subs) == 1:
            return ['│'.center(l), *below]
        seen = 0
        expected = len(subs)
        builder = [' '] * l
        for i in range(l):
            c = top[i]
            if c in '┴┼│123456789':
                seen += 1
                if seen == 1:
                    builder[i] = '┌'
                elif seen == expected:
                    builder[i] = '┐'
                else:
                    builder[i] = '┬'
            elif 0 < seen < expected:
                builder[i] = '─'
        center = l // 2
        if builder[center] == '┬':
            builder[center] = '┼'
        else:
            builder[center] = '┴'
        return [''.join(builder), *below]

Builds a tree from the leaves up, one layer at a time.


Minecraft Inventory Management Minecraft inventory management is hard. You have 17 diamonds, but you need 7 to craft an enchantment table, a pickaxe, and a sword. Do you pick them up and right click 7 times? Or do you right click once and right click twice and take the 7 left? It's so confusing!

for those of you who are now confused, don't worry, I'll explain it all in a sec

Challenge

Given the size of a stack of items and a desired amount, determine the least number of clicks to get that amount. You only need to handle up to 64 for both inputs and you may assume you have infinite inventory slots. You cannot use the drag-to-distribute trick.

Definitions

The inventory is a collection of slots where you can store items.

A slot is a storage space in your inventory where you can place up to one type of item.

A stack is a number of items placed in the same group. For the purposes of this challenge, a stack is simply a bunch of items in the same place (so ignore stack-size)

The cursor is your pointy thingy. That cursor. It can have items "on it"; in other terms, if you clicked on a slot and picked up items, the items you picked up are "on the cursor" until you put them down.

Specifications

There are four possible situations. Either you have an item on your cursor or you don't, and either you left click or you right click.

If you don't have an item on your cursor and you left-click on a slot, you pick up the entire stack.

If you don't have an item on your cursor and you right-click on a slot, you pick up half the stack, rounded up.

If you have an item on your cursor and you left-click on a slot, you place all of the items into that slot. (For all you Minecraft players, you won't have >64 items for this challenge and they're all 64-stackable, and you only have one type so the item swap does not apply here)

If you have an item on your cursor and you right-click on a slot, you place one item into that slot.

So, you start with all of the items given (first input, or second; you may choose the order) in a slot, and you want to finish with having the desired amount (other input) in your cursor.

Let's run through an example. Say you start with 17 items and you want 7. First, you right-click on the stack, which means you have picked up 9 and there are 8 in that slot. Then, if you right-click on the stack again, you place one item back into the slot, leaving you with 8 and the slot with 9. Finally, you right-click again and you have 7 and the slot has 10. Thus, you would return 3 (the number of clicks).

If you manage to out-click-golf me, please tell me and I will edit the example :P

Test Cases

These are manually generated, so please tell me if there are any errors. I do inventory management through jitter-clicking right click so I don't have experience with optimal inventory management :P

Given, Desired -> Output
17, 7 -> 3
64, 8 -> 5
63, 8 -> 5
10, 10 -> 1
10, 0 -> 0 # note this case
25, 17 -> 7

Explanations

This challenge might be tricky for non-Minecraft players, I have no idea. Here are some explanations.

64, 8 -> 5 because you pick up 32 using right click, place it down, pick up 16, place it down, then pick up 8.

63, 8 -> 5 for the same reason.

25, 17 -> 7 because you pick up 13, place it down, pick up 6 from the leftover 12, place 2 back into the leftover stack, and then place the 4 in the cursor into the 13, and then pick those up.

Rules

Standard loopholes apply
You may assume that 0 <= desired <= given <= 64
You may take input in either order and do I/O in any reasonable format

C++, 498 482 457 bytes
If this function is just called once, it can be 455 bytes.
I found that almost every online GCC compilers (including TIO) forbids me to omit the type of the function f. However, the GCC on my computer allows that, and I don't know why.
This one can handle large inputs if a slot can contain that number of items (though needs a larger array and will probably run out of time).
#import<bits/stdc++.h>
#define t N.first
#define X n.erase(n.find
#define p(c){if(c==r)return l;if(L.emplace(w={n,c},l).second)Q[U++]=w;}
#define T(S,C)n.insert(S);p(C)X(S));
using m=std::multiset<int>;using s=std::pair<m,int>;s Q[99999];int x,l,B,U;int f(int a,int r){if(!r)return 0;std::map<s,int>L;s f({a},B=0),w,N;L[Q[U=1]=f];for(;;){l=L[N=Q[B++]]+1;x=N.second;t.insert(0);for(int i:t){m n=t;X(i));if(x){T(i+x,0)T(i+1,x-1)}if(!x&&i){p(i)T(i/2,i-i/2)}}}}

Ungolfed:
#include <map>
#include <set>
#include <queue>
#include <iostream>

using namespace std;

struct state {
    multiset<int> t; int q;
    bool operator<(const state& i) const { return make_pair(t, q) < make_pair(i.t, i.q); }
};

int f(int a, int target) {
    if (target == 0) return 0;

    map<state, int> len;
    queue<state> qu;
    state first = {{a}, 0};
    qu.push(first);
    len[first] = 0;

    #define push(c) { state a = {n, c}; auto t = len.insert({a, l + 1}); if (t.second) { \
        if (a.q == target) return l + 1; qu.push(a); \
    } } // push new state into queue and check for termination
    #define next(stk, cur) { n.insert(stk); push(cur); n.erase(n.find(stk)); }
    // insert new stack, push new state, erase the stack (for another use)

    while (qu.size()) { // BFS cycle
        state now = qu.front();
        qu.pop();

        int q = now.q;
        int l = len[now];

        multiset<int> n(now.t);
        for (int i : now.t) { // click on non-empty stack
            n.erase(n.find(i));
            if (!q) { // nothing on cursor
                push(i); // click left
                next(i / 2, (i + 1) / 2); // click right
            }
            else { // item on cursor
                next(i + q, 0); // click left
                next(i + 1, q - 1); // click right
            }
            n.insert(i);
        }
        if (q) { // click on empty stack
            next(q, 0); // click left
            next(1, q - 1); // click right
        }
    }
}


Draw nested radicals Many formulas in math involve nested radicals (square root signs inside other square roots signs). Your task here is to draw these using ascii art.
Specs
You will be given two integers, the number inside the radical, and the number of radicals. I think the best way to explain what you have to do is with an example. Here is the output for 2, 4:
        ____________________
\      /       _______________
 \    /  \    /     __________
  \  /    \  /  \  /   _____
   \/      \/    \/  \/ 2

Here are some things to note:

The height of each radical increases by one
The length of the _'s are always 5 times the height
There is a space after the last / and before the next inner radical starts
The number inside will never be greater than 4 digits
If the number of radicals is 0, just output the number
Putting extra spaces to pad it into a rectangle is up to you
This is code-golf, so shortest code in bytes wins!

Test Cases
2, 4:
        ____________________
\      /       _______________
 \    /  \    /     __________
  \  /    \  /  \  /   _____
   \/      \/    \/  \/ 2

23, 0:
23

4, 1:
  _____
\/ 4

1234, 3:
      _______________
\    /     __________
 \  /  \  /   _____
  \/    \/  \/ 1234


Replace alias to form phrases Inspired by the C-directive #define.

Challenge

Given one phrase with some alias, and one array with each alias text. Output the initial phrase replacing each alias with its respective text.

An alias is defined by one sharp # followed by its index in the array (the index may start at zero or one). Alias can contains another alias inside its text, and you must resolve all them (maybe recursively). You can assume the alias will never run into an infinite-loop. Alias won't have leading zeroes (#02 is not alias at index 2, it is alias at index 0 followed by the text 2).

You can assume the array will not pass 20 items in length.

You can write a program, or a function or even a #define-it would be nice :)

You can also use another input-method that fits better for your language.

Example

phrase: "#0 & #3"
array: [
    "Programming #1",
    "Puzzles",
    "Code",
    "#2 Golf"
]
output: "Programming Puzzles & Code Golf"

Step by step:

0> "#0 & #3"
1> "Programming #1 & #2 Golf"
2> "Programming Puzzles & Code Golf"

Since this is code-golf, shortest answer in bytes wins!

Another samples

phrase: "#0!"
array: [
    "We are #1",
    "#2",
    "#3",
    "#4 !",
    "graduating"
]
output: "We are graduating !!"

phrase: "##0#1#0#21#3#4"
array: [
    "a",
    "m",
    "z",
    "n",
    "g"
]
output: "#amaz1ng"

phrase: "##1#23"
array: [
    "WEIRD",
    "0 C",
    "AS"
]
output: "WEIRD CAS3"

phrase: "#1#7#6y#4#7#10s#7b#11#0#0#11r#7#0h#6#5#2#5#9#4."
array: [
    "t",
    "#12#3",
    "#11ga#3",
    "#0#10v#11",
    "#0h#10#8g",
    "#7#8",
    "a#8",
    " ",
    "n",
    "o",
    "i",
    "e",
    "P#9s#10"
]
output: "Positive anything is better than negative nothing."

The examples above used Array with index starting at zero.


Is it a Pascal Prime? It is well known that odd primes will appear in Pascal's triangle exactly twice. However, not all numbers that appear exactly twice in Pascal's triangle are prime. We'll call these numbers Pascal primes.

Pascal primes are composite numbers that appear exactly twice in Pascal's triangle. The first few Pascal primes are

4, 8, 9, 12, 14, 16, 18, ...

Your challenge is to take a positive integer n as input and output true or false, depending on if n is a Pascal prime or not. This is code-golf, so the shortest program wins!

Wolfram Language (Mathematica), 45 bytes

CompositeQ@#&&Binomial~Array~{#-1,#}~FreeQ~#&

Try it online!

Every composite number n appears exactly twice on row n and cannot appear afterwards. So the condition for Pascal primes is that they don't appear at all within the first n-1 rows.

As far as I can tell, this is shorter than checking that it appears exactly twice within the first n rows and being able to use !PrimeQ instead.


Sum up a number in words Here's a simple one.

In the shortest code possible, given an arbitrary number such as 567421, print it out in words:

five
six
seven
four
two
one

You may assume the input is an integer that is already provided in a one-letter variable such as n.

Python

for i in `n`:print' ottffssennwhoiieiieoruvxvgn  ere ehe  e   nt'[int(i)::9]

"Inspired" by https://codegolf.stackexchange.com/a/32156/18638


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

The of operator is used to get a property from an object:

log words of "Hello World"

But in many cases you can use 's as a shortcut to save 1 character:

log "Hello World"'s words


Can the king catch the pawn? Given an input of four integers x1, y1,
x2, and y2, output whether a white king in chess
(with coordinates (x1,  y1)) could catch a black pawn
(with coordinates (x2,  y2)) and capture it if the
pawn is moving to promote to a queen as fast as possible.

The coordinates of the board are as follows:

       first coordinate (x)
             12345678

           1 .#.#.#.#
           2 #.#.#.#.
           3 .#.#.#.#
  second   4 #.#.#.#.
coordinate 5 .#.#.#.#
    (y)    6 #.#.#.#.
           7 .#.#.#.#
           8 #.#.#.#.

Assume it is white to move (the king's turn) and that both players play
optimally (the king will move as fast as possible to catch the pawn, and the
pawn will move as fast as possible to promote). The input coordinates will
always be distinct, and the pawn will never start with a y-coordinate of 8.

The king moves one square in any direction every turn (it can move diagonally),
and the pawn can only move one space forwards (decrease its y-coordinate),
unless it's at its initial position (with our coordinate system, y-coordinate
of 7), in which case it can move two spaces forwards.

The input can be given as a whitespace-/comma-separated string, an array of
strings/integers, or four function/command line/etc arguments. The coordinates
can be given in whichever order is most convenient/golfy (so, accepting input
as [y2, y1, x1, y2] is okay as long
as it's consistent). The output must be a truthy or falsy
value.

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

Truthy test cases:

5 3 3 2

6 1 1 7

3 3 3 2

4 1 4 7

7 7 1 7

1 8 1 7

Falsy test cases:

6 4 3 2

8 8 1 7

3 4 3 2

Python 2, 53 40
lambda x,y,p,q:y-2<q>=abs(x-p)+q/7+y/8*5

The king has coordinates (x, y) and the pawn (p, q).
There are three significant cases:

The pawn is on rank 7 and the king on rank 8. To capture the pawn, the king must be on the same file or an adjacent one.
Result: q = 7  ⋀  y = 8  →  |x - p| ≤ 1

The pawn is on rank 7. To capture the pawn, the king must be within six files.
Result: q = 7  →  |x - p| ≤ 6

The pawn is on a lower rank. To capture the pawn, the king must be able to reach the promotion square at most one move after the pawn.
Result: q < 7  →  |x - p| ≤ q  ⋀  y - 1 ≤ q

My solution is just these conditions golfed down. Hopefully there aren't mistakes this time.


Javascript function challenge add(1,2) and add(1)(2) both should return 3 A friend of mine challenged me to write a function that works with both of these scenarios

add(1,2)  // 3
add(1)(2) // 3

My instinct was the write an add() function that returns itself but I'm not sure I'm heading in the right direction.  This failed.

function add(num1, num2){
    if (num1 && num2){
        return num1 + num2;
    } else {
        return this;
    }
}

alert(add(1)(2));

So I started reading up on functions that return other functions or return themselves.

http://davidwalsh.name/javascript-functions
https://stackoverflow.com/questions/17235259/javascript-self-calling-function-returns-a-closure-what-is-it-for
https://stackoverflow.com/questions/17235259/javascript-self-calling-function-returns-a-closure-what-is-it-for

I am going to keep trying, but if someone out there has a slick solution, I'd love to see it!

JavaScript (as asked)
This is a "correct" way to do it but hardly the golfiest way. It's unclear if you're asking for shortest code (the question looks like it will be closed soon anyway.)
function add(a, b) {
    if(typeof b === "undefined")
        return function(c) { return a + c }
    return a + b
}


Find the maximum of 3 numbers without branching This time around your goal is to find the maximum of 3 integers (from -(2^31) to 2^31 - 1 in binary 2's complement) without using branching or loops.

You are only allowed to use

Inequality/Equality (==, >, >=, <, <=, !=) These count as 2 tokens.
Arithmetic (+, -, *, /)
Logical Operators (! not, && and, ||  or)
Bitwise Operators (~ not, & and, | or, ^ xor, <<, >>, >>> arithmetic and logical left and right shifts)
Constants. 0 tokens
Variable assignment. 0 tokens

Input 3 variables as a, b and c. Output the maximum number.

Standard atomic code-golf rules apply. If you have any questions please leave them in the comments. One token is any of the above with the special rules.

Javascript
6 tokens
function maxOf3(a, b, c) {
    (b>a) && (a=b);
    (c>a) && (a=c);
    return a;
}


Escape the labyrinth! You are trapped in this 5x5 labyrinth - each room is labelled from 1 to 25 and the exit is in room 1.

You are given as input the room you are currently in. Your task is to output the shortest sequence of moves (north, east, south, west) needed to reach room 1.

Moves can be output in any format you wish (list, string, array...) as long as you use the characters n,w,e,s.

Here are all the test cases:

1 => empty string/list
2 => w
3 => ww
4 => swwnw
5 => wswwnw
6 => seenwnw
7 => nw
8 => wnw
9 => wwnw
10 => swwnwnw
11 => eenwnw
12 => enwnw
13 => nwnw
14 => wnwnw
15 => wwnwnw
16 => enenwnw
17 => nenwnw
18 => wnenwnw
19 => nwnwnw
20 => wnwnwnw
21 => nenenwnw
22 => enwnenwnw
23 => nwnenwnw
24 => wnwnenwnw
25 => nwnwnwnw

Shortest answer in bytes wins!

Python 2, 64 bytes

def f(n):d=0x1211252b5375>>2*n-4&3;print"nwes"[d];f(n+d*3+d%2-5)

Try it online!

A function that prints one direction per line, terminating with error.

The constant 0x1211252b5375 encodes in base 4 the direction d we travel from each room number as a number 0 through 3. The extraction digit >>2*n-4&3 is also designed to give a negative shift error when n=1, terminating the code. We update the room number n via an offset that's computed from the direction d as d*3+d%2-5, which maps:

d   d*3+d%2-5
0  -> -5
1  -> -1
2  ->  1
3  ->  5


Matrix rotation sort Lets define a non-empty, unsorted and finite matrix with unique numbers as follow:
 $$N = \begin{Bmatrix} 4&5&7\\1&3&6 \end{Bmatrix}$$

Lets define 4 matrix moves as:

↑* (up): Moves a column up
↓* (down): Moves a column down
→* (right): Moves a row to the right
←* (left): Moves a row to the left

The asterisk(*) represents the column/row that is affected by the move (It can be 0-indexed or 1-indexed. Up to you. Please state which one in your answer).

The challenge is, using above moves, sort the matrix in a ascendant order (being the top left corner the lowest and the bottom right corner the highest).

Example

Input:
$$N=\begin{Bmatrix}4&2&3\\1&5&6 \end{Bmatrix}$$
Possible Output: ↑0 or ↓0. (Notice any of those moves can sort the matrix so both answer are correct)

Input:
$$N=\begin{Bmatrix}2&3&1\\4&5&6 \end{Bmatrix}$$
Possible Output: →0

Input (Example test case):
 $$N = \begin{Bmatrix} 4&5&7\\1&3&6 \end{Bmatrix}$$
Possible Output: ↑0↑1←1↑2

Input:
$$N = \begin{Bmatrix} 5&9&6\\ 8&2&4\\ 1&7&3 \end{Bmatrix}$$
Possible Output:
↑0↑2→0→2↑0→2↑1↑2←1

Input:
$$N = \begin{Bmatrix} 1 & 27 & 28 & 29 & 6 \\10 & 2 & 3 & 4 & 5 \\17 & 7 & 8 & 13 & 9 \\15 & 11 & 12 & 18 & 14 \\26 & 16 & 21 & 19 & 20 \\30 & 22 & 23 & 24 & 25  \end{Bmatrix}$$
Possible Output:
↑2↑1←3→0←3↓0←0←2→3↑3↑4

Input:
$$N = \begin{Bmatrix} 1  \end{Bmatrix} $$
Output:
 or any move

Input:
$$N = \begin{Bmatrix} 1&2\\3&4  \end{Bmatrix} $$
Output:

Notes

There can be different correct outputs (there don't need to be necessarily the same as the test cases or the shortest one)
You can assume it will be always a way to order the matrix
Edges connects (like pacman :v)
There wont be a matrix with more than 9 columns or/and rows
Assume matrix contains only positive non-zero unique integers
You can use any 4 distinct values other than numbers to represent the moves (in case of that, please state that in your answer)
Column/row can be 0 or 1 indexed
Winning criteria code-golf

Extra test cases are always welcome

JavaScript (ES6),  226  219 bytes
Brute force search, using right ("R") and down ("D") moves.
Returns either a string describing the moves, or an empty array if the input matrix is already sorted. Columns and rows in the output are 0-indexed.

f=(m,M=2)=>(g=(s,m)=>m[S='some'](p=r=>r[S](x=>p>(p=x)))?!s[M]&&m[0][S]((_,x,a)=>g(s+'D'+x,m.map(([...r],y)=>(r[x]=(m[y+1]||a)[x])&&r)))|m[S]((_,y)=>g(s+'R'+y,m.map(([...r])=>y--?r:[r.pop(),...r]))):o=s)([],m)?o:f(m,M+2)

Try it online!
Commented
f =                              // f = main recursive function taking:
(m, M = 2) => (                  //   m[] = input matrix; M = maximum length of the solution
  g =                            // g = recursive solver taking:
  (s, m) =>                      //   s = solution, m[] = current matrix
    m[S = 'some'](p =            // we first test whether m[] is sorted
      r =>                       // by iterating on each row
        r[S](x =>                // and each column
          p > (p = x)            // and comparing each cell x with the previous cell p
        )                        //
    ) ?                          // if the matrix is not sorted:
      !s[M] &&                   //   if we haven't reached the maximum length:
      m[0][S]((_, x, a) =>       //     try all 'down' moves:
        g(                       //       do a recursive call:
          s + 'D' + x,           //         append the move to s
          m.map(([...r], y) =>   //         for each row r[] at position y:
            (r[x] =              //           rotate the column x by replacing r[x] with
              (m[y + 1] || a)[x] //           m[y + 1][x] or a[x] for the last row (a = m[0])
            ) && r               //           yield the updated row
      ))) |                      //
      m[S]((_, y) =>             //     try all 'right' moves:
        g(                       //       do a recursive call:
          s + 'R' + y,           //         append the move to s
          m.map(([...r]) =>      //         for each row:
            y-- ?                //           if this is not the row we're looking for:
              r                  //             leave it unchanged
            :                    //           else:
              [r.pop(), ...r]    //             rotate it to the right
      )))                        //
    :                            // else (the matrix is sorted):
      o = s                      //   store the solution in o
)([], m) ?                       // initial call to g(); if we have a solution:
  o                              //   return it
:                                // else:
  f(m, M + 2)                    //   try again with a larger maximum length


Reverse Bit Order of 32-bit Integers Write the shortest code to reverse the bit order of a 32-bit integer.

Rules:

Input is assumed to be a valid integer or string equivalent if your language doesn't support numerical values (e.g. Windows Batch).
Output must be a valid integer or string equivalent if your language doesn't support numerical values (e.g. Windows Batch).
Standard library only.
It may be a function or a complete program.
Input may be either from stdin or as a function argument.
Output must be either stdout or as a returned value.
If your language has a built-in or standard library function that does this in one step (e.g. rbit in ARM assembly), that cannot be used.

Examples:

Key:

decimal

binary
(reverse)
reversed binary
decimal output

Examples:

-90 (8-bit example for demonstration)

10100110b
(reverse)
01100101b
101

486

00000000000000000000000111100110b
(reverse)
01100111100000000000000000000000b
1736441856

-984802906

11000101010011010001100110100110b
(reverse)
01100101100110001011001010100011b
1704506019

Note: Omissions are free game. If I didn't say it, and it's not one of the standard loopholes, then it's completely allowed.

MMIX assembly (28 Bytes)

64 bit numbers

rbit:
    SETH $1,#0102 # load matrix in 16-byte steps
    ORMH $1,#0408
    ORML $1,#1020
    ORL  $1,#4080
    MOR  $0,$1,$0 # multiplication 1
    MOR  $0,$0,$1 # multiplication 2
    POP  1,0      # return

This assembles to:

rbit:
    E0010102 # SETH $1,#0102
    E9010408 # ORMH $1,#0408
    EA011020 # ORML $1,#1020
    EB014080 # ORL  $1,#4080
    DC000100 # MOR  $0,$1,$0
    DC000001 # MOR  $0,$0,$1
    F8010000 # POP  1,0

How does it work?

The MOR instruction performs a matrix multiplication on two 64-bit quantities used as two 8x8 matrices of booleans. A boolean number with digits abcdefghklmnopqr2 is used as a matrix like this:

/ abcd \
| efgh |
| klmn |
\ opqr /

The MOR instruction multiplies the matrices represented by their arguments where multiplication is and and addition is or. It is:

/ 0001 \      / abcd \      / opqr \
| 0010 |  \/  | efgh |  --  | klmn |
| 0100 |  /\  | klmn |  --  | efgh |
\ 1000 /      \ opqr /      \ abcd /

and furthermore:

/ opqr \      / 0001 \      / rqpo \
| klmn |  \/  | 0010 |  --  | nmlk |
| efgh |  /\  | 0100 |  --  | hgfe |
\ abcd /      \ 1000 /      \ dcba /

which is the reverse order of bits of the original number.

32 bit numbers

If you just want the reverse of a 32 bit number instead of a 64 bit number, you can use this modified method:

rbit:
    SETL   $1,#0408 # load first matrix in two steps
    ORML   $1,#0102
    MOR    $1,$1,$0 # apply first matrix
    SLU    $2,$1,32 # compile second matrix
    16ADDU $1,$2,$1
    MOR    $1,$0,$1 # apply second matrix
    POP    1,0      # return

assembled:

rbit:
    E3010408 # SETL   $1,#0408
    EA010102 # ORML   $1,#0102
    DC010001 # MOR    $1,$1,$0
    3B020120 # SLU    $2,$1,32
    2E010201 # 16ADDU $1,$2,$1
    DC010001 # MOR    $1,$0,$1
    F8010000 # POP    1,0

The first matrix multiplication basically works like this:

/ 0000 \      / 0000 \      / 0000 \
| 0000 |  \/  | 0000 |  --  | 0000 |
| 0001 |  /\  | abcd |  --  | efgh |
\ 0010 /      \ efgh /      \ abcd /

the corresponding octabyte is #0000000001020408 which we load in the first two instructions. The second multiplication looks like this:

/ 0000 \      / 0001 \      / 0000 \
| 0000 |  \/  | 0010 |  --  | 0000 |
| efgh |  /\  | 0100 |  --  | hgfe |
\ abcd /      \ 1000 /      \ dcba /

The corresponding octabyte is #0102040810204080 which we create from the first matrix like this:

SLU $2,$1,#32   # $2 = #0102040800000000
16ADDU $1,$2,$1 # $2 = $2 + $1 << 4
                     = $2 + #0000000010204080
                #    = #0102040810204080

The second multiplication is business as usual, the resulting code has the same length (28 bytes).


Fifth Grade Math Problem for the Week: Automated Decryption of Caesar Ciphers My fifth-grade daughter is learning about codes and ciphers. She has reached the point of decoding a ciphertext that has been encoded with the Caesar cipher where the offset is not provided in advance.

Without computers this can be time-consuming, especially for long blocks of text. Luckily, we do have computers, and let's prove it.

Cipher definition and other bounds:

Every letter is offset by a fixed (but unknown) number of characters, while retaining the same case. Spaces and punctuation marks are unaffected. Thus, with offset 1, "A"→"B" and "c"→"d" but "," stays as ",".
Offset will be a positive integer.
English plaintexts only, and no accent marks in the ciphertext or the plaintext.

Your task: Given a ciphertext, determine the most likely correct plaintext via brute force with a dictionary lookup. Thus, generate all 26 possible solutions, then check for the presence of every word in each potential decryption in an English dictionary and select the potential solution with the highest percentage of words that are found there.

The ciphertext should be the only input to your program, and the plaintext should be the only output.

For the sake of this challenge: garbage in, garbage out — given an undecryptable input, your code can return any output. And if multiple solutions tie for % found in the dictionary, you can return any of them.

Sample inputs:

"Fsyvoxmo kxn mywwsddoo woodsxqc."

"Gwbqs Sadwfs Ghfwysg Poqy, Ghof Kofg vog pssb bchvwbu pih o pzif ct wbobs waousg kwhv ob slqszzsbh gcibrhfoqy."

"Pda pnqpd sehh oap ukq bnaa. Xqp jkp qjpeh ep eo bejeodaz sepd ukq."

Your system should accept any string as input and attempt to decode it, and must be able to decode these examples correctly. I completed an ungolfed solution in Mathematica in about 700 characters. Standard rules apply; no hard-coded solutions, etc. Smallest number of bytes wins.

Python 2, 384 319

a=raw_input()
e=lambda v,b:(ord(v)+b-65-32*(v>"``"))%26+65+32*(v>"``")
c=lambda b:''.join(chr(e(f,b))if f.isalpha() else f for f in a)
p=map(c,range(26))
w=map(str.strip,open('w'))
l=[0]*26
for k,i in enumerate(p):
    for j in i.split():
        if j.lower() in w:l[k]+=1
m=[i for i,j in enumerate(l)if j==max(l)][0]
print p[m]

I named my wordlist w, which is a newline-separated list of lowercase words.


Palindromic Primes without 11 Every palindrome with an even number of digits is divisible by 11, so 11 is the only [palindromic prime] with an even number of digits. - David Wasserman, OEIS

I learned this today the manual way, before I did my research, when my program skipped numbers with an even number of digits (except 11) when calculating palindromic primes. Your task: create a program or function that when given an integer input N, outputs the Nth term in Stephen's Palindromic Sequence™.

Stephen's Palindromic Sequence™

Stephen's Palindromic Sequence™ starts with 11, and continues with palindromic semiprimes divisible by 11. Basically, all of the semiprimes that would be primes if 11 didn't "count." The upside is that this list contains numbers with an even number of digits! Yay. And, a lot of numbers with an odd number of digits are skipped, since they were already prime.

The beginning of the sequence:

1   : 11
2   : 22
3   : 33
4   : 55
5   : 77
6   : 121
7   : 737
8   : 979
9   : 1111
10  : 1441
11  : 1661
12  : 1991
13  : 3113
14  : 3223
15  : 3443
16  : 3883
17  : 7117
18  : 7447
19  : 7997
20  : 9119
21  : 9229
22  : 9449
23  : 10901

*Although 1331 (11^3) and similar fit the spirit of this sequence, they do not fit the rules.

Longer test cases:

26  : 91619
31  : 103301
41  : 139931
51  : 173371
61  : 305503
71  : 355553
81  : 395593
91  : 725527
101 : 772277
127 : 997799
128 : 1099901
141 : 3190913
151 : 3739373
161 : 7589857
171 : 9460649
200 : 11744711
528 : 39988993

Input

Integer N, >= 1. You can use a 0-indexed N (be sure to adjust test cases) if you specify so in your answer. Trailing newlines allowed.

Output

The Nth term in Stephen's Palindromic Sequence™. Trailing newlines allowed.

Rules

The only input your program/function can take is N. Your program cannot, for example, fetch a sequence from OEIS (aka standard loopholes apply).
You must be able to print an output up to six digits (N=127). Time is not a factor - however, if your program/function gets very long very fast, you must prove that the algorithm works. If your language naturally allows longer outputs, it you can let it expand naturally up to its limit, or cap it at ten digits, whichever you prefer. Output/termination beyond your limit does not matter, as long as it does not appear to be a valid output.
Program/function function on invalid input is irrelevant.

Python 2, 76 73 72 70 69 68 bytes

n=input();c=k=m=11
while n:m*=k/c;k+=c;n-=`k`==`k`[::~m%k-c]
print k

Thanks to @WheatWizard for golfing off 3 bytes!

Thanks to @ØrjanJohansen for golfing off 1 byte!

Thanks to @xnor and @ØrjanJohansen for paving the way to 68 bytes!

Input is 0-indexed. Try it online! or verify the first 31 test cases.

Background

Recall that Wilson's theorem states that for all integers p > 1,

meaning that (p - 1)! + 1 is evenly divisible by p if and only if p is prime.

If p > 1 is not prime, it is composite; let q be the smallest prime divisor of p. Clearly, q ≤ p/q. There are two cases:

If q = p/q, we have that p = q².

If q = 2, (p - 1)! = 3! = 6, so (p - 1)! is congruent to 2 modulo p.

If p/q = q > 2, so 2q < p. This way, q and 2q are both among 1, …, p - 1, whose product is the factorial of p - 1, so 2p = 2q² = q · 2q divides (p - 1)! evenly.
If q < p/q, q and p/q are both among 1, …, p - 1, so p = q · p/q divides (p - 1)! evenly.

Summing up,

for all integers p > 1.

Now, for all integer congruences and all integers a, b, and c, the following holds.

When a = -1, b = 11, and c = -1, we follow that

and, since 21 and -23 are congruent modulo 44 and -1 and 11p-1 are congruent modulo 11p, we arrive at the following conclusion.

For all possible values of p, the outcome (11, 21, or 11p - 1) will fall in the range 0, …, 11p - 1, so these values match those that will be returned by Python's % operator.

How it works

We initialize c, k, and m to 11 after the saving the input in n. c will be constant for the remainder of the program. Since there are three occurrences of c on the following line and assigning c costs only two bytes, this saves a byte. k can be thought of 11p using the meaning of p from the previous paragraph; initially, k = 11 = 11 · 1!. m takes the place of 11 · (p - 1)!; initially, m = 11 = 11 · 0!. k and m will satisfy the relationship m = 11 · (k/11)! at all times.

n represents the number of “Stephen's palindromes” we have to find. Since k = 11 initially, we can output k verbatim without further computation. However, when n is positive, we enter the while loop. The loop begins by multiplying m by k/c = p, then adding 11 to k, thus incrementing p. If k is a member of the sequence, we subtract 1 from n and start over. Once n reaches 0, we found the sequence member at the desired index and break out of the loop, then print the last value of k.

The expression

`k`==`k`[::~m%k-c]

performs the actual test, and it's result (True / 1 for sequence members, 0 / False otherwise) is subtracted from n. As seen before, ~m % k = (-m - 1) % k = (-11 · (p - 1)! - 1) % 11p equals 10 if p is prime, 21 if p = 4, and 11p - 1 > 43 if p > 4 is composite. Thus, after subtracting c = 11, we're left with -1 for prime p and a positive integer larger than 9 otherwise.

For prime p, `k`[::-1] gives us the string representation of k with reversed digit order, so comparing it to `k` checks whether k is a palindrome. If it is, all conditions are fulfilled and k is a sequence member. However, if p is not prime, the large range step and the fact that k will always have more than one digit mean that `k`[::-1] cannot have the same number of digits as `k`, let alone be equal to it.


Make a math equation from the date In my Economics class, my friends and I like to come up with ways to rearrange the digits in the date (in MM/DD/YY) format to create a valid mathematical equation. For the most part, we are allowed to use addition, subtraction, multiplication, division, parentheses, and exponentiation in addition to concatenation.

Your program should do something similar. The program should import the current date and insert operators to print an expression according to the following rules.

The digits MUST be used in order. Rearrangement of digits is not allowed.
The resulting expression must be mathematically accurate.
Addition, subtraction, multiplication, division, exponentiation, and use of parentheses is allowed. So is concatenation of digits. However, not all operations are necessary. You cannot use a subtraction sign to make a digit negative (like -1+1+11=10 on November 11, 2010).
The program must run in 60 seconds on a standard machine.

For example, this challenge was written on November 10, 2015. The program would interpret this as 11/10/15. A sample output would be (1+1)/10=1/5.

Bonuses

You may multiply the number of bytes in your code by 0.9 for each one of the following your program supports.

The program prints all possible expressions that can be formed, separated by newlines. Multiply by an additional 0.95 if the expressions are listed in increasing order of additional symbols.
The program also works for MM/DD/YYYY dates, printing a possibility with the first two digits of the year in addition to the possibility without. If this bonus is combined with the first bonus, all possibilities with the first two digits of the year must be printed.
The program also prints an equation for when there are multiple equalities (for example, on November 11, 2011, 1=1=1=1=1=1 would be printed, in addition to possibilities such as 1*1=1=1=1=1, 1*1*1=1=1=1, and 1*1*1*1=1=1. All such cases must be printed for the first bonus to be achieved.
The program supports conversion to bases between 2 and 16. Note that if the base is not 10, all numbers in the expression must be written in the same base, and  (Base b) must be written after the expression (with b replaced accordingly).

This is code golf, so standard rules apply. Shortest code in bytes wins.

Python 3, 424 420 369 363 bytes
import time as t
r=range
x=len
d=list(t.strftime('%m%d%y'))
o=([[x,x+'(',x+')']for x in ['']+"+ - == * / **".split()])
n=[]
for l in o:
    n=l+n
o=n
for p in r(x(o)**(x(d)-1)):
    e=''
    for i in r(x(d)-1):
        e+=str(d[i])+o[(p//(x(o)**i))%x(o)]
    e+=str(d[-1])
    try:
        if eval(e)and e.find('=')!=-1:
            print(e.replace('==','=').replace('**','^'))
            break
    except:pass

Brute-forces all possible combinations of operations in the numbers and stops when it finds one.
EDIT: Saved 4 bytes thanks to @NoOneIsHere
EDIT 2: Saved 51(!) bytes thanks to @ValueInk


Draw the Olympic Games logo Challenge
Draw the Olympic Games logo...

...as character (e.g. ASCII) art!
Sample Output
      * * *               * * *               * * *
  *           *       *           *       *           *
*               *   *               *   *               *
*               * * *               * * *               *
*           *   *   *   *       *   *   *   *           *
  *       *   *       *   *   *   *       *   *       *
      * * *               * * *               * * *
          *               *   *               *
            *           *       *           *
                * * *               * * *

Your art doesn't have to look exactly like mine, but it has to represent the Olympic rings well enough that it's recognizable.
Rules

The program must write the art to the console.
Shortest code (in bytes, any language) wins.
A solution that prints rings in their respective colors (or a close representation) will be awarded a minus-twenty-point bonus.

The winner will be chosen on February 23rd at the end of the 2014 Winter Olympics.

Winners

Gold: marinus - APL, 62 points

Silver: Ayiko - Perl 6, 75 points

Bronze: evuez - Python, 107 points

Popular choice: Danko Durbić - Commodore 64 BASIC

Commodore 64 BASIC

Writing directly in the screen and color memory.

Output:

Here's how you do this with sprites.


Implement a strongly Darboux function According to Wikipedia, a strongly Darboux function is

  one for which the image of every (non-empty) open interval is the whole real line

In other words, a function \$f\$ is strongly Darboux if given 3 arbitrary real numbers \$a\$, \$b\$, and \$y\$, it is always possible to find an \$x\$ between (distinct) \$a\$ and \$b\$ such that \$f(x) = y\$.

For the purposes of this challenge, we will consider strongly Darboux functions over the rationals instead.

Your challenge is to write a program or function that:

gives a rational number as output for every rational number input,
always gives the same output for a given input, and
has the strongly Darboux property.

Input and output may be either of the following:

an arbitrary-precision number type, if your language has one (or has a library for one, e.g. GMP).
a string representation of the number, which you may assume will always contain a decimal point and at least one digit on either side. It may be in any base \$b \geq 2\$, but input and output must be in the same base. You may use any set of characters for the digits and decimal point (but again, they must be consistent between input and output).

The input will always have a terminating base \$b\$ expansion. As for the output, which may have a theoretically non-terminating base \$b\$ expansion depending on your choice of function, you may choose any of the following:

output digits forever.
take an additional integer as input and output at least that many digits.
output at least as many digits as are in the input (which may contain trailing zeroes).

Note that by the nature of this challenge, the convention that numbers may be assumed to be representable by standard number types does not apply, except for the second input described in option 2 above.

To avoid loopholes with functions that are only defined on non-terminating rationals, your submission must be able to produce output arbitrarily close to a desired value in practice. Formally, given rational numbers \$a\$, \$b\$, \$y\$, and \$\varepsilon\$, there must be a rational number \$x\$ that terminates in your chosen base such that \$a<x<b\$ and \$|f(x)-y|<\varepsilon\$.

To give you some ideas, here is a description of the Conway base 13 function:

Convert \$x\$ to base 13 and remove the decimal point.
If the result is of the form \$[x]A[y]C[z]_{13}\$, where \$[y]\$ and \$[z]\$ consist of only digits from 0 to 9, then \$f(x) = [y].[z]\$.
If the result is of the form \$[x]B[y]C[z]_{13}\$, where \$[y]\$ and \$[z]\$ consist of only digits from 0 to 9, then \$f(x) = -[y].[z]\$.
Otherwise, \$f(x) = 0\$.

This function is strongly Darboux. Say, for example, that we want to find some \$x\$ between \$123.456_{13}\$ and \$123.457_{13}\$ such that \$f(x) = 7.89\$. The base-13 value \$123.456A7C89_{13}\$ would satisfy this requirement.

Your submission may be an implementation of this function, although I suspect that there are other strongly Darboux functions that are a lot shorter to implement. :)

Retina 0.8.2, 43 50 bytes

^.*\.(..)*1(.)((..)+)1.((..)*)$
$2$*-$3.$5
0(.)
$1

Try it online! I/O is as a binary string. Encode a binary number y close to another binary number a as follows:

If a does not contain a ., suffix one.
If a contains an odd number of digits after the ., suffix a 0.
If y is negative then suffix 11 otherwise suffix 10.
For each digit in y, suffix 0 followed by that digit.
If y contains a ., suffix 11 at that point, otherwise suffix it after all the digits in y.

Explanation:

^.*\.(..)*1(.)((..)+)1.((..)*)$
$2$*-$3.$5

Pair the digits starting at the binary point. If the number is a valid encoding, then decode the last 1x digit pair to a . and the second last to an optional - sign. Digits before that are ignored.

0(.)
$1

This should just leave pairs that begin with 0, so delete the 0s.


Draw the Warm Welcome Secret Hat Winter Bash 2014 is on its prime and don't we all love the hats? Especially the secret hats!
So why not draw one of secret hats?
The challenge
Your task is to draw the Warm Welcome Hat in proportion, in a language of your choice and having an exact construction as appearing on this page.
As always, you can render the hat to a file or screen using vector or raster graphics. If your output is rasterised, your image must have dimensions of 400x400 pixels or more.
Moreover, the actual contents of the hat (the area of the bounding rectangle of the colored parts of the image) should cover more than 40% of your output image.
Specifications
The image below lists out various dimensions of the hat. All dimensions are in the unit, for example, pixels. All border radius in the image are to be drawn with a radius of 13 units.

Colors:

Red in the star and circular ring - rgb(255, 28, 34)
Yellow in the circle - rgb(255, 202, 87)
Lightest grey - rgb(88, 88, 92)
Darkest grey - rgb(31, 26, 26)
Middle grey - rgb(64, 64, 64)

Scoring
This is code golf, so the shortest answer (in bytes) wins.
As a word of warning, using existing compression (like embedding a compressed GIF) falls into several standard loopholes.

SVG (462 460 454 429 384 365 bytes)

I know it isn't a programming language, but I thought this will at least be useful to anyone generating SVG output...

This is based on Peter Taylor's SVG.

By using the original coords, and optimizing the paths a little, I managed to shrink the SVG down.  I also fixed the colours.

<svg><g stroke-linecap=round stroke-linejoin=round stroke-width=26><path d=M54,13,13,36V75H151V36L110,13 stroke=#1f1a1a /><path d=M21,84V36H37A91,91,0,0,1,127,36h16V84z stroke=#404040 /><path d=M30,36v48h104V36z stroke=#58585c fill=#58585c /></g><circle cx=82 cy=60 r=23 fill=#ffca57 stroke=#ff1c22 stroke-width=5 /><path d=M82,43,92,74,66,55H98L72,74z fill=#ff1c22

Update: Fixed flaw pointed out by Peter Taylor and position of rects and saved 2 more bytes.

Update 2: Incorporated another fix and suggestions from Peter (-6 bytes)

Update 3: Just noticed the instructions now specify all radii are 13, so taking advantage of that, and optimizing the paths a bit more, I saved another 25 bytes. More readable fiddle here.

Update 4: Since I am already assuming the SVG is embedded in HTML (standalone SVGs need the namespace declaration), I can actually squeeze this more. (a) I don't need the  width and height attributes because the size of the SVG is smaller than the default size browsers give to objects whose size is indeteminate (300x150), and (b) the HTML parser is forgiving about attributes which don't have quotes, so some of them can be removed (idea from Squeamish Ossifrage).  Saves another 45 bytes.

Update 5: Using hsl's tricks for de-quoting the colours and dropping the trailing end tags.  We saved another 19 bytes.  The latter seemed a bit cheaty to me at first, but since it works in all browsers, I changed my mind. :)  Thanks hsl!


Monday Mini-Golf #1: Reverse Fibonacci Solver Monday Mini-Golf: A series of short code-golf challenges, posted (hopefully!) every Monday.

A Fibonacci-like sequence is obtained using the same method as the famous Fibonacci sequence; that is, each number F(n) is found by adding the previous two numbers in the sequence (F(n) = F(n-1) + F(n-2)), or by subtracting the next two numbers (F(n) = F(n+2) - F(n+1)). The main difference is that these sequences can start with any two numbers. The zero-indexing of these sequences is disputable, but for now, we're going to use this rule:

The 0th number in a Fibonacci-like sequence is the last number which is smaller than the preceding number.

As an example, the Fibonacci sequence could be written as 1, 0, 1, 1, 2, 3, 5..., so the 0th number in the sequence is the lone 0.

Challenge

The goal of the challenge is to write a program or function that takes in three integers, in any format:

A and B, the two numbers with which to start generating a sequence.
N, the length of the resulting sequence to output.

And outputs the first N numbers of the sequence, starting at the 0th.

Details

A, B, and N may be taken in any order and format, as long as they are visibly separated. If you use a different order/format, please specify what it is.
You may assume that A, B, and N are always positive integers.
You may assume that N is no more than 100, and the resulting sequence will not contain x >= 2^31.
If A is larger than B, then B is the 0th number in the sequence.
The output must be separated by spaces, commas, and/or newlines.
A trailing space or newline is allowed, but not a trailing comma.

Test-cases

Example 1:

8 13 10

Working backward from 8 13 until we find a number larger than the previous, we get 13 8 5 3 2 1 1 0 1. Thus, 0 is the 0th number in this sequence. Working forward from this, we print out 0 and the next 9 members:

0 1 1 2 3 5 8 13 21 34

Example 2:

23 37 5

Again working backward to find the 0th number, we find 37 23 14 9 5 4 1 3. The 0th number this time is 1, so we print it out, along with the next 4 members:

1 4 5 9 14

Example 3:

4 3 8

With this one, we don't have to work backward to find the 0th number, because 3 is smaller than 4:

3 7 10 17 27 44 71 115

Example 4:

29 47 11

Result:

1 3 4 7 11 18 29 47 76 123 199

Scoring

This is code-golf, so shortest valid code in bytes wins. Tiebreaker goes to earlier posted submission. The winner will be chosen next Monday, Sep 28. Good luck!

Edit: Congrats to your winner, @Jakube, using Pyth for an amazing 23 bytes!

Pyth, 23 bytes

AQWgHGA,-HGG)VvwHA,H+GH

Try it online: Demonstration or Test Suite

Quite unusual style of Pyth programming. Sometimes functional programming has its downsides.

Explanation:

AQWgHGA,-HGG)VvwHA,H+GH  Q = input list of the two starting numbers
AQ                       G, H = Q (unpacking Q)
  WgHG                   while H >= G:
      A,-HGG                G, H = [H - G, G]
            )            end while
              vw         read a number from input
             V           for N in range(^):
                H           print H
                 A,H+GH     G, H = [H, G + H]


Type "Hello, World!" Write a program which generates keyboard events which type Hello, World!.

It doesn't have to be platform-independent.

It can't leave any keys pressed.  For example, in Java, Robot.KeyPress('H'); will leave H pressed, so you must release it with Robot.KeyRelease('H');

You may assume that the caps lock is off when your program is run.  Capital letters can be typed either by holding shift and pressing the letter, or by toggling caps lock.  For the !, you'll probably have to use the shift method.

Shortest code wins.

AppleScript, 50 bytes

tell app"System Events"to keystroke"Hello, World!"

Thanks to marinus for the suggestion.


Build a 4-vertex Connectedness Tester using NAND gates A connected graph is a graph that contains a path between any two vertices.
Challenge
Build a [2-input NAND-gate] circuit that determines whether a 4-vertex graph is connected.

(A gate's 2 inputs can be the same input bit or other gate.)

Output True if the graph is connected, and False otherwise.
Input
The six possible edges of a simple graph with 4 vertices:
[ 0e1 , 0e2 , 1e2 , 0e3 , 1e3 , 2e3 ]
where aeb represents whether there is an edge between vertices a and b
Connectedness is equivalent to the following conditions:

If less than 3 inputs are True then output False.

If more than 3 inputs are True then output True.

If exactly 3 inputs are True and they form a triangle then output False.

Otherwise, output True.

The answer that uses the fewest gates wins.  Ties will be broken by

the lowest circuit depth (length of longest path(s) from input to output).

19 NANDs
There is no simpler circuit than this.
There is code for testing it below the picture.
As for understanding it, that's difficult.
There are a couple of IF gates there, and the inputs are kinda grouped into a triangle with the free corner lines added for analysis one by one, but not in a simple way. If anyone manages to understand it, I will be impressed.

Verilog code with testing:
// 4-vertex Connectedness Tester
// Minimal at 19 NANDs
//
// By Kim Øyhus 2018 (c) into (CC BY-SA 3.0)
// This work is licensed under the Creative Commons Attribution 3.0
// Unported License. To view a copy of this license, visit
// https://creativecommons.org/licenses/by-sa/3.0/
//
// This is my entry to win this Programming Puzzle & Code Golf
// at Stack Exchange:
// https://codegolf.stackexchange.com/questions/69912/build-a-4-vertex-connectedness-tester-using-nand-gates/
//
// I am sure there are no simpler solutions to this problem.
// It has a logical depth of 11, which is deeper than
// circuits using a few more NANDs.

module counting6 ( in_000, in_001, in_002, in_003, in_004, in_005, in_006, out000 );
  input  in_000, in_001, in_002, in_003, in_004, in_005, in_006;
  output out000;
  wire   wir000, wir001, wir002, wir003, wir004, wir005, wir006, wir007, wir008, wir009, wir010, wir011, wir012, wir013, wir014, wir015, wir016, wir017;

  nand gate000 ( wir000, in_000, in_000 );
  nand gate001 ( wir001, in_001, in_003 );
  nand gate002 ( wir002, wir001, wir000 );
  nand gate003 ( wir003, in_002, wir002 );
  nand gate004 ( wir004, wir002, wir002 );
  nand gate005 ( wir005, wir004, in_002 );
  nand gate006 ( wir006, wir005, wir004 );
  nand gate007 ( wir007, in_005, wir006 );
  nand gate008 ( wir008, in_003, wir006 );
  nand gate009 ( wir009, in_004, wir003 );
  nand gate010 ( wir010, wir003, wir009 );
  nand gate011 ( wir011, wir009, wir000 );
  nand gate012 ( wir012, wir011, in_001 );
  nand gate013 ( wir013, wir008, wir012 );
  nand gate014 ( wir014, wir013, in_005 );
  nand gate015 ( wir015, wir006, wir013 );
  nand gate016 ( wir016, wir015, wir007 );
  nand gate017 ( wir017, wir016, wir010 );
  nand gate018 ( out000, wir014, wir017 );
endmodule

module connecting6_test;
   reg [5:0] X;
   wire a;

  counting6 U1 (
  .in_000 (X[0]),
  .in_001 (X[1]),
  .in_002 (X[2]),
  .in_003 (X[3]),
  .in_004 (X[4]),
  .in_005 (X[5]),
  .in_006 (X[6]),
  .out000 (a )
  );

  initial begin
    X = 0;
  end

  always
    #10  X = X+1;

 initial  begin
    $display("\t\t     \t_");
    $display("\t\ttime,\t \\db/_,\tconnected");
    $monitor("%d,\t%b,\t%d",$time, X, a );
  end

  initial
   #630  $finish;

endmodule

// iverilog -o hello hello.v
// vvp hello

Kim Øyhus