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

Suppose there are n balls in a circular tube that is 100 meters long. Initially, each ball is positioned at a specific distance from a starting point. The balls travel in different directions at a speed of 0.1 meters per second. When two balls meet, they collide and change their direction of travel. We need to find the total number of collisions that occur over 10^9 + 6 seconds.

Problem Analysis

The key insight is that balls moving in opposite directions will collide multiple times as they circle the tube. The collision count depends on:

  • Number of balls moving in each direction
  • Initial positions of adjacent balls
  • Total simulation time

Algorithm Steps

To solve this problem, we follow these steps:

  1. Sort the input array of initial positions
  2. Calculate base collisions: 2 × lap_count × (size/2) × (size - size/2)
  3. Add extra collisions for adjacent balls that are exactly 1 meter apart
  4. Return the total collision count

Implementation

def solve(input_array):
    input_array.sort()
    size = len(input_array)
    lap_count = (10**5) * 2  # Number of laps in the given time
    
    # Base collision calculation
    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  # Extra collisions for adjacent balls
                stop = 1
            else:
                stop = 0
        else:
            stop = 0
    
    return output

# Test with the given example
print(solve([0, 10]))
400000

Example Walkthrough

For the input [0, 10]:

  • Two balls at positions 0 and 10 meters
  • Assuming they move in opposite directions
  • Base collisions: 2 × 200000 × 1 × 1 = 400000
  • No additional collisions since balls aren't adjacent (difference ? 1)
  • Total collisions: 400000

Key Points

Component Value Description
Tube Length 100 meters Circular tube circumference
Ball Speed 0.1 m/s Constant speed for all balls
Simulation Time 10^9 + 6 seconds Total time for collision counting
Lap Count 200000 Number of complete laps

Conclusion

This solution calculates ball collisions in a circular tube by considering the base collision formula and adding extra collisions for adjacent balls. The algorithm efficiently handles large time periods by using mathematical formulas rather than simulation.

Updated on: 2026-03-25T20:28:16+05:30

324 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements