Created
July 19, 2013 18:54
-
-
Save tautologico/6041482 to your computer and use it in GitHub Desktop.
Simple bit vector for exploring all complementary sets to cover a set of indexes.
This file contains hidden or 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
// bitvec.c | |
// Bit vector com ate 64 elementos | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
#define MAX_SIZE 64 | |
typedef struct tagBitVector { | |
int size; | |
unsigned vector; | |
} BitVector; | |
BitVector* create_bit_vector(int size) | |
{ | |
BitVector *res = malloc(sizeof(BitVector)); | |
if (size > MAX_SIZE) | |
return NULL; | |
if (res == NULL) | |
return NULL; | |
res->size = size; | |
res->vector = 0; | |
return res; | |
} | |
void destroy_bit_vector(BitVector *bv) | |
{ | |
if (bv != NULL) | |
free(bv); | |
} | |
int is_member(BitVector* vec, int index) | |
{ | |
assert( index <= MAX_SIZE ); | |
unsigned mask = 1 << index; | |
return vec->vector & mask ? 1 : 0; | |
} | |
void test(void) | |
{ | |
BitVector *bv = create_bit_vector(4); | |
int setA[5], setB[5]; | |
if (bv == NULL) { | |
fprintf(stderr, "Erro criando bit vector\n"); | |
exit(2); | |
} | |
unsigned max = 1 << 4; | |
int indexA, indexB; | |
for (int i = 0; i < max; ++i) { // loop testando todas as divisoes A/B | |
bv->vector = i; | |
indexA = indexB = 0; | |
for (int j = 0; j < 4; ++j) { // p/ cada divisao, separe os arrays | |
if (is_member(bv, j)) { // membro significa conjunto B | |
setB[indexB++] = j; | |
} | |
else { | |
setA[indexA++] = j; | |
} | |
} | |
setA[indexA] = setB[indexB] = -1; | |
// imprime conjuntos | |
printf("Conjunto A: "); | |
for (int j = 0; setA[j] != -1; ++j) | |
printf("%d ", setA[j]); | |
printf("\n"); | |
printf("Conjunto B: "); | |
for (int j = 0; setB[j] != -1; ++j) | |
printf("%d ", setB[j]); | |
printf("\n"); | |
} | |
destroy_bit_vector(bv); | |
} | |
int main(void) | |
{ | |
test(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment