# Program to check two spheres can ever meet by accelerating or not in a 3D space in Python

PythonServer Side ProgrammingProgramming

Suppose there are two spheres whose radius values are r1 and r2. They are at (x1, y1, z1) and (x2, y2, z2) coordinates. And their acceleration values are given like (ax1, ay1, az1) and (ax2, ay2, az2). We have to check whether these two spheres will ever meet on 3D space if they move with given acceleration or not.

So, if the input is like r1 = 1 r2 = 2 pos1 = (0, 0, 0) acc1 = (100,0,0) pos2 = (4, 0, 0) acc2 = (0,0,0), then the output will be True, because second sphere has no acceleration, so it will not move, but first one will move at x direction so they will collide.

To solve this, we will follow these steps −

• px := pos1 - pos2
• py := pos1 - pos2
• pz := pos1 - pos2
• ax := acc1 - acc2
• ay := acc1 - acc2
• az := acc1 - acc2
• da := ax * ax + ay * ay + az * az
• dp := px * px + py * py + pz * pz
• co := ax * px + ay * py + az * pz
• x := 0.0
• if da is not same as 0, then
• x := - co / da
• x := maximum of x, 0
• dis := square root of (da * x * x + 2 * co * x + dp)
• if dis −= r1 + r2, then
• return True
• otherwise return False

## Example

Let us see the following implementation to get better understanding −

def solve(r1, r2, pos1, acc1, pos2, acc2):
px, py, pz = pos1 - pos2, pos1 - pos2, pos1 - pos2
ax, ay, az = acc1 - acc2, acc1 - acc2, acc1 - acc2
da = (ax * ax + ay * ay + az * az)
dp = (px * px + py * py + pz * pz)
co = (ax * px + ay * py + az * pz)

x = 0.0
if da != 0:
x = - co / da
x = max(x, 0)
dis = (da * x * x + 2 * co * x + dp) ** 0.5
if dis <= r1 + r2:
return True
else:
return False

r1 = 1
r2 = 2
pos1 = (0, 0, 0)
acc1 = (100,0,0)
pos2 = (4, 0, 0)
acc2 = (0,0,0)
print(solve(r1, r2, pos1, acc1, pos2, acc2))

## Input

1, 2, (0, 0, 0), (100,0,0), (4, 0, 0), (0,0,0)

## Output

False