2
I need to create a function that makes the intersection between two vectors: vetorA
∩ vetorB
and allocates the values found at this intersection in a vetorC
!
Rules:
to) The complexity of the intersection function/method must be:
O(n), if
n > m
O(m), if
m > n
b) The signature of the intersection function must be:
void intersecao(char a[], int n, char b[], int m, char c[], int *k)
c) Default language functions cannot be used for handling of vectors (search, pertinence, insertion, exclusion, ordering, etc.).
I was thinking of using a complexity algorithm O(n) which is termed "Linear time". But this algorithm he makes the comparison "linear" obviously as the name says.
Example:
A = { 'E', 'C', 'B', 'J', 'S', 'F', 'C', 'V', 'G' }
B = { 'G', 'C', 'M', 'W', 'L', 'O' }
C = { 'G', 'C' }
What is my difficulty?
I am trying to develop a logic that meets the requested complexity O(n) and O(m), But I’m having a hard time picking up a particular element of a particular vector, going through this element, comparing all the other given vector. The only solution I can think of would be at least one O(n²).
Illustration of what I’m trying to do:
MY CODE:
bool checkHasStringEqual(char vectorA, char vectorB) {
string stringA, stringB;
stringA = toupper(vectorA),
stringB = toupper(vectorB);
size_t found = stringA.find(stringB);
return (found != std::string::npos);
}
void intersection(char a[], char b[], char c[], int n, int m, int *k){
cout << "VETOR [A]: {" << a << "}" << endl;
cout << "VETOR [B]: {" << b << "}\n\n" << endl;
if(n > m) {
int index = 0;
for (int i = 0; i < n; i++) {
if (checkHasStringEqual(a[i], b[index]) && !checkHasStringEqual(b[index], c[index])) {
k = new int[strlen(c) + 1];
c[k] = b[index];
i = 0;
index++;
cout << "EH IGUAL: " << a[i] << " == " << b[index] << endl;
}
}
}
if(m > n) {
//CÓDIGO
}
}
I don’t believe it’s possible to do this in O(n)...my guess is O(m*n), which is not bad, I think
– zentrunix
@zentrunix is possible to do with the algorithm I mentioned above, but it searches and compares linearly for example: a[0] == b[0], a[1] == b[1] and so on, I need to try to modify it so that "traverse" the index of a vector and search and compare everything for example a[0] == b[0] , a[1] == b[0] and so on.
– user148754
I believe that you can only do such an algorithm if both vectors are sorted. Then it becomes a balanced line problem.
– anonimo
@anonimo and ai friend, all right? I just answered my question also with the algorithm already ready, thanks for everything!
– user148754