Skip to content

Commit a1755d0

Browse files
committed
pb14
1 parent 208552f commit a1755d0

File tree

3 files changed

+48
-1
lines changed

3 files changed

+48
-1
lines changed

README.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,4 +206,15 @@ Given an integer k and a string s, find the length of the longest substring that
206206
For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb".
207207

208208
### Solution
209-
[JS](pb13/answer.js) (10:47)
209+
[JS](pb13/answer.js) (10:47)
210+
211+
---
212+
213+
## 14
214+
> This problem was asked by Google.
215+
216+
The area of a circle is defined as `πr²`. Estimate `π` to 3 decimal places using a Monte Carlo method.
217+
Hint: The basic equation of a circle is `x² + y² = r²`.
218+
219+
### Solution
220+
[Python](pb14/answer.py) (19:37)

pb14/Problem.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
> This problem was asked by Google.
2+
3+
The area of a circle is defined as `πr²`. Estimate `π` to 3 decimal places using a Monte Carlo method.
4+
Hint: The basic equation of a circle is `x² + y² = r²`.

pb14/answer.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#!/usr/bin/env python3
2+
# Time : 19:37
3+
4+
import math
5+
from random import random
6+
from PIL import Image
7+
from PIL import ImageDraw
8+
9+
# Square area = (2r)²
10+
# Circle area = π * r²
11+
# Cirle-Square area ratio = π / 4
12+
# So if you pick K random points in the square, K * π / 4 should be inside the circle
13+
# With L being the number of points inside the circle, whe have
14+
# π = 4M / K
15+
def approx_pi(nb_trials):
16+
inside_circle = 0
17+
img = Image.new('RGB', (500, 500), "white")
18+
draw = ImageDraw.Draw(img)
19+
for _ in range(nb_trials):
20+
21+
# Picks point at random in a 1 x 1 square
22+
x = random()
23+
y = random()
24+
# If the picked point lands in a r=1 circle
25+
if math.hypot(x, y) < 1:
26+
inside_circle +=1
27+
draw.point((int(x * 500), int(y * 500)), fill="blue")
28+
img.save('pi.png')
29+
print('π is approx.: ', round((4.0 * inside_circle / nb_trials), 3))
30+
31+
32+
approx_pi(10**6)

0 commit comments

Comments
 (0)