Quesiton:


Given a method

long compute(int i)
{
  return ...
}

The error rate p = 1 / 10,000


Another method

long total(int n)
{
  long s = 0;
  for (i = 0 ; i < n ; i ++)
  {
    s += compute(i);
  }
  return s;
}

Thus the error rate is np.


How to improve the second method to control its rate below p.


total will run n steps. So to make the total rate below p.

each step need to below p / n.


let's run compute k times when

(p ^ k < p / n).

long total(int n)
{
  int k = calcComputeTimes(n);
  
  long s = 0;
  for (int i = 0 ; i < n ; i++)
  {
    s += safeCompute(i, k);
  }
  return s;
}

// Find the min value of k when P^k < p/n
int calcComputeTimes(n)
{
  double temp = p / n;
  int k = 1;
  while(pow(P, k) >= temp)
  {
    k ++;
  } 
  return k;
}

// Runs compute() k times to find the most possible results.
// If the possible of two results are the same, return the first computed one.
double safeCompute(i, k)
{
  Map<Double, Integer> computeMap = new HashMap<>();
  int maxOccurSeen = 0;
  double result = 0;
  for (int t = 0 ; t < k ; t ++)
  {
    int r = compute(i);
    Integer occur = computeMap.get(r);
    if (occur == null)
    {
      occur = 1;
    }
    computeMap.put(r, occur);
    if (occur > maxoccurSeen)
    {
      maxOccurSeen = occur;
      result = r;
    }
  }
  return result;
}

static double P = 1 / 10,000;