Imagine sorting a basket of laundry consisting of n pairs of socks, each of a different color. Randomly pulling out socks, one at a time, you will either put each on the sorting surface or match it up with its mate to make a pair and put them away in the sock drawer.
The maximum number of socks in the sorting space can then be any number from 1 to n. For example with 3 pairs, pulling them in the order AABBCC will only require one space, ABACCB requires two, and ABCABC will require three spaces.
Find the expected number of sorting spaces required in terms of n.
I was not able to come up with a heuristic way of looking at this to get a solution.
I did calculate some answers for several values of n, but I did not find a general formula.
My first attempt was an exhaustive search algorithm for n pairs of socks, which looks at (2n)! cases so it is rather inefficient. It's results:
n Expected value
1 2/2 1
2 40/24 5/3
3 1680/720 7/3
4 119424/40320 2.962
5 12967680/3628800 3.573
Direct exhaustive count too slow for n>5.
Next I did a randomized algorithm
Randomized program output:
1 1.0
2 1.66425
3 2.33391
4 2.95684
5 3.57884
6 4.16907
7 4.7632
8 5.34133
9 5.91856
10 6.4963
11 7.04952
12 7.61177
13 8.17568
14 8.72635
15 9.28324
16 9.82852
17 10.38886
18 10.93691
19 11.47587
20 12.03072
21 12.5694
22 13.10687
23 13.6544
24 14.18575
I tried using a spreadsheet to fit a polynomial to see if that would give a clue to the formula, but it was not very helpful.
--------------------
from itertools import permutations
import random
def socksort(n):
socks= [i for i in range(1,n+1)]*2
spaces = []
for p in permutations(socks):
stored = 0
maxstored = 0
table = []
for i,v in enumerate(p):
table.append(v)
for t in set(table):
if table.count(t) == 2:
table.remove(t)
table.remove(t)
stored -= 2
stored += 1
maxstored = max(maxstored,stored)
spaces.append(maxstored)
# print(p,maxstored)
return sum(spaces), len(spaces), sum(spaces) / len(spaces)
def sockrand(n, reps = 100000):
socks= [i for i in range(1,n+1)]*2
spaces = []
for i in range(reps):
random.shuffle(socks)
stored = 0
maxstored = 0
table = []
for i,v in enumerate(socks):
table.append(v)
for t in set(table):
if table.count(t) == 2:
table.remove(t)
table.remove(t)
stored -= 2
stored += 1
maxstored = max(maxstored,stored)
spaces.append(maxstored)
return sum(spaces) / len(spaces)
|
Posted by Larry
on 2023-09-30 12:16:26 |