Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdio.h>
- #include <stdlib.h>
- int reduce(int (*f)(int, int), int* a, int n)
- {
- int res = 0;
- for (int i = 0; i < n; i++)
- res = f(res, a[i]);
- return res;
- }
- int* map(int (*f)(int), int* a, int n)
- {
- int* res;
- res = (int*)calloc(n, sizeof(int));
- for (int i = 0; i < n; i++)
- res[i] = f(a[i]);
- return res;
- }
- int* filter(int (*f)(int), int* a, int n, int* k)
- {
- int* res = NULL;
- *k = 0;
- for (int i = 0; i < n; i++)
- {
- if (f(a[i]))
- {
- res = (int*)realloc(res, (*k + 1) * sizeof(int));
- res[(*k)] = a[i];
- (*k)++;
- }
- }
- return res;
- }
- int f_sum(int a, int b)
- {
- return a + b;
- }
- int inc(int a)
- {
- return ++a;
- }
- int even(int a)
- {
- return (a % 2 == 0);
- }
- int main()
- {
- int* a;
- int n;
- scanf_s("%d", &n);
- a = (int*)calloc(n, sizeof(int));
- for (int i = 0; i < n; i++)
- scanf_s("%d", &a[i]);
- int res1, * res2, * res3;
- res1 = reduce(f_sum, a, n);
- printf("Reduce:\n%d\n", res1);
- res2 = map(inc, a, n);
- printf("Map:\n");
- for (int i = 0; i < n; i++)
- printf("%d ", res2[i]);
- puts("");
- printf("Filter:\n");
- int k;
- res3 = filter(even, a, n, &k);
- for (int i = 0; i < k; i++)
- printf("%d ", res3[i]);
- free(a);
- free(res2);
- free(res3);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement