11package com .thealgorithms .simulation ;
22
3+ /**
4+ * NRobotsCollision simulates the movement of N robots on a 1D line and determines
5+ * the earliest time at which any two robots collide.
6+ *
7+ * <p>Each robot has an initial integer position and a direction of movement
8+ * ('R' for right, 'L' for left). All robots move simultaneously at the same speed.
9+ * A collision occurs when a right-moving robot and a left-moving robot meet.
10+ * The time of collision between two adjacent (in sorted order) robots moving toward
11+ * each other is half the distance between them.
12+ *
13+ * <p>If no two robots ever collide, the method returns -1.
14+ */
315public class NRobotsCollision {
16+ /**
17+ * Pair holds a robot's position and its direction of movement.
18+ */
419 static class Pair {
520 int first ;
621 char second ;
@@ -9,6 +24,19 @@ static class Pair {
924 this .second = second ;
1025 }
1126 }
27+ /**
28+ * Finds the earliest time at which any two robots collide.
29+ *
30+ * <p>Robots are sorted by position. A collision can only happen between a robot
31+ * moving right ('R') and the next robot (in sorted order) moving left ('L').
32+ * The collision time for such a pair is {@code (posL - posR) / 2}.
33+ *
34+ * @param n the number of robots
35+ * @param positions an array of initial positions of the robots
36+ * @param directions a string where each character is 'L' or 'R', representing
37+ * the direction of the corresponding robot
38+ * @return the earliest collision time, or -1 if no collision occurs
39+ */
1240 public static int earliestCollisionTime (int n , int [] positions , String directions ) {
1341 List <Pair > sortedDirections = new ArrayList <>();
1442 for (int i = 0 ; i < n ; i ++){
0 commit comments