1 linia pliku to liczba ktora przechowywana jest przez zmienna dataSets, 2 linia pliku(zmienna size1) oznacza liczbe elementow w linii 3(tablica A1),natomiast 4 linia(zmienna size2) liczbe elementow w linii 5(tablica A2). Linie od 2-5 wlacznie sa nadpisywane w petli w funkcji readFile, oraz dla elementow z tablic A2 i A1 funkcja countElementsInArray zwraca ilosc wystapien kolejnych elementow tablicy A2 w tablicy A1. Moj program staje kiedy pushuje wyniki do vectora o nazwie counts. To zadne zadanie ze spoja itp. Prosze o pomoc :)
txt:
3
4
-5 -1 0 8
7
7 9 2 0 -7 2 -5
4
1 2 3 4
2
1 1
5
0 0 0 0 0
1
3
Result for above input should be:
Dataset1:
0 0 0 1 0 0 1
Dataset2:
1 1
Dataset3:
0
int main() {
int dataSets = 0, size1 = 10, size2 = 10;
std::fstream file;
openFile(file);
int *A1 = new int[size1];
int *A2 = new int[size2];
readFile(file, dataSets, size1, size2, A1, A2);
}
void readFile(std::fstream &file, int &dataSets, int &size1, int &size2, int *&A1, int *&A2) {
std::vector<int> counts;
file >> dataSets;
for (size_t i = 0; i < dataSets; i++) {
file >> size1;
for (size_t j = 0; j < size1; j++)
file >> A1[j];
file >> size2;
for (size_t j = 0; j < size2; j++)
file >> A2[j];
for (size_t j = 0; j < size2; j++) {
int searchValue = A2[j];
counts.push_back(countElementsInArray(A1, size1, searchValue));
}
int numberOfDataSet = i + 1;
std::cout << "Dataset" << numberOfDataSet << ":" << std::endl;
for (size_t j = 0; j < size2; j++) {
std::cout << counts[j] << " ";
}
std::cout << std::endl;
}
}
int countElementsInArray(int *A, int size, int searchValue) {
int count = 0, first = 0, last = size;
int i = 1;
int j = 1;
while (first <= last) {
int mid = first + (last - 1) / 2;
if (A[mid] == searchValue) {
count++;
do {
if (A[mid + i] == searchValue && A[mid - j] == searchValue) {
count += 2;
i++;
j++;
} else if (A[mid + i] == searchValue) {
count++;
i++;
} else if (A[mid - j] == searchValue) {
count++;
j++;
}
return count;
} while (A[mid + i] == searchValue || A[mid - j] == searchValue);
} else if (searchValue < A[mid])
last = mid - 1;
else if (searchValue > A[mid])
first = mid + 1;
}
return count;
}