1 character typo generating most error messages from C++ compilation It seems that simple changes to a C++ file, especially with templates, can generate pages of errors. This contest is to see what the largest "bang of the buck" is, that is the more verbose error output with the smallest change to the source code (1 character addition).

Because other languages are more sane, this will be limited to C++ and gcc version 4.x.

Rules

Original source file must compile with gcc 4.9.2 to object code without error.
One ASCII character is added to source code to create a typo, increasing file size by 1 byte.
Compiler is run with default options. Necessary options like -c and -std=c++11 are allowed, options like -Wall are not.
Metric is

    number of bytes of generated error messages
    -----------------------------------------------------------------------
    (bytes of source code with typo) (length of filename passed to compiler)

Answers will be validated with http://ideone.com/ C++ 4.9.2.

Example:

Filename is a.cpp, which is 5 bytes long.

int foo();

Working Compilation

 gcc -c a.cpp

Corrupted source code:

in t foo();

Failing Compilation

$ gcc -c a.cpp
a.cpp:1:1: error: ‘in’ does not name a type
in t foo();
  ^
$ gcc -c a.cpp |& -c wc
64
$ wc -c a.cpp
12 a.cpp

Score:
    64/12/5 = 1.0666

Better attempt: Insert { between parens of foo()

$ gcc -c a.cpp |& wc -c
497

New score: 497/12/5 = 8.283

Good Luck!

UPDATE

I encourage people to ignore the recursive implementation. That technically wins but is not in the spirit of the contest.

UPDATE 2

As many people have noted, the contest probably would have been more interesting if the C pre-processor was not allowed.  So I would like to encourage people to post solutions that do not use  pre-processor commands at all. That implies no use of any header files at all, since #include is not allowed!

As far as using IDEONE to validate, you are allowed to either use the IDEONE output directly (and the source name as prog.cpp), or you can run the IDEONE output through a global search and replace (s/prog.cpp/a.cc/ for example) and pretend that you were able to set the file name directly.

UPDATE 3

As people pointed out, Ideone is a little too restrictive, requiring linkage not just object file creation.  As this contest is purely in the name of fun, please be honest and specify what you used to get your score. Either use ideone, or use the most vanilla build (all defaults) of gcc 4.9.2 as you can muster.  The contest is intended to bring awareness to the awfulness of C++ error messages.

gcc 4.5.2, Score: 8579.15 (or 14367.49 for filename "a.C", may update later)

Original file, 29 bytes, compiles clean (a.cpp):

#if 0
#include"a.cpp"
#endif

Modified file, 30 bytes:

#iff 0
#include"a.cpp"
#endif

Errors:

$ gcc -c a.cpp 2>&1 | wc -c
1286873

Score:

1286873 / (30 * 5) = 8579.15

Head and tail of error output:

a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:1:2: error: invalid preprocessing directive #iff
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:

... And so on, backing out with second error after max include depth:

a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0,
                 from a.cpp:2,
                 from a.cpp:2:
a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0,
                 from a.cpp:2:
a.cpp:3:2: error: #endif without #if
In file included from a.cpp:2:0:
a.cpp:3:2: error: #endif without #if
a.cpp:3:2: error: #endif without #if

Note:
- If .C ends up qualifying as a valid extension then score is 1,206,869 / (28 * 3) = 14,367.49.
- If Dennis' suggested second #include is added, file name "a.cpp", score is 80,797,292,934 / (46 * 5) = 351,292,578.97


Write a program that checks the consistency of modern mathematics Modern mathematics has been formalised using set theory by various systems of axioms. Zermelo Frankel set theory with the axiom of choice (ZFC) forms an intuitive set of axioms and is hence most popular, though stronger choices exist.
Inspiration: A Relatively Small Turing Machine Whose Behavior Is Independent
of Set Theory by Adam Yedidia and Scott Aaronson
In this paper, a 7918-state Turing machine has been discovered that "checks" the consistency of ZFC. More specifically, it has been proven impossible to prove the machine as either halting or non-halting within ZFC. Note that if the program actually halts in a finite number of steps, its behaviour is also provably halting in any reasonable axiomatic system since we can enumerate this finite number of steps explicitly. Therefore halting can only mean an inconsistency in ZFC itself.
A 1919-state TM was also discovered subsequently
The method they've used (for the 8000 state machine) is to identify a mathematical statement whose truth has been proven to imply the consistency of ZFC, in this case Friedman's mathematical statement on graphs (section 3.1 of the paper), then written a program in a higher level language to check that, then converted it to a Turing machine
Your task: Write a program in any accepted language on this site (not necessarily a Turing machine) which cannot be proven as halting or non-halting within ZFC. This is code golf, so shortest program wins.
Your program must be deterministic, it cannot use "random" numbers or take external "random" input.
Likely method to go about this would be to identify a mathematical statement which is already known to be independent of ZFC or a stronger system, and check that - though this is by no means the only way to go about it. Here's a list of such statements to get you started.
Related: Analogous challenge for Peano arithmetic

NQL: 335 characters
In The Busy Beaver Frontier page 12, Scott Aaronson mentions that Stefan O'Rear found a 748-state Turing machine that halts iff ZF is inconsistent. Here is the code that compiles to that Turing machine from a higher-level programming language called NQL, based on Laconic. I'm not very familiar with this language, but applying basic golfing techniques yields 397 characters:
global x;global lcm;global l;global num;global denom;global i;global a;global b;global c;global d;proc main(){lcm=1;while(true){x=x+1;l=lcm;while(lcm!=(lcm/l)*l||lcm!=(lcm/x)*x){lcm=lcm+1;}if(x>253){num=0;denom=1;i=1;while(i<=lcm){num=num*i+denom;denom=denom*i;i=i+1;}a=num-denom*x;a=a*a;b=denom*denom;c=0;d=1;i=1;while(i<=x){c=c*i+d;d=d*i;i=i+1;}c=c*c;c=c*c*x;d=d*d;d=d*d;if(a*d>b*c){return;}}}}

I confirmed that the same output is produced as the original program with
diff <(python3 nqlaconic.py --print-tm riemann-matiyasevich-aaronson.nql) \
<(python3 nqlaconic.py --print-tm riemann-matiyasevich-aaronson-golfed.nql)

Applying variable name shortening (this changes the output) yields 335 characters:
global x;global v;global l;global z;global y;global i;global a;global b;global c;global d;proc main(){v=1;while(true){x=x+1;l=v;while(v!=(v/l)*l||v!=(v/x)*x){v=v+1;}if(x>253){z=0;y=1;i=1;while(i<=v){z=z*i+y;y=y*i;i=i+1;}a=z-y*x;a=a*a;b=y*y;c=0;d=1;i=1;while(i<=x){c=c*i+d;d=d*i;i=i+1;}c=c*c;c=c*c*x;d=d*d;d=d*d;if(a*d>b*c){return;}}}}

Given its C-like syntax, I imagine the code could be easily adapted to other languages and shortened further.


Evaluate a Linear Feedback Shift Register Introduction

The Fibonacci Linear Feedback Shift Register (LFSR) is a digital circuit which generates a stream of random-looking bits.  It consists of several 1-bit flip-flops in a row, with certain positions designated as 'tapped'.  In each iteration, the values in the tapped positions are XORed together (i.e., summed modulo 2) and the result is held in reserve.  Then the bits are shifted to the right.  The rightmost bit falls off the register and becomes the output, while the reserve bit is input on the left.

Maximal LFSR

The output stream of a LFSR is periodic; it repeats after some number of iterations.  A maximal LFSR has a period of 2^n - 1, where n is its number of bits.  This only occurs if the tapped positions are correctly chosen; otherwise the period will be less.  If the LFSR is maximal, it will cycle through all possible internal states (except all zeroes) exactly once before repeating.

For more information about maximal Fibonacci LFSRs (primitive polynomials), see this article:  https://en.wikipedia.org/wiki/Linear_feedback_shift_register#Fibonacci_LFSRs

Task

You must write a function that takes as its arguments a list representing the initial internal state of an n-bit LFSR (a list of length n made of 0 and at least one 1), and a list of tapped positions.  The tapped positions are input as a list with either of these general formats (brackets, commas, and spaces are shown for convenience and are entirely optional):

Format A:  [0, 0, 1, 1]

Format B:  [3, 4]

Both formats declare that the 3rd and 4th positions are tapped.

The function must produce exactly one complete cycle of output of the LFSR (either as function output, or printed to the screen), as well as a Boolean evaluation of whether or not the LFSR period is maximal.

If you prefer, you may use two functions to produce the LFSR output and maximality evaluation.

Scoring

Per usual code golf rules, your score is the number of characters in your code.  Make sure your code evaluates these examples correctly:

Example 1

State: [1, 0, 1, 0]

Taps:  [3,4]

Output:  [0,1,0,1,1,1,1,0,0,0,1,0,0,1,1] and True (since the period is 2^n - 1 = 15)

Example 2

State:  [1, 0, 1, 0, 1]

Taps:  [3, 5]

Output:  [1,0,1,0,1,0,0,0,0,1,0,0,1,0,1,1,0,0,1,1,1,1,1,0,0,0,1,1,0,1,1] and True (since the period is 2^n - 1 = 31)

Example 3

State:  [1, 0, 1, 0, 1]

Taps:  [4, 5]

Output:  [1,0,1,0,1,1,1,1,1,0,0,0,0,1,0,0,0,1,1,0,0] and False (since the output has period 21, which is not equal to 2^n - 1)

GolfScript, 38 characters
:f;:i[{0{(2$=^}f/\+)\.i=!}do;].,)2i,?=

You may declare it as a named function if you enclose the code in {<code>}:F. It takes the top two arguments from the stack and pushes the results back to the stack, e.g. (test it online):
[1 0 1 0 1] [3 5]

:f;:i[{0{(2$=^}f/\+)\.i=!}do;].,)2i,?=

# => yields [1 0 1 0 1 0 0 0 0 1 0 0 1 0 1 1 0 0 1 1 1 1 1 0 0 0 1 1 0 1 1] 1

Annotated code:
:f;          # save tap positions (1 indexed) to variable f
:i           # and the initial state to variable i
[{           # the [{...}do;] loop generates an array using the loop
             #   top of stack is the current state
  0          #   push zero (accumulator)
  {          #   {...}f/ loops over all tap positions
    (        #     make the current position zero-indexed
    2$=      #     take the corresponding bit from the current state (2$)
    ^        #     xor with the accumulator
  }f/        #   end of loop
  \+         #   prepend the new bit to the current state
  )\         #   and shift out the last bit (output)
  .i=        #   compare the current state to input
  !          #   if not equal then loop
}do;]        # end of loop - discard the state
.,)          # length of the output + 1
2i,?         # 2^length of initial state
=            # are those two numbers equal?


New Password Idea: Word-walker I thought of a new way to generate my passwords, and even though it's probably not very clever in the long run, it could still make for a fun code-golf.

Taking a string of words, the password is generated thus:

Pick the nth character in the nth word
If n is larger than the word, continue counting backwards

Example:

This is a fun task!
T     s a  u      !

T is the first character
s is the second
a is the first, but going back and forth it is also the third
u is the second but because of counting backwards it's also the fourth
'!' is the fifth character in 'task!' and thus will be included in the final password, Tsau!

Rules

Input will be a string
Separate the string on spaces, all other characters must be included
Uppercase letters must remain uppercase, same with lowercase
You take n steps in each word, where n is the number of words that have come before plus one
If n is larger than the word, you must step backwards through the word, if you hit the start, you go forward again until you have stepped n times
The first and last character is only stepped once, so 'fun' on the seventh position as an example goes 'funufun' and ends on n, not 'funnuff' and ends on f
Output must be a string

Examples:

Input              Output
Once Upon A Time   OpAe
There was a man    Taaa
Who made a task    Waak
That was neat!     Taa
This is a long string to display how the generator is supposed to work  Tsagnoyotoipto

The shortest code in bytes wins!

Python 2, 72 bytes

lambda s:''.join((-~i*(w+w[-2:0:-1]))[i]for i,w in enumerate(s.split()))

Try it online!


Remove Spaces, Maintaining Capitalization Your input will be an English sentence, phrase, or word. It will only contain a-zA-Z' -,.!?. Your task is to take the input, remove spaces, and then redistribute capitalization such that letters at indexes that were capitalized before (and only letters at indexes that were capitalized before) are capitalized.

For example, if the input is A Quick Brown Fox Jumped Over The Lazy Dog, the (0-based) indexes of the capital letters are 0, 2, 8, 14, 18, 25, 30, 34, 39. Next, remove spaces from the input: AQuickBrownFoxJumpedOverTheLazyDog. Next, lowercase all letters, but uppercase those at 0, 2, 8, 14, 18, 25, 30, 34, 39: AqUickbrOwnfoxJumpEdovertHelazYdog, which is your output.

Input

Your input will be an English sentence, phrase, or word. It can only contain lowercase letters, uppercase letters, hyphens, apostrophes, commas, periods, question marks, exclamation marks, and spaces.

Output

The input with spaces removed, lowercase-d, with letters at the index of capital letters in the input uppercase-d.

NOTE: Your program cannot crash (error such execution terminates) with an IndexOutOfRange or similar error.

Test Cases

Hi! Test!
Hi!tEst!

A Quick Brown Fox Jumped Over The Lazy Dog
AqUickbrOwnfoxJumpEdovertHelazYdog

testing TESTing TeStING testing testing TESTING
testingtESTIngteStInGTEstingtestingtestiNG

TESTING... ... ... success! EUREKA???!!! maybe, don't, NOOOOO
TESTING.........success!eureKA???!!!maybe,don't,nooooo

Enter        PASSWORD ---------
Enterpassword---------

A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Z z
AabbCcddEeffGghhIijjKkllMmnnOoppQqrrSsttUuvvWwxxZz

  TEST
teST


Press any key to continue Your task is to create a program that will display the following text, wait for the user to press a key (it is okay to ignore keys like ctrl, alt, caps lock, etc., as long as keys like letters, numbers, symbols, and enter are not ignored), and then terminate the program:

Press any key to continue...

Trailing newlines are allowed. The program must exit immediately after a key is pressed. Also, the program must be fairly portable (i.e no OS-specific headers or modules, runs outside of an IDE, etc.).

The prompt must be exactly as shown above, unless a trailing newline cannot be avoided.

This is code-golf, so the shortest answer in bytes wins. This is also my first code-golf question, so I apologize if I do not know the rules on PPCG.

Batch, 46 bytes

@echo Press any key to continue...
@pause>nul

Because pause's output contains a space before each ..


Calculate a rock rolling down a hill Introduction
Sisyphus was having some troubles at work lately. It seems he just never gets anything done, and he would love to find a solution to this problem.
His current employment requires rolling a rock up a hill. He usually does his job well, but every time he is near the top of the hill it rolls down again.
He is getting really frustrated with his job and wants to solve the problem scientifically by having a computer simulate the rock rolling down the hill.
It so happens that Sisyphus isn't particularly good at programming, so maybe you can help him out?
The Challenge
After this silly introduction, let's come to business. Your program will receive an illustration of the hill and the rock which looks similar to this:
#o
##
###
######
########

Where # represents a part of the hill and o represents the rock.
You now have to implement a program which moves the rock 1 layer down. For example, the output of the above should be:
#
##o
###
######
########

If there is a horizontally even area, the hill just rolls horizontally, so...
o
########

...this would just make the stone roll sideways.
 o
########

If there is a vertical area, the rock falls down one step, so...
#o
#
#
#####

...would yield...
#
#o
#
#####

You will also receive the width and height of the image respectively in one line above the image. So, in complete, our sample input would look like this:
10 5
#o
##
###
######
#########

(Note that the whitespace here are spaces. Select the text and see what I mean.)
Some details

When the rock is already in the last line when running the program, you can choose to either terminate the program or output the unchanged input

The hill only ever goes downwards

Your program should format the output exactly the same as the input (including the dimensions), so if you pipe the output of the program to itself, it calculates the next step.

You can assume there is always a way to the bottom, so input where the path is "blocked" may cause undefined behaviour

You can assume there is always a space in the last line. The rock should "rest" there, so after calling the program a few times, always piping it's output into itself, you should end up with the rock in the last line, laying where the space previously was.

You may accept input in any form you like (stdin, file,...). You have to post the WHOLE program (so all pre-initialized variables count as code).

The lines are terminated with \n.

You can get some example inputs here (make sure you copy the spaces correctly!)

This is code-golf, so the working submission with the least bytes wins.

The winner will be chosen on July 26th, 2014. You can post solutions after that, but you can't win

If you have any questions, let me know in the comments.
Happy golfing!

Regex (.NET, Perl, PCRE, JavaScript, ... flavours), 25 bytes

Yes, this will create some debate again, whether a regular expression is a valid program, but I'll pre-empt that and say that this submission is just for fun and doesn't need to be considered for the winner. (As opposed to the 31 byte Perl variant at the bottom ;).)

So here is a pure regex replacement solution.

Pattern (note the trailing space):

o(( *)\n#*)(?=\2) |o

Replacement (note the leading space):

 $1o

The byte count is for the sum of the two.

You can test it at http://regexhero.net/tester/. Make sure to choose Unix-style line endings and "preserve pasted formatting" when pasting. If it still doesn't work, you still have pasted Windows-style line endings. The easiest fix in that case is to replace \n with \r\n in the pattern to see that it works.

Here is a 48 byte ECMAScript 6 function using this

f=(s)=>s.replace(/o(( *)\n#*)(?=\2) |o /,' $1o')

Finally, I've also got an actual program. It's 31 bytes of Perl (including two bytes for p and 0 flags; thanks to Ventero for the suggestion!).

s/o(( *)\n#*)(?=\2) |o / $1o/

If you want to test it, don't even save it in a file, just do

perl -p0e 's/o(( *)\n#*)(?=\2) |o / $1o/' < hill.txt


Super speedy totient function The goal is simple: calculate the totient function for as many numbers as you can in 10 seconds and sum the numbers.

You must print your result at the end and you must actually calculate it. No automated totient function is allowed, but bignum libraries are. You have to start at 1 and count up all the integers consecutively. You are not allowed to skip numbers.

Your score is how many numbers your program can calculate on your machine / how many my program can calculate on your machine. My code is a simple program in C++ (optimizations off), hopefully you can run it.

Important properties you could use!

if gcd(m,n) = 1, phi(mn) = phi(m) * phi(n)
if p is prime, phi(p) = p - 1 (for p < 10^20)
if n is even, phi(2n) = 2 phi(n)
others listed in first link

My code

#include <iostream>
using namespace std;

int gcd(int a, int b)
{
    while (b != 0)
    {
        int c = a % b;
        a = b;
        b = c;
    }
    return a;
}

int phi(int n)
{
    int x = 0;
    for (int i=1; i<=n; i++)
    {
        if (gcd(n, i) == 1)
            x++;
    }
    return x;
}

int main()
{
    unsigned int sum = 0;
    for (int i=1; i<19000; i++) // Change this so it runs in 10 seconds
    {
        sum += phi(i);
    }
        cout << sum << endl;
        return 0;
}

Nimrod: ~38,667 (580,000,000/15,000)

This answer uses a pretty simple approach. The code employs a simple prime number sieve that stores the prime of the smallest prime power in each slot for composite numbers (zero for primes), then uses dynamic programming to construct the totient function over the same range, then sums the results. The program spends virtually all its time constructing the sieve, then calculates the totient function in a fraction of the time. It looks like it comes down to constructing an efficient sieve (with the slight twist that one also has to be able to extract a prime factor for composite numbers from the result and has to keep memory usage at a reasonable level).

Update: Improved performance by reducing memory footprint and improving cache behavior. It's possible to squeeze out 5%-10% more performance, but the increase in code complexity is not worth it. Ultimately, this algorithm primarily exercises a CPU's von Neumann bottleneck, and there are very few algorithmic tweaks that can get around that.

Also updated the performance divisor since the C++ code wasn't meant to be compiled with all optimizations on and nobody else did it. :)

Update 2: Optimized sieve operation for improved memory access. Now handling small primes in bulk via memcpy() (~5% speedup) and skipping multiples of 2, 3, and 5 when sieving bigger primes (~10% speedup).

C++ code: 9.9 seconds (with g++ 4.9)

Nimrod code: 9.9 seconds (with -d:release, gcc 4.9 backend)

proc handleSmallPrimes(sieve: var openarray[int32], m: int) =
  # Small primes are handled as a special case through what is ideally
  # the system's highly optimized memcpy() routine.
  let k = 2*3*5*7*11*13*17
  var sp = newSeq[int32](k div 2)
  for i in [3,5,7,11,13,17]:
    for j in countup(i, k, 2*i):
      sp[j div 2] = int32(i)
  for i in countup(0, sieve.high, len(sp)):
    if i + len(sp) <= len(sieve):
      copyMem(addr(sieve[i]), addr(sp[0]), sizeof(int32)*len(sp))
    else:
      copyMem(addr(sieve[i]), addr(sp[0]), sizeof(int32)*(len(sieve)-i))
  # Fixing up the numbers for values that are actually prime.
  for i in [3,5,7,11,13,17]:
    sieve[i div 2] = 0

proc constructSieve(m: int): seq[int32] =
  result = newSeq[int32](m div 2 + 1)
  handleSmallPrimes(result, m)
  var i = 19
  # Having handled small primes, we only consider candidates for
  # composite numbers that are relatively prime with 31. This cuts
  # their number almost in half.
  let steps = [ 1, 7, 11, 13, 17, 19, 23, 29, 31 ]
  var isteps: array[8, int]
  while i * i <= m:
    if result[i div 2] == 0:
      for j in 0..7: isteps[j] = i*(steps[j+1]-steps[j])
      var k = 1 # second entry in "steps mod 30" list.
      var j = 7*i
      while j <= m:
        result[j div 2] = int32(i)
        j += isteps[k]
        k = (k + 1) and 7 # "mod 30" list has eight elements.
    i += 2

proc calculateAndSumTotients(sieve: var openarray[int32], n: int): int =
  result = 1
  for i in 2'i32..int32(n):
    var tot: int32
    if (i and 1) == 0:
      var m = i div 2
      var pp: int32 = 2
      while (m and 1) == 0:
        pp *= 2
        m = m div 2
      if m == 1:
        tot = pp div 2
      else:
        tot = (pp div 2) * sieve[m div 2]
    elif sieve[i div 2] == 0: # prime?
      tot = i - 1
      sieve[i div 2] = tot
    else:
      # find and extract the first prime power pp.
      # It's relatively prime with i/pp.
      var p = sieve[i div 2]
      var m = i div p
      var pp = p
      while m mod p == 0 and m != p:
        pp *= p
        m = m div p
      if m == p: # is i a prime power?
        tot = pp*(p-1)
      else:
        tot = sieve[pp div 2] * sieve[m div 2]
      sieve[i div 2] = tot
    result += tot

proc main(n: int) =
  var sieve = constructSieve(n)
  let totSum = calculateAndSumTotients(sieve, n)
  echo totSum

main(580_000_000)


Gode-Colf: Wipping Flords around Here is another short string related code-golf. You must write a full program that reads a string (from STDIN or as command line arguments, as long as you specify which) and wips the flords around (flips the words around). A valid flord wip must

Flip all of the beginning consonants. (All of the leading consonants up to the first vowel) For example, "Flipping Words" does not become "Wlipping Fords" because this only flips the first letter of each. Instead, it becomes "Wipping Flords"

Never flip a vowel. For example, "Eating Breakfast" becomes "Breating Eakfast"

Capitalize the first letter of each output word, and no more. For example 'Stack Overflow' becomes 'Ack Stoverflow', not 'ack StOverflow'.

Your input:

Will have the first letter of every word capitalized, and all the other letters lowercase.

Will consist entirely of upper and lowercase letters and spaces.
There will not be any extra or leading spaces.

There will be no strange consonant only words. For the purposes of this challenge, "y" is a consonant.

Will have at least 2 words, each separated with a single space. If there are an even number of words, you must flip the first word with the second, the third with the fourth, the fifth with the sixth and so on and so forth. If there are an odd number of words, the same rules apply, and the last word is skipped.

Here are some sample inputs and outputs.

Bunny Rabbit ---> Runny Babbit
Programming Puzzles And Code Golf ---> Pogramming Pruzzles Cand Ode Golf
The Cake Is A Lie ---> Ce Thake Is A Lie ("Is" and "A" both start with a vowel, so nothing changes. "Lie" is the last odd-word-out so nothing changes)
May The Best Golfer Win ---> Thay Me Gest Bolfer Win

CJam, 62 53 bytes

This is too long for now. Will add explanations once I am done golfing.

qS%2/{{el__"aeiou"&0=#_2$<@@>}%(a+2/Wf%~}%{s(eu\+}%S*

Try it online here


Golfing with User Agents Usually when performing an internet challenge, there's no problem with having to specify a user agent, but when it comes to dealing with Google, it changes.

Google blacklists the Urllib user agent, presumably to stop spambots, so you have to specify a user agent. This takes up many bytes, and is frankly rather annoying.

Example 1. Example 2. Example 3.

Note: I have updated my Python answers to use the tip suggested below

So how do you get around this problem using the shortest number of bytes?

The requests module, if allowed, is much shorter and easier than urllib in Python (2 and 3):

__import__('requests').get('url').text

On my computer, the user agent defaults to:

python-requests/2.3.0 CPython/3.4.3 Darwin/14.3.0


Triangulating Angles Prompt:
You are given two sets of XY coordinates along with two angles (all are floats): X1 Y1 A1 X2 Y2 A2. The angles are relative to world coordinates: 0 being straight up or north and going clockwise.
Your program or function has to return a set of two floats of the XY coordinates the two angles cross at.
Example:

In this case, the resulting point is between the two inputted points. For the case 100 500 50 300 600 80 (using degrees), the correct answer is 198 582. Online representation here
Other examples of edge cases:
1 1 45 4 4 45 returns NULL
1 4 45 2 4 45 returns NULL
https://imgur.com/a/2t0vky8
Rules:

Angles can be in radians or in degrees
The program should have a separate answer if there is not a valid answer: if the two lines are parallel (zero solutions) or the same line (infinitely many solutions)
The value returned can be represented in any form: 198;582, 198 582 and 198_582 are all valid
The answer can be rounded to a full number
This is code-golf

JavaScript (ES6), 76 bytes
Expects the angles in radians. Returns either [x,y] or 0 if the lines are parallel or coincident.

(x,y,a,X,Y,A)=>a-A&&[(m=(t=Math.tan)(a))*(X-=(x-=m*y)+t(A)*Y,X/=m-t(A))+x,X]

Try it online!
Or 71 bytes if we can just return [Infinity,Infinity] for invalid inputs.


Halt with 50% non-Halting Create a program that halts exactly 50% of the time. Be original. Highest voted answer wins. By exactly I mean that on each run there is a 50% chance of it halting.

Perl

fork || do {sleep(1) while(1)}

Each time you run this program, it halts and doesn't halt.


Triangular battleships (A computational geometry problem) You are the captain of a battleship. The engineering department's been cutting corners with designs this year, so the ship you're on takes the shape of a simple triangle.

You walk out onto the deck and enjoy the sea breeze... though not for long. An enemy has fired at you! — but will the shot hit?

Input

You may write either a function or a full program for this challenge.

Your program will take in 11 integers, ten of which are paired:

The first three pairs of integers (x1, y1), (x2, y2), (x3, y3) will specify the vertices of your ship. The triangle formed will have nonzero area.
The next pair of integers (ex, ey) specifies the location of the enemy's cannon. The enemy cannon will never lie on, or within the boundary of your ship.*
The pair (ax, ay) after that specifies where the enemy aimed at. This will be distinct from (ex, ey).
The final positive integer R specifies the range of the enemy's shot

*You'd be a terrible captain if you didn't even notice that happening!

Output

You must print/return a truthy value (e.g. true, 1) if the battleship will be hit, otherwise a falsy value (e.g. false, 0).

What is a hit?

The enemy shot is a straight line segment of length R from (ex, ey) in the direction of (ax, ay). If this line segment overlaps any part of the interior of your triangular battleship, then this counts as a hit. Otherwise it is not a hit.

Shots which graze along or only reach up to the boundary of the triangle do not count as a hit.

Examples

0 0 0 1 1 0
1 1
0 0
2

Hit: The enemy has shot right through the centre of your ship!

2 0 0 2 4 4
0 0
1 1
1

No hit: The enemy's range is too short, so you are safe.

0 0 1 2 3 0
-4 0
0 0
8

No hit: The enemy has grazed the side of your ship, so this does not count as a hit. Lucky!

0 0 -1 3 4 -1
-3 -4
3 4
5

No hit: The enemy shot just stops short of the ship, so you are safe. If the enemy's cannon had even slightly better range, then you would have been hit! Phew!

-2 -3 -3 6 7 -2
-6 2
1 -4
7

Hit: Even though the shot didn't penetrate to the other side, this is still a hit.

-3 2 2 -4 7 -3
-3 -4
-3 0
10

No hit: For the record, this is another close miss.

Additional test cases

0 0 6 0 6 8
-6 -8
6 8
20

No hit: This is another graze, but at an angle.

0 0 -2 -5 5 3
-3 4
0 0
6

Hit: The shot entered via a vertex of the ship.

Scoring

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

Python 3, 252 bytes

This is certainly the most variables I've ever used in code golf. :^P

from math import*;A=atan2
def h(a,b,c,d,e,f,g,h,i,j,R):
 r=R;_=0
 while r>0:Q=A(j-h,i-g);k,l=g+r*cos(Q),h+r*sin(Q);D=A(d-b,c-a);E=A(f-b,e-a);F=A(l-b,k-a);G=A(b-d,a-c);H=A(f-d,e-c);I=A(l-d,k-c);_=_ or(D<F<E or E<F<D)and(G<I<H or H<I<G);r-=.001
 return _

Slightly ungolfed, with comments:

from math import*
# Parameters:
#  (a,b) (c,d) (e,f) - vertices of the triangle
#  (g,h) - location of cannon
#  (i,j) - aim of cannon
#  R - range of cannon
# Variables within function:
#  _ - was this shot a hit?
#  r - distance 0 < r <= R that we're testing
#  Q - angle between cannon source and destination
#  (k,l) - point that we're testing
#  D,E,F - angles between point 1 and 2,3,test
#  G,H,I - angles between point 2 and 1,3,test
def h(a,b,c,d,e,f,g,h,i,j,R):
    r=R;_=0
    while r>0:
        Q=atan2(j-h,i-g)
        k,l=g+r*cos(Q),h+r*sin(Q)
        D=atan2(d-b,c-a)
        E=atan2(f-b,e-a)
        F=atan2(l-b,k-a)
        G=atan2(b-d,a-c)
        H=atan2(f-d,e-c)
        I=atan2(l-d,k-c)
        _=_ or(D<F<E or E<F<D)and(G<I<H or H<I<G)
        r-=.001
    return _

How it works:

Calculate the endpoint of the shot.
Test lots of points along the line from the endpoint to the cannon's location:

Calculate angles from vertex 1 to other two vertices and to test point;
Calculate angles from vertex 2 to other two vertices and to test point;
If the test point angle is between the other two angles, in both cases, then the test point is within the triangle and the ship has been hit.

Sample runs:

>>> h(0,0,0,1,1,0,1,1,0,0,2)
True
>>> h(0,0,1,2,3,0,-4,0,0,0,8)
False
>>> h(0,0,-1,3,4,-1,-3,-4,3,4,5)
False
>>> h(-2,-3,-3,6,7,-2,-6,2,1,-4,7)
True


Surrounded and reversed The task

In this challenge, your task is to determine whether some string occurs as a substring of a given string both surrounded by another string and reversed.

Your input is a non-empty string S of lowercase ASCII letters.
If there exist non-empty strings A and B such that the concatenation ABA and the reversal rev(B) are both contiguous substrings of S, then your output shall be a truthy value.
Otherwise, your output shall be a falsy value.
The two substrings may occur in any order, and they can even overlap.
However, it can be shown that in all truthy cases, you can either find non-overlapping substrings or a solution where B is a palindrome.

Example

Consider the input string S = zyxuxyzxuyx.
We choose A = xu and B = xyz, and then we can find the following substrings:

S      = zyxuxyzxuyx
ABA    =   xuxyzxu
rev(B) = zyx

The choice A = x and B = u would also be valid.
The correct output in this case is truthy.

Rules and scoring

You can write a full program or a function.
Standard loopholes are disallowed.
The lowest byte count wins.

Test cases

Truthy

sds
aaxyxaa
aaxyaaayx
hgygjgyygj
zyxuxyzxuyx
cgagciicgxcciac
iecgiieagcigaci
oilonnsilasionloiaammialn
abbccdeeaabccddbaacdbbaccdbaaeeccddb

Falsy

a
aaxyaa
jjygjhhyghj
abcaabbccaabca
egaacxiagxcaigx
lnsiiosilnmosaioollnoailm
cabbccabdcaddccabbddcaabbdcaddccaadcabbccaabbcadcc

Fun fact

One can construct arbitrarily long falsy strings using four distinct letters, but not using three letters.
The fourth falsy test case is the longest possible.

Brachylog, 13 bytes

s↔B&sA,B,A~s?

Try it online!

How it works

s↔B&sA,B,A~s?
s              the input has substring temp
 ↔B            temp reversed is B
   &           and the input
    sA         has substring A
      ,B,A     A,B,A
          ~s?  is a substring of input


Four distinct 8-bit integers Submit a well-formed program or function with usual I/O rules which satisfy the input, output, and algorithm conditions below. Shortest submission (in bytes) wins. As always, standard loopholes are forbidden.

In short: Two distinct 8-bit integer inputs must produce two 8-bit integer outputs so that all four numbers are distinct, i.e., not equal.

Input Conditions

Two distinct 8-bit integers, a and b, both of which are in 8-bit signed (or unsigned at your discretion) format.

Output Conditions

Two 8-bit integers, c and d, which are in the same format as the input (signed or unsigned), such  that a, b, c, and d are distinct, i.e., no two of them are equal to each other.

Algorithm Conditions

The algorithm must halt for all possible valid inputs.

Valid inputs are those where a and b are distinct. When a and b are equal, the behaviour of the algorithm is unspecified.

The algorithm must be deterministic.

Running the algorithm with the same input must produce the same output.

The algorithm must satisfy the output conditions for all valid inputs.

Verification

There are two ways to verify your algorithm.

Brute force: explicitly check the program for all valid input combinations.
Prove/show, by analysis, that a clash is impossible (preferred).

FAQ

What if my programming language doesn't provide 8-bit integers?
What if my programming language doesn't support fixed-width integers?

Only the range of the outputs matter; internal computations may be in any precision.  If the outputs can be rounded/scaled to the required integral range, then the programming language is good to go.

Edits

Edit 1: Thank you for the submissions! I am glad to see so many creative solutions! Initially, I planned to restrict the algorithm to one-to-one mapping (i.e., invertible), however, decided against it to make the problem simpler. Looking at the enthusiastic response, I will consider submitting a second code golf with the one-to-one mapping requirement.

JavaScript (Node.js), 35 31 27 23 bytes

-4 bytes thanks to Arnauld and Kevin Cruijssen

-4 bytes thanks to xnor

a=>b=>[c=3^a&1^b&2,c^4]

Try it online!

Explanation:

Takes the flipped 1 bit of the first number, and adds the flipped 2 bit of the second number, guaranteeing a number different from both inputs in the 2 least significant bits. Outputs this number, and 4 added to this number


Heaviest increasing subsequence A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. A strictly increasing subsequence is a subsequence in which every element is bigger than the preceding one.

The heaviest increasing subsequence of a sequence is the strictly increasing subsequence that has the biggest element sum.

Implement a program or function in your language of choice that finds the element sum of the heaviest increasing subsequence of a given list of non-negative integers.

Examples:

                    [] ->  0 ([])
                   [3] ->  3 ([3])
             [3, 2, 1] ->  3 ([3])
          [3, 2, 5, 6] -> 14 ([3, 5, 6])
       [9, 3, 2, 1, 4] ->  9 ([9])
       [3, 4, 1, 4, 1] ->  7 ([3, 4])
       [9, 1, 2, 3, 4] -> 10 ([1, 2, 3, 4])
       [1, 2, 4, 3, 4] -> 10 ([1, 2, 3, 4])
[9, 1, 2, 3, 4, 5, 10] -> 25 ([1, 2, 3, 4, 5, 10])
       [3, 2, 1, 2, 3] ->  6 ([1, 2, 3])

Note that you only have to give the element sum of the heaviest increasing subsequence, not the subsequence itself.

The asymptotically fastest code wins, with smaller code size in bytes as a tiebreaker.

Python, O(n log n)

I didn't golf this, because I'm competing primarily on the fastest code side of things. My solution is the heaviest_subseq function, and a test harness is also included at the bottom.

import bisect
import blist

def heaviest_subseq(in_list):
    best_subseq = blist.blist([(0, 0)])
    for new_elem in in_list:

        insert_loc = bisect.bisect_left(best_subseq, (new_elem, 0))

        best_pred_subseq_val = best_subseq[insert_loc - 1][1]

        new_subseq_val = new_elem + best_pred_subseq_val

        list_len = len(best_subseq)
        num_deleted = 0

        while (num_deleted + insert_loc < list_len
               and best_subseq[insert_loc][1] <= new_subseq_val):
            del best_subseq[insert_loc]
            num_deleted += 1

        best_subseq.insert(insert_loc, (new_elem, new_subseq_val))

    return max(val for key, val in best_subseq)

tests = [eval(line) for line in """[]
[3]
[3, 2, 1]
[3, 2, 5, 6]
[9, 3, 2, 1, 4]
[3, 4, 1, 4, 1]
[9, 1, 2, 3, 4]
[1, 2, 4, 3, 4]
[9, 1, 2, 3, 4, 5, 10]
[3, 2, 1, 2, 3]""".split('\n')]

for test in tests:
    print(test, heaviest_subseq(test))

Runtime analysis:

Each element has its insertion position looked up once, is inserted once, and is possibly deleted once, in addition to a constant number of value lookups per loop. Since I am using the built-in bisect package and the blist package, each of those operations are O(log n). Thus, the overall runtime is O(n log n).

The program works by maintaining a sorted list of best possible increasing subsequences, represented as a tuple of ending value and sequence sum. An increasing subsequence is in that list if there are no other subsequences found so far whose ending value is smaller and sum is at least as large. These are maintained in increasing order of ending value, and necessarily also in increasing order of sum. This property is maintained by checking the successor of each newly found subsequence, and deleting it if its sum is not large enough, and repeating until a subsequence with a larger sum is reached, or the end of the list is reached.


There are two new sheriffs in town – Identifying DJMcMego pairs! We have some new sheriffs moderators in town, Mego and DJMcMayhem. We need a challenge to properly honour them for their new positions, so there we go.

Here's something that has caught my attention when hovering over their profiles –  their user IDs are \$31716\$ and \$45941\$. If you perform digit-wise subtraction, you'll notice something pretty exciting (of course, taking the absolute differences):

3|1|7|1|6
4|5|9|4|1
-+-+-+-+- (-)
1|4|2|3|5

The number generated by the above algorithm is \$14235\$. There is something special about this integer: It consists of consecutive digits only, sorted in  ascending order, but exactly one of the digits is not placed correctly — \$4\$.

We will call a pair of positive integers \$(a, b)\$ a DJMcMego pair if the digit-wise absolute differences are consecutive integers, sorted in ascending order, but exactly one of them is not where it belongs. That is, it is possible to move exactly one digit of the result of digit-wise subtraction to another position, such that the integer obtained only has consecutive digits, sorted in ascending order.

In our example above, the pair \$(31716, 45941)\$ is a DJMcMego pair, because if \$4\$ is moved between \$3\$ and \$5\$, the result is \$12345\$, which fulfils the criteria. Note that the digits of the resulting number do not need to start at \$1\$, they just ought to be consecutive. When one is unsure about what decision they should make, they can always rely on the other's help to sort things out.

Your task is to output a truthy/falsy value depending on whether a pair of positive integers given as input is a DJMcMego pair.

You are guaranteed that \$a\$ and \$b\$ will have the same number of digits, always at least 4.
You can take the integers in any reasonable format (i.e. native integers, strings, lists of digits, etc.)
You can compete in any programming language and can take input and provide output through any standard method, while taking note that these loopholes are forbidden by default. This is code-golf, so the shortest submission (in bytes) for every language wins.

Test cases

a, b -> Output

31716, 45941 -> Truthy
12354, 11111 -> Truthy
56798, 22222 -> Truthy
23564, 11111 -> Truthy
1759,  2435  -> Truthy
12345, 11111 -> Falsy
3333,  2101  -> Falsy
22354, 22222 -> Falsy
31717, 45941 -> Falsy
14325, 11111 -> Falsy
89789, 78865 -> Falsy
14954, 61713 -> Falsy
25631, 11114 -> Falsy

Or, in another format.

C (gcc), 259 258 254 253 250 248 233 222 bytes

Thanks to Stan Strum for inspring a one byte golf.
Saved four bytes by juggling some variable initializations.
Saved a byte by golfing for(...;l++)b*=B[l]==-~B[l-1]; to for(...;b*=B[l]==-~B[~-l++]); (most likely relying on undefined behaviour, as it requires first evaluating B[l] followed by -~B[~-l++]).
Saved three five bytes.
Saved fifteen twenty-six bytes thanks to ceilingcat.

j,k,l,L,r,b;f(char*A,char*B){for(j=r=0;k=A[L=j];)A[j++]=-~abs(A[j]-B[j]);for(;k-L;k++)for(j=~0;L-++j;r|=!b)if(k-j)for(bcopy(B-~l,strcpy(B,A)+l,strlen(A+l)),bcopy(B+j,B-~j,L+~j),B[j]=A[k],l=b=0;B[++l];b|=B[l]+~B[~-l]);A=r;}

Try it online!

Explanation (248 byte version)

j,k,l,L,r,b;                            // global variables
f(char*A,char*B){                       // function takes two strings
 for(j=r=0;A[j];L=j)                    // loop through A, compute array length L
  A[j++]=-~abs(A[j]-B[j]);              // set every entry in A to the absolute
                                        // difference of A and B at that position
                                        /* Test out all possible movements of        *
                                         * characters and see if any one             *
                                         * results in a sorted list => DJMcMego pair */
 for(j=0;j-L;j++)                       // loop through array
  for(k=~0;L-++k;r|=!b)                 // loop through array
   if(j-k){                             // j is not equal to k
    for(l=0;A[l];B[l++]=A[l]);          // copy A to B
    for(l=j;A[l];B[~-l]=B[++l]);        // shift part of B
    for(l=L;l-k;B[-~l]=B[--l]);         // shift part of B
    B[k]=A[j];                          // insert character at correct position
    for(l=b=0;B[++l];b|=B[l]+~B[~-l]);} // test if B is sorted
 A=r;}                                  // return if there was a DJMcMego pair found

Try it online!


A Geometrical Challenge Everybody loves geometry.  So why don't we try and code golf it?  This challenge involves taking in letters and numbers and making shapes depending on it.
The Input
The input will be in the form of (shapeIdentifier)(size)(inverter).
But what are shapeIdentifier, size, and inverter?
The shape identifier is the identifier for the type of shape you will be making with *s.  The following are the shape identifiers:

s - Square
t - Triangle

The size will be between 1-20, and it is the size of the figure.
The inverter is whether or not the shape will be upside down, which is denoted by a + or a -.  Do note:  s3- == (equals) s3+ because squares are symmetric.  However, t5- != (does not equal) t5+.
Trailing whitespace is okay in the output but leading whitespace is not.
Output Examples
Input: s3+
Output:
***
***
***

Input: t5+

Output:
  *
 ***
*****

Input: t3-
Output:
***
 *

Special Notes
The triangle input will always be an odd number, so the triangles will always end with 1 * at the top.

The size of the triangle is the size of the base if the inverter is
+ and is the size of the top if the inverter is -.

Pyth, 40 36 34 32 bytes
-1 byte by @isaacg
JstPz_W}\+zjl#m.[J*\*-J*}\tzyd;J

A semicolon inside a lambda is now the lambda variable's global value, a feature that saves one byte.
                         Implicit: z = input
JstPz                    J = size.
_W }\+z                  Reverse if "+" in z
j l# m                J  Join the nonempty lines in map lambda d:... over range(J)
      .[J            ;   Pad the following with spaces (;) to length J
         *\*               "*", this many times:
            -J*}\tzyd        J if "t" not  in z,
                             otherwise the correct number for a triangle.

Try it here.
Test suite.


Calculate ELO Rating Expected Score Your task is to calculate the expected chance of winning for 2 players in some game, each with their own ELO Rating. Player A has ELO Ra and player B has ELO Rb

The expected score for Player A (Ea) is: 1 / (1 + 10(Rb - Ra) / 400). There is a similar equation for Player B (Eb): 1 / (1 + 10(Ra - Rb) / 400).

If you want a more copiable version: 1 / (1 + 10^((a-b) / 400))

Ea + Eb should be equal to 1.

Therefore, the score for a player is their expected chance of winning some match, in decimal.

Your program/function should take 2 inputs, Player A's ELO, and Player B's ELO, and print/return their respective chance to win in decimal format. The output must add up to one, and you must be accurate to at least 5 decimal places (0.00000). After 5 decimal places, you may have inaccurate digits, provided the two outputs still add up to one.

Examples:

1200 2100 -> 0.005591967 0.994408033
1 1 -> 0.5 0.5
60 20 -> 0.557312 0.442688
9999 9998 -> 0.501439 0.498561
9999 1 -> 0.999999 0.000001

In the final test case, some answers use scientific exponentiation to represent the value. This is not valid.

You can see in test case 3 here that 0.557312 is not quite accurate, because the 2 should be a 1, but this is fine because it is after five decimal places and the outputs still add up to one.

This is an example of invalid output:

9999 9998 -> 0.5014391117091516, 0.49856088829084844

This looks like it satisfies the requirements at first glance, but the numbers add up to 1.00000000000000004 and therefore the output is not valid.

Trailing zeroes in the output is fine.

You may assume a player's ELO will always be greater than 0, and nobody will have an ELO higher than 9999.

The input and output format is flexible, but the input and output must still be in base 10.

As this is code-golf, the answer with the lowest byte count will win!

Jelly, 9 bytes

÷400⁵*÷S$

Try it online! or View all test cases.

The input is an array [Ra, Rb] and the output is an array [Ea, Eb].

Explanation

÷400⁵*÷S$  Input: array [Ra, Rb]
÷400       Divide each by 400, makes [Ra/400, Rb/400]
    ⁵*     Raise 10 to that power, makes [10^(Ra/400), 10^(Rb/400)]
        $  Monadic chain operating on previous result
      ÷      Divide each by
       S     The sum of the whole
           Makes [10^(Ra/400)/(10^(Ra/400) + 10^(Rb/400)),
                  10^(Rb/400)/(10^(Ra/400) + 10^(Rb/400))]
               = [1/(1 + 10^((Rb-Ra)/400)), 1/(1 + 10^((Ra-Rb)/400))]


Be there or be square! Everybody has heard of the phrase "be there or be square". So I thought it was time for a challenge about it.

Input

You will take a full absolute directory address as text as input via STDIN or equivalent.

Output

If the directory address exists and is valid, your program will move itself to that folder on your computer. If not, it will output via STDOUT or equivalent the following square:

+-+
| |
+-+

Requirements

Standard loopholes are disallowed.
You may output a single trailing newline if unavoidable.
Your program must produce no output if it has been moved.
Your program must be able to run again wherever it has been moved to.

Assumptions

You may assume that the input is never empty.
You may assume the directory never has a filename appended to the end.
You may assume that the input directory is never the current one.
You may assume you have permissions to write and execute everywhere.

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

PowerShell, 59 62 61 60 bytes

$z=ls($d=$args)-di;('"+-+
| |
+-+"','mv b.ps1 "$d"')[$?]|iex

Try it online!

Explanation

PowerShell's Move-Item cmdlet (mv) renames a file as well, so giving it a directory that doesn't exist as the destination just renames the file to that last component instead (as long as the parent exists), so that was no good.

I could use Test-Path to determine that the destination exists and is a directory, but it's too long Test-Path $d -PathT C.

So instead I'm using Get-ChildItem (ls) with the (shortened) -Directory parameter, and checking $? to see if it was successful. The output if there is any is assigned to $z so that it isn't seen.

That's done in the form of an array with 2 elements, then indexing into the array with the boolean value of $?, which will get coalesced to 0 or 1, so the first array element is chosen if the destination directory doesn't exist, and second if it does.

The first array element is a string containing the box (quoted); newlines are allowed in strings, even when they're not heredocs. The second element is a string containing the move command.

The result of that array selection gets piped into Invoke-Expression (iex) to be executed. This is necessary because of I just leave the actual move command in the array, it gets executed no matter what (to populate the array), which defeats the purpose.


Remove more than n consecutive vowels from input string I don't like strings with more than three vowels in a row. Can you write a program that removes all the vowels I don't want from words?

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

Input is a string containing only printable ASCII character (0x20 to 0x7E, inclusive).

Output is a string containing only runs of at most 3 consecutive vowels. If there is a run of more than 3 consecutive vowels in the input string, your program should produce an output string including the first three vowels encountered in that run, discarding any further consecutive vowels.

Y is not a vowel for the purposes of this challenge.

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

Test Cases

"Aeiou" => "Aei"
"screeeen" => "screeen"
"We're queueing up for the Hawaiian movie." => "We're queung up for the Hawaiin movie."
"Spaces break runs: aei iou." => "Spaces break runs: aei iou."


Program that permutes itself to encode a string (quine-variant) Write a program that prints the following 80-character line:

  This program from codegolf.stackexchange.com permutes itself to encode a string.

then accepts one line of input, then prints its source code with its code points possibly reordered (none added and none deleted). When that code is executed, the same has to happen, except the printed line would be the most recent line of input.

The Perl-style regex ^[A-Za-z0-9. ]{80}$ will match any line of input. You cannot make any additional assumption.

A submission's score is the number of code points in its source code less 94. Lower is better.

The code must not do anything that would be unacceptable in a quine (e.g. file reading). In particular, any submission with a negative score must be cheating somehow, as 93! is less than 6480.

Added 2014-04-21: Your program's entire source code must be well-formed in the character encoding under which you count code points. For example, you cannot use 80 consecutive bytes in the UTF-8 trailing byte range (80..BF) and count each as a single U+FFFD REPLACEMENT CHARACTER (or worse, as not a code point at all).

Additionally, if the encoding allows multiple ways to encode a code point (e.g. SCSU), your program, as well as all programs it directly or indirectly generates, must only use one of them (or at least all must be treated equivalently throughout the code).

GolfScript, 231 162 131

'1àâ4ÿaVo5GùpZBtiXOürsóNîMmWåKHc09JdñúêyzíECäYïhDU ãáIFõ6é8òRìjTv23ønuðLwxfSkôbëAelqý.çèPQ
öûg7'{0@.$[{}/]:&\{@2$,*2$2$?+@@^}/{;65base}:b~{&=}%''+puts'"#{`head -1`}"'~{&?}%)b[94,{)1$1$%@@/}/;]-1%&\[{1$=.@^}/]"'".@+\+\'.~'}.~

How it works

We start by choosing 94 different characters that will get permuted to encode a string. Any 94 characters would work, but we choose the following for golfing purposes:

\n .0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
àáâãäåçèéêëìíîïðñòóôõöøùúûüýÿ

Let's call the array of these characters “&”.

The line of input will always contain 81 characters (including the LF). All of those characters are present in the first 65 characters of “&”. This is the sole reason for choosing characters in the upper 128 bytes.

We replace each character of the string by its index in “&”, so LF becomes 0, space becomes 1, etc.

We consider the 81 obtained numbers the digits of a single base 65 number. Let's call this number “N”.

Now, we enumerate all possible permutations of “&” and retrieve the permutation corresponding to the number from above. This is achieved in the following manner:

Set c = 1 and A = [].
Prepend N % c to A.
Set N = N / c and c = c + 1.
If c < 95, go back to 2.
Set i = 0 and s = "".
Retrieve the charcter &[A[i]], append it to “s” and remove it from “&”.
Set i = i + 1.
If i < 94 go back to 6.

Suppose we have code blocks “E” and “D” that encode and decode a string as explained above.

Now, we need a wrapper for those code blocks that complies with the requirements of the question:

'encoded string'{\.$[{}/]:&; D puts '"#{`head -1`}"'~ E "'".@+\+\'.~'}.~

This does the following:

{…}.~ defines a block, duplicates it and executes the second copy. The first copy will remain on the stack.
\.$ swaps the encoded string with the block and creates a copy of the encoded string, with sorted characters.
[{}/]:&; converts the string from above into an array, saves it in “&” and discards it.
D puts decodes the encoded string and prints the result.
'"#{`head -1`}"'~ reads one line of input by executing head -1 in the shell.
E "'".@+\+ encodes the string and prepends and appends a single quote.
\'.~' swaps the encoded string and the block and appends the string '.~'.
After the block has been executed, GolfScript prints the contents of the stack (encoded string, block, '.~') and exits.

“E” can be defined as follows:

{&?}%        # Replace each character by its index in “&”.
);           # Remove the last integer from the array, since it corresponds to the LF.
65base       # Convert the array to an integer “N” by considering it a base 65 number.
[            #
  94,        # For each integer “c” in 0 … 93:
  {          #
    )        # Increment “c”.
    1$1$%    # Push “N % c”.
    @@/      # Rotate “N % c” below “N” and “c” and divide the first by the latter.
  }/;        # Discard “N”.
]            # Collect the results of “N % c” in an array “A”.
-1%          # Reverse “A”.
&\           # Push “&” and swap it with “A”.
[            #
  {          # For each “j” in “A”:
    1$=.[]+  # Push “&[j] [&[j]]”.
    @^       # Rotate “&” on top of “[&[j]]” and take their symmetric difference.
  }/         #
]            # Collect the charcters into an array.

“D” can be defined as follows:

0&           # Push 0 (initial value of the accumulator “A”) and “&”.
@            # Rotate the encoded string on top of “&”.
{            # For each character “c” of the encoded string:
    @2$,*    # Rotate “A” on top of the stack and multiply it by the length of “&”.
    2$2$?+   # Get the index of “c” in “&” and add it to “A”.
    @@^      # Rotate “A” below “&” and “c” and take their symmetric difference.
}/;          # Discard “&”.
65base       # Convert “A” into the array of its digits in base 65.
{&=}%        # Replace each digit by the corresponding character in “&”.
''+          # Convert the resulting array into a string.

Final golfing:

Replace \.$[{}/]:&;0&@ with 0@.$[{}/]:&\ to save two characters.
Define the function {;65base}:b to save one character.
Remove all whitespace except the trailing LF and the LF in the string.

Example

$ # Create GolfScript file using base64 to avoid encoding issues.
$ base64 > permute.gs -d <<< JzHg4jT/YVZvNUf5cFpCdGlYT/xyc/NO7k1tV+VLSGMwOUpk8frqeXrtRUPkWe9oRFUg4+FJRvU26TjyUuxqVHYyM/hudfBMd3hmU2v0YutBZWxx/S7n6FBRCvb7ZzcnezBALiRbe30vXTomXHtAMiQsKjIkMiQ/K0BAXn0vezs2NWJhc2V9OmJ+eyY9fSUnJytwdXRzJyIje2BoZWFkIC0xYH0iJ357Jj99JSliWzk0LHspMSQxJCVAQC99LztdLTElJlxbezEkPS5AXn0vXSInIi5AK1wrXCcufid9Ln4K
$
$ # Set locale to en_US (or any other where one character is one byte).
$ LANG=en_US
$
$ # Go back and forth between two different strings.
$ # Second and sixth line are user input, not output from the script.
$
$ golfscript permute.gs | tee >(tail -n+2 > tmp.gs) && golfscript tmp.gs && rm tmp.gs
This program from codegolf.stackexchange.com permutes itself to encode a string.
Permuting source code code points to encode a string is a certain quine variant.
'18äJoS3sgV9qdçëxm0ÿKMNe5íPî.Htn2ciâIuøbRZéð4AwB7áìUüöôWõèûfñåLàóDrhQlO6
pTaýzòkùYCyFêïãG júEvX'{0@.$[{}/]:&\{@2$,*2$2$?+@@^}/{;65base}:b~{&=}%''+puts'"#{`head -1`}"'~{&?}%)b[94,{)1$1$%@@/}/;]-1%&\[{1$=.@^}/]"'".@+\+\'.~'}.~
Permuting source code code points to encode a string is a certain quine variant.
This program from codegolf.stackexchange.com permutes itself to encode a string.
'1àâ4ÿaVo5GùpZBtiXOürsóNîMmWåKHc09JdñúêyzíECäYïhDU ãáIFõ6é8òRìjTv23ønuðLwxfSkôbëAelqý.çèPQ
öûg7'{0@.$[{}/]:&\{@2$,*2$2$?+@@^}/{;65base}:b~{&=}%''+puts'"#{`head -1`}"'~{&?}%)b[94,{)1$1$%@@/}/;]-1%&\[{1$=.@^}/]"'".@+\+\'.~'}.~
$
$ # Sort all characters from the original source code and hash them.
$ fold -1 permute.gs | sort | md5sum
b5d978c81df5354fcda8662cf89a9784  -
$
$ # Sort all characters from the second output (modified source code) and hash them.
$ golfscript permute.gs | tail -n+2 | fold -1 | sort | md5sum
Permuting source code code points to encode a string is a certain quine variant.
b5d978c81df5354fcda8662cf89a9784  -
$
$ # The hashes match, so the characters of the modified source code are a permutation
$ # of the character of the original one.


Score a Game of Boggle Background
In Boggle, a round is scored by adding up the points for each unique word a player has found (i.e. any word that more than one player has found is worth 0 points). The points are calculated based on the number of letters in each word, as follows:
3 letters: 1 point
4 letters: 1 point
5 letters: 2 points
6 letters: 3 points
7 letters: 5 points
8 or more letters: 11 points
Challenge
In this challenge, write a program or function that takes in a list of lists of strings representing each player's words and outputs a list of the players' scores. You can assume that there will be at least 2 players and all words will be 3 or more letters and will all be lowercase (or all uppercase if you would prefer). You may also assume that each player will only use each word once; that is, no player's list will contain duplicates. This is code golf, so shortest answer in bytes wins.
Rules
Input can be taken in any reasonable format. Examples include a list of lists of strings, a list of comma-separated strings, a comma separated string on each line of input, etc. Output can be in the form of a list of integers (or your language's equivalent) or you can print the values to stdout using a separator of your choice (such as a newline).
Test Cases
Input => Output
[["cat","dog","bird","elephant"],
 ["bird","dog","coyote"],
 ["dog","mouse"]]                 => [12,3,2]

[["abc","def","ghi"],
 ["ghi","def","abc"]]             => [0,0]

[["programming","puzzles"],
 ["code","golf"],
 []]                              => [16,2,0]

Husk, 21 20 19 bytes
-2 bytes thanks to Zgarb
Idea taken from A055228
ṠṀöṁ(⌈√Π-3▼8L)fε`#Σ

Try it online!
Explanation (Of older version)
            ṠṀ-oṠ-uΣ   Remove duplicated words
                   Σ   Concatenate
                  u    Remove duplicates
               oṠ-     Remove those unique elements from the list (give list of elements that appear more than once)
            ṠṀ-        Remove those words from each list in the input
m                      For each list
 ṁ(                    Map then sum
          L)           Length
        ▼8             Min(8,x)
      -3               Minus 3
     Π                 Factorial
    √                  Square root
   ⌈                   Ceiling


Code words in integer sequences Introduction

Pareidolia: From Ancient Greek; παρα (para, “concurrent, alongside”) + εἴδωλον (eídōlon, “image”). The tendency to interpret a vague stimulus as something known to the observer, such as interpreting marks on Mars as canals, seeing shapes in clouds, or hearing hidden messages in music. Source: Wiktionary.

For example:

Paralogia: From Ancient Greek; παρα (para, “concurrent, alongside”) + λόγος (lógos, “speech, oration, word, ...”). The tendency to perceive words in arbitrary sequences of characters, such as in code golf programs. Source: yeah, I made that up (actually the word means something else, as pointed out by @Martin).

For example:

    df4$/H)hEy_^p2\
    jtK2$)look|x1$

Challenge

Write a program that takes a positive integer as input, produces an integer as output, and includes an English word as part of the code. The input-output relationship must correspond to an integer sequence that can be found in OEIS.

Rules

Only words from this list are allowed. This is admittedly arbitrary, but it's essential that we all agree on which words are accepted; and in that regard this list is probably as good as any other.
Words need to be formed by concatenating at least two function names or statements. If your language for example has a function called correlation it can't be used as is. The concatenation has to be strict: no other symbols should appear between the parts of the word. For example, bro~ken would not count as a word.
Case is unimportant: both valid and vaLiDare acceptable.
Words within strings do not count. The letters that make up the word need to be functions or statements in the language of choice, that is, something that is actually executed. For example, the following code would not be allowed: 'deoxyribonucleic'~1, where '...' is a string, ~ discards the previous content, and 1 just prints number 1.
Every letter of the word should be necessary. This means that removing a single letter from the word should change the input-output relation. That includes outputting a different sequence, or outputting any other thing(s), or producing no output, or causing an error.
Any positive integer should be acceptable as an input, and should produce an output, except for data-type or memory restrictions.
The outputs corresponding to inputs 1, 2, 3, ... should correspond to a sequence appearing in OEIS. No other output should be produced; only an integer number, possibly with trailing or leading whitespace.
Input and output can be function arguments or stdin/stdout.

Score

The score is computed as total code length minus twice the length of the longest word, in characters. Or equivalently, number of not-in-longest-word characters minus length of longest word.

Lowest score wins.

Examples

Consider an imaginary postfix language that has these functions: c: input a number; At: compute square; $: add 1.

cAt would be a valid program (its output corresponds to the sequence 1, 4, 9, ..., which is A000290), and it would have score −3.

cAt$ would also be valid (sequence 2, 5, 10, ..., which is A002522), with score −2.

c$At would not be valid, because the only word here is "At" and is produced by a single function or statement.

CJam, -20
COUNTErREVOLUTIONARIES],

Outputs the nth element in the sequence A010861.
COUNTE                      e# push values of six preinitialized variables
      r                     e# read a token of input
       REVOLUTIONARIES      e# push values of 15 other preinitialized variables
                      ]     e# wrap whole stack in array
                       ,    e# get length

Removing a character from the word results in a completely different sequence A010860. There is a quite interesting relationship between the two sequences: at every index n, A010860(n) is coprime to A010861(n)! There must be some deep mathematical reason behind this.
Try it here.


Create a "hacker typer" program that renders its own source code If you are unfamiliar with hacker typer, see hackertyper.net. In short, it is a program that outputs one chunk of a code base per keystroke for comedic effect. BUT, the hackertyper.net version is far too easy to implement. It simply outputs three characters at a time from an arbitrary piece of code. For this challenge, a program must output its own source code, and print one space delimited chunk of code per keystroke.
Details

One cannot hard code a file name for the program; it must determine its name dynamically. If the program compiles to an executable, it may append the standard file extension to the name of the executable (excluding the .exe if using Windows) and assume that the source file is within the executable's directory. For example, if a C executable is named "hacker", it should pull its source code from a file named "hacker.c" in its same directory. If a compiled program has an extension, it should be dropped before determining the name of its source code ("typer.exe" -> "typer.cs").
Programs must contain at least 5 spaces, with at least one character between each space. This means that the smallest possible size for this challenge is 9 bytes. The spaces do not have to be crucial to the functioning of the program.
Any formatting (indentation, new lines, etc.) must be maintained in the output. This formatting may either be printed with the code that proceeds it or follows it, what matters is that the formatting be maintained.
Avoid using comments to satisfy the 5 space requirement unless there is no other way to implement the spaces in your language of choice.

EDIT: New lines can be used in place of, or in addition to, spaces as chunk separators.

HTML & JavaScript, 123

This works similarly to hacker typer, but with its own source code. Let me know if I've misunderstood the rules.

And here's a styled version (170 characters):

I've made a demo. It's modified because JS Bin adds a lot of extra code, but the general idea is the same.


quine-ish tic-tac-toe Write a program in your chosen language which plays a perfect game of tic-tac-toe on a 3 * 3 board against a human player. However, every move has to be a different program, generated from the previous iteration.

How and in what form you evaluate human input, is up to you, but it has to be read from the standard input. Similarly, you are free to choose a method how you will determine which player starts (for example, you ask first, or you allow the human to enter an invalid move to signal that the computer starts, or other ideas).

Validating moves is not necessary, you can assume a fairly playing human opponent.

Basically, you have program which corresponds to a state of the board. The state is printed in any recognizable way, but at least the following level of detail is expected:

X..
00X
x..

After the human player entered his moves, your program has to generate the next iteration of itself as a source file in the same language (either to standard output or to a file) and terminate. You are not allowed to store information anywhere else outside of that source file. (it is not necessary for your program to build and run the generated program, it can be done by the user - however, it's not forbidden). When the generated program is built and run, it will behave similarly, display the state, wait for user input, etc.

At the end of the game, you have to print the result (whether you won or it's a tie) in any unambiguously identifiable way.

By perfect play I mean the program must not lose, and if there is a possibility to force a win, it should win.

Shortest code wins, winner is selected at least 10 days after the first valid entry.

You get a 10% reduction in the score if your program can handle the building and launching of its next iteration. (I know, it's most probably not worth it) Of course, the program itself must be terminated by the time the next iteration accepts the moves from the user.

If you use some strange uncommon tricks, please post a short explanation with your code.

Perl, 933 characters

$m=<<'';$_='         ';
sub h{/^(?:...)*(\d)\1\1/|/^.?.?(\d)..\1..\1/|/(\d)...\1...\1/|/^..(\d).\1.\1/&&$1}
sub r{substr($_,$p-1,1)=pop}sub p{my$w=pop;my@b=(0,h==$w||h&&-1);if(!$b[1]&&/ /){$b[1]=-9;
while(/ /g){local($_,$p)=($_,pos);r$w;$r=-(p($w^1))[1];@b=($p,$r)if$r>$b[1]}}@b}
if(($w=h||!/ /)||!@ARGV){$w--&&print+(nobody,X,O)[$w]," wins\n";s/(...)/$1\n/g;
tr/ 23/.XO/;print}else{$w=3;$w^=1for/\d/g;($p=pop)?r($w^1)&&!h&&(($p)=p$w)&&r$w:s/ /2/;
print"\$m=<<'';\$_='$_';\n$m\n$m"}

sub h{/^(?:...)*(\d)\1\1/|/^.?.?(\d)..\1..\1/|/(\d)...\1...\1/|/^..(\d).\1.\1/&&$1}
sub r{substr($_,$p-1,1)=pop}sub p{my$w=pop;my@b=(0,h==$w||h&&-1);if(!$b[1]&&/ /){$b[1]=-9;
while(/ /g){local($_,$p)=($_,pos);r$w;$r=-(p($w^1))[1];@b=($p,$r)if$r>$b[1]}}@b}
if(($w=h||!/ /)||!@ARGV){$w--&&print+(nobody,X,O)[$w]," wins\n";s/(...)/$1\n/g;
tr/ 23/.XO/;print}else{$w=3;$w^=1for/\d/g;($p=pop)?r($w^1)&&!h&&(($p)=p$w)&&r$w:s/ /2/;
print"\$m=<<'';\$_='$_';\n$m\n$m"}

Please note that the blank line in the middle of the script is actually required to be there. (The line breaks at the end of the long lines are not required, other than for legibility, and are not included in the character count.)

Usage: When the program is run without arguments, it displays the current game state. Since at the start the board is empty, the output will be:

...
...
...

Run the program with an argument between 1 and 9 to claim that square as your move. The program will make its own move and then output a replacement script with the new state. Thus, for example:

$ perl ./qttt 5 > ./qttt-2
$ perl ./qttt-2
O..
.X.
...

On the very first turn only, you may give a move of 0 to indicate that the computer should take the first move. Note that the first player will always be X.

When the game is over, the display output will include a note to that effect:

$ perl ./qttt-4 6 > ./qttt-5
$ perl ./qttt-5
O wins
OXX
OOX
X.O

The program works by doing a standard minimax search of the game tree. (Tic-tac-toe is a small enough game that a full game tree can be generated on every run.) The exception to this is when the computer moves first -- in this case the initial move to the upper left corner is hard-coded.

Note that this program works in the fashion of a proper quine -- at no point does the script access its own source file in order to produce its output.


Type the Alphabet - as fast as you can! Your task is to make a program that measures how fast you can type the letters of the English alphabet.

The program shall only accept lowercase letters a to z in alphabetical order.
Each letter is echoed as typed on the same line (without new line or any other separators between letters).
If you type an invalid character the program shall output Fail on a new line and exit.
If you type all 26 letters the program shall, on a new line, output the time in milliseconds it took from the first to the last letter and exit.
The timer starts when you type the first letter, a.

Example outputs:

b
Fail

abcdefgg
Fail

abcdefghijklmnopqrstuvwxyz
6440

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

HTML (JavaScript (ES6)), 129 126 117 bytes

<input id=i onfocus=l=0,n=Date.now onkeypress=event.which-97-l?i.outerHTML='Fail':24<l?i.outerHTML=n()-t:t=l++?t:n()>

Click in the input and start typing! Also, my typing sucks; I take about 5 seconds even with practice. Edit: Saved 2 bytes thanks to @HermanLauenstein by switching language. Saved 3 bytes thanks to @qw3n. Saved 9 bytes thanks to @tsh.


Digit sum of central binomial coefficients The task is simply to see how much faster you can calculate n choose n/2 (for even n) than the builtin function in python.  Of course for large n this is a rather large number so rather than output the whole number you should output the sum of the digits. For example, for n = 100000, the answer is 135702. For n=1000000 it is 1354815.

Here is the python code:

from scipy.misc import comb
def sum_digits(n):
   r = 0
   while n:
       r, n = r + n % 10, n / 10
   return r
sum_digits(comb(n,n/2,exact=True))

Your score is (highest n on your machine using your code)/(highest n on your machine using my code).  Your code must terminate in 60 seconds or less.

Your program must give the correct output for all even n: 2 <= n <= (your highest n)

You can't use any builtin code or libraries which calculate binomial coefficients or values which can quickly be transformed into binomial coefficients.

You can use any language of your choice.

Leading answer   The current leading answer with an amazing 680.09 is by justhalf.

C++ (GMP) - (287,000,000 / 422,000) = 680.09

Shamelessly combine Kummer's Theorem by xnor and GMP by qwr.
Still not even close to the Go solution, not sure why.

Edit: Thanks Keith Randall for the reminder that multiplication is faster if the number is similar in size. I implemented multi-level multiplication, similar to memory coalescing concept on memory management. And the result is impressive. What used to take 51s, now takes only 0.5s (i.e., 100-fold improvement!!)

OLD CODE (n=14,000,000)
Done sieving in 0.343s
Done calculating binom in 51.929s
Done summing in 0.901s
14000000: 18954729

real    0m53.194s
user    0m53.116s
sys 0m0.060s

NEW CODE (n=14,000,000)
Done sieving in 0.343s
Done calculating binom in 0.552s
Done summing in 0.902s
14000000: 18954729

real    0m1.804s
user    0m1.776s
sys 0m0.023s

The run for n=287,000,000

Done sieving in 4.211s
Done calculating binom in 17.934s
Done summing in 37.677s
287000000: 388788354

real    0m59.928s
user    0m58.759s
sys 0m1.116s

The code. Compile with -lgmp -lgmpxx -O3

#include <gmpxx.h>
#include <iostream>
#include <time.h>
#include <cstdio>

const int MAX=287000000;
const int PRIME_COUNT=15700000;

int primes[PRIME_COUNT], factors[PRIME_COUNT], count;
bool sieve[MAX];
int max_idx=0;

void run_sieve(){
    sieve[2] = true;
    primes[0] = 2;
    count = 1;
    for(int i=3; i<MAX; i+=2){
        sieve[i] = true;
    }
    for(int i=3; i<17000; i+=2){
        if(!sieve[i]) continue;
        for(int j = i*i; j<MAX; j+=i){
            sieve[j] = false;
        }
    }
    for(int i=3; i<MAX; i+=2){
        if(sieve[i]) primes[count++] = i;
    }
}

mpz_class sum_digits(mpz_class n){
    clock_t t = clock();
    char* str = mpz_get_str(NULL, 10, n.get_mpz_t());
    int result = 0;
    for(int i=0;str[i]>0;i++){
        result+=str[i]-48;
    }
    printf("Done summing in %.3fs\n", ((float)(clock()-t))/CLOCKS_PER_SEC);
    return result;
}

mpz_class nc2_fast(const mpz_class &x){
    clock_t t = clock();
    int prime;
    const unsigned int n = mpz_get_ui(x.get_mpz_t());
    const unsigned int n2 = n/2;
    unsigned int m;
    unsigned int digit;
    unsigned int carry=0;
    unsigned int carries=0;
    mpz_class result = 1;
    mpz_class prime_prods = 1;
    mpz_class tmp;
    mpz_class tmp_prods[32], tmp_prime_prods[32];
    for(int i=0; i<32; i++){
        tmp_prods[i] = (mpz_class)NULL;
        tmp_prime_prods[i] = (mpz_class)NULL;
    }
    for(int i=0; i< count; i++){
        prime = primes[i];
        carry=0;
        carries=0;
        if(prime > n) break;
        if(prime > n2){
            tmp = prime;
            for(int j=0; j<32; j++){
                if(tmp_prime_prods[j] == NULL){
                    tmp_prime_prods[j] = tmp;
                    break;
                } else {
                    mpz_mul(tmp.get_mpz_t(), tmp.get_mpz_t(), tmp_prime_prods[j].get_mpz_t());
                    tmp_prime_prods[j] = (mpz_class)NULL;
                }
            }
            continue;
        }
        m=n2;
        while(m>0){
            digit = m%prime;
            carry = (2*digit + carry >= prime) ? 1 : 0;
            carries += carry;
            m/=prime;
        }
        if(carries>0){
            tmp = 0;
            mpz_ui_pow_ui(tmp.get_mpz_t(), prime, carries);
            for(int j=0; j<32; j++){
                if(tmp_prods[j] == NULL){
                    tmp_prods[j] = tmp;
                    break;
                } else {
                    mpz_mul(tmp.get_mpz_t(), tmp.get_mpz_t(), tmp_prods[j].get_mpz_t());
                    tmp_prods[j] = (mpz_class)NULL;
                }
            }
        }
    }
    result = 1;
    prime_prods = 1;
    for(int j=0; j<32; j++){
        if(tmp_prods[j] != NULL){
            mpz_mul(result.get_mpz_t(), result.get_mpz_t(), tmp_prods[j].get_mpz_t());
        }
        if(tmp_prime_prods[j] != NULL){
            mpz_mul(prime_prods.get_mpz_t(), prime_prods.get_mpz_t(), tmp_prime_prods[j].get_mpz_t());
        }
    }
    mpz_mul(result.get_mpz_t(), result.get_mpz_t(), prime_prods.get_mpz_t());
    printf("Done calculating binom in %.3fs\n", ((float)(clock()-t))/CLOCKS_PER_SEC);
    return result;
}

int main(int argc, char* argv[]){
    const mpz_class n = atoi(argv[1]);
    clock_t t = clock();
    run_sieve();
    printf("Done sieving in %.3fs\n", ((float)(clock()-t))/CLOCKS_PER_SEC);
    std::cout << n << ": " << sum_digits(nc2_fast(n)) << std::endl;
    return 0;
}


Compute the uncomputable ... sort of Implement a function \$f\$ (as a function or complete program), such that
\$
\displaystyle\lim_{n\rightarrow \infty} f(n)
\$
converges to a number which is not a computable number.
Answers will be scored in bytes with fewer bytes being better.
IO formats
Your answer may be in any of the following formats

A program or function that takes \$n\$ as input and outputs \$f(n)\$.
A program or function that takes \$n\$ as input and outputs all \$f(m)\$ where \$m \leq n\$.
A program or function that outputs successive members of the sequence indefinitely.

Numeric output can be given as any of the following

An arbitrary precision rational type.
A pair of arbitrary precision integers representing a numerator and denominator. e.g. \$(2334, 888)\$
A string representing a rational expressed as a fraction. e.g. 2334/888
A string representing a rational expressed as a decimal expansion. e.g. 3.141592

Use of fixed precision floating point numbers is unfortunately not accepted. They end up being messy when dealing with limits, I hope the options permitted allow the majority of languages to compete in this challenge relatively unencumbered.
Neither of the fractional outputs are required to be in reduced form.
Examples
Here are some numbers which are not computable, but are computable in the limit.  That is any of the following numbers are potential limits for valid solutions to the challenge.  This list is obviously not exhaustive.

The real whose binary expansion encodes the halting problem.
The real whose binary expansion encodes the busy beaver numbers.
The real whose binary expansion encodes the truth set of first order logic.
Chaitin's constant

Example algorithm
The following is an example algorithm which solves the problem by converging to the first example.
Take a positive integer \$n\$ as input.  Take the first \$n\$ Turing machines and run each of them for \$n\$ steps.  Output
\$
\displaystyle\sum_{m=0}^n \begin{cases}2^{-m}& \text{if machine }m\text{ halted before }n\text{ steps}\\0 & \text{otherwise}\end{cases}
\$
That is to say we start at zero and add \$1/2^m\$ for each machine \$m\$ that halts in our simulation.
Now since computing a Turing machine for \$n\$ steps is computable, and adding rational numbers certainly is computable, this algorithm is as a whole computable.  However if we take the limit, we get a string that exactly encodes the solutions halting problem.  The limit is:
\$
\displaystyle\sum_{m=0}^\infty \begin{cases}2^{-m}& \text{if machine }m\text{ halts}\\0 & \text{otherwise}\end{cases}
\$
I think it is intuitive that this sort of thing is not something that can be computed.  But more concretely if we were able to compute this number then we could use it to solve the halting problem, which is not possible.

05AB1E, 25 24 bytes
LεÅγιøIãʒηεøJË}à}gĀ}'.šJ

Try it online!
-1 thanks to @ovs
f(n) is a decimal number such that it's xth digit is 1 iff x<=n and when you run length encode x and convert it to matching pairs, it has a solution to PCP with a length of at most n pairs.
outputs as .digits after the dot. In case the 0 is needed, it's +1 to replace '. with „0.
Code explaination:
L      all numbers from 1 to N
ε      map each to
 Åγ    run length encode
 ι     uninterleave to two lists
 ø     tranpose
 Iã    cartesian power N, all choices of N such pairs
 ʒ     only keep those such that
  η    its prefixes
  ε    map each to
   ø   itself transposed
   J   joined
   Ë   both elements are equal
  }
  à    maximum - if any of those are 1
 }
 gĀ    the length of the filtered list isn't 0
}
'.š    prepend .
J      join, and implicitly print

We can show a reduction from PCP with two symbols (which is known to be undecidable):
given an instance of PCP with two symbols, 1 and 2 (for example [2,1], [11,2], [2212,111]), unflatten the pairs (which would give [2,1,11,2,2212,111] in the example) and run length decode with alternating 1, 0. That number would be x. The solution to the PCP instance is 1 iff the xth digit of the limit of this function is 1.


Fabulous glamour shot Found this picture on the web today. Being a lazy programmer, I don't want to actually open google and type a couple of characters. Way too much work! This is such an important task that it should be automated.
Challenge
Everyone knows that the first image in a google search result is always the best. Hence it should be presented to the user.
You are to write a program or function which takes a string as parameter and displays the first image it finds on google when you search for that name + the words glamour shot behind it.
Google search queries
To search for images on google, the url should contain the query parameter tbm=isch and q=query, with query being the name you want to search for.
A valid query string for my name Bas would be www.google.com/search?tbm=isch&q=Bas
Input
Your program or function takes a single parameter of input, which is the name you want to search for on google. This string will consist of the characters [a-z], [A-Z], [0-9] and   (space). This string can be space seperated, to search for a space seperated string on google, one should replace the spaces with +. For example, this is a valid query:
www.google.com/search?tbm=isch&q=Bassdrop+Cumberwubwubwub+glamour+shot
Output
The image can either be drawn to the screen, or saved to a file (in any format).
If the first search result on google is a gif file, you can either show the gif or show any frame of that gif.
Test cases
Run this snippet to see the expected results

f('Bas') // www.google.com/search?tbm=isch&q=Bas+glamour+shot

f('Bassdrop Cumberwubwubwub') // www.google.com/search?tbm=isch&q=Bassdrop+Cumberwubwubwub+glamour+shot

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

PowerShell v4+, 160 bytes

param($a)iwr (((iwr "google.com/search?tbm=isch&q=$($a-replace' ','+')+glamour+shot").links|?{$_.innerhtml-like"*$a*"})[0].innerhtml-split'"')[3] -outf "$a.jpg"

Takes input $a as a string. Does an Invoke-WebRequest (iwr) to the appropriate Google location, using inner-string script block to -replace spaces with + in the input string. We take the .links of that, where the .innerhtml is -like our input string. That yields the links with the proper thumbnail description. Take the first [0] one of those, take its .innerhtml and -split it on quotations. The fourth [3] element is the text inside the img src=" portion, so we do another iwr on that, specifying -outfile to be $a.jpg in the local folder. Since these are just the Google generated thumbnails, they're guaranteed to be jpg.


Convert Numbers To Emoji Math In Emoji Math, a user created module for the video game Keep Talking And Nobody Explodes, numbers are written as strings of emoticons, where each emoticon represents a base 10 digit.
Below is the conversion table between digits and emoticons.

Digit | Emoticon
  0   |    :)
  1   |    =(
  2   |    (:
  3   |    )=
  4   |    :(
  5   |    ):
  6   |    =)
  7   |    (=
  8   |    :|
  9   |    |:

Given a number, output it in Emoji Math encoding. You may assume the absence of non-numeric characters.

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

Japt, 29 24 bytes

-5 bytes thanks to @Shaggy

s":)=((:)=:():=)(=:||:"ò

Takes input as a string

Try it online!


Calculate the points in a "sjoelen"-game Okay, so yesterday was 2nd Christmas day and my (grand)parents and me had a game of "sjoelen", as it is called in the Netherlands. The inner programmer came up in me, but just when I had the answer, I lost it. I want you to remake it.

The rules:

You have a wooden plank, a sjoelbak, with 4 boxes, each with their own number. When a schijf (A puck-like object) goes in one of the boxes you get the points above that box.

When there is a schijf in all 4 of the boxes, you don't get 10 but you get 20 points.

Example:

From left to right: 3 5 4 3
Each box has at least 3 schijven (Plural of schijf) so that is 20 * 3 = 60 points.

Resulting values: 0 2 1 0
0*2 + 2*3 + 1*4 + 0*1 = 10 points.

Which makes a total of 60+10 = 70 points.

The input:
The amount of schijven from left to right, ie "4 5 4 5", [4,5,4,5], "4\n5\n4\n5", whatever you like.

The output:
The amount of points, ie 84, as output, variable, return or on top of the stack, whatever you like.

As in each and every code golf, you can not use external scripts and the code with the least bytes wins.

PS: As you may have already noticed, I'm Dutch. Feel free to edit possible grammar mistakes.

CJam, 23 21 20 bytes
q~_$0=f+1m>{X):X*+}*

I might be able to golf a couple of bytes off this.
Input is like
[3 5 4 3]

Output is the score
70

How it works
q~                         "Read the input and evaluate into an array";
  _$0=                     "Copy the array, sort it and get the minimum number";
                           "This minimum is the number of common schijven";
      f+                   "Increment each of the schijven by the common schijven number";
        1m>                "Take 1 element from the end of the array and put";
                           "it in the beginning";
           {      }*       "Reduce the elements of the array based on this block";
            X):X           "Increment and update the value of X (initially 1)";
                *          "Multiply the number of schijven with X";
                 +         "Add it to current score";

Algorithm

Since I have right shifted the number of schijven, the score order now becomes [1 2 3 4].
Moreover, using the fact that 1 + 2 + 3 + 4 = 10, I simply add the minimum common schijven to each one to get the effect of bonus 10 score.
Now when I reduce, I get 2 elements initially on stack, the first one, which I ignore is the one with a score of 1 each, then I multiply the second one with 2 and add it to first. In the next iteration, I get the current sum and score 3 schijven. And so on.

Try it online here


The Professor's base building number converter The nutty maths professor wants to encode all of their research using a system sure to fox even the wiliest of their competitors!
To this end the professor has decided to change the base of not just the number that they're writing but every single digit in that number, according to which place the digit finds itself in (counting from the right, starting with 1). For example:
The number 0 has one digit, so it is represented in base 1: 0
The number 1 would have one digit in base ten, but in our professor's system that isn't valid. The first place is reserved for base 1 digits only! This means it must be bumped to the second place where base 2 is allowed: 10
The number 2 requires at least base 3 to be written: 100
But now the number 3 can be written by changing the digit in the second place: 110
and 4 as so: 200
Here are some more examples to help you get the idea:

5:210
6:1000
7:1010
8:1100
9:1110
10:1200
11:1210
12:2000
13:2010
14:2100
15:2110
16:2200
17:2210
18:3000

Using this system the professor's notes will make no sense to anyone but them, and they can finally take over the world!!!! sleep well at night.
Of course the encoding method must be as obscure as possible.

Your task is to write 10 code snippets, each representing one of the base 10 digits

0 1 2 3 4 5 6 7 8 9

which when combined in the order of the number to be converted will produce a number written in the professor's diabolical numbering system (the output method may be of your choice but must be a human readable number using only the digits 0-9)
For example if my snippets are:
0=MONKEY 1=EXAMPLE, 2=CODE, 3=GOLF and 9=TEST
then
19 = EXAMPLETEST -> 3010
20 = CODEMONKEY -> 3100
21 = CODEEXAMPLE -> 3110
22 = CODECODE -> 3200
23 = CODEGOLF -> 3210
No input numbers with more than 10 digits or negative numbers need to be considered, though if you want to write the code for additional digits you will get extra kudos. This is code golf, so shortest answer (using the combined byte totals of all snippets) wins and the standard loopholes aren't allowed.
ADDENDUM: Before anyone gets started on whether 0 is the correct representation of 0 in base 1 I would like to remind you that this professor is nutty. Live with it.

Mathematica (REPL environment), 858 total bytes

Here is the 86-byte code snippet for the digit 9:

1;ValueQ@a||(a=0;b=3);a=10a+9;b++;FromDigits[a~IntegerDigits~MixedRadix@Range[b,1,-1]]

The code snippets for the digits 1 through 8 are identical, except that the 9 is replaced by the appropriate digit. The code snippet for the digit 0 is identical, except that +9 is simply deleted.

a~IntegerDigits~MixedRadix@Range[b,1,-1] computes the list of the factorial-number-system digits of a, as long as b is at least as large as the number of digits; FromDigits converts that list of digits to a regular base-10 integer for the purposes of output. (If any of the list elements exceeds 9, something funny happens.)

In Mathematica's REPL environment, computations can be terminated with semicolons to suppress the output; so only the last output in a semicolon-separated chain will be displayed. We recursively define the integer a designated by the snippets, and also a bound b on the number of factorial-system digits needed. The command ValueQ@a||(a=0;b=3) initializes these variables if they're uninitialized (i.e., in the first snippet) and leaves them alone otherwise; then a=10a+9;b++ carries out the recursion. Finally, the initial 1; is for gluing the snippets together: it multiplies intermediate computations by 1 (which we never see anyway).


Tips for golfing in K K is a programming language in the APL family designed by Arthur Whitney. While the official interpreter is closed-source and commercial, a trial version with a workspace limit of 32 bits of addressing space (which shouldn't pose problems for code golf) can be found at the Kx Systems website. This version bundled as part of the kdb+ database is colloquially known as "K4". There are also open-source K implementations available, including Kona, which is based on K3, and my own interpreter called oK, which is based on K5 and has a browser based REPL.

Kx Systems has a wiki with K4/kdb+/Q information, and the Kona GitHub page also has an excellent collection of reference materials. I have begun writing a manual for oK/k5 which may be a useful reference.

Like J and APL, K is a very terse and powerful language, and can often make a good showing in code golf. Please share tips, tricks and idioms you discover, and if you haven't tried K before consider giving it a spin! Post one tip per answer, please!

Calling a Dyad

Assuming you had a dyadic (2-argument) function f:

f: {x+2*y}

You would ordinarily call it like so:

f[3;47]

You can save a character by instead currying in the first argument and then applying the resulting partial function to the second argument by juxtaposition:

f[3]47

The same naturally works for array indexing:

  z: (12 17 98;90 91 92)
(12 17 98
 90 91 92)

  z[1;2]
92

  z[1]2
92