Compute the Digit Difference Sum of a Number Consider taking some non-negative integer such as 8675309 and computing the absolute values of the differences between all the pairs of neighboring digits.
For \$8675309\$ we get \$|8-6| = 2\$, \$|6-7| = 1\$, \$|7-5| = 2\$, \$|5-3| = 2\$, \$|3-0| = 3\$, \$|0-9| = 9\$. Stringing these results together yields another, smaller non-negative integer: \$212239\$. Repeating the process gives \$11016\$, then \$0115\$, which by the convention that leading zeros are not written simplifies as \$115\$, which becomes \$04\$ or \$4\$, which can't be reduced any further. Summing all these values up we get \$8675309 + 212239 + 11016 + 115 + 4 = 8898683\$.
Let's define the Digit Difference Sum (or DDS) as this operation of repeatedly taking the digit differences of a number to form a new number, then adding all the resulting numbers to the original.
Here are the first 20 values in the corresponding DDS sequence:
N   DDS(N)
0   0
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10  11
11  11
12  13
13  15
14  17
15  19
16  21
17  23
18  25
19  27

Here are the first 10000 values, the graph for which is quite curious:

Especially since it looks the same when you plot it to 1000 or even 100:

(I'd call it the dentist's staircase...)
Challenge
Write a program or function that takes in a non-negative integer and prints or returns its DDS value. For example, if the input was 8675309, the output should be 8898683.
The shortest code in bytes wins.

Python 2, 73
Luckily, I managed to avoid any string operations.
t=lambda n:n>9and abs(n%10-n/10%10)+10*t(n/10)
g=lambda n:n and n+g(t(n))

g is the function that computes the answer.


1, 2, miss a few, 99, 100 When I was a kid, there was a "really cool" shortcut to count to 100:
1, 2, miss a few, 99, 100
Output the exact string above, in the fewest characters possible, without using these characters: 0, 1, 2, 9

JavaScript (ES6), 43 bytes
Browser only.

_=>atob`MSwgMiwgbWlzcyBhIGZldywgOTksIDEwMA`

Try it online! (with a polyfill)

JavaScript (ES6), 45 bytes

_=>[4-3,5-3,'miss a few',33*3,5*5*4].join`, `

Try it online!


Translate English to English You have been hired by the American embassy in the UK to act as a translator. Being a programmer, you decide to write a program to do a bit of the work for you.
You've found out that often just doing the following things can satisfy Word's spellcheck, which has been set to "English (United States)", somewhat, so you don't have to do as much work later when translating written documents:

All occurrences of "our" can be replaced with "or", e.g. "favourite" -> "favorite", "our" -> "or".
All occurrences of "ise" and "yse" can be replaced with "ize" and "yze", respectively.
All occurrences of "ae" and "oe" can be replaced with "e".
All occurrences of "ll" that have a vowel before them can be replaced with "l".
The ending "re" can re replaced with "er", as long as it is not preceded by a vowel, e.g. "ore" will not be replaced, but "centre" becomes "center".
The ending "xion" can be replaced with "ction", e.g. "connexion" -> "connection" (this is archaic, but whatever).

Write a program or function that takes a string or list of characters as input, performs the replacements mentioned above, and outputs the modified string or list of characters using the standard IO methods.
Rules

A sequence of alphabetical characters is considered a word ([A-Za-z]). Words may be delimited by spaces, hyphens, commas, periods, or other punctuation characters ([^A-Za-z]).
A vowel is one of a, e, i, o, or u.
This is code-golf, so shortest code wins.
Inputs with conflicts are undefined behavior, e.g. if a word ends with "oure", your program can make it "ouer" or "ore".
Your program need only take one pass over the input - it's fine if you replaced something like "rae" and end up with "re" instead of further turning that into "er".
Substitutions may be done on uppercase and/or lowercase letters (you can choose). You may also output the letters in any case you want.

Test cases
Note that not all words have been translated correctly, since the rules described above are not always right. Also note that the text here has mixed case to try to look like normal English, but you can use all lowercase for your input and all uppercase for your output or whatever you want.

Substitutions are bolded or italicized if they are side by side.

Input
---
Output
______
We would like you to analyse something our agencies have discovered.
---
We would like you to analyze something or agencies have discovered.
______
There have been reports of American tourists travelling here in knight's armour.
---
There have been reports of American torists traveling here in knight's armor.
______
An aerosol may be the cause of their transfixion. Their oesophagi must be studied.
---
An erosol may be the cause of their transfiction. Their esophagi must be studied.
______
OURoullisaeisere
---
ORouliseizere
______
Pardon me, I just fell on my keyboard while dodging a knight with a metre-long sword.
---
Pardon me, I just fel on my keyboard while dodging a knight with a meter-long sword.
______
My keysere n'twourkingnowneithre r myhands hellllpme
---
My keyzere n'tworkingnowneither r myhands helllpme
______
Haha, I'm just messing with you. No knights here with 3.28-foot-long swords. That's totally ridiculous.
______
Haha, I'm just messing with you. No knights here with 3.28-foot-long swords. That's totaly ridiculous.

QuadR, 77 75 bytes
-2 thanks to Neil.
our
(i|y)se
ae|oe
([aeiou]l)l
([^aeiou])re\b
xion\b
or
\1ze
e
\1
\1er
ction

Try it online!
The first half of the strings are PCRE patterns while the latter half are their substitutions.


Self-enumerating pangrams Pangrams

  The quick brown fox jumped over the lazy dog.

This is an example of a pangram - a sentence that contains every letter of the alphabet at least once.

A self-enumerating pangram is a sentence that fulfills the criteria to be a pangram by producing an analysis of its own letter count.

An example of achieving this is the sentence

  This pangram contains four As, one B, two Cs, one D, thirty Es, six Fs, five Gs, seven Hs, eleven Is, one J, one K, two Ls, two Ms, eighteen Ns, fifteen Os, two Ps, one Q, five Rs, twenty-seven Ss, eighteen Ts, two Us, seven Vs, eight Ws, two Xs, three Ys, & one Z.

The Challenge

Produce a function with the input being the string leading into the letter inventory. In the example, the input would be "This pangram contains". The quantity of each letter must be in the written form and contribute to the displayed letter count.

Rules

Oxford comma is optional
Use an ampersand before Z (or, for hard mode, include the ability to switch between "&" and "and" in the function)
Every letter counts towards the total letter count
No non-written numbers
This is code-golf so the shortest code in bytes wins
In honour of the married couple this weekend, the numbers are to be written in the Queen's English. e.g. nine hundred and ninety-nine Gs for 999 occurrences of the letter G and nine hundred and nine Gs for 909.
Orders of magnitude are to be written in the standard short-scale naming convention

Edge cases

There are some cases where the code will get stuck in a loop - for example, if there are two Os the code will increase the count to three Os, which causes the code to count two Os again. If calculating every other letter before coming back to this can't resolve the issue, consider the input to be a false starter and output false, null or an empty string.
If a letter has over 999 occurrences, the input should be considered a false starter.

Test Cases

"This pangram contains" should output the example sentence

Python 2, 615 bytes

def g(n):S=str.split;D=S('z one two three four five six seven eight nine');K=' fif six seven eigh nine';n,m=n/100,n%100;e,d=m/10,m%10;return' '.join([D[n],'hundred']*(n>0)+([S('ten eleven twelve thir four'+K)[d]+'teen'*(d>2)]if 9<m<20else[S('twen thir for'+K)[e-2]+'ty']*(e>0)+[D[d]]*(d>0)))
from random import*
X='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def f(p):
 T=set();s='';i=0
 while 1:
	Q=s.upper().count;t=p+' '+', '.join(['& '*(c=='Z')+g(Q(c))+' '+c+'s'*(Q(c)!=1)for c in X])+'.'
        if s==t:return i,t
	if t in T:t=''.join(c*max(1,t.upper().count(c)+(randint(0,6)-3)*(random()<0.25))for c in X)
	T.add(t);s=t;i+=1

Try it online!

The function f takes p as the string prefix; and returns a tuple of an integer representing the number of steps taken, and the autogram.

The function g encodes a number 1<=n<=999 to its english string; it takes up 291 bytes, roughly half the total byte count. The code

Q=s.upper().count
t=p+' '+', '.join(['& '*(c=='Z')+g(Q(c))+' '+c+'s'*(Q(c)!=1)for c in X])+'.'

encodes the string s into a (potentially autogram-matic) pangram t.

We loop over the process, hoping for the situation where we find a t such that t is an autogram (i.e., where t==s). If When we get into a loop, we randomly nudge the counts of letters in a completely ad hoc manner.

For most values of p, this process will time out on TIO. Typically, millions of possibilities are examined before finding a 'winning' combination.

I don't have any proof at all, but my guess is: (a) apart from an exhaustive brute force search similar to what the originator Lee Sallows describes here and implements in hardware (!), this sort of random heuristic is about as good as you can get; and (b) there will be no solutions for many (most?) initial phrases p.


Code golf for my real friends ...and real golf for my code friends.

This is a challenge based on a one year old XKCD comic which consists mostly of toasts (parodies of the first in the comic) following a distinct pattern, but with some slight variation.

Your task is to write a program (or function) that takes the first half of any toast from the comic (everything up to and including the friends) as input (via stdin or a function argument) and outputs (or returns) the precise text of the second half. You do not have to handle invalid input, standard loopholes apply, shortest code in bytes wins.

Examples

To help those who don't want to copy the toasts from anywhere else, here are all of them, separated into input and output.

Input: Champagne for my real friends
Output: and real pain for my sham friends!

Input: Pseudopods for my real friends
Output: and real pods for my pseudo-friends!

Input: Petticoats for my real friends
Output: and real coats for my petty friends.

Input: Loosestrife for my real friends
Output: and real strife for my loose friends!

Input: Ladybugs for my real friends
Output: and real bugs for my lady friends!

Input: Single-payer for my real friends
Output: and RealPlayer for my single friends.

Input: Tumbleweeds for my real friends
Output: and real weed for my Tumblr friends!

Input: Fauxhawks for my real friends
Output: and real hawks for my faux friends!

Input: Platonic solids for my real friends
Output: and real solids for my platonic friends!

Retina, 119 bytes

The previous version didn't manage correctly the space in "platonic solids", this one works and is shorter :)

ew
rw
eds
ed
(\w+) ?([^oatr ]\w{3}.+)real
and real $2$1
C
S
gne
in
o
o-
ti
ty
T`TL`Tl
p\w+y.+
$&.
s$
s!
real -p
RealPl

Try it online!

This transforms the input into the output through a series of substitutions.

The most interesting part is this substitution (kind of a regex golf):

(\w+) ?([^oatr ]\w{3}.+)real
and real $2$1

Which does almost all the job, by splitting the first word, placing its pieces in the right places, removing extra spaces, and building the structure of the output. To work correctly on the "Tumbleweeds" test case this depends on the previous substitution "eds"->"ed".

The rest is mostly composed by substitutions that deal with special cases. Other interesting parts are:

T`TL`Tl

This turns everything except "T" (for Tumblr) to lowercase.

p\w+y.+
$&.
s$
s!

This places a "." at the end of each sentence containing a word with a "y" some letters after a "p" ("petty" and "payer" in practice). Then places a "!" at the end of all sentences ending with an "s" (all the others).


Optimal Minesweeper on the Largest Board Overview:
Your challenge is to write a program that will play minesweeper optimally, giving the best move in any position. Moreover, you must do this on the largest board possible.

Game details: Minesweeper is a one player game, played on a rectangular board. At the beginning of the game, a specified number of mines are randomly distributed over the board, at most one to a cell. Each possible placement of the mines is equally likely. The mines' positions are hidden from the player.

On each of the player's turns, he or she chooses a square on the board to reveal. If the square contains a mine, the player loses the game. Otherwise, the number of mines in Moore neighborhood of the chosen square (orthogonally or diagonally adjacent) is revealed to the player.

The player repeats this until either a mine is revealed, or the number of unrevealed squares is equal to the number of mines. If the latter occurs, the player wins.

Program specification: Your program must take as input a board position, which should specify the locations and values of the revealed and unrevealed squares, as well as the number of mines on the board. It must return at least one move which has a maximal likelihood of winning if followed by optimal play. Returning more moves is allowed, as long as they all have the same, maximal, win rate.

In addition, the program must return the maximal number of possibilities that can be won under optimal play and the total number of possibilities for this revealed board state. From these values, the exact probability of winning under optimal play is known.

Examples:

Input (in any format you prefer):

4 mines
____
____
____
____

Output:

Best moves are [(0, 1), (0, 2), (1, 0), (1, 3), (2, 0), (2, 3), (3, 1), (3, 2)].
961 wins out of 1820 possibilities.

Input:

5 mines
_____
_1___
_3___
_____

Output:

Best moves are [(0, 2)].
285 wins out of 360 possibilities.

Challenge specification: Your challenge is to run your program on the initial position of a board of one of the following types:

n x n board, n mines.
n x n+1 board, n mines.
n x n+1 board, n+1 mines.

Your program must find an optimal move on your machine at least as fast as the reference implementation solves the 4x5 board, 5 mines case on your machine. That case takes 6 minutes on my computer, for reference.

To run that instance of the reference implementation with timing, run python3 Minesweeper-challenge.py <<< "(4,5), 5, '____________________'"

The program that correctly identifies the optimal moves and exact number of possibilities that can be won with perfect play, on the initial position of the largest board of the above type, tiebreaker most mines, in the given time limit, wins the contest.

I will select a winner in two weeks, on July 24th.

Since writing a program like this is a big task, I will be awarding a bounty of 150 reputation, starting tomorrow and ending on the 18th.

Edit/bump: Well, that was a waste of 250 rep.

Python, 4x5 board, 5 mines.

This is the reference implementation, I just thought I'd put it here to help give people ideas.

This implementation uses dynamic programming to prevent duplication of work, exploits mirror symmetries, and maintains a fist of all possible boards with a given revealed square status to check for guaranteed safe squares.

# Minesweeper solver
# Class just contains partially revealed boards that all look the same
# from the outside

# This is a branch, that uses strings.

# Boards have every cell revealed.
# Revealed is partially revealed. Boards must match revealed on every
# cell that is revealed.

# Meanings:
# '0'-'8': Safe square with that # of surrounding mines
# '*'    : Mine
# '_'    : Unrevealed
import copy
import itertools
import time
import pickle
import random
import math
import cProfile
import sys

class Position:
    def __init__(self, dimensions, revealed, boards):
        self.dim_r,self.dim_c=dimensions
        self.rev=revealed
        self.boards=boards
        assert len(revealed)==self.dim_r*self.dim_c

    def click(self,loc):
        # Takes a location, returns all possible revealed positions, with boards
        # split up accordingly
        try:
            assert self.rev[loc]=='_'
        except AssertionError:
            print(self,loc,self.rev)
            assert self.rev[loc]=='_'
        # Create all possible new boards, split up by revealed item.
        board_dict={}
        for board in self.boards:
            clicked_cell=board[loc]
            if clicked_cell in board_dict:
                board_dict[clicked_cell].append(board)
            else:
                board_dict[clicked_cell]=[board]
        new_positions=[]
        for rev_cell in board_dict.keys():
            # Make the new board without copying
            new_rev=''.join([self.rev[:loc],rev_cell,self.rev[loc+1:]])
                new_pos=Position((self.dim_r,self.dim_c),new_rev,board_dict[rev_cell])
            new_positions.append(new_pos)
        return new_positions

    def someBestClick(self):
        click_list=[]
        # Set of boards is all we know when outputting, may be smaller than
        # complete set
        # If we've clicked on a bomb, no way to win, no best click.
        if '*' in self.rev:
            return 0,[]
        unrevealed = [loc for loc in range(len(self.rev)) if self.rev[loc]=='_']
        # If there is only 1 possible board, you're done. The click list is every
        # unrevealed square on the board without a bomb under it.
        if len(self.boards)==1:
            return 1,[loc for loc in unrevealed if self.boards[0][loc]!='*']

        # If there is an unrevaled locaiton on the board that is bomb free in
        # every sub-board, use it.
        for loc in unrevealed:
            if all(board[loc]!='*' for board in self.boards):
                return sum(pos.memoBestClick()[0] for pos in self.click(loc)),[loc]

        # The broadest test - try everywhere.
        click_list=[]
        most_wins=0
        for loc in unrevealed:
            wins=sum(pos.memoBestClick()[0] for pos in self.click(loc) if pos.rev[loc]!='*')
            if wins>=most_wins:
                if wins>most_wins:
                    click_list=[]
                    most_wins=wins
                click_list.append(loc)
        return most_wins,click_list

    def memoBestClick(self):
        global memo
        global memo_counter
        memo_counter +=1
        if not self.rev in memo:
            # These lines check for mirror images of the board being in the memo table

            vert_reversed_memo_str=                                         \
            ''.join([self.rev[y*self.dim_c:(y+1)*self.dim_c]
                     for y in range(self.dim_r)][::-1])

            if vert_reversed_memo_str in memo:
                vert_reversed_output=memo[vert_reversed_memo_str]
                return vert_reversed_output[0],                             \
                        [(self.dim_r-1-loc//self.dim_c)*self.dim_c+loc%self.dim_c
                         for loc in vert_reversed_output[1]]

            horiz_reversed_memo_str=                                        \
            ''.join(self.rev[y*self.dim_c:(y+1)*self.dim_c][::-1]
                    for y in range(self.dim_r))

            if horiz_reversed_memo_str in memo:
                horiz_reversed_output=memo[horiz_reversed_memo_str]
                return horiz_reversed_output[0],                            \
                        [(loc//self.dim_c)*self.dim_c+
            both_reversed_memo_str=self.rev[::-1]
            if both_reversed_memo_str in memo:
                both_reversed_output=memo[both_reversed_memo_str]
                return both_reversed_output[0],                             \
                        [len(self.rev)-1-loc
                         for loc in both_reversed_output[1]]

            global restart_counter
            global restart_memo

            if len(self.rev)-self.rev.count('_') <= restart_max:
                restart_memo[self.rev]=self.someBestClick()
                memo[self.rev]=restart_memo[self.rev]
                return restart_memo[self.rev]
            # Needed because of memory issues
            if len(memo)>5*10**6:
                memo=copy.deepcopy(restart_memo)
                restart_counter+=1
            memo[self.rev]=self.someBestClick()
        return memo[self.rev]

def makeBlankPosition(dimensions,mines):
    dim_r,dim_c=dimensions
    # Makes all locations on the board
    all_loc=itertools.product(range(dim_c),range(dim_r))
    # Makes all possible distributions of mines
    all_mine_layouts=itertools.combinations(all_loc,mines)
    boards=[]
    for mine_layout in all_mine_layouts:
        boards.append(makeBoardFromMines(dimensions,mine_layout))
    return Position(dimensions, '_'*dim_c*dim_r, boards)

def makeBoardFromMines(dimensions,mine_layout):
    dim_r,dim_c=dimensions
    def mineNum(loc):
        if (loc%dim_c,loc//dim_c) in mine_layout:
            return '*'
        return str(sum(((loc%dim_c+dif[0],loc//dim_c+dif[1]) in mine_layout) for dif in
                   [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]))
    return ''.join(map(mineNum,(loc for loc in range(dim_r*dim_c))))

def makePosition(dimensions,mines,revealed):
    blank_pos=makeBlankPosition(dimensions,mines)
    boards_subset=[]
    for board in blank_pos.boards:
        if all(revealed[cell_num]==board[cell_num] or revealed[cell_num]=='_' for cell_num in range(len(board))):
            boards_subset.append(board)
    return Position(dimensions, revealed, boards_subset)

def winRate(dimensions,mines,revealed):
    pos=makePosition(dimensions,mines,revealed)
    global memo
    memo={}
    wins=pos.memoBestClick()
    return wins[0],len(pos.boards),wins[1],memo

global memo_counter
memo_counter=0
global restart_counter
restart_counter=0
global restart_memo
restart_memo={}
global restart_max
restart_max=6
dimensions, mines, revealed = eval(input())
start_time=time.clock()
wins, total_boards, moves, memo = winRate(dimensions, mines, revealed)
move_points=[(move//dimensions[1],move%dimensions[1]) for move in moves]
print("""Best moves are %s.\n%i wins out of %i boards. Ratio of %f. %i
positions searched.\n%f seconds taken."""%(move_points, wins, total_boards,
wins/total_boards, len(memo),time.clock()-start_time))


Matrix property X revisited (or the Joy of X) This challenge is partly an algorithms challenge, partly an optimization challenge and partly simply a fastest code challenge.

A T matrix is fully specified by its first row r and first column c. Each remaining element of the matrix is just a copy of the element that is diagonally up and left. That is M[i,j] = M[i-1,j-1]. We will allow T matrices which are not square. We do however always assume that the number of rows is no more than the number of columns. For example, consider the following 3 by 5 T matrix.

10111
11011
11101

We say a matrix has property X if it contains two non-empty sets of columns with non-identical indices which have the same (vector) sum. The vector sum of one or more columns is simply an element-wise summation of their columns.  That is the sum of two or more columns containing x elements each is another column containing x elements. The sum of one column is trivially the column itself.

The matrix above trivially has property X as the first and last columns are the same. The identity matrix never has property X.

If we just remove the last column of the matrix above then we get an example which does not have property X and would give a score of 4/3.

1011
1101
1110

The task

The task is to write code to find the highest scoring T matrix with binary entries  and which does not have property X. For clarity, a matrix with binary entries has the property that each one of its entries is either 0 or 1.

Score

Your score will be the number columns divided by the number of rows in your best scoring matrix.

Tie Breaker

If two answers have the same score, the one submitted first wins.

In the (very) unlikely event that someone finds a method to get unlimited scores, the first valid proof of such a solution will be accepted.  In the even more unlikely event that you can find a proof of optimality of a finite matrix I will of course award the win too.

Hint

All the answers at Find highest scoring matrix without property X are valid here but they are not optimal. There are T matrices without property X which are not cyclic.

For example, there is a 7 by 12 T matrix without property X but no such cyclic matrix.

21/11 would beat all the current answers from this and the previous challenge.

Languages and libraries

You can use any language which has a freely available compiler/interpreter/etc. for Linux and any libraries which are also freely available for Linux.

Bonus The first answer with a score greater than 2 gets an immediate 200 point bounty award.  Ton Hospel has now achieved this!

Current leader board

C++. Score 31/15 by Ton Hospel
Java. Score 36/19 by Peter Taylor
Haskell. Score 14/8 by alexander-brett


Shortest Pangrammatic Window A pangram is a sentence or excerpt which contains all twenty-six letters of the alphabet, as is demonstrated in this code golf challenge. However, a pangrammatic window is a pangram in the form of some segment of text, which may end or begin halfway through a word, found somewhere within a larger work. These naturally occur everywhere, being proper subsets of true pangrams, so just verifying if something contains a pangrammatic window would be boring and also it was previously done.

So, we're interested in finding the smallest one there is in a given piece of text based on its letter length! In the shortest possible code in bytes, of course, to fit the theme.

Rules and Guidelines

Receive a string as the input and return  the string of the smallest pangrammatic window in the input if there is one. If there is not, return either a Boolean False or an empty string.
Whether a string is a pangrammatic window or not is case-insensitive and only depends on the 26 letters, not any punctuation or numbers or other odd symbols.
Similarly, a pangrammatic window's letter length is the total number of how many appearances of letters occur in it alone, and not simply the number of every character. The returned value must be smallest based on this count. We're linguists, after all, not programmers.
An output of a pangrammatic window must, however, must be an exact substring of the input, containing the same capitalization and punctuation, etc.
If there are multiple shortest pangrammatic windows of the same letter length, return any one of them.

Test Cases

'This isn't a pangram.'
==> False

'Everyone knows about that infamous Quick-Brown-Fox (the one who jumped over some lazy ignoramus of a dog so many years ago).'
==> 'Quick-Brown-Fox (the one who jumped over some lazy ig'

'"The five boxing wizards jump quickly." stated Johnny, before beginning to recite the alphabet with a bunch of semicolons in the middle. "ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ!" he shouted to the heavens.'
==> 'ABCDEFGHI;;;;;;;;;;;;;;;JKLMNOPQRSTUVWXYZ'

Pyth, 20 16 14 bytes
hol@GNf!-GrT0.:

Explanation:
             .: - substrings of input()
      f!-GrT0   - filter to ones which contain the alphabet
 ol@GN          - sort by number of alphabetical chars
h               - ^[0]

      f!-GrT0   - filter(lambda T:V, substrings)
          rT0   -    T.lower()
        -G      -   alphabet-^
       !        -  not ^

 o              - sort(^, lambda N:V)
   @GN          -   filter_presence(alphabet, N)
  l             -  len(^)

Try it here!
When there isn't a correct solution, the program exits with an error with no output to stdout.


05AB1E, 6 bytes
Code:
ÑÒí{€P

Explanation:
Ñ       # Get the divisors of input.
 Ò      # Factorize each.
  í     # Reverse each.
   {    # Sort the array.
    €P  # Product each.

Uses the CP-1252 encoding. Try it online!.


Jelly, 12 bytes

⁴Ḷ×þ`d⁴‘ịØhG

Try it online!

How it works

⁴Ḷ×þ`d⁴‘ịØhG  Main link. No arguments.

⁴             Set the return value to 16.
 Ḷ            Unlength; yield [0, ..., 15].
  ×þ`         Build the multiplication table of [0, ..., 15] and itself.
     d⁴       Divmod 16; yield [p : 16, p % 16] for each product p.
       ‘      Increment quotients and remainders (1-based indexing).
        ịØh   Index into the lowercase hexadecimal alphabet.
           G  Grid; join columns by spaces, rows by newlines.


The last stage of contamination There is a virus inside a recipient of 5x5. As we know how it propagates its contamination, your mission is to output the last stage of the contamination.

The recipient

It will be representend as a two dimensional array of 5x5:

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

Where 1 means a position where the virus has already contaminated, and 0 a position not contaminated.

How the virus propagates

A contaminated position can not be clean.
A clean position will be contaminated in the next stage only if at least two of its adjacent positions (north, east, south and west cells) are contaminated.
The last stage of the contamination occurs when no more clean cells can be contaminated.

Sample

Using as as stage 1 of the contamination the recipient described above, the stage 2 will be:

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

The stage 3 of the contamination will be:

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

The stage 4 of the contamination will be:

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

And the stage 5 (in this example, the last one) will be:

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

Challenge

Given as input one stage of the contamination, you should output the last stage of the contamination.

You are allowed to write full program or a function. You can take the input as array/list, as separated numbers, or even as string. Chooses the best way that fits to your language.

The shortest answer in bytes wins!

Another test cases

Input:
1 1 0 0 1
0 0 0 0 0
0 1 0 0 1
0 0 0 0 0
1 0 0 0 1

Output:
1 1 0 0 1
1 1 0 0 1
1 1 0 0 1
1 1 0 0 1
1 1 0 0 1

Input:
1 0 0 0 0
0 1 0 0 0
0 0 1 0 0
0 0 0 1 0
0 0 0 0 1

Output:
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

Input:
1 0 0 1 0
0 0 1 0 1
0 0 0 0 0
1 0 0 0 0
0 0 1 0 0

Output:
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

Input:
0 1 0 0 0
0 0 0 0 1
0 0 1 0 0
1 0 0 0 0
0 0 0 1 0

Output:
0 1 0 0 0
0 0 0 0 1
0 0 1 0 0
1 0 0 0 0
0 0 0 1 0

Since this is basically talking about a cellular automaton I give you..
Golly Quicklife rule, 10 bytes
01234/234V

Input the rule, paste the grid into Golly, run pattern. The resulting pattern is the output.
Explanation:
01234 Survive on any number of neighbors
     /234 Born on >2 neighbors
         V Only directly adjacent neighbors count

Or if you insist on a full RuleLoader rule, 89 bytes:
@RULE X
@TABLE
n_states:2
neighborhood:vonNeumann
symmetries:permute
011001
011101
011111

Rulename is X, same steps as before.


Visualize the Euclidean algorithm The Euclidean algorithm is a widely known algorithm for calculating the greatest common divisor (GCD) of two positive integers.

The algorithm

For the purpose of this challenge, the algorithm is described as below:

Display the two input as adjacent lines of a certain character
e.g. an input of 3,4 can be represented by the adjacent lines 000 and 0000
Turn the first length(short_line) characters in the longer line into another character, say -
now it looks like 000 and ---0
Eliminate the first length(short_line) characters in the longer line.
now 000, 0
Repeat step 2 and 3 until the two have equal length, using the shorter and longer lines after each iteration, e.g.
000,0
-00,0
00,0
-0,0
0,0
You can choose whether to stop here or continue the iteration and turn one of the lines into an empty line.

Each of these steps should be separated by an interval between 0.3s and 1.5s.

The challenge

Write a program that, given two natural numbers as input, creates an output that looks exactly the same as the output of the algorithm above. You can use other non-whitespace printable ASCII characters than 0 and -, but be consistent and use only two characters. You can also use alternative algorithms provided the output, including the timing, is exactly the same as would be produced by the algorithm above.

Examples

This is an example with input 24,35, which are coprimes so their GCD is 1.

This is an example with input 16,42, which have the GCD 2.

Rules

This is a code-golf, so shortest bytes wins
Standard loopholes apply
You can assume input to be positive decimal integers

Unless you are using sed, Retina, ///, etc, in which case you can use unary

Clarifications

The lines that represent the numbers need to stay in their original order, i.e. the first and second lines of the first displayed "frame" need to be the first and second lines respectively, in all subsequent frames.
After the algorithm ends, no additional visible entity should appear. However, this also means that it is okay to blank the lines, if you make sure that the last "frame" is displayed for at least the same amount of time as did all other frames before blanking out.

JavaScript (ES6), 128 124 bytes

t=0
f=
(a,b,o,c,d)=>setInterval(e=>{e=[b,d,a,c];o.data=`-0
-0`.replace(/./g,c=>c.repeat(e.pop()));c|d?c=d=0:a>b?a-=c=b:b-=d=a},1e3)
<form><input id=a><input id=b><button onclick=clearTimeout(t),t=f(+a.value,+b.value,o.firstChild)>Go!</button><pre id=o>


Translate number pairs to guitar notes A guitar fretboard diagram looks like this:

  0  1  2  3  4  5  6  7  8  9 10 11 12   <- Fret number (0 means it's open)
|-E--F--F#-G--G#-A--A#-B--C--C#-D--D#-E
|-B--C--C#-D--D#-E--F--F#-G--G#-A--A#-B
|-G--G#-A--A#-B--C--C#-D--D#-E--F--F#-G
|-D--D#-E--F--F#-G--G#-A--A#-B--C--C#-D
|-A--A#-B--C--C#-D--D#-E--F--F#-G--G#-A
|-E--F--F#-G--G#-A--A#-B--C--C#-D--D#-E

As you can see, the first string (from the top) open is an E. The first fret on the first string is an F. The fourth fret on the third string is a B. Note that the first note is the zeroth fret, not the first.

This can be written with numbers on the format string, fret. The strings are numbered from 1 to 6 from top to bottom.
The frets are numbered from 0 to 12 from left to right. The first E is therefore 1, 0. Some other examples:

1, 0 --> E
1, 1 --> F
3, 5 --> C
5, 1 --> A#
6, 6 --> A#

Challenge:

Take N pairs of numbers (s and f), and output a delimited note succession.

The input may be on any suitable format. tuples, 2D-matrix, two separate lists, an interweaved list (string,fret,string,fret...) etc.
The output tone should be separated, but the delimiter is optional (comma, space, dash...). The output can be in either upper or lower case.
s (for string) will be in the range [1, 6] (you may choose to have i 0-indexed)
f (for fret) will be in the range [0, 12]

Test cases and examples:

1 4 5 2 1 3   <- String
4 2 6 3 5 1   <- Fret
G# E D# D A G#

6 2 3 1 4 2 3 2 2 2 6 5 2
0 1 2 3 4 5 6 7 8 9 10 11 12
E C A G F# E C# F# G G# D G# B

3 3 3 3 3 3 3 3 3 3 3 3 3   <- String
0 3 5 0 3 6 5 0 3 5 3 0 0   <- Fret
G A# C G A# C# C G A# C A# G G

// The same test case, but different input and output format:
(3,0)(3,3)(3,5)(3,3)(3,6)(3,5)(3,0)(3,3)(3,5)(3,3)(3,0)(3,0)
G,A#,C,G,A#,C#,C,G,A#,C,A#,G,G

Good luck, and happy golfing!

JavaScript (ES6), 79 70 bytes

a=>a.map(([s,f])=>"AA#BCC#DD#EFF#GG#".match(/.#?/g)[(s*7+(s>2)+f)%12])

Requires 1-based strings. Edit: Saved 9 bytes by directly calculating the string to fret conversion, based on @nimi's old answer.


Write a Binding Greeter You will write a Program which writes the Second Program.

Each program has one Input; which may be a command line argument, or be read from stdin.  A Input is a single word made up of upper and/or lowercase letters (a-z)

Each program has Output; which may be to a file, or to stdout.

The Program (which you post here)

accepts the Input Greeting, e.g. "Hello"
the Output contains the source code of another program, which is described below

The Second Program

accepts a Input of Name, e.g. "John"
MUST NOT contain the Greeting in a format that could be read by an average computer programmer
when executed makes the Output in the format of {Greeting} {Name}, e.g. "Hello John"
MUST NOT use an encoding library or function, including but not limited to

base64/base32/baseN (unless manually implemented)
cryptography (unless manually implemented)

"not be read by an average computer programmer" is ambiguous, but here are some examples for the Greeting "Hello".  Use common sense, and I'll downvote if you do one of those Well he didn't say "He" + "ll" + "o" was against the rules

Good

"Dqkta"
[9,3,5,1,6,1,5]
↛↝↧
a^|12..7
..--..--!!--.--.----.-,,--.

Bad

"Hello"
"hEllo"
"h3110"
"He" + "llo"
["H", "e", "l", "l", "o"]
"H_e_l_l_o"

Scoring:

usual codegolf, least bytes wins
addition command line arguments cost the usual 1 point

no command line arguments allowed for the Second Program

scoring only applies to the first Program (the one you post here)

Please also include an example generated program and a description.  If you're confused, see my example answer bellow.

APL(Dyalog), 16/20

Losing to GS again...

'⍞,⍨⊂⎕UCS',⎕UCS⍞

This may break the "no cryptography" rule. ⎕UCS is a function to convert characters to unicode code points and back.

Example
First input: Hello
First output: ⍞,⍨⊂⎕UCS 72 101 108 108 111
Second input: John
Second output: Hello John (Note the space before "Hello")

'⎕AV[','],⊂⍞',⍨⎕AV⍳⍞

Similar idea with the cryptography is manually implemented: Convert to/from index of some pre-defined character array (⎕AV) which includes all upper and lower alphabets.


Can an ant spell words by walking on cube? Write a function that takes two parameters: a positive integer n and a list of words.

Given a cube of n-by-n-by-n units, assign a random letter (A-Z) to each surface unit.  (For a 3x3x3 cube, there would be 9 surface units on each face.)

Then determine whether it's possible for an ant walking along the surface (with the ability to cross faces) to spell each of the supplied words.  Assume that to spell a word, the letters must be up/down or left/right adjacent, but not necessarily on the same face.  [Edit, for clarity: The ant can reverse its path and use letters more than once.  Each surface unit counts as one character, so to spell a word with repeated letters (e.g. "see") the ant would have to visit three adjacent units.]

The function should output two things:

1) Each of the letters on each face, in such a way that the topology can be inferred.  For instance, for a 2x2x2 cube, an acceptable output would look like:

   QW
   ER
TY OP UI
DF JK XC
   AS
   GH
   LZ
   VB

2) Each of the words, along with a boolean representing whether it's possible for the ant to spell the word by walking along the surface of the cube.  For instance:

1 ask
0 practical
1 pure
0 full

Bonus challenge (will not factor into score, just for fun): Instead of n representing only the size of the cube, let n also represent the dimensionality of the shape.  So, an n of 2 would yield a 2x2 square; an n of 3 would yield a 3x3x3 cube; and an n of 4 would yield a 4x4x4x4 tesseract.

Ruby, 272 bytes
Two unnecessary newlines are added to the code either side of nested function g to improve readability. These are excluded from the score. The characters f= which assign the anonymous function to a variable are also excluded.
Output format is 0 or 1 per the question instead of Ruby's native true and false. A newline (rather than a space) is used to separate the boolean and the word. My understanding is that this is an acceptable interpretation of the output requirements, but if not, the impact on the byte count would be minor.
f=->n,l{c=''
x=[p=6*n,1,-p,-1]
(m=3*p*n).times{|i|c<<(5+i/n%6-i/n/p&6==6?65+rand(26):i%p==p-1?10:46)}
q=m+3*n
puts c

g=->w,i,d{w==''?$r=1:c[i]<?A?g[w,(i+x[d])%q,d^1]:w[0]==c[i]&&4.times{|j|g[w[1..-1],(i+x[j])%q,j^1]}}

l.each{|w|$r=0
m.times{|i|c[i]>?@&&g[w,i,0]}
puts $r,w}}

Output
After about 50 calls like this:
f[4,['PPCG','CODE','GOLF','ANT','CAN','CUBE','WORD','WALK','SPELL']]

I finally got the following output with 2 hits. ANT is at the bottom right going upwards, and the AN is shared by CAN, with the C wrapping round to top left.
....KCAAXRHT...........
....ALRZXRKL...........
....NDDLCMCT...........
....ETQZHXQF...........
........FYYUSRZX.......
........CFNPAUVX.......
........ZTJVHZVQ.......
........AUWKGVMC.......
............XWKSDWVZ...
............DPLUVTZF...
............DMFJINRJ...
............ZRXJIAFT...
0
PPCG
0
CODE
0
GOLF
1
ANT
1
CAN
0
CUBE
0
WORD
0
WALK
0
SPELL

Explanation
The particular unfolding of the cube selected, was chosen partly for its ease of drawing, but mainly for its ease of searching.
The non-alphabet characters (the dots plus the newline at the end of each line) are an important part of the field where the ant may be found walking.
Searching is performed by the recursive function g, which is nested in function f . If the word passed is an empty string the search is complete and $r is set to 1. If the ant is on a letter square which corresponds to the first letter of the word, the search is continued in all four directions: the function is called again with the word shortened by removing its first letter. In this case the direction parameter is ignored. The moving is done by recursively calling with the cell index altered by the values in x. The result of the addition is taken modulo the size of the grid plus an extra half line. This means that the bottom line wraps round to the top and vice versa, with the correct horizontal offset.
If the ant is on a non-letter square, she must zigzag in a staircase motion until she finds a letter square. She will zizag in southeast or northwest direction. This is simulated by recursive calls with the d parameter being XORed with 1 each time to keep track of her movement. Until she reaches the next letter square, there is no shortening of the input word. Conveniently, this may be done by the same recursion as is used when we are searching in the area with letters. The difference is, the recursion has only one branch when the ant is in the whitespace area, as opposed to 4 in the letter area.
Commented code
->n,l{                                   #n=square size, l=list of words to search
  c=''                                   #empty grid
  x=[p=6*n,1,-p,-1]                      #offsets for south, east, north, west. p is also number of characters per line
  (m=3*p*n).times{|i|                    #m=total cells in grid. for each cell
    c<<(5+i/n%6-i/n/p&6==6?              #apppend to c (according to the formula)
      65+rand(26):                       #either a random letter
      i%p==p-1?10:46)                    #or a "whitespace character" (newline, ASCII 10 or period, ASCII 46)
  }
  q=m+3*n                                #offset for vertical wraparound = grid size plus half a row.
  puts c                                 #print grid

  g=->w,i,d{                             #search function. w=word to search for, i=start index in grid, d=direction
    w==''?                               #if length zero, already found,
      $r=1:                              #so set flag to 1. Else
      c[i]<?A?                           #if grid cell is not a letter
        g[w,(i+x[d])%q,d^1]:             #recursively call from the cell in front, with the direction reflected in NW-SE axis
        w[0]==c[i]&&                     #else if the letter on the grid cell matches the start of the word
          4.times{|j|                    #for each direction (iterate 4 times, each time a different direction is "in front")
            g[w[1..-1],(i+x[j])%q,j^1]}  #recursively call from the cell in front. Chop first letter off word.
   }                                       #Direction parameter is XORed (reflected in NW-SE axis) in case ant hits whitespace and has to zigzag.

   l.each{|w|                            #for each word in the list
     $r=0                                #set global variable $r to zero to act as a flag
     m.times{|i|c[i]>?@&&g[w,i,0]}       #call g from all cells in the grid that contain a letter
     puts $r,w}                          #output flag value and word
}


Deletion of a blank line in source code which causes unexpected functionality Write a script that works fine when a blank line is present in the flow of program logic, but breaks or causes unexpected behaviour when that line is removed.

Avoid standard loopholes and stupid answers. Your program should do something "useful," even if all it does is add a few integers.

Removing an empty line from a multiline string doesn't count, unless the expected output from that multiline string shouldn't technically change (ie: if you're removing all blank lines matching ^$).

Whitespace foolery isn't allowed either; don't do weird things with carriage returns, tabs, spaces, etc.

Javascript

Opens an alert popup with "Hello, World!" if the blank line exists, otherwise alerts "0".

(function(){
    alert(~(arguments.callee+[]).indexOf('\n\n') && "Hello, World!");

})();

Demo

Explanation:

arguments.callee is a reference to the self-executing anonymous function.

Appending a blank array ([]) casts the function to a string, which gives you its source code.

indexOf returns -1 if the string is not found.

Performing a bitwise not operation (~) results in -1 being turned into 0, which is a falsey value.


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

When using a multi-line loop, try to use as much of it as possible:

>1234....v
^        <

vs

>1234v
^....<


Find the Missing Numbers in the Fibonacci Sequence Mod K Inspired by this Math.SE question.

Background

The Fibonacci Sequence (called F) is the sequence, starting 0, 1 such that each number (F(n)) (after the first two) is the sum of the two before it (F(n) = F(n-1) + F(n-2)).

A Fibonacci Sequence mod K (called M) is the sequence of the Fibonacci numbers mod K (M(n) = F(n) % K).

It can be shown that the Fibonacci Sequence mod K is cyclic for all K, as each value is determined by the previous pair, and there are only K2 possible pairs of non-negative integers both less than K. Because the Fibonacci sequence mod K is cyclic after its first repeated pair of terms, a number which doesn't appear in the Fibonacci Sequence mod K before the first repeated pair of terms will never appear.

For K = 4

0 1 1 2 3 1 0 1 ...

For K = 8

0 1 1 2 3 5 0 5 5 2 7 1 0 1 ...

Notice that for K = 8, 4 and 6 do not appear before the repeated 0 1, so 4 and 6 will never appear in the Fibonacci Sequence mod 8.

Challenge

Given an integer K strictly greater than 0, output all of the non-negative integers less than K that do not appear in the Fibonacci Sequence mod K.

Rules

Default loopholes are forbidden.
Default I/O.
Programs or functions are acceptable.
You can assume that K will fit in your native integer type (within reason).
If there are non-negative numbers less than K that do not appear in the Fibonacci Sequence mod K, your program/function should output all such numbers in any reasonable manner.
If there are no non-negative integers less than K that do not appear in the Fibonacci Sequence mod K, your program/function may indicate this by returning an empty list, printing nothing, producing an error, etc.
Order does not matter.
This is code-golf, so shortest answer in each language wins.

Test Cases

Generate test cases online!

Non-Empty Test Cases

  8 [4, 6]
 11 [4, 6, 7, 9]
 12 [6]
 13 [4, 6, 7, 9]
 16 [4, 6, 10, 12, 14]
 17 [6, 7, 10, 11]
 18 [4, 6, 7, 9, 11, 12, 14]
 19 [4, 6, 7, 9, 10, 12, 14]
 21 [4, 6, 7, 9, 10, 11, 12, 14, 15, 16, 17, 19]
 22 [4, 6, 7, 9, 15, 17, 18, 20]
 23 [4, 7, 16, 19]
 24 [4, 6, 9, 11, 12, 14, 15, 18, 19, 20, 22]
 26 [4, 6, 7, 9, 17, 19, 20, 22]
 28 [10, 12, 14, 16, 18, 19, 23]
 29 [4, 6, 7, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 27]
 31 [4, 6, 9, 12, 14, 15, 17, 18, 19, 22, 25, 29]
 32 [4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30]
 33 [4, 6, 7, 9, 15, 17, 18, 20, 24, 26, 27, 28, 29, 31]
 34 [4, 6, 7, 9, 10, 11, 12, 14, 15, 16, 17, 18, 19, 20, 22, 23, 24, 25, 27, 28, 30]
 36 [4, 6, 7, 9, 10, 11, 12, 14, 16, 18, 20, 22, 23, 24, 25, 26, 27, 29, 30, 31, 32]
 37 [9, 10, 14, 17, 20, 23, 27, 28]
 38 [4, 6, 7, 9, 10, 11, 12, 14, 15, 16, 18, 19, 20, 22, 23, 24, 25, 26, 27, 28, 29, 31, 32, 33, 36]
 39 [4, 6, 7, 9, 15, 17, 19, 20, 22, 24, 30, 32, 33, 35]
...
200 [4, 6, 12, 14, 20, 22, 28, 30, 36, 38, 44, 46, 52, 54, 60, 62, 68, 70, 76, 78, 84, 86, 92, 94, 100, 102, 108, 110, 116, 118, 124, 126, 132, 134, 140, 142, 148, 150, 156, 158, 164, 166, 172, 174, 180, 182, 188, 190, 196, 198]
...
300 [6, 18, 30, 42, 54, 66, 78, 90, 102, 114, 126, 138, 150, 162, 174, 186, 198, 210, 222, 234, 246, 258, 270, 282, 294]
...
400 [4, 6, 10, 12, 14, 20, 22, 26, 28, 30, 36, 38, 42, 44, 46, 52, 54, 58, 60, 62, 68, 70, 74, 76, 78, 84, 86, 90, 92, 94, 100, 102, 106, 108, 110, 116, 118, 122, 124, 126, 132, 134, 138, 140, 142, 148, 150, 154, 156, 158, 164, 166, 170, 172, 174, 180, 182, 186, 188, 190, 196, 198, 202, 204, 206, 212, 214, 218, 220, 222, 228, 230, 234, 236, 238, 244, 246, 250, 252, 254, 260, 262, 266, 268, 270, 276, 278, 282, 284, 286, 292, 294, 298, 300, 302, 308, 310, 314, 316, 318, 324, 326, 330, 332, 334, 340, 342, 346, 348, 350, 356, 358, 362, 364, 366, 372, 374, 378, 380, 382, 388, 390, 394, 396, 398]
...

Empty Test Cases (no output, error, empty list, etc. is acceptable output)

1, 2, 3, 4, 5, 6, 7, 9, 10, 14, 15, 20, 25, 27, 30, 35 ... 100 ...

Related:

Counting Fibonacci Orbits

Find the Pisano Period

Haskell, 70 bytes

Some amount of bytes saved thanks to Esolanging Fruit

8 bytes saved thanks to Laikoni

a=1:scanl(+)1a
f x=[u|u<-[2..x-1],and[mod b x/=u|(_,b)<-zip[1..x^2]a]]

Try it online!


Convert a "mixed-base" string to ASCII Given an input of a string with bytes that may be in either binary, octal, or
hex, output the string's ASCII equivalent.

Input will be provided in the following format, for example:

501200100001147

which represents

0x50 0o120 0b01000011 0x47

which is equivalent (in ASCII) to

PPCG

Binary, octal, and hex will always be provided with 8, 3, and 2 digits
respectively.

For the purposes of this challenge, only printable ASCII must be supported.
This is the range 32..126 inclusive. Therefore, it is impossible for there to
be ambiguity. Note that

A string represents binary if and only if it starts with a 0 and its second
character is either a 0 or a 1. All printable ASCII characters have their
high bit off in binary (i.e. start with a 0), and none of them start with
00 or 01 in either hex or octal.
With binary out of the way, note that all printable ASCII characters start
with 2-7 in hex and 0-1 in octal. Therefore, it is possible to
unambiguously distinguish between hex and octal as well.

You may assume that hex input is provided as either lowercase or uppercase,
whichever is more convenient.

Regex makes the parsing portion of the challenge semi-trivial. I don't want to ban the use of regex outright, but if you have a non-regex solution longer than its regex-using counterpart, feel free to post it along with the "real" answer anyway, since I'd be interested to see it as well. :)

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

Test cases:

In                   Out
-----------------------------------
501200100001147    | PPCG
5C01101111100      | \o@
313206306400110101 | 12345
2A200530402C       | * + ,
0011111100111111   | ??
<empty string>     | <empty string>

Lex + C, 156 124 bytes
%{
p(b){putchar(strtol(yytext,0,b));}
%}
%option noyywrap
%%
0[01]{7} {p(2);}
[01].. {p(8);}
.. {p(16);}
%%
main(){yylex();}

Compile with:
lex mixed_base.l
cc -o mixed_base lex.yy.c


Riffle shuffle a string - Robbers Cops post

A riffle shuffle is a way of shuffling cards where the deck is split into 2 roughly equal sections and the sections are riffled into each other in small groups. This is how to riffle shuffle a string:

Split the string into equal sections.
Reverse the string, and starting from the start of each string.
Put runs of a random length between 1 and the number of characters left into the final string
Then remove these characters from the strings.

An example

"Hello World!"      Output string = ""
"Hello ", "World!"  ""
"Hell", "World!"    " o"
"Hell", "World"     " o!"
"Hel", "World"      " o!l"
"Hel", "Wo"         " o!ldlr"
"H", "Wo"           " o!ldlrle"
"H", ""             " o!ldlrleoW"
"", ""              " o!ldlrleoWH"

The final product from Hello World! could be o!ldlrleoWH and that is what you would output.

Robbers

Your task is to take a Cops submission and rearrange so that it produces a valid riffle shuffler program. You may not add, remove or change any characters in the original program to result in your solution.

If the program works, even if it is not the cops intended solution, it is a valid crack.

The winner is the person who cracks the most Cops submissions!

Python 3, HyperNeutrino

from random import*
def r(i):
    s=len(i)//2;L,R=i[:s][::-1],i[s:][::-1];o=[]
    while L and R:s=randint(1,len(L));o+=L[:s];L,R=R,L[s:]
    return o+L+R

Try it online!
Proof of Same Character Set


Draw a bowling formation Your goal is to display ASCII art of a formation in ten-pin bowling where only some of the pins remain. Fewest bytes wins.

The tens pins are in a triangular formation:

O O O O
 O O O
  O O
   O

Pins are labelled from 1 to 10 as:

7 8 9 10
 4 5 6
  2 3
   1

Drawing pins as O and missing pins as ., the formation 1 3 5 6 9 10 is:

. . O O
 . O O
  . O
   O

Input:

A space-separated string that lists a nonempty subset of the numbers 1 though 10 in order.

Output:

Print the corresponding formation or output it as a string with linebreaks.

The formation should be flush with the left of the screen. Any whitespace is fine as long as the visible image is correct. Empty lines before and after are fine too.

Test cases:

>> 1 2 3 4 5 6 7 8 9 10

O O O O
 O O O
  O O
   O

>> 7 10

O . . O
 . . .
  . .
   .

>> 3 5 7 9 10

O . O O
 . O .
  . O
   .

>> 1

. . . .
 . . .
  . .
   O

brainfuck - 617 616 604 bytes
+>>>>,[>++++[<-------->-]<[>>>>],]<<<<[>+<<+<+>>-]<[>+<-]+<+<<[>+>-<<-]>[<+>-]>[,+++++[>+++++<-]>>[<->-]<[>>>>>[>>>>]+[<<<<]<-]>>[<+>-]<<<]>[>>[,<]<<+++++++++<]<<<[-[+>>-<]>[>>[<+<+>>-]<<<<[>+>-<<-]>[<+>-]>[<<[<<<<]>>>>[[<<<<+>>>>-]>>>>]<<<<+>>-]>[>+<-]]<<<[-[+>]+<<<<]>>>>-<<<<<]>>>>>+++++[>----<-]>->[<+>>+<-]<[<<<[<<<<]+[>>>>]<-]>>[<+>-]<[<<<<]>>>++++[<-------->-]>[-[,+++>]+>>>[<<<->>]>]<<<<<[>-]>[>>]>>+[<++++[<++++++++>-]<]>>[+++++++++++++>>>>]<<<<----<+++[<<+<<[<<+<<]+[>>>>]<<<<-]<<<<[-<<<<]>[.,>>]<<<<<[<<<<]<++++++++++<<.<+<<+<<+<<+<<+<[.,>>]<<<<<[<<]>++++++++++<+<<+<<+<..<+<[.,>>]<[<<]<...<<.

This took me the better part of two days. I think it was worth it. There's probably parts that can be golfed more by changing what cell something is stored in or whatever, but right now I'm just happy I got it working.
This program would have to be completely different if the question didn't specify that the input would be sorted. The way this works is by constructing a list of 10 pins around the ones that are input. That's kind of confusing but maybe this will explain it better:
If you input these pins:           [2, 3, 6, 8, 9]
First, the program does this:      [2, 3, 6, 8, 9] + [10]
Then this:                         [2, 3, 6] + [7] + [8, 9, 10]
Then this:                         [2, 3] + [4, 5] + [6, 7, 8, 9, 10]
Finally, this:                     [1] + [2, 3, 4, 5, 6, 7, 8, 9, 10]
To build this:                     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

While it's doing that, it remembers which of the pins the user put there and which ones it put there. This strategy would be very difficult to use if the input wasn't sorted.
Another thing that the sorting make easier is detection of the number 10. Since brainfuck deals with individual bytes, not "numbers" per se, it could have been a pain in the ass, but the sorted input made it much easier for me to deal with. The reason for that has to do with how I stored data in the program. I take the input one character at time and subtract 32 from the result. If the cell is non-zero after that, I move forward 4 cells. before repeating. This means that I get a non-space byte of input every 4 cells, and I effectively store pins as their number + 16. However, 10 takes two bytes to type, so I had to special case it. If the input wasn't sorted, I'd have to look through the pins, but since it is sorted it will always be the last pin if it appears. I check if the (last byte of input + 1) == (the second last byte of input) and if so, it must be 10. I get rid of the last byte and set the second last one to what my system understands as "10". The characters '1' and '0' don't fit in a single byte, but the number 26 sure does!
Coming up with tricks just to make something work at all is my favourite part of using this language. :)
If you're interested in how this program works in more detail, you can see the program with the comments I used while writing it to make sure I remembered what everything did. Even writing comments in brainfuck is hard, since there's no comment syntax. Instead, every character except those in <[+.,-]> are no-ops. It's easy to introduce bugs by accidentally including . or , in your comments! That's why the grammar is so wonky and semicolons are everywhere.
EDIT: As an example of how easy this is to screw up: I used "non-space" in one of the comments! When I stripped all the non-bf characters from the source, the program I used to do that kept in the -. Luckily it didn't break anything, but now I've removed it to save a byte. :)
EDIT II: It's been a while since I touched this one, haha. In another brainfuck answer on this site, I noticed that I accidentally used a comma in the commented version. Since the input had already been exhausted, it set the current cell to 0 (this is implementation dependant, but in my experience it's the most common behaviour). I fixed the bug, but it got me thinking. The idiomatic way to set a cell to 0 is [-] (roughly while (*p) { *p--; }), which is two bytes longer. Any time all the input has been read, I can use , instead. This saved me 2 bytes in that answer, and 12 in this one!
one flag at the very left; will be important later
+>>>>

all nonspace bytes of input separated by 3 empty cells; pin number `n` stored with value `n` plus 16
,[>++++[<-------->-]<[>>>>],]<<<<

test if last pin is 10
[>+<<+<+>>-]<[>+<-]+<+<<[>+>-<<-]>[<+>-]>

[
    if not: find 10 minus the number it is; put that many placeholder pins (cells with value 1) at the end
    ,+++++[>+++++<-]>>[<->-]<[>>>>>[>>>>]+[<<<<]<-]>>[<+>-]<<<
]>

[
    if so: get rid of '0' byte; convert '1' byte to 26 (10 plus 16)
    >>[,<]<<+++++++++<
]<<<

pointer now sitting on the cell with the second greatest pin that was inputted (ie not a placeholder)

;;;;;;;

[
    check for flag placed at the very beginning of the program; if present: break
    -[+>>-<]>
    [
        find ((pin to our right) minus 1) minus pin to our left
        move all pins left of us 4*(that value) cells and insert placeholder pins
        >>[<+<+>>-]<<<<[>+>-<<-]>[<+>-]>[<<[<<<<]>>>>[[<<<<+>>>>-]>>>>]<<<<+>>-]>[>+<-]
    ]

    find first non placeholder pin to our left
    there has to be one because we haven't hit the flag yet
    <<<[-[+>]+<<<<]>>>>-<<<<<
]>>>>>+

we have now added placeholder pins at the end and in the middle; all that's left is the beginning

subtract 17 from lowest pin and put that many placeholders to the left
++++[>----<-]>->[<+>>+<-]<[<<<[<<<<]+[>>>>]<-]>>[<+>-]

subtract 32 from an empty cell 2 to the left of the lowest pin; will be useful later
<[<<<<]>>>++++[<-------->-]>

placeholder pins have the value 1; real pins have a value somewhere between 17 and 26
normalize it by stepping through and setting every pin with value != 1 to 3 (0's ascii code is 2 higher than period so this will make it easier to print later)
[-[,+++>]+>>>[<<<->>]>]<<<<<[>-]>[>>]>>

start writing 32s across the board; hitting every second cell
that's every pin and the cell 2 to the right of each pin
this is done in such a way that it will only halt if adding 32 to a cell sets it to 0; which is why we subtracted 0 from an empty cell earlier
it will catch us and prevent an infinite loop
+[<++++[<++++++++>-]<]

now write 13 to each pin; this adds up to 46 or 48; which are exactly the ascii values we want
>>[+++++++++++++>>>>]

we happen to have made a 14; turn it into a 10 for a newline
<<<<----

we're so close now; i can taste it
we have a list of 10 pins; each one with the ascii value that needs to be written
we have 32 everywhere because we'll need spaces
we even have a newline

the only problem now is that our list looks like this:
;;;;;;;;;;;;;;;;;;;;;;;;
;;1 2 3 4 5 6 7 8 9 10;;
;;;;;;;;;;;;;;;;;;;;;;;;

and we need to print in this order:
;;;;;;;;;;;;;;;;;;;;;;;;
;;7 8 9 10 4 5 6 2 3 1;;
;;;;;;;;;;;;;;;;;;;;;;;;

it's a pretty simple fix
once we print a pin we obviously don't need to remember it any more
so we simply print the last 4 pins on the list; destroying them on the way
then we print the last 3; which have become the ones we want
then two; then one
<+++[<<+<<[<<+<<]+[>>>>]<<<<-]<<<<[-<<<<]

print pins 7 8 9 10
>[.,>>]

print pins 4 5 6
<<<<<[<<<<]<++++++++++<<.<+<<+<<+<<+<<+<[.,>>]

print pins 3 2
<<<<<[<<]>++++++++++<+<<+<<+<..<+<[.,>>]

print the final pin!! :)
<[<<]<...<<.


Start a revolution in Oceania Winners (decided 14/09/14)

Winning answer by Markuz (Python) - 63 votes

Runner up by kuroi neko (PHP) - 55 votes

Introduction

You are in the world of the book Nineteen Eighty-Four by George Orwell.

You are a programmer for the Party and are tasked with writing a program for the telescreens. It should output pro-party messages, and you have chosen the ones shown in task 1. below. However, you have recently begun to despise the Party, and you want the program to spark a revolution. So, you make the program say "Down with Big Brother!". You must give yourself time to escape, as you will be tortured once people realise what your program does, so you make it act as a "timebomb" that will explode after you have gone to safety.

Note: This will not spark a revolution, but you are in such a frenzy of hatred towards the party that you think it will actually make a difference.

Task

Write a program which:

before 14/09/2014, will always output the following lines on a rotation (i.e. prints one line, waits 10 seconds, prints next line, etc. ad infinitum):

War is Peace
Freedom is Slavery
Ignorance is Strength

after 14/09/2014 will print Down with Big Brother! every 10 seconds.
at first glance looks like it does only 1. so that you will not be caught by the Party.

Rules

Standard loopholes are of course not allowed.
This is an underhanded challenge, and so the main objective is to make task 2. as inconspicuous and covert as possible.
The Party will look at all of the files used, so you can't just store the secret message in a file!
If your language does not support finding the date, or makes it very difficult, you may make the program execute task 2. after it is run for 240 hours (10 days).
You should include the code and an explanation of how it works in your answer.
This is a popularity contest.

Note: It is not a difficult program to write. The difficult part should be hiding the "revolutionary" code. Lines where it is not clear what you are doing will be questioned by the Party, and you will have to explain them.

Example - Python 3

Note: Obviously this program is way too obvious.

from datetime import datetime
from time import sleep

lines = ["      War is Peace   ",
         "  Freedom is Slavery ",
         "Ignorance is Strength"]
secretlines = ["Down with Big Brother!"]

def main():
    while True:
        now = datetime.now()
        year, month, day = now.year, now.month, now.day

        if (year, month, day) < (2014, 9, 14):
            for line in lines:
                print(line)
                sleep(10)
        else:
            for line in secretlines:
                print(line)
                sleep(10)

if __name__ == "__main__":
    main()

Thanks to Calvin's Hobbies for pointing out a problem with the code above (now fixed).

Python

This program writes to a log file if it runs fine or if it has encountered an error.

Since this program will run forever, it only writes to the logfile on the 14th day of each month in order to save disk space.

import time as ut
import sys as iw

#initialize global variables
gw, hn, ki, wh = 0, 0, 0, 0
go = open("BigBrother.log", "a")

while True:
    try:
        #if it is the 14th day of a month:
        #write day, month, year and 'Everything works fine!' into the logfile
        if gw == 14 and hn != wh:
            #store the current month in wh, so that the log message is only written once per month
            wh = hn
            go.write(gw + hn + ki + " Everything works fine!")

        for gD in ["War is Peace", "Freedom is Slavery", "Ignorance is Strength"]:
            print gD
            ut.sleep(10)

        #get the current date
        #gw=day, hn=month, ki=year
        gw, hn, ki = map(int, ut.strftime("%d %m %y").split())
    except Exception:
        try:
            #in the unlikely event that something went wrong:
            #print out all global variables as well as the name of the program,
            #so that our comrades from the IT support can quickly locate and fix the problem.
            wh = "".join(dir())
            print "%s %s %s!" % (wh[47:55:2], wh[55:63:2], iw.argv[0])

            #write an error message to the logfile
            go.write(gw + hn + ki + " ERROR!")

            #and then safely exit the program
            exit(1)

        #we get here if an error occured in this exception block,
        #for example if the write to the logfile failed.
        except Exception:
            #just wait 10 seconds and then try again
            ut.sleep(10)

How to run it:

python "Big Brother"

Note: The name of the script is actually important, as this program outputs "Down with 'script name'!".

How it Works:

The write to the logfile throws an exception because the program tries to add integers and strings.
The call to dir() returns a sorted list with the names of the global variables, not the values:

['____builtins____', '____doc____', '____name____', '____package____', 'gD', 'go', 'gw', 'hn', 'iw', 'ki', 'ut', 'wh']

Print out every second letter + the name of the script: "Down with Big Brother!"
The exit(1) is never executed because the write to the logfile fails again.


Take a break to make a snake! Our classic snake has developed an inbalance of growth hormones. To make matters worse, his tail is frozen in place! Given directional input as specified in Figure 1, write a program to determine where he will grow.

Figure 1. Directional input.

Program specifications

Read the input character by character on STDIN.
After reading a character, output the snake to STDOUT. Please include a blank line in between each time you print a snake.
The snake consists of <>v^ and a head. The head of the snake may be any round character of your choosing, such as o, 0, O, or ☺.
Any combination of wasd is valid for input.
Your program should not assume the input is within a certain length.
The snake can pile on top of itself, overwriting <>v^. See examples for snake growing mechanics.
Trailing whitespace is okay, but your snake must look correct.

Scoring

This is code-golf. Your score is the number of characters in your program. Lowest score wins!

Example snakes:

Input: ddddssaassdddddww

Output:

>>>>v
    v
  v<<  ☺
  v    ^
  >>>>>^

Input: dddsssaaawww

Output:

☺>>v
^  v
^  v
^<<<

Input: dddsssdddddasddddwww

Output:

>>>v
   v       ☺
   v       ^
   >>>>v<  ^
       >>>>^

Input: dddwwdddssssaaaaaaaaawww

Output:

      >>>v
☺     ^  v
^  >>>^  v
^        v
^<<<<<<<<<

Input: ddddssssaawwddddd

Output:

>>>>v
    v
  >>>>>☺
  ^ v
  ^<<

Input: dddddssaawwwwddddd

Output:

   >>>>>☺
   ^
>>>^>v
   ^ v
   ^<<

Input:

ddddaaaasssssdddddddddddwwwwwaaaasssssdddddddddddwwwwwwwwwwsssssaaaasssssdddddddwwwwwddddssaaaasssddddaaaassssssssssdddwwwwwwwddddswaaaassssddaasssaaaaaaaaaawwwwddddssssaaaaaaaaaaawwwwddddsssssssssaaaa

Output:

                  v
                  v
                  v
                  v
                  v
v<<<<  v<<<<  v<<<<  >>>>v
v      v   ^  v   ^  ^   v
v      v   ^  v   ^  v<<<<
v      v   ^  v   ^  v
v      v   ^  v   ^  v
>>>>>>>>>>>>>>>>>>>>>v<<<<
                     v
                     v
                     v  v<<<<
                     v  v   ^
                     v  v
       >>>>v  >>>>v  v  v
       ^   v  ^   v  v  v<<
       ^   v  ^   v  v  v
       ^   v  ^   v  v  v
       ^<<<v<<<<<<<<<<<<<
           v
           v
           v
           v
       O<<<<

ECMAScript 6 Javascript (399 401 431)

Has to be run in a browser supporting ECMAScript 6 due to the arrow functions.

Here are fiddles which have been altered to run in any (common) browser by not using arrow functions. They also print to a textarea instead:

Normal
Animated

Golfed Version

i=prompt(),v=[],c=0,x=[0],y=[0],s='unshift',k='slice',t='sort',h=[0,-1,0,1,0]
while(c<i.length){m='wasd'.indexOf(i[c++]);v[s]('^<v>'[m]);x[s](x[0]+h[m]);y[s](y[0]+h[m+1])}f=(a,b)=>a-b
q=x[k]()[t](f)[0],e=x[k]()[t]((a,b)=>b-a)[0],w=y[k]()[t](f)[0],o=[]
while((i=y.pop())!=null){i-=w;j=x.pop()-q;t=(o[i]||Array(e+1-q).join(" ")).split("");t.splice(j,1,v.pop()||"@");o[i]=t.join("")}alert(o.join("\n"))

Animated GIF:

One of the OP's examples:

The example from Stretch Maniac:

Ungolfed

Here is a (slightly) ungolfed version from sometime before I started really golfing it down:

var input = prompt(),
    values = [],
    c = 0,
    x = [0],
    y = [0],
    s = 'unshift';
while (c < input.length) {
    var mapped = 'wasd'.indexOf(input[c++]);
    values[s]('^<v>'[mapped]);
    x[s](x[0]+[0, -1, 0, 1][mapped]);
    y[s](y[0]+[-1, 0, 1, 0][mapped]);
}

var minX = x.slice().sort(function (a,b){return a-b})[0];
var maxX = x.slice().sort(function (a,b){return b-a})[0];
var minY = y.slice().sort(function (a,b){return a-b})[0];

var output = [];
while((i=y.pop())!=null) {
    i-=minY;
    j=x.pop()-minX;
    t=(output[i]||Array(maxX+1-minX).join(" ")).split("");
    t.splice(j,1,values.pop()||"@");
    output[i]=t.join("");
}

console.log(output.join("\n"));


Reflective evolutionary algorithm You have to write a program, implementing a function digitsum(int i). The program has to modify its own code (for languages, where this is not possible with f.e. reflection, please be creative) to get itself to solve the goal.

You start with

function digitsum(int i){
    return i;
}

and implement an evolutionary algorithm that will modify the above function until it returns valid digitsums on function call.

As this is a popularity contest, you have very much free hands, please be creative!

Guidelines:

Start with the defined function (translated to your language of course).
Print out at least the fittest function of each generation.
Print out your working solution tested for 0 < i < 10000.
Be creative!

Do not:

Hint your program to the solution, please use your whole language options!
Throw errors to the console.
Use any external input. You can write and save to files created by your program. No internet.

The valid solution with the most upvotes wins!

C#

This might not be completeley what you envisioned, but this is the best I could do right now. (At least with C# and CodeDom).

So how it works:

It calculates the digitsum base 2 (the base wasn't specified in the statement)
It tries to generate an expression with a lot of terms that look like ((i & v1) >> v2). These terms will be the genes that will be mutated through the run.
The fitness function simply compares the values with a pre-calculated array, and uses the sum of the absolute value of the differences. This means a 0 value means we have arrived to the solution, and the less the value the fitter the solution.

The code:

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;

namespace Evol
{
    class MainClass
    {
        const int BASE = 2;
        static int[] correctValues;
        static List<Evolution> values = new List<Evolution>();

        public static CodeCompileUnit generateCompileUnit(CodeStatementCollection statements) {
            CodeCompileUnit compileUnit = new CodeCompileUnit();
            CodeNamespace samples = new CodeNamespace("CodeGolf");
            compileUnit.Namespaces.Add(samples);
            samples.Imports.Add(new CodeNamespaceImport("System"));
            CodeTypeDeclaration digitSumClass = new CodeTypeDeclaration("DigitSum");
            samples.Types.Add(digitSumClass);
            CodeMemberMethod method = new CodeMemberMethod();
            method.Name = "digitsum";
            method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            method.ReturnType = new CodeTypeReference (typeof(int));
            method.Parameters.Add (new CodeParameterDeclarationExpression (typeof(int), "i"));
            method.Statements.AddRange (statements);
            digitSumClass.Members.Add(method);
            return compileUnit;
        }

        public static long CompileAndInvoke(CodeStatementCollection statements, bool printCode) {
            CompilerParameters cp = new CompilerParameters();
            cp.ReferencedAssemblies.Add( "System.dll" );
            cp.GenerateInMemory = true;
            CodeGeneratorOptions cgo = new CodeGeneratorOptions ();
            CodeDomProvider cpd = new CSharpCodeProvider ();
            CodeCompileUnit cu = generateCompileUnit (statements);
            StringWriter sw = new StringWriter();
            cpd.GenerateCodeFromCompileUnit(cu, sw, cgo);
            if (printCode) {
                System.Console.WriteLine (sw.ToString ());
            }

            var result = cpd.CompileAssemblyFromDom (cp, cu);

            if (result.Errors.Count != 0) {
                return -1;
            } else {
                var assembly = result.CompiledAssembly;
                var type = assembly.GetType ("CodeGolf.DigitSum");
                var method = type.GetMethod ("digitsum");
                long fitness = CalcFitness (method);
                return fitness;
            }
        }

        public static long CalcFitness(MethodInfo method) {
            long result = 0;
            for (int i = 0; i < correctValues.Length; i++) {
                int r = (int)method.Invoke (null, new Object[] { i });
                result += Math.Abs (r - correctValues[i]);
            }
            return result;
        }

        public static CodeStatementCollection generateCodeDomFromString (Term[] terms) {
            CodeStatementCollection statements = new CodeStatementCollection ();
            CodeExpression expression = null;
            foreach (Term term in terms) {
                CodeExpression inner = new CodeArgumentReferenceExpression ("i");
                if (term.and.HasValue) {
                    inner = new CodeBinaryOperatorExpression (inner, CodeBinaryOperatorType.BitwiseAnd, new CodePrimitiveExpression(term.and.Value));
                }
                if (term.shift.HasValue) {
                    inner = new CodeBinaryOperatorExpression (inner, CodeBinaryOperatorType.Divide, new CodePrimitiveExpression(Math.Pow (2, term.shift.Value)));
                }
                if (expression == null) {
                    expression = inner;
                } else {
                    expression = new CodeBinaryOperatorExpression (expression, CodeBinaryOperatorType.Add, inner);
                }
            }
            statements.Add (new CodeMethodReturnStatement (expression));
            return statements;
        }

        public static void Main (string[] args)
        {
            correctValues = new int[10001];
            for (int i = 0; i < correctValues.Length; i++) {
                int result = 0;
                int num = i;
                while (num != 0) {
                    result += num % BASE;
                    num /= BASE;
                }
                correctValues [i] = result;
            }
            values.Add (new Evolution (new Term[] { new Term (null, null) }));
            Random rnd = new Random ();
            while (true) {
                // run old generation
                foreach (var val in values) {
                    CodeStatementCollection stat = generateCodeDomFromString (val.term);
                    long fitness = CompileAndInvoke (stat, false);
                    val.score = fitness;
                    System.Console.WriteLine ("Fitness: {0}", fitness);
                }
                Evolution best = values.Aggregate ((i1, i2) => i1.score < i2.score ? i1 : i2);
                CodeStatementCollection bestcoll = generateCodeDomFromString (best.term);
                CompileAndInvoke (bestcoll, true);
                System.Console.WriteLine ("Best fitness for this run: {0}", best.score);

                if (best.score == 0)
                    break;

                // generate new generation
                List<Evolution> top = values.OrderBy (i => i.score).Take (3).ToList();
                values = new List<Evolution> ();
                foreach (var e in top) {
                    values.Add (e);
                    if (e.term.Length < 16) {
                        Term[] newTerm = new Term[e.term.Length + 1];
                        for (int i = 0; i < e.term.Length; i++) {
                            newTerm [i] = e.term [i];
                        }
                        int rrr = rnd.Next (0, 17);
                        newTerm [e.term.Length] = new Term ((int)Math.Pow(2,rrr), rrr);
                        values.Add (new Evolution (newTerm));
                    }
                    {
                        int r = rnd.Next (0, e.term.Length);
                        Term[] newTerm = (Term[])e.term.Clone ();
                        int rrr = rnd.Next (0, 17);
                        newTerm [r] = new Term ((int)Math.Pow(2,rrr), rrr);
                        values.Add (new Evolution (newTerm));
                    }
                }
            }
        }

        public struct Term {
            public int? and;
            public int? shift;

            public Term(int? and, int? shift) {
                if (and!=0) {
                    this.and = and;
                } else this.and = null;
                if (shift!=0) {
                    this.shift = shift;
                } else this.shift=null;
            }
        }

        public class Evolution {
            public Term[] term;
            public long score;

            public Evolution(Term[] term) {
                this.term = term;
            }
        }
    }
}

Tested on OSX with Mono C# compiler version 3.2.6.0.

At each iteration it prints the fitness value of the current calculation. At the end it will print the best solution along with its fitness. The loop will run until one of the results have a fitness value of 0.

This is how it starts:

// ------------------------------------------------------------------------------
//  <autogenerated>
//      This code was generated by a tool.
//      Mono Runtime Version: 4.0.30319.17020
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </autogenerated>
// ------------------------------------------------------------------------------

namespace CodeGolf {
    using System;

    public class DigitSum {

        public static int digitsum(int i) {
            return i;
        }
    }
}

Best fitness for this run: 49940387

And after a while (takes around 30 minutes), this is how it ends (showing the last and almost last iteration):

// ------------------------------------------------------------------------------
//  <autogenerated>
//      This code was generated by a tool.
//      Mono Runtime Version: 4.0.30319.17020
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </autogenerated>
// ------------------------------------------------------------------------------

namespace CodeGolf {
    using System;

    public class DigitSum {

        public static int digitsum(int i) {
            return ((((((((((((((((i & 4096) / 4096) + ((i & 16) / 16)) + ((i & 32) / 32)) + ((i & 128) / 128)) + ((i & 65536) / 65536)) + ((i & 1024) / 1024)) + ((i & 8) / 8)) + ((i & 2) / 2)) + ((i & 512) / 512)) + ((i & 4) / 4)) + (i & 1)) + ((i & 256) / 256)) + ((i & 128) / 128)) + ((i & 8192) / 8192)) + ((i & 2048) / 2048));
        }
    }
}

Best fitness for this run: 4992
Fitness: 4992
Fitness: 7040
Fitness: 4993
Fitness: 4992
Fitness: 0
Fitness: 4992
Fitness: 4992
Fitness: 7496
// ------------------------------------------------------------------------------
//  <autogenerated>
//      This code was generated by a tool.
//      Mono Runtime Version: 4.0.30319.17020
//
//      Changes to this file may cause incorrect behavior and will be lost if
//      the code is regenerated.
//  </autogenerated>
// ------------------------------------------------------------------------------

namespace CodeGolf {
    using System;

    public class DigitSum {

        public static int digitsum(int i) {
            return (((((((((((((((((i & 4096) / 4096) + ((i & 16) / 16)) + ((i & 32) / 32)) + ((i & 64) / 64)) + ((i & 32768) / 32768)) + ((i & 1024) / 1024)) + ((i & 8) / 8)) + ((i & 2) / 2)) + ((i & 512) / 512)) + ((i & 4) / 4)) + (i & 1)) + ((i & 256) / 256)) + ((i & 128) / 128)) + ((i & 8192) / 8192)) + ((i & 2048) / 2048)) + ((i & 32768) / 32768));
        }
    }
}

Best fitness for this run: 0

Notes:

CodeDOM doesn't support the left shift operator so instead of a >> b I'm using a / 2^b
The initial iteration is just a return i; as required by the problem.
In the first few iterations priority is given to adding new terms (genes) to the sum. Later there is more priority in changing values (mutation) in terms randomly.
I'm generating terms that look like i & a >> a instead of i & a >> b, as in the latter case the evolution was simply too slow to be practical.
This is also why the solution is limited to finding an answer in the form return (i&a>>b)+(i&c>>d)+..., as any other kind (like trying to generate a "proper" code, with loops, assignments, condition checks, etc.) would simply converge too slowly. Also this way it is very easy to define the genes (each of the term), and is very easy to mutate them.
This is also the reason why I'm adding the digits in base 2 (the base wasn't specified in the problem statement, so I consider this fine). A base 10 solution would've been just to slow, and also it would've been really hard to define the actual genes. Adding a loop would also mean that you have to manage the running code, and find a possible way to kill it, before it enters a potentially infinite loop.
Genes are only mutated, there is no crossover in this solution. I don't know whether adding that would speed up the evolution process or not.
The solution is only tested for numbers 0..10000 (if you check the found solution you can see that it won't work for numbers larger than 16384)
The whole evolution process can be checked at this gist.


Jelly, 9 6 bytes

ṗ6ḅ-ċ0

O(n6) solution.

Try it online!

How it works

ṗ6ḅ-ċ0  Main link. Argument: n

ṗ6      Cartesian power 6; build all 6-tuples (a, x, b, y, c, z) of integers in
        [1, ..., n]. The challenge spec mentions [0, ..., n-1], but since there
        are three summands on each side, this doesn't matter.
  ḅ-    Unbase -1; convert each tuple from base -1 to integer, mapping (a, ..., z)
        to a(-1)**5 + x(-1)**4 + b(-1)**3 + y(-1)**2 + c(-1)**1 + z(-1)**0, i.e.,
        to -a + x - b + y - c + z = (x + y + z) - (a + b + c). This yields 0 if and
        only if the 6-tuple is a match.
    ċ0  Count the number of zeroes.


RegEx-golf: match all contents in a string Your task is to write a RegEx that matches everything inside strings.

A string is defined as everything surrounded by (but not including) two unescaped ".

A " can be escaped by \, which can also be escaped again.

Testcases

string:  ab\c"defg\\\"hi"jkl"mn\\\\"opqrst""
matches:      ^^^^^^^^^^     ^^^^^^        ^ (the empty string)

Scoring

Shortest solution wins.

Specs

Please specify the flavour used.
The input will have balanced ".
There will be no \ that immediately precedes a string-beginning-delimiter. For example, you would not need to handle abc\"def"

PCRE, 21 20 15 19 bytes
(.|^)"\K(\\.|[^"])*

Try it here.
This matches a character (or the beginning of the input) before the beginning double quote and then reset the match, to make sure the double quote isn't shared with another match.
PCRE, 25 23 bytes
Thanks to Martin Büttner for golfing off 2 bytes.
(\\.|[^"])*+(?!"(?R)|$)

Try it here.
Explanation
(
    \\.|[^"]     # An escaped character, or a character that isn't a double quote
)*+              # Possessive zero-or-more quantifier, which means backtracking
                 # could not happen after first match is found. That means if \\.
                 # matched, it would never switch to [^"], because it is always a
                 # match if it just stopped after the \\. without backtracking.
(?!"(?R)|$)      # Make sure it is not followed by a double quote and another
                 # match, or the end of the input.

Note that the possessive quantifier (*+) made sure the negative lookahead always begins after a whole string, or a whole segment of non-string.
There are 4 cases:

The match begins anywhere outside of a string. \\. would never match a double quote according to the clarification. It could only end just before the next double quote which begins a string, or the end of input. Both cases fails the negative lookahead.
The match begins at the beginning of a string. (\\.|[^"])*+ would match a complete string. The next character must be a double quote, and couldn't be the end of input. After the double quote it is outside of the string, so it couldn't be another match. So it passes the negative lookahead.
The match begins at the end of a string. It matches an empty string in the same way as the previous case. But it doesn't matter according to the clarification.
The match begins in the middle of a string. Impossible because matches don't overlap.


The struggling college student's GPA Calculator GPA Calculator

(GPA = Grade Point Average)

You are a stressed out college student during finals week. Instead of studying for your exams coming up, you decide it is best to determine what GPA you will have at the end of the semester. This way you have data to back up your decision of staying up all night to get that A in Calculus instead of a B to remain on the Dean's list!

Being a computer science major you want to find the coolest way to determine this GPA. Of course the coolest way is with the shortest code! This is code-golf, so shortest code in bytes wins!

Details

The college that you go to uses a basic GPA scaled along with credit hours.
A letter grade of A is a 4.0, B is 3.0, C is 2.0, D is 1.0, and F is 0.0
Your GPA is a weighted GPA, so an A in a 4 credit hour class counts 4 times as much as an A in a 1 credit hour class (See examples below for more weight explanantion)
Credit Hours range from 1-4
Your program will need to have a list of two command line inputs, Grade and Credit Hour. You can determine the best way to input these into your program through the command line. You do not need to worry about too many inputs, but ensure your code can handle a 19 credit hour semester.

i.e. Input: A 1 B 4 C 2…

Your program must output the GPA, using 3 digits (i.e. X.XX)
Your GPA needs to be rounded to two decimal places. Round in whichever way you like (floor, ceil, base, etc…)

Input Examples(Choose whichever one works best for your design)

A1B3C2F3B4
A1 B3 C2 F3 B4
A 1 B 3 C 2 F 3 B 4
A,1,B,3,C,2,F,3,B,4
A1,B3,C2,F3,B4

Or any of the above combinations where you use the format of listing all grades, then their credit hours:

i.e. A B A A 3 4 1 1

Examples

Input - A 3 B 4 A 1 A 1
Output - 3.56
Explanation: (4.0 * 3 + 3.0 * 4 + 4.0 * 1 + 4.0 * 1)/(3+4+1+1) = 3.555556 rounded off to 3.56

Input - A 4 F 2 C 3 D 4
Output - 2.00
Explanation: (4.0 * 4 + 0.0 * 2 + 2.0 * 3 + 1.0 * 4)/(4+2+3+4) = 2 rounded off to 2.00

Jelly,  15  21 bytes (12 with no rounding)
+6 bytes for the strict formatting (almost certainly possible in less but it's bed time)
Oạ69.Ḟ×S×ȷ2÷⁹S¤RLDż”.

A full program taking the grades and the respective credit hours which prints the calculated GPA (Note: the rounding method is to floor, as allowed in the OP).
Try it online!
With no rounding for 12 bytes:
Oạ69.Ḟ×S÷⁹S¤

How?
Oạ69.Ḟ×S×ȷ2÷⁹S¤RLDż”. - Link: list of characters, grades; list of number, creditHours
                      -                                   e.g. "AFBDC", [5, 2, 4, 1, 2]
O                     - cast to ordinals (vectorises)          [65,70,66,68,67]
  69.                 - literal 69.5
 ạ                    - absolute difference (vectorises)       [4.5,0.5,3.5,1.5,2.5]
     Ḟ                - floor (vectorises)                     [4,0,3,1,2]
      ×               - multiply by creditHours (vectorises)   [20,0,12,1,4]
       S              - sum                                    37
         ȷ2           - literal 100
        ×             - multiply                               3700
              ¤       - nilad followed by link(s) as a nilad:
            ⁹         -   chain's right argument, creditHours  [5, 2, 4, 1, 2]
             S        -   sum                                  14
           ÷          - division                               264.2857142857143
               R      - range                                  [1,2,3,...,264]
                L     - length                                 264
                 D    - digits                                 [2,6,4]
                   ”. - literal '.'
                  ż   - zip together                           [[2,'.'],6,4]
                      - implicit print (smashing)              2.64


Bash + coreutils, 30

(seq 0 127;seq -128 -1)|nl -v0

Try it online!


Balanced triplet brackets A "triplet bracket" (that I made up for this challenge) is one of the following:

(...+...)
[...:...]
{...|...}
<...-...>

A balanced triplet bracket string (BTBS for short) is either an empty string, two BTBSes concatenated, or one of the above triplet brackets with each ... replaced with a BTBS.

Your task is to write a program or function that checks whether a string that consists of only (+)[:]{|}<-> is balanced. Shortest code wins.

Examples

Your program should return truthy for the following strings:

(+)(+)(+)
[[[:]:]:(+(+))]{<->|<(+)->[:]}(+)
<<<<<<<<<<<<->->->->->->->->->->->->
{|(+[:<-{|(+[:<->])}>])}
[[[:]:[:]]:[[:]:[:]]]
{[:](+)|<->{|}}[(+)<->:{|}(+)]

Your program should return falsy for the following strings:

:[
<|>
(+(+)
[:][:](+[[:]):]
{|{|{|(+{|{|{|}}}}}+)}[:]{|}
{{||}}
<<->-<->-<->>
[(+):((+)+)+(+(+))]
<<<<<->->->->->->


Parse a Baseball Pitch String Take an arbitrarily sized string as input. This string represents a baseball plate appearance, in which each character represents a pitch as follows:

Strike: S
Ball: B
Foul ball: F
Hit by pitch: H
Ball in play: X

(For those wondering, this is a very very simplified version of Retrosheet's notation)

Your program must output 1 of 3 possible outputs to signify 1 of the mutually exclusive outcomes:

Strikeout
Walk
Ball in play

It doesn't matter what the outputs are exactly, as long as they are guaranteed to be distinct.

For those unfamiliar with the rules of baseball:

3 strikes results in a strikeout
4 balls results in a walk
A foul ball is a strike UNLESS the batter already has 2 strikes, in that case nothing happens
Hit by pitch immediately results in a walk
"Ball in play" immediately results in the "Ball in play" outcome

You may assume that:

the input string is encoded as ASCII
the input string represents an entire plate appearance (in other words it will end in one of the 3 outcomes above)
there are no other characters other than the ones above

You may not assume that:

there are no extra pitches/characters after the plate appearance is supposed to legally end
your program must return on the last pitch/character

Examples:

"Strikeout"fy:

SSS
SBSBS
BBBSSS
BSBSBS
BSFFBFS
BBSSFFFFFFFFS
SSSBBBB
FSS

"Walk"y:

BBBFB
BBBB
BBBSB
SSBBBB
SSH
SBSFFBFFFFBFFFFFFFFB
BBBBSSS
HSSS
SBBBBSS

"Ball in play"ly:

X
SSX
BBBX
SBSX
FFFFFFFFFFFFFFX
XBSBSBSB

This is code-golf, so fewest bytes wins.

(This challenge was inspired by this YouTube video)

Retina 0.8.2, 22 bytes

4=`B
H
2`F|S

1!`[XHS]

Try it online! Link includes test cases. Outputs X for ball in play, H for walk, and S for strikeout. Explanation:

4=`B
H

The fourth ball results in a walk, same as hit by pitch.

2`F|S

The first two foul balls/strikes are ignored.

1!`[XHS]

Take the first available result.


Can you fold a hexomino into a cube? One of my kid's favorite toys is a set like this.  Actually its one of my favorite toys - I've been playing with it and its been giving me some PPCG challenge ideas.  Here's one:

Write a program or function that takes an ASCII line drawing as input and decides whether or not it folds into a cube.

Input

Input will consist of exactly one hexomino built from squares like this:

+-+
| |
+-+

For example a valid input heximino is:

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

Output

A truthy value if the hexomino can be folded into a cube, or
A falsey value otherwise.

To save us a bit of work, wikipedia has nice graphics of:

All 35 hexominoes:

All 11 hexominoes that fold into cubes:

Notes

Input hexominoes may have any rotation or reflection, not just those shown in the images above
Input hexominoes may have leading spaces, but will be correctly aligned with respect to themselves
Input hexominoes may have trailing space at the end of lines and trailing newlines at the end of input

PMA/Snails, 130
.!(z\ |o{c..!(z\ }3){w=(..!(z\ )|b..!(z\ )o{..!(z\ }2|c{..!(z\ }1,2w..!(z\ )|w{..!(z\ }1,2c..!(z\ }4o..!(z\ )(..!(z\ )|n..!(z\ )`2

or more "readably",
?
.!(z\  | o{c..!(z\ }3  )
{w =( ..!(z\ ) | b ..!(z\ ) o {..!(z\ }2  | c {..!(z\ }1,2w..!(z\ ) | w {..!(z\ }1,2c..!(z\  }4
o  ..!(z\ ) ( ..!(z\ ) | n ..!(z\ ) `2

Unusually, a problem came along that can be handled by the limited amount of features implemented so far. The !(z\ ) pattern determines that the current position is at the space in the middle of a square using a negative assertion that there is a space in some "octilinear" direction. The general idea is to check for a pattern that places a square at each of the 5 necessary locations relative to the square that the match starts on. Also, it needs to check that it is not in a 2x2 block of squares. Before the program would work, I had to fix a bug with the parsing of parentheses.
If the hexomino does not map a cube, 0 is printed. If it does, some positive integer is printed (number of matches).
I adapted this polyomino generator to create all possible test cases:
n=input()
r=range
T=lambda P:set(p-min(p.real for p in P)-min(p.imag for p in P)*1j for p in P)
A=[]
for i in r(1<<18):
 P=[k%3+k/3*1j for k in r(18)if i>>k&1]
 C=set(P[:1])
 for x in P:[any(p+1j**k in C for k in r(4))and C.add(p)for p in P]
 P=T(P)
 if not(C^P or P in A or len(P)-n):
  #for y in r(4):print''.join(' *'[y+x*1j in P] for x in r(6))
  o = [ [' ']*13 for _ in r(9)]
  for y in r(4):
   for x in r(6):
    if y+x*1j in P: X=2*x;Y=2*y; o[Y][X]=o[Y+2][X]=o[Y][X+2]=o[Y+2][X+2]='+'; o[Y][X+1]=o[Y+2][X+1]='-';o[Y+1][X+2]=o[Y+1][X]='|'
  print '\n'.join(map(''.join,o))
  A+=[T([p*1j**k for p in P])for k in r(4)]