How to implement the copy_if algorithm to copy elements satisfying a predicate in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

/*
    copy_if: Copies elements from src[] to dst[] only if they satisfy a predicate.

    Parameters:
        src      - input array
        n        - number of elements in src
        dst      - output array (must be allocated by caller)
        predicate- function pointer returning true for elements to be copied

    Returns:
        The number of elements copied into dst.
*/
size_t copy_if(const int *src, size_t n, int *dst, bool (*predicate)(int)) {
    size_t count = 0;

    for (size_t i = 0; i < n; i++) {
        // If the predicate is satisfied, copy the element
        if (predicate(src[i])) {
            dst[count++] = src[i];
        }
    }

    return count;
}

/*
    Predicate:
    Returns true if the number is even.
*/
bool is_even(int x) {
    return (x % 2) == 0;
}

/*
    Predicate:
    Returns true if the number is greater than 10.
*/
bool greater_than_10(int x) {
    return x > 10;
}

int main(void) {
    // Input array
    int src[] = {1, 2, 3, 4, 10, 11, 12, 20, 21};
    size_t n = sizeof(src) / sizeof(src[0]);

    // Allocate destination array (same size as src is safe)
    int *dst = malloc(n * sizeof(int));
    if (!dst) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1;
    }

    // Use copy_if with the "is_even" predicate
    size_t copied_even = copy_if(src, n, dst, is_even);

    printf("Copying even numbers:\n");
    for (size_t i = 0; i < copied_even; i++) {
        printf("%d ", dst[i]);
    }
    printf("\n\n");

    // Use copy_if with the "greater_than_10" predicate
    size_t copied_gt10 = copy_if(src, n, dst, greater_than_10);

    printf("Copying numbers > 10:\n");
    for (size_t i = 0; i < copied_gt10; i++) {
        printf("%d ", dst[i]);
    }
    printf("\n");

    free(dst);
    
    return 0;
}


/*
run:

Copying even numbers:
2 4 10 12 20 

Copying numbers > 10:
11 12 20 21 

*/

 



answered Jul 26 by avibootz

Related questions

...