informaticage

Random array intersection

May 7th, 2021
810
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdbool.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5.  
  6. bool exists_in(int V[], size_t v_length, int to_find) {
  7.   for (size_t i = 0; i < v_length; i++) {
  8.     if (V[i] == to_find) {
  9.       return true;
  10.     }
  11.   }
  12.   return false;
  13. }
  14.  
  15. #define N 10
  16. int main(void) {
  17.  
  18.   srand(time(NULL));
  19.   int A[N] = {0}, B[N] = {0}, intersection[N + N] = {0};
  20.   for (size_t i = 0; i < N; i++) {
  21.     A[i] = rand() % 30 + 1;
  22.     B[i] = rand() % 30 + 1;
  23.   }
  24.  
  25.   // Printing generated array A
  26.   printf("A: [");
  27.   for (size_t i = 0; i < N; i++) {
  28.     printf("%d ", A[i]);
  29.   }
  30.   printf("]\n");
  31.  
  32.   // Printing generated array B
  33.   printf("B: [ ");
  34.   for (size_t i = 0; i < N; i++) {
  35.     printf("%d ", B[i]);
  36.   }
  37.   printf("]\n");
  38.  
  39.   // A intesection B
  40.   int intersections_i = 0;
  41.   for (size_t i = 0; i < N; i++) {
  42.     if (exists_in(B, N, A[i]) &&
  43.         !exists_in(intersection, intersections_i, A[i])) {
  44.       intersection[intersections_i++] = A[i];
  45.     }
  46.   }
  47.  
  48.   // Printing insersection
  49.   printf("Intersection: [ ");
  50.   for (size_t i = 0; i < intersections_i; i++) {
  51.     printf("%d ", intersection[i]);
  52.   }
  53.   printf("]\n");
  54.   return 0;
  55. }
RAW Paste Data