Skip to content

Instantly share code, notes, and snippets.

@joriki
Created June 14, 2016 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joriki/6459d82d15868697120b87e7572a22ad to your computer and use it in GitHub Desktop.
Save joriki/6459d82d15868697120b87e7572a22ad to your computer and use it in GitHub Desktop.
Simulate coupon collection with trading of doubles; see http://math.stackexchange.com/questions/1825418.
import java.util.Random;
public class Question1825418 {
final static int ntrials = 1000000;
final static int n = 10000;
final static Random random = new Random ();
public static void main (String [] args) {
long count = 0;
for (int i = 0;i < ntrials;i++) {
int nmissing = n;
int ndouble = 0;
int npairs = 0;
while (npairs != nmissing) {
int next = random.nextInt (n);
if (next < nmissing)
nmissing--;
// nsingle++;
else if (next < nmissing + ndouble) {
ndouble--;
npairs++;
// nsingle++;
}
else
// nsingle--;
ndouble++;
count++;
}
}
System.out.println (count / (double) ntrials);
count = 0;
for (int i = 0;i < ntrials;i++) {
int nmissing = n;
int ndouble = 0;
while (nmissing != 0) {
int next = random.nextInt (n);
if (next < nmissing)
nmissing--;
// nsingle++;
else if (next < nmissing + ndouble) {
ndouble--;
nmissing--;
// nsingle += 2;
}
else
// nsingle--;
ndouble++;
count++;
}
}
System.out.println (count / (double) ntrials);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment