Advertisement
Bkmz

Untitled

Apr 23rd, 2012
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. #include <malloc.h>
  5. #include <time.h>
  6.  
  7. #define N 128
  8. #define K 32
  9.  
  10. #define MAX 256
  11. #define THREADS 4
  12.  
  13. #define res(cond) abs(result[cond].a) * abs(result[cond].b)
  14.  
  15. struct equation {
  16.     int a;
  17.     int b;
  18. };
  19.  
  20. int *array;
  21.  
  22. struct equation *result;
  23. int result_size=2;
  24. int result_in=0;
  25.  
  26. void generate_array()
  27. {
  28.     srandom(time(NULL));
  29.     int i;
  30.     array = (int *)malloc(sizeof(int)*N);
  31.     for (i=0;i<N;i++)
  32.     {
  33.         array[i] = rand() % MAX;
  34.     }
  35. }
  36.  
  37. void print(int *data)
  38. {
  39.     int i;
  40.     for(i=0;i<N;i++)
  41.     {
  42.         printf("%i ", data[i]);
  43.     }
  44.     printf("\n");
  45. }
  46.  
  47. struct equation make_equation(int a, int b)
  48. {
  49.     return *(struct equation[]){a,b};
  50. }
  51.  
  52. int main(void)
  53. {
  54.     // loop index
  55.     int i,j;
  56.     // equation variables:
  57.     int a,b;
  58.  
  59.     if (THREADS < 4)
  60.     {
  61.         fprintf(stderr, "Minimum threads are: 4. Your's: %i\n", THREADS);
  62.         exit(1);
  63.     }
  64.  
  65.     // allocation memory for result
  66.     result = malloc(sizeof(struct equation)*result_size);
  67.  
  68.     generate_array();
  69.  
  70.     printf("K: %i\n\n", K);
  71.  
  72.     for(i=0;i<N;++i)
  73.     {
  74.         for(j=0;j<N;++j)
  75.         {
  76.             a = array[i];
  77.             b = array[j];
  78.  
  79.             if (b-a == K)
  80.             {
  81.                 if(result_in >= result_size)
  82.                 {
  83.                     result = realloc(result, sizeof(struct equation)*result_size*2);
  84.                     result_size*=2;
  85.                 }
  86.  
  87.                 // after insert increase index
  88.                 result[result_in++] = make_equation(a,b);
  89.             }
  90.         }
  91.     }
  92.  
  93.  
  94.     int max = res(0);
  95.     struct equation tmp;
  96.  
  97.     for (i=0;i<result_in;i++)
  98.     {
  99.         if (max < res(i))
  100.         {
  101.             max = res(i);
  102.             tmp.a = result[i].a;
  103.             tmp.b = result[i].b;
  104.         }
  105.     }
  106.     printf("|%i|*|%i| = %i\n", tmp.a, tmp.b, max);
  107.     return 0;
  108. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement