Advertisement
informaticage

UniversApp - EX Array Duplicates - C

Sep 1st, 2022
1,088
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.27 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3.  
  4. int main(void) {
  5.   int N, M;
  6.  
  7.   printf("Insert N, M: ");
  8.  
  9.   scanf("%d %d", &N, &M);
  10.  
  11.   // VLA V1, V2
  12.   int V1[N];
  13.   int V2[M];
  14.  
  15.   // Loading V1
  16.   for (int i = 0; i < N; i++) {
  17.     scanf("%d", &V1[i]);
  18.   }
  19.  
  20.   // Loading V2
  21.   for (int i = 0; i < M; i++) {
  22.     scanf("%d", &V2[i]);
  23.   }
  24.  
  25.   // Declaring common array
  26.   int max_len = N * (N > M) + M * (M >= N);  // max (M, N)
  27.  
  28.   // Common items array
  29.   int common[max_len];
  30.   int common_items = 0;
  31.  
  32.   // For each item in V1
  33.   for (int i = 0; i < N; i++) {
  34.     // If item exists in V2 as well and not in common array
  35.     bool is_in_v2 = false;
  36.  
  37.     // Current item exists in v2
  38.     for (int j = 0; j < M && !is_in_v2; j++) {
  39.       if (V1[i] == V2[j]) {
  40.         is_in_v2 = true;
  41.       }
  42.     }
  43.  
  44.     // If in v2 check for existance in common array
  45.     bool is_in_common = false;
  46.     for (int j = 0; j < common_items && !is_in_common; j++) {
  47.       if (V1[i] == common[j]) {
  48.         is_in_common = true;
  49.       }
  50.     }
  51.  
  52.     if (is_in_v2 && !is_in_common) {
  53.       common[common_items] = V1[i];
  54.       common_items++;
  55.     }
  56.   }
  57.  
  58.   printf("Duplicates: \n[ ");
  59.   for (int i = 0; i < common_items; i++) {
  60.     printf("%d ", common[i]);
  61.   }
  62.   printf("]");
  63.   return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement