How to print all distinct 4 elements from an array that have the same given sum in C

1 Answer

0 votes
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <math.h>

int compare(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);
}

void getDistinct4Elements(int arr[], int size, int sum) {
    qsort(arr, size, sizeof(int), compare);

    for (int i = 0; i <= size - 4; i++) {
        for (int j = i + 1; j <= size - 3; j++) {
            int k = sum - (arr[i] + arr[j]);

            int fromstart = j + 1, fromend = size - 1;

            while (fromstart < fromend) {
                if (arr[fromstart] + arr[fromend] < k) {
                    fromstart++;
                }

                else if (arr[fromstart] + arr[fromend] > k) {
                    fromend--;
                }

                else {
                    printf("%d, %d, %d, %d\n", arr[i], arr[j], arr[fromstart], arr[fromend]);
                    fromstart++, fromend--;
                }
            }
        }
    }
}

int main(void)
{
    int arr[] = { 4, 8, 1, 5, 9, 0, 3, 7 };

    int sum = 18;

    int size = sizeof(arr) / sizeof(arr[0]);

    getDistinct4Elements(arr, size, sum);

    return 0;
}




/*
run:

0, 1, 8, 9
0, 3, 7, 8
0, 4, 5, 9
1, 3, 5, 9
1, 4, 5, 8

*/

 



answered Aug 20, 2022 by avibootz
...