DEV Community

loading...
Cover image for Solving Joma Tech's favorite interview question

Solving Joma Tech's favorite interview question

albert_hadacek profile image Albert Hadacek ・2 min read

About a year ago Joma released a video where he shows his favorite interview question. The question is a bit tricky and requires the programmer to use some basic math and ingenuity. For me personally, it is one of the most beautiful examples of what we can do with code.

Let's dive into the question.

You have a function called random, that generates a number from 0 to 1 and it is uniformly distributed (in human language: chances of getting any number from the function are the same). Now, calculate the value of PI

As Joma mentions, this question resembles the "classic" mathy memes where the teacher gives you the price of an apple but wants you to calculate the speed of light.

To solve the question, we need to use a bit of geometry and equations. We know that we can extract PI (3.14) from the area of a circle which is PI*r^2. We can also create coordinates in 2D world calling our random function. If we can create coordinates, we can also calculate the distance from the center of the circle (0,0) to that point and see if the point is in the circle or outside.

Now we need to work with some math. As you can see, in the picture Joma provided, we can split our circle into 4 pieces so we only care about a single quadrant. We can now construct our equation which basically is Area of the Circle / Area of the square = Points in the Circle / All points. From that, we can extract PI using some simple math operations and we end discover, that PI should be 4 * the ratio of the points in the circle and all the points.

The last thing we need is to define our formula for the distance of the point to the center. If our radius is 1, the points where sqrt(x*x + y*y) is less than 1 have to be within the circle, all the other points must be outside.

Alt Text

Let's code it in JavaScript.


let inCount = 0;
let allCount = 0;

const numOfPoints = 10000

for (let i = 0; i < numOfPoints; i++) {
  const x = Math.random()
  const y = Math.random()
  const dist = Math.sqrt((x*x + y*y))

  if(dist < 1) {
    inCount++
  }

  allCount++
}


const pi = 4 * (inCount / allCount)

console.log(pi) // 3.1436 / 3.12 / 3.1528

Enter fullscreen mode Exit fullscreen mode

The more points we use, the more accurate estimation of PI we get. In our example, we used the built-in Math.random() method, which should provide approximately uniform distribution based on MDN.

What is your favorite coding problem?

Discussion (0)

pic
Editor guide