aboutsummaryrefslogtreecommitdiff
path: root/week09/Exercise3/TrainNetwork.cpp
blob: cf9b6a96f6761cb2b7520bd0dc12666131f9b2a9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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;
}