Last active
October 18, 2023 17:03
-
-
Save gcs-abdulwahab/ee9a8eb6b9a94f8bd1b014c57b9512db to your computer and use it in GitHub Desktop.
Set 2.0
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; | |
public: | |
int getCount(){ | |
int count = 0; | |
for (int i = 0 ; ar[i] != -1 ; i++) | |
count++; | |
return count; | |
} | |
void initialize(int ar[] , int cap){ | |
for (int i = 0 ; i<cap ; i++) | |
ar[i] = -1; | |
} | |
Set (int cap){ | |
ar = new int[cap]; | |
initialize(ar, cap); | |
} | |
~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); | |
// cout<<"idx " <<idx<<endl; | |
// cout<<"last " <<getCount()<<endl; | |
ar[idx] = ar [ getCount() -1 ]; | |
ar[getCount() -1 ] = -1; | |
return true; | |
} | |
return false; | |
} | |
void Union (Set &s){ | |
cout<< getCount() << endl; | |
cout<< s.getCount() << endl; | |
} | |
}; | |
int main() { | |
{ | |
Set s1(100); | |
s1.add(10); | |
s1.add(20); | |
s1.add(30); | |
Set s2 (100); | |
s2.add(50); | |
s2.add(20); | |
s2.add(60); | |
s2.add(70); | |
s1.Union(s2); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment