thewitchking

Untitled

Jul 17th, 2025
352
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. struct Ant {
  6.     int position;
  7.     int direction; // -1 for left, 1 for right
  8. };
  9.  
  10. int timeUntilAllFall(int plankSize, std::vector<int> left, std::vector<int> right) {
  11.     std::vector<Ant> ants;
  12.  
  13.     // Initialize ants
  14.     for (int pos : left) ants.push_back({pos, -1});
  15.     for (int pos : right) ants.push_back({pos, 1});
  16.  
  17.     int time = 0;
  18.  
  19.     while (!ants.empty()) {
  20.         time++;
  21.  
  22.         // Move all ants
  23.         for (auto& ant : ants) {
  24.             ant.position += ant.direction;
  25.         }
  26.  
  27.         // Handle collisions — if two ants are on the same position, switch direction
  28.         for (int i = 0; i < ants.size(); ++i) {
  29.             for (int j = i + 1; j < ants.size(); ++j) {
  30.                 if (ants[i].position == ants[j].position) {
  31.                     ants[i].direction *= -1;
  32.                     ants[j].direction *= -1;
  33.                 }
  34.             }
  35.         }
  36.  
  37.         // Remove ants that fall off the plank
  38.         ants.erase(std::remove_if(ants.begin(), ants.end(),
  39.                                   [plankSize](const Ant& ant) {
  40.                                       return ant.position < 0 || ant.position > plankSize;
  41.                                   }),
  42.                    ants.end());
  43.     }
  44.  
  45.     return time;
  46. }
  47.  
  48. int main() {
  49.     int plankSize = 10;
  50.     std::vector<int> left = {4, 7};
  51.     std::vector<int> right = {2, 5};
  52.  
  53.     int totalTime = timeUntilAllFall(plankSize, left, right);
  54.     std::cout << "Time until all ants fall off: " << totalTime << " seconds\n";
  55.  
  56.     return 0;
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment