Last active
October 18, 2023 19:49
-
-
Save gcs-abdulwahab/823aab467546f208ffb84b02d8cdb027 to your computer and use it in GitHub Desktop.
Set Operations Simplified
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Online C++ compiler to run C++ program online | |
#include <iostream> | |
using namespace std; | |
class Set { | |
int *ar; | |
int capacity; | |
public: | |
int getCapacity(){ | |
return capacity; | |
} | |
int getCount(){ | |
int count = 0; | |
for (int i = 0 ; ar[i] != -1 ; i++) | |
count++; | |
return count; | |
} | |
void initialize(int cap){ | |
for (int i = 0 ; i<cap ; i++) | |
ar[i] = -1; | |
} | |
Set (){ | |
capacity = 1000; | |
ar = new int[capacity]; | |
initialize(capacity); | |
} | |
~Set (){ | |
delete []ar; | |
} | |
bool doesExist(int val){ | |
for (int i = 0 ; ar[i] != -1 ; i++){ | |
if (ar[i] == val) | |
return true; | |
} | |
return false; | |
} | |
bool add(int val){ | |
if ( !doesExist(val) ){ | |
ar[ getCount() ] = val; | |
return true; | |
} | |
return false; | |
} | |
void print (){ | |
for (int i = 0 ; ar[i] != -1 ; i++){ | |
cout<< ar[i]<<" , "; | |
} | |
cout<<endl; | |
} | |
int getIndex(int val){ | |
if (doesExist(val)){ | |
for (int i = 0 ; ar[i] != -1 ; i++){ | |
if(ar[i] == val){ | |
return i; | |
} | |
} | |
return -1; | |
} | |
} | |
bool remove(int val){ | |
if (doesExist(val)){ | |
// swap last value with the the index value and make the last value -1; | |
int idx = getIndex(val); | |
ar[idx] = ar [ getCount() -1 ]; | |
ar[getCount() -1 ] = -1; | |
return true; | |
} | |
return false; | |
} | |
int getElement(int pos){ | |
return ar[pos - 1]; | |
} | |
Set ( Set &s){ | |
capacity = s.capacity; | |
ar = new int[capacity]; | |
initialize(capacity); | |
for(int i = 1 ; i<= s.getCount(); i++){ | |
ar[i-1] = s.getElement(i); | |
} | |
} | |
Set Union (Set &s){ | |
Set s3 (s); | |
// Write Code here | |
return s3; | |
} | |
Set Intersection(Set &s){ | |
Set s3; | |
return s3; | |
} | |
}; | |
int main() { | |
{ | |
Set s1; | |
s1.add(10); | |
s1.add(20); | |
s1.add(30); | |
Set s2; | |
s2.add(50); | |
s2.add(20); | |
s2.add(60); | |
s2.add(70); | |
Set s3 = s1.Union(s2); | |
s3.print(); | |
sinter = s1.Intersection(s2) ; | |
sinter.print(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment