Advertisement
Guest User

Untitled

a guest
Aug 31st, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct{
  5. int tam;
  6. int *valores;
  7. }conjunto;
  8.  
  9. conjunto constroiConjunto(){
  10. conjunto aux={0};
  11. return aux;
  12. }
  13.  
  14. int temValor(conjunto a, int valor){
  15. int i;
  16.  
  17. for(i=0;i<a.tam;i++)
  18. if(a.valores[i]==valor)
  19. return 1;
  20.  
  21. return 0;
  22. }
  23.  
  24. void addValor(conjunto *conj, int valor){
  25. if(!temValor(*conj, valor)){
  26. conj->tam++;
  27. conj->valores = (int*) realloc(conj->valores, conj->tam);
  28. conj->valores[(conj->tam)-1] = valor;
  29. }
  30. }
  31.  
  32. conjunto intercecao(conjunto a, conjunto b){
  33. int i, j;
  34. conjunto inter=constroiConjunto();
  35.  
  36. for(i=0;i<a.tam;i++)
  37. for(j=0;j<b.tam;j++)
  38. if(a.valores[i]==b.valores[j])
  39. addValor(&inter,a.valores[i]);
  40.  
  41. return inter;
  42. }
  43.  
  44. conjunto diferenca(conjunto a, conjunto b){
  45. int i, j;
  46. conjunto dife=constroiConjunto();
  47.  
  48. for(i=0;i<a.tam;i++){
  49. int eDiferente = 1;
  50.  
  51. for(j=0;j<b.tam;j++){
  52. if(a.valores[i]==b.valores[j]){
  53. eDiferente = 0;
  54. break;
  55. }
  56. }
  57.  
  58. if(eDiferente)
  59. addValor(&dife,a.valores[i]);
  60. }
  61.  
  62. for(i=0;i<b.tam;i++){
  63. int eDiferente = 1;
  64.  
  65. for(j=0;j<a.tam;j++){
  66. if(b.valores[i]==a.valores[j]){
  67. eDiferente = 0;
  68. break;
  69. }
  70. }
  71.  
  72. if(eDiferente)
  73. addValor(&dife,b.valores[i]);
  74. }
  75.  
  76. return dife;
  77. }
  78.  
  79. void printarValores(conjunto a){
  80. int i;
  81.  
  82. for(i=0;i<a.tam;i++)
  83. printf("%d ", a.valores[i]);
  84. printf("\n");
  85. }
  86.  
  87. int main(){
  88. conjunto a=constroiConjunto(), b=constroiConjunto();
  89.  
  90. addValor(&a,1);
  91. addValor(&a,2);
  92. addValor(&a,3);
  93.  
  94. addValor(&b,2);
  95. addValor(&b,3);
  96. addValor(&b,7);
  97. addValor(&b,9);
  98.  
  99. conjunto inter = intercecao(a,b), dife = diferenca(a,b);
  100.  
  101. printf("Intercecao:\n");
  102. printarValores(inter);
  103. printf("\nDiferenca:\n");
  104. printarValores(dife);
  105.  
  106. return 0;
  107. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement