Katkat

Approximate Pi from Random Points

TomaFrontend Engineer · Technical Screen

Last updated

This question evaluates a candidate's understanding of Monte Carlo estimation, basic Euclidean geometry, probability, and numerical reasoning when using random sampling to approximate mathematical constants.

You are given an array pts of points in the unit square. Each point is represented as an array of two numbers [x, y], where 0 <= x <= 1 and 0 <= y <= 1.

A point lies inside the quarter circle of radius 1 if x*x + y*y <= 1.

Write a function approx(pts) that returns an approximation of pi using the fraction of points that fall inside the quarter circle.

Assume:

  • pts is never null
  • pts contains at least one point
  • every point has exactly two numeric coordinates

Example function signature:

function approx(pts) {
 return 0;
}