Two arrays are given. Write the C code to swap elements from each array such that after
swapping, sum of elements of array1=sum of elements of array2..
Example:
Array 1: 3, 2, 10, 12
Array 2: 6, 4, 9, 10
After swapping 3 (from Array 1) with 4 (from Array 2)
Array1: 4, 2, 10, 12 Sum = 28
Array2: 6, 3, 9, 10 Sum = 28
#include <stdio.h>
void print_array(int a[], int n, char* str) {
int i;
printf(str);
for (i=0; i<n; i++) {
printf("%d ", a[i]);
}
printf("\n");
}
int sum_array(int a[], int n) {
int i;
int s = 0;
for (i=0; i<n; i++) {
s += a[i];
}
return s;
}
int swap(int a1[], int m, int a2[], int n) {
int dif;
int i, j, tmp;
dif = sum_array(a1, n) - sum_array(a2, n);
for (i=0; i<m; i++) {
for (j=0; j<n; j++) {
if (a1[i] - a2[j] == dif/2) {
tmp = a1[i];
a1[i] = a2[j];
a2[j] = tmp;
return 1;
}
}
}
return 0;
}
int main() {
int a1[] = { 3, 2, 10, 12};
int a2[] = { 6, 4, 9, 10};
int m = sizeof(a1) / sizeof(a1[0]);
int n = sizeof(a2) / sizeof(a2[0]);
print_array(a1, m, "Array1: ");
print_array(a2, n, "Array2: ");
printf("\nSwapping\n");
if (swap(a1, m, a2, n)) {
print_array(a1, m, "Array1: ");
printf("Summ is %d\n", sum_array(a1, m));
print_array(a2, n, "Array2: ");
printf("Summ is %d\n", sum_array(a2, n));
}
else {
printf("Sorry, can't do that\n");
}
}
Comments
Leave a comment