package edu.bloomu.ch7b;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
@author
public class RandomizedPlaylist {
public static void main(String[] args) {
System.out.print("How many songs on the playlist? ");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
final int trials = 1_000_000;
int total = 0;
for (int i = 0; i < trials; i++) {
total += playSongs(n);
}
int result = total / trials;
String out = "Expected number of songs played before one is repeated: %d%n";
System.out.printf(out, result);
}
@param n
@return
private static int playSongs(int n) {
boolean[] alreadyPlayed = new boolean[n];
int numSongs = 0;
ThreadLocalRandom rand = ThreadLocalRandom.current();
while (true) {
int k = rand.nextInt(n);
if (alreadyPlayed[k]) {
return numSongs;
}
alreadyPlayed[k] = true;
numSongs++;
}
}
}