Tn = function(x) {
  n = length(x)
  s = 0
  for (i in 1:(n-1)) {
    for (j in (i+1):n) {
      s = s + 2*min(x[i], x[j]) - (x[i] + x[j])/2
    }
  }
  return(s/choose(n, 2)/mean(x))
}

alpha = 0.05
N = 10000
for (n in c(20, 50)) {
  # niz vrednosti test statistike pri nultoj hipotezi
  ts0  = rep(0, N)
  for (i in 1:N) {
    x = rexp(n)
    ts0[i] = sqrt(n)*Tn(x)
  }
  
  # mera testa ako se koristi granicna raspodela -> N(0, 1/3)
  c = qnorm(1 - alpha/2, 0, sd = sqrt(1/3))
  mera1 = 1 - ecdf(abs(ts0))(c)
  
  # mera testa ako se koristi empirijska nulta tablica
  ts_0_pom  = rep(0, N)
  for(i in 1:N) {
    x = rexp(n)
    ts_0_pom[i] = sqrt(n)*Tn(x)
  }
  c = quantile(ts_0_pom, 1 - alpha)
  mera2 = 1 - ecdf(abs(ts0))(c)
  
  # niz vrednosti test statistike pri alternativnoj hipotezi
  ts1 = rep(0, N)
  for (i in 1:N) {
    x = rgamma(n, 2, 1)
    ts1[i] = sqrt(n)*Tn(x)
  }
  
  # moc testa ako se koristi granicna raspodela
  c = qnorm(1 - alpha/2, 0, sd = sqrt(1/3))
  moc1 = 1 - ecdf(abs(ts1))(c)

  # moc testa ako se koristi empirijska nulta tablica
  c = quantile(ts_0_pom, 1 - alpha)
  moc2 = 1 - ecdf(abs(ts1))(c)
  
  print(c(mera1, mera2, moc1, moc2))
}
