Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct{
- int tam;
- int *valores;
- }conjunto;
- conjunto constroiConjunto(){
- conjunto aux={0};
- return aux;
- }
- int temValor(conjunto a, int valor){
- int i;
- for(i=0;i<a.tam;i++)
- if(a.valores[i]==valor)
- return 1;
- return 0;
- }
- void addValor(conjunto *conj, int valor){
- if(!temValor(*conj, valor)){
- conj->tam++;
- conj->valores = (int*) realloc(conj->valores, conj->tam);
- conj->valores[(conj->tam)-1] = valor;
- }
- }
- conjunto intercecao(conjunto a, conjunto b){
- int i, j;
- conjunto inter=constroiConjunto();
- for(i=0;i<a.tam;i++)
- for(j=0;j<b.tam;j++)
- if(a.valores[i]==b.valores[j])
- addValor(&inter,a.valores[i]);
- return inter;
- }
- conjunto diferenca(conjunto a, conjunto b){
- int i, j;
- conjunto dife=constroiConjunto();
- for(i=0;i<a.tam;i++){
- int eDiferente = 1;
- for(j=0;j<b.tam;j++){
- if(a.valores[i]==b.valores[j]){
- eDiferente = 0;
- break;
- }
- }
- if(eDiferente)
- addValor(&dife,a.valores[i]);
- }
- for(i=0;i<b.tam;i++){
- int eDiferente = 1;
- for(j=0;j<a.tam;j++){
- if(b.valores[i]==a.valores[j]){
- eDiferente = 0;
- break;
- }
- }
- if(eDiferente)
- addValor(&dife,b.valores[i]);
- }
- return dife;
- }
- void printarValores(conjunto a){
- int i;
- for(i=0;i<a.tam;i++)
- printf("%d ", a.valores[i]);
- printf("\n");
- }
- int main(){
- conjunto a=constroiConjunto(), b=constroiConjunto();
- addValor(&a,1);
- addValor(&a,2);
- addValor(&a,3);
- addValor(&b,2);
- addValor(&b,3);
- addValor(&b,7);
- addValor(&b,9);
- conjunto inter = intercecao(a,b), dife = diferenca(a,b);
- printf("Intercecao:\n");
- printarValores(inter);
- printf("\nDiferenca:\n");
- printarValores(dife);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement