Here's another freebie, but I am not really sure how to solve it. Guess I wouldn't be getting that job at Google :)

This problem was asked by Google.

The area of a circle is defined as πr^2. Estimate π to 3 decimal places using a Monte Carlo method.

Hint: The basic equation of a circle is x2 + y2 = r2.

c++ solution 

@Absinthe Even worse overengineering than previously: gitlab.com/tymorl/warmups/blob .

I think the most interesting part is the stopping condition. I arrived at it by a mix of trial-and-error and intuition. The intuition was just "the square is needed, because something something statistics", so pretty bad. If anyone knows what the stopping condition should be I am all ears.

c++ solution 

@timorl while discussing this with an associate, he suggested waiting for a place to 'calm down'. In general you would keep going until it stopped mirroring and that might be as far as it might be able to go

c++ solution 

@Absinthe But then how many points should I add between checks whether it calmed down? If I add only one point, then it "calms down" as soon as I generated about 1k points, which is much too early. Although maybe I'm missing something.

c++ solution 

@timorl something that comes to the eye, since you are constructing your point with the same function calls, why not make that part of the constructor as defaults? Something like :

Point(long double ix = dis(gen), long double iy = dis(gen))

Then you have the option of calling
Point().inCircle(); without creating unnecessary extra doubles.

If you return 1 or 0 instead of boolean, then you can simply :

inCircle += Point.inCircle();

Not sure if any of that makes too much difference. But I figured I would mention.

c++ solution 

@Absinthe Both of these are not EnterpriseSolutions™ and I like keeping my code EnterpriseGrade™, especially when writing c++. The first one would require giving Point access to dis and gen, which is hard to do without making them global variables or something and the latter... well, if something is a test it should return a boolean.

More seriously, yours are good suggestions for writing solutions in general, but if I wanted to do that I wouldn't make any classes at all, just a couple functions.

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.