@@ -22,7 +22,7 @@ func (em *ElevatorManager) OperateAllElevators() {
2222
2323func (em * ElevatorManager ) OperateElevator (elevator * Elevator ) {
2424 for { // infinte loop to keep elevator operating(real world scenario -> event can come any time)
25-
25+
2626 if len (elevator .Destinations ) == 0 {
2727 elevator .CurrentDirection = Still
2828 continue
@@ -47,8 +47,8 @@ func (em *ElevatorManager) DecideDirection(elevator *Elevator) {
4747 return
4848 }
4949
50- currentFloor := elevator .CurrentFloor
51- nearestDestination := elevator .Destinations [ 0 ]
50+ currentFloor := elevator .CurrentFloor // current floor of elevator
51+ nearestDestination := em . getNearestDestinationFloor ( currentFloor , elevator .Destinations ) // nearest request destination floor from current floor
5252 if nearestDestination > currentFloor {
5353 elevator .UpdateCurrentDirection (Up )
5454 em .MoveElevatorUp (elevator )
@@ -143,23 +143,23 @@ func (em *ElevatorManager) calculateDistance(elevator *Elevator, floor int, dire
143143 } else {
144144 // Request is behind → calculate distance after finishing current sweep
145145 if direction == Up {
146- farthest := elevator .FarthestDestination ()
147- return abs (farthest - currentFloor ) + abs (farthest - floor )
146+ farthest := elevator .HighestDestinationFloor ()
147+ return abs (farthest - currentFloor ) + abs (farthest - floor )
148148 } else { // Down
149- nearest := elevator .NearestDestination ()
150- return abs (currentFloor - nearest ) + abs (floor - nearest )
149+ nearest := elevator .LowestDestinationFloor ()
150+ return abs (currentFloor - nearest ) + abs (floor - nearest )
151151 }
152152 }
153153 }
154154
155155 // Case 3: Elevator moving in opposite direction
156156 if (currentDirection == Up && direction == Down ) || (currentDirection == Down && direction == Up ) {
157157 if currentDirection == Up {
158- farthest := elevator .FarthestDestination ()
159- return abs (farthest - currentFloor ) + abs (farthest - floor )
158+ farthest := elevator .HighestDestinationFloor ()
159+ return abs (farthest - currentFloor ) + abs (farthest - floor )
160160 } else { // Down
161- nearest := elevator .NearestDestination ()
162- return abs (currentFloor - nearest ) + abs (floor - nearest )
161+ nearest := elevator .LowestDestinationFloor ()
162+ return abs (currentFloor - nearest ) + abs (floor - nearest )
163163 }
164164 }
165165
@@ -173,3 +173,22 @@ func abs(x int) int {
173173 }
174174 return x
175175}
176+
177+ func (em * ElevatorManager ) getNearestDestinationFloor (currentFloor int , destinations []int ) int {
178+ if len (destinations ) == 0 {
179+ return 0
180+ }
181+
182+ nearest := destinations [0 ]
183+ minDistance := abs (currentFloor - nearest )
184+
185+ for _ , dest := range destinations {
186+ distance := abs (currentFloor - dest )
187+ if distance < minDistance {
188+ minDistance = distance
189+ nearest = dest
190+ }
191+ }
192+
193+ return nearest
194+ }
0 commit comments