Advertisement
Atheuz

Untitled

Oct 29th, 2011 (edited)
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.93 KB | None | 0 0
  1. /*
  2.  *  Dato: 29-10-2011
  3.  *  Kursus: Imperativ Programming
  4.  *  Underviser: Kurt Nørmark
  5.  *  Opgave: Opgave 11 side 462 i Problem Solving and Program Design in C, sixth edition.
  6.  *  Tid brugt: 120 minutter.
  7.  */
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11.  
  12. void combined_array(double *arr1, int a1_size, double *arr2, int a2_size, double *out);
  13.  
  14. int main(void) {
  15.     // Initialize variable arrays.
  16.     double arr1[]  = {-10.5, -1.8, 3.5, 6.3, 7.2};
  17.     double arr2[]  = {-1.8, 3.1, 6.3};
  18.     // Get size of arrays as we can't do this in the function.
  19.     int a1_size = sizeof(arr1)/sizeof(double);
  20.     int a2_size = sizeof(arr2)/sizeof(double);
  21.     double out[a1_size+a2_size];
  22.  
  23.     combined_array(arr1, a1_size, arr2, a2_size, out);
  24.  
  25.     return 0;
  26. }
  27.  
  28. // Create sorting function
  29. void combined_array(double *arr1, int a1_size, double *arr2, int a2_size, double *out) {
  30.     double temp[a1_size+a2_size];
  31.     double d;
  32.     int i, j, k;
  33.  
  34.     // Merge
  35.     for (i = 0, j = 0, k = 0; i < a1_size && j < a2_size;) {
  36.         if (arr1[i] < arr2[j]) {
  37.             temp[k] = arr1[i];
  38.             k++;
  39.             i++;
  40.         }
  41.         else {
  42.             temp[k] = arr2[j];
  43.             k++;
  44.             j++;
  45.         }
  46.     }
  47.  
  48.     while (i < a1_size) {
  49.         temp[k++] = arr1[i++];
  50.     }
  51.     while (j < a2_size) {
  52.         temp[k++] = arr2[j++];
  53.     }
  54.  
  55.     // Remove duplicates.
  56.     i = 0;
  57.     j = 0;
  58.     int counter = 0;
  59.     int duplicate_counter = 0;
  60.  
  61.     while (i < a1_size+a2_size) {
  62.         d = temp[i];
  63.         j = i+1;
  64.         while (j < a1_size+a2_size) {
  65.             if (temp[i] == temp[j]) {
  66.                 i++;
  67.                 duplicate_counter++;
  68.             }
  69.             j++;
  70.         }
  71.         out[counter] = d;
  72.         counter++;
  73.         i++;
  74.     }
  75.    
  76.     printf("Duplicates: %d\n", duplicate_counter);
  77.  
  78.     for(i = 0; i < a1_size + a2_size; i++) {
  79.         printf("%f ", out[i]);
  80.     }
  81. }
  82.  
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement