Sunday, July 26, 2015

The Sock Drawer Problem

SockDrawer

The Sock Drawer Problem

Problem 1 from Fifty Challenging Problems in Probability by Frederick Mosteller

"A drawer contains red socks and black socks. When two socks are drawn at random, the probability that both are red is $\frac{1}{2}$.   (a) How small can the number of socks in the drawer be?   (b) How small if the number of black socks is even?"

In [1]:
# Initialize with 2 red socks and 1 black sock.
Red=2
Black=1

# define a tolerance factor
tol=1e-5

# Drawer Capacity (limits the search space)
cap=100

def prDraw2Red(r,b):
    '''
        Function returns the prob of drawing two red socks.  
        args: (num red socks, num black socks)
    '''
    pr1=float(r)/(r+b)         # probability first sock drawn out is red
    pr2=float(r-1)/((r-1)+b)   # probability second sock is red, given first was red
    return pr1*pr2             # probability both red

P=prDraw2Red(Red,Black)
Total=Red+Black

while abs(P-0.5)>tol and Total<cap:
    if P < 0.5:
        Red+=1
    else:
        Black+=1
    P=prDraw2Red(Red,Black)
    Total=Red+Black

print " Red =", Red, " Black =", Black, " Prob =", P, " Total Socks =", Total
 Red = 3  Black = 1  Prob = 0.5  Total Socks = 4