Hungarian alphabetical order For those who wish a lot more challenge then the old Spanish alphabetical order, let's take a look at how the Hungarian alphabet is ordered.

a, á, b, c, cs, d, dz, dzs, e, é, f, g, gy, h, i, í, j, k, l, ly, m, n, ny, o, ó, ö, ő, p, q, r, s, sz, t, ty, u, ú, ü, ű, v, w, x, y, z, zs

actually, q, w, x and y are not used in Hungarian words, but they are included for loanwords and foreign names. Foreign accented characters which are not part of the Hungarian alphabet (like ñ), have the same priority as the non-accented ones, but we disregard them for this challenge.
The rules, summarized:

Digraphs (cs, sz, etc.) and the trigraph (dzs) are considered as they were letters on their own.

cudar
cukor
cuppant
csalit
csata

If the same digraph or trigraph occurs twice directly after each other in a word, they are written in a simplified way: ssz instead of szsz, ddzs instead of dzsdzs but for the alphabetical order the non-simplified order is used. For example kasza < kaszinó < kassza, because kassza is used as k+a+sz+sz+a for the sake of ordering. Sometimes you can find the non-contracted version in a word, in case of compound words.

kasza
kaszinó
kassza
kaszt
nagy
naggyá
nagygyakorlat
naggyal
nagyít

capitalization doesn't matter, with the exception when the two words would be exactly the same without capitalization, in which case the lower case letter has priority

jácint
Jácint
Zoltán
zongora

The short and long versions of accented vowels have the same priority (a - á, e -é, i - í, o - ó, ö - ő, u - ú ü - ű), with a single exception: if the two words would otherwise be exactly the same, the short vowel has priority over the long vowel. Note, that the vowels with umlaut (ö and ü) are completely different characters from o and u.

Eger
egér
író
iroda
irónia
kerek
kerék
kérek
szúr
szül

Hyphens or spaces (for example, in compound words, names, etc.) are completely ignored

márvány
márványkő
márvány sírkő
Márvány-tenger
márványtömb

The task
Your program/function receives strings, composed of characters from the Hungarian alphabet (both lower- and upper-case), but a string might contain spaces or hyphens. For simplicity's sake, the minus sign (ASCII 45) can be used as a hyphen. Note that some characters (like the ő) are not part of ASCII. You can use any encoding you wish, if it supports all the required characters.
You have to order the lines correctly and display/return the result.
You can use any randomly ordered subset of the above examples for testing.
EDIT:
Please don't use any built-in or other way which already knows the Hungarian alphabetical ordering by itself. It would make the competition pointless, and take all the challenge from finding the best regular expression or the best code golfing tricks.
EDIT2:
To clear a clarification asked by isaacg: "two strings that only differ by capitalization and long vs. short vowels, but differs in both ways" : Although no rule in the official document explicitly addresses this question, an example found within points to the length of the vowel having more importance than the capitalization.

Java 8, 742 bytes
Could reduce by another 3 bytes naming the function s instead of sort or another 16 bytes if not counting class-definition.

public class H{String d="cs|dzs?|gy|ly|sz|ty|zs";void sort(java.util.List<String>l){l.sort((a,b)->{String o="-a-á-b-cs-dzs-e-é-f-gy-h-i-í-j-k-ly-m-ny-o-ó-ö-ő-p-q-r-sz-ty-u-ú-ü-ű-v-w-x-y-zs-";int i=c(r(a),r(b),r(o));return i!=0?i:(i=c(a,b,o))!=0?i:b.charAt(0)-a.charAt(0);});}String r(String a){for(int i=0;i<8;i++)a=a.toLowerCase().replace("ááéíóőúű".charAt(i),"aaeioöuü".charAt(i));return a;}int c(String a,String b,String o){a=n(a);b=n(b);while(!"".equals(a+b)){int i=p(a,o),j=p(b,o);if(i!=j)return i-j;a=a.substring(i%4);b=b.substring(j%4);}return 0;}int p(String a,String o){a=(a+1).replaceAll("("+d+"|.).*","-$1");return o.indexOf(a)*4+a.length()-1;}String n(String a){return a.toLowerCase().replaceAll("(.)(?=\\1)("+d+")| |-","$2$2");}}

Can be used like this:
new H().sort(list);

Test-suite:
public static void main(String[] args) {
    test(Arrays.asList("cudar", "cukor", "cuppant", "csalit", "csata"));
    test(Arrays.asList("kasza", "kaszinó", "kassza", "kaszt", "nagy", "naggyá", "nagygyakorlat", "naggyal",
            "nagyít"));
    test(Arrays.asList("jácint", "Jácint", "Zoltán", "zongora"));
    test(Arrays.asList("Eger", "egér", "író", "iroda", "irónia", "kerek", "kerék", "kérek", "szúr", "szül"));
    test(Arrays.asList("márvány", "márványkő", "márvány sírkő", "Márvány-tenger", "márványtömb"));
}

private static void test(final List<String> input) {
    final ArrayList<String> random = randomize(input);
    System.out.print(input + " -> " + random);
    new H().sort(random);
    System.out.println(" -> " + random + " -> " + input.equals(random));
}

private static ArrayList<String> randomize(final List<String> input) {
    final ArrayList<String> temp = new ArrayList<>(input);
    final ArrayList<String> randomOrder = new ArrayList<>(input.size());
    final Random r = new Random();
    for (int i = 0; i < input.size(); i++) {
        randomOrder.add(temp.remove(r.nextInt(temp.size())));
    }
    return randomOrder;
}

yielding
[cudar, cukor, cuppant, csalit, csata] -> [csata, cudar, cuppant, csalit, cukor] -> [cudar, cukor, cuppant, csalit, csata] -> true
[kasza, kaszinó, kassza, kaszt, nagy, naggyá, nagygyakorlat, naggyal, nagyít] -> [naggyá, kassza, kaszinó, nagygyakorlat, nagyít, nagy, kaszt, kasza, naggyal] -> [kasza, kaszinó, kassza, kaszt, nagy, naggyá, nagygyakorlat, naggyal, nagyít] -> true
[jácint, Jácint, Zoltán, zongora] -> [Zoltán, jácint, zongora, Jácint] -> [jácint, Jácint, Zoltán, zongora] -> true
[Eger, egér, író, iroda, irónia, kerek, kerék, kérek, szúr, szül] -> [egér, Eger, kerék, iroda, író, kerek, kérek, szúr, irónia, szül] -> [Eger, egér, író, iroda, irónia, kerek, kerék, kérek, szúr, szül] -> true
[márvány, márványkő, márvány sírkő, Márvány-tenger, márványtömb] -> [márványtömb, márványkő, Márvány-tenger, márvány sírkő, márvány] -> [márvány, márványkő, márvány sírkő, Márvány-tenger, márványtömb] -> true

Ungolfed:
public class HungarianOrder {

    String d = "cs|dzs?|gy|ly|sz|ty|zs";

    void sort(java.util.List<String> l) {
        l.sort((a, b) -> {
            String o = "-a-á-b-cs-dzs-e-é-f-gy-h-i-í-j-k-ly-m-ny-o-ó-ö-ő-p-q-r-sz-ty-u-ú-ü-ű-v-w-x-y-zs-";
            int i = c(r(a), r(b), r(o));
            return i != 0 ? i
                    : (i = c(a, b, o)) != 0 ? i
                            : b.charAt(0) - a.charAt(0);
        });
    }

    // toLower + remove long accent
    String r(String a) {
        for (int i = 0; i < 8; i++)
            a = a.toLowerCase().replace("ááéíóőúű".charAt(i), "aaeioöuü".charAt(i));
        return a;
    }

    // iterate over a and b comparing positions of chars in o
    int c(String a, String b, String o) {
        a = n(a);
        b = n(b);
        while (!"".equals(a + b)) {
            int i = p(a, o), j = p(b, o);
            if (i != j)
                return i - j;
            a = a.substring(i % 4);
            b = b.substring(j % 4);
        }
        return 0;
    }

    // find index in o, then looking if following characters match
    // return is index * 4 + length of match; if String is empty or first character is unknown -1 is returned
    int p(String a, String o) {
        a = (a+1).replaceAll("("+d+"|.).*", "-$1");
        return o.indexOf(a) * 4 + a.length() - 1;
    }

    // expand ddz -> dzdz and such
    String n(String a) {
        return a.toLowerCase().replaceAll("(.)(?=\\1)("+ d +")| |-", "$2$2");
    }
}

I am using Java's List-type and the order()-function of it, but the comparator is all mine.


Minimum-cost flow problem A flow network is a directed graph G = (V, E) with a source vertex s ϵ V and a sink vertex t ϵ V, and where every edge (u, v) ϵ E on the graph (connecting nodes u ϵ V and v ϵ V) has 2 quantities associated with it:

c(u, v) >= 0, the capacity of the edge
a(u, v) >= 0, the cost of sending one unit through the edge

We define a function 0 <= f(u, v) <= c(u, v) to be the number of units being passed through a given edge (u, v). Thus, the cost for a given edge (u, v) is a(u, v) * f(u, v). The minimum-cost flow problem is defined as minimizing the total cost over all edges for a given flow amount d, given by the following quantity:

The following constraints apply to the problem:

Capacity requirements: the flow through a given edge may not exceed the capacity of that edge (f(u, v) <= c(u, v)).
Skew symmetry: the flow though a given edge must be antisymmetric when the direction is reversed (f(u, v) = -f(v, u)).
Flow conservation: the net flow into any non-sink non-source node must be 0 (for each u ∉ {s, t}, summing over all w, sum f(u, w) = 0).
Required flow: the net flow out of the source and the net flow into the sink must both equal the required flow through the network (summing over all u, sum f(s, u) = sum f(u, t) = d).

Given a flow network G and a required flow d, output the minimum cost for sending d units through the network. You may assume that a solution exists. d and all capacities and costs will be non-negative integers. For a network with N vertices labeled with [0, N-1], the source vertex will be 0 and the sink vertex will be N-1.

This is code-golf, so the shortest answer (in bytes) wins. Remember that this is a competition within languages as well as between languages, so don't be afraid to post a solution in a verbose language.

Built-ins are allowed, but you are encouraged to include solutions without builtins, either as an additional solution in the same answer, or as an independent answer.

Input may be in any reasonable manner that includes the capacities and costs of each edge and the demand.

Test Cases

Test cases are provided in the following format:

c=<2D matrix of capacities> a=<2D matrix of costs> d=<demand> -> <solution>

c=[[0, 3, 2, 3, 2], [3, 0, 5, 3, 3], [2, 5, 0, 4, 5], [3, 3, 4, 0, 4], [2, 3, 5, 4, 0]] a=[[0, 1, 1, 2, 1], [1, 0, 1, 2, 3], [1, 1, 0, 2, 2], [2, 2, 2, 0, 3], [1, 3, 2, 3, 0]] d=7 -> 20
c=[[0, 1, 1, 5, 4], [1, 0, 2, 4, 2], [1, 2, 0, 1, 1], [5, 4, 1, 0, 3], [4, 2, 1, 3, 0]] a=[[0, 1, 1, 2, 2], [1, 0, 2, 4, 1], [1, 2, 0, 1, 1], [2, 4, 1, 0, 3], [2, 1, 1, 3, 0]] d=7 -> 17
c=[[0, 1, 4, 5, 4, 2, 3], [1, 0, 5, 4, 3, 3, 5], [4, 5, 0, 1, 5, 5, 5], [5, 4, 1, 0, 3, 2, 5], [4, 3, 5, 3, 0, 4, 4], [2, 3, 5, 2, 4, 0, 2], [3, 5, 5, 5, 4, 2, 0]] a=[[0, 1, 4, 2, 4, 1, 1], [1, 0, 3, 2, 2, 1, 1], [4, 3, 0, 1, 4, 5, 2], [2, 2, 1, 0, 2, 2, 3], [4, 2, 4, 2, 0, 4, 1], [1, 1, 5, 2, 4, 0, 2], [1, 1, 2, 3, 1, 2, 0]] d=10 -> 31
c=[[0, 16, 14, 10, 14, 11, 10, 4, 3, 16], [16, 0, 18, 19, 1, 6, 10, 19, 5, 4], [14, 18, 0, 2, 15, 9, 3, 14, 20, 13], [10, 19, 2, 0, 2, 10, 12, 17, 19, 22], [14, 1, 15, 2, 0, 11, 23, 25, 10, 19], [11, 6, 9, 10, 11, 0, 14, 16, 25, 4], [10, 10, 3, 12, 23, 14, 0, 11, 7, 8], [4, 19, 14, 17, 25, 16, 11, 0, 14, 5], [3, 5, 20, 19, 10, 25, 7, 14, 0, 22], [16, 4, 13, 22, 19, 4, 8, 5, 22, 0]] a=[[0, 12, 4, 2, 9, 1, 1, 3, 1, 6], [12, 0, 12, 16, 1, 2, 9, 13, 2, 3], [4, 12, 0, 2, 2, 2, 2, 10, 1, 1], [2, 16, 2, 0, 2, 1, 8, 4, 4, 2], [9, 1, 2, 2, 0, 5, 6, 23, 5, 8], [1, 2, 2, 1, 5, 0, 13, 12, 12, 1], [1, 9, 2, 8, 6, 13, 0, 9, 4, 4], [3, 13, 10, 4, 23, 12, 9, 0, 13, 1], [1, 2, 1, 4, 5, 12, 4, 13, 0, 13], [6, 3, 1, 2, 8, 1, 4, 1, 13, 0]] d=50 -> 213

These test cases were computed with the NetworkX Python library.

[R + lpSolve], 201 186 149 144 bytes

function(c,a,d,`^`=rep,N=ncol(c),G=diag(N),P=t(1^N),M=P%x%G+G%x%-P)lpSolve::lp(,a,rbind(M,diag(N*N)),c('=','<')^c(N,N*N),c(d,0^(N-2),-d,c))$objv

Try it online!

The code constructs the following Linear Problem and solve it using lpSolve package :

$$
\begin{align}
      min & \sum_{\forall x \in V}\  \sum_{\forall y \in V} A_{x,y} \cdot f_{x,y} \\
subject\ to : & \\
          & \sum_{x \in V} f_{v,x} - f_{x,v} = 0 & \forall v \in V : v \neq \{s,t\} \\
          & \sum_{x \in V} f_{s,x} - f_{x,s} = d \\
          & \sum_{x \in V} f_{t,x} - f_{x,t} = -d \\
          & f_{x,b} \leq C_{x,b}                 & \forall x \in V,\forall y \in V
\end{align}
$$
where :

\$V\$ is the set of vertices
\$s\$ s is the source vertex
\$t\$ s is the target (or sink) vertex
\$A_{x,y}\$ is the flow cost for edge x -> y
\$f_{x,y}\$ is the flow of edge x -> y in the optimal solution
\$d\$ is the required flow at sink (i.e. the demand at \$t\$ and the production at \$s\$)
\$C_{x,y}\$ is the maximum capacity of edge x -> y


The Solitude of Prime Numbers Recently I read the novel "The Solitude of Prime Numbers" where the main characters are somewhat compared to twin prime numbers ("always together, but never touching").

A twin prime is a prime number that is either \$\require{cancel}2\$ less or \$2\$ more than another prime number —for example, the twin prime pair \$(41, 43)\$. In other words, a twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin or prime pair. Wikipedia

Although I didn't like much the depressing novel, and since I have fallen into PPCG lately, that raised a question in my mind...
Task:
Given a positive integer number \$N > 4\$, find the lonely prime numbers (AKA isolated prime numbers) between the closest couples of twin primes.
Please note that in this case with the term lonely prime numbers, I mean all the prime numbers that are not twin primes and between couples of twin primes. That's why \$N > 4\$ because the first two couples of prime numbers are \$(3, 5)\$ and \$(5, 7)\$.
Example:

\$N = 90\$.
Find the first two couples of twin primes \$< N\$ and \$> N\$. They are: \$(71, 73)\$ and \$(101, 103)\$.
Find the lonely primes in the range \$> 73\$ and \$< 101\$.
They are: \$79, 83, 89, 97\$.

Special cases:
- If N is in between two twin prime numbers, find the closest couples of twin primes \$> N+1\$ and \$< N-1\$. Example: \$N=72\$, find the closest couples of twin primes \$> 73\$ and \$< 71\$ then exclude from the list \$71\$ and \$73\$ because they are not *lonely primes*. So for \$N = 72\$ the expected result is:  \$67, \cancel{71}, \cancel{73}, 79, 83, 89, 97\$
- If N belongs to a couple of twin primes, for example \$N = 73\$, the closest couples of twin primes are \$(71, 73)\$ and \$(101, 103)\$. If \$N = 71\$, the closest couples of twin primes are \$(59, 61)\$ and \$(71, 73)\$.
Test cases:
N = 70   >  Lonely primes are:  67
N = 71   >  Lonely primes are:  67
N = 72   >  Lonely primes are:  67, 79, 83, 89, 97 (not the twins 71 and 73)
N = 73   >  Lonely primes are:  79, 83, 89, 97
N = 90   >  Lonely primes are:  79, 83, 89, 97
N = 201  >  Lonely primes are:  211, 223
N = 499  >  Lonely primes are:  467, 479, 487, 491, 499, 503, 509

Rules:

Write a full program or function that will take the number N from standard input.
Output the list of lonely primes in a readable format as csv, list, array, etc.
Shortest code wins.
Please include (when possible) a testable online fiddle.

PowerShell v2+, 237 149 147 231 216 181 174 169 166 bytes

param($n)filter f($a){'1'*$a-match'^(?!(..+)\1+$)..'}for($i=$n;!((f $i)-and(f($i+2)))){$i++}for(){if(f(--$i)){if((f($i-2))-or(f($i+2))){if($i-lt$n-1){exit}}else{$i}}}

Takes input $n. Defines a new function f as the regex prime function (here returning a Boolean if the input is a prime or not).

The next part sets $i to be equal to $n, then loops upward until we find the bottom half of our twin prime pair upper bound. E.g., for input 90, this stops at $i=101.

Then, we loop from the upper bound downward. I know, it looks like an infinite loop, but it'll eventually end.

If the current number is a prime (f(--$i)), but its +/- 2 isn't a prime, we add $i to the pipeline. However, if its +/- 2 is a prime, we check whether we're lower than $n-1 (i.e., to account for the situation when it's inside a twin prime pair), at which point we exit. At program completion, the pipeline is printed to screen via implicit Write-Output.

NB - Due to the looping structure, prints the primes in descending order. OP has clarified that's OK.

Examples

Output here is space-separated, as that's the default stringification method for an array.

PS C:\Tools\Scripts\golfing> 70,71,72,73,90,201,499,982|%{"$_ --> "+(.\the-solitude-of-prime-numbers.ps1 $_)}
70 --> 67
71 --> 67
72 --> 97 89 83 79 67
73 --> 97 89 83 79
90 --> 97 89 83 79
201 --> 223 211
499 --> 509 503 499 491 487 479 467
982 --> 1013 1009 997 991 983 977 971 967 953 947 941 937 929 919 911 907 887


Determine ranges from a list of values Given an unsorted list of unique, positive integers, output the shortest list of the longest possible ranges of sequential integers.

INPUT

An unsorted list of unique, positive integers

e.g. 9 13 3 11 8 4 10 15

Input can be taken from any one of the following:

stdin
command-line arguments
function arguments

OUTPUT

An ordered list of ranges or individual values printed on one line to stdout or your language's closest similar output.

If two or more sequential integers (sequential by value, not by location in the list) are present, they will be denoted as an inclusive range using -, e.g. 8-11
All other integers are simply printed with no other notation
A single space will delimit the output

Numbers not present in the input should not be in the output, e.g. 3 5 6 cannot be shortened to 3-6 because 4 is not present

EXAMPLES

Successful:

 IN> 9 13 3 11 8 4 10 15 6
OUT> 3-4 6 8-11 13 15

 IN> 11 10 6 9 13 8 3 4 15
OUT> 3-4 6 8-11 13 15

 IN> 5 8 3 2 6 4 7 1
OUT> 1-8

 IN> 5 3 7 1 9
OUT> 1 3 5 7 9

Wrong:

 IN> 9 13 3 11 8 4 10 15
OUT> 3-15

Range contains values not in the input

 IN> 9 13 3 11 8 4 10 15
OUT> 3 4 8 9 10 11 13 15

All sequential values should be represented as a range

 IN> 9 13 3 11 8 4 10 15
OUT> 3-4 8-9 10-11 13 15

Divided range, 8-9 and 10-11 should be 8-11

 IN> 9 13 3 11 8 4 10 15
OUT> 8-9 13 10-11 3-4 15

Output not ordered correctly

RULES

Standard loopholes are disallowed
If your language has a function to do this it's not allowed
You may write a full program, or a function
trailing whitespace doesn't matter

SCORING

Least bytes wins

Python 2, 123 120 bytes

N=sorted(map(int,raw_input().split(' ')));print(''.join((''if n+1in N else'-'+`n`)if n-1in N else' '+`n`for n in N)[1:])

If the input can be a list as a function argument then (thanks mbomb007 and xnor for the conditionals)

93 90 81 bytes

def f(N):print''.join((' '+`n`,`-n`*-~-(n+1in N))[n-1in N]for n in sorted(N))[1:]

(77 bytes if leading whitespace is acceptable - drop the final [1:])


Write a D*mn Unambiguous Censor Censors are a common tool used on the interwebs. But they often censor too much of the word, and thus make the cursing ambiguous to the reader. And sometimes they don't censor enough, so the words still remain offending. Your task is to fix that.
Your task
Write a program/function/whatever that takes two lists and a string. The first list will be the dictionary of all words in your language like: ["hello", "goodbye", "belgium", "offensive", "jumping", "hypercool"]. The next will be subset of the first list containing all of the offensive words in the language: ["belgium", "offensive"]. The words in these lists are guaranteed to contain only lowercase letters of the alphabet.
The string is the phrase you will have to censor. It will be made of words from the dictionary, separated by spaces: "Goodbye offensive belgium"
The return value will be that phrase censored. However, you have to censor in a certain way. Specifically, for each word in the offensive list, you have to censor as many letters as possible while remaining completely unambiguous in the main dictionary. So here it would be: Goodbye o******** b******.
Clarifications

Your code has to interpret the words case-insensitively, but return with the initial capitalization.
If there are multiple optimal answers, pick any of them.
If unambiguous censoring is impossible, censor a single letter that has the least number of other possible interpretations (If multiple are possible, again, its your choice).

Test Cases
["hello", "goodbye", "belgium", "offensive", "jumping", "hypercool"] ["belgium", "offensive"] "Goodbye offensive belgium" -> "Goodbye o******** b******"
["word"] ["word"] "word" -> "****"
["hot", "hat", "bat", "had"] ["hat"] "hat" -> "*at" or "h*t" or "ha*"
https://gist.github.com/deekayen/4148741 ["quart"] "I am a quart" -> "I am a q**r*"

This is code-golf so shortest d*mn code in bytes wins!
P.S. Anyone caught the reference with belgium? ;P

JavaScript ES7, 194 bytes

(d,c,s,g=(a,b)=>[...b].reduce((z,l,i)=>z+(a[i]==l?1:0),0))=>[for(s of s.split` `)~d.indexOf(s)?[...c[(x=[for(i of c)g(i,s)]).indexOf(Math.max(...x))]].map((l,i)=>l!=s[i]?`*`:l).join``:s].join` `

A very large function. I'm guessing a few bytes can be golfed off but not much unless I completely change the way it works.


Days and months make years Today's date is quite an interesting one. Let's take a look at why. The date 07/12/2017 (in DD/MM/YYYY date format) can be split into the year (2017) and the rest (07/12). You may notice that the digits in the year can be rearranged to match the digits in the rest of the date, which is the basis of this challenge.
The task
Given an valid integer (e.g. no leading zeros) representing a year, consisting of exactly four digits, output all unique possible valid dates that can be made from those digits. You may take the number as a list of digits, or a string representing the input if you want. Each number in the input must be used exactly once in each of the final outputs. As leading 0s aren't used in integers, the input will be in the range 1000 <= input <= 9999.
A valid date is one in which the date exists on the Gregorian Calendar, such as 17/05/2000. The only corner case is February 29th, which is only a valid date when the year is a leap year. You can (but don't have to) assume that leap years are years that are divisible by 4.
You have to output a separator between the day and the month (e.g. /) and a different separator between different dates. You may optionally output the year with each date, but this must be consistent between dates.
Finally, you may choose between the date format order, i.e. you can output as any of DD/MM/YYYY, MM/DD/YYYY etc. but leading 0s are required when the input contains at least one 0.
Essentially, you may output in any obviously understandable format, such as an array of strings, one concatenated string etc.
This is a code-golf so shortest code wins!
Test cases
input
outputs

2017
07/12, 12/07, 17/02, 21/07, 27/01, 27/10

2092
22/09, 29/02

2029
22/09

1000
Nothing

8502
25/08, 28/05

Reference Implementation

Japt, 31 30 26 24 23 22 17 bytes
Locale dependent. Outputs a 2D-array of the format [["MM","DD"],...].
á â mò fÈÎ-ÐNcX)Î

Try it or Try It Online! (to avoid the locale dependency)
Explanation
If it wasn't for JavaScript's Date object wrapping invalid dates, I'd be able to get this down to about 20 18 16 bytes. Even when providing its argument as a single string, which the spec says shouldn't lead to wrapping, dates up to 31 still do for months that don't have 31 days. However, as the month's can only wrap over by one, we can take advantage of the fact that string arguments use 1-based months to simply filter by subtraction - if the month rolls over then the result of that subtraction will be 0.
á â mò fÈÎ-ÐNcX)Î     :Implicit input of N=[U="YYYY"]
á                     :Permutations of U
  â                   :Deduplicate
    m                 :Map
     ò                :  Partitions of length 2 (=[["MM","DD"],...])
       f              :Filter
        È             :By passing each X through the following function
         Î            :  First element of X
          -           :  Subtract
           Ð          :  Create new Date from
            NcX       :    N concatenated with X (=["YYYY","MM","DD"], which gets coerced to "YYYY-MM-DD", with MM being 1-based)
               )      :  End date creation
                Î     :  0-based month (=NaN for invalid dates, n-NaN=NaN)

Original, 22 bytes
Preserving this, 'cause I really liked the setwise union trick.
á
â¡ÐNcXòÃfÈÎ-2îUvÃms7

Try it (footer formats the output to match the examples in the challenge)Or Try it online! to somewhat mitigate the locale dependency - TIO's locale doesn't include leading 0s for dates & months, so they're added back in in the footer.
Explanation
á\nâ¡ÐNcXòÃfÈÎ-2îUvÃms7     :Implicit input of N=[U="YYYY"]
á                           :Permutations of U
 \n                         :Reassign to U, leaving the value in N unchanged
   â                        :Setwise union with
    ¡                       :Map each X in U
     Ð                      :  New Date from
      Nc                    :  N concatenated with
        Xò                  :  Partitions of X of length 2 (=["YYYY","MM","DD"], which gets coerced to "YYYY-MM-DD", with MM being 1-based)
          Ã                 :End map
           f                :Filter by
            È               :Passing each through the following function
             Î              :  Get 0-based month (=NaN for invalid date)
              -             :  Subtract (NaN-n=NaN)
               2î           :  First 2 characters of
                 Uv         :  Remove and return first element of U
                   Ã        :End filter
                    m       :Map
                     s7     :  To locale date string (="DD/MM/YYYY")

The reason the setwise union doesn't include any elements from the first array is because v modifies that array so the filter ends up removing all elements from it.
In the 16 byte version, which assumes a way to avoid dates wrapping over, we don't need to reassign the array of possible dates to U and instead filter by using Í to try to subtract the timestamp from 2, which will result in NaN if the date is invalid. We can't use the setwise union trick, though, so â get tacked on the end to deduplicate the final array.


Convert λ-expressions to SK-expressions The λ-calculus, or lambda calculus, is a logical system based on anonymous functions. For example, this a λ-expression:

λf.(λx.xx)(λx.f(xx))

However, for the purposes of this challenge, we'll simplify the notation:

Change λ to \ (to make it easier to type): \f.(\x.xx)(\x.f(xx))
The . in lambda headers is unnecessary, so we can drop it: \f(\xxx)(\xf(xx))
Use the Unlambda-style prefix notation with ` for application rather than writing the two functions together (for a full explanation of how to do this, see Convert between Lambda Calculus Notations): \f`\x`xx\x`f`xx
This is the most complicated substitution. Replace each variable with a number in brackets based on how deeply nested the variable is relative to the lambda header it belongs to (i.e. use 0-based De Bruijn indexing). For example, in \xx (the identity function), the x in the body would be replaced with [0], because it belongs to the first (0-based) header encountered when traversing the expression from the variable to the end; \x\y``\x`xxxy would be converted into \x\y``\x`[0][0][1][0]. We can now drop the variables in the headers, leaving \\``\`[0][0][1][0].

Combinatory logic is basically a Turing Tarpit made out of the λ-calculus (Well, actually, it came first, but that's irrelevant here.)

"Combinatory logic can be viewed as a variant of the lambda calculus, in which lambda expressions (representing functional abstraction) are replaced by a limited set of combinators, primitive functions from which bound variables are absent."1

The most common type of combinatory logic is the SK combinator calculus, which uses the following primitives:

K = λx.λy.x
S = λx.λy.λz.xz(yz)

Sometimes a combinator I = λx.x is added, but it is redundant, as SKK (or indeed SKx for any x) is equivalent to I.

All you need is K, S, and application to be able to encode any expression in the λ-calculus. As an example, here's a translation from the function λf.(λx.xx)(λx.f(xx)) to combinatory logic:

λf.(λx.xx)(λx.f(xx)) = S(K(λx.xx))(λf.λx.f(xx))
λx.f(xx) = S(Kf)(S(SKK)(SKK))
λf.λx.f(xx) = λf.S(Kf)(S(SKK)(SKK))
λf.S(Sf)(S(SKK)(SKK)) = S(λf.S(Sf))(K(S(SKK)(SKK)))
λf.S(Sf) = S(KS)S
λf.λx.f(xx) = S(S(KS)S)(K(S(SKK)(SKK)))
λx.xx = S(SKK)(SKK)
λf.(λx.xx)(λx.f(xx)) = S(K(S(SKK)(SKK)))(S(S(KS)S)(K(S(SKK)(SKK))))

Since we are using the prefix notation, this is ```S`K``S``SKK``SKK``S``S`KSS`K``SKK`.

1 Source: Wikipedia

The Challenge

By now, you've probably guessed what is: Write a program that takes a valid λ-expression (in the notation described above) as input and outputs (or returns) the same function, rewritten in SK-combinator calculus. Note that there are an infinite number of ways to rewrite this; you only need to output one of the infinite ways.

This is code-golf, so the shortest valid submission (measured in bytes) wins.

Test Cases

Each test case shows one possible output. The expression on top is the equivalent λ-calculus expression.

λx.x:
\[0]                        -> ``SKK
λx.xx:
\`[0][0]                    -> ```SKK``SKK
λx.λy.y:
\\[0]                       -> `SK
λx.λy.x:
\\[1]                       -> K
λx.λy.λz.xz(yz):
\\\``[2][0]`[1][0]          -> S
λw.w(λx.λy.λz.xz(yz))(λx.λy.x):
\``[0]\\[1]\\\``[2][0]`[1][0] -> ``S``SI`KS`KK

Haskell, 251 237 222 214 bytes

15 bytes saved thanks to @Ørjan_Johansen (also see his TIO links in the remarks)!

8 more bytes saved thanks to @nimi!

data E=S|K|E:>E|V Int
p(h:s)|h>'_',(u,a)<-p s,(v,b)<-p u=(v,a:>b)|h>'['=a<$>p s|[(n,_:t)]<-reads s=(t,V n)
a(e:>f)=S:>a e:>a f
a(V 0)=S:>K:>K
a(V n)=K:>V(n-1)
a x=K:>x
o(e:>f)='`':o e++o f
o S="S"
o K="K"
f=o.snd.p

p parses the input, returning the remaining unparsed part in the first component of the resulting pair. The first character of its argument must be a backtick, a backslash or an opening bracket. The pattern guards of p check these cases in this order. In the first case, denoting an application, two more expressions are parsed and combined to an element of the E data type with the infix constructor :>. In the lambda case, the following expression is parsed and immediately given to the a function. Otherwise it is a variable, we get its number with the reads function (which returns a list) and drop the closing bracket by pattern matching with (_:t).

The a function does the quite well known bracket abstraction. To abstract an application, we abstract the two subexpressions and use the S combinator to distribute the argument to both. This is always correct, but with more code we could do much better by handling special cases in order to get shorter expressions. Abstracting the current variable gives I or, when we don't have that, SKK. Usually the remaining cases can just add a K to the front, but when using this notation we have to renumber the variables as the inner lambda is abstracted.

o turns the result to a string for output. f is the complete function.

As in many languages, backslash is an escape character, so it has to be given twice in a string literal:

*Main> f "\\[0]"
"``SKK"
*Main> f "\\`[0][0]"
"``S``SKK``SKK"
*Main> f "\\\\[0]"
"``S``S`KS`KK`KK"
*Main> f "\\\\[1]"
"``S`KK``SKK"
*Main> f "\\\\\\``[2][0]`[1][0]"
"``S``S`KS``S``S`KS``S`KK`KS``S``S`KS``S``S`KS``S`KK`KS``S``S`KS``S`KK`KK``S`KK``SKK``S``S`KS``S``S`KS``S`KK`KS``S`KK`KK``S`KK`KK``S``S`KS``S``S`KS``S`KK`KS``S``S`KS``S`KK`KK``S``S`KS`KK`KK``S``S`KS``S``S`KS``S`KK`KS``S`KK`KK``S`KK`KK"


Sort the months of the year Write a function or program that takes string inputs, fully-spelled, English month names in title case: January, February, March, etc. (null/CR/LF terminated OK, delimited with some non-alpha character if you so choose) and either

compares two inputs, returning a Truthy value if the second input is greater (in month order) than the first. Equal values result in a Falsey value
or sorts an arbitrary sequence (list, delimited string, etc.) of them in chronological order

(The crux of the challenge is defining a method/expression that gives the correct lexicographical sort. Some languages might have a shorter answer with one or the other)

You cannot use any internal time parsing methods (e.g. strptime) to translate the month name into a number or a pre-canned mapping of month names. Use properties of the strings themselves, a parsimonious look-up table you define, or something clever.

Example

Functioning examples, though the first is prohibited by the rules...

import datetime
def is_later_month(a, b):
    '''
    Example of prohibited code because it relies on language
    features about how to parse month names
    '''
    return datetime.strptime(a, '%B') < datetime.strptime(b, '%B')

The below versions are OK though, because we code that info

months = {
    'January':  1, 'February':  2, 'March':      3,
    'April':    4, 'May':       5, 'June':       6,
    'July':     7, 'August':    8, 'September':  9,
    'October': 10, 'November': 11, 'December':  12,
}
def is_later_month(a, b):
    """
    Returns True/False when comparing two months.
    """
    return months[a] < months[b]

Or you could do a sorting function

months = {'as above...'}
def sort_months(l):
    """
    Sorts list and returns it. Different input and output than the above,
    but equally valid. Sorting versus comparing might be shorter in your
    favorite language.
    """
    return sorted(l, key=lambda x: months[x])

Example tests

assert is_later_month('January', 'February')
assert is_later_month('January', 'December')
assert is_later_month('November', 'December')
assert not is_later_month('July', 'July')
assert not is_later_month('October', 'September')

Jelly, 19 bytes

11ị“bMAanlseovc”iµÞ

This is a monadic link that takes a list as argument and sorts it. Try it online!

Background

Jelly uses modular, 1-based indexing. If we repeat the months names often enough to obtain 11 characters, we get the following array.

J a n u a r y J a n u
F e b r u a r y F e b
M a r c h M a r c h M
A p r i l A p r i l A
M a y M a y M a y M a
J u n e J u n e J u n
J u l y J u l y J u l
A u g u s t A u g u s
S e p t e m b e r S e
O c t o b e r O c t o
N o v e m b e r N o v
D e c e m b e r D e c

In the 11th (last) column, all characters are different, so we can use them to identify the order of the months.

How it works

11ị“bMAanlseovc”iµÞ  Monadic link. Argument: A (array of months)

                 µ   Combine the preceding chain into a link.
                  Þ  Sort A by that link.
11ị                    Select the 11th character of the month's name.
   “bMAanlseovc”       Find the index of that character in "bMAanlseovc".
                       For 'u' ("January"), this returns 0 (not found).


Alexa and the Tea Plantation Hey guys, first time poster here. I went on Coderoulette recently and some guy posted this question. I looked around online but it doesn't seem to be anywhere. I figured I would post it here for anyone who is a fan of these types of problems. Enjoy!

Alexa is a druid who loves Mathematics! She lives in the land of Alfa, taking care of a tea plantation.
The plantation has N plants and the height of the ith plant is Hi.

Alexa has developed a recent interest in palindromes. She wants to crop the plants so the height of the plants forms a palindrome (without any reordering). She has 2 spells in her arsenal- the 'Growlith' spell will increase the height of a plant by 1 unit, the 'Shrinkooza' spell will decrease the height of a plant by 1 unit. The 'Growlith' and 'Shrinkooza' spells cost A and B units of magic respectively. Help Alexa find the minimum units of magic, that shall enable her to fulfill her objective.

Input Format

First line contains an integer T. T testcases follow.
First line of each test case consists of 3 space-separated integers N, A and B.
Next line consists of N space-separated integers, the initial height of the plants.

Output Format

Print the answer to each test case on a new line.

Constraints

1 <= T <= 10
1 <= N <= 105
0 <= A, B <= 108
1 <= Hi <= 103

Example

Input

1
5 2 2
1 6 2 3 4

Output

12

Explanation

She can use the 'Growlith' spell on the first plant 3 times and the 'Shrinkooza' spell on the second plant 3 times to form 4 3 2 3 4.

Challenge

Write code that will create a palindrome using the least units of magic possible for N plants.

Scoring

This is code golf. The shortest code in bytes wins.

05AB1E, 20 bytes

WU|vy#Â‚ø€¥˜Ä2ä`OX*,

Explanation

WU                    # store minimum cost in X
  |v                  # for each testcase
    y#                # convert to list split on spaces
      Â‚ø             # zip with its own reverse
         €¥           # deltas of each pair
           ˜Ä         # deep flatten and take absolute value
             2ä       # split into 2 pieces
               `      # flatten (leaves the smaller piece on top of the stack)
                O     # sum
                 X*   # multiply with minimum cost
                   ,  # print

Try it online!


Random sampling without replacement Create a function that will output a set of distinct random numbers drawn from a range. The order of the elements in the set is unimportant (they can even be sorted), but it must be possible for the contents of the set to be different each time the function is called.

The function will receive 3 parameters in whatever order you want:

Count of numbers in output set
Lower limit (inclusive)
Upper limit (inclusive)

Assume all numbers are integers in the range 0 (inclusive) to 231 (exclusive). The output can be passed back any way you want (write to console, as an array, etc.)

Judging

Criteria includes the 3 R's

Run-time - tested on a quad-core Windows 7 machine with whatever compiler is freely or easily available (provide a link if necessary)
Robustness - does the function handle corner cases or will it fall into an infinite loop or produce invalid results - an exception or error on invalid input is valid
Randomness - it should produce random results that are not easily predictable with a random distribution. Using the built in random number generator is fine. But there should be no obvious biases or obvious predictable patterns. Needs to be better than that random number generator used by the Accounting Department in Dilbert

If it is robust and random then it comes down to run-time. Failing to be robust or random greatly hurts its standings.

Python

import random

def sample(n, lower, upper):
    result = []
    pool = {}
    for _ in xrange(n):
        i = random.randint(lower, upper)
        x = pool.get(i, i)
        pool[i] = pool.get(lower, lower)
        lower += 1
        result.append(x)
    return result

I probably just re-invented some well-known algorithm, but the idea is to (conceptually) perform a partial Fisher-Yates shuffle of the range lower..upper to get the length n prefix of a uniformly shuffled range.

Of course, storing the whole range would be rather expensive, so I only store the locations where the elements have been swapped.

This way, the algorithm should perform well both in the case where you're sampling numbers from a tight range (e.g. 1000 numbers in the range 1..1000), as well as the case where you're sampling numbers from a large range.

I'm not sure about the quality of randomness from the built-in generator in Python, but it's relatively simple to swap in any generator that can generate integers uniformly from some range.


FIFO cache anomalies This is the followup challenge from this one, if you're confused please check that one out first.

First, let \$m(s, k)\$ be the number of cache misses a sequence \$s\$ of resource accesses would have assuming our cache has capacity \$k\$ and uses a first-in-first-out (FIFO) ejection scheme when it is full.
Then given a ratio \$r > 1\$, return a non-empty sequence of resources accesses \$s\$ such that there exists \$k > j\$ with \$m(s, k) \geq r \cdot m(s, j)\$.
In plain English, construct a sequence \$s\$ of resource accesses so that there's two cache sizes where the bigger cache has (at least) \$r\$ times more cache misses when used to resolve \$s\$.
An example for \$r = 1.1\$, a valid output is the sequence \$(3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4)\$, as it causes \$9\$ cache misses for a cache size of \$3\$, but \$10\$ misses for a cache size of \$4\$.
It doesn't matter what sequence you return, as long as it meets the requirements.

Shortest code in bytes wins.

Wolfram Language (Mathematica), 124 113 101 bytes
Flatten@{s=⌈2#⌉;q=Range[r=2s+1];g=Mod[q s-s,r];{Sort@g[[#+1;;]],g[[;;#]]}&~Array~r,Table[q,s^3]}&

Try it online!
NOTE: The TIO output is not the actual list because it would be very long. The wrapper function on TIO tells you the number of page faults for two cache capacities.
For the actual list: Try it online!
Related: arXiv:1003.1336
How?
Let's assume a situation where we have two cache capacities, 3 and 4.
Also, let's say the 3-cache has {4, 2, 5} paged, and 4-cache has {5, 4, 3, 2} paged. Then, let's try paging {1, 2, 3, 4, 5, 1, 2, 3, 4, 5}:
page  3-cache   4-cache
      {4,2,5}  {5,4,3,2}
  1   {1,4,2}  {1,5,4,3}
  2   {1,4,2}  {2,1,5,4}
  3   {3,1,4}  {3,2,1,5}
  4   {3,1,4}  {4,3,2,1}
  5   {5,3,1}  {5,4,3,2}
  1   {5,3,1}  {1,5,4,3}
  2   {2,5,3}  {2,1,5,4}
  3   {2,5,3}  {3,2,1,5}
  4   {4,2,5}  {4,3,2,1}
  5   {4,2,5}  {5,4,3,2}

The 3-cache had 5 page faults, while the 4-cache had 10. We also returned to our original state.
Here, if we repeat paging {1, 2, 3, 4, 5}, we would asymptotically reach the ratio of 2.
We can extend this phenomenon to higher cache capacities so that we can page {1, 2, 3, ... , 2n + 1} and end up with any ratio.


Print the alphabet without using each vowel Inspiration: in 1939, a man named Ernest Vincent Wright wrote a novel called Gadsby without using the letter 'e'.
Your task is to write a set of (up to 5) programs in any language (which has a text-based syntax*) to output all 26 letters of the alphabet in order.  However for each vowel aeiou, at least one of the programs must not include any occurrence of the vowel.
So there must be

a program that does not use 'a' or 'A' anywhere in the syntax of the program.
a program that does not use 'e' or 'E' anywhere in the syntax of the program.
a program that does not use 'i'  or 'I' anywhere in the syntax of the program.
a program that does not use 'o' or 'O' anywhere in the syntax of the program.
a program that does not use 'u' or 'U' anywhere in the syntax of the program.

All of them must output abcdefghijklmnopqrstuvwxyz.
The winner shall be the solution where the length of all programs is the shortest.
* since the constraint wouldn't be much of a challenge in Piet or Whitespace


Half-Exponential Function A half-exponential function is one which when composed with itself gives an exponential function. For instance, if f(f(x)) = 2^x, then f would be a half-exponential function. In this challenge, you will compute a specific half-exponential function.

Specifically, you will compute the function from the non-negative integers to the non-negative integers with the following properties:

Monotonically increasing: if x < y, then f(x) < f(y)
At least half-exponential: For all x, f(f(x)) >= 2^x
Lexicographically smallest: Among all functions with the above properties, output the one which minimizes f(0), which given that choice minimizes f(1), then f(2), and so on.

The initial values of this function, for inputs 0, 1, 2, ... are:

[1, 2, 3, 4, 8, 9, 10, 11, 16, 32, 64, 128, 129, 130, 131, 132, 256, 257, ...]

You may output this function via any of the following methods, either as a function or as a full program:

Take x as input, output f(x).
Take x as input, output the first x values of f.
Infinitely output all of f.

If you want to take x and output f(x), x must be zero indexed.

Reference implementation

This is code golf - shortest code in bytes wins. Standard loopholes are banned, as always.

JavaScript (ES7), 51 48 bytes

Saved 3 bytes thanks to @Arnauld

f=i=>i?f[f[q=f(i-1),r=f[i]||q+1]=(i>1)<<i,i]=r:1

Takes in n and outputs the n'th item in the sequence.

JavaScript (ES7), 70 68 64 bytes

f=(n,a=[],q=1)=>n?f(n-1,a,(n=2**a.indexOf(a.push(q)))<++q?q:n):a

A recursive function that takes in x and returns the first x items of the sequence as an array.

How it works

The array a is procedurally generated, one item at a time, until it reaches the desired length. (A port of the infinite technique used in xnor's excellent Python answer would likely be shorter.)

We can make the following observation for each index i (0-indexed):

If i exists as an item in a at index j (a[j] = i), then a[i] needs to be at least 2j.

This is true because f(f(j)) needs to be at least 2j, and f(f(j)) is equivalent to a[a[j]], which is in turn equivalent to a[i].

Normally the correct option is exactly 2j. However, for the singular case i = 2, 2 exists in the array at index j = 1, which means that 2j would be 2—but this means that we would have 2 at both a[1] and a[2]. To get around this, we take the maximum of 2j and a[i-1] + 1 (one more than the previous item), which gives 3 for i = 2.

This technique also happens to take care of deciding whether or not j exists—if it doesn't, JS's .indexOf() method returns -1, which leads to taking the max of a[i-1] + 1 and 2-1 = 0.5. Since
all items in the sequence are at least 1, this will always return the previous item plus one.

(I'm writing this explanation late at night, so please let me know if something is confusing or I missed anything)


8-bit style bouncing ball around a canvas Inspired by this listing from the Commodore 64 User's Guide:

10 PRINT "{CLR/HOME}"
20 POKE 53280,7 : POKE 53281,13
30 X = 1 : Y = 1
40 DX = 1 : DY = 1
50 POKE 1024 + X + 40 * Y, 81
60 FOR T = 1 TO 10 : NEXT
70 POKE 1024 + X + 40 * Y, 32
80 X = X + DX
90 IF X <= 0 OR X >= 39 THEN DX = -DX
100 Y = Y + DY
110 IF Y <= 0 OR Y >= 24 THEN DY = -DY
120 GOTO 50

Make a similar program in your chosen language/platform to bounce a ball-alike object around your terminal, screen, canvas or other visual display area.

You don't have to mimic the C64's PETSCII graphics exactly, a simple O or o will do, nor do you have to use the GOTO command if it exists in your language still. As long as your ball starts at the top of your canvas and travels diagonally until it hits a canvas limit, and then bounces accordingly, as follows:

Travelling downwards and right and hits the bottom of the screen area, bounces up and continues right;
Travelling up and right and hits the right-most boundary, and bounces left and up;
Travelling left and up and hits the top, bounces left and down;
Travelling left and down and reaches the left-most boundary, bounces right and down;
Hits any corner and reverses direction;

Then we're all good.

You don't have to move the ball 8-pixels at a time either, like is happening in the BASIC listing on the C64; you can move one character block or one pixel at a time, whichever you think is most appropriate.

To see this BASIC listing working, you can type it in with this online Commodore 64 emulator providing your browser supports Flash.

Bash + Unix utilities, 125 117 bytes

for((x=y=u=v=1;;x+=u,y+=v,u=(x<1||x>=`tput cols`-1)?-u:u,v=(y<1||y>=`tput lines`-1)?-v:v)){
tput cup $y $x
sleep .1
}

Animation of sample run:


It's the end, but the code-golf has been prepared for Welcome to BBC Casting. We need a program that we can use to select a new actor to play The Doctor on Doctor Who. In the spirit of the show, your program will perform a regeneration from one actor's name to the next.

We will test your program by running through the 13 names of actors who have already played The Doctor and then run it another 13 times. We will pass the output from one call as the input to the next in a loop.

Detailed Requirements

Your program will take a string as its only input and output a single string. It must not store any state between calls or use any additional resources outside of the program.
If the input is your starting string, your program must return "William Hartnell", the first name on the list.

You should select and document any string you wish to use as the starting string, as long as it isn't the name of a listed actor. My example below uses an empty string.

If the input string is an actor's name (other than the last), your program must return the next name on the list following the name inputted.
For any other inputs, behavior of your program is undefined.
The list of actors below is incomplete. You must complete the list by selecting 13 more names of actors you feel would be good at playing The Doctor.

Each extra name must be of a professional actor with an IMDB page.
The extra names returned by your program must be the actors' names exactly as listed on IMDB, including case, accents and diacritics.
The completed list of 26 actors must be 26 distinct individuals with distinct names.

You may interpret input and output according to the constraints of your language's execution environment. (Parameters, quotes, end-of-lines, stdin/out, encoding etc.)
Shortest conforming program wins. Normal code-golf rules apply.
You may use someone else's list of actors. If you do, give appropriate credit and share the glory. (Finding a list of actors that would compress well might be part of the challenge.)

The first half of the list of names is as follows. These strings must be output exactly as shown, preserving case including the extra capital letter in "McCoy" and "McGann".

William Hartnell
Patrick Troughton
Jon Pertwee
Tom Baker
Peter Davison
Colin Baker
Sylvester McCoy
Paul McGann
John Hurt
Christopher Eccleston
David Tennant
Matt Smith
Peter Capaldi

For example:

YourProgram("") returns "William Hartnell".
YourProgram("William Hartnell") returns "Patrick Troughton".
YourProgram("Patrick Troughton") returns "Jon Pertwee".
/* 10 more. */
YourProgram("Peter Capaldi") returns "Pauley Perrette".
YourProgram("Pauley Perrette") returns "Nathan Fillion".
/* 12 more. */

Python 2, 340 bytes

#coding:L1
import zlib;r=zlib.decompress("x5mÂ@¯Â 8]c]u×Xã-q1H5½ýRãþ#÷O³PÌsÆ=¹IºÁÑêx¼*~W=¿ñX,èÆ{v6ø¢§<â¦©Yô³é¦üäÇ¼Ý¥¦NAs+Ò5(´£96ÉÃë}»eJ9>3óz8²*©ãÜ¡+âÃG®¡;å^pY\nÁ|þ7Ü9¿\"®ICmYXqÁÊ½$f,g¶3yÞ!ZéûfÇñÑTU¶ Û\r[M8Ì¨põ)ËåÂxïÑ¬LÂÜlßÜ\nwI×+nX`£åep;·ûÃVÿ À]b").split('.');print r[r.index(input())+1]

The encoding is Latin-1 (aka ISO-8859-1). That first line is important because Python 2 doesn't like non-ASCII characters in files by default (and using Python 3 wouldn't help, because it expects UTF-8 by default, along with loads of other issues).

Takes quoted input (single and double both work), with the initial input as the empty string ('').

The strategy I used was constructing a list of period-separated names (starting with an empty string) and compressing it with zlib (which gave better results over both shoco and lzma). This program decompresses that list, splits it on periods, and outputs the element in the list that follows the input.

I didn't use any real strategy with choosing the next 13 actors, other than picking living British actors (sorry, Alan Rickman, you would've been great) that I liked who haven't played a Doctor yet. The rationale was, the character distribution in the first 13 names is fairly random (as far as names go), so it's unlikely (in my opinion) that 13 more names could be picked that would make a significant difference in compressed size.

For reference, the list I used (with an extra linebreak to separate the new actors):

William Hartnell
Patrick Troughton
Jon Pertwee
Tom Baker
Peter Davison
Colin Baker
Sylvester McCoy
Paul McGann
John Hurt
Christopher Eccleston
David Tennant
Matt Smith
Peter Capaldi

Emma Watson
Patrick Stewart
Ian McKellen
Benedict Cumberbatch
Tom Hiddleston
Sean Connery
Hugh Laurie
Daniel Radcliffe
Rupert Grint
Gary Oldman
Simon Pegg
Keira Knightley
Liam Neeson


Tips for Fastest Code challenges What general tips do you have for how to answer fastest-code challenges?

Please post one tip per answer.

The objective of these challenges is to make the program that will run in the least amount of wall-clock time given a specific set of computer specifications (based on who will be judging the timings).

Please keep tips specific to fastest-code and not fastest-algorithm; you can assume that the coder has already found the most efficient algorithm to use.

Language

For example, Python is an interpreted language, not a compiled language, so it would surely be faster if you wrote it in C to begin with.

Rust, C++, C, javascript, and Haskell seem to be popular choices. One would have to evaluate them.


Convert a string representation of a number to int[] in C# What is the shortest C# statement that will convert a string representation of a number to an int[] that contains each digit?

string number = "1234";
number.Array.ConvertAll(line.ToCharArray(), c => Int32.Parse(c.ToString()));
number.ToCharArray().Select(i => Convert.ToInt32(i.ToString())).ToArray();
number.Select(i => Int32.Parse(i.ToString())).ToArray();
number.Select(i => i - '0').ToArray();

Can anyone beat my last approach?

28 bytes

You can make your last approach a bit shorter by replacing the '0' by 48. You can also strip all unnecessary spaces and use 1-char variable names (for example, number -> n):

n.Select(i=>i-48).ToArray();


Make your code error, but only sometimes! Your task is to create a program or function which randomly errors. Specifically, there must be a nonzero probability of erroring, but also a nonzero probability of running without error.

An error is anything that causes a program to terminate abnormally, such as dividing by zero or using an uninitialized variable. This also includes runtime errors, syntax errors and errors while compiling. Statements which manually throw an error, such as JavaScript's throw are allowed.

This program doesn't need to do anything if it doesn't error, other than exiting gracefully.

This is code-golf, so shortest answer per language wins.

Note: For this challenge, "randomly" follows the current consensus (so no using undefined behavior or uninitialized memory for randomness), and the program must be capable of producing both outputs if run or compiled multiple times (so a random number with the same seed is not valid)

Baby Language, 0 bytes

Try it online!
I knew this could be fun with a non-deterministic tarpit! I looked through the category on the Esolang wiki and found this language...
From the page:

A Baby Language interpreter ignores the input program and does something random. (Likewise, a Baby Language compiler generates a random executable.) As such, whatever you wanted your program to do, there's an (admittedly small) chance that it will actually do it.
The intended use case for the language is to run your program repeatedly until it does what you want. Just like trying to reason with a real baby, this may take quite a while.

So the blank program, and every program for that matter, executes a random program which will therefore randomly error!

Details on TIO link
I used Esolang user Enoua5's source code which generates and executes a random brainfuck program. It's linked on the Esolang page:

An interpreter created in Python 3 by User:Enoua5: View Source

So the TIO link above takes you to Python 3 interpreter is implemented in the header and the actual (blank) code is in the (blank) code slot, which is ignored anyway!
The above interpreter is simply copied and pasted into the header; a multiline comment starting/ending in the header/footer nullifies the actual code.


When is a giraffe not a giraffe? I hope this kind of "riddle" is ontopic in Programming Puzzles & Code Golf.

Give an example of a situation where the C# method below returns false:

public class Giraffe : Animal
{
  public bool Test()
  {
    return this is Giraffe;
  }
}

Rules: The code lines above must not be changed in any way, but you would put the code into an application so that the "project" compiles and the method is called. When run, the method must return false. The solution I have in mind, does not emit its own IL at run-time or similar "exotic" things, it's an ordinary instance method call.

Yay, found it!

public class Animal
{
    public class Giraffe { } // 1
}
public class Giraffe : Animal // 2
{
    public bool Test()
    {
        return this is Giraffe;
    }
}

Since Giraffe 1 is a member of Animal, and Giraffe 2 is one level further out, the name Giraffe in the is test refers to the former (section 7.6.2 in the C# 5 spec).

Visual Studio shows a warning for this is Giraffe:

  The given expression is never of the provided type

which is obviously true, since it's the whole point :)

You cannot put Giraffe 1 directly inside Giraffe 2, because

  member names cannot be the same as their enclosing type

– but such a rule does not exist for derived classes.

Neat problem, took me a while.


Avast, ye scallywags! Blackbeard was an English pirate of the early 18th century. Although he was known for looting and taking ships, he commanded his vessels with the permission of their crews. There are no accounts of him ever harming or murdering his captives.

This challenge is in honor of the infamous Blackbeard and inspired by International Talk Like a Pirate Day (September 19). It is also the inverse of this challenge by Pyrrha.

The Challenge

Create a program that takes a treasure map as an input (composed of the characters listed below), and outputs it's directions.

Input

All inputs will consist of v, >, <, ^, whitespace, and a single X.

You can assume the following:

the map will never loop or cross itself
the starting arrow will always be the bottommost character in the leftmost column
there will always be a treasure (X)

A sample input is shown below.

  >>v   >>>>>>v
  ^ v   ^     v
  ^ v   ^   v<<
  ^ v   ^   v
  ^ >>>>^   >>X
  ^
>>^

Output

The output should be a ", "-delimited string of directions. Below is the correct output from the above map.

E2, N6, E2, S4, E4, N4, E6, S2, W2, S2, E2

A single trailing newline or space is permitted.

Examples

In:
>>>>>>>>>>>>>>>v
               v
               v
               >>>>X

Out:
E15, S3, E4

In:
>>>>>>v
^     v
^     >>>>X

Out:
N2, E6, S2, E4

In:
X
^
^
^

Out:
N3

In:
>>>>>>v
^     v
^     v
      v
      >>>>>>X

Out:
N2, E6, S4, E6

In:
 X
 ^
 ^
>^

Out:
E1, N3

In:
>X

Out:
E1

In:
v<<<<<
vX<<<^
>>>>^^
>>>>>^

Out:
E5, N3, W5, S2, E4, N1, W3

Happy International Talk Like a Pirate Day!

CJam, 86 bytes

qN/_,{1$=cS-},W=0{_3$3$==_'X-}{"^v<>"#_"NSWE"=L\+:L;"\(\ \)\ ( )"S/=~}w];Le`{(+}%", "*

Try it online

Explanation:

qN/     Get input and split into rows.
_,      Calculate number of rows.
{       Loop over row indices.
  1$=     Get row at the index.
  c       Get first character.
  S-      Compare with space.
},      End of filter. The result is a list of row indices that do not start with space.
W=      Get last one. This is the row index of the start character.
0       Column number of start position. Ready to start tracing now.
{       Start of condition in main tracing loop.
  _3$3$   Copy map and current position.
  ==      Extract character at current position.
  _'X-    Check if it's the end character `X.
}       End of loop condition.
{       Start of loop body. Move to next character.
  "^v<>"  List of directions.
  #       Find character at current position in list of directions.
  _       Copy direction index.
  "NSWE"  Matching direction letters.
  =       Look up direction letter.
  L\+:L;  Append it to directions stored in variable L.
  "\(\ \)\ ( )"
          Space separated list of commands needed to move to next position for each of
          the 4 possible directions.
  S/      Split it at spaces.
  =       Extract the commands for the current direction.
  ~       Evaluate it.
}w      End of while loop for tracking.
];      Discard stack content. The path was stored in variable L.
Le`     Get list of directions in variable L, and RLE it.
{       Loop over the RLE entries.
  (+      Swap from [length character] to [character length].
}%      End of loop over RLE entries.
", "*   Join them with commas.


Make any number by repeatedly adding 2 numbers You are given a machine with two 16-bit registers, x and y. The registers are initialized x=1 and y=0. The only operation the machine can do is addition modulo 65536. That is:

x+=y - x is replaced by (x + y) mod 65536; y is unchanged
y+=x - similarly for y
x+=x - x is replaced by 2x mod 65536; legal only if x is even
y+=y - similarly for y

The goal is to get a predetermined number in one of the registers (either x or y).

Write a program or a subroutine that receives a number (in stdin, argv, function parameter, top of stack or any other conventional place), and outputs a program to get this number. The output should go to stdout, or (if your language has no stdout) to any other conventional output device.

The output program can be up to 100% plus 2 steps far from optimal. That is, if the shortest program to get the target number has n steps, your solution cannot be longer than 2n+2. This restriction is to avoid "too easy" solutions (e.g. counting 1, 2, 3, ...) but not require full optimization; I expect that the shortest program is easiest to find, but cannot be sure...

For example: Input = 25. Output:

y+=x
x+=y
x+=y
x+=x
x+=x
x+=x
y+=x

Another example: For any fibonacci number, the output has this alternating pattern. For Input = 21, output is

y+=x
x+=y
y+=x
x+=y
y+=x
x+=y
y+=x

Shortest code (measured in bytes) wins.

(this puzzle was inspired by some code for a 16-bit processor I had to generate recently)

P.S. I wonder - for which number the optimal program is longest?

Perl 107 97

First post, so here goes.

sub h{($i)=@_;return if(($i%=65536)==0);($i%4==0)?do{h($i/2);say"y+=y";}:do{h($i-1);say"y+=x";}}

Which fits all of the register addition criteria, but I didn't run an exhaustive check to see if my answer was always within 2n+2 of the optimal number of steps.  It is well inside the limit for every Fibonacci number, though.

Here is a more detailed breakdown

sub h{                           # Declare the subroutine, it should be called referencing an integer value
   ($i)=@_;                      # Assign the i variable to the integer used in the call
   return if(($i%=65536)==0);    # Check for base condition of called by 0, and enforce modulo from the start.
   ($i%4==0) ?                   # If the value passed is even, and will result in an even number if we halve it
   do{h($i/2);say"y+=y";}        # Then do so and recurse
   :do{h($i-1);say"y+=x";}       # Otherwise "subtract one" and recurse
}                                # Note that the print statements get called in reverse order as we exit.

As I mentioned, this is my first attempt at golfing, so I'm sure this can be improved upon.  Also, I'm not sure if the initial subroutine call has to be counted in a recursive call or not, which could drive us up a few chars.

Interestingly we can reduce the code by 11 bytes* and improve our "efficiency" in terms of the number of register operations, by relaxing the requirement that only even values can be "doubled".  I've included that for fun here:

sub h{($i)=@_;return if(($i%=65536)==0);($i%2==0)?do{h($i/2);say"y+=y";}:do{h($i-1);say"y+=x";}}

Begin addendum:

Really liked this problem, and I've been fiddling with it off and on for the last couple weeks.  Thought I would post my results.

Some numbers:

Using a BFS algorithm to find an optimal solution, in the first 2^16 numbers there are only 18 numbers that require 23 steps.  They are: 58558, 59894, 60110, 61182, 61278, 62295, 62430, 62910, 63422, 63462, 63979, 64230, 64314, 4486, 64510, 64698, 64854, 65295.

Using the recursive algorithm described above, The "most difficult" number to reach is 65535, at 45 operations.  ( 65534 takes 44, and there are 14 numbers that take 43 steps)  65535 is also the largest departure from optimal, 45 vs 22.  The 23 step difference is 2n+1.  (Only three numbers hit 2n: 65534, 32767, 32751.)  Excepting the trivial (zero-step) cases, over the defined range, the recursive method averages approximately 1.4 times the optimal solution.

Bottom line: For the numbers 1-2^16, the recursive algorithm never crosses the defined threshold of 2n+2, so the answer is valid.  I suspect that it would begin to depart too far from the optimal solution for larger registers/more bits, however.

The code I used to create the BFS was sloppy, memory intensive, not commented, and quite deliberately not included.  So... you don't have to trust my results, but I'm pretty confident in them.


CJam, 626 397 325 218 168 134 93 55 54 53 bytes

8A#{[_8b3394241224Ab?A0e[A,]ze~__,f#:+s_$@s=*~}%$1>N*

Execution takes roughly four and a half hours on my machine. One Armstrong number is hardcoded, the remaining ones are computed.

Computing all Armstrong numbers is theoretically possible in 24 hours, but the approach

9A#{_9b8 9erA0e[A,]ze~__,f#:+s_$@s=*~}%$1>N*

drives the garbage collector nuts. So far, all settings I've tried resulting either in a GC error message or too much memory consumption.

How it works

8A#              e# Compute 8¹⁰ = 1,073,741,824.
{                e# Map the following block over all I in [0 ... 1,073,741,824].
  [              e#   Begin an array.
    _8b          e#     Copy I and convert the copy to base 8.
    3394241224Ab e#     Push [3 3 9 4 2 4 1 2 2 4], the representation of the
                 e#     Armstrong number 1122763285329372541592822900204593.
    ?            e#     If I is non-zero, select the array of base 8 digits.
                 e#     Otherwise, select the hardcoded representation.
    A0e[         e#     Left-pad the digit array with 0's to length 10.
    A,           e#     Push [0 1 2 3 4 5 6 7 8 9].
  ]              e#   End the array.
  ze~            e#   Transpose and perform run-length decoding, repeating the
                 e#   digit n k times, where k in the n-th entry of the repr.
                 e#   This is a potential Armstrong number, with sorted digits.
  _              e#   Push a copy.
  _,             e#   Compute the length of yet another copy.
  f#             e#   Elevate all digits to that power.
  :+s            e#   Add the results and cast to string.
  _$             e#   Push a sorted copy.
  @s             e#   Stringify the sorted digits.
  =*             e#   Compare for equality and repeat the string that many times.
                 e#   This pushes either the representation of an Armstong number
                 e#   or an empty string.
  ~              e#   Evaluate, pushing the number or doing nothing.
}%               e#
$1>              e# Sort and remove the lowest number (0).
N*               e# Join, separating by linefeeds.


Mex table generation There is a table (the matrix one, not the one in your kitchen) called the "mex table". It has a left-top cell, at coordinates (0,0), but extends to infinity rightwards and downwards. The x-coordinate increases to the right and the y-coordinate increases downwards.

Every cell has a value >=0, and the cell at (0,0) has the value 0. The value of any other cell is defined as the lowest integer, >=0, which does not occur directly above it or directly to the left of it.

The start of the mex table looks like this:

+---+---+---+---+---+-
| 0 | 1 | 2 | 3 | 4 | ..
+---+---+---+---+---+-
| 1 | 0 | 3 | 2 | 5 | ..
+---+---+---+---+---+-
| 2 | 3 | 0 | 1 | ..
+---+---+---+---+-
| 3 | 2 | 1 | ..
+---+---+---+-
| 4 | 5 | ..
+---+---+-
| : | : | \

So, for example, the cell at (2,1) is 3 because 0 occurs left of it, 1 occurs left of it and 2 occurs above the cell. The cell at (3,1) is 2, however, because in the part of the row directly to the left of (3,1) and the part of the column directly above (3,1), 0, 1 and 3 occur, but 2 doesn't.

Objective: Print, to standard output, the number in the cell at (x,y) given two integers, both >=0, on standard input, space-separated and newline-terminated.

Thunderbirds are GO!

(This is derived from a question from the national finals of the Dutch Informatics Olympiad of some time ago.)

GolfScript (2 chars)

~^

This is familiar to anyone who knows anything at all about combinatorial game theory.


Numbers with multiple runs of ones Task

Find the set of numbers such that the binary representation contains two or more runs of 1 separated by at least one 0.

For example, the for the numbers that are 4 bits long:

 0 0000        (no ones)
 1 0001        (only one run)
 2 0010        (only one run)
 3 0011        (only one run)
 4 0100        (only one run)
 5 0101 Valid
 6 0110        (only one run)
 7 0111        (only one run)
 8 1000        (only one run)
 9 1001 Valid
10 1010 Valid
11 1011 Valid
12 1100        (only one run)
13 1101 Valid
14 1110        (only one run)
15 1111        (only one run)

Input

An integer provided to the application via some input in the range 3 .. 32.  This represents the maximum number of bits to count up to.

The input of n indicates that the numbers 0 .. 2n-1 need to be examined.

Output

A delimited (your choice) list of all numbers meeting the criteria. The numbers are to be presented in numeric order.  An extra trailing delimiter is acceptable.  Data structure enclosures (e.g. [] and similar) are also acceptable.

Example

Input: 3
Output: 5

Input: 4
Output: 5, 9, 10, 11, 13

Input: 5
Output: 5, 9, 10, 11, 13, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 29

This is code-golf - the answer with the least amount of bytes wins.

Python, 48

lambda n:[i for i in range(2**n)if'01'in bin(i)]

I had been vastly overthinking this. We just need to check if the binary expansion contains '01'.
For there to be two runs of ones, the one on the right must be preceded by a 0. If there's only one run, there won't be any leading 0's, so that won't happen.

Old answer:
lambda n:[i for i in range(2**n)if len(set(bin(i).split('0')))>2]

The Python binary representation works very nicely here. A binary number is written like bin(9)=='0b10110'. Splitting at '0' results in a list of

Empty strings to the left of the initial 0, between any two consecutive 0's, and to the right of any final 0
The letter b followed by one or more leading ones
Runs of 1's that are not leading

The first two categories always exist, but the last one only exists if there is a run one 1's that doesn't contain the leading '1', and so only if there's more than one run of 1's. So, it suffices to check if the list contains more than 2 distinct elements.
Python 3.5 saves 2 chars by unpacking {*_} in place of set(_).


ASCII Arc Length: How long is a piece of string? Given an ASCII representation of a piece of string, determine its length.

Input

An multi-line ASCII rendering of a piece of string, which runs from top to bottom, with one 'node' (corner) on each line of input. The delimiter may be assumed to be CR, LF, CRLF, or LFCR. Input may be accepted from STDIN, Command Line Argument, Function Parameter, or whatever daft method your language of choice necessitates if none of the prior are applicable.

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

Each line in the context of the previous tells you the position of one of the nodes on the string. The first line always has exactly one hash #, so the position is trivially found. Each following line has a hash '#' on the node itself, and on all calls which must be included to make the string 'complete' (attached to itself). All positions will be between 0 and 9 inclusive, but the difference is what realy matters.

For example, the string defined by the sequence 1, 3, 6, 5, 1, 3, 4 has the following nodes:

 #
   #
      #
     #
 #
   #
 #
     #
    #

Which we must join up on a line by line basis starting from the top (nodes marked with X for clarity, they will be hashes in actual imputs). This means, the first line has no hashes, and each following line has exactly as many hashes as are rquired to 'connect' the previous node to the current with hashes. This can be thought of as putting a hash in every space between the two nodes (on the lower line) and then removing any that appear on the line above. Example:

 X
  #X
    ##X
     X
 X###
   X
 X#
   ##X
    X

There will be no fewer than 2 lines, and no more than 100. The input will be padded with spaces to form a rectangle of width 10 (excluding the line delimiters). You may require a trailing new-line be present or absent, but declare any such requirements in your answer.

Computing the Arc Length

You must output the arc length of this string. You compute the arc length by taking the distances between each consequtive nodes. The distance between one node and the next is sqrt(d^2 + 1) where d is the difference in position (that is, the current position minus the previous). For example, the sequence 4, 8, 2, 3, 4, 4 has differences 4, -6, 1, 1, 0, which gives distances (rounded to 2 dp) 4.12, 6.08, 1.41, 1.41, 1 by squaring, adding one, and square-rooting. The arc length is then the sum of these distances, 14.02.

You must reduce the result of the square-root to 2 decimal places before summing (this is to allow sqrt tables and make answers consistent/comparable across systems; see below).

Using the input example at the top`

  #    2 -1  1.41
 #     1 +0  1.00
 #     1 +4  4.12
  #### 5 -5  5.10
##     0 +3  3.16
  ##   3 -2  2.24
 #     1 +2  2.24
  ##   3 -1  1.41
  #    2

            20.68 (total)

Output

You must output the arc length as exactly one number, or a decimal string represenation with 2 decimal places of precision. Numerical output must be rounded, but I'm not going to quibble about minute floating point inaccuracies.

SQRT Table

This is a table of the rounded squareroots you must conform to. You can either use this table itself, or verify that your system conforms to the results.

1  1.00
2  1.41
5  2.24
10 3.16
17 4.12
26 5.10
37 6.08
50 7.07
65 8.06
82 9.06

Powershell to produce this table:

0..9 | % {"" + ($_ * $_ + 1) + " " + [System.Math]::Sqrt($_ * $_ +1).ToString("0.00")}

Test Cases

Input:

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

Output: 20.68

Input:

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

Output: 49.24

Input:

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

Output: 44.34

Test Code

A larger test case and a C# solver and example generator can be found as a Gist.

Victory Criterion

This is code-golf, the shortest code will win.

JavaScript (ES6), 158 bytes

-1 byte thanks to @VisualMelon

s=>s.split`
`.map(s=>(s=s.replace(/./g,(m,i)=>m>" "?i:""),n=s[0]>n?s.slice(-1):s[0]),n=p=0).reduce((t,v,i)=>(r=i&&t+(((p-v)**2+1)**.5*100+.5|0)/100,p=v,r),0)

Output is sometimes not exact  (0.999 instead of 1) due to floating-point imprecision, but rounding was done part-way through the steps in order to match the square root table.

Test Snippet

Note that trailing spaces on each line are ignored, so they can be omitted from the input.

f=
s=>s.split`
`.map(s=>(s=s.replace(/./g,(m,i)=>m>" "?i:""),n=s[0]>n?s.slice(-1):s[0]),n=p=0).reduce((t,v,i)=>(r=i&&t+(((p-v)**2+1)**.5*100+.5|0)/100,p=v,r),0)
<textarea id=I rows=15 cols=12></textarea><br>
<button onclick="O.value=f(I.value)">Run</button> <input id=O disabled>


Hidden Inversions (Cops' Thread) This is a cops-and-robbers puzzle the robbers' thread can be found here.
Your task will be two write two programs (or functions) such that they are anagrams of each other and one performs the left inverse of the other.  These programs may accept and output as many integers or complex numbers as you wish.  If you choose take numbers as character points or any other reasonable means you must indicate you are doing so in your answer.  If you choose to restrict the domain of your function you must also indicate the restricted domain in your answer.
You will then present the first program in the form of an answer with left inverse hidden for robbers to find.
The shown program must implement a injective function (otherwise it would be impossible for a hidden answer to exist).
If your answer has not been cracked in one week you may reveal the hidden answer and mark it as safe.  Safe answers cannot be cracked by robbers and will remain un-cracked indefinitely.
The goal will be to create the shortest un-cracked answer in bytes.
Example
You could show the following python program that adds one to the input
lambda x:~-x

A solution could be:
lambda x:-~x

This subtracts one from the input

Python 3, 80 bytes (Cracked)

bhmq = int(input())
print(bhmq ** 2)
(1 or [(sqrt),(specification+of*integerr)])

Domain: positive integers. Function is just squaring of a number. Input to stdin, output to stdout, as well as in the inverse function. Note that Python ignores the third line here, because it is syntactically valid and 1 is already a truthy value, so Python doesn't even look whether the right part of 'or' is well-defined.

Robbers should write a sqrt function that will work correct on all non-zero squares, printing integer value as is, without floating point (so on input '4' output should be '2' or '2\n', not '2.0' or '2.0\n').


Tasteless and other bugs Some versions of the standard Android calculator app allow you to press a key, like 'sin' and then the 'del' key to make it 'si'. Probably just a bug which they can't be bothered with removing.

The following letters/letter groupings are typable:

sin
si
s
cos
co
c
tan
ta
t
ln
l
log
lo
e

So, 'tasteless' is typable, because ta-s-t-e-l-e-s-s and so is 'clogs' because 'c-log-s'. However 'got' is not typable, neither is 'an' or 'xyz'.

Write a program that takes a single word (or sequence of letters, only a-z in input) as input and produces output to indicate if a word is typable or not.

Output may be a single character/letter/digit/etc. or it may be larger. All typable words should produce the same output. All non-typable words should also produce the same output.

P.S. Just out of curiosity, is 'tasteless' the longest dictionary word that is typable?

Perl, 47 43 41 + 1 = 42 bytes
-4 bytes thanks to @Sunny Pun.  -2 bytes thanks to @Brad Gilbert b2gills and @Downgoat
Run with the -n flag.
say!/^(s(in?)?|co?|t(an?)?|ln?|log?|e)+$/

It can definitely be golfed futher, but in the spirit of competition, I'm leaving the mostly-original regex I came up with at the beginning.
Returns nothing if true, 1 if false.
Try it online!
I downloaded a dictionary file, and the longest word I found was 11 letters -- tattletales


Square Number Digit Density The square number digit density (SNDD) of a number - invented by myself - is the ratio of the count of square numbers found in consecutive digits to the length of the number.  For instance, 169 is a 3-digit number containing 4 square numbers - 1, 9, 16, 169 - and thus has a square number digit density of 4/3, or 1.33.  The 4-digit number 1444 has 6 squares - 1, 4, 4, 4, 144, 1444 - and thus a ratio of 6/4, or 1.5.  Notice in the previous example that squares are allowed to be repeated.  Also, 441 is not allowed, because it cannot be found consecutively inside the number 1444.

Your task is to write a program that searches a given range A - B (inclusive) for the number with the highest square number digit density.  Your program should abide by the following specifications:

Take input A, B in the range 1 to 1,000,000,000 (1 billion).  Example: sndd 50 1000
Return as a result the number with the largest SNDD.  In the case of a tie, return the smallest number.
0 does not count as a square in any form, 0, 00, 000, etc.  Neither do squares starting with 0, such as 049 or 0049.
Note that the entire number does not have to be a square number.

Examples:

sndd 14000 15000
Output: 14441

sndd 300 500
Output: 441

Bonus: What is the number with the largest SNDD between 1 and 1,000,000,000?  Can you prove whether this is the largest possible, or there might be a larger one in a higher range?

Current Scores:

Ruby: 142
Windows PowerShell: 153
Scala: 222
Python: 245

Now that an answer has been selected, here is my (ungolfed) reference implementation in JavaScript: http://jsfiddle.net/ywc25/2/

Answering the bonus: the best score for numbers <1e9 is 5/3=1.666..., generated by 144411449 (and maybe others?).

But you can do better with larger numbers.  Generally if n has a score of x, then you can concatenate two copies of n and get the same score x.  If you're lucky and n has the same first and last digit, then you can drop one of those digits in the concatenation and improve your score slightly (one less than double the number of squares and one less than double the number of digits).

n=11449441 has a score of 1.625 and has the same first & last digit.  Using that fact, we get the following sequence of scores:

1.625 for 11449441
1.666 for 114494411449441
1.682 for 1144944114494411449441
1.690 for 11449441144944114494411449441
1.694 for 114494411449441144944114494411449441

which gives an infinite sequence of numbers which are strictly (although decreasingly) better than previous numbers, and all but the first 2 better than the best score for numbers < 1e9.

This sequence may not be the best overall, though.  It converges to a finite score (12/7=1.714) and there may be other numbers with better scores than the limit.

Edit: a better sequence, converges to 1.75

1.600 14441
1.667 144414441
1.692 1444144414441
1.706 14441444144414441
1.714 144414441444144414441


Which ghosts are missing? In this challenge, given a list of ghosts from Pac-Man, you must output which ghosts are missing. You must do it in as few bytes as you can

Input

Input will consist of a string or list, which will include a number ghosts, which could include;

Blinky
Inky
Pinky
Clyde

However, input may also include Pac-Man (with that punctuation). So, the maximum amount of items in a list will be five, in any order. It can be assumed that no invalid items will be in the list

Output

Output will consist of a string, or list. This will include of all the ghosts that are not in the input, in any order. However, if Pac-Man is in the input, all ghosts will be considered missing (because he eats them).

Test cases

input: Clyde
output: Blinky, Inky, Pinky
alternate output: Inky, Pinky, Blinky
or one of the other 4 permutations

input: Clyde, Blinky # or however you delimit it
output: Inky, Pinky
alt: Pinky, Inky

input: Pac-Man, Clyde
Output: Blinky, Inky, Pinky, Clyde
or you could output one of the other 23 permutations

input:[null]
Output: Blinky, Inky, Pinky, Clyde
or you could output one of the other 23 permutations

This is codegolf, so the lower the bytecount, the better.

Retina, 45 bytes

A`-
$
,;BliNClyde,INPiN
N
nky,
D`\w+,
.*;|,$

The trailing linefeed is significant. Input and output are comma separated.

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

I did not expect to be able to show off Retina's latest addition (deduplication stages) so soon, but it's really helpful for this challenge. :)

Stage 1: Anti-Grep

A`-

Anti-grep stages discard all lines that match the given regex. The regex is just - and the input is always a single line, so this discards all ghosts if the input contains Pac-Man.

Stage 2: Substitution

$
,;BliNClyde,INPiN

This simply appends the fixed string ,;BliNClyde,INPiN. This will be the list of ghosts in the output after some clean-up.

Stage 3: Substitution

N
nky,

Note that we've written the three *nky ghosts with an N in the previous stage (and omitted the comma after them), and we now expand this shorthand, which saves a couple of bytes. There is now a comma after every single ghost, and we've got the input ghosts and list of all ghosts separated by a semicolon.

Stage 3: Deduplication

D`\w+,

This is the new part. Deduplication stages find all instances of the given regex and discard all matched substrings which are equal to an earlier matched substring. The regex simply matches all the ghosts, both in the input and in the list of potential outputs. If the input contains a ghost, then the same ghost will be matched again in the second list and is discarded. Otherwise, the ghost is matched for the first time in the second list and kept. So after this, the list after the semicolon is our desired output. All that's left is a bit of clean-up:

Stage 5: Substitution

.*;|,$

We simply match everything up to the semicolon as well as the comma at the end of the string and remove them.


Shoot the ASCII Moon (Previously on "Print the __ without using __" ... this one and this one)
The game of Hearts has a popular scoring variant called "Shooting the Moon," whereby instead of trying to not acquire penalty cards (and thus penalty points), as is the usual gameplay strategy, if you acquire all of the penalty cards you actually score the best that round. We're going to apply that same logic to some code golf.
The ASCII printable characters (plus space) are, in order
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

Let's divide these into three groups:
Alphanumeric:
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

Symbolic (or non-alphanumeric)
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

and the space character.
Your task is to use the alphanumeric characters to print the symbolic characters (in any order), with the following restrictions:

The program/function should take no input and output to STDOUT (or equivalent).
You can use a symbolic character in your source code for a penalty of +5 per unique character.
Using the same character more than once does not increase your penalty (e.g., you can use [ 25 times and only get one +5 penalty)
Whitespace (including tabs and newlines) in the output or the source code is completely optional. Leading, trailing, inline - no penalties or bonuses. They still count for bytes in source code as usual.
If you manage to use all 32 symbolic characters in your code, you get a bonus of -100 points for Shooting the Moon instead of any penalties.
If you manage to use all 32 symbolic and all 62 alphanumeric characters in your code, you instead get a bonus of -250 points for Shooting the Sun instead of any penalties.
Characters inside literal strings, literal characters, or comments do not count for the bonus or the penalty. (E.g., a Foo program of something like "!#$%..." would be allowed, but would not get the bonus or penalty points for the characters inside the literal).
Literal string or comment delimiters do count, however, so something like // !#$*... would count the initial / for penalty/bonus calculations.
Yes, this rules out languages like Whitespace or the like, where everything not whitespace is treated as a comment. Bummer.
Scoring is bytes of code + penalty(ies) + bonus(es), lowest score wins. Negative scores are possible.

Example scores:
50 bytes code + (5 unique symbolic characters)*5 penalty each = 75 points
200 bytes code + (32 unique symbolic characters)*0 penalty each + (-250 bonus for shooting the sun) = -50 points

GolfScript, -153

{""''!$%&()*+,-./:;<=>?@[\]^_`|~#
}ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789

Prints

{""''!$%&()*+,-./:;<=>?@[\]^_`|~#
}

Score:

97 bytes of source code: +97
Shooting the Sun: -250

Try it online.

How it works

Since the code block (lambda, anonymous function)

{""''!$%&()*+,-./:;<=>?@[\]^_`|~#
}

does not contain any syntax errors, it will be pushed on the stack and printed verbatim if left on it. The linefeed is required to end the comment that # started.

Finally, ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 is an undefined token; it does nothing.


Tuple addition in pointfree What is the shortest way we can express the function

f(a,b)(c,d)=(a+c,b+d)

in point-free notation?

pointfree.io gives us

uncurry (flip flip snd . (ap .) . flip flip fst . ((.) .) . (. (+)) . flip . (((.) . (,)) .) . (+))

which with a little bit of work can be shortened to

uncurry$(`flip`snd).((<*>).).(`flip`fst).((.).).(.(+)).flip.(((.).(,)).).(+)

for 76 bytes.  But this still seems really long and complex for such a simple task.  Is there any way we can express pairwise addition as a shorter point-free function?

To be clear by what I mean by point-free,  a point-free declaration of a function involves taking existing functions and operators and applying them to each other in such a way that the desired function is created.  Backticks, parentheses and literal values ([],0,[1..3], etc.) are allowed but keywords like where and let are not.  This means:

You may not assign any variables/functions
You may not use lambdas
You may not import

Here is the same question when it was a CMC

44 bytes
Got this from \x y -> (fst x + fst y, snd x + snd y)

(<*>).((,).).(.fst).(+).fst<*>(.snd).(+).snd

Try it online!
Or, 42 bytes using do:
do a<-fst;((,).(a+).fst<*>).(.snd).(+).snd

Try it online!


Cap the highest values in a list so that the sum equals a given number A slightly more challenging one compared to my previous challenge. Given a list of positive integers (>0) and the positive integer m, output a list of positive integers that are capped values of the input values so that the sum of the capped values equals m. Cap the highest values first. And keep the same order.

Cases

(Given 'list' and 'sum' output 'list')

Given 4, 2 and 6 output 4, 2 no capping needed (ncn), keep order (ko)
Given 2, 4 and 6 output 2, 4 ncn, ko
Given 3, 3 and 6 output 3, 3 ncn
Given 3, 3 and 7 output 3, 3 ncn

Then this:

Given 4, 2 and 5 output 3, 2 cap the highest (cth), ko
Given 2, 4 and 5 output 2, 3 cth, ko
Given 3, 3 and 5 output 3, 2 or 2, 3 cap any of the highest (cath)

Then this:

Given 5, 4, 2 and 10 output 4, 4, 2 cth, ko
Given 2, 4, 5 and 10 output 2, 4, 4 cth, ko
Given 4, 4, 2 and 7 output 3, 2, 2 or 2, 3, 2 cth, cath, ko
Given 4, 2, 4 and 7 output 3, 2, 2 or 2, 2, 3 cth, cath, ko

Then this:

Given 4, 4, 2 and 5 output 2, 2, 1 or any permutation (oap)
Given 2, 4, 4 and 5 output 1, 2, 2 oap
Given 4, 4, 2 and 4 output 1, 2, 1 oap
Given 2, 4, 4 and 4 output 1, 1, 2 oap
Given 70, 80, 90 and 10 output 3, 3, 4 oap

Then this:

Given 4, 2, 4 and 2 output an error or a falsy value, because the sum of 3 positive integers cannot be 2.

Rules

Both input and output are all about positive integers (>0)
The number of values in the input and output list are equal.
The sum of the output values is exactly equal to m or less than m only if the sum of the input values was already lower.
If the sum of the values in the input list is already lower then or equal to m, no capping is needed. (ncn)
Cap the highest values first (cth)
When multiple values are the highest value and equally high, it doesn't matter which you cap. (cath)
The capped values in the output list have to be in the same order as their original values in the input list. (ko)
When at some point (thinking iteratively) all values are equally high, it stops being important which you cap.
If there's no solution output an error or a falsy value.

The winner

The shortest valid answer - measured in bytes - wins.

Apart form the rules, I'm interested to see a program that keeps a value intact as long as possible. Consider the input values a plant each with the heights 10,2,10 and the maximum m=5, it would be a waste to cap the baby plant in the middle.

Python 3, 70 77 56 bytes

-21 bytes thanks to Jonathan Allan!

def f(l,n):
 while n/all(l)<sum(l):l[l.index(max(l))]-=1

Try it online!


Zero an arbitrarily large cell in Brainf*** Your task is to write a piece of code that zeros the current cell in the Brainfuck variant that, each cell can contain a signed integer of arbitrarily large magnitude, instead of the normal 0 to 255.
You may assume there are l cells to the left and r cells to the right of the current cell that are initially zero. You program may only access these l+r+1 cells. After your code ends it should leave the l+r extra cells zero and the pointer to the current cell at the original position.
You may not use any input/output.
The code with smallest l+r wins. If there is a tie, the shortest code wins. It is recommended to also state the time complexity of your program for reference, where n is the absolute value of the original integer in the current cell.
Useful tools
You can test a Brainfuck program in this variation using this interpreter on TIO by mbomb007.
You can also use the interpreter in this answer by boothby (other Python answers probably also work, but I didn't test).

l+r = 0+2 = 2, 55 53 51 bytes

[>+[-<+>>+<]<[>]>[+[-<+<->>]<[->+<]]>[-<+>]<<]>[-]<

l+r = 1+2 = 3, 46 44 bytes

[[>+[-<+<+>>]<[<+[->->+<<]]>]>[>]<[-]<<[-]>]

My own algorithm. The pointer should begin at the number that needs to be zeroed. The time complexity is O(n^2).

How it works:

We start with the number n.
We increment one, so the number becomes n+1.
We decrement two, so the number becomes n+1-2 = n-1
We increment three, so the number becomes n-1+3 = n+2.
We decrement four, so the number becomes n+2-4 = n-2.

We repeat the process, increasing the in-/decrement each step, until we get zero.


How many goals has Steven Gerrard scored? Steven Gerrard was born on 30th of May 1980. He is now 37 years old. Happy birthday, Steven!

To celebrate his anniversary, your goal is to remind him the number of goals he has scored each year in premiere league for Liverpool.

He doesn't want to remember the goals scored before or after playing for Liverpool. It is like scoring 0 goals.

Input

The starting year of football season.

Output

The number of goals scored by Steven during this season for Liverpool.

List of seasons and goals

1998–99     0
1999–2000   1
2000–01     7
2001–02     3
2002–03     5
2003–04     4
2004–05     7
2005–06     10
2006–07     7
2007–08     11
2008–09     16
2009–10     9
2010–11     4
2011–12     5
2012–13     9
2013–14     13
2014–15     9

Example

Input    Output
2002     5
2017     0
1990     0
2014     9

This is code-golf so the shortest submission in bytes in each language wins. Explanations are encouraged.


Are the beams above or below the notes? In musical notation, groups of notes shorter than one beat are joined together by a line at the bottom called a beam. Here are a few bars of music with the beams highlighted:

(Taken from Second Suite in F by Gustav Holst; you can hear how these notes sound at 0:13 in this video.)

You may notice that beam #6 is above the ovals that define the notes, and its vertical lines attached to their right sides, while the others are below the notes and attached to their left. What determines this? There are a few simple rules, which are the subject of this challenge.

By default, the placement of the beam is determined by its highest or lowest note. If the note farthest from the centermost line of the staff is above it, then the beam goes below the notes. If the note with the highest absolute value is above the centermost line of the staff, then the beam goes below the notes.
If the highest and the lowest note are the same distance from the center line, the direction of the beam is determined by which side of the center line the majority of notes in the beam lie on. If a majority of notes lie above the centre line, the beam goes down. If a majority of notes lie below the centre line, the beam goes up. Notes on the center line do not count either way.
If the highest and the lowest note are the same distance from the center line, and equally many notes lie above and below the center line, the beam may be placed either above or below the notes.

In the sample notation above, the beams of clusters #1, 2, 3, and 5 are determined to be below the notes because their highest notes (their second, second, first, and third respectively) are above the center line. #6's lowest note is its first/third note, which is below the center line. #4's highest and lowest note are equally distant from the center line and it contains no majority either way. Its beam could be placed either above or below, but my composition program renders it as below.

Your commission

Write a program that takes in a list of integers, which may be zero or negative, and outputs a truthy/falsey value. These integers represent notes and their distance from the center line; positive values represent notes above the line, zero represents notes on the line, and negative values represent notes below the line. Determine, given a cluster of notes that sit those distances from the center line, which way the cluster's beam should go; output TRUE if the beam should go above the notes and FALSE if the beam should go below the notes. To restate the rules above and give the algorithm:

Find the number in the list with the largest absolute value. If it is greater than zero, output FALSE. If it is less than 0, output TRUE. If it is 0, output may be TRUE or FALSE as convenient. If there are positive and negative numbers with the same, maximal absolute value, continue.
Determine whether the majority of numbers are positive and negative, ignoring zeroes. If a majority of numbers are positive, output FALSE. If a majority of numbers are negative, output TRUE.
Otherwise, output may be TRUE or FALSE as convenient.

You might be given only one number. In that case, it has the highest absolute value, so if it is greater than 0 output false; if it is less than zero output true; and if it is 0 you may output true or false.

You may not assume the numbers are sorted.

Test cases

5, 4, 3 -> FALSE                     # #3
1, 0, -1 -> TRUE or FALSE            # #4
0, 1, 2, 0 -> FALSE                  # #5
-2, -1, -2 -> TRUE                   # #6
3, 1, 4, 1, 5, -9 -> TRUE            # Largest absolute value below 0, rule 1
3, 1, 4, 1, 5, -5 -> FALSE           # Largest absolute value tied, determined by majority, rule 2
3, 1, -3, -1, 5, -5 -> TRUE or FALSE # Largest absolute value tied and no majority, unspecified

R, 40 bytes

function(x)min(x)+max(x)+mean(sign(x))<0

Try it online!

If min(x)+max(x) is non-zero, its sign corresponds to the note farthest from the centre and gives the direction of the beam.

Adding mean(sign(x)) can never change the sign. Indeed, either (a) all notes are of the same sign and mean(sign(x)) is of the same sign as min(x)+max(x) or (b) notes are of both signs and mean(sign(x)) is strictly in \$(-1,1)\$  whereas min(x)+max(x) is an integer, so the sign of the sum is unchanged.

If min(x)+max(x)==0, the sign of the mean decides the direction.

If undecided, defaults to FALSE.