SHARE
TWEET

ssanina

a guest Dec 9th, 2019 88 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. int reduce(int (*f)(int, int), int* a, int n)
  6. {
  7.     int res = 0;
  8.     for (int i = 0; i < n; i++)
  9.         res = f(res, a[i]);
  10.     return res;
  11. }
  12.  
  13. int* map(int (*f)(int), int* a, int n)
  14. {
  15.     int* res;
  16.     res = (int*)calloc(n, sizeof(int));
  17.     for (int i = 0; i < n; i++)
  18.         res[i] = f(a[i]);
  19.     return res;
  20. }
  21.  
  22. int* filter(int (*f)(int), int* a, int n, int* k)
  23. {
  24.     int* res = NULL;
  25.     *k = 0;
  26.     for (int i = 0; i < n; i++)
  27.     {
  28.         if (f(a[i]))
  29.         {
  30.             res = (int*)realloc(res, (*k + 1) * sizeof(int));
  31.             res[(*k)] = a[i];
  32.             (*k)++;
  33.         }
  34.     }
  35.     return res;
  36. }
  37.  
  38. int f_sum(int a, int b)
  39. {
  40.     return a + b;
  41. }
  42.  
  43. int inc(int a)
  44. {
  45.     return ++a;
  46. }
  47.  
  48. int even(int a)
  49. {
  50.     return (a % 2 == 0);
  51. }
  52.  
  53. int main()
  54. {
  55.     int* a;
  56.     int n;
  57.     scanf_s("%d", &n);
  58.     a = (int*)calloc(n, sizeof(int));
  59.     for (int i = 0; i < n; i++)
  60.         scanf_s("%d", &a[i]);
  61.     int res1, * res2, * res3;
  62.     res1 = reduce(f_sum, a, n);
  63.     printf("Reduce:\n%d\n", res1);
  64.     res2 = map(inc, a, n);
  65.     printf("Map:\n");
  66.     for (int i = 0; i < n; i++)
  67.         printf("%d ", res2[i]);
  68.     puts("");
  69.     printf("Filter:\n");
  70.     int k;
  71.     res3 = filter(even, a, n, &k);
  72.     for (int i = 0; i < k; i++)
  73.         printf("%d ", res3[i]);
  74.     free(a);
  75.     free(res2);
  76.     free(res3);
  77.     return 0;
  78. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top