diff options
| author | Syndamia <kamen@syndamia.com> | 2024-05-07 22:17:32 +0300 |
|---|---|---|
| committer | Syndamia <kamen@syndamia.com> | 2024-05-07 22:17:32 +0300 |
| commit | cbd6d3aa606b18dde3f203e6edfab04935bbbd59 (patch) | |
| tree | ca4288a359e7061ce74f16f3e8f05f7d40ade95f /week09/Exercise3/TrainNetwork.cpp | |
| parent | 88f15e35713c9632216931d26443dc588238732f (diff) | |
| download | oop-2023-solutions-cbd6d3aa606b18dde3f203e6edfab04935bbbd59.tar oop-2023-solutions-cbd6d3aa606b18dde3f203e6edfab04935bbbd59.tar.gz oop-2023-solutions-cbd6d3aa606b18dde3f203e6edfab04935bbbd59.zip | |
[w9] Added rough solution to ex 3
Diffstat (limited to 'week09/Exercise3/TrainNetwork.cpp')
| -rw-r--r-- | week09/Exercise3/TrainNetwork.cpp | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/week09/Exercise3/TrainNetwork.cpp b/week09/Exercise3/TrainNetwork.cpp new file mode 100644 index 0000000..cf9b6a9 --- /dev/null +++ b/week09/Exercise3/TrainNetwork.cpp @@ -0,0 +1,73 @@ +#include "TrainNetwork.h" +#include <cstring> +#include <fstream> + +bool TrainNetwork::HaveCollided(int index1, int index2) { + if (trains[index1].railID != trains[index2].railID) { + return false; + } + if (strcmp(trains[index1].currentRegion, trains[index2].currentRegion) != 0) { + return false; + } + + std::ifstream regionFile(trains[index1].regionsFileName); + if (!regionFile.is_open()) { + throw "Couldn't open region file!"; + } + + // Обикаляме файла от края към началото и сравняваме всяка буква със съответната от сегашния регион + // Тоест сравняваме последния ред във файла със сегашния + regionFile.seekg(-1, std::ios::end); // Често текстови редактори слагат едно \n в края на файла, затова го пропускаме + // Това и да го направите и да не го е все едно + int regionIndex = strlen(trains[index1].currentRegion) - 1; + while (!regionFile.fail() && regionFile.peek() != '\n' && regionIndex >= 0) { + // Щом последния ред (последната локация) се различава от сегашната, то + // сегашната ще се намира някъде другаде във файла и ще има колизия + if (regionFile.peek() != trains[index1].currentRegion[regionIndex]) { + regionFile.close(); + return true; + } + regionIndex--; + regionFile.seekg(-1, std::ios::cur); + } + + bool lastLineEqualsCurrent = (regionFile.tellg() == -1 || regionFile.peek() == '\n') && regionIndex == 0; + regionFile.close(); + + return !lastLineEqualsCurrent; +} + +int TrainNetwork::RunTrains() { + bool anyMovedForward = true; + while (anyMovedForward) { + anyMovedForward = false; + + for (int i = 0; i < 512; i++) { + if (collided[i]) continue; + + for (int j = 0; j < 512; j++) { + if (collided[j] || j == i) continue; + + if (HaveCollided(i, j)) { + collided[i] = collided[j] = true; + break; + } + } + + if (collided[i]) continue; + + try { + trains[i].TransferNextRegion(); + anyMovedForward = true; + } + catch (int error) { + } + } + } + + int sum = 0; + for (int i = 0; i < 512; i++) { + sum += collided[i]; + } + return sum; +} |
