Calculate probability of getting half as many heads as coin tosses.

10

Write a program that, given a small positive even integer from standard input, calculates the probability that flipping that many coins will result in half as many heads.

For example, given 2 coins the possible outcomes are:

HH HT TH TT

where H and T are heads and tails. There are 2 outcomes (HT and TH) that are half as many heads as the number of coins. There are a total of 4 outcomes, so the probability is 2/4 = 0.5.

This is simpler than it looks.

Test cases:

2 -> 0.5
4 -> 0.375
6 -> 0.3125
8 -> 0.2734375

david4dev

Posted 2011-02-27T17:07:12.710

Reputation: 665

1We can assume the coins are perfect and there's an even chance of getting heads or tails? – Juan – 2011-02-27T17:18:36.313

Do we need to print the output to stdout? – Wile E. Coyote – 2011-02-27T18:24:49.303

@Juan yes. @Dogbert yes. – david4dev – 2011-02-27T18:37:16.063

Could we get some more test cases to verify our solutions? – Wile E. Coyote – 2011-02-27T19:44:35.257

@Dogbert - done – david4dev – 2011-02-27T20:02:35.753

Does the output have to be actually printed out or is computing enough? I've got a couple of answers I could shave characters from if I migrated from complete program to interactive session. – J B – 2011-03-02T08:29:10.117

Answers

3

J, 22 19 (killer approach)

I got down to this while golfing my Haskell answer.

%/@:>:@i.&.(".@stdin)_

(same I/O as my other J answer)

J B

Posted 2011-02-27T17:07:12.710

Reputation: 9 638

This gives an error for me: 0 1|domain error: script | %/ >:i.&.(".@stdin)_ – david4dev – 2011-03-01T17:22:03.687

@david4dev Ouch. My leftover script file didn't work either. I don't remember where I messed up, but the version you tested is faulty indeed. It's now fixed. – J B – 2011-03-01T17:46:22.623

3

Pari/GP - 32 30 34 chars

print(binomial(n=input(),n\2)/2^n)

Wile E. Coyote

Posted 2011-02-27T17:07:12.710

Reputation: 943

32 characters: print(binomial(n=input,n\2)/2^n). – Charles – 2015-04-28T14:49:47.217

Wow, I didn't consider a programming language having a built in binomial function. – david4dev – 2011-02-27T18:38:15.003

3

Python 53 Characters

i=r=1.;exec"r*=(2*i-1)/i/2;i+=1;"*(input()/2);print r

fR0DDY

Posted 2011-02-27T17:07:12.710

Reputation: 4 337

3

Haskell, 39 43 46

main=do x<-readLn;print$foldr1(/)[1..x]

Demonstration:

$ runhaskell coins.hs <<<2
0.5
$ runhaskell coins.hs <<<4
0.375
$ runhaskell coins.hs <<<6
0.3125
$ runhaskell coins.hs <<<8
0.2734375

J B

Posted 2011-02-27T17:07:12.710

Reputation: 9 638

I think main=do x<-readLn;print$foldr1(/)[1..x] does the same thing and saves 3 bytes? – Lynn – 2015-05-17T20:57:36.457

Indeed. Merging, thanks! – J B – 2015-05-27T21:30:56.137

I get an error: Undefined variable "readln" – david4dev – 2011-02-28T16:42:51.887

@david4dev the 'L' in readLn is a capital one. – J B – 2011-02-28T16:54:16.063

3

Excel, 25

Not quite according to spec, though :)

Name a cell n and then type the following into another cell:

=COMBIN(n,n/2)/POWER(2,n)

Joey

Posted 2011-02-27T17:07:12.710

Reputation: 12 260

2Excel actually implements the ^ properly, so you can cut out a few characters that way. – SuperJedi224 – 2015-06-08T20:40:25.437

2

Golfscript - 30 chars

Limitation - only works for inputs less than 63

'0.'\~..),1>\2//{{*}*}%~\/5@?*

test cases

$ echo 2 | ruby golfscript.rb binom.gs 
0.50
$ echo 4 | ruby golfscript.rb binom.gs 
0.3750
$ echo 6 | ruby golfscript.rb binom.gs 
0.312500
$ echo 8 | ruby golfscript.rb binom.gs 
0.27343750

Analysis

'0.' GS doesn't do floating point, so we'll fake it by writing an integer after this
\~ Pull the input to the top of the stack and convert to an integer
.. Make 2 copies of the input
),1>Create a list from 1..n
\2//Split the list into 1..n/2 and n/2+1..n
{{*}*}%Multiply the elements of the two sublists giving (n/2)! and n!/(n/2)!
~Extract those two numbers onto the stack
\Swap the two numbers around
/Divide
5@?*Multiply by 5**n. This is the cause of the limitation given above

gnibbler

Posted 2011-02-27T17:07:12.710

Reputation: 14 170

I'm curious as to why the limitation. Are you using Gosper's hack to generate all the combinations? The idea occurred to me (and the spec doesn't say anything about execution time). – Peter Taylor – 2011-02-28T12:05:27.700

Golfscript doesn't have a float point variable class, so what he does is calculate an integer that written after the string 0. is the decimal part of the answer, but that method leaves out the required 0 when the chance grows less than 10%. – aaaaaaaaaaaa – 2011-02-28T14:30:00.267

@Peter, what eBusiness said :) – gnibbler – 2011-02-28T23:45:30.790

2

J, 25 (natural approach)

((!~-:)%2&^)&.(".@stdin)_

Sample use:

$ echo -n 2 | jconsole coins.ijs 
0.5
$ echo -n 4 | jconsole coins.ijs
0.375
$ echo -n 6 | jconsole coins.ijs
0.3125
$ echo -n 8 | jconsole coins.ijs 
0.273438

It's all self-explanatory, but for a rough split of responsibilities:

  • !~ -: could be thought of as binomial(x,x/2)
  • % 2&^ is "divided by 2^x"
  • &. (". @ stdin) _ for I/O

J B

Posted 2011-02-27T17:07:12.710

Reputation: 9 638

2

GNU Octave - 36 Characters

disp(binopdf((n=input(""))/2,n,.5));

Juan

Posted 2011-02-27T17:07:12.710

Reputation: 2 738

2

Ruby, 39 characters

p 1/(1..gets.to_i).inject{|a,b|1.0*b/a}

Ventero

Posted 2011-02-27T17:07:12.710

Reputation: 9 842

2

TI-BASIC, 10

This will take more than ten bytes of calculator memory because there is a program header, but there are only ten bytes of code.

binompdf(Ans,.5,.5Ans

//Equivalently:

2^~AnsAns nCr (.5Ans

This takes input in the form [number]:[program name]; adding an Input command uses three more bytes. ~ is the unary minus token.

lirtosiast

Posted 2011-02-27T17:07:12.710

Reputation: 20 331

1

Ruby - 50 57 54 chars

p (1..(n=gets.to_i)/2).reduce(1.0){|r,i|r*(n+1-i)/i/4}

Wile E. Coyote

Posted 2011-02-27T17:07:12.710

Reputation: 943

This calculates nCr not the probability. – david4dev – 2011-02-27T19:24:54.420

@david4dev, fixed. – Wile E. Coyote – 2011-02-27T19:52:07.623

1

J, 20

f=:(]!~[:<.2%~])%2^]

examples:

f 2
0.5
f 4
0.375
f 6
0.3125
f 8
0.273438

Eelvex

Posted 2011-02-27T17:07:12.710

Reputation: 5 204

The question asks for input from STDIN, not a function. – Wile E. Coyote – 2011-02-28T10:26:13.240

@Dogbert: I know; I forgot to mention this. I intended to update it... – Eelvex – 2011-02-28T10:37:48.457

1

APL 21 15 chars

((N÷2)!N)÷2*N←⎕

For where it doesn't render right

((N{ColonBar}2)!N){ColonBar}2*N{LeftArrow}{Quad}

Where everything in {} are APL specific symbols like here.

jpjacobs

Posted 2011-02-27T17:07:12.710

Reputation: 3 440

Is the last character supposed to be a square? – J B – 2011-02-28T19:43:12.170

Yes it should be the quad symbol. – jpjacobs – 2011-02-28T19:46:29.127

I get �[token]: � undefined – david4dev – 2011-03-01T17:31:19.403

I guess this is a coding issue. In NARS2000 you can copy paste it as is.

– jpjacobs – 2011-03-05T11:42:57.583

1

Windows PowerShell, 45

($p=1)..($n="$input"/2)|%{$p*=(1+$n/$_)/4}
$p

Meh.

Joey

Posted 2011-02-27T17:07:12.710

Reputation: 12 260

1

MATLAB, 29

n=input('');binopdf(n/2,n,.5)

Memming

Posted 2011-02-27T17:07:12.710

Reputation: 163

0

PostScript, 77

([)(%stdin)(r)file token{2 idiv}if def
1
1 1[{[exch div 1 add 4 div mul}for
=

Joey

Posted 2011-02-27T17:07:12.710

Reputation: 12 260

0

Mathematica, 19

f=2^-# #!/(#/2)!^2&

Tally

Posted 2011-02-27T17:07:12.710

Reputation: 387

0

Javascript, 86 bytes

a=prompt(f=function(n){return n?n*f(n-1):1});alert(f(a)/(f(a/2)*f(a/2)*Math.pow(2,a)))

SuperJedi224

Posted 2011-02-27T17:07:12.710

Reputation: 11 342

0

Python 3, 99

This is a naive approach, I suppose, and fR0DDY's solution is much cooler, but at least I am able to solve it.

Try it here

from itertools import*
n=int(input())
print(sum(n/2==i.count("H")for i in product(*["HT"]*n))/2**n)

Python 2, 103

from itertools import*
n=int(raw_input())
print sum(n/2==i.count("H")for i in product(*["HT"]*n))/2.**n

mbomb007

Posted 2011-02-27T17:07:12.710

Reputation: 21 944

0

Objective-C:

152 148 bytes for just the function.

Class methods, headers, and UI are not included within the code.

Input: an int value determinining the number of coins.

Output: a float value determining the probability.

-(float)calcPWithCoins:(int)x {int i=0;int j=0;for (int c=x;c<1;c+-){i=i*c;} for(int d=x/2;d<1;d+-){j=j*d;} return (((float)i/(float)j)/powf(2,x));}

Ungolfed:

-(float)calcPWithCoints:(int)x
{
    int i = 0;
    int j = 0;
    for (int c = x; c < 1; c+-) {
         i = i * c;
    }
    // Calculate the value of x! (Factorial of x)

    for (int d = x / 2; d < 1; d+-)
         j = j * d;
    }
    // Calculate (x/2)! (Factorial of x divided by 2)

    return (((float)i / (float)j) / powf(2, x));
    /* Divides i! by (i/2)!, then divides that result (known as the nCr) by 2^x.
    This is all floating-point and precise. If I didn't have casts in there,
    It would be Integer division and, therefore, wouldn't have any decimal
    precision. */
}

This is based off of the Microsoft Excel answer. In C and Objective-C, the challenge is in hard-coding the algorithms.

DDPWNAGE

Posted 2011-02-27T17:07:12.710

Reputation: 276