Advertisement
xSiRON

es1_esame180618

Jun 19th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.76 KB | None | 0 0
  1. /*
  2. ESERCIZIO 1:
  3. Scrivere un metodo che prenda in input una matrice A di dimensione n*n ed un array B di n elementi distinti, e
  4. restituisca un array C, allocato dinamicamente di dimensione n, che contenga gli elementi corrispondenti ad
  5. A intersecato B (C non deve contenere intersezioni)
  6. */
  7.  
  8. #include <iostream>
  9. #include <cstdlib>
  10. #include <ctime>
  11. #define DIM 3
  12.  
  13. using namespace std;
  14.  
  15. int *arrayIntersezione(int array[], int matrice[][DIM]);
  16. void push(int array[], int x);
  17.  
  18. int main(){
  19.     srand(time(NULL));
  20.  
  21.     int matrice[DIM][DIM];
  22.  
  23.     cout << "MATRICE:" << endl;
  24.     for(int i = 0; i < DIM; i++){
  25.         for(int j = 0; j < DIM; j++){
  26.             matrice[i][j] = rand()%10+1;
  27.             cout << matrice[i][j] << " ";
  28.         }
  29.         cout << endl;
  30.     }
  31.  
  32.     int array[] = {7, 3, 9};
  33.  
  34.     cout << "\nARRAY B:" << endl;
  35.     for(int i = 0; i < DIM; i++){
  36.         cout << array[i] << " ";
  37.     }
  38.     cout << endl;
  39.  
  40.     int *C = arrayIntersezione(array, matrice);
  41.  
  42.     cout << "\nARRAY C:" << endl;
  43.     for(int i = 0; i < DIM; i++){
  44.         cout << C[i] << " ";
  45.     }
  46.     cout << "\n\n";
  47. }
  48.  
  49. int *arrayIntersezione(int array[], int matrice[][DIM]){
  50.     int *C = new int[DIM];
  51.  
  52.     for(int i = 0; i < DIM; i++){
  53.         C[i] = -1;
  54.     }
  55.  
  56.     for(int i = 0; i < DIM; i++){
  57.         bool found = false;
  58.         int k = 0;
  59.        
  60.         while(k < DIM && !found){
  61.             int j = 0;
  62.             while(j < DIM && !found){
  63.                 if(array[i] == matrice[k][j]){
  64.                     push(C, array[i]);
  65.                     found = true;
  66.                 }
  67.                 j++;
  68.             }
  69.             k++;
  70.         }
  71.     }
  72.  
  73.     return C;
  74. }
  75.  
  76. void push(int *array, int x){
  77.     static int i = 0;
  78.     array[i++] = x;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement