text:
Build a random number generator that passes the Diehard tests
While there are many code golf questions on here involving randomness, I haven't seen one yet that actually asks for building an algorithmic pseudorandom number generator. There's this one that asks you to generate a bit stream, but the randomness tests provided on that one were not very rigorous, and it's not code-golf.
The program you write will have a single callable function that will return a random integer from 0 to 4294967295. This function must not call upon any libraries or other functions that were not also written as part of the program, especially calls to /dev/random or a language's built-in rand() library. More specifically, you are limited to the basic operators of the language you are working in, such as arithmetic, array access, and conditional flow control statements.
The score of your program is calculated as follows:
Score = C / R

Where C is the length of the code in characters, and R is the number of Diehard tests that your generator passes (If your random number generator does not pass at least one Diehard test, its score is infinity and it is disqualified). Your generator passes a Diehard test if the file it generates provides a range of P-values that appear to be distributed uniformly along the interval [0, 1).
To calculate R, use your random number generator with its default seed to generate a 16 MB binary data file. Each call of the function returns four bytes; if your function is too slow to return bytes, this will factor a trade-off into attaining a low score by how difficult it is to test. Then, run it through the Diehard tests and check the P-values provided. (Do not try and implement these yourself; use the ones provided here)
Lowest score wins, of course.

Is code that requires internet connectivity allowed? (not gonna access any random function online, but maybe ping or the values of an api call)

"This function must not call upon any libraries or other functions that were not also written as part of the program." That includes Internet connectivity functions. Your generation should be purely algorithmic.

The diehard suite expects input files of 10-11 MB.

The link to the tests seems to be broken, here's a possible alternative.

How should do this for my brain-flak answer (removed below)? I think the code is too slow to be practical

Also the tests are broken again

ECMAScript 6, 31 30 25 / 15 = 1.66
This is Keith Randall's solution implemented in ES6:
e=3;R=_=>e=e**3%(2**32-5)

Removed semicolon (thanks The Thonnu!)
Drop unnecessary comma operator and use _ for param (an assignment statement will return the new value)

Welcome to code golf! Nice first answer

Nice answer! I think you might be able to leave off the last semicolon. (I've seen a lot of answers on this site do that as well)

Perl 28 / 13 ≈ 2.15
sub r{$s^=~($s^=$s/7215)<<8}

log file here
Perl 29 / 13 ≈ 2.23
sub r{$s^=~($s^=$s<<8)/60757}

log file here
These are something of a variation on a Xorshift, using floating point division instead of a right shift. They both pass 13 of 15 tests, failing only tests 6 and 7.
I'm not exactly sure how long the cycle is, but because the following code doesn't terminate in any short period of time, it's likely the full 232:
$start = r();
$i++ while $start != r();
print $i;

Perl 39 / 10 = 3.9
$s=$^T;sub r{~($s=$s*$s%4294969373)||r}

Note: if you're looking for a Blum-Blum-Shub-esque PRNG, Keith Randall's solution is far better than either of these.
As with my original solution below, this is also an implementation of the Blum Blum Shub, with one major difference. I uses a modulus slightly larger than 232 (M = 50971 • 84263), and whenever a value is encountered that it is not a valid 32-bit integer (that is, larger than 232), it returns the next value in the rotation instead. In essense, these values are pruned out, leaving the rest of the rotation undisturbed, resulting in a nearly uniform distribution.
It seems to have helped. In addition to passing the same 9 tests as before, it now also convincingly passes the Minimum Distance test. A sample log file can be found here.

Perl 33 / 9 ≈ 3.67 (Invalid?)
 $s=$^T;sub r{$s=$s*$s%4294951589}

Note: this solution might be considered invalid, as the top-most 0.00037% of the range will never be observed.
A quick and dirty implementation of the Blum Blum Shub. I claim the following results:
 1. passed - Birthday Spacings
 2. FAILED - Overlapping Permutations
 3. passed - Ranks of 31x31 and 32x32 Matrices
 4. passed - Ranks of 6x8 Matrices
 5. FAILED - Monkey Tests on 20-bit Words
 6. FAILED - Monkey Tests OPSO, OQSO, DNA
 7. FAILED - Count the 1s in a Stream of Bytes
 8. passed - Count the 1s for Specific Bytes
 9. passed - Parking Lot Test
10. FAILED - Minimum Distance Test
11. passed - Random Spheres Test
12. FAILED - The Squeeze Test
13. passed - Overlapping Sums Test
14. passed - Runs Test
15. passed - The Craps Test

A sample log file can be found here, feel free to dispute any of the results. The file for diehard can be generated in the following manner:
print pack('N', r()) for 1..4194304

and then piping the output into a file. Minimum Distance looks like it might have passed, but if you run it multiple times it's always very close to 1.0, which indicates failure.

Details
In general, the Blum Blum Shub is a terrible PRNG, but it's performance can be improved by choosing a good modulus. The M I've chosen is 7027 • 611207. Both of these prime factors, p and q, have modular residue 3 (mod 4), and gcd(φ(p-1), φ(q-1)) = 2, which is as low as it can be.
Although these are the only criteria listed on the wiki page, it doesn't seem to be enough. Almost all of the modulo I tried failed every test. But there's a handful that will pass some of the tests, and the one I've chosen seems to be exceptionally good, for whatever reason.
As a final note, Test 5 on its own seems to be a fairly good indicator of how good the PRNG is. If it doesn't almost pass Test 5, it will fail the rest of them spectacularly.

BONUS: Perl 62 / 14 ≈ 4.43
$t=$^T;sub r{$t|=(($s=$s/2|$t%2<<31)^($t/=2))<<31for 1..37;$t}

Just for geekery, this is a 32-bit version of the PRNG used in the original Tetris for NES. Amazingly, it passes 14 of the 15 tests!
 1. passed - Birthday Spacings
 2. passed - Overlapping Permutations
 3. passed - Ranks of 31x31 and 32x32 Matrices
 4. passed - Ranks for 6x8 Matrices
 5. passed - Monkey Tests on 20-bit Words
 6. passed - Monkey Tests OPSO, OQSO, DNA
 7. FAILED - Count the 1s in a Stream of Bytes
 8. passed - Count the 1s for Specific Bytes
 9. passed - Parking Lot Test
10. passed - Minimum Distance Test
11. passed - Random Spheres Test
12. passed - The Squeeze Test
13. passed - Overlapping Sums Test
14. passed - Runs Test
15. passed - The Craps Test

Sample log file can before here.
Admittedly, the 1..37 bit isn't an exact transcription. In the orginal version, the entropy routine is updated 60 times per second, and then queried at random intervals, largely dependent on user input. For anyone who cares to disassemble the ROM, the entropy routine begins at 0xAB47.
Python-style pseudo-code:
carry = entropy_1 & 1
entropy_1 >>= 1
entropy_2 = (entropy_2 >> 1) | (carry << 31)
carry = (entropy_1 & 1) ^ (entropy_2 & 1)
entropy_1 |= carry << 31

Yeah, I noticed that your algorithm "failed" the bitstream test, but actually had a few values below 0.999999. Still, your tests seem accurate.

There is one problem, though, and that is that numbers from 4294951589 to 4294967295 have no chance of occurring (although I suppose that is part of the reason it failed some of the Diehard tests).

@JoeZeng yes, that is a problem. It's most evident in Test 5: the first run has 151k missing words, and the rest of them only have 143k missing. One solution would be to choose a modulus slightly larger than 2^32, and allow the values that are too large to wrap around to zero, but I wasn't able to find one that works well. If I do, I'll update the post.

Python, 46 / 15 = 3.0666
v=3
def R():global v;v=v**3%(2**32-5);return v

Uses modular exponentiation to generate randomness.  2**32-5 is the largest prime less than 2^32.
(Same deal with not being able to run test #2.)

Could you paste a log file?

Log here: http://codepad.org/ZWhoGe0t

Stupid Windows. It was converting all occurances of \r and \n to \r\n, which obviously skews the results. A fix is to write the file directly using f = open('file.bin', 'wb') and f.write.

This new score undercuts the previous score, so is now the accepted answer.

This new score was undercut yet again, so I have changed the accepted answer.

Mathematica, 32 / 15 = 2.133
x=3;Mod[x=Mod[x^2,28!-67],2^32]&

A straightforward implementation of BBS.
Binary file generated with:
f = %; (* assigns anonymous function declared in the previous expression to f *)
Export["random.bin", Array[f, 2^22], "UnsignedInteger32"];

Summary of results:
 1. BIRTHDAY SPACINGS TEST           .684805
 2. OVERLAPPING 5-PERMUTATION TEST   .757608/.455899
 3. BINARY RANK TEST                 .369264/.634256
 4. BINARY RANK TEST                 .838396
 5. THE BITSTREAM TEST                (no summary p-value)
 6. OPSO, OQSO and DNA                (no summary p-value)
 7. COUNT-THE-1's TEST               .649382/.831761
 8. COUNT-THE-1's TEST                (no summary p-value)
 9. PARKING LOT TEST                 .266079
10. MINIMUM DISTANCE TEST            .493300
11. 3DSPHERES TEST                   .492809
12. SQEEZE                           .701241
13. OVERLAPPING SUMS test            .274531
14. RUNS test                        .074944/.396186/.825835/.742302
15. CRAPS TEST                       .403090/.403088/.277389

Full random.bin here.
Full log file here.

28!-67 is somewhat prohibitive. Is there a smaller value that would fit in a 64-bit integer?

@primo Like Python, Mathematica's integers are arbitrary-precision by default, so it doesn't cause a problem.

I was thinking specifically for portability into C.

@primo https://gmplib.org/

Ruby, 32/15 = 2.1333
This is Keith Randall's solution, implemented in Ruby.
$v=3;def R;$v=$v**3%(2**32-5)end

@JoeZ This seems to be the new lowest answer, tied with the brand-new Mathematica answer.

Python, 41 / 15 = 2.73333
v=0
def R():global v;v=hash(`v`);return v

Kinda cheating using the built-in hash function, but it is built-in, so no more cheating than using other builtins, like len.  On the flip side, it pains me to have to pay for the global v; statement...
Passes all the Diehard tests (I had a problem with test #2, it SEGVs on my OSX machine.  For my score, I'm assuming it will pass).
Here's a driver to generate the 16MB file:
import sys
for i in xrange(1<<22):
  r=R()
  sys.stdout.write('%c%c%c%c'%(r&255, r>>8&255, r>>16&255, r>>24&255))

"This function must not call upon any libraries or other functions that were not also written as part of the program, especially calls to /dev/random or a language's built-in rand() library." I'm sorry, but that disqualifies your entry.

To be clear, "len" would also disqualify your entry.

Where do you draw the line?  Is + a built-in function, and hence disqualified?

is an operator. By functions, I refer to things that, in most languages, would require a name of the function, then brackets to surround the arguments, such as f(x).

But in lots of languages, operators and functions are identical.  See + and __add__ in python, or operator overloading in c++.  I know I'm kind of splitting hairs, so consider this example.  In python can I create a map like this: {'a':5}?  You'll probably say yes, but then consider that under the covers, hash('a') gets called when you do that.

I suppose I'd draw the line when you need to syntactically refer to the function in that way. If you can find a hack in Python that will allow you to directly access the map address without syntactically referring to the "hash" function, I might accept it.

This seems to fail a lot of tests: http://codepad.org/zPCbIz2J specifically 2, 5, 6, 7, 12, and 15. Generated using cPython v2.7.2. Also, for what my opinion is worth, functions for basic data manipulation (len, pop, etc.) should probably be allowed, although things like hash, crypt, etc. are definitely questionable.

Works for me on 2.6.1 and 2.7.2 on OSX.  I wonder what's different about the hash?

@KeithRandall It must be a fundamentally different implementation. I tried experimenting with different seeds, instead of 0, but they all fail Test 5 at the very least.

C# 144 / 15 = 9.6
uint a=15,b=26,y;uint q(int n){y=(a*1414549U+876619U)^(b*889453U+344753U);b=a;a=y>>12;return(a%256)<<n;}uint r(){return q(24)|q(16)|q(8)|q(0);}

This passed all of the tests.
With not too many more characters it passes TestU01.
Result: http://codepad.org/iny6usjV
    uint a = 15;
    uint b = 26;

    byte prng8()
    {
        uint y = ((a * 1414549U + 876619U) ^ (b * 889453U + 344753U)) >> 12;
        b = a;
        a = y;
        return (byte)y;
    }

    uint prng32()
    {
        return ((uint)prng8() << 24) | ((uint)prng8() << 16) | ((uint)prng8() << 8) | (uint)prng8();
    }

C, 38/15 = 2.533
long long x;f(){return(x+=x*x+9)>>32;}

I couldn't get the Diehard tests working on my machine, but it passes the PractRand suite for up to 8GB of output so I assume it would pass them all.

C# - 103 / 14 = 7.36
double j=999;uint N(){uint i=0,n=0;for(;i++<4;n=n*256+(uint)j%256)for(j/=277;j<100000;j*=j);return n;}

Results
Passes all except test #6
See results at http://codepad.org/k1NSoyQW
Explanation
C# just can't compete with Ruby and Python for terseness, as usual, but I enjoyed trying. There are certainly other values that will work just as well (i.e., the initial value for j=999, and the divisor=277).  I picked these after brief experimentation.
With file-creation wrapper
class R
{
    public static void Main(string[] args)
    {
        var r = new R();
        using (var f = new System.IO.FileStream(".\\out.bin", System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read))
        using (var b = new System.IO.BinaryWriter(f))
        {
            for (long i = 0; i < 12 * 1024 * 1024; i += 4)
            {

                b.Write(r.N());
            }
        }
    }

    double j = 999;

    uint N()
    {
        uint i = 0, n = 0;
        for (; i++ < 4; n = n * 256 + (uint)j % 256)
            for (j /= 277; j < 100000; j *= j) ;
        return n;
    }

}

Brain-Flak, 344/(pending)
<>((()()){})<> push the amount of iterations to do for the PRNG
(((((((((((((((((((((((((((((((((((()()()){}()){})){}{}){()()()()({}[()])}{})){}{})){}{})()){}{})()){}{})){}{})){}{}){}())){}{})){}{})()){}{})()){}{})){}{})){}{})()){}{})()){}{}) push M (one of the values for the Blum Blum Shub PRNG
((((((((((((()()()){}){}){})){}{}){()({}[()])}{}){}())){}{})()){}{}) push s see above
<>{({}[()])<>starts the loop
(({({})({}[()])}{}) squares the current number
(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]({}))mods by M
<>}{}<>loop ends

Try it online!
This works fine but the diehard tests links are all broken :( so until we get new ones i do not have a final score
This uses the Blum Blum Shub PRNG so it should pass most the cases. The numbers used are large enough no patterns will appear within the 16 MB of test cases

if this is invalid just tell me

I count 344. Theorem: No fully golfed Brain-flak program have an odd number of bytes.

Objective-C, 40/1 = 40
Pretty clever approach, exploiting .hash to somewhat cheat here, but I like it
for(int v=9;v=@(v).hash;printf("%i",v));


text:
Keep track of a Roulette game
You're writing a program for a new automated roulette croupier to be installed in a major casino. Unfortunately, the last guy bailed out on the company and published buggy software. You're stuck with a thousand burned flash chips with only a few kilobytes of space to store a working program. Can you do it?
The task is to write a program which will accurately handle bets, wins and losses of a roulette game.
It will be run as a session. When it initialises, players place their bets which are sent through STDIN. Once all bets have been received, the input for where the ball landed is given. The program must then calculate the winnings for each of the players and the casino.
A single zero wheel is assumed. Assume dollars will be bet (not chips) and that the input is always valid. You only need to support the "outside bets" and numbered bets (lists of numbers, not named.) Payouts are described on the Wikipedia article.
Outside bet names: c1, c2, c3 (1st-3rd column), d1, d2, d3 (1st-3rd dozen), o (odd), e (even), r (red), b (black), 1-18, 19-36.
Example session (> indicates input, < indicates output):
> 7 800

Place a bet on the number "7" only, for $800.
> 8,9,10,11 50

Place a bet on the range "8,9,10,11", for $50.
> c1 2000

Place a bet on "1st column" (1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34) for $2000.
> ok
> 7

All players done. Pocketed in 7.
< 1 28800
< 2 0
< 3 6000

Payout details: #1 gets 36x original bet (35-to-1), #2 did not win and #3 gets 3x original bet (2-to-1)
< c -34750

Casino is down $34,750.
Deciding the winner

Code space is critical so the smaller the program the better. The smallest program implementing all of the described features will be the winner, unless bonus features are present, in which case the best overall program will be decided based on the combination of size and features supported.
The program must implement at least the bets described above, but support for other types, as well as number bets such as splits and baskets will be considered and may add bonus points.

If Player 2 did win, how much would he get? 9x? Could you give 5 numbers as input?

@beary605 The odd payouts are listed on the Wikipedia article I linked to -- just add one to get the amount paid.

Are only numbers allowed to be combined by commas, or do we have to handle something like c1,c2 100?

@Keith Only numbers can be combined by commas.

Shouldn't c in your example be -31950 = 800+50+2000-28800-6000?

@Keith Each individual receives their original bet back plus the payout.

That can't be right.  Consider the bet e 1.  If I win, I get my dollar back, plus 2 more dollars?  That means I have an expected edge against the house (win 2 dollars a bit less than 50% of the time, lose 1 dollar a bit more than 50% of the time).

Python, 443 440 chars
R=range
N=37
V=91447186090
M={'e':R(0,N,2),'o':R(1,N,2),'r':[i for i in R(N)if V>>i&1],'b':[i for i in R(1,N)if~V>>i&1],'1-18':R(1,19),'19-36':R(19,N)}
for i in R(1,4):M['c%d'%i]=R(i,N,3);M['d%d'%i]=R(i*12-11,i*12+1)
for i in R(1,N):M[`i`]=[i]
B=[]
r=raw_input()
while'ok'!=r:x,k=r.split();B+=[(sum((M[y]for y in x.split(',')),[]),int(k))];r=raw_input()
z=input()
c=0
i=1
for b,k in B:v=36/len(b)*k*(z in b);print i,v;c+=k-v;i+=1
print'c',c

Makes M, a map from bet names to a list of numbers that win that bet.  Then it reads the bets in, storing each one as a pair (list of numbers, dollar amount) in the list B.  Finally, reads in the spin z and computes the payouts.

Would the shorthand for repr(i) save chars on line 6?

@beary605: yup, saves 3 chars.

Python (548)
Wow, the biggest thing I've done in a while.
r=[];R=range
for i in[1,12,19,30]:r+=R(i,i+7+i%2*2,2)
a=[];b='01';c=''
while'ok'!=c:
 if'c'in c:c=R(int(c[1]),37,3)
 if'd'in c:c=R(1+(int(c[1])-1)*12,13+(int(c[1])-1)*12)
 if'r'in c:c=r
 if'b'in c:c=filter(lambda x:x not in r,R(1,36))
 if'o'in c:c=R(1,36,2)
 if'e'in c:c=R(2,36,2)
 if'-'in c:e=18*(c[1]>'-');b[0]=R(1+e,19+e)
 if"'"in`c`:c=map(int,b[0].split(','))
 a+=[[c,b[1]]];b=raw_input().split();c=b[0]
a=a[1:]
i=input()
z=[(i in p[0])*int(p[1])*(36/len(p[0])+1)-int(p[1])for p in a]
for j,k in enumerate(z):print j+1,max(k,0)
print"c",-sum(z)

Things that can probably be compressed:

generating the numbers for things like e, o, d2
the math formula for calculating z

[x for x in R(1,36)if x not in r] is two characters shorter than filter(lambda x:x not in r,R(1,36))

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Make a pattern alternate
Problem
You are given a sequence of coloured balls (red R and green G). One such possible sequence is:
RGGGRRGGRGRRRGGGRGRRRG

In as few moves as possible, you must make it so that each ball is a different colour to its neighbours (i.e. the sequence alternates.)
RGRGRGRGRGRGRGRGRGRGRG

You should write a program that can convert an unordered sequence (in this case a string) with equal numbers of "R" and "G" into a sequence where the items alternate. One example session is below, for a naive algorithm (< is input to program, > is output. It isn't necessary to include the carets on the input or output.)
< RGGGRRGGRGRRRGGGRGRRRG
> RGGRGRGGRGRRRGGGRGRRRG
> RGRGGRGGRGRRRGGGRGRRRG
> RGRGRGGGRGRRRGGGRGRRRG
> RGRGRGGRGGRRRGGGRGRRRG
> RGRGRGGRGRGRRGGGRGRRRG
> RGRGRGGRGRGRGRGRGGRRRG
> RGRGRGGRGRGRGRGRGRGRRG
> RGRGRGGRGRGRGRGRGRGRGR
> RGRGRGRGGRGRGRGRGRGRGR
> RGRGRGRGRGGRGRGRGRGRGR
> RGRGRGRGRGRGGRGRGRGRGR
> RGRGRGRGRGRGRGGRGRGRGR
> RGRGRGRGRGRGRGRGGRGRGR
> RGRGRGRGRGRGRGRGRGGRGR
> RGRGRGRGRGRGRGRGRGRGGR
> RGRGRGRGRGRGRGRGRGRGRG (15 moves)

Another possibility is outputting "5,7" for example to indicate swapping of positions 5 and 7.
You may position either Red or Green first, and you don't have to be consistent. Each sequence will be the same length as every other sequence.
You may only swap any two letters in each move (they do not need to be adjacent.)
Winning Criteria
The program must show each step of the sort process. The program which makes the fewest total moves for all the below strings, wins. If there is a tie, the shortest code will win.
Input Strings
The following strings will be used to test the programs:
GGGGGGGGGGRRRRRRRRRR
GGRRGGRRGGRRGGRRGGRR
RRGGGGRRRRGGGGRRRRGG
GRRGRGGGGRRRGGGGRRRR
GRGGGRRRRGGGRGRRGGRR
RGRGRGRGRGRGRGRGRGRG

The last sequence should result in zero moves.

Shouldn't "You may only swap any two pairs in each move" read "You may only swap any two letters in each move"?

@dude very good, I'll correct that.

Any requirement that a particular letter start the sorted sequence?

@dmckee From the question - "You may position either Red or Green first, and you don't have to be consistent."

Nice problem to work on. I suggest that you ask folks to post several examples of their input and output.  This way, those who don't program in the language chosen can make an evaluation about the suitabiity of the outputs for the respective inputs.

A little bit more challenging variation is where you have the restriction that you can only swap neighboring elements. So if you have an array you can swap a[i] and a[j] if abs(i - j) == 1

Can we assume it's possible to do? Eg. RRR would be invalid input - or do we have to return a falsy value?

Python, 140 122 119 115
r=raw_input()
f=lambda x:[i for i in range(x,len(r),2)if x-(r[i]!=max('RG',key=r[::2].count))]
print zip(f(0),f(1))

Technically you don't need the assignment of s. It'd save you a couple more characters.

Yeah, you're welcome. I had to do something clever after you trounced what I was working on.

GolfScript (47 chars)
:S;4,{S,,{.S=1&3*\1&2*^1$=},\;}%2/{zip}%{,}$0=`

E.g. (using a test case which is far easier to check for correctness than any of the suggested ones, which all have lots of correct answers):
< RRGGRGRGRGRGRGRGRGRG
> [[1 2]]

Output is a list of zero-indexed pairs to swap.

If [[1 2]] means to swap letters at positions 1 and 2, the result would appear to be identical to the input. Please clarify.

@dude, what kind of weirdo starts counting at 1?

(My hand is raised).

APL 46
((2|y)/y←(i≠↑i)/n),[.1](~2|y)/y←(i=↑i)/n←⍳⍴i←⍞

Running the given test cases yields:
GGGGGGGGGGRRRRRRRRRR
11 13 15 17 19
 2  4  6  8 10

GGRRGGRRGGRRGGRRGGRR
3 7 11 15 19
2 6 10 14 18

RRGGGGRRRRGGGGRRRRGG
3 5 11 13 19
2 8 10 16 18

GRRGRGGGGRRRGGGGRRRR
3 5 11 17 19
4 6  8 14 16

GRGGGRRRRGGGRGRRGGRR
7  9 13 15 19
4 10 12 14 18

RGRGRGRGRGRGRGRGRGRG

The above solution uses index origin 1 with the swaps given in the columns of the results matrix. Two characters can be saved if the input vector i is initialised with the input string prior to execution rather than being input at the time of execution.

Python, 213 chars
I=raw_input()
def M(S,T):
 S=list(S);m=[]
 while S!=list(T):z=zip(S,T);x=z.index(('R','G'));y=z.index(('G','R'));m+=[(x,y)];S[x],S[y]='GR'
 return m
N=len(I)/2
x=M(I,N*'RG')
y=M(I,N*'GR')
print[x,y][len(x)>len(y)]

M finds the moves required to convert S to T.  It does this by repeatedly finding an R and a G out of position and swapping them.  We then find the shorter move sequence to get to either RGRG...RG or GRGR...GR.
Should find an optimal sequence of moves for every input.

Mathematica 238
Code
f[x_] := With[{g = "GRGRGRGRGRGRGRGRGRGR", c = Characters, p = Position},
y = c[x]; s = c[g]; {v = Equal @@@ ({s, y}\[Transpose]),
w = Not /@ v}; {vv = Thread[{y, v}], ww = Thread[{y, w}]};
((Flatten /@ {p[#, {"R", False}], p[#, {"G", False}]}) &[If[Count[Equal @@@
({s, y}\[Transpose]), False] < 10, vv, ww]])\[Transpose]]

N.B.: \[Transpose] is a single character, a superscripted "t", in Mathematica]
Examples
f@"GGGGGGGGGGRRRRRRRRRR"
f@"GGRRGGRRGGRRGGRRGGRR"
f@"RRGGGGRRRRGGGGRRRRGG"
f@"GRRGRGGGGRRRGGGGRRRR"
f@"GRGGGRRRRGGGRGRRGGRR"
f@"RGRGRGRGRGRGRGRGRGRG"
f@"GRGRGRGRGRGRGRGRGRGR"

{{12, 1}, {14, 3}, {16, 5}, {18, 7}, {20, 9}}
{{4, 1}, {8, 5}, {12, 9}, {16, 13}, {20, 17}}
{{2, 3}, {8, 5}, {10, 11}, {16, 13}, {18, 19}}
{{2, 1}, {10, 7}, {12, 9}, {18, 13}, {20, 15}}
{{2, 1}, {6, 3}, {8, 5}, {16, 11}, {20, 17}}
{}
{}

Mathematica 134 or 124
Depending on how you count "Transpose[]" which on Mathematica is just one char (no representation here). Spaces added for clarity
G = 0; R = 1;
x_~ d ~ y__:= Transpose[Position[Symbol /@ Characters@x - PadLeft[{}, 20, {y}], #, 1] &
                                                                                /@ {1, -1}]
f = SortBy[{d[#, 0, 1], d[#, 1, 0]}, Length][[1]] &

Sample:
f@"GGGGGGGGGGRRRRRRRRRR"
f@"GGRRGGRRGGRRGGRRGGRR"
f@"RRGGGGRRRRGGGGRRRRGG"
f@"GRRGRGGGGRRRGGGGRRRR"
f@"GRGGGRRRRGGGRGRRGGRR"
f@"RGRGRGRGRGRGRGRGRGRG"
f@"GRGRGRGRGRGRGRGRGRGR"

Output
{{{11}, {2}}, {{13}, {4}}, {{15},  {6}}, {{17},  {8}}, {{19}, {10}}}
{{{3},  {2}}, {{7},  {6}}, {{11}, {10}}, {{15}, {14}}, {{19}, {18}}}
{{{1},  {4}}, {{7},  {6}}, {{9},  {12}}, {{15}, {14}}, {{17}, {20}}}
{{{2},  {1}}, {{10}, {7}}, {{12},  {9}}, {{18}, {13}}, {{20}, {15}}}
{{{2},  {1}}, {{6},  {3}}, {{8},   {5}}, {{16}, {11}}, {{20}, {17}}}
{}
{}

Very economical coding. Nice use of pure functions.

@dude Thanks :). I'm sure the PadLeft[{}, 20, {y}], #, 1] can be compressed a bit more

Javascript - 173 characters
a=prompt(w=[[],[]]).split('');for(i=a.length,f=a[0];i--;)if(i%2<1&&a[i]!=f)w[0].push(i);else if(i%2>0&&a[i]==f)w[1].push(i);for(i=w[0].length;i--;)alert(w[0][i]+','+w[1][i])

A great challenge, kept me busy for some time.
Here the codes results for the test cases:
GGGGGGGGGGRRRRRRRRRR: [10, 1] [12, 3] [14, 5] [16, 7] [18, 9]
GGRRGGRRGGRRGGRRGGRR: [ 2, 1] [ 6, 5] [10, 9] [14,13] [18,17]
RRGGGGRRRRGGGGRRRRGG: [ 2, 1] [ 4, 7] [10, 9] [12,15] [18,17]
GRRGRGGGGRRRGGGGRRRR: [ 2, 3] [ 4, 5] [10, 7] [16,13] [18,15]
GRGGGRRRRGGGRGRRGGRR: [ 6, 3] [ 8, 9] [12,11] [14,13] [18,17]
RGRGRGRGRGRGRGRGRGRG:

PHP - 34 moves - 193 characters
$l=strlen($a=$_GET["a"]);$n=$a[0]=="R"?"G":"R";while($i<$l){if($a[++$i]!=$n){echo$o."
";$o=$a=substr($a,0,$i).$n.preg_replace("/".$n."/",$n=="R"?"G":"R",substr($a,$i+1),1);}$n=$n=="R"?"G":"R";}

Might still try to improve this...
red_green.php?a=GGGGGGGGGGRRRRRRRRRR

GRGGGGGGGGGRRRRRRRRR
GRGRGGGGGGGGRRRRRRRR
GRGRGRGGGGGGGRRRRRRR
GRGRGRGRGGGGGGRRRRRR
GRGRGRGRGRGGGGGRRRRR
GRGRGRGRGRGRGGGGRRRR
GRGRGRGRGRGRGRGGGRRR
GRGRGRGRGRGRGRGRGGRR
GRGRGRGRGRGRGRGRGRGR

it could be better to use $argv[0] instead, saving you 2 bytes/each. And will be more valid, since $argv is often used for input via CMD

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Simple redstone simulator
Redstone is a material in the game Minecraft, and it is used for many complex contraptions. For this program, you will only need to simulate three items: the redstone wire (noted with R), redstone torch (noted with T), and block (noted with B).
Here are a list of basic rules about how redstone works:
A redstone torch sends power to any adjacent redstone wire.
TRRRR
 ^This redstone wire is powered.

Redstone wire can only hold power for 15 blocks.
TRRRRRRRRRRRRRRRR
                ^This last wire is unpowered, because the torch is >15 blocks away.

A block is said to be powered if a powered redstone wire is found adjacent to it.
TRRRB
    ^This block is powered.

If a block next to a redstone torch is powered, then the torch stops emitting power.
T
R
R
R
B <This block is powered.
T <This redstone torch does not emit power because of the block next to it.
R <This redstone is unpowered because the torch is not providing power.
R

Input will be given in two dimensional arrays up to a size of 64x64, like this:
TRRR
   B
TBRTRR
R
RRRRRRRRR
        R
   RRRRRR

It is guaranteed that the input will not have any "clocks", or redstone powered by a torch pointing to the block that the torch is on. There will only be one redstone circuit in every input.
Your program must change each character to be a 1 or a 0, 1 indicating if this item is powered/emitting power, and a 0 if it is unpowered/not emitting power.
This input should have this output:
1111
   1
100000
1
111111111
        1
   001111

This is a code-golf, so shortest code wins, as always.

What output do you expect for situations like "TRR\nB B\nRRT"?

111\n0 1\n000 is the output; it seems to be sound within the rules. I will put an input restriction saying you cannot have any situations like TRR B R RRR, where it flashes repeatedly.

Can we assume that each input array will contain  only one complete circuit running from top to bottom as in your example or do we have to code for multiple separate circuits starting anywhere in the array?

@Graham: There will only be one redstone circuit for each input.

Knowing the game Minecraft, I think that in your example given the block on line 2 does not stop the adjacent torch from giving power (the redstone doesn't actually connect to the block). Is this an error or a meant simplification?

Also, can we expect a maximum input size for the array?

@tomsmeding: simplification purposes. Maximum size? How about 64x64, that's nice :)

Does whitespace after the end of the line matter in the output? Also, should the output end with a newline?

I must answer this in Minecraft...

Haskell, 400
import Data.Char
import Data.List
f x=[(++[x]).tail,(x:).init]
h(' ':_)=' '
h('T':s)=if elem 'b's then 'T'else 't'
h('t':s)=h$'T':s
h('B':s)=if any(`elem`s)['e'..'s']then 'b'else 'B'
h('b':s)=h$'B':s
h(_:s)=max 'd'$chr$ord(maximum s)-1
o ' '=' '
o c|elem c"dTB"='0'
o _='1'
a=(map.map)o.(!!(64^2+16)).iterate(map(map h.transpose).transpose.(\l->[g l|g<-id:f(map(const ' ')$head l)++map map (f ' ')]))

map(map h.transpose).transpose.(\l->[g l|g<-id:f(map(const ' ')$head l)++map map (f ' ')]) replaces each tile by a list of itself followed by its four neighbors, then maps that through h. h says for each tile how it reacts to neighbors: Torches turn off ('T' rather than 't') when there's a power block ('b') nearby, wires ('d' for dead through 's') imperfectly copy their most-powered neighbor (though cant get worse than dead), etc.
iterate repeats this step, (!!(64^2+16)) plucks out an iteration at which acyclic circuits are done converging, and I totally wrote it like that to give an intuitive bound, not to land at 400.

Python, 699
This is just a quick pass (ran out of time for now).  It can probably use a lot more golfing.
import sys
m=[list(x)for x in sys.stdin.read().split('\n')]
e=enumerate
S=set
s=lambda x:S([(r,c)for r,i in e(m)for c,j in e(i)if j==x])
q=S()
t=s('T')
b=s('B')
n=s('R')
def d(o,r,c,i,h,q):
 if i<0:return 0
 o[(r,c)]=1
 for p in[(r+1,c),(r-1,c),(r,c+1),(r,c-1)]:
  if p in q or(p in b and not(r,c)in n):continue
  if(r,c)in b and p in t-q:
   x=S([p])
   q|=x
   o[p]=0
   return 1
  if p in h or not p in o:continue
  h|=S([p])
  if not d(o,p[0],p[1],i-1,h,q):return 1
g=1
while g:
 o=dict(zip(b,[0]*len(b))+zip(n,[0]*len(n))+zip(q,[0]*len(q)))
 g=0
 for x,y in t:
  if not(x,y)in q and d(o,x,y,15,S(),q):g=1
for p in o.keys():m[p[0]][p[1]]=o[p]
print"\n".join(map(lambda x:"".join(map(str,x)),m))

Yep, for example, you could use f=set and create a l=lambda x:zip(x,[0]*len(x)). Well, you'd still be over 700 chars. Also, you left a useless space at ... or not (a,z)in o.

Do you need the space after your print statement?

@ZacharyT You're right.  Thanks!

This was already said, but f=set would shave a few chars, and you have another useless character @ not (a,z)in o

Use tabs AND spaces for some indentation savings.

Python 2, 556 bytes
c=' 0';L=len;M=map;q=list;r='B';s='16';t='T';u='0';E=enumerate
b=[q(M(lambda x:x+[u,s][x==t],q(w[:-1])))+[c]*(64-L(w))for w in open('redstone.txt')]
k=lambda h,l,z:max(q(M(lambda x:[int((x or c)[1:]),0][l^((x or c)[0]==h)],z)))
def v(d=0):
 for e,f in E(b):
    for g,G in E(f):z=[e!=0and b[e-1][g],g<L(f)-1and f[g+1],e<L(b)-1and b[e+1][g],g and f[g-1]];j=G;i=j[0]+str([[s,u][k(r,1,z)>0],4,4,k(t,0,z),0,max(1,k(r,0,z))-1][ord(j[0])%7]);b[e][g]=i;d=d|(i!=j)
 return d
while v():0
for f in b:print''.join(M(lambda j:[' ',`int(j[1:]!=u)`][j[0]!=' '],f))+'\n'

See it in action

Assumes each line in input ends with a newline
Outputs via print()
Each line of output ends with lots of whitespace and a newline

Saved lots of bytes thanks to @mbomb007 (#34718)
Saved 1 byte thanks to @ZacharyT (#55550)

You are not required to have input and output via files. You may use stdin and stdout, with input() and print. Also, str(int(bool(j[1:]!=u))) is the same as \int(j[1:]!=u)``.

@mbomb007 Well, not quite, I still need the str(, but good point about bool(.

\x`(using backticks, it's an alias forrepr) is the same as str(x)(for small integers, at least. It's different for certain objects, longs, generators, etc). Another golf:if g!=0is the same asif g. You can also have k=lambda h,l,z:max(...`

@mbomb007 Backticks are not for Py3, and I don't have 2 on this pc. If I install it or switch computers, I'll add that, thanks.

Use an online interpreter, like https://repl.it or https://www.ideone.com. Then save it, and put the link in your answer. Then we can all try your code with the click of a button.

You should also view the Tips for golfing in Python page.

And on lines that are two spaces in (like f=b[e]), use a single tab instead of the two spaces.

@mbomb007 I actually saw that page, was able to save some space but the double-for-into-one-for-loop didn't work for me. I'll change whitespace as soon as I can get it working on py2.

Let us continue this discussion in chat.

Do you need the space here? print ''? Could it be print''?


text:
Arbitrary-Length Ternary Squarefree Words
A string is squarefree if it contains no substring twice in a row.
It is possible to have an arbitrarily long squarefree word using a 3-letter alphabet.
Write a program which accepts a positive integer n from stdin and prints any squarefree word of length n, using characters A, B and C.
Shortest code wins.

GolfScript (40 27 chars)
~1,{.{!}%+}2$*1,/<{,65+}%n+

The approach is a trivial variant on one of those described in Wikipedia: the run-lengths of 1s in the Thue-Morse sequence.
If the extra trailing newline is unacceptable it can be removed at the cost of one character by replacing n with ''.

Python, 94
n=input()
x=[0]
exec"x+=[1-y for y in x];"*n
print''.join('ABC'[x[i+1]-x[i]]for i in range(n))

It uses the Thue–Morse sequence method from wikipedia.
Efficient version (100 chars):
n=input()
x=[0]
while x==x[:n]:x+=[1-y for y in x]
print''.join('ABC'[x[i+1]-x[i]]for i in range(n))

exec"x+=[1-y for y in x];"*n saves 6 chars at the expense of efficiency - but hey this is golf!

Python, 129 125 119
Using John Leech's method as described on the linked wiki page.
s='A'
n=input()
while len(s)<=n:s=''.join('ABCBCACABBCAABCCABBCACABABCBCACABBCAABC'[ord(t)%5::3]for t in s)
print s[:n]

You could save some characters with: 'ABCBCACABBCAABCCABBCACABABCBCACABBCAABC'[ord(t)%5::3]

while s[:n]==s: saves 1 more

Python2 - 112 chars
This is pretty inefficient. It generates a much much much longer string than required and then truncates it. For example the intermediate s for n=7 is 62748517 (13n) characters long
s='A'
n=input()
exec"s=''.join('ABCBCACABBCAABCCABBCACABABCBCACABBCAABC'[ord(t)%5::3]for t in s);"*n
print s[:n]

Mathematica 159 140  134
Edit: A complete rewrite, using recursion (NestWhile).
Much faster and no wasted effort.
Code
g@n_:=StringTake[NestWhile[#~StringReplace~{"A"-> "ABCBACBCABCBA","B"-> "BCACBACABCACB",
     "C"->"CABACBABCABAC"}&,"ABC",StringLength[#]<n&],n]

Usage
It takes approximately 1/40 sec to generate a ternary square free word with one million characters.
g[10]
g[53]
g[506]
AbsoluteTiming[g[10^6];]

Verifying
f will test whether a string is square free.
f[s_]:=StringFreeQ[s, x__~~x__]

Checking the above outputs and one case in which the string "CC" appears.
f@Out[336]
f@Out[337]
f@Out[338]
f["ABCBACBCABCBABCACBACCABCACBCABACBABCABACBCACBACABCACBA"]

True
True
True
False


text:
Convert number to a base where its representation has most "4"s
Inspired by this. There is a number, given as either integer, string or array of digits (your choice). Find the base in which the representation of the number will have most "4"s and return that base.
Number    Result
624        5
444       10
 68       16

restrictions:

The base returned should not be greater than the input.
Numbers less than or equal to 4 should not be considered valid input, so undefined returns are acceptable

What is the highest acceptable base?

I would assume 36, as it gets difficult to represent after that

@SeanCheshire: You don't actually have to display the number.  You can easily represent a number in any base as an array, such as [1,15,3,64,43] for some number in base 80.  You're only outputting the base number, so you could technically test every base from 2 to n.

What is the correct answer for 1, 2, and 3, which have the same number of "4"s (0) in every base?  Also, many numbers have the same number of "4"s in many bases (e.g., 4 in any base > 5, 44 in any base > 45, 14 in base 9, or any base > 15, etc).  Should the correct answer be the smallest base with the largest number of "4"s?

note that it's not much use testing bases 2 3 and 4, as they can't produce a 4 in the first place

@SeanCheshire True, but it could shorten the code to leave the test in for 0,1,2,3 and 4 (it does in my case at least).

@mellamokb, 14 in any base greater than 15 would not have a 4 in it - e.g. 14 base 16 is D - this also applies to any base higher than 10 - the 4 may be in the original number, but the symbol chosen to represent it would not be a 4, but another number

@SeanCheshire: Oops, you are right, I didn't think that through completely.  However, it is still true that 4 would have 1 four in every base >= 5, so that should be clarified in the spec.

What's abs(4)?

APL (31 19)
Now tests all possible bases.
⊃⍒{+/4=K⊤⍨K⍴⍵}¨⍳K←⎕

Explanation:

⍳K←⎕: read user input, store in K. Make a list from 1 to K, which are the bases to try.
{...}¨: for each of these, run the following function
K⊤⍨K⍴⍵: encode K into that base giving a list of digits (as numbers) per base. Use K digits (a big overestimate, but it doesn't matter because the unused ones will all be zero anyway).
4=: see which of these are equal to 4
+/: sum these, now we know how many fours per base
⊃⍒: give the indices of the list if it were sorted downwards, so the index of the biggest one is at the front. Take the first item of this list.

I love your APL solutions.

Funny how that APL expression contains the expression most people make when reading it: ⍨

GolfScript, 30 characters
.,{[2+.2$\base{4=},,\]}%$)~p];

Works for any base - test the code online.
Comment: This solution was based on the original version of the question. It thus may return a base larger than the input, e.g. for the input 4 it correctly returns base 5 - which is no longer valid by the new rules.

VBA, 121
Function k(a)
For w=5 To a
Z=0:q=a:Do:c=q Mod w:Z=Z-(c=4):q=Int(q/w):Loop Until q=0
If Z>x Then x=Z:k=w
Next
End Function

usage:

direct window: ?k(num)
Excel formula: =k(A1)

fixed for all bases, and reduced test to simply counting 4s

FWIW, you can remove a space: For w=5To a

Python 2.x, 77 chars
F=lambda x:max((sum(x/b**d%b==4for d in range(99)),b)for b in range(5,99))[1]

Works up to base 98 and numbers at most 98 digits long.

J, 38 characters
f=.[:(i.>./)[:+/[:|:4=(10#"0(i.37))#:]

Usage:
   p 624
5
   p 444
10
   p 68
16

GolfScript (23 chars)
~:^,2>{^\base[4]/,~}$0=

or
~:^,2>{^\base[4]/,}$-1=

or
~:^,2>{^\base[4]/,}$)\;

Note that this takes input from stdin: for a fair comparison with Howard's GolfScript version subtract one char.

Howard points out that the rules have changed, and it's not very logical that they now exclude 4 as a possible input when it has a valid output (any integer greater than 4). To cover that case as well requires an extra 2 characters, which can be added in all kinds of ways:
~:^)),2>{^\base[4]/,}$)\;

or
~:^,{))^\base[4]/,}$)))\;

being a couple of the obvious ones.

Nice. But gives wrong answer for input "4".

I just saw that they changed the rules completely and removed any special cases after I did my submission. Thus your solution conforms to the new rules.

@Howard, the rules may say that that case doesn't need to be handled, but in the interests of completeness I'll add some variants.

Nevertheless, I can't +1 more than once ;-)

@Howard, you can add a bounty if you really want ;)

Jelly, 6 bytes
bⱮċ€4M

Try it online!
Outputs "all" bases up to N which gives the most 4's. If you want maximal or minimal base, add Ṁ (max) or Ṃ (min) respectively.
How it works
bⱮċ€4M    Main link (monad). Input: integer N.
bⱮ        Convert N to each base of 1..N
  ċ€4     Count 4's in each representation
     M    Take maximal indices

Mathematica 59
Code
Sort[{Count[IntegerDigits[n, #], 4], #} & /@ Range[5, 36]][[-1, 2]]

Let's give the above function a name.
whichBase[n_] := Sort[{Count[IntegerDigits[n, #], 4], #} & /@ Range[2, 36]][[-1, 2]]

Explanation

Count[IntegerDigits[n,k],4]:  Count the number of fours in the base k representation of n.
Sort the bases from fewest to most  4s.
Return the base from the last item in the list, that is, the base that had the representation with the most 4's.

Some special numbers
Now let's apply whichBase to the following special numbers.
numbers= {1953124, 8062156, 26902404, 76695844, 193710244, 444444444,
943179076, 1876283764, 3534833124, 6357245164, 10983816964,
18325193796, 29646969124, 46672774204, 71708377284, 107789473684,
158856009316, 229956041484, 327482302084, 459444789604, 635782877604,
868720588636, 1173168843844, 1567178659764, 2072449425124,
2714896551724, 3525282954756, 4539918979204, 5801435550244,
7359635486844, 9272428079044, 11606852190676}

{5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, \
  23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36}

If you convert each number to the corresponding base, you will see what is special about them.

I think you'd have to add 7 bytes for a complete function definition if you want to use n there. Also, MaximalBy really helps, knocks it down to 49 bytes: MaximalBy[Range[a=#],a~IntegerDigits~#~Count~4&]& (just ignore messages from it trying to use base-1)

Also, the current one fails starting on n = 152, where it gives 36 instead of 37.

Although your code works, I do not understand how it knows which bases to use.  Shouldn't it need to be told to examine bases 2 through 36 (or 1 through 36)?

Base 36 is never specified in the problem, and that's why I claim that yours fails for n = 152 = 4·37 + 4. My code checks all bases from 1 to n, since bases n + 1 and onward will only contain the single digit n.

Thanks for the clear explanation.

Japt -h, 10 bytes
444 in base 10 is [4,4,4] which contains the number and digit 4 3 times but 444 in base 100 is [4,44] which also contains the digit 4 3 times, but only as a number once. Given the expected output in the challange for the 444 test case, I'd guess we're supposed to be counting the number 4:
õ ñ@ìX è¥4

Try it
But if we are counting the digit 4 then:
õ ñ@ìX ¬è4

Try it
õ              :Range [1,...,input]
  ñ@           :Sort by passing each X through a function
    ìX         :  Convert the input to a base X digit array
               :(VERSION 1)
       è       :  Count the elements
        ¥4     :    Equal to 4
               :(VERSION 2)
       ¬       :  Join to a string
        è4     :  Count the occurrences of "4"
               :Implicitly output the last element in the sorted array

C - (114 characters)
In all it's golfy glory:
x,k,c,d,n;main(v){scanf("%d",&v);for(k=5;v/k;++k){x=v;c=0;while(x)c+=x%k==4,x/=k;c>=d?n=k,d=c:0;}printf("%d",n);}

And somewhat ungolfed:
x,k,c,d,n; // declare a bunch of ints, initialized to 0
main(v){   // declare one more, without using an extra comma
    scanf("%d",&v); // get the input (v)
    for(k=5;v/k;++k){ // loop over each base (k) greater than or equal to (/)
                      // our input (v)
        x=v;          // temp value (x) set to input (v)
        c=0;          // number of 4s in the current base (c) re-initialized
        while(x)       // loop over our temp until it's used up
            c+=x%k==4, // if the next digit (x%k) is 4 (==4) increment the
                       // current count (c+=)
            x/=k;      // remove the current digit
        c>=d?n=k,d=c:0; // if the number of 4s in this base (c) is greater
                       // than the current maximum number of 4s (d), then
                       // save the new best base (n), and new maximum
                       // number of 4s
    }
    printf("%d",n);   // output the result
}

Just for fun here's the output for the numbers [0,127] (these are the largest bases under the input number itself).

0, 0, 0, 0, 0, 5, 6, 7, 8, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 5, 21, 22, 23, 6, 25, 26, 27, 7, 29, 30, 31, 8, 33, 34, 35, 9, 37, 38, 39, 10, 41, 42, 43, 11, 5, 46, 47, 12, 49, 50, 51, 13, 53, 54, 55, 14, 57, 58, 59, 15, 61, 62, 63, 16, 65, 66, 67, 17, 69, 5, 71, 18, 73, 74, 75, 19, 7, 78, 79, 20, 81, 82, 83, 21, 85, 86, 87, 22, 89, 90, 91, 23, 93, 94, 5, 24, 97, 98, 99, 25, 101, 102, 103, 26, 5, 106, 107, 27, 109, 5, 111, 28, 113, 114, 5, 29, 9, 5, 5, 5, 121, 122, 123

@AttilaO. I was hoping someone would notice :)

R - 148 137 chars
(so, far away from the rest of the competition but still)
f=function(n){s=sapply;which.max(s(lapply(strsplit(s(4:n,function(x){q=n;r="";while(q){r=paste(q%%x,r);q=q%/%x};r})," "),`==`,4),sum))+3}

Basically transform the input from base 10 to all bases from 4 to n (using modulo %% and integer division %/%) and pick the index of the first one having the most 4s.
f(624)
[1] 5
f(444)
[1] 10

J translation of @marinus' APL solution:
NB. Expression form (22 characters, not including "n" - the "argument"):
{.\:(+/@(4=$#:[)"0 i.)n
NB. Function form (24 characters, not including "f=:"):
f=:{.@\:@(+/@(4=$#:[)"0 i.)

Just for interest, here are some values:
(,.f"0)9+i.24
 9  5
10  6
11  7
12  8
13  9
14  5
15 11
16  6
17 13
18  7
19  5
20  5
21  5
22  5
23  5
24  5
25  6
26  6
27  6
28  6
29  5
30  7
31  7
32  7

It outputs the smallest base that gives a fouriest transform. For the last few values in the table, the representations look like “4n” (e.g 31 in base 7 is “43”).

05AB1E, 10 9 bytes
LBε4¢}Zk>

-1 byte thanks to @Cowabunghole.
If multiple bases have the same amount of 4s, it will output the smallest one (i.e. 16 will result in 6, but 12 would also have been a possible output).
Try it online or verify all test cases.
Explanation:
L           # Create a list in the range [1, (implicit) input]
            #  i.e. 624 → [1,2,3,...,622,623,634]
 B          # Convert the (implicit) input integer to Base-N for each N in this list
            #  i.e. 624 and [1,2,3,...,622,623,624]
            #   → ["1","1001110000","212010",...,"12","11","10"]
  ε  }      # Map this list to:
   4¢       #  Count the number of 4s in the number
            #   → [0,0,0,0,4,0,0,0,0,1,0,2,...,0,0,0]
      Z     # Take the max (without popping the list)
            #  i.e. [0,0,0,0,4,0,0,0,0,1,0,2,...,0,0,0] → 4
       k    # Get the index of this max in the list
            #  i.e. [0,0,0,0,4,0,0,0,0,1,0,2,...,0,0,0] and 4 → 4
         >  # Increase it by to convert the 0-index to our base (and output implicitly)
            #  i.e. 4 → 5

Couldn't you replace Qƶà with k>? i.e. find the 0-based index of the max and increment it?

@Cowabunghole Ah, you're indeed right. Not sure how I missed that. Thanks!

k, 18 bytes
{*>+/'4=x{y\x}'!x}

Try it online!
{                } /function(x)
        x     '!x  /for every y in 0, 1, ..., (x-1):
         {y\x}     /    do x in base y
      4=           /see which digits equal four
   +/'             /sum, to get number of 4s per base
 *>                /get index (which equals base) of largest number of 4s

C# (482 ~423 Bytes)
First attempt at a 'golfed' solution.  I used basically the same algorithm as the VBA above.  I could probably save some bytes inlining the conversion function, or shortening the name.  Like I said this is a first attempt, so please be gentle.
With whitespace:
using System;
class Program
{
    static void Main(string[] args)
    {
        int n = int.Parse(args[0]);
        int c=0, m=0;
        string r="";
        int t = 0;
        for (int i = 5; i < 37; i++)
        {
            while (n > 0)
            {
                r = (char)((int)(n % i) + 48 + (7 * ((int)(n % i) > 9 ? 1 : 0))) + r;
                n = (int)(n / i);
            }
            t = r.Length - r.Replace("4", "").Length;
            if (t > c) { c = t; m = i; }
        }
        Console.WriteLine("Base: " + m);
    }
}

I don't think the namespace is required.  All names should be a single character, including Program and cBase.  And yes, you should inline cBase. Also, combine declaration and initialization, i.e., int c=0,m=0.

Also, it looks like you've combined your test code with the function code that performs the logic.  The spec requires an input of a number/string of digits, and the output of an integer.  It would be fair to simply create a function that takes int parameter, and returns int parameter, without even a Main method, and call the character count your score.

@mellamokbtheWise - I learned something new. I always assumed the namespace was required. Also, good catch on the test array, that saves me some chars, and I am now actually answering the challenge.

C# with Linq 273
using System;using System.Linq;class P{static void Main(){int r,z,k=int.Parse(Console.ReadLine());if(k<=4) return;Console.WriteLine(Enumerable.Range(4, k).Select(x =>{r = 0;z = k;while (z > 0){if(z % x==4){r++;}z/=x;}return new[]{r, x};}).OrderBy(n => n[0]).Last()[1]);}}

or
using System;
using System.Linq;

class P
{
    static void Main()
    {
        int r, z, k = int.Parse(Console.ReadLine());
        if (k <= 4) return;
        Console.WriteLine(
            Enumerable.Range(4, k).Select(x =>
                {
                    r = 0;
                    z = k;
                    while (z > 0)
                    {
                        if (z % x == 4)
                        {
                            r++;
                        }
                        z /= x;
                    }
                    return new[] { r, x };
                }).OrderBy(n => n[0]).Last()[1]);

    }
}

Pretty sure the number of variables can be reduced and the if's can be converted to ?s. Oh well...

Burlesque - 28 bytes
Jbcjro{dg}Z]J{4CN}Cmsb[~Fi?i
Jbcjro                        create a list 1..input and convert input
                              to an infinite list.
      {dg}Z]                  convert number to base (zipWith operation)
            J                 duplicate
             {4CN}Cm          create comparison function
              4CN             count the number of fours.
                    sb        sort by
                      [~      take the last element (which is going to be
                              the base-n representation where count of fours
                              is highest)
                        Fi    Find the index of this last element in the original
                              unsorted list
                          ?i  increment (because base 1 is index 0)

Try it online.

there you go. (see the edit or click https://tio.run/##SyotykktLixN/a9jZmTy3yspOasovzolvTYq1qvaxNmv1jm3OCm6zi3TPvP/fwA)

Perl 6, 44 bytes
{max 5..$^a,by=>{grep 4,$a.polymod($_ xx*)}}

Try it online!
Good old polymod.

Husk, 9 bytes
S€►#4ṠMBḣ

Try it online!
 €           The 1-based index in
      MB     the list of the input's representations in every base
     Ṡ  ḣ    from 1 to itself
S ►          of its element which has the largest
   #         number of
    4        fours.

Julia, 50 bytes
n->sort(2:n+1,by=b->-sum(digits(n,base=b).==4))[1]

Try it online!

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Reducing Leibniz perl code in characters
This Perl code is supposed to calculate the Leibniz formula. The original problem is here.
The input format is:
T
<T test cases, each on their own line>

Each test case is a number < 10^7. The output format should be the same, minus the first line.
For example, an input:
2
10
20

And for output:
0.760459904732351
0.77290595166696

My first solutions, at 62 and 61 characters respectively.
for(1..<>){$s=0;map{$s+=($_&1||-1)/(2*$_-1)}1..<>;print"$s\n"}

for(1..<>){$s=0;$s+=($_&1||-1)/(2*$_-1)for 1..<>;print"$s\n"}

Edit: The best solution so far is 53 characters, by @teebee:
<>;print${\map$a-=(-1)**$_/(2*$_-1),1..$_},$a=$/for<>

possible duplicate of Calculate pi to 5 decimals

Why post the same question on two sites? I feel like it's either help or a puzzle, but not both. And as a puzzle it needs a puzzle-type ([tag:code-golf], [tag:coding-challenge]) and objective winning criteria.

I was recommended that this question belongs here more then stackoverflow so posted here.

Perl 55 bytes
<>;map($s-=(-1)**$_/(2*$_-1),1..$_),$s=!print$s,$/for<>

Without using any Perl non-standard features (such as say). 3 bytes are wasted removing the first value from the input.
Sample usage:
in.dat
2
10
20

$ perl leibniz.pl < in.dat
0.760459904732351
0.77290595166696

Alternative, also 55 bytes
map{$s-=(-1)**$_/($_*2-1)for 1..<>;$s=!print$s,$/}1..<>

The alternative may be run interactively, without requiring an input file. Which, as I understand, is what you meant by running indefinitely.

That goes in an infinite loop, but using this notation for for can save 2 more bytes map($s-=(-1)**$_/(2*$_-1),1..<>),$s=!print$s.$/for 1..<>

It will only cause an 'infinite' loop if the input given contains an infinite amount of lines. The for<> construction will iterate over every line in input passed to STDIN exactly once, without needing to 'know' beforehand how many there are.

Perl 53 bytes
You can save two more strokes:
<>;print${\map$a-=(-1)**$_/(2*$_-1),1..$_},$a=$/for<>

Very clever. One would expect \map... to return a single array reference, and not a list of scalar references.


text:
Finding the most 'unique' word
Using you language of choice, write the shortest function/script/program you can that will identify the word with the highest number of unique letters in a text.

Unique letters should include any distinct character using UTF-8 encoding.

Upper and lower case versions of the same character are different and distinct; 'a' != 'A'

Words are bound by any whitespace character.
'Letters' are any symbol which can be represented by a single unicode character.
The text document must be read in by your code -- no preloading/hard-coding of the text allowed.
The output should be the word, followed by the count of unique letters.

llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch - 18
Any delimiter/spacing between the two values is up to you, so long as there is at least one character to separate them.

In the event more than one word exists with the highest count, print all words for that count, with one new line delimiting.

superacknowledgement - 16
pseudolamellibranchiate - 16
This is code golf, so shortest code wins.

This answer on English.SE inspired me to create this challenge. The example uses just a word list, but any text should be able to be processed.

How are words separated?  You say unique letters are any UTF-8 character, but that would imply that the entire file is just one word.

@cardboard_box, my interpretation is that it's left flexible, so that you can decide to use code point 10 as a word separator, or code point 32, or treat any non-empty sequence of characters drawn from the 26 Unicode whitespace characters as a word separator.

@PeterTaylor Correct. I'll update the question to make note of the whitespace.

How are you defining letters here? As I've just been and pointed out on one of the English.SE answers LlanfairPG is a Welsh word and contains letters from the Welsh alphabet - ll and ch are both single letters in the Welsh language.

If the function is required to read the input, why require it be a (parameterless) function? It seems that a script would be more than adequate.

@Gareth I was not aware of that distinction, my mistake. Are there unicode representations of those two 'letters'? For the purposes of this challenge, each individual unicode character is a letter.

@Gaffi No, because they're easily represented as two characters from the english alphabet there's no point in having a separate Unicode character for them. I wasn't having a go - just wanted to be sure of what you meant by 'letter' if you mean Unicode character that's perfectly clear.

@primo Fair enough. Any code implementation will work - script, function, complete program, what have you - so long as the code reads in the text.

@Gareth That's all it is, Uni char. :-)

Can you clarify "The text document must be read in by your code"? Can the input/document be a function parameter? Do you expect us to load a filestream? What about a prompt box in javascript?

@Shmiddty All of the above are ok. Essentially, I meant for that rule to mean 'no cheating'. I intentionally left it vague, since I know some implementations will be smaller with reading STDIN vs. passing an argument vs. opening/scanning a text file.

One last question, do upper and lower-case characters count separately?

Yes, they are different and distinct. Updating question...

So abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+~\<>/\?'";:{}[],.` is a valid "word"?

Off-topic, but apparently there used to be single letters for LL and ll in Welsh. At least Unicode has U+1EFA and U+1EFB for those; "Middle-Welsh" it calls them. There is no titlecase Ll though.

@Shmiddty Yep, that's valid.

APL (56)
{⎕ML←3⋄⊃{⍵,⍴∪⍵}¨W[⍙]⍴⍨↑+/∆∘.=∆←∆[⍙←⍒∆←↑∘⍴∘∪¨W←⍵⊂⍨⍵≠' ']}

This is a function (question says that's allowed) that takes a string and returns a matrix of words and unique lengths.
Usage:
      {⎕ML←3⋄⊃{⍵,⍴∪⍵}¨W[⍙]⍴⍨↑+/∆∘.=∆←∆[⍙←⍒∆←↑∘⍴∘∪¨W←⍵⊂⍨⍵≠' ']}'The quick brown fox jumps over the lazy dog.'
quick 5
brown 5
jumps 5

Explanation:

⎕ML←3: set migration level to 3 (so that ⊂ is partition instead of enclose)
W←⍵⊂⍨⍵≠' ': store in W the given string, where each partition consists of non-whitespace characters.
⍙←⍒∆←↑∘⍴∘∪¨W: get the amount (⍴) of unique (∪) elements in each part (¨) of W, and store these in ∆, then get the sort order when sorted downwards on this (⍒) and store that in ⍙.
∆[⍙...]: sort ∆ by ⍙, so now we have the unique lengths in order.
∆∘.=∆←∆: store the sorted ∆ back in ∆, and see which elements of ∆ are equal.
↑+/: sum the rows (now we know how many elements are equal to each element) and then take the first item (now we know how many elements are equal to the first element, i.e. how many of the words are tied for first place.)
W[⍙]⍴⍨: sort W by ⍙, and take the first N, where N is the number we just calculated.
{⍵,⍴∪⍵}¨: for each of these, get the word itself and the amount of unique characters in the word
⊃: format as matrix

Perl 78 bytes
map{push$_[keys{map{$_,1}/./g}]||=[],$_}split for<>;print"$_ $#_
"for@{$_[-1]}

Interpretting the restriction "The text document must be read in by your code" to mean that command line options that read and parse the input are not allowed. As with the PHP solution below, only characters 10 and 32 are considered to be word delimiters. Input and output are also taken in the same manner.

PHP 128 bytes
<?foreach(split(~ßƒõ,fread(STDIN,1e6))as$s){$w[count(count_chars($s,1))][]=$s;}krsort($w)?><?=join($f=~ß.key($w).~õ,pos($w)),$f;

The only characters considered to be word delimiters are characer 10, and character 32. The rest, including puncuation, are considered to be part of the word.
This contains a few binary characters, which saves quotation marks, but as a result needs to be saved with an ANSI encoding in order to function properly. Alternatively, this version can be used, which is 3 bytes heavier:
<?foreach(split(' |
',fread(STDIN,1e6))as$s){$w[count(count_chars($s,1))][]=$s;}krsort($w)?><?=join($f=' '.key($w).'
',pos($w)),$f;

Sample I/O:
input 1:
It was the best of times, it was the worst of times, it was the age of wisdom,
it was the age of foolishness, it was the epoch of belief, it was the epoch of
incredulity, it was the season of Light, it was the season of Darkness, it was
the spring of hope, it was the winter of despair, we had everything before us,
we had nothing before us, we were all going direct to Heaven, we were all going
direct the other way - in short, the period was so far like the present period,
that some of its noisiest authorities insisted on its being received, for good
or for evil, in the superlative degree of comparison only.

output 1:
$ php most-unique.php < input1.dat
incredulity, 11

input 2:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis, nisl sit
amet consequat fringilla, justo risus iaculis justo, vel ullamcorper dui tellus
ut enim. Suspendisse lectus risus, molestie sed volutpat nec, eleifend vitae
ligula. Nulla porttitor elit vel augue pretium cursus. Donec in turpis lectus.
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia
Curae; Quisque a lorem eu turpis viverra sodales. Pellentesque justo arcu,
venenatis nec hendrerit a, molestie vitae augue.

output 2:
$ php most-unique.php < input2.dat
consequat 9
ullamcorper 9
Vestibulum 9

incredulity has 10 unique letters, not 11.

@DavidCarraher his code is including the comma, which is theoretically allowed via the rules.

The explanation is absolutely incredulous.

Not only is it 'theoretically allowed', but given the wording of the question (specifically points 2 and 3), it seems to be a requirement.

@DavidCarraher Yes, punctuation are valid characters. Anything other than whitespace is valid.

Mathematica 96 115
Edit: code now finds all words of the maximum number of characters. I refuse to treat commas as word characters.
f@t := With[{r = {#, Length@Union@Characters@#} & /@
StringSplit[t,RegularExpression@"\\W+"]},  Cases[r, {_, Max[r[[All, 2]]]}]]

Examples
f@"It was the best of times,...of comparison only."

or
f@Import["t1.txt"]

{{"incredulity", 10}, {"superlative", 10}}

f@"Lorem ipsum... vitae augue."

or
f@Import["t2.txt"]

{"Vestibulum", 9}

Longer Examples
f@Import["ShakespearesSonnets.txt"]
f@Import["OriginOfSpecies.txt"]
f@Import["DeclarationOfIndependence.txt"]
f@Import["DonQuixoteISpanish.txt"]
f@Import["AliceInWonderland.txt"]
f@Import["UNHumanRightsGerman.txt"]
f@Import["GenesisKJV.txt"]

Surprise: The most "unique" word in the Declaration of Independence is also the most unique word in Alice in Wonderland!

{"prognosticate", 11}
{"undiscoverable", 13}
{"uncomfortable", 12}
{"regocijadamente", 12}
{"uncomfortable", 12}
{"Verpflichtung", 13}
{"buryingplace", 12}

does this only return a single most-unique word? It should return them all. e.g. "superlative, incredulity, 10"

@Shmiddty I addressed your criticism. (It cost 19 bytes.)

I believe RegularExpression@"\\W+" can be replaced with WhitespaceCharacter for -4 bytes

Python 2 (110 (98 using file input))
import sys
f=lambda x:len(set(x))
a=sys.stdin.read().split()
c=max(map(f,a))
for i in a:
 if f(i)==c:print i,c

.
f=lambda x:len(set(x))
a=file('a').read().split()
c=max(map(f,a))
for i in a:
 if f(i)==c:print i,c

Things to improve: printing (33 characters)
Punctuation is considered letters.

Python 2.7.3: NameError: global name 'r' is not defined. After adding single quotes around the r: AttributeError: 'file' object has no attribute 'split'. Python 3.3.0: SyntaxError: invalid syntax 'print i,c'.

Oops, I didn't test it. Thanks for saying that, I would have never seen that. As for Python 3: doesn't work.

This is my first codegolf, I'm so excited :) Also that means it is probably not any good.
Groovy 127 117 112 105
Edit: Since functions seem to be allowed here is one in 105. I also renamed the variables to make the first column read ACDC, because that is important in any kind of source code:

A={e={it.toSet().size()}
C=it.text.tokenize()
D=e(C.max{e(it)})
C.grep{e(it)==D}.each{println"$it $D"}}

You would call it like that:

A(new File("words.txt"))

Without function using standard input in 112:
a={it.toSet().size()}
b=System.in.getText().tokenize()
c=a(b.max{a(it)})
b.grep{a(it)==c}.each{println "$it $c"}

a={it.toSet().size()}
b=System.in.getText().tokenize().sort{-a(it)}
c=a(b[0])
b.grep{a(it)==c}.each{println "$it $c"}

a={it.toSet().size()}
System.in.getText().tokenize().sort({-a(it)}).groupBy{a(it)}.take(1).each{k,v->v.each{println "$it $k"}}
Input: Lorem Ipsum Text from primo
All scripts output:
consequat 9
ullamcorper 9
Vestibulum 9

Anyone got an idea how to make them more groovy?

GoRuby 2.0.0 – 66 chars
The solutions below didn't actually find all matches but only one. Here's my final version:
a=$<.r.sp.m{|x|[x,x.ch.u.sz]};a.m{|x|s x*' - 'if x.l==a.m_(&:l).l}

Examples:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis,
  nisl sit amet consequat fringilla, justo risus iaculis justo, vel
  ullamcorper dui tellus ut enim. Suspendisse lectus risus, molestie sed
  volutpat nec, eleifend vitae ligula. Nulla porttitor elit vel augue
  pretium cursus. Donec in turpis lectus. Vestibulum ante ipsum primis
  in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque a
  lorem eu turpis viverra sodales. Pellentesque justo arcu, venenatis
  nec hendrerit a, molestie vitae augue.

produces:
$ ruby golf.rb < input.txt
consequat - 9
ullamcorper - 9
Vestibulum - 9

GoRuby 2.0.0 – 29 chars (not exact output format)
s$<.sp.m{|x|[x.ch.u.sz,x]}.mx

Expects input from stdin. The output format is a little bit different, though. For example:
$ ruby golf.rb < british.1
14
manoeuvrability

GoRuby 2.0.0 – 42 40 chars
s$<.r.sp.m{|x|[x.ch.u.sz,x]}.mx.rv*' - '

expects input from stdin
Ruby 1.9.3 - 69 65 chars
puts$<.read.split.map{|x|[x.chars.uniq.size,x]}.max.reverse*' - '

expects input from stdin (same as above, but without GoRuby abbreviations)

R - 106 characters
As a function with the input text as parameter:
f=function(t){
s=strsplit
a=sapply
t=s(t," ")[[1]]
w=a(a(s(t,""),unique),length)
n=(w==max(w))
cbind(t[n],w[n])
}

And a few examples:
f("It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way - in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.")
     [,1]           [,2]
[1,] "incredulity," "11"

f("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis, nisl sit amet consequat fringilla, justo risus iaculis justo, vel ullamcorper dui tellus ut enim. Suspendisse lectus risus, molestie sed volutpat nec, eleifend vitae ligula. Nulla porttitor elit vel augue pretium cursus. Donec in turpis lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque a lorem eu turpis viverra sodales. Pellentesque justo arcu, venenatis nec hendrerit a, molestie vitae augue.")
     [,1]          [,2]
[1,] "consequat"   "9"
[2,] "ullamcorper" "9"
[3,] "Vestibulum"  "9"

Or R - 100 characters
As a function with the path to the text file as parameter:
f=function(t){
t=scan(t,"")
a=sapply
w=a(a(strsplit(t,""),unique),length)
n=(w==max(w))
cbind(t[n],w[n])
}

Usage:
f("t1.txt")
Read 120 items
     [,1]           [,2]
[1,] "incredulity," "11"

I think this is missing "The text document must be read in by your code".

@StevenRumbalski this is corrected.

Husk, 19 13 16 15 14 bytes
Edit: -6 bytes by taking inspiration from Shaggy's Japt answer, but then +3 +2 +1 byte to scrupulously adhere to the output format (without surrounding parentheses and/or quotation marks)
mS+ȯΘs₁→k₁w
Lu

Try it online!
Lu                  # helper function: get the number of unique letters

¶m§,I₁→k₁w          # main program
¶                   # split result by newlines
 m                  # for each element of list
  §,I₁              # combine itself (I) with result of helper function
      →k₁w          # list:
      →             # last element of
       k w          # groups of words of input, grouped & sorted by
        ₁           # results of helper function

The output requirements may be a little archaic, but I don't think that this meets them.

@WheatWizard fixed for +3 bytes Edit +2

Javascript 163 155 152 162 bytes
This is about as short as I can get it:

prompt(x=[]).split(/\s/).forEach(function(a){b={};c=0;a.split('').forEach(function(d){b[d]?1:b[d]=++c});x[c]?x[c].push(a):x[c]=[a]});alert((l=x.length-1)+':'+x[l])
prompt(x=[]).split(/\b/).map(function(a){b={};c=0;a.split('').map(function(d){b[d]?1:b[d]=++c});x[c]?x[c].push(a):x[c]=[a]});alert((l=x.length-1)+':'+x[l])
prompt(x=[]).split(/\s/).map(function(a){b=[c=0];a.split('').map(function(d){b[d]?1:b[d]=++c});x[c]=(x[c]||[]).concat(a)});alert((l=x.length-1)+':'+x[l])

prompt(x=[]).split(/\s/).map(function(a){b=[c=0];a.split('').map(function(d){b[d]?1:b[d]=++c});x[c]=(x[c]||[]).concat(a)});alert((l=x.length-1)+':'+x[l].join('\n'))

In this version /\s/ separates words based on whitespace, so it includes punctuation, commas, periods, etc as part of words. This is easily changed to /\b/ to not included them.
I'll see what I can do with for-loops instead of forEaches in a bit.
I/O:

It was the best of times, it was the worst of times, it was the age of
  wisdom, it was the age of foolishness, it was the epoch of belief, it
  was the epoch of incredulity, it was the season of Light, it was the
  season of Darkness, it was the spring of hope, it was the winter of
  despair, we had everything before us, we had nothing before us, we
  were all going direct to Heaven, we were all going direct the other
  way - in short, the period was so far like the present period, that
  some of its noisiest authorities insisted on its being received, for
  good or for evil, in the superlative degree of comparison only.

11:incredulity,

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis,
  nisl sit amet consequat fringilla, justo risus iaculis justo, vel
  ullamcorper dui tellus ut enim. Suspendisse lectus risus, molestie sed
  volutpat nec, eleifend vitae ligula. Nulla porttitor elit vel augue
  pretium cursus. Donec in turpis lectus. Vestibulum ante ipsum primis
  in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque a
  lorem eu turpis viverra sodales. Pellentesque justo arcu, venenatis
  nec hendrerit a, molestie vitae augue.

9:consequat
ullamcorper
Vestibulum

A little tired, perhaps. But I feel peaceful. Your success in the ring
  this morning was, to a small degree, my success. Your future is
  assured. You will live, secure and safe, Wilbur. Nothing can harm you
  now. These autumn days will shorten and grow cold. The leaves will
  shake loose from the trees and fall. Christmas will come, and the
  snows of winter. You will live to enjoy the beauty of the frozen
  world, for you mean a great deal to Zuckerman and he will not harm
  you, ever. Winter will pass, the days will lengthen, the ice will melt
  in the pasture pond. The song sparrow will return and sing, the frogs
  will awake, the warm wind will blow again. All these sights and sounds
  and smells will be yours to enjoy, Wilbur—this lovely world, these
  precious days…

10:Wilbur—this

Nearly all children nowadays were horrible. What was worst of all was
  that by means of such organizations as the Spies they were
  systematically turned into ungovernable little savages, and yet this
  produced in them no tendency whatever to rebel against the discipline
  of the Party. On the contrary, they adored the Party and everything
  connected with it... All their ferocity was turned outwards, against
  the enemies of the State, against foreigners, traitors, saboteurs,
  thought-criminals. It was almost normal for people over thirty to be
  frightened of their own children.

15:thought-criminals.

There is a potential awkwardness with the output: if there are multiple words in the output and one of the words ends with a comma, it could show two commas in a row which would be confusing.

From the spec, In the event more than one word exists with the highest count, print all words for that count, **with one new line delimiting**.

@Gaffi should be fixed now. 10 bytes >.<

Scala 129 chars:
def f{
val l=readLine.split(" ").map(s=>(s,s.distinct.length)).sortBy(_._2)
println(l.filter(x=>x._2==l.last._2).mkString)}

Jelly, 13 bytes
QL
ḲÇÐṀ,ÇKƊ€Y

Try it online!
Just returning the number of unique characters is 6 bytes and just returning the words (no count), is 7 bytes.
How it works
QL - Helper link. Takes a string W on the left
Q  - Deduplicate W
 L - Length
     This returns the number of unique characters in W

ḲÇÐṀ,ÇKƊ€Y - Main link. Takes a string S on the left
Ḳ          - Split S on spaces
  ÐṀ       - Find the words for which the following is maximal:
 Ç         -   The number of unique characters
       Ɗ€  - Over each maximal word:
     Ç     -   Yield the number of unique characters
    ,      -   Pair with the word
      K    -   Join by spaces
         Y - Join by newlines

Japt v2.0a0 -hR, 11 bytes
Uses a comma as the delimiter.
¸®¸pZâ lÃüÌ

Try it
¸®¸pZâ lÃüÌ     :Implicit input of string            > "Finding the most unique word"
¸               :Split on spaces                     > ["Finding","the","most","unique","word"]
 ®              :Map each Z
  ¸             :  Split on spaces                   > [["Finding"],["the"],["most"],["unique"],["word"]]
   p            :  Push
    Zâ          :    Z deduplicated                  >   ["Findg","the","most","uniqe","word"]
       l        :    Length                          >   [5,3,4,5,4]
        Ã       :End map                             > [["Finding",5],["the",3],["most",4],["unique",5],["word",4]]
         ü      :Group & sort by
          Ì     :  Last element                      > [[["the",3]],[["most",4],["word",4]],[["Finding",5],["unique",5]]]
                :Implicit output of last element     > [["Finding",5],["unique",5]]
                :  joined with newlines              > "Finding,5\nunique,5"

does this print all words + counts if there's more-than-one with the same max unique letter count?  (the Japt website doesn't seem to work with my old browser, and the explanation implies that only (one) last element is output...)

Yes, @DominicvanEssen; the included test case, for example, outputs Finding,5\nunique,5. TIO doesn't support Japt v2 but here it is in the official interpreter: https://ethproductions.github.io/japt/?v=2.0a0&code=uK64cFriIGzD/Mw=&input=IkZpbmRpbmcgdGhlIG1vc3QgdW5pcXVlIHdvcmQiCi1oUg==

I'll update the explanation with a step-by-step momentarily

Got it - thanks!  (and the official interpreter link works for me, even with my antiquated browser...)

Updated with that step-by-step, @DominicvanEssen.

Great - and it's inspired me to discover the Husk k function, that seems to be similar to Japt ü!  Thanks again!

Python 176 168
w = "".join((open('c')).readlines()).replace("\n", " ").split(" ")
l = sorted(zip([len(set(w[i])) for i in range(len(w))],w,))
print([x for x in l if l[-1][0] == x[0]])

Python3 119
Reads from a file called a.
r={w:len(set(w))for w in open("a").read().split()};print("\n".join(str((k,v))for k,v in r.items()if v==max(r.values())))

Tested with the input texts from @primo:
Input 1:
    ('incredulity,', 11)

Input 2:
    ('Vestibulum', 9)
    ('consequat', 9)
    ('ullamcorper', 9)

Haskell, 85 bytes
k(a:b)=k(filter(/=a)b)-1
k[]=0
f x=unlines[y++show(k y)|y<-x,all((>=k y).k)x]
f.words

Try it online!
This employs one clever trick.  Instead of counting up the number of unique characters in each word, it counts down.  So hello yeilds \$-4\$ rather than \$4\$.  This allows us to use - as the delimter later which saves us a tiny bit.
With more lenient IO, 65 bytes
k(a:b)=1+k(filter(/=a)b)
k[]=0
f x=[(y,k y)|y<-x,all((<=k y).k)x]

Try it online!
20 bytes were spent just conforming to the archaic IO restrictions.  This takes a list of input words and outputs a list of tuples containing the word and the count.

Zsh, 77 bytes
for x;z=`fold -1<<<$x|sort|uniq|wc -l` m=$[z>m?z:m]&&echo $z $x>>p
grep ^$m p

Try it Online!
$z is a count of the unique letters in each word. $m is the maximum $z. We write each word and its count to file p, then grep for $m.
OG: 119 bytes using associative array.

JavaScript, 147 bytes
With map:
t=>(s='',m=new Map(),t.split(' ').map(w=>m.set(w,new Set(w).size)),d=[...m].sort((a,b)=>b[1]-a[1]),d.map(x=>x[1]==d[0][1]&&(s+=x.join('-')+`
`)),s)

With plain object
t=>(s='',m={},t.split(' ').map(w=>m[w]=new Set(w).size),d=Object.entries(m).sort((a,b)=>b[1]-a[1]),d.map(x=>x[1]==d[0][1]&&(s+=x.join('-')+`
`)),s)

Try it:

f=t=>(s='',m=new Map(),t.split(' ').map(w=>m.set(w,new Set(w).size)),d=[...m].sort((a,b)=>b[1]-a[1]),d.map(x=>x[1]==d[0][1]&&(s+=x.join('-')+`
`)),s)

console.log(f('It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way - in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.'));

console.log(f('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis, nisl sit amet consequat fringilla, justo risus iaculis justo, vel ullamcorper dui tellus ut enim. Suspendisse lectus risus, molestie sed volutpat nec, eleifend vitae ligula. Nulla porttitor elit vel augue pretium cursus. Donec in turpis lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque a lorem eu turpis viverra sodales. Pellentesque justo arcu, venenatis nec hendrerit a, molestie vitae augue.'));

console.log(f('A little tired, perhaps. But I feel peaceful. Your success in the ring this morning was, to a small degree, my success. Your future is assured. You will live, secure and safe, Wilbur. Nothing can harm you now. These autumn days will shorten and grow cold. The leaves will shake loose from the trees and fall. Christmas will come, and the snows of winter. You will live to enjoy the beauty of the frozen world, for you mean a great deal to Zuckerman and he will not harm you, ever. Winter will pass, the days will lengthen, the ice will melt in the pasture pond. The song sparrow will return and sing, the frogs will awake, the warm wind will blow again. All these sights and sounds and smells will be yours to enjoy, Wilbur—this lovely world, these precious days…'));

console.log(f('Nearly all children nowadays were horrible. What was worst of all was that by means of such organizations as the Spies they were systematically turned into ungovernable little savages, and yet this produced in them no tendency whatever to rebel against the discipline of the Party. On the contrary, they adored the Party and everything connected with it... All their ferocity was turned outwards, against the enemies of the State, against foreigners, traitors, saboteurs, thought-criminals. It was almost normal for people over thirty to be frightened of their own children.'));

Pip -p, 24 23 bytes
(a^:s(Y#*UQ*a)@*My)ZDNy

Try It Online!

Ooh, and then you can do a^:s(a...) -> (a^:s...) and save one more byte.

JavaScript, 76 71 bytes
s=>s.split` `.map(w=>(n=new Set(w).size)<s||[w,s=n]).filter(x=>x[1]==s)

Try it online!

Output needs to be a string unfortunately

Doesn't mention that anywhere in the spec, @Jacob.

Are you sure? I interpreted "Any delimiter/spacing between the two values is up to you, so long as there is at least one character to separate them." and "In the event more than one word exists with the highest count, print all words for that count, with one new line delimiting." as meaning that

Thunno N, \$ 29 \log_{256}(96) \approx \$ 23.87 bytes
A_ZiDedZULEZZz:zGAJzHAKerA_sj

Attempt This Online!
We can save a character if joining by a digit is allowed: Attempt This Online!
Explanation
A_Zi      # Split the (implicit) input by spaces        ["Finding", "the", "most", "unique", "word"]
    D     # Duplicate this list                         ["Finding", "the", "most", "unique", "word"], ["Finding", "the", "most", "unique", "word"]
     e    # Map over it:                                ["Finding", "the", "most", "unique", "word"]
      dZU #  Uniquify the string                         ["Findg", "the", "most", "uniqe", "word"]
L         #  And get the length                          [5, 3, 4, 5, 4]
 E        # (End map)                                   ["Finding", "the", "most", "unique", "word"], [5, 3, 4, 5, 4]
  ZZ      # Zip this with the split list                [[5, "Finding"], [3, "the"], [4, "most"], [5, "unique"], [4, "word"]]
    z:zG  # Sort and group by:                          [[3, "the"], [4, "most"], [4, "word"], [5, "Finding"], [5, "unique"]]
AJ        #  First element of each                       [3, 4, 4, 5, 5]
  zH      # (End group)                                 [[[3, "the']], [[4, "most"], [4, "word"]], [[5, "Finding"], [5, "unique"]]]
    AK    # Get the last element                        [[5, "Finding"], [5, "unique"]]
      e   # Map over it:                                [[5, "Finding"], [5, "unique"]]
       r  #  Reverse                                     [["Finding", 5], ["unique", 5]]
A_sj      #  And join by spaces                          ["Finding 5", "unique 5"]
          # (N flag joins by newlines)                  "Finding 5", "unique 5"
          # Implicit output

You can save 1 by joining by a digit instead of spaces, not sure if that's allowed though.

@Jacob yeah, I thought of that, but as there aren't any other answers doing that, I decided to leave it.

VBScript - 430 / VBA - 420
VBScript:
Function r(t)
d="Scripting.Dictionary"
Set w=CreateObject(d)
c=1
Do Until c>Len(t)
p=InStr(c,t," ")
i=InStr(c,t,vbCr)
If p<i Then s=i Else s=p
If s=0 Then s=Len(t)+1
f=Mid(t,c,s-c)
If Not w.Exists(f) Then
Set x=CreateObject(d)
For l=1 To Len(f)
n=Mid(f,l,1)
If Not x.Exists(n) Then x.Add n,n
Next
w.Add f,f
y=x.Count
If m=y Then z=f &vbCr &z
If m<y Then m=y:z=f
End If
c=s+1
Loop
r=z &" " &m
End Function

VBA:
Function r(t)
d="Scripting.Dictionary"
Set w=CreateObject(d)
c=1
Do Until c>Len(t)
p=InStr(c,t," ")
i=InStr(c,t,vbCr)
s=IIf(p<i,i,p)
If s=0 Then s=Len(t)+1
f=Mid(t,c,s-c)
If Not w.Exists(f) Then
Set x=CreateObject(d)
For l=1 To Len(f)
n=Mid(f,l,1)
If Not x.Exists(n) Then x.Add n,n
Next
w.Add f,f
y=x.Count
If m=y Then z=f &vbCr &z
If m<y Then m=y:z=f
End If
c=s+1
Loop
r=z &" " &m
End Function

Python 3, 88 bytes
lambda s:[(w,len({*w}))for w in s.split()if len({*w})==max(map(len,map(set,s.split())))]

Try it online!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/