Skip to content

Instantly share code, notes, and snippets.

@MhdSyrwan
Created January 11, 2015 17:52
Show Gist options
  • Save MhdSyrwan/45b6eeec66b9d2c9199f to your computer and use it in GitHub Desktop.
Save MhdSyrwan/45b6eeec66b9d2c9199f to your computer and use it in GitHub Desktop.
// Set.h: interface for the Set class.
// this code is'nt under any license so feel free to edit or copy/paste any peace of it
//////////////////////////////////////////////////////////////////////
#ifndef SET_H
#define SET_H
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
template <int N>
class Set
{
typedef unsigned int word_t;
private:
enum { WORD_SIZE = sizeof(word_t) * 8 };
const int length;
word_t data[N / 32 + 1];
inline int bindex(int b) { return b / WORD_SIZE; }
inline int boffset(int b) { return b % WORD_SIZE; }
void set_bit(int b)
{
data[bindex(b)] |= 1 << (boffset(b));
}
void clear_bit(int b)
{
data[bindex(b)] &= ~(1 << (boffset(b)));
}
int get_bit(int b)
{
return data[bindex(b)] & (1 << (boffset(b)));
}
public:
Set() : length(N / 32 + 1)
{
clear_all();
}
virtual ~Set()
{
}
void clear_all()
{
for (int i=0;i<length;i++)
data[i]=0;
}
void set_all()
{
for (int i=0;i<length;i++)
data[i]=~(0);
}
void print(ostream &output)
{
for (int i=0;i<length;i++)
{
if (data[i]!=0)
{
for (int j=0 ;j<WORD_SIZE ; j++)
{
if (j+i == N) break;
if (get_bit(i+j))
output << i+j << ", " ;
}
}
}
}
Set& operator << (int b)
{
set_bit(b);
return (*this);
}
Set& operator >> (int b)
{
clear_bit(b);
return (*this);
}
Set operator &(const Set& b)
{
Set<N> c;
for (int i=0;i<length;i++)
c.data[i]=data[i] & b.data[i];
return c;
}
Set operator |(const Set& b)
{
Set<N> c;
for (int i=0;i<length;i++)
c.data[i]=data[i] | b.data[i];
return c;
}
Set operator ^(const Set& b)
{
Set<N> c;
for (int i=0;i<length;i++)
c.data[i]=data[i] ^ b.data[i];
return c;
}
Set operator ~()
{
Set<N> c;
for (int i=0;i<length;i++)
c.data[i]=~data[i] ;
return c;
}
friend ostream& operator << (ostream& output,Set&);
};
template <int N>
ostream& operator << (ostream& output,Set<N>& _set)
{
_set.print(output);
return output;
}
#endif // SET_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment