Simplify a continued fraction Continued fractions are expressions that describe fractions iteratively. They can be represented graphically:
$$
a_0 +\cfrac 1
 {a_1 + \cfrac 1
  {a_2 + \cfrac 1
   {\ddots + \cfrac 1
    {a_n}
   }
  }
 }
$$
Or they can be represented as a list of values: \$[a_0 ; a_1, a_2, \dots, a_n]\$
The challenge:
take a base number: \$a_0\$ and a list of denominator values: \$[a_1, a_2, \dots, a_n]\$ and simplify the continued fraction to a simplified rational fraction: return or print numerator and denominator separately.
Examples:

\$\sqrt 19\$: [4;2,1,3,1,2]: 170/39
\$e\$: [1;0,1,1,2,1,1]: 19/7
\$\pi\$: [3;7,15,1,292,1]: 104348/33215
\$ϕ\$: [1;1,1,1,1,1]: 13/8

Example implementation: (python)
def foo(base, sequence):
    numerator = 1
    denominator = sequence[-1]
    for d in sequence[-2::-1]:
        temp = denominator
        denominator = d * denominator + numerator
        numerator = temp
    return numerator + base * denominator, denominator
Winning: shortest code in bytes: --no builtins that do the entire problem allowed--

J, 8 5 bytes
Same as this, but uses a build-in for rationals.
Argument is {a0,a1,a2,a3,...} as a list of J extended precision rational numbers. Result is the fraction as a J extended precision rational number.
(+%)/

(+%) the plus-the-reciprocal-of
/ reduction over
Try it online!
-3 thanks to miles.


Tips for golfing in Excel? It's strange that I haven't seen this, as Excel seems to be a valid language for code golfing (despite its 'compiler' not being free).

Excel is somewhat of a wildcard in golfing, being good at golfing challenges of medium complexity, and sometimes simpler challenges as well. More often than not, Excel is good at challenges with string manipulation and mixed string-number manipulation.

What general tips do you have for golfing in Excel? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Excel (NOT VBA). Please, one tip per answer.

Vectorization with Arrays

Whenever a function takes an array as an argument instead of a singleton, That function will also output an array with the result value to the corresponding indecies.

Example:
=LEN(A1)+LEN(B2)+LEN(C3)
could be replaced with
=SUM(LEN({A1,B2,C3}))


Let's design a digit mosaic Challenge

Given a positive integer \$N\$, repeat each of its digits \$d_1, d_2, d_3, \cdots, d_n\$ a number of times corresponding to its position in \$N\$. In other words, each digit \$d_k\$ should be repeated \$k\$ times (for each \$1\le k\le n\$, 1-indexed), thus creating the new number:

$$\overline{d_1d_2d_2d_3d_3d_3\cdots\underbrace{d_nd_nd_n\cdots d_n}_{n\text { times}}}$$

Then, write it down both horizontally and vertically and fill in the blanks with copies of the digit that corresponds to the greater index between the column index and the row index of the blank space. The final output should look like this:

$$\begin{bmatrix}
 \color{red}{d_1}  \color{green}{d_2  d_2}  \color{blue}{d_3  d_3  d_3} \cdots \\
 \color{green}{d_2  d_2  d_2}  \color{blue}{d_3  d_3  d_3} \cdots \\
 \color{green}{d_2  d_2  d_2}  \color{blue}{d_3  d_3  d_3} \cdots \\
 \color{blue}{d_3  d_3  d_3  d_3  d_3  d_3} \cdots \\
 \color{blue}{d_3  d_3  d_3  d_3  d_3  d_3} \cdots \\
 \color{blue}{d_3  d_3  d_3  d_3  d_3  d_3} \cdots \\
 \vdots
\end{bmatrix}$$

Specs

You may take  \$N\$ as an integer, a string, a list of digits or a list of characters representing the digits. The output can be a newline-separated string, a list of strings / integers or a list of lists of characters / digits, but please include a pretty-print version too, if possible. If the output is a newline-separated string, it is also acceptable to:

have leading / trailing whitespace, as long as the visual appearance of the output doesn't change
separate the columns using a consistent amount spaces or the rows with a consistent (non-zero) amount of newlines

You can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default. This is code-golf, so try  to complete the task in the least bytes you can manage in your language of choice.

Test cases

65:

655
555
555

---------------

203:

200333
000333
000333
333333
333333
333333

--------------

233:

233333
333333
333333
333333
333333
333333

---------------

5202:

5220002222
2220002222
2220002222
0000002222
0000002222
0000002222
2222222222
2222222222
2222222222
2222222222

---------------

12345:

122333444455555
222333444455555
222333444455555
333333444455555
333333444455555
333333444455555
444444444455555
444444444455555
444444444455555
444444444455555
555555555555555
555555555555555
555555555555555
555555555555555
555555555555555


Cardinals and ordinals, 1 to 100 Here's a simple one to stretch your compression muscles. Your code (a complete program) must output the spelled-out English representation of all the cardinal numbers from 1 to 100, and then all the ordinal numbers from 1 to 100. The numerals in each list should be delimited by commas and spaces and properly hyphenated. Each list should begin with a single capital letter and conclude with a period. The two lists should be separated by a newline.

For clarity's sake, you must produce this exact byte stream:

One, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, twenty-one, twenty-two, twenty-three, twenty-four, twenty-five, twenty-six, twenty-seven, twenty-eight, twenty-nine, thirty, thirty-one, thirty-two, thirty-three, thirty-four, thirty-five, thirty-six, thirty-seven, thirty-eight, thirty-nine, forty, forty-one, forty-two, forty-three, forty-four, forty-five, forty-six, forty-seven, forty-eight, forty-nine, fifty, fifty-one, fifty-two, fifty-three, fifty-four, fifty-five, fifty-six, fifty-seven, fifty-eight, fifty-nine, sixty, sixty-one, sixty-two, sixty-three, sixty-four, sixty-five, sixty-six, sixty-seven, sixty-eight, sixty-nine, seventy, seventy-one, seventy-two, seventy-three, seventy-four, seventy-five, seventy-six, seventy-seven, seventy-eight, seventy-nine, eighty, eighty-one, eighty-two, eighty-three, eighty-four, eighty-five, eighty-six, eighty-seven, eighty-eight, eighty-nine, ninety, ninety-one, ninety-two, ninety-three, ninety-four, ninety-five, ninety-six, ninety-seven, ninety-eight, ninety-nine, one hundred.
First, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth, twenty-first, twenty-second, twenty-third, twenty-fourth, twenty-fifth, twenty-sixth, twenty-seventh, twenty-eighth, twenty-ninth, thirtieth, thirty-first, thirty-second, thirty-third, thirty-fourth, thirty-fifth, thirty-sixth, thirty-seventh, thirty-eighth, thirty-ninth, fortieth, forty-first, forty-second, forty-third, forty-fourth, forty-fifth, forty-sixth, forty-seventh, forty-eighth, forty-ninth, fiftieth, fifty-first, fifty-second, fifty-third, fifty-fourth, fifty-fifth, fifty-sixth, fifty-seventh, fifty-eighth, fifty-ninth, sixtieth, sixty-first, sixty-second, sixty-third, sixty-fourth, sixty-fifth, sixty-sixth, sixty-seventh, sixty-eighth, sixty-ninth, seventieth, seventy-first, seventy-second, seventy-third, seventy-fourth, seventy-fifth, seventy-sixth, seventy-seventh, seventy-eighth, seventy-ninth, eightieth, eighty-first, eighty-second, eighty-third, eighty-fourth, eighty-fifth, eighty-sixth, eighty-seventh, eighty-eighth, eighty-ninth, ninetieth, ninety-first, ninety-second, ninety-third, ninety-fourth, ninety-fifth, ninety-sixth, ninety-seventh, ninety-eighth, ninety-ninth, one hundredth.

This is code golf, shortest answer in bytes wins.

Common Lisp, 88 82 80 bytes
(format t"~@(~{~R~^, ~}~).
~:*~@(~{~:R~^, ~}~)."(loop as i to 99 collect(1+ i)))

(It is part of the language, I hope you don't mind)
Output
One, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty, twenty-one, twenty-two, twenty-three, twenty-four, twenty-five, twenty-six, twenty-seven, twenty-eight, twenty-nine, thirty, thirty-one, thirty-two, thirty-three, thirty-four, thirty-five, thirty-six, thirty-seven, thirty-eight, thirty-nine, forty, forty-one, forty-two, forty-three, forty-four, forty-five, forty-six, forty-seven, forty-eight, forty-nine, fifty, fifty-one, fifty-two, fifty-three, fifty-four, fifty-five, fifty-six, fifty-seven, fifty-eight, fifty-nine, sixty, sixty-one, sixty-two, sixty-three, sixty-four, sixty-five, sixty-six, sixty-seven, sixty-eight, sixty-nine, seventy, seventy-one, seventy-two, seventy-three, seventy-four, seventy-five, seventy-six, seventy-seven, seventy-eight, seventy-nine, eighty, eighty-one, eighty-two, eighty-three, eighty-four, eighty-five, eighty-six, eighty-seven, eighty-eight, eighty-nine, ninety, ninety-one, ninety-two, ninety-three, ninety-four, ninety-five, ninety-six, ninety-seven, ninety-eight, ninety-nine, one hundred.
First, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth, fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth, twenty-first, twenty-second, twenty-third, twenty-fourth, twenty-fifth, twenty-sixth, twenty-seventh, twenty-eighth, twenty-ninth, thirtieth, thirty-first, thirty-second, thirty-third, thirty-fourth, thirty-fifth, thirty-sixth, thirty-seventh, thirty-eighth, thirty-ninth, fortieth, forty-first, forty-second, forty-third, forty-fourth, forty-fifth, forty-sixth, forty-seventh, forty-eighth, forty-ninth, fiftieth, fifty-first, fifty-second, fifty-third, fifty-fourth, fifty-fifth, fifty-sixth, fifty-seventh, fifty-eighth, fifty-ninth, sixtieth, sixty-first, sixty-second, sixty-third, sixty-fourth, sixty-fifth, sixty-sixth, sixty-seventh, sixty-eighth, sixty-ninth, seventieth, seventy-first, seventy-second, seventy-third, seventy-fourth, seventy-fifth, seventy-sixth, seventy-seventh, seventy-eighth, seventy-ninth, eightieth, eighty-first, eighty-second, eighty-third, eighty-fourth, eighty-fifth, eighty-sixth, eighty-seventh, eighty-eighth, eighty-ninth, ninetieth, ninety-first, ninety-second, ninety-third, ninety-fourth, ninety-fifth, ninety-sixth, ninety-seventh, ninety-eighth, ninety-ninth, one hundredth.

Explanations
See Formatted Output to Character Streams.

(format t "<control string>" <arguments>) formats the control string according to the (variadic) arguments and prints to standard output (because t)

(loop ...) builds the list of integers from 1 to 100

~@( ... ~) capitalizes the string returned by the inner control string

~{ ... ~} iterates over the current argument and applies the inner formatting to each element

Inside the iteration, everything that follows ~^ is not printed on the last iteration: this is used to add the comma-space separator between elements.

~R outputs current argument as a cardinal

~:R outputs current argument as an ordinal

~% outputs a new line

~:* reset the current argument to be processed as the previous one, which is used here to reuse the list of integers a second time.

Saved 2 bytes thanks to PrzemysławP.


Efficient Scientific Notation The other day my chemistry teacher was explaining to us about scientific notation (using a small number and multiplying it by powers of ten to express large numbers more easily), which brought me back a few years to when I first learnt it. After learning the basics, we had done a bunch of typical maths questions, some of which were like the following:

  Represent the following in scientific notation:
  a) 50000000
  b) 120000000000000
  c) 90000000000000000000000000000000000000
  d) pi^e^i^j^k^std::vector
  ...
  z) 200
  ...

And I thought, "What? We were told that scientific notation was used to make writing large numbers more efficient, but some cases aren't more efficient at all!"

Consider the number

300

and its representation in scientific notation:

3x10^2

What, the scientifically notated version actually takes up more space? We can't have that now can we? (Screen space is precious.)
We could determine ourselves if it's more space efficient to write a number in scientific notation or not, or...

Task

Your program or function should take as input a single positive number n of arbitrary size (up to what your language supports) and output the scientifically notated version of the number.
However, if the original number n, after removal of trailing zeroes and trailing decimal place, takes less or the same amount of characters to display than its scientifically notated version, you must output that original number n instead.

Your code needs to be as short as possible because the output also has to be as short as possible.

Specifications

Efficient Scientific Notation is defined as follows:

bx10^e

b is the input number appropriately divided by powers of 10 such that 1 <= b < 10.  This number must have all trailing zeroes (and decimal point if required) removed, but must have the precision of the original number (up to the decimal point limit in your language, of course). Ie 90000 becomes 9, 13.500 becomes 1.35, 0.000675 becomes 6.75 etc. If this number ends up containing more decimal places than your language can handle, it should be rounded to that maximum number of decimal places.

e is the exponent to which ten is raised such that n = b x 10^e (remember that this number needs to be negative if n is smaller than 1). This number should not have any trailing zeros or a decimal place (mainly because if it's not an integer something is wrong...).

The characters x10^ must remain as is in the string between b and e.

Test cases

Input -> output
1 -> 1
20 -> 20
3000000 -> 3x10^6
400000 -> 400000
0.008093 -> 0.008093
0.007835000000000 -> 0.007835
0.000003000000 -> 3x10^-6
0.00000065 -> 6.5x10^-7
0 -> 0

Scoring

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

Other rules and clarification

Trailing zeros (and/or trailing decimal place) are not counted towards the character count of the original input number n. Keep that in mind for cases such as test case 6
You may assume that if the input number is less than 1, it will always start with a 0 in place for the ones digit (as in test cases 5-8).
Input number will never be negative
Built-ins that make this challenge trivial and standard loopholes are disallowed
A trailing newline in the output is OK

EDIT
Thanks to user81655 for pointing out test cases 7 and 8 had incorrect powers of ten. I have now fixed those so make sure your code evaluates them correctly.

ES6, 83 81 bytes

x=>(e=s=>s.replace(/e\+?/,'x10^'),z=e(x.toExponential()),y=e(''+x))[z.length]?z:y

Probably fails for some edge cases where toString insists on exponential format.

Edit: Saved 2 bytes thanks to @user81655.


Implement the Method of Finite Differences The Method of Finite Differences is a technique used to find the next term in a sequence of numbers, given that the sequence is governed by consecutive values of a certain polynomial. Given a list of n terms, the Method will be able to determine the degree of the polynomial, which is a maximum of n+1.

The Method works by arranging the numbers in order, like so.

4 8 15 16 23 42

Then the difference between any number and its neighbor to the right (given that it has a neighbor to the right) is written in the row below. Note that entries must be written one space (ASCII 20) to the right of the longest entry in the previous column.

4 8 15 16 23 42
4 7 1  7  19

The process is repeated until there is one entry left in the bottom row.

4   8  15 16 23 42
4   7  1  7  19
3   -6 6  12
-9  12 6
21  -6
-27

Then the bottom row's entry is duplicated.

4   8   15 16 23 42
4   7   1  7  19
3   -6  6  12
-9  12  6
21  -6
-27 -27

Then the above process for finding differences is reversed until there is a new entry in the first row, which is separated from the other entries by  |

4   8   15  16  23  42 | 46
4   7   1   7   19  4
3   -6  6   12  -15
-9  12  6   -27
21  -6  -33
-27 -27

The Method moves down rows until all of the entries in a row are equal. Take the starting numbers 2 5 10 17 26. This is the finished table.

2 5 10 17 26 | 37
3 5 7  9  11
2 2 2  2

The degree of the polynomial is the number of rows minus 1. As you might tell from the previous example, the polynomial is x^2+1.

Your program will take as its input a list of integers separated by whitespace. You may assume that the list contains only integers and has at least 2 elements (they need not be distinct; the resulting chart would have only 1 row). The program will output the entire table generated by the Method of Finite Differences, as defined above.

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

CJam, 74 73 71 68 bytes

q~]{_2ew::-Wf*_)-}g0]W%{_W=@W=++_}*;)"|"\++]W%z{:s_:,$W=)f{Se]}}%zN*

Try it online

The latest version uses the middle section of @MartinBüttner's proposed solution, which is 3 bytes shorter than what I had. The first part for calculating the difference rows was identical. The part for the final formatting was the same length, so I kept my original version. Martin's savings came from making the sum part of the list while the new values are calculated, and using a * instead of a % loop. That also simplified the insertion of the "|".

Explanation:

l       Get one line of input.
~]      Interpret input and wrap in list.
{       While loop to construct additional lines.
  _2ew    Copy and build pairs of subsequent numbers.
  ::-     Reduce all number pairs by subtraction.
  Wf*     Multiply all of them by -1, since the reduction calculated 1st minus 2nd,
          but we need 2nd minus 1st.
  _)-     Check if all numbers in list are equal by popping off last and removing
          value from the list. This is truthy if all numbers are not equal.
}g      End of while loop to construct additional lines.
0       Add a 0 at the end, which will be the starting point of the sum for
        calculating the new values.
]       Wrap all lines in a list.
W%      Revert order of list, since adding the additional numbers in each row
        goes in bottom-up order.
{       Start of loop over rows.
  _W=     Get last value of row.
  @       Rotate previous row to top.
  W=      Extract last value as new increment. For the 0 that was added as an
          additional row, this is a comparison with -1, which gives the desired
          value of 0.
  +       Add increment to last value.
  +       Append value to list.
  _       Copy row for use in next loop iteration.
}*      End of loop over rows.
;       Remove extra copy of last row.
)       Pop off last value of last row.
"|"     Push the vertical bar.
\       Swap vertical bar and last value.
++      Concatenate the 3 parts.
W%      Revert order of list, to get the rows back in original order.
z       Transpose list for handling column alignment.
{       Loop over columns.
  :s      Convert values to strings.
  _:,     Copy and calculate the length of all values.
  $W=     Get maximum length by sorting and getting last value.
  )       Increment to add space between columns.
  f{      Apply to all values.
    Se]     Right pad to column width with spaces.
  }       End apply to all values.
}%      End loop over columns.
z       Transpose back to row order.
N*      Join rows with newlines.


Longest common substring in linear time This challenge is about writing code to solve the following problem.

Given two strings A and B, your code should output the start and end indices of a substring of A with the following properties.

The substring of A should also match some substring of B.
There should be no longer substring of A that satisfies the first property.

For example:

A = xxxappleyyyyyyy

B = zapplezzz

The substring apple with indices 4 8 (indexing from 1) would be a valid output.

Functionality

You can assume the input will be on standard in or in a file in the local directory, that is your choice. The file format will simply be two strings, separated by a new line. The answer should be a full program and not just a function.

I would eventually like to test your code on two substrings taken from the strings in http://hgdownload.cse.ucsc.edu/goldenPath/hg38/chromosomes/ .

Score

This is code-golf with a twist. Your code must be run in O(n) time, where n is the total length of the input.

Languages and libraries

You can use any language which has a freely available compiler/interpreter/etc. for Linux. You should only use standard open source libraries not designed to solve this task. In case of dispute, I will count this as any library which either comes as standard with your language or one that you can install in a default ubuntu machine from a default repository.

Useful information

There are at least two ways to solve this problem in linear time. One is to first compute the suffix tree and the second is to first compute the suffix array and the LCP array.

Here is a full and (perhaps over-)detailed explanation of linear time suffix tree construction (it turns out some of the figures are messed up unfortunately). There is also a very nice SO answer about linear time suffix tree construction at https://stackoverflow.com/questions/9452701/ukkonens-suffix-tree-algorithm-in-plain-english .  It includes a link to source code too.  Another detailed explanation can be found here, this time giving a full solution in C.
Section 2 of http://www.cs.cmu.edu/~guyb/realworld/papersS04/KaSa03.pdf gives a linear time suffix array construction algorithm and Appendix A has C++ source code.  This answer tells you how then to compute the longest common substring https://cs.stackexchange.com/questions/9555/computing-the-longest-common-substring-of-two-strings-using-suffix-arrays .  Section 5 of https://courses.csail.mit.edu/6.851/spring12/scribe/lec16.pdf which also has an associated video lecture https://courses.csail.mit.edu/6.851/spring12/lectures/L16.html also explains the same algorithm starting at 1:16:00.

Python 2, 646 bytes

G=range;w=raw_input;z=L,m,h=[0]*3
s=w();t=len(s);s+='!%s#'%w();u=len(s);I=z*u
def f(s,n):
 def r(o):
	b=[[]for _ in s];c=[]
	for x in B[:N]:b[s[x+o]]+=x,
	map(c.extend,b);B[:N]=c
 M=N=n--~n/3;t=n%3%2;B=G(n+t);del B[::3];r(2);u=m=p=r(1)>r(0);N-=n/3
 for x in B*1:v=s[x:x+3];m+=u<v;u=v;B[x/3+x%3/2*N]=m
 A=1/M*z or f(B+z,M)+z;B=[x*3for x in A if x<N];J=I[r(0):n];C=G(n)
 for k in C:b=A[t]/N;a=i,j=A[t]%N*3-~b,B[p];q=p<N<(s[i:i-~b],J[i/3+b+N-b*N])>(s[j+t/M:j-~b],J[j/3+b*N]);C[k]=x=a[q];I[x]=k;p+=q;t+=1-q
 return C
S=f(map(ord,s)+z*40,u)
for i in G(u):
 h-=h>0;j=S[I[i]-1]
 while s[i+h]==s[j+h]:h+=1
 if(i<t)==(t<j)<=h>m:m=h;L=min(i,j)
print-~L,L+m

Try it online
This uses the skew algorithm described in "Simple Linear Work Suffix Array Construction" by Kärkkäinen and Sanders. The C++ implementation included in that paper already feels a little "golfy", but there is still plenty of room for making it shorter. For example, we can recurse until arriving at an array of length one, instead of short circuiting as in the paper, without violating the O(n) requirement.
For the LCP part, I followed "Linear-Time Longest-Common-Prefix Computation in Suffix Arrays and Its Applications" by Kasai et al.
The program outputs 1 0 if the longest common substring is empty.
Here is some development code that includes an earlier version of the program that follows the C++ implementation a bit more closely, some slower approaches for comparison, and a simple test case generator:
from random import *

def brute(a,b):
    L=R=m=0

    for i in range(len(a)):
        for j in range(i+m+1,len(a)+1):
            if a[i:j] in b:
                m=j-i
                L,R=i,j

    return L+1,R

def suffix_array_slow(s):
    S=[]
    for i in range(len(s)):
        S+=[(s[i:],i)]
    S.sort()
    return [x[1] for x in S]

def slow1(a,b):
    # slow suffix array, slow lcp

    s=a+'!'+b
    S=suffix_array_slow(s)

    L=R=m=0

    for i in range(1,len(S)):
        x=S[i-1]
        y=S[i]
        p=s[x:]+'#'
        q=s[y:]+'$'
        h=0
        while p[h]==q[h]:
            h+=1
        if h>m and len(a)==sorted([x,y,len(a)])[1]:
            m=h
            L=min(x,y)
            R=L+h

    return L+1,R

def verify(a,b,L,R):
    if L<1 or R>len(a) or a[L-1:R] not in b:
        return 0
    LL,RR=brute(a,b)
    return R-L==RR-LL

def rand_string():
    if randint(0,1):
        n=randint(0,8)
    else:
        n=randint(0,24)
    a='zyxwvutsrq'[:randint(1,10)]
    s=''
    for _ in range(n):
        s+=choice(a)
    return s

def stress_test(f):
    numtrials=2000
    for trial in range(numtrials):
        a=rand_string()
        b=rand_string()
        L,R=f(a,b)
        if not verify(a,b,L,R):
            LL,RR=brute(a,b)
            print 'failed on',(a,b)
            print 'expected:',LL,RR
            print 'actual:',L,R
            return
    print 'ok'

def slow2(a,b):
    # slow suffix array, linear lcp

    s=a+'!'+b+'#'
    S=suffix_array_slow(s)

    I=S*1
    for i in range(len(S)):
        I[S[i]]=i

    L=R=m=h=0

    for i in range(len(S)):
        if I[i]:
            j=S[I[i]-1]
            while s[i+h]==s[j+h]:
                h+=1
            if h>m and len(a)==sorted([i,j,len(a)])[1]:
                m=h
                L=min(i,j)
                R=L+h
            h-=h>0

    return L+1,R

def suffix_array(s,K):
    # skew algorithm

    n=len(s)
    s+=[0]*3
    n0=(n+2)/3
    n1=(n+1)/3
    n2=n/3
    n02=n0+n2
    adj=n0-n1

    def radix_pass(a,o,n=n02):
        c=[0]*(K+3)
        for x in a[:n]:
            c[s[x+o]+1]+=1
        for i in range(K+3):
            c[i]+=c[i-1]
        for x in a[:n]:
            j=s[x+o]
            a[c[j]]=x
            c[j]+=1

    A=[x for x in range(n+adj) if x%3]+[0]*3

    radix_pass(A,2)
    radix_pass(A,1)
    radix_pass(A,0)

    B=[0]*n02
    t=m=0

    for x in A[:n02]:
        u=s[x:x+3]
        m+=t<u
        t=u
        B[x/3+x%3/2*n0]=m

    A[:n02]=1/n02*[0]or suffix_array(B,m)
    I=A*1
    for i in range(n02):
        I[A[i]]=i+1

    B=[3*x for x in A if x<n0]
    radix_pass(B,0,n0)

    R=[]

    p=0
    t=adj
    while t<n02:
        x=A[t]
        b=x>=n0
        i=(x-b*n0)*3-~b
        j=B[p]
        if p==n0 or ((s[i:i+2],I[A[t]-n0+1])<(s[j:j+2],I[j/3+n0]) if b else (s[i],I[A[t]+n0])<(s[j],I[j/3])):R+=i,;t+=1
        else:R+=j,;p+=1

    return R+B[p:n0]

def solve(a,b):
    # linear

    s=a+'!'+b+'#'
    S=suffix_array(map(ord,s),128)

    I=S*1
    for i in range(len(S)):
        I[S[i]]=i

    L=R=m=h=0

    for i in range(len(S)):
        if I[i]:
            j=S[I[i]-1]
            while s[i+h]==s[j+h]:
                h+=1
            if h>m and len(a)==sorted([i,j,len(a)])[1]:
                m=h
                L=min(i,j)
                R=L+h
            h-=h>0

    return L+1,R

stress_test(solve)


Which Day of Christmas is it? Preface

In the well known carol, The Twelve Days of Christmas, the narrator is presented with several gifts each day. The song is cumulative - in each verse, a new gift is added, with a quantity one higher than the gift before it. One Partridge, Two Turtle Doves, Three French Hens, and so on.

At any given verse, N, we can calculate the cumulative sum of presents so far in the song by finding the Nth tetrahedral number, which gives the results:

Verse 1: 1
Verse 2: 4
Verse 3: 10
Verse 4: 20
Verse 5: 35
Verse 6: 56
Verse 7: 84
Verse 8: 120
Verse 9: 165
Verse 10: 220
Verse 11: 286
Verse 12: 364

For example, after verse 4, we've had 4*(1 partridge), 3*(2 turtle doves), 2*(3 French hens) and 1*(4 calling birds). By summing these, we get 4(1) + 3(2) + 2(3) + 1(4) = 20.

The Challenge

Your task is to write a program or function which, given a positive integer representing the number of presents 364 ≥ p ≥ 1, determines which day (verse) of Christmas it is.

For example, if p = 286, we are on the 11th day of Christmas. However, if p = 287, then the next load of presents has begun, meaning it is the 12th day.

Mathematically, this is finding the next tetrahedral number, and returning its position in the whole sequence of tetrahedral numbers.

Rules:

This is code-golf, so the shortest solution (in bytes) wins.
Standard golfing loopholes apply.
When it comes to days, your program must be 1-indexed.
Your submission must be a full program or a function - but not a snippet.

Test Cases

1   ->  1
5   ->  3
75  ->  7
100 ->  8
220 ->  10
221 ->  11
364 ->  12

Python, 27 bytes

lambda n:int((n*6)**.33359)

Try it online!

A direct formula with some curve-fitting, same as the original one found by Level River St.

The shifted equation i**3-i==n*6 is close to i**3==n*6 for large i. It solves to i=(n*6)**(1/3). Taking the floor the rounds down as needed, compensating for the off-by-one.

But, there are 6 inputs on boundaries where the error takes it below an integer it should be above. All of these can be fixed by slightly increasing the exponent without introducing further errors.

Python, 38 bytes

f=lambda n,i=1:i**3-i<n*6and-~f(n,i+1)

The formula n=i*(i+1)*(i+2)/6 for tetrahedral numbers can be more nicely written in i+1 as n*6=(i+1)**3-(i+1). So, we find the lowest i for which i**3-i<n*6. Each time we increment i starting from 1, the recursive calls adds 1 to the output. Starting from i=1 rather than i=0 compensates for the shift.


Print the intersection of sequences Sequences

You are given four number sequences, numbered 1 through 4.

OEIS The location of 0's when the natural numbers are listed in binary. Here's an example of how to calculate the sequence:

 0,1,10,11,100,101,110,111
 ^    ^     ^^  ^    ^
 0    3     78  10   14

The start of the sequence goes like this: 0, 3, 7, 8, 10, 14, 19, 20, 21, 23, 24, 27, 29, 31, 36, 37, 40, 45, 51, ...

OEIS This sequence includes the first natural number, skips the next two, then includes the next three, then skips the next four, and continues.

 0, 3, 4, 5, 10, 11, 12, 13, 14, 21, 22, 23, 24, 25, 26, 27, 36, ...

OEIS Positive integers where both the number of 0's and the number of 1's in the binary representation of the number are powers of 2.

2, 4, 5, 6, 9, 10, 12, 16, 23, 27, 29, 30, 33, 34, 36, 39,

OEIS The Hofstadter Q sequence.

  a(1) = a(2) = 1;
   a(n) = a(n-a(n-1)) + a(n-a(n-2)) for n > 2.

1, 1, 2, 3, 3, 4, 5, 5, 6, 6, 6, 8, 8, 8, 10, 9, 10, 11, 11, 12, 12, 12, 12, 16, 14, ...

Little is proven rigorously about this sequence, but many empirical results exist. One is particularly important, and you may assume it's valid for the entire series:

This paper observed that the elements of the series can be grouped into generations. If we number them starting at 1, then the kth generation contains exactly 2k elements. The relevant property is that all numbers in generation k are obtained by summing two numbers from generations k-1 and/or k-2, but never from earlier generations. You may use this (and only this) observation to put a lower bound on the remaining elements in the sequence.

Challenge

Your challenge is to print the first x numbers in the intersection of the given input sequences.

Input: Two numbers separated by a space on STDIN. The first number is an integer from 1 to 15 inclusive where each bit corresponds to a sequence. The lowest bit corresponds to sequence 1, and the highest corresponds to sequence 4. The second is amount of numbers, x, to output on STDIN.

Output: The first x numbers that intersect with the given input sequences. Print the numbers on STDOUT with any clear whitespace or punctuation as a delimiter (spaces, tabs, newlines, commas, colons, periods, etc).

Examples

1. Print the first 3 numbers that are in every sequence.

Input: 15 3

Output: 10,23,40

2. Print the first 12 numbers in sequences number 1 and 4.

Input: 9 12

Output: 3,8,10,14,19,20,21,23,24,31,37,40

3. Print the first 10 numbers in sequence 2.

Input: 2 10

Output: 0,3,4,5,10,11,12,13,14,21

4. Print the first 6 numbers in sequences 3 and 4.

Input: 12 6

Output: 2,4,5,6,9,10

Details

You may print the output as you go or all at once at the end.

Huge thanks to everyone who helped out with this in chat! This question benefited greatly from being in the sandbox.

Python 3, 590 639 characters

from itertools import count as C
D=lambda n,t='1':bin(n).count(t)
Y=range
def O():
 for n in C(0):yield from bin(n)[2:]
def B():
 s=i=0
 while 1:
  i+=s
  for j in Y(i,i+s+1):yield j
  s+=2;i+=s-1
def s(i):return D(i)==1
def F():
 a=[1]*3
 for n in C(3):a+=[a[n-a[n-1]]+a[n-a[n-2]]];yield a[-1]
L,R=input().split()
J=[x for x,U in zip([F(),(n for n in C(0)if s(D(n,'0')-1)and s(D(n))),B(),(i for i,c in enumerate(O())if'1'>c)],"{0:04b}".format(int(L)))if U>'0']
X=[set()for _ in J]
M=[]
Z=int(R);K=1
while len(M)<Z:
 for x,j in zip(X,J):x.add(next(j))
 for _ in Y(K):X[0].add(next(J[0]));K+=1
 M=X[0]
 for x in X:M=M&x
print(sorted(M)[:Z])

This is the straight-forward solution: use generators to define each of the infinite sequences, and so long as the intersection isn't large enough, add a step to each sequence.

To account for the non-monotonically-increasing Hofstadter sequence: at each step I generate twice as many for that sequence, e.g. 1, then 2, 4, 8, 16, 32, etc. I think that satisfies the bound stated in the question, and it's still fast enough for all the test cases presented there.


Number of tilings on a triangular board with triangular tiles Background

Consider the shape \$T(n)\$ consisting of a triangular array of \$\frac{n(n+1)}{2}\$ unit regular hexagons:

John Conway proved that \$n = 12k + 0,2,9,11\$ if and only if \$T(n)\$ can be tiled (i.e. exactly covered without overlapping) with \$T(2)\$. At the same time, he also proved that no coloring argument could prove the fact. (Yes, this is yet another Conway challenge.)

Challenge

Let's define \$a_n\$ as the number of distinct tilings of \$T(n)\$ by \$T(2)\$. Compute as many terms of \$a_n\$ as possible in 10 minutes.

Reflection and/or rotation of a tiling is considered distinct from itself, unless the two are identical.

The program that prints the largest number of terms wins. In case of tie, the one that prints the last term in shorter time wins.

I have a Windows 10 machine with Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz and 32GB RAM, with Ubuntu 18.04 installed in WSL. Please include the instructions to run your code and where it works (Windows or Linux).

Output format (with test cases)

The submission should print the results infinitely for each \$n\$ starting from 0. Each line should include the values of \$n\$ and \$a_n\$. Here is first 21 lines of the expected output:

0 1
1 0
2 1
3 0
4 0
5 0
6 0
7 0
8 0
9 2
10 0
11 8
12 12
13 0
14 72
15 0
16 0
17 0
18 0
19 0
20 0
21 185328
22 0
23 4736520
24 21617456
25 0
26 912370744
27 0
28 0
29 0
30 0
31 0
32 0

Test cases for \$n \le 20\$ are generated using a naive Python 3 program. \$a_{21}\$ through \$a_{32}\$ (meaningful highest being \$a_{26}\$) were found using Arnauld's JS submission.

Notably, neither the full sequence 1, 0, 1, 0, 0, 0, ... nor the stripped-down one 1, 1, 2, 8, 12, 72, ... is on OEIS yet. As I don't have an OEIS account, I will let anyone interested to post this sequence (both versions) to OEIS (please leave a comment before you do). The sequence of nonzero indices is A072065. Edit: The sequence is on A334875, thanks to Lyxal.

Leaderboard

Rust with rustc -O by Anders Kaseorg, Score 44 at 45s
C++ with g++ -O3 by l4m2, Score 35 at 7min
Javascript with node by Arnauld, Score 32 at 1.8s

Pending

(none)

JavaScript (Node.js), N =  22 25  32 in ~2 seconds
A recursive search using bit masks and a cache to keep track of patterns whose result is already known.
It doesn't make much sense to try go further in Node. Using a binary matrix is significantly slower and BigInts are even slower. It should rather be ported to a language natively supporting 64-bit integers.
'use strict';

let ts = new Date;

for(let n = 0; n <= 32; n++) {
  console.log(
    n.toString().padStart(2) + ' ' +
    solve(n).toString().padStart(10) + ' ' +
    '(' + ((new Date - ts) / 1000).toFixed(2) + ')'
  );
}

function solve(n) {
  // trivial cases
  if(![0, 2, 9, 11].includes(n % 12)) {
    return 0;
  }
  if(n == 0) {
    return 1;
  }

  // We work on a triangle stored as an array of bit masks:
  //   8 7 6 5 4 3 2 1 0 |
  //  -------------------+---  With this format, the tribones
  //   . . . . . . . . A | 0   are turned into the following
  //   . . . . . . . A A | 1   trominos:
  //   . . . . . . B B C | 2
  //   . . . . . D B C C | 3    X O    and    . X
  //   . . . . D D E E F | 4    O .           O O
  //   . . . G H H E F F | 5
  //   . . G G H I I J J | 6   where 'X' is the arbitrary anchor
  //   . K L L M I N J O | 7   point used in this code
  //   K K L M M N N O O | 8
  let a = Array(n).fill(0),
      cache = a.map(_ => new Object);

  // recursive search, starting at (x, y) = (0, 0)
  return (function search(x, y) {
    // if we've reached the last row, make sure it's complete
    if(y == n - 1) {
      if(a[y] == (1 << n) - 1) {
        return 1;
      }
      return 0;
    }

    // if we are beyond the last column, go on with the next row
    if(x < 0) {
      y++;

      // either return the result from the cache right away
      if(cache[y][a[y]] !== undefined) {
        return cache[y][a[y]];
      }
      // or do a full search
      return cache[y][a[y]] = search(y, y);
    }

    // if (x, y) is already set, advance to the next column
    if(a[y] >> x & 1) {
      return search(x - 1, y);
    }

    let res = 0;

    // try to insert X O
    //               O .
    if(x && !(a[y] >> x - 1 & 1)) {
      a[y] ^= 3 << x - 1;
      a[y + 1] ^= 1 << x;
      res += search(x - 2, y);
      a[y] ^= 3 << x - 1;
      a[y + 1] ^= 1 << x;
    }

    // try to insert . X
    //               O O
    if(!(a[y + 1] >> x + 1 & 1)) {
      a[y] ^= 1 << x;
      a[y + 1] ^= 3 << x;
      res += search(x - 1, y);
      a[y] ^= 1 << x;
      a[y + 1] ^= 3 << x;
    }

    return res;
  })(0, 0);
}

Try it online!
Output
 0          1 (0.00)
 1          0 (0.00)
 2          1 (0.00)
 3          0 (0.00)
 4          0 (0.00)
 5          0 (0.00)
 6          0 (0.00)
 7          0 (0.00)
 8          0 (0.00)
 9          2 (0.00)
10          0 (0.00)
11          8 (0.00)
12         12 (0.01)
13          0 (0.01)
14         72 (0.01)
15          0 (0.01)
16          0 (0.01)
17          0 (0.01)
18          0 (0.01)
19          0 (0.01)
20          0 (0.01)
21     185328 (0.05)
22          0 (0.05)
23    4736520 (0.24)
24   21617456 (0.60)
25          0 (0.60)
26  912370744 (2.18)
27          0 (2.18)
28          0 (2.18)
29          0 (2.18)
30          0 (2.18)
31          0 (2.18)
32          0 (2.18)


Print arrays from the middle out This is a code-golf question.

Given integers s and n the task is to output all arrays of length n which take values from -s to s.  The only twist is that you must output them in the following order.

The all zeros array of length n.
All arrays of length n with elements from -1 to 1 excluding any array you have outputted before.
All arrays of length n with elements from -2 to 2 excluding any array you have outputted before.
And so on until you get to all arrays of length n with elements from -s to s excluding any array you have outputted before.

You should output one array per line. They can be space or comma separated.

Here is some non-complying python code that outputs the arrays/lists/tuples in the right order.

import itertools

s =  3
n = 2

oldsofar = set()
newsofar = set()
for i in xrange(s):
    for k in itertools.product(range(-i,i+1), repeat = n):
        newsofar.add(k)
    print newsofar - oldsofar
    oldsofar = newsofar.copy()
    print "***"

Extra glory (and an upvote from me) for answers  that perform no set subtraction or equivalent.

MATL, 18 bytes
_G2$:iZ^t!|X>4#SY)

First input is s, second is n
This works in current version (15.0.0) of the language.
Try it online!
Explanation
_      % take input s implicitly. Negate to obtain -s
G      % push input s again
2$:    % inclusive range from -s to s
i      % take input n
Z^     % Cartesian power. Gives 2D array, with each result on a row
t!     % duplicate and transpose
|      % absolute value
X>     % maximum of each column
4#S    % sort and push the indices of the sorting
Y)     % apply as row indices into the 2D array. Display implicitly


The Colors in Our Stars Write a program that takes in a string or text file whose first line has the form

width height

and each subsequent line has the form

x y intensity red green blue

where:

width and height may be any positive integers.
x and y may be any integers.
intensity may be any non-negative integer.
red, green, and blue may be any integers from 0 to 255 inclusive.

Your program must output a truecolor image in any common lossless image file format whose dimensions are width by height. Each x y intensity red green blue line represents a colorful star or orb that must be drawn on the image. There may be any number of stars to draw, including 0. You may assume the string or file has a trailing newline.

The algorithm for drawing the image is as follows, though you may implement it in any way you like as long as the result is identical:

  For every pixel (X,Y) in the image (where X is 0 at the leftmost
  edge and width-1 at the rightmost edge, and Y is 0 at the top edge
  and height-1 at the bottom edge), the color channel C ϵ {red,
  green, blue} (a value pinned between 0 to 255) is given by the equation:

  Where the dist function is either Euclidean distance:

  Or Manhattan distance:

  Choose whichever distance function you prefer, based on golfability or aesthetics.

  Each of the lines in the input besides the first is an element of the Stars set. So, for example, Sx represents the x value on one of the input lines, and SC represents either red, green, or blue, depending on which color channel is currently being calculated.

Examples

Example A

If the input is

400 150
-10 30 100 255 128 0

the output should be

if you're using Euclidean distance, and

if you're using Manhattan distance.

Example B

If the input is

200 200
100 100 10 255 255 255
20 20 40 255 0 0
180 20 40 255 255 0
180 180 40 0 255 0
20 180 40 0 0 255

the respective outputs for Euclidean and Manhattan distance should be

 and .

Example C

If the input is

400 400
123 231 10 206 119 85
358 316 27 170 47 99
95 317 3 202 42 78
251 269 17 142 150 153
43 120 3 145 75 61
109 376 6 230 231 52
331 78 21 31 81 126
150 330 21 8 142 23
69 155 11 142 251 199
218 335 7 183 248 241
204 237 13 112 253 34
342 89 18 140 11 123

the output should be

if you're using Euclidean distance, and

if you're using Manhattan distance.

Example D

If the input is

400 400
123 231 5 206 119 85
358 316 5 170 47 99
95 317 5 202 42 78
251 269 5 142 150 153
43 120 5 145 75 61
109 376 5 230 231 52
331 78 5 31 81 126
150 330 5 8 142 23
69 155 5 142 251 199
218 335 5 183 248 241
204 237 5 112 253 34
342 89 5 140 11 123

the output should be

if you're using Euclidean distance, and

if you're using Manhattan distance.

Example E

If the input is

100 1

then the output should be a 100 pixel wide by 1 pixel tall image that is completely black.

Notes

Take the input string or the name of a text file that contains it from stdin or the command line, or you may write a function that takes in a string.
"Outputting" the image means either:

Saving it to a file with the name of your choice.
Printing the raw image file data to stdout.
Displaying the image, such as with PIL's image.show().

I won't be checking that your images are pixel perfect (Stack Exchange lossily compresses images anyway) but I will be very suspicious if I can visually tell any difference.
You may use graphics/image libraries.

Winning

The shortest submission in bytes wins. In case of ties, the earliest submission wins.

Fun Bonus: Give the input for a truly spectacular output image.


Randomized Brainfuck Compiler Joe is your average BF developer. He is about to check in his code changes to their repository when he gets a call from his boss. "Joe! The new client's machine is broken! The brainfuck interpreter sets all the cells to random values before program execution. No time to fix it, your code will have to deal with it." Joe doesn't think much of it, and is about to write a program to set the first million cells to zero, when his boss interrupts him again - "... and don't think about using brute force, the code has to be as small as possible." Now you have to help poor Joe!

Specifications

You will get some valid brainfuck code as input
Your program will then modify the code so that it should work on a randomized brainfuck interpreter
This means that before program execution, the cells can be set to any value.
The new program should have the exact same behavior no matter the initial conditions.
The interpreter will have max-cell value of 255 with wrapping, and an infinite length tape.

Scoring

Your score is 10 times the compiler size in bytes plus the sum of the test case sizes. Lowest score obviously wins.To mitigate against test-case optimization, I reserve the right to change the test-cases around if I suspect anything, and probably will do so before picking a winner.

Test Cases

(I got these from the esolangs page and this webpage: http://www.hevanet.com/cristofd/brainfuck/). Also thanks to @Sparr for the last test case.

Hello World: ++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
Reverse Input: >,[>,]<[.<]
Powers of Two (Infinite Stream): >++++++++++>>+<+[[+++++[>++++++++<-]>.<++++++[>--------<-]+<<]>.>[->[
<++>-[<++>-[<++>-[<++>-[<-------->>[-]++<-[<++>-]]]]]]<[>+<-]+>>]<<]
Squares Under 10000: ++++[>+++++<-]>[<+++++>-]+<+[>[>+>+<<-]++>>[<<+>>-]>>>[-]++>[-]+>>>+[[-]++++++>>>]<<<[[<++++++++<++>>-]+<.<[>----<-]<]<<[>>>>>[>>>[-]+++++++++<[>-<-]+++++++++>[-[<->-]+[<<<]]<[>+<-]>]<<-]<<-]
Fibonacci Stream: >++++++++++>+>+[[+++++[>++++++++<-]>.<++++++[>--------<-]+<<<]>.>>[[-]<[>+<-]>>[<<+>+>-]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>+>+<<<-[>+<-]]]]]]]]]]]+>>>]<<<]
ASCII Sequence till input: ,[.[>+<-]>-] (This one requires varying cell numbers based on the input)

sed, 46 byte compiler
s/</<</g
s/>/>[->[-]>[-]+<<]>/g
s/^/[-]>[-]+</

I didn't notice that the output was also supposed to be golf until after writing the program, so I will go for the short compiler. Also it was far too much work to test, so please notify if it does not function correctly :)


Let us make a quine maker! You are to create a program, that, given another program, and a position, will make it a quine. Namely, it needs to insert an expression at that point that evaluates to a string that is the programs input. For example:

main=do
    putStrLn "Welcome to the open source program, would you like my source code?"
    (ans:_) <- getLine
    case ans of
        'y' -> putStrLn  --Quine goes here
        'n' -> putStrLn "Okay, Good bye"
        _  -> putStrLn "Unrecongnized command. Try again." >> main

Now if I told it to put the source code at (5,24) the result would be.

main=do
    putStrLn "Welcome to the open source program, would you like my source code?"
    (ans:_) <- getLine
    case ans of
        'y' -> putStrLn ((\a b->a++(show a)++" "++(show b)++b) "main=do\n    putStrLn \"Welcome to the open source program, would you like my source code?\"\n    (ans:_) <- getLine\n    case ans of\n        'y' -> putStrLn ((\\a b->a++(show a)++\" \"++(show b)++b) " ")--Quine goes here\n        'n' -> putStrLn \"Okay, Good bye\"\n        _  -> putStrLn \"Unrecongnized command. Try again.\" >> main\n")--Quine goes here
        'n' -> putStrLn "Okay, Good bye"
        _  -> putStrLn "Unrecongnized command. Try again." >> main

Clarifications:

The program you make and the type of programs it act upon may be different if you like.
Your program may get the position in the program and its source code however it sees fit. You may put the new source code where ever you see fit.
Obviously, the new program can't simply grab its source code from its file
You may only insert things at the position the user specifies (so you may not be able to include any new modules in the new program depending on target language)

This is code golf, so shortest answer wins!
Let us see how many different languages we can make quine makers for as well.

J - 73 char

Takes input on stdin, as the 0-origin index in characters and the source, separated by a newline. Introduces a copy of the program at the specified point as a string.

((".@{.~({.,}.,~'(',')',~(LF;''',LF,''')rplc~quote@])(}.~>:))i.&LF)1!:1]3

Explained by explosion:

(                                  )1!:1]3  NB. stdin
 (                           )i.&LF         NB. find the first newline
     {.~                                    NB. the index part of input
  ".@                                       NB. convert index to integer
                      (}.~>:)               NB. the source program part
        ({.,}.,~     )                      NB. program before and after index
                ...@]                       NB. program quoted properly

For example, given input

3
abcdef'ghij'
kl mn 0p1

the output is

abc('abcdef''ghij''',LF,'kl mn 0p1')def'ghij'
kl mn 0p1

because J uses Pascal-style strings: 'Isn''t this great?'


Substitute a string with itself! Substitute a string with itself

Your goal is to substitute a string with itself by replacing each character in the original string with the one before it, starting with the first character and wrapping around. Here are some examples to show what I mean:

1st example:

Input: program
Output: apgopra

How:
Program -> mrogram (replace p by m in program)
-> mpogpam (replace r by p in mrogram)
-> mprgpam (replace o by r in mpogpam)
-> mpropam (replace g by o in mprgpam)
-> mpgopam (replace r by g in mpropam)
-> mpgoprm (replace a by r in mpgopam)
-> apgopra (replace m by a in mpgoprm)

2nd example:

Input: robot
Output: orbro

How:
Robot -> tobot (replace r by t in robot)
-> trbrt (replace o by r in tobot)
-> trort (replace b by o in trbrt)
-> trbrt (replace o by b in trort)
-> orbro (replace t by o in trbrt)

3rd example:

Input: x
Output: x

How:
x -> x (replace x by x in x)

4th example:

Input: xy
Output: xx

How:
xy -> yy (replace x by y in xy)
-> xx (replace y by x in yy)

Sidenotes:

The string x will only contain lowercase alphanumeric characters and spaces
This is code-golf so shortest code in bytes wins!

CJam, 11 bytes

q__1m>.{er}

Test it here.

Explanation

q__    e# Read input and make two copies.
1m>    e# Rotate the second copy one character to the right.
.{er}  e# For each pair of characters from the second and third string,
       e# replace occurrences of the first with the second.


Pushing items in the sequence Aim
If you are given a sequence such as (A, G, M, _, _, C, D, _, G) your aim is to push all non empty elements to one side to get (A, G, M, C, D, G, _, _, _). You must preserve the order of the non-empty elements.
Rules

You are free to choose the sequence type. (strings, numbers, containers etc). You must also choose a Nil/None/Null character or element that will fit your sequence type. eg; spaces or underscores inside a string.
User should be able to input the push direction (left or right) and the sequence. Input values and format are up to you to choose. eg; Your code handles sequences that are numbers with 7 as the null character. You set R for right, L for left. So user inputs R, 1577462722727777. The result is 7777777715462222
Rearranged sequence should be displayed or written to a file.
Your code should not exceed 128 bytes.

Points

+(10 / bytes) golfing points
+1 for Moses-Mode. Push half the elements to the left, and half to the right. If odd number of items are present, you may choose the direction of the final element. eg; (A, G, M, _, _, _, C, D, G)

You may use use this calculator to round your points to the hundredth decimal place.

R - 10 / 71 70 66 39 bytes = 0.26 points

Saved 27 bytes thanks to Mickey!

function(d,s)s[order(xor(!is.na(s),d))]

This creates an unnamed function which takes a direction d (logical with TRUE corresponding to right and FALSE to left (legit per OP's comment)) and a vector s (assumed to use NA for empty elements) as input and returns a vector. To call it, give it a name, e.g. f=function(d,s)....

This does not support "Moses Mode."

Ungolfed + explanation:

f <- function(d, s) {
    # Order the elements of s by non-missing exclusive or direction
    s[order(xor(!is.na(s), d))]
}

Examples:

> test <- c(1, 5, NA, NA, 4, 6, 2, NA, 2, 2, NA, 2, NA, NA, NA, NA)
> f(FALSE, test)
[1] NA NA NA NA NA NA NA NA  1  5  4  6  2  2  2  2
> f(TRUE, test)
[1]  1  5  4  6  2  2  2  2 NA NA NA NA NA NA NA NA

And an extra special example just for FryAmTheEggman:

> c(f(TRUE, test), "BATMAN")
[1] "1" "5" "4" "6" "2" "2" "2" "2" NA NA NA NA NA NA NA NA "BATMAN"


ASCII art "Hello-World!" Your goal is to write the shortest program that outputs "Hello-World!" as ASCII art.

Rules :

It must be human readable, I don't care about it's size (cols/rows)
Output must contain only spaces (" "), sharps ("#") and newlines
The output must work with a monospaced font (but the letters doesn't necessary use a monospaced font)
In the result, each character must be separated from each other by at least one space

Please add a title with the language and the number of bytes in your code.


Super Folding Numbers We have already defined a folding number here.

But now we are going to define a Super Folding Number.  A Super Folding number is a number that if folded enough times it will eventually reach one less than a power of two.  The method of folding is slightly different than in the folding number question.

The folding algorithm goes as follows:

Take the binary representation

e.g. 5882

1011011111010

Spilt it into three partitions.  First half, last half and middle digit (iff it has a odd number of digits)

101101 1 111010

If the middle digit is zero this number cannot be folded
Reverse the second half and superimposed on the first half

010111
101101

Add the digits in place

111212

Iff there are any 2s in the result the number cannot be folded otherwise the new number is the result of the folding algorithm.

A number is a Super Folding number if it can be folded to a continuous string of ones. (All Folding numbers are also Super Folding Numbers)

Your task is to write code that takes in a number and outputs a truthy value if the number is a Super Folding number and falsy otherwise.  You will be scored on the size of your program.

Examples

5200

Convert to binary:

1010001010000

Split in half:

101000 1 010000

The middle is one so we continue
Superimpose the halves:

000010
101000

Added them:

101010

No twos so we continue
Split in half:

101 010

Fold:

010
101

111

The result is 111 (7 in decimal) so this is a Super Folding Number.

Test Cases

The first 100 Super Folding Numbers are:

[1, 2, 3, 6, 7, 8, 10, 12, 15, 20, 22, 28, 31, 34, 38, 42, 48, 52, 56, 63, 74, 78, 90, 104, 108, 120, 127, 128, 130, 132, 142, 150, 160, 170, 178, 192, 204, 212, 232, 240, 255, 272, 274, 276, 286, 310, 336, 346, 370, 400, 412, 436, 472, 496, 511, 516, 518, 524, 542, 558, 580, 598, 614, 640, 642, 648, 666, 682, 704, 722, 738, 772, 796, 812, 852, 868, 896, 920, 936, 976, 992, 1023, 1060, 1062, 1068, 1086, 1134, 1188, 1206, 1254, 1312, 1314, 1320, 1338, 1386, 1440, 1458, 1506, 1572, 1596]

Here's my first ever shot at code golf:

Python 3, 167 bytes

167 bytes if tabs or single spaces are used for indentation

def f(n):
 B=bin(n)[2:];L=len(B);M=L//2
 if'1'*L==B:return 1
 S=str(int(B[:M])+int(B[:-M-1:-1]))
 return 0if(~L%2==0and'0'==B[M])or'2'in S else{S}=={'1'}or f(int(S,2))

Edit: Thanks to everyone's help below, the code above has been reduced from an original size of 232 bytes!


Let's divide a lattice Let's say we have a n × n lattice; we can then divide the lattice into two sections by drawing a line through the lattice.  Everything to one side of the line is in one set and everything else in another.

How many ways can we divide the lattice in the manner?

For example lets take a 2 × 2 lattice:

. .
. .

We can make 2 partitions dividing the lattice in half like so:

× ×    × o
o o    × o

We can also partition off each of the corners:

× o    o ×    o o    o o
o o    o o    × o    o ×

Lastly we can put all of the points in one partition by missing the lattice entirely:

× ×
× ×

This makes for a total of 7 partitions.  Note that the following partition is not valid because it cannot be made with a single straight line.

× o
o ×

Here is a 3 × 3 lattice

. . .
. . .
. . .

There are 4 purely horizontal or vertical partitions

× × ×    × × ×    × o o    × × o
× × ×    o o o    × o o    × × o
o o o    o o o    × o o    × × o

There are 4 corner partitions

× 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    o o o    o o ×    × o o

There are 4 larger corner partitions

× × o    o × ×    o o o    o o o
× o o    o o ×    o o ×    × o o
o o o    o o o    o × ×    × × o

There are 8 partitions of partial corners

× × 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 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 × ×    × × o    × o o    o o o

There are 8 knights move partitions

× × 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 o    × o o
× o o    o o ×    o o o    × × ×    o × ×    × × o    × × ×    o o o

And there is one whole partition

× × ×
× × ×
× × ×

That makes for 29 partitions in total.

Task

Given a number n as input, output the number of partitions that can be made in this fashion of an n × n lattice.

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

Test Cases

Here are the first 34 courtesy of the OEIS:

1, 7, 29, 87, 201, 419, 749, 1283, 2041, 3107, 4493, 6395, 8745, 11823, 15557, 20075, 25457, 32087, 39725, 48935, 59457, 71555, 85253, 101251, 119041, 139351, 161933, 187255, 215137, 246691, 280917, 319347, 361329, 407303

OEIS A114043


Deal the cards to the players Tonight is card game night! You are the dealer and your task is to write a program to deal the cards to the players.
Given an array of cards and the number of players, you need to split the array of cards into a hand for each player.

Rules
Your program will receive an non-empty array A , as well as a non-zero positive integer n. The array should then be split into n hands. If the length of the string isn't divisible by n any leftover cards at the end should be distributed as evenly as possible.

If n==1, you will need to return an array of array with A as it's only element

If n is greater than the length of A, you will need to return every hand and an empty hand. if n = 4 and array A = [1,2,3], you should return [[1],[2],[3]] or  [[1],[2],[3],[]]. You are free to handle the empty hand with empty, undefined or null.

The array can contain any type rather than a number.

You should not change the order of the array while dealing. For example if n = 2 and A= [1,2,3], any result rather than [[1,3],[2]] will be invalid.

Test Cases
n   A               Output

1   [1,2,3,4,5,6]   [[1,2,3,4,5,6]]
2   [1,2,3,4,5,6]   [[1,3,5],[2,4,6]]
3   [1,2,3,4,5,6]   [[1,4],[2,5],[3,6]]
4   [1,2,3,4,5,6]   [[1,5],[2,6],[3],[4]]
7   [1,2,3,4,5,6]   [[1],[2],[3],[4],[5],[6]] // or [[1],[2],[3],[4],[5],[6],[]]

Demo Program

def deal(cards, n):
	i = 0
	players = [[] for _ in range(n)]
	for card in cards:
		players[i % n].append(card)
		i += 1
	return players

hands = deal([1,2,3,4,5,6], 2)

print(hands)

Try it online!
This is code-golf, so you the shortest bytes of each language will be the winner.
Inspired from Create chunks from array by chau giang

05AB1E, 3 1 byte

Saved 2 bytes thanks to Adnan

ι

Try it online!
or as a Test Suite

Explanation

ι  # uninterleave

Does exactly what the challenge asks for


Render a version of the BBC Micro owl logo Can you render out a version of the BBC Micro Owl logo as per above from code?

Rules:

You can use any programming language you like.
Output can be text or graphic.
Circles don't have to overlap.

Winner:

The answer with the most upvotes wins.

Kudos for anyone that attempts this in BBC basic.

You can read about the BBC Micro here


Find all reachable nodes in a graph You are given a directed graph in an adjacency dictionary format. This can be whatever format is most natural for your language. For instance, in python, this would be a dictionary with  keys of nodes and values which are lists of nodes which that node has an edge to. For instance:

G={1: [2, 3], 2: [3], 3: [1], 4:[2]}

Be reasonable. A dictionary of frozen sets is not allowed, even if it makes your code shorter. A list of lists is fine, if your language doesn't have dictionaries.

Your task is to implement a function that takes a directed graph and a starting node, and outputs all nodes reachable from the starting node. The output format is also flexible. A return value from a function is fine, so is print, etc.

Test case:

G={1: [2, 3], 2: [3], 3: [1], 4:[2]}
s=1

R(G,s)
{1,2,3}

Fewest characters wins. I will clarify if needed.

Mathematica 63 40 37
My earlier submission was incorrect. I had misinterpreted what ConnectedComponents returns.  The present approach relies on Belisarius' suggestion to useVertexOutComponent. 3 additional chars saved by alephalpha.
The following generates an 11 by 11 adjacency matrix of 0's and 1's, where 1 indicates that the vertex with the row number is connected directly to the vertex corresponding to column number of the cell. (SeedRandom ensures that your matrix a will match mine.)
SeedRandom[21]
a = Array[RandomChoice[{0.9, 0.1} -> {0, 1}] &, {11, 11}];

Example
(37 chars)
 AdjacencyGraph@a~VertexOutComponent~4

{4, 1, 7, 8, 9, 3}

Verifying
The directed graph displays how to reach vertices {1, 7, 8, 9, 3} from vertex 4.
AdjacencyGraph[a, ImagePadding -> 30, VertexLabels -> "Name"]


Count characters in lo..ol and print a phrase Assuming 'lol' with a variavle number of 'o's. Print a the following phrase:

What does 1st, 2nd, 3rd, 4th ... 'o' stand for?

Examples:

lol    -> What does 1st 'o' stand for?
loooool -> What does 1st, 2nd, 3rd, 4th, 5th 'o' stand for?

So far I managed to write a 128 characters solution in Perl:

$l=(<>=~tr/o//);print"What does ";print$_,$_==1?'st':$_==2?'nd':$_==3?'rd':'th',$_<$l?', ':''for(1..$l);print " 'o' stand for?";

and a 123 characters solution in Haskell:

p 1="1st";p 2="2nd";p 3="3rd";p n=show n++"th";main=putStr$"What does "++(foldr(++)"'o' stand for?"[p i++", "|i<-[1..23]]);

How short can you write it?

GolfScript, 82 characters
"What does "\,2-,{)..10/10%1=!\10%`"123"\?)*"thstndrd"2/=+}%", "*" 'o' stand for?"

Works even for >100 'o's, test it online.


C# First 1 (right to left) in binary number I am trying to use C# to find the index of the first 1 (right to left) in the binary representation of a number. For example, since 100 in binary is:

0b1100100

The first 1 is in the third position from the right, so it should yield 3.

234 should yield 2, 0 should yield 0, etc.

Here is my current solution:

k < 1 ? 0 :(int)Math.Log(k & -k, 2) + 1;

Any ways I can make this shorter?

If only C# supported machine-specific intrinsics… There is a single instruction that can do this in x86 assembly language, and on most other processor architectures as well. Then you'd have not only the shortest code, but very likely the fastest.

In fact, making this code shorter is an extremely boring problem compared to making this code fast. There are all sorts of really neat, efficient, bit-twiddling solutions, and you could also consider using a look-up table.

None of that matters for golfing, though. It looks to me like your current solution is the best you can do. Of course, you can remove the superfluous whitespace:

k<1?0:(int)Math.Log(k&-k,2)+1

I would personally write it as:

k>0?(int)Math.Log(k&-k,2)+1:0

because I think it's slightly clearer to have the direction of the conditional test that way, as well as to compare it against zero, but I guess it's six one way, half a dozen the other.

C# doesn't support implicit conversion from int to bool like C and C++ do, so you can't really shorten the conditional test any further.

You are also stuck with the explicit cast from double (as returned my Math.Log) to int, as C# won't allow this to happen implicitly. Of course, that's normally a good thing because it would point out that you have a big performance problem here: promoting an int to a double, computing the log of a double, and then converting the double result back to an int will be massively slow, so it's normally something that you'd want to avoid. But these are the kinds of perversions you have to put up with when playing code golf.

I had initially come up with

k > 0
      ? ((k & -k) >> 1) + 1
      : 0

(ungolfed for clarity, of course), which avoids taking the logarithm and is therefore an improvement in code size and speed. Unfortunately, this doesn't always get the right answer, and I assume that's an inflexible requirement. :-) Specifically, it fails if the input value (k) is a factor of 8. This is fixable, but not without making the code longer than the Math.Log version.


We'll be counting stars Your objective is to take multiline ASCII like

|  v  |
* * * *
 * * *

and have an array that includes everything that isn't a star changed to a star (except for [any-width] spaces) and the number of stars it included and the number of stars it now includes.  So the output of my example would be:

['*  *  *
* * * *
 * * *',7,10]

or

["*  *  *\n* * * *\n * * *", 7, 10]

depending on what your code language does.

This is a code-golf challenge, so the shortest bytes wins!

GolfScript, 30 characters
.{.'
 '?)\42if}%.{@'*'/,(}2*]`

Takes the input from stdin. Example (test online):
> |  v  |
> * * * *
>  * * *

["*  *  *\n* * * *\n * * *\n" 7 10]


Perfect Squares Without Borders Given n=m^2, return a list of integers that do not border the m x m grid of integers from 1 to n.

Examples

n=1 (m=1)

Grid:

[1]

Return:

[]

n=4 (m=2)

Grid:

[1,2]
[3,4]

Return:

[]

n=9 (m=3)

Grid:

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

Return:

[5]

n=16 (m=4)

Grid:

[ 1, 2, 3, 4]
[ 5, 6, 7, 8]
[ 9,10,11,12]
[13,14,15,16]

Return:

[6,7,10,11]

For higher values of m, this answer does a great visualization.

Rules:

You may take in either m or n (where n = m*m).

If taking in n you are allowed to have undefined behavior where there exists no m for n (E.G. 15).
n > 0, m > 0: Both must be integer values.

The output may be as a 1D/2D array, matrix or whitespace delimited
The output must be in order from least to greatest.

If outputting as a matrix this means it must be as it would be in the grid.

This is code-golf, lowest byte-count wins.

C, 50 bytes

i;f(m){for(i=m;++i<m*m-m;)i%m>1&&printf("%d ",i);}

Try it online!


Smallest Fibonacci Multiples Sandbox

Background (not necessary for the challenge)

A standard number theory result using the pigeonhole principle is the fact that given any natural number k, there is a Fibonacci number that is a multiple of k.

We can see this by considering modular pairs (F(n-1) % k, F(n) % k), and noting that there are only a finite number of possibilities of the pairs, while there are infinitely many pairs, so by the pigeonhole principle, there are naturals n, m such that (F(m-1) % k, F(m) % k) = (F(n-1) % k, F(n) % k). But, this implies that F(m-2) % k = F(n-2) % k, and more generally, F(m-i) % k = F(n-i) % k. Notably, if m < n, F(0) % k = F(n-m) % k. But, F(0)=0, so this means that F(n-m) is a multiple of k.

Challenge

You must provide a program that takes in a natural k as an input and return m, the smallest Fibonacci number that is a multiple of k. This program must be irreducible in the sense that one can't remove any bytes and maintain the same functionality.

This challenge is a code-challenge, as your score will be the smallest Fibonacci multiple of (the number of bytes in your program + 1).

To find your program's score, use this TIO link: Try it online!

The lowest score for a valid response in each language wins!

Test Cases

1: 1
2: 2
3: 3
4: 8
5: 5
6: 144
7: 21
8: 8
9: 144
10: 610
11: 55
12: 144
13: 13
14: 46368
15: 6765
16: 144
17: 34
18: 144
19: 2584
20: 832040
21: 21
22: 832040
23: 46368
24: 144
25: 75025
26: 10946
27: 14930352
28: 46368
29: 377
30: 1548008755920
31: 832040
32: 46368
33: 6765
34: 34
35: 102334155
36: 144
37: 4181
38: 2584
39: 317811
40: 832040
41: 6765
42: 46368
43: 701408733
44: 832040
45: 1548008755920
46: 46368
47: 987
48: 144
49: 225851433717
50: 2111485077978050
51: 14930352
52: 267914296
53: 196418
54: 14930352
55: 55
56: 46368
57: 14930352
58: 267914296
59: 591286729879
60: 1548008755920
61: 610
62: 832040
63: 46368
64: 4807526976
65: 9227465
66: 1548008755920
67: 72723460248141
68: 2584
69: 46368
70: 5358359254990966640871840
71: 190392490709135
72: 144
73: 24157817
74: 365435296162
75: 354224848179261915075
76: 2584
77: 102334155
78: 160500643816367088
79: 8944394323791464
80: 1548008755920
81: 16641027750620563662096
82: 1548008755920
83: 160500643816367088
84: 46368
85: 1134903170
86: 1725375039079340637797070384
87: 317811
88: 832040
89: 89
90: 1548008755920
91: 225851433717
92: 46368
93: 1548008755920
94: 4807526976
95: 2880067194370816120
96: 46368
97: 7778742049
98: 57602132235424755886206198685365216
99: 1548008755920

You can use the TIO link above to generate more test cases if needed.

EDIT: As there seems to be some confusion on the scoring, here is how to generate your score:

Take the number of bytes in your function, add 1, and take the result of this addition, and find the smallest Fibonacci multiple of this result.

JavaScript (Node.js), 33 bytes, score: 34

Expects a BigInt as input.

f=(n,x=0n,y=1n)=>y%n?f(n,y,x+y):y

Try it online!


Which number is bigger? Define f(a,b) := a if b=1; a^f(a,b-1) if b>1 (Tetration, where ^ means power) for positive integers a and b, given four positive integers a,b,c,d, compare f(a,b) and f(c,d).

Your program should output three constant values to mean "greater", "less" and "equal".

Samples:

a b c d f(a,b) output f(c,d)
3 2 2 3 27     >      16
4 2 2 4 256    <      65536
4 1 2 2 4      =      4

Lowest time complexity to max{a,b,c,d} win, with tie-breaker code length(the shorter the better) and then answer time(the earlier the better).

Complexity assumption

Your code should handle a,b,c,d up to 100, and your algorithm should handle all legal input
You can assume integer calculations (that your language directly support) in O((a+b+c+d)^k) cost O(1) time if can be done in O(1) for 2k bit numbers if k bit computing can be done in O(1)
For example, both plus(+) and multiply(*) can be done in O(1) for 2k bit numbers if k bit computing for both can be done in O(1), so both satisy the requirement. It's fine if multiply can't be done without plus, or even if both can't be done without each other.
Float calculations in O(log(a+b+c+d)) bit precision in ±2^O((a+b+c+d)^k), takes O(1), with same requirements like integer calculations.

Java (JDK 10), 295 bytes

int f(Long a,long b,long c,long d){return a>c?-f(c,d,a,b):a<c?b>d?d==1?(a==2&((b==2&c==4)|(b==3&c==16)))|(a==3&b==2&c==27)?0:1:b-d>1?1:f(t(a,b),1,c,d):-1:a<2?0:a.signum(b-d);}long t(long a,long b){long t=1;for(;b-->0;)t=p(a,t);return t;}long p(long a,long b){long p=1;for(;b-->0;)p*=a;return p;}

Try it online!

Codes:

1 if a^^b > c^^d
-1 if a^^b < c^^d
0 is a^^b == c^^d


Algorithm to print the Minimum number of adjacent character swaps necessary to remove all instances of "VK" in a given string? For example, how many adjacent swaps are at least needed to convert some string such as BVVKCV to one without any instances of VK?

Input-length of the string will be within the range 1 <= length <= 200.
VK will be hardcoded across all test cases.

Input string examples:

Input:  VKVKVVVKVOVKVQKKKVVK
Output: 8

Input:  VVKEVKK
Output: 3

Input:  JUSTIN
Output: 0

Japt, 44 bytes

m£Z¯Y cZtY2 Ô cZsY+2Ãrc
®¬ø"VK"
W+VÌ
Ve ?ß:W

Try it online!

It times out on the first test case because it's super inefficient (something like O(n^n)?) but it should be a viable algorithm. Input is weird; it is a singleton list containing the input, but the input itself is formatted as a list of upper-case characters. I think that would typically be valid, but if not let me know.

Explanation:

#Step 1: try all the swaps
m                          #For each string Z reachable with n swaps (n starts at 0)
 £                  Ã      # For each letter Y in Z:
  Z¯Y                      #  Get the letters before it in Z
      c                    #  Concat
       ZtY2 Ô              #  Y swapped with the following character
              c            #  Concat
               ZsY+2       #  The rest of Z
                     rc    #Flatten by one level
                           #Result: A list of all strings reachable with n+1 swaps

#Step 2: Check for "VK"
®¬         #For each string from Step 1:
  ø"VK"    # Check whether it contains "VK"
           #Result: A list where 1 indicates there was "VK" and 0 otherwise

#Step 3: Increment the counter appropriately
W+      #Increase the counter by
  VÌ    #The value for the original string when run through step 2
        #Result: 0 if 0 swaps were required, the current number of swaps otherwise

#Step 4: Iterate or end
Ve ?       #If all the reachable strings contain "VK"
    ß      # Repeat the program with the current values
     :W    #Otherwise return the counter
           #Result: Outputs the counter when a non-"VK" string is found.


Basic Calculator with GUI I recently had to add a small basic calculator to a project. I wrote a quick dirty one, but it seemed small enough to check with you people out here ;)

Just out of curiosity & an appetite to get surprised for some real hacky solutions, try and beat this one :

CODE (JS/JQUERY):

function scalcy() {
    var b="", p=parseFloat,t,i;
    return $("<div>").append("789/456*123-.0=+".split("").map(function(i){
        return $("<button/>").text(i).width(32).height(32).click(function(){
        b = (!p(i=$(this).text())? b.replace(/\D+$/,""): b) + i;
        t.val(((!(i.match(/[.\d]/))? (b=eval(b.slice(0,-1))+i+"").slice(0,-1):
                p(b.match(/[.\d]+/g).pop()) || 0) + "").slice(0,8));
    })})).prepend(t=$("<input/>").width(123).click(function(){
        this.value=b="0";})).width(130);
}

Screenshot (in chrome): (DEMO)

Considerations: Better the UI & lesser the bugs, the better.

Minimum Functionalities:

Supports floating point arithmetic (/*-+),
Reset feature,
Continuous Operation (like working on with the last result)

Note:

Use any language & library, but please not a library call like new
calculator().
Forking the above code itself is most welcome.

Additional Notes:

A graphical UI is obviously considered better than not having any at all.
I'd suggest to have a look at this challenge (for inspiration): Create a GUI Piano.

Tcl/Tk, 100

pack [entry .e -textv e] -f both -e 1
bind . <Return> {catch {expr $e} e}
bind . <Escape> {set e {}}

Buttons are not required, so leave them alone.
The GUI is great. So simple that you can finally focus on the task that you try to do.


Add Numbers deux — Bitwise Addition Your job is to implement bitwise addition.

To ensure that this is done, you will compute and print the result of addition without carry (or bitwise XOR). Then, you will compute the carry of the addition (bitwise AND) and multiply it by two (bitwise left shift). If the carry is nonzero, then you add the carry and the previous result until the carry is zero, at which point you stop producing output. If all is done correctly, the final result printed should be the sum of the two integers that you received as input.

Here's an ungolfed reference implementation in C:

#include <stdio.h>

void print_add(unsigned a, unsigned b)
{
    unsigned carry;

    while(b)
    {
        carry = a & b;
        a ^= b;
        printf("%u\n", a);
        b = carry << 1;
    }
}

Input

Two positive integers in any convenient format.

Output

A list of positive integers in any convenient format representing each result of addition without carry. Leading/trailing whitespace/newlines are allowed.

Rules

This is code-golf. The answer with the least bytes in each language wins, which means that I will not accept an answer.
Standard loopholes are forbidden. This includes, but is not limited to, Abusing native number types to trivialize a problem.

Testcases

1, 1 -> 0, 2
3, 17 -> 18, 16, 20
6, 7 -> 1, 13
21, 19 -> 6, 36, 32, 40
10, 9 -> 3, 19
20, 20 -> 0, 40

Your code must work for at least all pairs of positive integers that your integer type can represent the sum of.

JavaScript (ES6), 34 bytes
Takes input as (A)(B), where A+B is a positive-looking 32-bit integer, i.e. less than 0x80000000.
Returns an array.

A=>g=B=>B?[A^=B,...g((B&~A)*2)]:[]

Try it online!
Or for 35 bytes, a BigInt version with unlimited input:

A=>g=B=>B?[A^=B,...g((B&~A)*2n)]:[]

Try it online!
How?
In order to use only 2 variables and pass a single variable to the recursive function, we apply the XOR right away to A and prepend the result to the output array.
Instead of computing (A AND B) * 2, we now need to compute (B AND (A XOR B)) * 2. Fortunately this can also be expressed as:
(B AND (NOT A)) * 2

leading to the rather short (B&~A)*2 in JS syntax.


Play a valid chess move, given a board on stdin The program plays white.

Example stdin:

8 ║♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜
7 ║♟ ♟ ♟ ♟ … ♟ ♟ ♟
6 ║… … … … … … … …
5 ║… … … … ♟ … … …
4 ║… … … … … … … …
3 ║… … ♘ … … … … …
2 ║♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙
1 ║♖ … ♗ ♕ ♔ ♗ ♘ ♖
——╚═══════════════
—— a b c d e f g h

Example stdout:

8 ║♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜
7 ║♟ ♟ ♟ ♟ … ♟ ♟ ♟
6 ║… … … … … … … …
5 ║… … … … ♟ … … …
4 ║… … … … ♙ … … …
3 ║… … ♘ … … … … …
2 ║♙ ♙ ♙ ♙ … ♙ ♙ ♙
1 ║♖ … ♗ ♕ ♔ ♗ ♘ ♖
——╚═══════════════
—— a b c d e f g h

Any valid move is ok. "En passant" and castling are ignored. It is ok to show error messages or print nothing if there is no valid move.

The answer with the most votes wins.

I'm not complaining about upvotes, but to be fair... my solution here isn't actually all that great. Ugoren's is better, apart from lacking unicode support. Be sure to look at all the answers before voting, if you've come across this question only now!Anyway.
Haskell, 1074 bytes (without castling)

χ=w⋈b;w="♙♢♤♔♕♖♗♘";b="♟♦♠♚♛♜♝♞"
μ=t⤀ζ++((\(x,y)->(x,-y))⤀)⤀μ;q c|((_,m):_)<-((==c).fst)☂(χ⋎μ)=m
t(x:y:l)=(d x,d y):t l;t _=[];d c=fromEnum c-78
ζ=["NM","NL","MMOM","MMMNMONMNOOMONOO",σ⋈δ,σ,δ,"MLOLPMPOOPMPLOLM"]
σ=l>>=(\c->'N':c:c:"N");δ=[l⋎l,reverse l⋎l]>>=(>>=(\(l,r)->[l,r]))
l="GHIJKLMOPQRSTU"
α c|c∊"♢♤"='♙'|c∊"♦♠"='♟'|c∊χ=c;π('♙':_)=6;π _=1
(⋎)=zip;(⤀)=map;(∊)=elem;(✄)=splitAt;(☂)=filter;(⋈)=(++)
φ r@(x,y)p a
 |x>7=φ(0,y+1)p a
 |y>7=[]
 |c<-a✠r=(c⌥r)p a y⋈φ(x+1,y)p a
(c⌥r)p a y
 |c==p!!0=(a☈r)c χ++const(y==π p)☂(a☈r)(p!!1)χ++(a☈r)(p!!2)('…':w)
 |c∊p=(a☈r)c χ
 |True=[]
a✠(x,y)=a!!y!!(x*2);o(x,y)=x>=0&&x<8&&y>=0&&y<8
(n➴a)(x,y)|(u,m:d)<-y✄a,(l,_:r)<-(x*2)✄m=u⋈(l⋈(n:r):d)
(a☈r@(x,y))c b=(α c➴('…'➴a)r)⤀((\r->o r&&not((a✠r)∊b))☂((\(ξ,υ)->(x+ξ,y+υ))⤀q c))
main=interact$unlines.uncurry((⋈).zipWith((⋈).(:" ║"))['8','7'..]
 .head.((all(any('♔'∊)).φ(0,0)b)☂).φ(0,0)w.(drop 3⤀)).(8✄).lines

Try it online!

When you have GHC installed (for instance as part of the Haskell platform) you can do just
$ runhaskell def0.hs < examplechessboard.txt
8 ║♜ ♞ ♝ ♛ ♚ ♝ ♞ ♜
7 ║♟ ♟ ♟ ♟ … ♟ ♟ ♟
6 ║… … … … … … … …
5 ║… ♘ … … ♟ … … …
4 ║… … … … … … … …
3 ║… … … … … … … …
2 ║♙ ♙ ♙ ♙ ♙ ♙ ♙ ♙
1 ║♖ … ♗ ♕ ♔ ♗ ♘ ♖
——╚═══════════════
—— a b c d e f g h


Counting orthogonal circulant matrices Two rows of a matrix are orthogonal if their inner product equals zero. Call a matrix with all rows pairwise orthogonal an orthogonal matrix. A circulant matrix is one where each row vector is rotated one element to the right relative to the preceding row vector. We will only be interested in matrices where the entries are either -1 or 1.

Task

Write code to count as many different n/2 by n orthogonal, circulant matrices as possible in 2 minutes (for even n).

Input

The code has no input. It can try any even values of n it likes. For example, the code could try all n that are multiplies of 4 starting from the smallest and also try n = 2.

Output

The number of orthogonal circulant matrices you have found. There should also be a simple switch in your code to enable it to output the matrices themselves.

Score

The number of circulant matrices you have found.

Hints

Orthogonal n/2 by n circulant matrices only exist when n is a multiple of 4 or n is less than 4.

An example orthogonal circulant matrix is:

-1  1 -1 -1
-1 -1  1 -1

Tips for a naive approach

The most naive approach is just to iterate over all possible matrices. This can be sped up using the following two observations.

To test orthogonality of a circulant matrix we need only compare each row to the first one.  This is implemented in the sample code.
We can iterate over Lyndon words and then if we find an orthogonal matrix multiply by the number of possible rotations. This is idea as yet untested so may be buggy.

Sample code

This is a very simple and naive python answer. I ran it using timeout 120.

import itertools
def check_orthogonal(row):
    for i in xrange(1,int(n/2)):
        if (sum(row[j]*row[(j+i) % n] for j in xrange(n)) != 0):
            return False
    return True

counter = 0
for n in xrange(4,33,4):
    for row in itertools.product([-1,1],repeat = n):
        if check_orthogonal(row):
            counter +=1
            print "Counter is ", counter, ". n = ", n

Correctness tests

For n = 4,8,12,16,20,24,28, the number of distinct matrices you should get is 12,40,144,128,80,192,560, respectively.

Levels of awesomeness

Judging by the sample code, I hereby present two levels of awesomeness that any answer can aspire to achieve.

Silver level awesomeness is achieved by getting a score or 1156.
Gold level of awesomeness is to get higher than that.

Languages and libraries

You can use any language or library you like (that wasn't designed for this challenge). However, for the purposes of scoring I will run your code on my machine so please provide clear instructions for how to run it on Ubuntu.

My Machine The timings will be run on my machine. This is a standard Ubuntu install on an 8GB AMD FX-8350 Eight-Core Processor.  This also means I need to be able to run your code.

Leading answers

332 by flawr in Octave
404 by R.T. in Python
744 by Sample Solution using pypy
1156 by Thomas Kwa using Java. Silver level awesomeness!
1588 by Reimer Behrends in OCaml. Gold level awesomeness!

OCaml, 1588 (n = 36)

This solution uses the usual bit pattern approach to represent vectors of -1s and 1s. The scalar product is as usual calculated by taking the xor of two bit vectors and subtracting n/2. Vectors are orthogonal iff their xor has exactly n/2 bits set.

Lyndon words are not per se useful as a normalized representation for this, as they exclude any pattern that is a rotation of itself. They are also relatively expensive to compute. Therefore, this code uses a somewhat simpler normal form, which requires that the longest consecutive sequence of zeroes after rotation (or one of them, if there are multiples) must occupy the most significant bits. It follows that the least significant bit is always 1.

Observe also that any candidate vector must have at least n/4 ones (and at most 3n/4). We therefore only consider vectors with n/4 ... n/2 bits set, since we can derive others via complement and rotation (in practice, all such vectors seem to have between n/2-2 and n/2+2 ones, but that seems to also be difficult to prove).

We build these normal forms from the least significant bit up, observing the constraint that any remaining runs of zeroes (called "gaps" in the code) must follow our normal form requirement. In particular, as long as at least one more 1-bit has to be placed, there must be room for the current gap and another than that is at least as big as the current gap or any other gap observed so far.

We also observe that the list of results is small. Therefore, we do not try to avoid duplicates during the discovery process, but simply record the results in per-worker sets and calculate the union of these sets at the end.

It is worth noting that the runtime cost of the algorithm still grows exponentially and at a rate that is comparable to that of the brute-force version; what this buys us is essentially a reduction by a constant factor, and comes at the cost of an algorithm that is more difficult to parallelize than the brute-force version.

Output for n up to 40:

 4: 12
 8: 40
12: 144
16: 128
20: 80
24: 192
28: 560
32: 0
36: 432
40: 640

The program is written in OCaml, to be compiled with:

ocamlopt -inline 100 -nodynlink -o orthcirc unix.cmxa bigarray.cmxa orthcirc.ml

Run ./orthcirc -help to see what options the program supports.

On architectures that support it, -fno-PIC may offer some small additional performance gain.

This is written for OCaml 4.02.3, but may also work with older versions (as long as they aren't too old).

UPDATE: This new version offers better parallelization. Note that it uses p * (n/4 + 1) worker threads per instance of the problem, and some of them will still run considerably shorter than others. The value of p must be a power of 2. The speedup on 4-8 cores is minimal (perhaps around 10%), but it scales better to a large number of cores for large n.

let max_n = ref 40
let min_n = ref 4
let seq_mode = ref false
let show_res = ref false
let fanout = ref 8

let bitcount16 n =
  let b2 n = match n land 3 with 0 -> 0 | 1 | 2 -> 1 | _ -> 2 in
  let b4 n = (b2 n) + (b2 (n lsr 2)) in
  let b8 n = (b4 n) + (b4 (n lsr 4)) in
  (b8 n) + (b8 (n lsr 8))

let bitcount_data =
  let open Bigarray in
  let tmp = Array1.create int8_signed c_layout 65536 in
    for i = 0 to 65535 do
      Array1.set tmp i (bitcount16 i)
    done;
    tmp

let bitcount n =
  let open Bigarray in
  let bc n = Array1.unsafe_get bitcount_data (n land 65535) in
  (bc n) + (bc (n lsr 16)) + (bc (n lsr 32)) + (bc (n lsr 48))

module IntSet = Set.Make (struct
  type t = int
  let compare = Pervasives.compare
end)

let worker_results = ref IntSet.empty

let test_row vec row mask n =
  bitcount ((vec lxor (vec lsr row) lxor (vec lsl (n-row))) land mask) * 2 = n

let record vec len n =
  let m = (1 lsl n) - 1 in
  let rec test_orth_circ ?(row=2) vec m n =
    if 2 * row >= n then true
    else if not (test_row vec row m n) then false
    else test_orth_circ ~row:(row+1) vec m n
  in if test_row vec 1 m n &&
        test_orth_circ vec m n then
  begin
    for i = 0 to n - 1 do
      let v = ((vec lsr i) lor (vec lsl (n - i))) land m in
      worker_results := IntSet.add v !worker_results;
      worker_results := IntSet.add (v lxor m) !worker_results
    done
  end

let show vec n =
  for i = 0 to n / 2 - 1 do
    let vec' = (vec lsr i) lor (vec lsl (n - i)) in
    for j = 0 to n-1 do
      match (vec' lsr (n-j)) land 1 with
      | 0 -> Printf.printf "  1"
      | _ -> Printf.printf " -1"
    done; Printf.printf "\n"
  done; Printf.printf "\n"; flush stdout

let rec build_normalized ~prefix ~plen ~gap ~maxgap ~maxlen ~bits ~fn =
  if bits = 0 then
    fn prefix plen maxlen
  else begin
    let room = maxlen - gap - plen - bits in
    if room >= gap && room >= maxgap then begin
      build_normalized
        ~prefix:(prefix lor (1 lsl (plen + gap)))
        ~plen:(plen + gap + 1)
        ~gap:0
        ~maxgap:(if gap > maxgap then gap else maxgap)
        ~maxlen
        ~bits:(bits - 1)
        ~fn;
      if room > gap + 1 && room > maxgap then
        build_normalized ~prefix ~plen ~gap:(gap + 1) ~maxgap ~maxlen ~bits ~fn
    end
  end

let rec log2 = function
| 0 -> -1
| n -> 1 + (log2 (n lsr 1))

let rec test_gap n pat =
  if n land pat = 0 then true
  else if pat land 1 = 0 then test_gap n (pat lsr 1)
  else false

let rec test_gaps n maxlen len =
  let fill k = (1 lsl k) -1 in
  if len = 0 then []
  else if test_gap n ((fill maxlen) lxor (fill (maxlen-len))) then
    len :: (test_gaps n maxlen (len-1))
  else test_gaps n maxlen (len-1)

let rec longest_gap n len =
  List.fold_left max 0 (test_gaps n len len)

let start_search low lowbits maxlen bits fn =
  let bits = bits - (bitcount low) in
  let plen = log2 low + 1 in
  let gap = lowbits - plen in
  let maxgap = longest_gap low lowbits in
  worker_results := IntSet.empty;
  if bits >= 0 then
    build_normalized ~prefix:low ~plen ~gap ~maxgap ~maxlen ~bits ~fn;
  !worker_results

let spawn f x =
  let open Unix in
  let safe_fork () = try fork() with _ -> -1 in
  let input, output = pipe () in
  let pid = if !seq_mode then -1 else safe_fork() in
  match pid with
  | -1 -> (* seq_mode selected or fork() failed *)
     close input; close output; (fun () -> f x)
  | 0 -> (* child process *)
    close input;
    let to_parent = out_channel_of_descr output in
    Marshal.to_channel to_parent (f x) [];
    close_out to_parent; exit 0
  | pid -> (* parent process *)
    close output;
    let from_child = in_channel_of_descr input in
    (fun () ->
      ignore (waitpid [] pid);
      let result = Marshal.from_channel from_child in
      close_in from_child; result)

let worker1 (n, k) =
  start_search 1 1 n k record

let worker2 (n, k, p) =
  start_search (p * 2 + 1) (log2 !fanout + 1) n k record

let spawn_workers n =
  let queue = Queue.create () in
  if n = 4 || n = 8 then begin
    for i = n / 4 to n / 2 do
      Queue.add (spawn worker1 (n, i)) queue
    done
  end else begin
    for i = n / 2 downto n / 4 do
      for p = 0 to !fanout - 1 do
        Queue.add (spawn worker2 (n, i, p)) queue
      done
    done
  end;
  Queue.fold (fun acc w -> IntSet.union acc (w())) IntSet.empty queue

let main () =
  if !max_n > 60 then begin
    print_endline "error: cannot handle n > 60";
    exit 1
  end;
  min_n := max !min_n 4;
  if bitcount !fanout <> 1 then begin
    print_endline "error: number of threads must be a power of 2";
    exit 1;
  end;
  for n = !min_n to !max_n do
    if n mod 4 = 0 then
    let result = spawn_workers n in
    Printf.printf "%2d: %d\n" n (IntSet.cardinal result);
    if !show_res then
      IntSet.iter (fun v -> show v n) result;
    flush stdout
  done

let () =
  let args =[("-m", Arg.Set_int min_n, "min size of the n by n/2 matrix");
             ("-n", Arg.Set_int max_n, "max size of the n by n/2 matrix");
             ("-p", Arg.Set_int fanout, "parallel fanout");
             ("-seq", Arg.Set seq_mode, "run in single-threaded mode");
             ("-show", Arg.Set show_res, "display list of results") ] in
  let usage = ("Usage: " ^
               (Filename.basename Sys.argv.(0)) ^
               " [-n size] [-seq] [-show]") in
  let error _ = Arg.usage args usage; exit 1 in
  Arg.parse args error usage;
  main ()


Largest Distinctly Sum-Free Partition related and inspired by -- Finding sum-free partitions

A set A is defined here as being distinctly sum-free if

1) it consists of at least three elements, |A| ≥ 3, and
2) its distinct self-sum A + A = { x + y | x, y in A} (with x,y distinct, i.e., x≠y) has no elements in common with A.

(Obsolete - do not use this going forward. Left here only because some answers may have used it. It does not match with the above conditions. Alternatively, the equation x + y = z has no solution for x,y,z ∈ A (again with x,y,z distinct, i.e., x≠y, x≠z, y≠z).)

For a simple example, {1,3,5} is distinctly sum-free, but {1,3,4} is not. {1,3} and {3} are also not, since they're not at least three elements.

The challenge here is to find the largest distinctly sum-free subset of the given input.

Input

An unordered set A of integers in any convenient format.
The integers could be positive, negative, or zero, but can be assumed to fit in your language's native [int] datatype (or equivalent).
The set is guaranteed to have only distinct elements (no multisets here).
The set is not necessarily sorted.

Output

The largest subset of A (which could be A itself), that is distinctly sum-free. Output can be in any suitable format.
If no such subset exists, output an empty set or other falsey value.
If multiple subsets are tied for largest, output any or all of them.
The subset does not necessarily need be sorted, or in the same order as the input. For example, for input {1,3,5} output {5,1,3} is acceptable.

Additional Rules

Standard loopholes are forbidden.
This is code-golf, so all usual golfing rules apply, and the shortest code wins.

Examples

Input     -> Output (any or all)
{0}       -> {}
{1, 2, 3} -> {}
{1, 3, 5} -> {1, 3, 5}
{1, 2, 3, 4, 5} -> {1, 2, 5}  {1, 2, 4}  {1, 3, 5}  {2, 3, 4}  {2, 4, 5}  {3, 4, 5}
{-5, 4, 3, -2, 0} -> {-5, 4, 3}  {-5, 4, -2}  {4, 3, -2}
{-5, 4, 3, -2} -> {-5, 4, 3}  {-5, 4, -2}  {4, 3, -2}
{-17, 22, -5, 13, 200, -1, 1, 9} -> {-17, 22, -5, 13, 200, -1, 1}  {-17, 22, -5, 200, -1, 1, 9}  {-17, -5, 13, 200, -1, 1, 9}

MATL, 47 43 bytes
nW:qB!ts2#Sw2>)PZ)"1G@)XJ2XN!"@sJ@X-m~*]?J.

Try it online!
Explanation
This uses two loops: an outer loop to generate all possible subsets, and an inner loop to take all pairs of elements and see if the sum equals any other element of the subset.
Subsets of at least 3 elements are tested in order of decreasing number of elements. The code stops as soon as a valid subset is found.
          % Take input implicitly
nW:q      % Generate [0 1 ... 2^n-1] where n is input length
B!        % Convert to binary. Gives a matrix. Each number corresponds to a column.
          % This will be used to select the elements of each subset
ts        % Duplicate. Sum of each column
2#S       % Sort. Output the sorted array and the indices of the sorting. Each index
          % corresponds to one possible subset
w2>       % Swap. Logical index of values that exceed 2. This is used to pick only
          % subsets of more than 2 elements
)         % Keeps only indices of subsets that have at least 3 elements
P         % Flip. This moves subsets with more elements to the front. As soon as a
          % subset fulfills the condition the outer loop will be exited, so we need
          % to start with the bigger subsets
Z)        % Index into columns of binary matrix. Each column is the binary pattern
          % defining a subset with at least 3 elements, starting with bigger subsets
"         % For each column. Each iteration corresponds to a subset
  1       %   Push 1
  G@)     %   Pick actual elements of each subset (logical index into input)
  XJ      %   Copy to clipboard J
  2XN!    %   All pairs of 2 elements from that subset. Each pair is a column
  "       %   For each column. Each iteration corresponds to a pair of elements
    @s    %     Sum of those two elements
    J@X-  %     Array with the other elements (obtained with set difference)
    m~    %     True if the sum of the two elemens is not a member of the array
    *     %     Multiply. Corresponds to logical AND
  ]       %   End for
  ?       %   If result is true: no sum of two elements equalled any element
    J     %     Push found subset (will be displayed implicitly)
    .     %     Exit loop
          %   End if implicitly
          % End for implicitly
          % Display stack implicitly


Ravenity of Cube Distance Numbers Inspired by this Numberphile entry
Background
The cube distance numbers of an integer n are defined here as the set of integers that are x³ distance away for a given x. For a simple example, with n=100 and x=2, the cube distance numbers are {92,108}.
This can be extended into a larger set simply by varying x. With x ∈ {1,2,3,4} and the same n=100, we have the resultant set {36,73,92,99,101,108,127,164}.
Let's define CD(n,x) as the set of all integers n ± z³ with z ∈ {1,2,3,...,x}.
Now we can focus on some of the special properties of these cube distance numbers. Of the many special properties that numbers can have, the two properties we're interested in here are primality and prime divisors.
For the above example CD(100,4), note that 73, 101, 127 are all prime. If we remove those from the set, we're left with {36,92,99,108,164}. All prime divisors of these numbers are (in order) {2,2,3,3,2,2,23,3,3,11,2,2,3,3,3,2,2,41}, which means we have 5 distinct prime divisors {2,3,23,11,41}. We can therefore define that CD(100,4) has ravenity1 of 5.
The challenge here is to write a function or program, in the fewest bytes, that outputs the ravenity of a given input.
Input

Two positive integers, n and x, in any convenient format.

Output

A single integer describing the ravenity of the two input numbers, when calculated with CD(n,x).

Rules

Input/output can be via any suitable method.
Standard loophole restrictions apply.
For ease of calculation, you can assume that the input data will be such that CD(n,x) will only have positive numbers in the set (i.e., no CD(n,x) will ever have negative numbers or zero).
The function or program should be able to handle input numbers so that n + x³ fits in your language's native integer data type. For example, for a 32-bit signed integer type, all input numbers with n + x³ < 2147483648 are possible.

Examples
n,x   - output
2,1   - 0   (since CD(2,1)={1,3}, distinct prime divisors={}, ravenity=0)
5,1   - 2
100,4 - 5
720,6 - 11

Footnotes
1 - So named because we're not interested in the cardinality of the set, but a different type of bird. Since we're dealing with "common" divisors, I chose to use the common raven.

Pyth - 21 19 18 bytes
I wonder if there's a trick.
l{st#mP+Q^d3s_BMSE

Test Suite.
l                   Length
 {                  Uniquify
  s                 Combine divisor lists
   t#               Filter by if more than one element
     PM             Take prime factorization of each number
       +RQ          Add each num in list to input
          s_BM      Each num in list and its negative (with bifurcate)
              ^R3   Cube each num in list
                 SE Inclusive unary range - [1, 2, 3,... n] to input