Created
October 14, 2013 02:57
-
-
Save nilsou/6969993 to your computer and use it in GitHub Desktop.
Array Partition of equal sum possible?
http://www.careercup.com/question?id=8879649
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
int compare_function(const void *a,const void *b) { | |
int *x = (int *) a; | |
int *y = (int *) b; | |
return *x - *y; | |
} | |
int array_partition_possible(int *array, int count) { //array needs to be already sorted | |
int sum_a = 0; | |
int sum_b = 0; | |
for (int i = count-1; i >= 0; i--) { | |
if (sum_a <= sum_b) { | |
sum_a += array[i]; | |
} else { | |
sum_b += array[i]; | |
} | |
} | |
printf("%d, %d\n",sum_a, sum_b ); | |
return (sum_a == sum_b); | |
} | |
int main(int argc, char *argv[]) { | |
int count = argc - 1; | |
// Create the input array based on the arguments of the main function. | |
int *input = malloc(count); | |
for (int i = 0; i < count; ++i) { | |
input[i] = atoi(argv[i+1]); | |
} | |
// Sort the input array | |
qsort(input, count, sizeof(*input), compare_function); | |
// Find if the partition is possible | |
if (array_partition_possible(input, count)) | |
{ | |
printf("true\n"); | |
} else { | |
printf("false\n"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment