# Python Program to find out how many times the balls will collide in a circular tube

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose, there are n balls in a circular tube. The tube is 100 meters long and initially, each ball in the tube is i meters away from a point that we call the starting point. Now the balls start to travel within the tube in a circular order in different directions. The balls travel 0.1 meters per second within the tube. When two balls meet at a point, a collision occurs and the balls change their direction of travel. If this process goes for a long time, let's say 10^9 + 6 seconds; we have to find out the number of times the balls engage in a collision. The initial distance of the balls from the starting point is given as input.

So, if the input is like input_array = [0, 10], then the output will be 400000

There are two balls, and their initial distance from the starting line is given to us as input. If their directions are the same, they will never engage in a collision. But, if their directions are different, they will collide in times. One ball will collide with another exactly 400000 times.

To solve this, we will follow these steps −

• sort the list input_array
• size := size of input_array
• lap_count := (10^5)*2
• output := 2 * lap_count * floor value of (size / 2) * (size - floor value of (size / 2))
• stop := 0
• for i in range 0 to size - 1, do
• if stop is not same as 1, then
• if input_array[i] + 1 is same as input_array[i+1], then
• output := output + 2
• stop := 1
• otherwise,
• stop := 0
• otherwise,
• stop := 0
• return output

## Example

Let us see the following implementation to get better understanding −

Live Demo

def solve(input_array):
input_array.sort()
size = len(input_array)
lap_count = (10**5)*2
output = 2*lap_count*(size//2)*(size - size//2)
stop = 0
for i in range(size - 1):
if stop != 1:
if input_array[i] + 1 == input_array[i+1]:
output+=2
stop = 1
else:
stop = 0
else:
stop = 0
return output
print(solve([0, 10]))

## Input

[0, 10]

## Output

400000
Updated on 18-May-2021 06:02:48