# tournament analysis
best_p = .8 # probability of best team winning game; also strength
worst_p = c(.2,.4,.6) # prob worst team winning game
nb = 5000 # number of sims
np = 6 # number of teams to power of 2
best = matrix(0, np ,length(worst_p)) # results
worst = matrix(0, np ,length(worst_p)) # results
for (ib in 1:length(worst_p)){
for (i in 1:np){
N = 2^i # must be power of 2
p = seq(best_p, worst_p[ib], length.out= N)
bestwin = 0
worstwin = 0
for (j in 1:nb){
seed = sample(N) # random seeding
#seed = 1:N # position seeding; re-run
d = data.frame(teams = seed, p = p[seed])
for(k in log(N,2):1){ # rounds
M = 2^k
odds = seq(1,M - 1,2)
q = abs(d$p[odds]-d$p[odds+1])/2 + 1/2 # prob better team wins
wins = sign(q - runif(length(q))) # whether better team wins
order = sign(d$p[odds]-d$p[odds+1]) # is better team first/second?
betterteams = d$teams[odds] # order the games
betterteams[which(order<1)] = d$teams[odds+1][which(order<1)]
worseteams = d$teams[odds+1]
worseteams[which(order<1)] = d$teams[odds][which(order<1)]
teams = betterteams # who won?
teams[wins<1] = worseteams[wins<1]
d = data.frame(teams = teams, p = p[teams])
}
bestwin[j] = 1*(d$teams == 1) # if best team won
worstwin[j] = 1*(d$teams == N) # if worst team won
}
best[i,ib] = mean(bestwin)
worst[i,ib] = mean(worstwin)
}
}
jpeg("tournament_wins1.jpg",height=600,width=620,quality=85)
plot(1,1,type='n', axes=FALSE, xlab="Number of teams", ylab="Chance team wins", ylim=c(0.005,max(best)), xlim=c(2,2^np),log='xy',main="Random seeding",las=1)
for (i in 1:length(worst_p)){
lines(2^(1:np),best[,i],type='b',pch=i,col=i,lwd=2)
lines(2^(1:np),worst[,i],type='b',pch=i,col=i,lwd=2,lty=4)
}
lines(2^(1:np),1/2^(1:np),lty=3,col=5,lwd=2)
axis(1,2^(1:np))
axis(2,c(.001,.005,.05,.1,.2,.3,.4,.5,.6,.7,.8),cex.axis=.7,las=1)
legend(16,.6,best_p-worst_p,lty=1,pch=1:3,bty="n",col=1:3,lwd=2)
grid(10)
dev.off()