Reputation: 707
A school project requires me to perform basic set operations using my own bit-string implementation (use of STL is prohibited). I have a very basic but functional bit-vector wrapper set up and it works perfectly with all the set operations that can be calculated by the native C bit-wise operators (Bit-wise AND, OR, XOR) etc.
However Set Subtraction is the one required operation I can't figure out how to calculate using bit-string operations. Set Subtraction meaning (A - B) = all values that ARE in A but are NOT in B
Here is my implementation and two of the basic operations:
#include <iostream>
#include <cstdlib>
#include <vector>
#define WORDSIZE 9 // the sets will only ever contain numbers from 0 to 9
#define BIT_WS 5
#define MASK 0x1f
using namespace std;
int init_bitvector(int **bv, int val)
{
*bv = (int*)calloc(val / WORDSIZE + 1, sizeof(int));
return *bv != NULL;
}
void set(int bv[], int i)
{
bv[i >> BIT_WS] |= (1 << (i & MASK));
}
int member(int bv[], int i)
{
return bv[i >> BIT_WS] & (1 << (i & MASK));
}
int main()
{
bool input_check = true; // Use to control user input
int input_temp;
int *bitvectorA, *bitvectorB, *bitvectorOR, *bitvectorAND, *bitvectorDIFF;
vector<int> SetA;
vector<int> SetB;
init_bitvector(&bitvectorA, WORDSIZE);
init_bitvector(&bitvectorB, WORDSIZE);
init_bitvector(&bitvectorOR, WORDSIZE);
init_bitvector(&bitvectorAND, WORDSIZE);
init_bitvector(&bitvectorDIFF, WORDSIZE);
// ...user input for set values...
for (int i = 0; i < SetA.size(); i++)
{
set(bitvectorA, SetA[i]);
}
for (int i = 0; i < SetB.size(); i++)
{
set(bitvectorB, SetB[i]);
}
cout << endl << "Intersection of Set A and Set B:" << endl;
*bitvectorAND = (*bitvectorA & *bitvectorB);
for(int i = 0; i <= WORDSIZE; i++)
{
if(member(bitvectorAND, i))
{
cout << i << ' ';
}
}
cout << endl;
cout << endl << "Union of Set A and Set B:" << endl;
*bitvectorOR = (*bitvectorA | *bitvectorB);
for(int i = 0; i <= WORDSIZE; i++)
{
if(member(bitvectorOR, i))
{
cout << i << ' ';
}
}
cout << endl;
I can confirm that this works exactly as intended for all operations that have bit-wise operators. I just can't figure out how to implement Set Subtraction in a comparable manner.
Upvotes: 1
Views: 640
Reputation: 707
Solution:
*bitvectorDIFF = (*bitvectorA & ~*bitvectorB);
Thanks to Cheers and hth. -Alf for the tip
Upvotes: 1