Necklace splitting problem Background

I was inspired by 3Blue1Brown's recent video about the necklace splitting problem (or as he calls it, the stolen necklace problem) and its relationship to the Borsuk-Ulam theorem.

In this problem, two thieves have stolen a valuable necklace consisting of several different types of jewels. There are an even number of each type of jewel and the thieves wish to split each jewel type evenly amongst the two of them. The catch is that they must do so by splitting the necklace into some number of contiguous segments and distribute the segments between the two of them.

Here is an example with four jewel types denoted S, E, D, and R (for sapphire, emerald, diamond, and ruby, respectively). Let's say the necklace is as follows:

[S,S,S,E,S,D,E,R,S,R,E,S,S,S,D,R,E,E,R,E,D,E,R,R,D,E,E,E]

There are 8 sapphires, 10 emeralds, 4 diamonds, and 6 rubies. We can split the necklace as follows:

[[S],[S],[S,E,S,D,E,R,S],[R,E,S,S,S,D,R,E,E,R,E,D,E],[R,R,D,E,E,E]]

Then if we give the first, third, and fifth segments to one thief and the second and fourth segments to the other thief, each will end up with 4 sapphires, 5 emeralds, 2 diamonds, and 3 rubies:

[S],    [S,E,S,D,E,R,S],                            [R,R,D,E,E,E]
    [S],                [R,E,S,S,S,D,R,E,E,R,E,D,E],

Using 0-indexing, these cuts occur at the indices [1,2,9,22].

Goal

It turns out that such a fair division can always be done using at most n cuts, where n is the number of jewel types. Your task is to write a complete program or function which takes a necklace as input and outputs a minimal such division (fewest number of cuts).

Input

Input may be in any convenient format. The necklace should be a sequence of jewels and nothing more; e.g. a list of integers, dictionary with keys representing the jewel types and values being lists of indices. You may optionally include the length of the necklace or the number of distinct jewel types, but you should not take any other input.

You may assume that the input necklace is valid. You do not need to handle the case where there is an odd number of jewels of a given type or the necklace is empty.

Output

Again, output may be in any convenient format; e.g. a list of segments, a list of cut positions, a dictionary with keys representing the two thieves and values being lists of segments, etc. Segments may be represented by their starting index, ending index, list of consecutive indices, list of jewels, their lengths, etc. You may use 0- or 1- indexing. If the ordering is not significant to your format, then your output may be in any order. Here is the above output in several different formats:

list of segments: [[S],[S],[S,E,S,D,E,R,S],[R,E,S,S,S,D,R,E,E,R,E,D,E],[R,R,D,E,E,E]]
list of cuts:     [1,2,9,22]
list of lengths:  [1,1,7,13,6]
dictionary:       {'thief1' : [(R,R,D,E,E,E),(S),(S,E,S,D,E,R,S)], 'thief2' : [(S),(R,E,S,S,S,D,R,E,E,R,E,D,E)]}

Note that order is important in the list of segments (segments alternate between the thieves) and the list of lengths (in order to identify the segments), but not in the list of cuts or the dictionary. Edit: Greg Martin pointed out that these wouldn't be valid outputs since a fair division can be obtained in two cuts

Test cases

[1,2,1,2,1,3,1,3,3,2,2,3] -> [[1,2,1],[2,1,3,1],[3,3,2],[2,3]]
[1,1,1,1,2,2,3,3,3,3,3,3] -> [[1,1],[1,1,2],[2,3,3,3],[3,3,3]]
[1,1,1,1,1,1,1,1,1,1,1,1] -> [[1,1,1,1,1,1],[1,1,1,1,1,1]]
[1,1,1,1,2,3,4,2,3,4,2,2] -> [[1,1],[1,1,2,3,4,2],[3,4,2,2]]

Notes

Standard loopholes are forbidden.
This is code-golf; shortest answer (in bytes) wins.

Jelly, 18 bytes
s2ZFṢ$€E¬,L
ŒṖṖÇÞḢ

Try it online!
Not efficient - the example has 28 jewels which wont work without huge resources since this implementation's first step would be to build a list of the 227 possible partitions.
Returns a list of lists - the segments in the order to dish them out between alternate thieves. (Re the TIO output: when a list only has a single item the implicit print does not bother with the brackets, [])
How?
s2ZFṢ$€E¬,L - Link 1, get (isUnfair, Slices): A possible partition
s2          - split into slices of length 2 (any odd one on it's own at the end)
  Z         - transpose (first item is one thief's slices, second is the others)
     $€     - last two links as a monad for €ach
   F        -     flatten
    Ṣ       -     sort
       E    - equal? (theif1's jewels == theif2's jewels)
        ¬   - not
          L - length (number of slices in the partition)
         ,  - pair

ŒṖṖÇÞḢ - Main link: necklace
ŒṖ     - all partitions
  Ṗ    - pop, we must remove the rightmost one...
              because Link 1 will say it is fair, and it will have length 1!
              (a list of one thing has all entries equal)
    Þ  - sort by
   Ç   -     last link (1) as a monad
     Ḣ - head (get the first one, i.e. minimal isUnfair, then minimal length)


Complete the grid-filling meander A grid-filling meander is a closed path that visits every cell of a square \$N \times N\$ grid at least once, never crossing any edge between adjacent cells more than once and never crossing itself. For example:

Once filled, each cell of the grid can be represented by one of the following 8 tiles:

Numbered this way, the tiles of the above meander can be represented by this matrix:

5 6 5 6
4 8 3 2
5 7 6 2
4 3 4 3

Your task is to complete a grid-filling meander given an incomplete set of tiles. For example, the incomplete meander:

...which can be represented using 0s for missing tiles:

5 0 0 0 6
0 0 7 0 0
0 0 0 0 3
2 4 0 0 0
0 0 3 0 0

...could be completed like this:

...i.e.:

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

Specifications

The input will always have at least \$1\$ and at most \$N^2\$ (non-empty) tiles, where \$2 \le N \le 7\$.
You may use any set of values to represent the tiles, as long as it's specified in your answer.
Your input and output may be in any format and order, as long as it's specified in your answer.
At least one valid solution will exist for all inputs (i.e. you don't need to handle invalid input).
Standard I/O rules apply.
Standard loopholes are forbidden.
Explanations, even for "practical" languages, are encouraged.

Test cases

  Input (Θ):

0 6
0 0

  Output (Θ):

5 6
4 3

  Input (Θ):

5 6 5 6
4 0 3 2
5 7 6 2
4 3 4 3

  Output (Θ):

5 6 5 6
4 8 3 2
5 7 6 2
4 3 4 3

  Input (Θ):

5 0 0 0 6
0 0 7 0 0
0 0 0 0 3
2 4 0 0 0
0 0 3 0 0

  Output (Θ):

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

JavaScript (ES7),  236 ... 193  185 bytes

Outputs by modifying the input matrix.

m=>(g=(d,x,y,v,r=m[y],h=_=>++r[x]<9?g(d,x,y,v)||h():r[x]=0)=>r&&1/(n=r[x])?x|y|!v?n?g(d='21100--13203-32-21030321'[n*28+d*3+7&31],x+--d%2,y+--d%2,v+=n<7||.5):h():!m[v**.5|0]:0)(0,0,0,0)

Try it online!

(includes some post-processing code to print the result both as a matrix and as a flat list compatible with the visualization tool provided by the OP)

Results

Test case #1
Test case #2
Test case #3

How?

Variables

\$g\$ is a recursive function taking the current direction \$d\$, the current coordinates \$(x,y)\$ and the number of visited cells \$v\$.

The following variables are also defined in the scope of \$g\$:

\$r\$ is the current row of the matrix.

r = m[y]

\$h\$ is a helper function that tries all values from \$1\$ to \$8\$ for the current cell and invokes \$g\$ with each of them. It either stops as soon as \$g\$ succeeds or sets the current cell back to \$0\$ if we need to backtrack.

h = _ => ++r[x] < 9 ? g(d, x, y, v) || h() : r[x] = 0

Initial checks

We first make sure that our current location is valid and we load the value of the current cell into \$n\$:

r && 1 / (n = r[x]) ? ... ok ... : ... failed ...

We test whether we're back to our starting position, i.e. we're located at \$(0,0)\$ and we've visited at least a few cells (\$v>0\$):

x | y | !v ? ... no ... : ... yes ...

For now, let's assume that we're not back to the starting point.

Looking for a path

If \$n\$ is equal to \$0\$, we invoke \$h\$ to try all possible values for this tile.

If \$n\$ is not equal to \$0\$, we try to move to the next tile.

The tile connections are encoded in a lookup table, whose index is computed with \$n\$ and \$d\$, and whose valid entries represent the new values of \$d\$.

d = '21100--13203-32-21030321'[n * 28 + d * 3 + 7 & 31]

The last 8 entries are invalid and omitted. The other 4 invalid entries are explicitly marked with hyphens.

For reference, below are the decoded table, the compass and the tile-set provided in the challenge:

   | 1 2 3 4 5 6 7 8
---+-----------------
 0 | 0 - - 1 3 - 3 1          1
 1 | - 1 - - 2 0 2 0        0 + 2
 2 | 2 - 1 - - 3 1 3          3
 3 | - 3 0 2 - - 0 2

We do a recursive call to \$g\$ with the new direction and the new coordinates. We add \$1/2\$ to \$v\$ if we were on a tile of type \$7\$ or \$8\$, or \$1\$ otherwise (see the next paragraph).

g(d, x + --d % 2, y + --d % 2, v += n < 7 || .5)

If \$d\$ is invalid, \$x\$ and \$y\$ will be set to NaN, forcing the next iteration to fail immediately.

Validating the path

Finally, when we're back to \$(0,0)\$ with \$v>0\$, it doesn't necessarily mean that we've found a valid path, as we may have taken a shortcut. We need to check if we've visited the correct number of cells.

Each tile must be visited once, except tiles \$7\$ and \$8\$ that must be visited twice. This is why we add only \$1/2\$ to \$v\$ when such a tile is visited.

In the end, we must have \$v = N^2\$. But it's also worth noting that we can't possibly have \$v > N^2\$. So, it's enough to test that we don't have \$v < N^2\$, or that the \$k\$th row of the matrix (0-indexed) does not exist, where \$k=\lfloor\sqrt{v}\rfloor\$.

Hence the JS code:

!m[v ** .5 | 0]

Formatted source

m => (
  g = (
    d,
    x, y,
    v,
    r = m[y],
    h = _ => ++r[x] < 9 ? g(d, x, y, v) || h() : r[x] = 0
  ) =>
    r && 1 / (n = r[x]) ?
      x | y | !v ?
        n ?
          g(
            d = '21100--13203-32-21030321'[n * 28 + d * 3 + 7 & 31],
            x + --d % 2,
            y + --d % 2,
            v += n < 7 || .5
          )
        :
          h()
      :
        !m[v ** .5 | 0]
    :
      0
)(0, 0, 0, 0)


Generate Hofstadter's Figure-Figure Sequence In Gödel, Escher, Bach, Douglas Hofstadter introduces an integer sequence which is commonly referred to as the figure-figure sequence:

2, 4, 5, 6, 8, 9, 10, 11, 13, 14, 15, 16, 17, 19, 20, 21, 22, 23, 24, 25, ...

You may enjoy working out the definition of the sequence yourself as part of the challenge, but if you can't or don't want to figure it out you can find it on OEIS as sequence A030124 and a slightly clearer definition on Wikipedia.

Write a program or function which, given n via STDIN, ARGV or function argument, prints a list of the first n numbers of the sequence to STDOUT in any reasonable list format.

This is code golf, the shortest solution in bytes wins.

CJam, 38 30 29 21 bytes

li_3*,2>\{(_pX+:X-}*;

Try it online.

How it works

li                     " Read an integer N from STDIN.              ";
  _3*,2>               " Push S := [ 2 3 ... (N * 3 - 1) ].         ";
        \{        }*   " Do the following N times:                  ";
          (            " Shift an integer I from S.                 ";
           _p          " Print a copy of I, followed by a linefeed. ";
             X+:X      " Execute X += I. (X is initialized to 1.)   ";
                 -     " Remove X from S.                           ";
                    ;  " Discard S from the stack.                  ";

Example run

$ cjam <(echo 'li_3*,2>\{(_pX+:X-}*;') <<< 20
2
4
5
6
8
9
10
11
13
14
15
16
17
19
20
21
22
23
24
25


Arrays Start at \$\pi\$ Your task is to take an array of numbers and a real number and return the value at that point in the array. Arrays start at \$\pi\$ and are counted in \$\pi\$ intervals. Thing is, we're actually going to interpolate between elements given the "index". As an example:

Index:    1π   2π   3π   4π   5π   6π
Array: [ 1.1, 1.3, 6.9, 4.2, 1.3, 3.7 ]

Because it's \$\pi\$, we have to do the obligatory trigonometry, so we'll be using cosine interpolation using the following formula:

\${\cos(i \mod \pi) + 1 \over 2} * (\alpha - \beta) + \beta\$

where:

\$i\$ is the input "index"
\$\alpha\$ is the value of the element immediately before the "index"
\$\beta\$ is the value of the element immediately after the "index"
\$\cos\$ takes its angle in radians

Example

Given [1.3, 3.7, 6.9], 5.3:

Index 5.3 is between \$1\pi\$ and \$2\pi\$, so 1.3 will be used for before and 3.7 will be used for after. Putting it into the formula, we get:

\${\cos(5.3 \mod \pi) + 1 \over 2} * (1.3 - 3.7) + 3.7\$

Which comes out to 3.165

Notes

Input and output may be in any convenient format
You may assume the input number is greater than \$\pi\$ and less than array length * \$\pi\$
You may assume the input array will be at least 2 elements long.
Your result must have at least two decimal points of precision, be accurate to within 0.05, and support numbers up to 100 for this precision/accuracy. (single-precision floats are more than sufficient to meet this requirement)

Happy Golfing!

R, 59 53 bytes

function(x,i)x[0:1+i%/%pi]%*%c(a<-cos(i%%pi/2)^2,1-a)

Try it online!

Nothing too clever here - just an R version of the formula in the question.
Thanks @MickyT for saving a byte, and to @Giueseppe and indirectly @xnor for another two, and thanks to @RobinRyder for saving a further 3.


Tweetable hash function challenge In this code-challenge you will write a hash function in 140 bytes1 or less of source code. The hash function must take an ASCII string as input, and return a 24-bit unsigned integer ([0, 224-1]) as output.

Your hash function will be evaluated for every word in this large British English dictionary2. Your score is the amount of words that share a hash value with another word (a collision).

The lowest score wins, ties broken by first poster.

Test case

Before submitting, please test your scoring script on the following input:

duplicate
duplicate
duplicate
duplicate

If it gives any score other than 4, it is buggy.

Clarifying rules:

Your hash function must run on a single string, not a whole array. Also, your hash function may not do any other I/O than the input string and output integer.
Built-in hash functions or similar functionality (e.g. encryption to scramble bytes) is disallowed.
Your hash function must be deterministic.
Contrary to most other contests optimizing specifically for the scoring input is allowed.

1 I am aware Twitter limits characters instead of bytes, but for simplicity we will use bytes as a limit for this challenge.
2 Modified from Debian's wbritish-huge, removing any non-ASCII words.

Python, 5333 4991

I believe this is the first contender to score significantly better than a random oracle.

def H(s):n=int(s.encode('hex'),16);return n%(8**8-ord('+%:5O![/5;QwrXsIf]\'k#!__u5O}nQ~{;/~{CutM;ItulA{uOk_7"ud-o?y<Cn~-`bl_Yb'[n%70]))


Write a base X to base Y function Create a function 'baseXtoY' which:

converts an integer or string n, which is a base x number (hexadecimal, binary, etc)
into a base y number, reliably, including numbers like 10e50 or higher, using the least bytes possible, and using the following constraints:

Provide built-in support for bases up to 64 using the following
sequence: 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=/
Provide support for bases higher than 64 by allowing a different sequence to be used in the input
Provide support for multi-byte sequences eg ('aa','bb','cc'...) in cases rally high value bases are needed (could also support unicode instead)
You cannot have a base less than 2. Show an error
You cannot use any built-in functions that convert base to base for you
You need not worry about floating point

parameters should be:

n - any number, as a string
x - the base of n, integer
y - the base of the return value
s1 - the sequence the given number's base uses
s2 - the sequence the desired base uses
b - the bytesize of the digits in s1
return value should be a string

example inputs:
using '88888'
base 10 to 2: baseXtoY('88888',10,2) >>> '10101101100111000'

base 2 to 5: baseXtoY('10101101100111000',2,5) >>> '10321023'

base 5 to 32: baseXtoY('10321023',5,32) >>> '2mpo'

base 32 to 10, using a new sequence, s=the above 64bit sequence, a=the alphabet: baseXtoY('2mpo',32,10,s,a) >>> 'hhhhh'

base 5 to 10, input base uses more than 1 byte per digit: baseXtoY('bbaaddccbbaaccdd',5,10,('aa','bb','cc','dd','ee'),'0123456789',2)) > '88888'`

you do not have to inlude the character length of the testing or input code, just the
function(s).

edit: I've given up trying to shorten my Python code lower than the answers, so I'll just show what I have. 585 characters python 2.7

r=range
def b1(n,x,s):
 if n==0:return s[0]
 if x<=1:raise
 l=[];p=n;i=0
 while 1:
  y=x**i;l.append(y)
  if y>p:break
  else:i+=1
 l.reverse();f=[]
 for p in l:h=int(n//p);f.append(h);n-=h*p
 while f[0]==0:f.pop(0)
 q=''
 for p in r(len(f)):q+=s[f[p]]
 return q
def b2(n,x,s,b):
 n=list(str(n));l=[]
 while n:
  a=''
  for p in r(b):a+=n.pop(0)
  l.append(a)
 m=0;q=0
 while l:c=s.index(l.pop());q+=c*(x**m);m+=1
 return q
s=''.join(map(chr,r(48,58)+r(97,123)+r(65,91)))+'=/'
def baseXtoY(n,x=10,y=2,s1=s,s2=s,b=1):return n if x==y else b2(n,x,s1,b)if y==10 else b1(b2(n,x,s1,b),y,s2)

test cases:

32 10 5 >>> 112

112 5 2 >>> 100000

100000 2 10 >>> 32

88888 10 5 0123456789 ('aa', 'bb', 'cc', 'dd', 'ee') 1 >>> bbaaddccbbaaccdd

bbaaddccbbaaccdd 5 10 ('aa', 'bb', 'cc', 'dd', 'ee') 0123456789 2 >>> 88888

GolfScript, 139 130 128 characters
~]{.,5<{[10,""*26,{[97+]}%""*.{32-}%"=/"+++]+}*}2*.,6<{1+}*~:B;.""?!{1/}*:T;.""?!{B/}*:S;:Y;:X;B/0\{S?\X*+}%;""\{.Y%T=@+\Y/.}do;

Most of the characters come from reading and converting parameters and adding the optional ones. The actual conversion is only few chars.
The example inputs are processed as expected:
'88888' 10 2                      # 10101101100111000
'10101101100111000' 2 5           # 10321023
'10321023' 5 32                   # 2mpo
'2mpo' 32 10                      # 88888
'88888' 10 5 '0123456789' ['aa' 'bb' 'cc' 'dd' 'ee'] 1
                                  # bbaaddccbbaaccdd
'bbaaddccbbaaccdd' 5 10 ['aa' 'bb' 'cc' 'dd' 'ee'] '0123456789' 2
                                  # 88888

Edit 1: some minor improvements, esp. coding the digits sequence.
Edit 2: this was an easy one: 0= can be replaced by ! two times in the conversion of the base parameters.


Let's play countdown! For those of you who have seen the popular daytime TV show Countdown, you will know that the contestants are given 9 randomly selected letters and must then find the longest word they can in 30 seconds.
Your challenge is, given a string of 9 letters, to find the longest word that is an anagram of the largest subset of input letters, this means that you don't have to use all of the letters in the input string.
Input/output can be stdin/stdout, or whatever the equivalent in your language is.
Rules

Input will always a 9 letter string, all lower-case
You can use as few or as many of the letters from the input string
A word is allowed if it is found in the specified dictionary file, the dictionary file containing all the allowed words can be found here (note: I didn't compile this, credit goes to the github uploader). The file is is a .txt file which contains ~101,000 words with each word on a new line - approx 985kB.
You must use the dictionary file specified above, this is to ensure that all fairness across all the entries, e.g. so everyone has the same chance of finding the longest word.
You are allowed to manipulate the dictionary file in such a way that none of the words are edited in any way and no new ones are added, for example copying all the words to an array, making all words comma separated or copying the whole contents of the file to another file would be allowed.
Inputs may contain any number of vowels and consonants, e.g. 9 vowels or 8 consonants and 1 vowel
If there are multiple words with the same length, then you must output all of them (up to a limit of 5 - to prevent long lists of 5/6 letter words). Multiple words must be delimited, but this can be done in any way - comma, space etc.

Test Cases
Input: mhdexaspo
Output: hexapods, mopheads
Input: iesretmng
Output: regiments
Input: cmilensua
Output: masculine calumnies
Input: floiufhyp
Output: huffily puffily
Input: frtuasmjg
Output: frusta,jurats,jumars,tragus,grafts
This is code-golf, so shortest code wins!

CJam, 51 bytes

Laeas$W%{1$f++}/:A;qN/{$aA&},{,~}$5<_0=,:L;{,L=},S*

CJam has no file I/O, so I opted to read the dictionary (converted to Unix format) from STDIN and read the string of letters as a command-line argument.

Test cases

$ for w in mhdexaspo iesretmng cmilensua floiufhyp frtuasmjg
> do cjam countdown.cjam $w < dictionary.txt
> echo
> done
hexapods mopheads
regiments
calumnies masculine
huffily puffily
frusta gamuts grafts jumars jurats

How it works

La        " Push T := [ '' ].                                                         ";
eas       " Push the command-line argument (R) as a string.                           ";
$W%       " Sort its letters, then reverse.                                           ";
{1$f++}/  " Iterate over the letters; prepend them to copies of the strings in T.     ";
:A;       " Save in A and discard. A contains all sorted substrings of R.             ";
qN/       " Read from STDIN and split at linefeeds.                                   ";
{$aA&},   " Filter; keep dictionary words D such that {sort(D)} ∩ A ≠ ∅.              ";
{,~}$     " Sort by negated word length.                                              ";
5<        " Keep only the first five words.                                           ";
_0=,:L;   " Save the length of the first in L.                                        ";
{,L=},    " Filter; keep dictionary words D such that len(D) = L.                     ";
 S*       " Separate by spaces.                                                       ";


Wherre are the adjacent characters in the title? [3, 4]! Title misspelled on purpose. Read more to find out why.

Your task: given a delimited string or list including the characters A,B,C,D, output the indexes of all the adjacent equal characters. Output can be multiple strings/integers on multiple lines, a list/array, or a delimited string.

All output should be in a list or string, or multiple printed lines. Each printed line, if there are multiple, should only contain 1 string or number. Trailing whatevers are okay.

Standard methods of input/output. Standard loopholes apply.

For example, the input 'ABCDDCBA' should output 3,4 or 4,5, depending on whether it is 0- to 1- indexed, because those numbers are the indexes of D and the D next to it.

Test cases:

Test cases have input given as a single string, and output as a ,-delimited string. Outputs are 0-indexed, add 1 to every outputted item to get it to be 1-indexed.

Input: 'ABCDCABCD'
Output: ''

Input: 'AABBCCDD'
Output: '0,1,2,3,4,5,6,7'

Input: 'ABCDDDCBA'
Output: '3,4,5'

Input: 'ABBCDD'
Output: '1,2,4,5'

This is code-golf, so shortest code wins!

Retina, 33 29 23 bytes

Saved 6 bytes thanks to Martin Ender

T`L`:`(.)\1+
:
$.`¶
T`L

Outputs a linefeed-separated list of indices.

Try it online!

Explanation

T`L`:`(.)\1+

Transliterate runs of the same character into colons, to mark positions where there are duplicate characters.

:
$.`¶

Then replace each colon with the length of the text before it, followed by a linefeed.

T`L

Finally, delete any remaining letters.


Modular broadcasting This challenge is related to some of the MATL language's features, as part of the May 2018 Language of the Month event.

Introduction

In MATL, many two-input functions work element-wise with broadcast. This means the following:

Element-wise (or vectorized): the function takes as inputs two arrays with matching sizes. The operation defined by the function is applied to each pair of corresponding entries. For example, using post-fix notation:

[2 4 6] [10 20 30] +

gives the ouput

[12 24 36]

This also works with multi-dimensional arrays. The notation [1 2 3; 4 5 6] represents the 2×3 array (matrix)

1 2 3
4 5 6

which has size 2 along the first dimension (vertical) and 3 along the second (horizontal). So for example

[2 4 6; 3 5 7] [10 20 30; 40 60 80] *

gives

[20 80 180; 120 300 560]

Broadcasting or (singleton expansion): the two input arrays do not have matching sizes, but in each non-matching dimension one of the arrays has size 1. This array is implicitly replicated along the other dimensions to make sizes match; and then the operation is applied element-wise as above. For example, consider two input arrays with sizes 1×2 and 3×1:

[10 20] [1; 2; 5] /

Thanks to broadcasting, this is equivalent to

[10 20; 10 20; 10 20] [1 1; 2 2; 5 5] /

and so it gives

[10 20; 5 10; 2 4]

Similarly, with sizes 3×2 and 3×1 (broadcasting now acts along the second dimension only),

[9 8; 7 6; 5 4] [10; 20; 30] +

gives

[19 18; 27 26; 35 34]

The number of dimensions may even be different. For example, inputs with sizes 3×2 and 3×1×5 are compatible, and give a 3×2×5 result. In fact, size 3×2 is the same as 3×2×1 (there are arbitrarily many implicit trailing singleton dimensions).

On the other hand, a pair of 2×2 and 3×1 arrays would give an error, because the sizes along the first dimension are 2 and 3: they are not equal and none of them is 1.

Definition of modular broadcasting

Modular broadcasting is a generalization of broadcasting that works even if none of the non-matching sizes are 1. Consider for example the following 2×2 and 3×1 arrays as inputs of the function +:

[2 4; 6 8] [10; 20; 30] +

The rule is as follows: for each dimension, the array that is smaller along that dimension is replicated modularly (cyclically) to match the size of the other array. This would make the above equivalent to

[2 4; 6 8; 2 4] [10 10; 20 20; 30 30] +

with the result

[12 14; 26 28; 32 34]

As a second example,

[5 10; 15 20] [0 0 0 0; 1 2 3 4; 0 0 0 0; 5 6 7 8; 0 0 0 0] +

would produce

[5 10 5 10; 16 22 18 24; 5 10 5 10; 20 26 22 28; 5 10 5 10]

In general, inputs with sizes a×b and c×d give a result of size max(a,b)×max(c,d).

The challenge

Implement addition for two-dimensional arrays with modular broadcasting as defined above.

The arrays will be rectangular (not ragged), will only contain non-negative integers, and will have size at least 1 in each dimension.

Aditional rules:

Input and output can be taken by any reasonable means. Their format is flexible as usual.
Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
Shortest code in bytes wins.

Test cases

The following uses ; as row separator (as in the examples above). Each test case shows the two inputs and then the output.

[2 4; 6 8]
[10; 20; 30]
[12 14; 26 28; 32 34]

[5 10; 15 20]
[0 0 0 0; 1 2 3 4; 0 0 0 0; 5 6 7 8; 0 0 0 0]
[5 10 5 10; 16 22 18 24; 5 10 5 10; 20 26 22 28; 5 10 5 10]

[1]
[2]
[3]

[1; 2]
[10]
[11; 12]

[1 2 3 4 5]
[10 20 30]
[11 22 33 14 25]

[9 12 5; 5 4 2]
[4 2; 7 3; 15 6; 4 0; 3 3]
[13 14 9;12 7 9;24 18 20;9 4 6;12 15 8]

[9 12 5; 5 4 2]
[4 2 6 7; 7 3 7 3; 15 6 0 1; 4 0 1 16; 3 3 3 8]
[13 14 11 16; 12 7 9 8; 24 18 5 10; 9 4 3 21; 12 15 8 17]

[6 7 9]
[4 2 5]
[10 9 14]

Charcoal, 25 23 bytes

ＡθＩＥ⌈ＥθＬιＥ⌈ＥθＬ§λ⁰ΣＥθ§§νιλ

Try it online! Link is to verbose version of code. Takes input as a 3-dimensional array. Explanation:

Ａθ

Input everything.

    θ                   Input
   Ｅ                    Map over arrays
      ι                 Current array
     Ｌ                  Length
  ⌈                     Maximum
 Ｅ                      Map over implicit range
          θ             Input
         Ｅ              Map over arrays
             λ          Current array
            § ⁰         First element
           Ｌ            Length
        ⌈               Maximum
       Ｅ                Map over implicit range
                 θ      Input
                Ｅ       Map over arrays
                    ν   Current array
                   § ι  Cyclically index using outer loop index
                  §   λ Cyclically index using inner loop index
               Σ        Sum
Ｉ                       Cast to string
                        Implicitly print on separate lines and paragraphs


Run the Nth characters to get N Write the shortest program possible such that when you combine the first character and every Nth character after it into a new program, the output is N. This must work for N = 1, 2, ..., 16.
Another way to say it is, if you remove all the characters from your program except for the first one and every Nth one after that, the output of the remaining code should be N.
Example
If your code was
ABCDEFGHIJKLMNOP

N = 1 results in ABCDEFGHIJKLMNOP. Running this should output 1.
N = 2 results in ACEGIKMO. Running this should output 2.
N = 3 results in ADGJMP. Running this should output 3.
N = 4 results in AEIM. Running this should output 4.
N = 5 results in AFKP. Running this should output 5.
N = 6 results in AGM. Running this should output 6.
N = 7 results in AHO. Running this should output 7.
N = 8 results in AI. Running this should output 8.
N = 9 results in AJ. Running this should output 9.
N = 10 results in AK. Running this should output 10.
N = 11 results in AL. Running this should output 11.
N = 12 results in AM. Running this should output 12.
N = 13 results in AN. Running this should output 13.
N = 14 results in AO. Running this should output 14.
N = 15 results in AP. Running this should output 15.
N = 16 results in A. Running this should output 16.
Details

All characters are allowed, ASCII and non-ASCII. (Newlines and unprintable ASCII are allowed as well. Note that carriage return and line feed count as distinct characters.)
Your score is the length in characters of your unaltered program (15 in example). The lowest score wins.
A score below 16 is clearly impossible because then at least two of the altered programs would be identical.
Output may be to a file or stdout or anything else reasonable. However, the output of the 16 different programs must all go to the same place (e.g. it's not ok if AO goes to stdout but A goes to a file). There is no input.
The output must be in decimal, not hex. The actual output should only contain the 1 or 2 characters that make up the number from 1 to 16, nothing else. (Things like Matlab's ans =  are ok.)
Your program does not have to work for N = 17 or above.


Counting Pages of a Book Task
Given the page of a book P on stdin, count all occurrences of the digits 0-9 in each member of the range 1 to P. There is no page zero and your program should handle any number less than 1,000,000. Since putting a constraint on how you can do it is difficult to explain there will be a time limit of 3 seconds instead. That may be too short for some of the answers already submitted but mine runs faster than that so it is possible.
Examples (plus a list of the occurences):
input: 10

0 = 1  (10)
1 = 2  (1, 10)
2 = 1  (2)
3 = 1  (3)
4 = 1  (4)
5 = 1  (5)
6 = 1  (6)
7 = 1  (7)
8 = 1  (8)
9 = 1  (9)

input: 20

0 = 2  (10, 20)
1 = 11 (1, 10, 11 ... 18, 19)
2 = 3  (2, 12, 20)
3 = 2  (3, 13)
4 = 2  (4, 14)
5 = 2  (5, 15)
6 = 2  (6, 16)
7 = 2  (7, 17)
9 = 2  (8, 18)

Matlab, 43 bytes

y=hist(+num2str(1:input('')),47:57);y(2:11)

Example:

>> y=hist(+num2str(1:input('')),47:57);y(2:11)
10
ans =
     1     2     1     1     1     1     1     1     1     1

How it works:

1:input('') generates a vector of numbers from 1 to the input number.

num2str converts all those numbers to a space-separated string (char array).

The + converts from char to ASCII codes. Digits are 48 to 57 in ASCII.

hist counts how many times each of those ASCII codes appears. Actually the count for value 47 is necessary too, because hist collects all lower values in the first bin. So that 47 just intercepts all spaces and prevents them from being confused as zeroes.

Lastly, y(2:11) removes that first count and prints the result.


Tips for golfing in Brachylog Brachylog is a language that's beginning to rise in prominence in code-golfing recently (and just received a major update with a terser syntax). Like Prolog, it has the advantage that it can often solve a problem (typically via brute force) merely from a sufficiently accurate description of what a problem looks like, a feature that means that on the right sort of challenge, it's often comparable to the top golfing languages (and has been known to beat Jelly from time to time).

What tips do you have for golfing (i.e. writing the shortest possible programs in) Brachylog? This is mostly looking for advice that's specific to Brachylog in particular, rather than advice that's applicable to a wide range of languages. (Tips about golfing in declarative languages in general might potentially be appropriate here, depending on how much application they'll have to languages other than Brachylog, although see also Tips for golfing in Prolog.)

Exploit nested predicates to create new variables

Brachylog has lots of special syntax cases to make its two special variables, ? (input / left parameter) and . (output / right parameter), terser to use. This means that if you don't need to access your predicate's ? and ., but do need to use variables, you can often save bytes via creating a nested predicate to use its ? and ..

As a simple example, consider a program that looks like this:

… A … ∧A … B … B …

This is a pretty common shape for a longer program; after all, there are lots of gaps that could contain anything. Suppose we have no need for ? or . inside the centre three gaps. Then we could rewrite it like this:

… { … & … . … } …

Here, the nested predicate's ? is serving the role of A, and its . is serving the role of B. We can observe that this is a byte shorter than the original code; changing AABB to {?.} has no change in terms of bytes, but this allowed us to simplify ∧? to the abbreviation &.

A related trick is to change

∧. … ?∧

to

~{ … }

(which is one byte shorter), although note that it's nearly always cheaper to get the caller to exchange the arguments instead (unless the predicate is called from at least three different places in the program, which is rare in Brachylog).


Approximate Brun's Constant Brun's constant is the value to which the sum of the reciprocals of twin prime pairs (1/p and 1/(p+2) where p and p+2 are both prime) converges. It is approximately 1.902160583104.
Given a positive integer N, approximate Brun's constant by summing the reciprocals of the twin prime pairs where both primes in the pair are less than N, and output the approximation.
Rules

N will be a positive integer within the representable range for your language.
The output must be as accurate as possible to the true value, within the limits of your language's floating-point implementation, ignoring any potential issues due to floating-point arithmetic inaccuracies. If your language is capable of arbitrary-precision arithmetic, it must be at least as precise as IEEE 754 double-precision arithmetic.
Alternatively, an exact fraction may be output in any consistent, unambiguous format.
If a prime appears in multiple twin prime pairs (e.g. 5, part of both (3, 5) and (5, 7)), its reciprocal contributes to the sum each time.

Test Cases
2 -> 0
6 -> 0.5333333333333333
10 -> 0.8761904761904762
13 -> 0.8761904761904762
100 -> 1.3309903657190867
620 -> 1.4999706034568274
100000 -> 1.67279958482774

Python 3, 78 77 75 70 68 62 bytes

f=lambda n,k=3,m=1,j=0:k<n and-m%k*j*2/k+f(n,k+2,m*k**4,m%k/k)

Thanks to @xnor for golfing off 2 4 bytes and paving the way for 4 more!

Try it online!

Background

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

where a ≡ b (mod d) means that a - b is evenly divisible by d, i.e., a and b have the same residue when divided by d.

In Wilson Theorems for Double-, Hyper-, Sub- and Super-factorials, the authors prove generalizations for double factorials, on which this answer builds. The double factorial of an integer k ≥ 0 is defined by

Theorem 4 of the aforementioned paper states the following.

Elevating both sides of the congruences to the fourth power, we deduce that

for all odd primes p. Since 1!! = 1, the equivalence holds also for p = 2.

Now, doing the same to Wilson's theorem reveals that

Since

it follows that

whenever p is prime.

Now, let k be an odd, positive, composite integer. By definition, there exist integers a, b > 1 such that k = ab.

Since k is odd, so are a and b. Thus, both occur in the sequence 1, 3, …, k - 2 and

where | indicates divisibility.

Summing up, for all odd integers k > 1

where p(k) = 1 if k is prime and p(k) = 0 if k is composite.

How it works

When the function f is called with a single argument, k, m, and j are initialized as 3, 1, and 0.

Note that ((k - 2)!!)4 = 1!!4 = 1 = m. In fact, the equality m = ((k - 2)!!)4 will hold at all times. j is a float and will always be equal to ((k - 4)!!)4 % (k - 2) / (k - 2).

While k < n, the right argument of and will get evaluated. Since j = ((k - 4)!!)4 % (k - 2) / (k - 2), as proven in the first paragraph, j = 1/(k - 2) if k - 2 is prime and j = 0 if not. Likewise, since m % k = ((k - 2)!!)4 equals 1 if k is prime and 0 if not, -m % k = k - 1 if k is prime and -m % k = 0 if not. Therefore, -m%k*j*2/k evaluates to 2(k - 1)/(k(k - 2)) = ((k - 2) + k)/(k(k - 2)) = 1/k + 1/(k - 2) if the pair (k - 2, k) consists of twin primes and to 0 if not.

After computing the above, we add the result to the return value of the recursive call f(n,k+2,m*k**4,m%k/k). k gets incremented by 2 so it only takes odd values‡†, we multiply m by k4 since mk4 = ((k - 2)!!)4k4 = (k!!)4, and pass the current value of m % k / k – which equals 1/k if the "old" k is a prime and 0 if not – as parameter j to the function call.

Finally, once k is equal to or greater than n, f will return False and the recursion stops. The return value of f(n) will be the sum of all 1/k + 1/(k - 2) such (k - 2, k) is a twin prime pair and k < n, as desired.

‡ The results from the Background paragraph hold only for odd integers. Since even integers cannot be twin primes, we can skip them safely.


Two steps forward and one step back Let's say I'm ten steps away from my destination. I walk there following the old saying, "Two steps forward and one step back". I take two steps forward, one back, until I'm standing exactly on my destination. (This might involve stepping past my destination, and returning to it). How many steps did I walk?

Of course, I might not be 10 steps away. I might be 11 steps away, or 100.
I could measure ten paces, and keep walking back and forth to solve the problem, or... I could write some code!

Write a function to work out how many steps it takes to get N steps away, in the sequence: two steps forward, one step back.
Assume you've started at step 0. Count the "two steps forward" as two steps, not one.
Assume all steps are a uniform length.
It should return the number of steps first taken when you reach that space. (For instance, 10 steps away takes 26 steps, but you'd hit it again at step 30). We're interested in the 26.
Use any language you like.
It should accept any positive integer as input. This represents the target step.
Smallest number of bytes win.

Example:

I want to get 5 steps away:

| | | | | | <- I'm at step 0, not yet on the grid.
| |X| | | | <- I take two steps forward, I'm on step 2: the count is 2
|X| | | | | <- I take one step back, I'm on step 1: the count is 3
| | |X| | | <- I take two steps forward, I'm on step 3: the count is 5
| |X| | | | <- I take one step back, I'm on step 2 again: the count is 6
| | | |X| | <- I take two steps forward, I'm on step 4: the count is 8
| | |X| | | <- I take one step back, I'm on step 3 again: the count is 9
| | | | |X| <- I take two steps forward, I'm on step 5: the count is 11

In this case, the result of the function would be 11.

Example results:

1      =>  3
5      =>  11
9      =>  23
10     =>  26
11     =>  29
100    =>  296
1000   =>  2996
10000  =>  29996
100000 =>  299996

Have fun, golfers!

Python 2, 18 bytes

lambda n:3*n-1%n*4

Try it online.

I picked this trick up from xnor just a few days ago…!


Solve sin(θ) = x in the range a ≤ θ ≤ b Challenge

Given a number, x where -1 ≤ x ≤ 1, and the integers a and b, where b > a, solve the equation sin(θ) = x for θ, giving all solutions in the range a° ≤ θ ≤ b°.

Rules

x will have a maximum of three decimal places of precision. The output, θ, must also be to three decimal places, no more, no less.

Your output may be as a list or separated output.

You may use built-in trig functions.

You may not use radians for a and b.

You will never be given invalid input.

Output may be in any order.

Examples

x, a, b => outputs
0.500, 0, 360 => 30.000, 150.000
-0.200, 56, 243 => 191.537
0.000, -1080, 1080 => 0.000, 180.000, 360.000, 540.000, 720.000, 900.000, 1080.000, -1080.000 -900.000, -720.000, -540.000, -360.000, -180.000

Winning

Shortest code in bytes wins.


Sum over an Interval Inspired by this challenge, and similar to this and this.
After seeing these, I figured I would continue the trend as there was no inclusive/exclusive sum.
The goal here is to sum an interval of integers, either inclusive and exclusive, and output the total to stdout.
Input format: either a ( or [ followed by 2 comma separated integers followed by a ) or ]. Ex: [a, b] (a, b] [a, b) (a, b)

Note: b > a >= 0 and the range will always contain at least 1 value.
Input regex: [\(\[]\d+,\d+[\)\]]

Examples:
Input -> Output

[2,6] -> 20
(15,25] -> 205
[0,16) -> 120
(15,20) -> 70
[1,2) -> 1
(2,12] -> 75
[11,16] -> 81
(15,29) -> 286
[14,15) -> 14
(2,16] -> 133
(12,18) -> 75

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

Jelly, 14 bytes
ḊṖVr/ḟ×ɗċⱮØ($S

A monadic Link accepting a list of characters that yields the sum of the described range.
Try it online! Or see the test-suite.
How?
ḊṖVr/ḟ×ɗċⱮØ($S - Link: list of characters, R  e.g. "[5,8)"
Ḋ              - dequeue                           "5,8)"
 Ṗ             - pop                               "5,8"
  V            - evaluate as Jelly                 [5,8]
                 (call that X)
            $  - last two links as a monad - f(R):
          Ø(   -   list of characters = "()"       "()"
         Ɱ     -   map across these with:
        ċ      -     count ocuurences (in R)       [0,1]
                     (call that Y)
       ɗ       - last three links as a dyad - f(X,Y):
    /          -   reduce (X) with:
   r           -     inclusive range               [5,6,7,8]
      ×        -   (X) multiply (Y) (vectorises)   [0,8]
     ḟ         -   filter discard                  [5,6,7]
             S - sum                               18


Maximizing by swapping Input
An integer n in the range 100 to 10^18 and an integer k in the range 1 to 18, inclusive.
The swap operation
A swap chooses two digits at different positions and exchanges their positions, as long as the swap does not result in a leading zero. For example if we start with the integer 12345 we can perform one swap to make it 12543.
Task
Output the largest number you can get after exactly k swaps.
Examples
n = 1283, k = 2. Output: 8312
n = 510, k = 1. Output: 501
n = 501, k = 2. Output: 501
n = 999, k = 3. Output: 999
n = 12345678987654321, k = 1. Output: 92345678187654321

Python 3, 194 190 196 193 175 164 162 bytes

def f(n,k):
 for i in range(len(n)-1):
  y=max(n[i:]);j=n[::-1].index(y)
  if(y>n[i])*k:n[i],n[~j]=y,n[i];k-=1
 if len(n)-len({*n})<k%2:n[-2:]=n[:-3:-1]
 return n

Try it online!

Pretty tough to golf this challenge in a real world language - I like it :)

After golfing down to 190 bytes (and below..), I found some cases where the algorithm would not find the maximum possible value. Bugfixing forced me back up to 196 193 bytes :/

... then I found some ways to better handle branching on k and went down below 180 :)

After the comment from Chas Brown, switching from integer to list I/O saved 28 bytes! (And more golfing another 2..)

Then, another bug: the algorithm incorrectly handles remaining swaps, if there are equal digits present. The fix cost 19 bytes.

Algorithm:

For each digit, starting from the leftmost one, swap it with the rightmost maximum digit, if that one is bigger. First line of the for-loop finds the maximum and its index. Second line does the swap.
If there are k' swaps left, swap two equal digits, or the two rightmost k' times. I.e. if  there are two equal digits present, or if k' is even, no more swaps have to be done. Else, just swap the last two digits once.


How many letters in this word? Inspired by Project Euler #17, this is your challenge. Write a full program or function that takes a number as input, then print or return how many letters it would take to count up to and including that number in English (starting at one). You do not include spaces, commas, or hyphens, but you should include the word and. For example. 342 is spelled: Three Hundred and Forty-Two. This is 23 letters long.

Your input will be a positive integer. You do not have to handle invalid inputs. Built-ins or libraries that convert numbers to English are not allowed.

Here are all of the rules for how to spell numbers. (Note: I realize that some people use a different set of rules for how to spell numbers. This will just be the official rules for the purpose of this challenge)

1 to 20

  one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen, eighteen, nineteen, twenty

21 to 99

Join these:

  Twenty, thirty, forty, fifty, sixty, seventy, eighty, ninety

to these:

  -one, -two, -three, -four, -five, -six, -seven, -eight, -nine,

Note that four has a u but forty does not!

Examples:

53: Fifty-three
60: sixty
72: seventy-two
99: ninety-nine

100 to 999

Write out how many hundreds (one hundred, two hundred, three hundred, etc.), an "and", and the rest of the number as above. The and does count towards your letter score.

Examples:

101: One hundred and one
116: One hundred and sixteen
144: One hundred and forty-four
212: Two hundred and twelve
621: Six Hundred and twenty-one

1,000 to 999,999

Write how many thousands (one thousand, two thousand, etc.), a comma, then the rest of the number as above. Note that if you have no hundreds, you still need the and.

Examples:

1,101: One thousand, one hundred and one
15,016: Fifteen thousand and sixteen
362,928: Three hundred and sixty-two thousand, nine hundred and twenty-eight

Millions

Write out how many millions, then the rest of the number as above. Note that "A million" is 6 zeroes "1,000,000".

Examples:

191,232,891: One hundred and ninety-one million, two hundred and thirty-two thousand, eight hundred and ninety-one
1,006,101: One million, six thousand, one hundred and one

The same rule applies to billions, trillions, quadrillions and above, but for the purpose of this challenge, you don't have to handle any number above 999,999,999 (Nine Hundred and ninety-nine million, nine-hundred and ninety-nine thousand, nine hundred and ninety-nine.)

Python solver

Here is a short python script to verify answers:

import en

def get_letter_num(s):
    count = 0
    for c in s:
        if c.isalpha():
            count += 1
    return count

number = input()
count = 0
for i in xrange(1, number + 1):
    count += get_letter_num(en.number.spoken(i))

print count

Note that this usesthe NodeBox linguistics library to convert numbers to English. (yes, I just broke my own rule, but this isn't a competing answer) This is freely available here.

Sample I/O

7: 27
19: 106
72: 583
108: 1000
1337: 31,131
1234567: 63,448,174

Python 2, 266 259 236 229 228 bytes

This works for all inputs below one billion. This works for all test cases.

def l(n):b=[6,3,2][(n<1000)+(n<10**6)];c=10**b;return int("0335443554"[n%10])+int("0366555766"[n/10])+(n-10in[4,6,7,9])if n<100else l(n/c)+(l(n%c)or-3*(b<3))+7+(b<6)+2*(b<3)+3*(b>2)*(0<n%c<101)
print sum(map(l,range(input()+1)))

To modify it to fit the question as stated (e.g. don't treat numbers ending with 100 special) simply replace the number 101 at the end of the first line with 100.

Explanation:

def l(n):
    b=[6, 3, 2][(n < 1000) + (n < 10**6)] # b = 2 if n < 1000 else 3 if n < 1000000 else 6
    c=10**b
    return (                            # Parenthesis added for readability.
            int("0335443554"[n % 10]) + # Compute length of last digit. one -> 3, seven -> 5, etc.
            int("0366555766"[n / 10]) + # Compute length of second to last digit. ten -> 3, eighty -> 6, etc.
            (n - 10 in[4, 6, 7, 9])     # Add one to length if the number is 14, 16, 17, or 19.

            if n < 100 else             # Use above procedure if the number is under 100.
                                        # If otherwise, use below procedure.

            l(n / c) +                  # Compute length of the top portion of number.
                (l(n % c) or            # Compute length of bottom portion of number.
                -3 * (b < 3)) +         # If the number < 1000 and is a multiple of 100,
                                        # subtract 3 from the length because of missing and.
            7 +                         # Add 7 to the length for "million"
            (b < 6) +                   # Add 8 to the length for "thousand"
            2 * (b < 3) +               # Add 10 to the length for "hundred and"
                3 *                     # Add 3 to the length for another "and"
                (b > 2) *               # if the number >= 1000
                (0 < n % c < 101)       # and the bottom portion > 0 and <= 100
    )
print sum(map(l,range(input()+1)))      # For the reader to figure out.


The FizzBuzz-ish String matcher Say that you have a string like this:

abaabbbbbaabba

Count the number of times that a specified character appears in the input string, but only if the character appears only once in a row. For example, if the character is a,

abaabbbbbaabba
^ x      x   ^

The total would be 2 (the aa's wouldn't count because the a appears two times in a row).

How is this related to FizzBuzz?

If the character appears 3 (or a multiple of 3) times in a row, or 5 (or a multiple of 5) times in a row, the counter is decremented instead. If it is a multiple of both 3 and 5 times, the counter is still incremented. Remember that the counter is also incremented if the character appears only once in a row, and it is ignored if the character appears any other number of times in a row (besides the situations described above).

To recap, if the string to match is a,

input            counter (explanation)

a                 1 (single occurence)
aaa               -1(multiple of 3)
aaaaa             -1(multiple of 5)
aaaaaaaaaaaaaaa   1 (multiple of 15)
aa                0 (none of the above)

aba               2 (two single instances)
aaba              1 (one single occurence(+1) and one double occurence(ignored))
aaaba             0 (one single occurence(+1) and one triple (-1)
aaaaaa            -1 (six is a multiple of three)

Reference (ungolfed) implementation in java:

import java.util.Scanner;
import java.util.regex.*;

public class StrMatcher {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in); //Scanner to get user input
        int total = 0;//Running total of matches

        System.out.println("Enter a string: ");
        String strBeingSearched = sc.nextLine(); //String that will be searched

        System.out.println("Enter string to match with: ");
        String strBeingMatched = sc.nextLine(); //Substring used for searching

        //Simple regex matcher
        Pattern pattern = Pattern.compile("(" + strBeingMatched + ")+");
        Matcher matcher = pattern.matcher(strBeingSearched);

        while(matcher.find()){  //While there are still matches

            int length = matcher.end() - matcher.start();
            int numberOfTimes = length/strBeingMatched.length();//Calculate how many times in a row the string is matched

            if((numberOfTimes == 1)||((numberOfTimes % 3 == 0) && (numberOfTimes % 5 == 0))){
                total++; //Increment counter if single match or divisible by 15
            } else if((numberOfTimes % 3 == 0)||(numberOfTimes % 5 == 0)) {
                total--; //Decrement counter if divisible by 3 or 5 (but not 15)
            }

            strBeingSearched = strBeingSearched.substring(matcher.end());
            matcher = pattern.matcher(strBeingSearched); //Replace string/matcher and repeat
        }

        System.out.println(total);
    }
}

The string that will be searched can be any length, but the pattern will only be a single character.
Neither string will have regex special characters.
This is code-golf; shortest program in bytes wins.
No standard loopholes.

Funciton, 1840 bytes

Damn, this language is ungolfable.

This program expects the first character of the input to be the character to search for, and the rest of the input to make the string to search through. This means that aaaba will search for a in the input aaba (and thus output 1). You can separate them with a newline or space (a aaba) but only because the extra newline/space makes no difference to the output.

As always, you can get a nicer-looking rendering (without the line spacing) if you execute $('pre').css('line-height',1) in your browser console.

      ┌───┐
      │╓─╖└─────────────┐
      └╢³╟┐    ┌─────┐ ┌┴┐╓─╖
┌─────┐╙─╜└────┤┌─╖ ┌┴╖│┌┘║¹║
│     ├───────┐└┤²╟─┤·╟┘│ ╙┬╜╔═══════╗
│    ┌┴╖╔═╗┌─╖├┐╘╤╝ ╘╤╝┌┘  └┬╢2097151║
│    │♭║║5╟┤%╟┘└─┴──┐│┌┘┌───┘╚═══════╝
│    ╘╤╝╚═╝╘╤╝╔═╗┌─╖│││┌┴┐┌────┐
│    ┌┴╖   ┌┘ ║3╟┤%╟┘││└┬┘│╔══╗└┐
│  ┌─┤·╟─┐ │  ╚═╝╘╤╝ │└┐  │║21╟┐│
│  │ ╘╤╝ ├─┘┌─────┘  └┐└┐ │╚══╝│└─┐
│ ┌┴╖┌┴╖┌┴╖┌┴╖┌─╖    ┌┴╖│ │┌─╖┌┴─╖│
│┌┤·╟┤?╟┤?╟┤?╟┤+╟────┤³║│ └┤²╟┤>>║└──┐
││╘╤╝╘╤╝╘╤╝╘╤╝╘╤╝    ╘╤╝│  ╘╤╝╘╤═╝╓─╖│
││ │ ┌┴╖┌┴╖┌┴╖┌┴╖╔═╗ ┌┴╖│  ┌┴╖ ├──╢²╟┤
││ └─┤·╟┤·╟┤?╟┤·╟╢1║┌┤·╟┘  │♯║┌┴╖ ╙─╜│
│└──┐╘╤╝╘╤╝╘╤╝╘╤╝╚═╝│╘╤╝   ╘╤╝│¹║┌───┘
└──┐│╔╧╗ └┬─┘ ┌┴╖   │┌┴─╖   │ ╘╤╝│
   ││║1║ ┌┴┐┌─┤?╟───┴┤>>╟┐ ┌┴╖┌┴╖│
   ││╚═╝ └┬┘│ ╘╤╝    ╘══╝│┌┤?╟┤=║│
   │└────┐│╔╧╗     ┌─────┘│╘╤╝╘╤╝│
╔═╗└────┐│├╢0║╔══╗┌┴╖┌─╖ ╔╧╗   └─┘
║ ║     │└┘╚═╝║21╟┤×╟┤♯╟┐║0║
╚╤╝     └──┐  ╚══╝╘═╝╘═╝│╚═╝
 │┌──┴────╖└────────────┘
 ││int→str║
 │╘══╤════╝
┌┴─╖┌┴╖┌─╖╔╗
│>>╟┤³╟┤¹╟╢║
╘═╤╝╘═╝╘═╝╚╝
╔═╧╗
║21║
╚══╝

(1840 bytes when encoded as UTF-16.)

Explanation

¹ returns the first character of a string.
² counts the number of occurrences of a character at the start of a given string. For example, given the character a and the string aaba, it returns 2. For a and baa, it returns 0.
³ calls ² to get the number of characters at the start, examines whether the number is divisible by 3 and 5 and whether it is equal to 1 and determines the proper increment/decrement. It also removes one extra character from the start of the string (e.g. given aaabba it removes 3+1=4 characters, giving ba). Then it calls itself recursively with the shorter string and adds the result.
The main program calls ¹ to remove the first character from the input and calls ³ with that character and the rest of the string as separate arguments.


Directories required for creating a folder tree Say that you have this folder structure on your coumputer:

/a

And you want to have these folders:

/a/b
/a/c
/b/b

You would need to create four directories, using mkdir for example:

mkdir /a/b
mkdir /a/c
mkdir /b
mkdir /b/b

Write a program that, given existing and required directory structures, will output the directories that need to be created.

Input

First line has two numbers: n, number of existing directories, and m, number of required directories
Next n lines has the list of existing directories
Next m lines has the list of required directories

Example:

1 3
/a
/a/b
/a/c
/b/b

Output

Directories you need to create

Example:

/a/b
/a/c
/b
/b/b

Python

In Python, you would just use os.makedirs(). See the docs at the bottom of this post
import sys

num_existing, num_required = map(int, next(sys.stdin).split())

sep = "/"
directory = {}

for i,path in enumerate(s.rstrip("\n") for s in sys.stdin):
    d = directory
    base = ""
    for p in path.split(sep)[1:]:
        base += sep+p
        if p not in d:
            if i >= num_existing:
                print base
            d[p]={}
        d = d[p]

Python docs for os.makedirs()
>>> import os
>>> help(os.makedirs)

Help on function makedirs in module os:

makedirs(name, mode=511)
    makedirs(path [, mode=0777])

    Super-mkdir; create a leaf directory and all intermediate ones.
    Works like mkdir, except that any intermediate path segment (not
    just the rightmost) will be created if it does not exist.  This is
    recursive.


Carve a square from a string Your challenge today is to take a multiline string, and output the biggest square contained within the string that includes the top left corner.

A square string is one where:

Each line has the same number of characters
The number of characters on each line is equal to the number of lines.

Consider the following possible input string:

abcde
fgh
asdf
foobar

The largest square you can take from it that includes the first character (the a in the topleft corner) is this:

abc
fgh
asd

There can't be a square of side-length 4, because the second line isn't long enough. Now consider this potential input:

a
bcd
edf
ghi

The biggest square here is just a. The 3x3 square formed in the bottom doesn't contain the very first character, and doesn't count.

Here's a few more test cases:

a

a

abc
def
gh

ab
de

ab
cd

ab
cd

abcde
fghij
klm
no

abc
fgh
klm

a
b

a

You may require input to be delimited by your choice of LF, CR, or CRLF.

The newline character(s) are not considered part of the line's length.

You may require there to be or to not be a trailing newline in input, which doesn't count as an additional line.

Input is a string or 1D char array; it is not a list of strings.

You may assume input is non-empty and all lines are non-empty, and that it only contains printable ASCII, including spaces and newlines (for the line delimiter) but not tabs.

This is code-golf, fewest bytes wins!

Husk, 13 bytes

►oΛ≈S+TzṀ↑Nḣ¶

Try it online!

Explanation

►oΛ≈S+TzṀ↑Nḣ¶  Implicit input, say "ab\nc".
            ¶  Split at newlines: ["ab","c"]
           ḣ   Take prefixes: [["ab"],["ab","c"]]
       z  N    Zip with [1,2,3..
        Ṁ↑     by taking that many characters from each row: [["a"],["ab","c"]]
►o             Find rightmost element that satisfies this:
  Λ            all strings in
    S+T        the list concatenated to its transpose
   ≈           have the same length: ["a"]
               Implicitly print separated by newlines.


Conway's Hello World It is often said, that all programmers should be able to write a "hello world" program in any programming language after a few glances on that language (And quicksort after a few more glances).

As the Conway's Game of Life is Turing complete (so it qualifies as a general-purpose programming language), the problem is self-explanatory:

Create a "Hello World!" application using only Conway's Game of Life!
The only valid entry is an initial state for the Conway's Game of Life, which:

does not contain any recognizable shape resembling the text "Hello World!"
will contain a recognizable shape resembling the text "Hello World!" within a reasonable number of cycles (it should not run for more than a couple of minutes on a good PC - this enables billions of cycles and should be enough)
the area where the "Hello World!" text will appear should be empty in the initial state! (Otherwise the problem would be way too easy) If no one manages to do it, we might reduce this requirement to "mostly empty"

Scoring:

The winner will be based on the number of upvotes in approximately one week after the first valid submission.

Guidelines for voting:

more elaborate and beautiful output should be worth more
output which is stable over many cycles should be worth more than one which fades away to be unrecognizable in the next cycle.
a solution locked into a perpetual cycle, or starting from an interesting pattern is worth the most, because it proves intelligent design of the state, and not just random trial and error with a reverse simulation.

The entry should be in a format readable by at least one of the notable simulators or an online simulator which the answerer links to. Links (to an animation or a simulator set to the initial state) are also accepted, even encouraged. If the output is not visible within a few cycles, the entry should specify after which cycle will the result be visible.

Edit:

There can be some slight tolerance in the phrase to be generated. It can be "Hello, World!", "hello, world" "HELLO WORLD!" etc.

My first attempt to this, a relatively simple solution. It fires a couple of glider barrels. Each pair of gliders turns into a block, which then form the text. This process takes about 16000 generations (you can set a frame skip or use the superstep button in my simulator).

Direct Link. Move around with right mouse, zoom with mouse wheel.

Link to .rle file (also works with Golly)

Image of the pattern 32:1:


Solve the 14-Pegs puzzle Introduction

A common puzzle involves a triangular board with 15 holes for tees/pegs as shown in the image below:

Starting with all the pegs in the board except for a hole at the top, the point of the puzzle is to jump pegs over one another like checkers in such a way to leave exactly one peg left.  The only valid move is to jump one peg over an adjacent peg in any direction into an empty hole.  The peg that was jumped is then removed from the board.  Play finishes when there remain no valid moves.

Spec

Your job is to write a program that can find a complete solution to the peg puzzle, i.e., one that leaves exactly one peg left.  There are multiple possible solutions, so your program just needs to print one.

Your program will receive no input.  You are not allowed to read data from any outside source.
Print out the list of 13 moves that gives a result of 1 peg remaining using this format:

  Peg 1 jumps Peg 3 to Hole 6.

The holes/pegs are numbered from top to bottom, left to right, so that the top peg/hole is 1, numbering until the bottom-right is 15.
Your program must find the solution at runtime.  Printing out a solution directly by any means other than solving it in the program is an automatic disqualification.
Bonus: receive 10 bonus points if you can output multiple unique solutions (can just print separated by blank lines).
Bonus: receive 5 bonus points if the number 15 appears nowhere in your source code.

Scoring

This is code-golf, so the shortest solution (by byte count) that prints out a correct answer will be the winner.  Bonus points are subtracted from your total byte count.  Please provide a sample output of running your program as well as a link to ideone or some similar site if possible demonstrating the execution of your program.

Ruby, score 240 238 234 = 249 - 10 - 5
s=->t,r,c{c>0?(t+t.reverse).gsub(/[A-O]{2}[a-o]/){|j|s[t.tr(j,j.swapcase),r+"Peg #{j[0].ord-64} jumps Peg #{j[1].ord-64} to Hole #{j[2].ord-96}.\n",c-1]}:$><<r+"\n"}
s["aBD,BDG,DGK,CEH,EHL,FIM,aCF,CFJ,FJO,BEI,EIN,DHM,DEF,GHI,HIJ,KLM,LMN,MNO,","",13]

A plain ruby implementation which prints all possible solutions to this puzzle (takes less than a minute on my computer). The first lines of output can be seen here:
Peg 6 jumps Peg 3 to Hole 1.
Peg 4 jumps Peg 5 to Hole 6.
Peg 1 jumps Peg 2 to Hole 4.
Peg 14 jumps Peg 9 to Hole 5.
Peg 7 jumps Peg 8 to Hole 9.
Peg 12 jumps Peg 13 to Hole 14.
Peg 10 jumps Peg 6 to Hole 3.
Peg 4 jumps Peg 5 to Hole 6.
Peg 3 jumps Peg 6 to Hole 10.
Peg 15 jumps Peg 10 to Hole 6.
Peg 6 jumps Peg 9 to Hole 13.
Peg 14 jumps Peg 13 to Hole 12.
Peg 11 jumps Peg 12 to Hole 13.

Peg 6 jumps Peg 3 to Hole 1.
Peg 4 jumps Peg 5 to Hole 6.
Peg 1 jumps Peg 2 to Hole 4.
Peg 14 jumps Peg 9 to Hole 5.
Peg 7 jumps Peg 8 to Hole 9.
...

And the online example can be found here.


Automated Bulls and Cows Player This is a code golf challenge to see the shortest implementation of an automated guesser in the pen and paper game bulls and cows.

The game works as follows:

A (usually 4 digit) secret code with only distinct integers 0-9 is picked by one player. A second player guesses codes that each receive a rank. This rank contains 1 bull for every digit that is correctly placed in the guess, and 1 cow for every digit in the guess that is in the secret code, but not in the correct location within the code.

The code should assume a format as follows:

The combination will be a 4 digit number containing only distinct digits 0-9. (eg. 0123 is valid, 0112 is not)
After each guess, you will be given a string as a response telling you how many bulls and how many cows are in your answer.  It will be formatted as xByC, in which x is the number of bulls and y is the number of cows. (i.e. 4B0C means you have won). You can assume that a made-up method called "rateGuess", which takes your guess as a string will provide the response.

Pyth - 11 bytes
This will eventually guess the correct answer. On average 2500 tries. Literally just takes random guesses no matter what the input is. Since you can't define rateGuess in pyth just takes (uneeded) input from stdin and outputs to stdout.
Ofql{T4^UT4

O         Pick random
 f        filter
  ql{T4   set length is four (checks for duplicates)
  ^  4    Caretesian product with 4 repeats
   UT     Unary range till 10


Menger Sponge Generator Challenge

My challenge, is for you to generate a Menger Sponge based on the level/iteration given. You need to draw it in 3d, anyway you can.

Examples

Inputs: 0, 1, 2, 3

Outputs:

Background Information

What is a Menger Sponge

  In mathematics, the Menger sponge (also known as the Menger universal curve) is a fractal curve. It is a three-dimensional generalization of the Cantor set and Sierpinski carpet

Properties

  See https://en.wikipedia.org/wiki/Menger_sponge#Properties (too long to copy and paste)

How do I construct the sponge?

  Begin with a cube  (first image).

  Divide every face of the cube into 9 squares, like a Rubik's Cube. This will sub-divide the cube into 27 smaller cubes.

  Remove the smaller cube in the middle of each face, and remove the smaller cube in the very center of the larger cube, leaving 20 smaller cubes (second image). This is a level-1 Menger sponge (resembling a Void Cube).

  Repeat steps 2 and 3 for each of the remaining smaller cubes, and continue to iterate ad infinitum.

  The second iteration gives a level-2 sponge (third image), the third iteration gives a level-3 sponge (fourth image), and so on. The Menger sponge itself is the limit of this process after an infinite number of iterations.

Credit

Background info taken from this wikipedia page on Menger Sponges.

Good Luck!

Remember this is code-golf the shortest program wins!

anyway.. here is the 3D answer
Mathematica, 15 bytes
#~MengerMesh~3&

new built-in in Mathematica 11.1
input

3

output


Valid term from quadratic sequence? You are given four numbers. The first three are \$a\$, \$b\$, and \$c\$ respectively, for the sequence:

$$T_n=an^2+bn+c$$

You may take input of these four numbers in any way. The output should be one of two distinct outputs mentioned in your answer, one means that the fourth number is a term in the sequence (the above  equation has at least one solution for \$n\$ which is an integer when \$a\$, \$b\$, \$c\$ and \$T_n\$ are substituted for the given values), the other means the opposite.

This is code golf, so the shortest answer in bytes wins. Your program should work for any input of \$a, b, c, T_n\$ where the numbers are negative or positive (or 0), decimal or integer. To avoid problems but keep some complexity, non-integers will always just end in \$.5\$.  Standard loop-holes disallowed.

Test cases

a   |b   |c   |T_n |Y/N
------------------------
1   |1   |1   |1   |Y     #n=0
2   |3   |5   |2   |N
0.5 |1   |-2  |-0.5|Y     #n=1
0.5 |1   |-2  |15.5|Y     #n=5
0.5 |1   |-2  |3   |N
-3.5|2   |-6  |-934|Y     #n=-16
0   |1   |4   |7   |Y     #n=3
0   |3   |-1  |7   |N
0   |0   |0   |1   |N
0   |0   |6   |6   |Y     #n=<anything>
4   |8   |5   |2   |N

JavaScript (ES7), 70 bytes
Returns a Boolean value.

(a,b,c,t)=>(t-=c,(a*=2)?(x=(b*b+2*a*t)**.5-b)%a&&(x+b+b)%a:b?t%b:t)==0

Try it online!
How?
For the sake of clarity, we define \$d = T_n-c\$. (The same variable \$t\$ is re-used to store this result in the JS code.)
Case \$a\neq0\$
The equation really is quadratic:
$$T_n=an^2+bn+c\\
an^2+bn-d=0$$
With \$a'=2a\$, the discriminant is:
$$\Delta=b^2+2a'd$$
and the roots are:
$$n_0=\frac{-b-\sqrt{\Delta}}{a'}\\
n_1=\frac{-b+\sqrt{\Delta}}{a'}$$
The equation admits an integer root if \$\sqrt{\Delta}\$ is an integer and either:
$$\begin{align}&-b-\sqrt{\Delta}\equiv 0\pmod{a'}\\ \text{ or }&-b+\sqrt{\Delta}\equiv 0\pmod{a'}\end{align}$$
Case \$a=0, b\neq0\$
The equation is linear:
$$T_n=bn+c\\
bn=d\\
n=\frac{d}{b}$$
It admits an integer root if \$d\equiv0\pmod b\$.
Case \$a=0, b=0\$
The equation is not depending on \$n\$ anymore:
$$T_n=c\\
d=0$$


Trumpscript, 303 285 244 231 226 bytes

make i 1000005-1000000
as long as,i;:
make i,i - fact;
say "_|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|"
say "___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|__"!
America is great

I would like to say this is one of the most verbose languages where almost everything fails to compile into a working program.

Apparently whether - works instead of minus is completely up to the interpreter and sometimes works. This time it did so I'm putting it in as golfed.

Abuses the fact Trumpscript is written in Python and therefore fact when used as an integer is one.

Golfing tips welcome.


The symmetry of months Introduction

Some months are completely symmetric, meaning they have central symmetry as well as reflection symmetry, like February of 2010:

     February 2010
┌──┬──┬──┬──┬──┬──┬──┐
│  │  │  │  │  │  │  │
├──┼──┼──┼──┼──┼──┼──┤
│  │  │  │  │  │  │  │
├──┼──┼──┼──┼──┼──┼──┤
│  │  │  │  │  │  │  │
├──┼──┼──┼──┼──┼──┼──┤
│  │  │  │  │  │  │  │
└──┴──┴──┴──┴──┴──┴──┘

Some months have only central symmetry, like February of 1996 or current month, the April of 2018:

      February 1996
          ┌──┬──┬──┬──┐
          │  │  │  │  │
 ┌──┬──┬──┼──┼──┼──┼──┤
 │  │  │  │  │  │  │  │
 ├──┼──┼──┼──┼──┼──┼──┤
 │  │  │  │  │  │  │  │
 ├──┼──┼──┼──┼──┼──┼──┤
 │  │  │  │  │  │  │  │
 ├──┼──┼──┼──┼──┴──┴──┘
 │  │  │  │  │
 └──┴──┴──┴──┘

       April 2018  ┌──┐
                   │  │
 ┌──┬──┬──┬──┬──┬──┼──┤
 │  │  │  │  │  │  │  │
 ├──┼──┼──┼──┼──┼──┼──┤
 │  │  │  │  │  │  │  │
 ├──┼──┼──┼──┼──┼──┼──┤
 │  │  │  │  │  │  │  │
 ├──┼──┼──┼──┼──┼──┼──┤
 │  │  │  │  │  │  │  │
 ├──┼──┴──┴──┴──┴──┴──┘
 │  │
 └──┘

And some are asymmetric, like the previous month, the March of 2018:

      March 2018
         ┌──┬──┬──┬──┐
         │  │  │  │  │
┌──┬──┬──┼──┼──┼──┼──┤
│  │  │  │  │  │  │  │
├──┼──┼──┼──┼──┼──┼──┤
│  │  │  │  │  │  │  │
├──┼──┼──┼──┼──┼──┼──┤
│  │  │  │  │  │  │  │
├──┼──┼──┼──┼──┼──┼──┘
│  │  │  │  │  │  │
└──┴──┴──┴──┴──┴──┘

Task

Take an input in form of a date, e.g.:

2018.04
2018.03
2010.02
1996.02

Output the corresponding symmetry, e.g.

2018.04 -> centrally symmetric
2018.03 -> asymmetric
2010.02 -> symmetric
1996.02 -> centrally symmetric

Rules

This is code golf, so the smallest number of bytes wins.
Standard loopholes are obviously not allowed.
Assume that the week starts with Monday (thanks to Angs and Arnauld for suggestion).
Consider only years between 1900 and 2100 (inclusive).
The input and output formatting rules are permissive, meaning you can use any equivalent format that is native to the language of your choice.
Base your solution on the Gregorian calendar.

JavaScript (ES6), 55 bytes
Saved 6 bytes thanks to @Neil
Takes input in currying syntax (year)(month). Returns false for asymmetric, true for centrally symmetric and 0 for completely symmetric.
y=>m=>(n=(g=_=>new Date(y,m--,7).getDay())()+g())&&n==7

Try it online!
How?
We define the function g() which returns the weekday of yyyy/mm/01, as an integer between 0 = Monday and 6 = Sunday.
g = _ => new Date(y, m--, 7).getDay()

Because getDay() natively returns 0 = Sunday to 6 = Saturday, we shift the result to the expected range by querying for the 7th day instead.
Then we define:
n = g() + g()

Because the constructor of Date expects a 0-indexed month and because g() decrements m after passing it to Date, we actually first compute the weekday of the first day of the next month and then add that of the current one.
Completely symmetric months
Completely symmetric months start with a Monday and are followed by a month which also starts with a Monday. This is only possible for February of a non-leap year.
- Feb --------------    - Mar --------------
Mo Tu We Th Fr Sa Su    Mo Tu We Th Fr Sa Su
--------------------    --------------------
01 02 03 04 05 06 07    01 02 03 04 05 06 07
08 09 10 11 12 13 14    08 09 10 11 12 13 14
15 16 17 18 19 20 21    15 16 17 18 19 20 21
22 23 24 25 26 27 28    22 23 24 25 26 27 28
                        29 30 31

This leads to n = 0.
Centrally symmetric months
Centrally symmetric months are months for which the sum of the weekday of their first day and that of the next month is 7.
- M ----------------    - M+1 --------------
Mo Tu We Th Fr Sa Su    Mo Tu We Th Fr Sa Su
--------------------    --------------------
 0  1 [2] 3  4  5  6     0  1  2  3  4 [5] 6
--------------------    --------------------
      01 02 03 04 05                   01 02
06 07 08 09 10 11 12    03 04 05 06 07 07 09
13 14 15 16 17 18 19    ...
20 21 22 23 24 25 26
27 28 29 30 31

Hence the second test: n == 7.

No built-in, 93 bytes
Uses Zeller's congruence. Same I/O format as the other version.
y=>m=>(n=(g=_=>(Y=y,((m+(m++>2||Y--&&13))*2.6|0)+Y+(Y>>2)-6*~(Y/=100)+(Y>>2))%7)()+g())&&n==7

Try it online!


Simultaneous equations With equations that have more than one unknown, simultaneous equations can be used in solving for them. This challenge will only deal with linear equations with two unknowns, to make things as elementary as possible.

The program should take two lines of input from stdin, each containing a linear equation with two unknowns (x and y). Output should be in the form x=<x-value>, y=<y-value>, where the angled bracketed text should be replaced by the appropriate value. Non-integer values can be outputted in either decimal point form rounded to at least 3 decimal places or until the fraction terminates (eg. 1/2 would be 0.5 not 0.500), or simplest (improper, not mixed) fraction form (as all results will be rational). If the equations are unsolvable (ie are parallel but not equivalent), output Unsolvable. If the equations are equivalent and would therefore have an infinite number of solutions, output Degenerate.

The use of external modules is not allowed. Also, any library functions that solve equations (this applies especially to Mathematica) are not allowed.

Each equation in the input will be in general form, with no whitespace. If a coefficent or the constant term is 0, the whole term will not appear, and if a coefficient is ±1, only the pronumeral will appear.

Test cases:

Input:                 Input:                 Input:                 Input:
7x+4y-8=0              4x+3y+32=0             x-y=0                  2x+5y-1=0
x-8y+1=0               x-4=0                  x-y+5=0                2x+5y-1=0
Output:                Output:                Output:                Output:
x=1, y=1/4 (or 0.25)   x=4, y=-16             Unsolvable             Degenerate

This is once again code-golf, so shortest code wins.

Python 3, 250

I reuse the code for parsing the input for each of the "coefficients" of x, y, and "=" by putting it into a string and multiplying it the right number of times.

For the "coefficient of =" case to work (absence means 0, not 1, like for x and y), the last "0" of the input has to be thrown away (and then magic takes over...).
Makes heavy use of short circuiting in logic expressions, and of False==0.

Uses Python's feature of leaving off trailing zeros of floats (finding out if the solution is an integer is still necessary).

exec((("R=input()[:-1];"+"*_,R=I,*_=R.split(%r);%s=R!=I and int(I in'+-'and I+'1'or I);"*3)*2)%tuple("xXyY=Cxxyy=c"))
d,u,v=X*y-Y*x,C*y-c*Y,X*c-x*C
print(d and"x=%s, y=%s"%(u%d and-u/d or-u//d,v%d and-v/d or-v//d)or"UDnesgoelnvearbaltee"[u==v==0::2])


Finding number of digits in an integer Given an integer n as input write a program to output the numbers of digit in it.

Input

12346

456

Output

5

3

Constraint

n<=10^9

GolfScript, 1 character

,

, means length...

Edit: You seem to have changed your question... please don't do that, but I still have a solution:

GolfScript, 12 7 characters (for multiline)

n%{,n}/

Thanks @Howard for reminding me about n to push newline and using separate strings instead of one, to save 5 chars ;)

Solutions that work with negative numbers:

GolfScript, 5 (for negative)

'-'-,

GolfScript, 11 (for multiline and negative)

n%{'-'-,n}/


Maximum distance to station Looking at the following hackerrank problem:
https://www.hackerrank.com/challenges/flatland-space-stations
You are given a number n where cities can be at indices 0 to n-1 and also given an unsorted list of indices of cities where there are stations. The goal is to find the maximum distance from a city to a station. For example, for n=5 and the station list [0,4], the answer would be 2 since index 2 is 2 away from both 0 and 4 and all other stations at indices 0-4 are closer to one of 0 or 4.
I was looking for a short Python3 solution. The function body takes in the number n and a list c (like [0,4] in the example). After some revisions, I came up with the 69 character function body below:
c.sort();return max(t-s for s,t in zip([-c[0]]+c,c+[2*n-c[-1]-1]))//2

Curious about whether anyone can come up with a shorter body.

Distance solution:
Python 3, 52 Bytes

return max(min(abs(l-c)for l in s)for c in range(n))

Try it online!
Index solution (added after my first two comments):

Python 3, 59 bytes

return max((min(abs(l-c)for l in s),c)for c in range(n))[1]

Try it online!

Edit: Switched back to Distance solution,
Thanks to Jonathan Allan for -1 Byte


Forecast the weather Write the shortest program to forecast the weather for the next 7 days

The input (from stdin) is the weekday and the season

The output (to stdout) is seven lines weekday and the temperature in centigrade

The weekdays begin on the input weekday

The temperatures are random numbers with the range depending on the season

Spring 10 - 30 degrees
Summer 20 - 40 degrees
Autumn  5 - 25 degrees  (Fall is a synonym for autumn)
Winter -5 - 15 degrees

Sample Input

Thursday Winter

Sample Output

Thursday -1
Friday 3
Saturday 8
Sunday 7
Monday 10
Tuesday 10
Wednesday -1

Your program must not have identical output every time it is run with the same input

Ruby 1.8, 95 characters

#!ruby -nrdate
7.times{|i|puts (Date.parse($_)+i).strftime"%A #{"\023\004\016\016\035"[$_[-3]%5]-9+rand(21)}"}

The character escapes inside the string should be replaced by the character literals they represent.

Found a shorter way to pack the data, Ruby 1.9 would be 4 characters longer now (add .ord after $_[-3]).
112 -> 105 by stealing Joey's idea of not splitting the input.
105 -> 101. Note that the first line is actually parsed by the Ruby interpreter itself, so it even works when running the solution like echo "Thursday Winter" | ruby1.8 forecast.rb
101 -> 96. Stole Joey's idea again to just embed the temperatures into a string instead of an array.
Whoops, just noticed it should be rand(21), not rand(20).
96 -> 95. Removed unnecessary whitespace.


Multigraphs with a given degree sequence This challenge will give you an input of a degree sequence in the form of a partition of an even number. Your goal will be to write a program that will output the number of loop-free labeled multigraphs that have this degree sequence.

Example

For example, given the input [3,3,1,1], you should output the number of labeled multigraphs on four vertices \$\{v_1, v_2, v_3, v_4\}\$ such that \$\deg(v_1) = \deg(v_2) = 3\$ and \$\deg(v_3) = \deg(v_4) = 1\$. In this example, there are three such multigraphs:

See Gus Wiseman's links on OEIS sequence A209816 for more examples.

Target data

input           | output
----------------+--------
[6,2]           | 0
[5,3,2]         | 1
[3,3,1,1]       | 3
[4,3,1,1,1]     | 6
[4,2,1,1,1,1]   | 10
[1,1,1,1,1,1]   | 15
[3,2,2,2,1]     | 15
[2,2,2,2,2]     | 22
[7,6,5,4,3,2,1] | 7757

Challenge

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

Haskell, 57 bytes

f(h:t)=sum[f l|l<-mapM(\n->[0..n])t,sum t-sum l==h]
f _=1

Try it online!


Find Abecedarian Words An Abecedarian Word is a word whose letters are in alphabetical order. Your goal is to write a program that outputs all abecedarian words from a given lexicon.
Rules:

Standard Loopholes are forbidden.

If a word contains punctuation, diacritical marks, or any characters other than ASCII alphabet characters (A-Za-z), remove the entire word.

Words that are abecedarian in ASCII are not necessarily abecedarian for this challenge. For example 'Maddox' shouldn't be considered abecedarian.

Your program should work with any lexicon, but for testing purposes, this one can be used. (If my code works properly) It contains 588 587 abecedarian words that follow the above rules. The lexicon does not count towards your byte total. https://gist.githubusercontent.com/wchargin/8927565/raw/d9783627c731268fb2935a731a618aa8e95cf465/words

As per the request of @Olivier Grégoire, here are the Abecedarian words from the lexicon:
A Abbott Abby Abe Abel Ac Acrux Aden Ag Ainu Al Alps Am Amos Amy Ann Apr Ar Art As At Au Av B BMW Be Begin Bell Bellow Ben Benny Benz Berry Bert Bess Best Betty Bi Biko Bill Billy Bk Blu Boru Br Btu C Cd Celt Cf Chi Chimu Chou Ci Cl Cm Co Coors Cory Cox Coy Cr Crux Cruz Cs Cu D Dee Deimos Deity Del Dell Dem Denny Depp Di Dino Dior Dis Dix Dot Dow Dr E Eggo Elmo Eloy Emmy Emory Enos Er Es Eu F Finn Finns Flo Flory Fm Fox Fr Fry G Gil Gill Ginny Gino Ginsu Gipsy Guy H Hill Hiss Ho Hz I Ill In Io Ir It Ivy J Jo Joy Jr K Knox Kory Kr L Ln Lot Lott Lou Lr Lt Lu Luz M Mn Mo Moor Moors Mort Moss Mott Mr Mrs Ms Mt N Nov Np O Oort Orr Os Oz P Pt Pu Q R Ru Rx S St Stu T Ty U V W X Y Z a abbess abbey abbot abet abhor abhors ably abort abuzz accent accept access accost ace aces achoo achy act ad add adder adders adds adept ado adopt ads adz aegis aery affix afoot aft aglow ago ah ahoy ail ails aim aims air airs airy all allot allow alloy ally almost alms am ammo amp amps an annoy ant any apt art arty as ass at ax ay b be bee beef beefs beefy been beep beeps beer beers bees beet befit beg begin begins begot begs bell bellow bells belly below belt bent berry best bet bevy bill billow billowy bills billy bin bins biopsy bit blot blow boo boor boors boos boost boot booty bop bops boss bossy bow box boy brr buy buzz by c cell cello cellos cells cent chi chill chills chilly chimp chimps chin chino chinos chins chintz chip chips chit choosy chop choppy chops chow city clop clops clot cloy coo coop coops coos coot cop cops copy cost cosy cot cow cox coy crux cry cs d deem deems deep deeps deer deers deft defy deity dell dells demo demos den dens dent deny dew dewy dill dills dilly dim dims din dins dint dip dips dirt dirty dis diss ditty divvy do door doors dopy dory dos dot dotty dry e eel eels eery effort egg eggs egis ego egos eh ell ells elm elms em empty ems emu envy err errs es ex f fill fills filly film films filmy fin finny fins fir firs first fist fit fix fizz floor floors flop floppy flops floss flow flu flux fly foot fop fops for fort forty fox foxy fry fuzz g ghost gill gills gilt gimpy gin gins gipsy girt gist glop glory gloss glossy glow gnu go goo goop gory got gs guy h hi hill hills hilly hilt him hims hint hip hippy hips his hiss hit ho hoop hoops hoot hop hops horsy hos host hot how i ill ills imp imps in inn inns ins is it ivy j jot joy k kW knot knotty know ks l lo loop loops loopy loot lop lops lorry loss lost lot low lox ls m moo moor moors moos moot mop mops moss mossy most mow ms mu my n no nor nosy not now nu o oops opt or ow ox p pry psst q r rs s sty t tux u v w x y z

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

Jelly, 9 bytes
fØẠŒlÞ$ƑƇ

Try it online!
-3 bytes thanks to Nick Kennedy
fØẠŒlÞ$ƑƇ  Main Link
        Ƈ  Keep elements that are
       Ƒ   Invariant when
.[][.]$    Last two links combined, but [ØẠ][ŒlÞ] is an LCC, so it takes another
f          Filtered to keep
 ØẠ        Alphabetical characters
     Þ     And sorted by
   Œl      Lowercase

Basically, "keep elements that are invariant when you filter out non-alphabetical characters and sort alphabetically". Jelly's sort is stable.


Rebuilding an ASCII City +--+
+--+ |  | +--+ +--+
|  | |  | |  | |  |
+--+ +--+ +--+ +--+

The people of ASCIIville are rebuilding their city and are sketching out new blueprints. Your job is to draw their new city based on how many buildings they want.

The input will be how many buildings there are. Each building is half the hight of the input (rounded up if odd), not including the top and bottom of the building.

Let's draw a basic example of 4

+--+ +--+ +--+ +--+
|  | |  | |  | |  |
|  | |  | |  | |  |
+--+ +--+ +--+ +--+

As you can see here, there are two |s in every building because the input was four. But there's a catch! (meaning the example above is incorrect, and the example at the top of this post is the real output for 4)

For each building that isn't a prime number, its height goes down by one. If the number is divisible by 3, 5, or 10, it goes down one more. If it's divisible by two or more of those numbers, the amount deducted adds up (10 is divisible by 10 and 5, and it's not a prime, so it gets deducted by 3).

Let's look at an example with an input of 5.

     +--+
+--+ |  | +--+ +--+ +--+
|  | |  | |  | |  | |  |
|  | |  | |  | |  | |  |
+--+ +--+ +--+ +--+ +--+

Here's an example of 7

     +--+                     +--+
+--+ |  | +--+ +--+ +--+      |  |
|  | |  | |  | |  | |  | +--+ |  |
|  | |  | |  | |  | |  | |  | |  |
|  | |  | |  | |  | |  | |  | |  |
+--+ +--+ +--+ +--+ +--+ +--+ +--+

And an example of 10

     +--+                     +--+
+--+ |  | +--+ +--+ +--+      |  | +--+
|  | |  | |  | |  | |  | +--+ |  | |  | +--+
|  | |  | |  | |  | |  | |  | |  | |  | |  | +--+
|  | |  | |  | |  | |  | |  | |  | |  | |  | |  |
|  | |  | |  | |  | |  | |  | |  | |  | |  | |  |
+--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+ +--+

And back to 6

     +--+
+--+ |  | +--+ +--+ +--+
|  | |  | |  | |  | |  | +--+
|  | |  | |  | |  | |  | |  |
+--+ +--+ +--+ +--+ +--+ +--+

Rules:

If a number gets deducted so much that it's height is less than or equal to zero, it is not shown but a space is left for it (I don't believe this is possible, 6 is the closest I've found to reaching zero).
Trailing spaces are allowed.
The width of each building must be 2.
Your input can be from stdin or encoded into the program.
Your program must be a full program, no functions.
Your program must be able 4-15 builds. 0-3 and negative numbers aren't needed and are not specified to do anything, meaning they can throw an error, print garbage, or do nothing.

CJam, 68 66 58 55 bytes

This is too long for now. But a start.

ri:K"!;tK"206b4b<{S5*a*"+--+ "a:I+K)2/)"|  | "e]I+}%zN*

UPDATE: Now hardcoding for inputs till 15 instead of calculating the offset. Suggestion by Sp3000

Try it online here


ASCII-art to numbers Inspired by Digits in their lanes

Input:

An ASCII-art of width ≤ 11, consisting of spaces and #. (You can choose any two distinct characters instead.) Example:

     #
    ###
     #
     #
    # #
   #   #
  #     #
 #  ###  #
#   ###   #
###########
#         #
#         #
#   ###   #
#   ###   #
#   ###   #
###########

Output:

A list of integers, with one element for each line of the input.
If you put a hash in each decimal digit's lane, including the minus sign, in
the order -0123456789. Duplicated digits are allowed, but ignored. The order of the digits in the output is not important.
Possible outputs for the above input include:

[ 4, 345, 4, 4, 35, 26, 17, 34580, -3459, -9876543210, -9, -9, -3459, -3459, -3459, -1234567890 ]
[ 4444444, 5345354354, 4, 44, 535, 2666, 71, 85430, -3495939495, -93678132645160234, -99, -99999, -934539, -935439, -9534, -9876543210 ]

Note that you have to distinguish between 0 and -0. If your output format doesn't support that, you can say there is a special value for -0 (e.g. None).

Leading zeros

If a number is 0 (or -0), the zero is always counted.

Else, you have to move the zero after the first digit (not necessarily next to it): For example, -09 stands for - and 9, so you have to output -90 instead. So, even if you output the string "-09" where -, 0 and 9 are #, that is not right.

In your output, leading zeroes are not counted (that is, the output is the same as if those leading zeroes are removed). This does also include zeroes directly after the minus signs.

Here are some examples for clarification:

-0123456789    OK           not OK
##          -> -0
###         -> -10          -01
##        # -> -90          -09
 ##         -> 10           01
  #         -> 01           10

This does also apply when you output a string!

General rules

You can assume that in every line, at least one of 0-9 is a # (not empty or only -)
You can submit a program or function
Choose any reasonable input/output format (eg. list of lines, list of characters, etc.)

Scoring

Your score is the number of bytes in your code.
Lowest score wins.

Loopholes

Standard loopholes are forbidden

Examples

Note that there is an infinite number of correct outputs for every input, here,
only one is mentioned. If you need to verify an output, you can usually use an
answer to
Digits in their lanes
and input your output. Then compare it's output with the original input.

     #         4
    ###        345
     #         4
     #         4
    # #        35
   #   #       26
  #     #      17
 #  ###  #     83450
#   ###   # -> -9534
###########    -9876543210
#         #    -9
#         #    -9
#   ###   #    -3459
#   ###   #    -3459
#   ###   #    -3459
###########    -1234567890

 #########     123456780
#         #    -9
#  ##  ## #    -23679
# #   #   #    -159
# #   # # #    -1579
#  ##  ## # -> -23679
#         #    -9
 ##### ###     12346780
     ##        45
     #         4

##   ##  ##    -45890
# # #   #      -137
##  #   #   -> -370
#   #   # #    -379
#    ##  ##    -4589

## ## ## ##    -2356890
#  #     ## -> -289
#  #           -2

##             -0
 ##            10
  ##           12
   ##          23
    ##      -> 34
     ##        45
      ##       56
       ##      67
        ##     78
         ##    89

Jelly, 13 bytes

...turns out it's slightly different to Dylnan's method, I thought they just beat me to it

ṙ€1T€ịØD;”-¤U

A monadic link accepting a list of lists of 1s and 0s which returns a list of lists of characters the output "numbers".

Try it online!

How?

ṙ€1T€ịØD;”-¤U - Link: list of lists of integers (in {0,1})
ṙ€1           - rotate €ach list left by one
   T€         - get the truthy (1-based) indices of €ach
           ¤  - nilad followed by link(s) as a nilad:
      ØD      -   decimal digit characters = "0123456789"
         ”-   -   literal '-' character
        ;     -   concatenate
     ị        - index into (vectorises)
            U - upend (reverses each resulting list of characters)


Shifting Caesars Shifts Description
A Caesar Shift is a very simple monoalphabetic cipher where each letter gets replaced by the one after it in the alphabet. Example:
Hello world! -> IFMMP XPSME!

(IBSLR, EGUFV! is the output for the actual challenge, this was an example of shifting by 1.)
As you can see, spacing and punctuation remain unattuned. However, to prevent guessing the message, all letters are capitalized. By shifting the letters back, the message was deciphered, convenient, but also really easy to decipher by other persons who are supposed not to know what the message means.
So, we'll be helping Caesar a bit by using an advanced form of his cipher: the Self-shifting Caesar Shift!
Challenge
Your task is to write a program or function, that, given a string to encipher, outputs the encrypted string corresponding to the input. The advanced Caesar Shift works like this:
1. Compute letter differences of all adjacent letters:
    1.1. Letter difference is computed like this:

         Position of 2nd letter in the alphabet
        -Position of 1st letter in the alphabet
        =======================================
                              Letter difference

    1.2. Example input: Hello
         H - e|e -  l|l  -  l|l  -  o
         7 - 5|5 - 12|12 - 12|12 - 15 Letter differences: 3; -7; 0; -3
            =3|   =-7|     =0|    =-3

2. Assign the letters continously a letter difference from the list,
   starting at the second letter and inverting the differences:
    2.1. 2nd letter: first difference, 3rd letter: second difference, etc.

    2.2. The first letter is assigned a 1.

    2.3. Example input: Hello with differences 3; -7; 0; -3

         Letter || Value
         =======||======
            H   ||   1
            E   ||  -3
            L   ||   7
            L   ||   0
            O   ||   3

3. Shift the letters by the value x they have been assigned:
    3.1. In case of a positive x, the letter is shifted x letters to the right.
    3.2. In case of a negative x, the letter is shifted |x| letters to the left.
    3.3. In case of x = 0, the letter is not shifted.

    3.4. If the shift would surpass the limits of the alphabet, it gets wrapped around
         Example: Y + Shift of 2 --> A

    3.5. Example input: See the table under 2.3.

                ||       || Shifted
         Letter || Value || Letter
         =======||=======||=========
            H   ||   1   ||    I
            E   ||  -3   ||    B     Program output:
            L   ||   7   ||    S     IBSLR
            L   ||   0   ||    L
            O   ||   3   ||    R

Spaces and other special symbols, such as punctuation are skipped in this process. It is guaranteed that your program will be given a string containing only printable ASCII characters. The output of your function/program must only be in upper case.
This is code-golf, so standard loopholes apply, and may the shortest answer in bytes win!

05AB1E, 28 27 24 bytes

láÇ¥R`XIlvyaiAyk+Aèëy}u?

Try it online!

Explanation

l                          # convert input to lower case
 á                         # keep only letters
  Ç¥                       # compute deltas of character codes
    R`                     # reverse and push separated to stack
      X                    # push 1
       Ilv                 # for each char y in lower case input
          yai              # if y is a letter
             Ayk           # get the index of y in the alphabet
                +          # add the next delta
                 Aè        # index into the alphabet with this
            ëy             # else push y
              }            # end if
            u?             # print as upper case


Parse a variable star designation The variable star designation is an identifier for a variable star (a star that fluctuates in brightness). It consists of either a 1-2 letter code or (when the letter code is no longer sufficient) a 'V' followed by a number. This code is followed by the genitive of the star constellation the star is found in (eg. "RR Coronae Borealis", in short "RR CrB"), and each constellation has their own independent numbering.

The series of variable star designations inside one constellation is as follows:

start with the letter R and continue alphabetically through Z.
Continue with RR...RZ, then use SS...SZ, TT...TZ and so on until ZZ.
Use AA...AZ, BB...BZ, CC...CZ and so on until reaching QZ, always omitting J in both the first and second positions.
After QZ (the 334th designation) abandon the Latin script and start naming stars with V335, V336, and so on (V followed by the full numeric index).

Note: The second letter is never alphabetically before the first, ie. BA for example is an invalid designation. Single letters before R are unused. J never appears in the designation.

Your Task

Parse a variable star designation and return its index in the series of variable star designations!

The input is a string of just the variable star designation (omitting the constellation reference that is usually included in a full variable star designation). It can be assumed to be a valid variable star designation; validation is not part of this challenge.

Output is a number representing at what index in the series the designation is. The index is 1-based.

Test cases:

QV => 330
U => 4
V5000 => 5000
AB => 56

This is code-golf, so the shortest code wins. Standard rules and loopholes apply.

Python 3, 121 bytes

lambda z,a='ABCDEFGHIKLMNOPQ',r='RSTUVWXYZ':int(z[1:])if z[2:]else[t+u for t in['',*r+a]for u in a+r if t<=u].index(z)-15

Try it online!

Explanation

The list comprehension [t+u for t in['',*r+a]for u in a+r if t<=u] evaluates to these strings:

t='':   A  B  C  D  E  F  G  H  I  K  L  M  N  O  P  Q  R  S  T  U  V  W  X  Y  Z
t='R':                                                 RR RS RT RU RV RW RX RY RZ
t='S':                                                    SS ST SU SV SW SX SY SZ
t='T':                                                       TT TU TV TW TX TY SZ
t='U':                                                          UU UV UW UX UY SZ
t='V':                                                             VV VW VX VY VZ
t='W':                                                                WW WX WY WZ
t='X':                                                                   XX XY XZ
t='Y':                                                                      YY YZ
t='Z':                                                                         ZZ
t='A': AA AB AC AD AE AF AG AH AI AK AL AM AN AO AP AQ AR AS AT AU AV AW AX AY AZ
t='B':    BB BC BD BE BF BG BH BI BK BL BM BN BO BP BQ BR BS BT BU BV BW BX BY BZ
...
...
...
t='Q':                                              QQ QR QS QT QU QV QW QX QY QZ

If there are any characters past the first two (z[2:]) then the result is int(z[1:]). Otherwise (i.e. if there are only one or two characters) we look the string up in the list we created and subtract 15 from the index.