Created
March 29, 2017 03:47
-
-
Save axsddlr/c3e6169898081a1770a473a5fef79c94 to your computer and use it in GitHub Desktop.
Fixed (I think) threesum
This file contains 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
/* | |
* threesum.c | |
*/ | |
#include <errno.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <time.h> | |
#include <unistd.h> | |
#ifndef MAX_ELEMENTS | |
#define MAX_ELEMENTS 10 | |
#endif /* MAX_ELEMENTS */ | |
#ifndef CLOCKS_PER_SEC | |
#error CLOCKS_PER_SEC not defined on this platform | |
#endif /* CLOCKS_PER_SEC */ | |
static | |
long int count(long int *a) | |
{ | |
int counting, i, j, k; | |
counting = 0; | |
for ( i = 0; i < MAX_ELEMENTS - 2; i++ ) | |
for ( j = i+1; j < MAX_ELEMENTS - 1; j++ ) | |
for ( k = j+1; k < MAX_ELEMENTS; k++ ) | |
if ( (a[i] + a[j] + a[k]) == 0 ) { | |
counting++; | |
printf("Triplet Found : %ld, %ld, %ld\n", a[i], a[j], a[k]); | |
}; | |
return counting; | |
} | |
int main(int argc, char * const argv[]) | |
{ | |
long int arr[MAX_ELEMENTS], i, cnt; | |
clock_t start_time, end_time; | |
double total_time; | |
FILE *fp; | |
switch ( argc ) { | |
case 1: | |
fp = stdin; | |
break; | |
case 2: | |
if ( (fp = fopen(argv[1], "r")) == NULL ) { | |
fprintf(stderr, "Could not open input file: %s\n", strerror(errno)); | |
return 2; | |
}; | |
break; | |
default: | |
fprintf(stderr, "Usage: %s [ FILE ]\n", argv[0]); | |
return 1; | |
break; | |
}; | |
start_time = clock(); | |
printf("Starting of the program: = %ld\n", start_time); | |
for ( i = 0; i < MAX_ELEMENTS; i++ ) { | |
fscanf(fp,"%ld", &arr[i]); | |
printf("%ld\n", arr[i]); | |
}; | |
fclose(fp); | |
cnt = count(arr); | |
end_time = clock(); | |
printf("Result: %ld\n", cnt); | |
total_time = (double)(end_time - start_time) / CLOCKS_PER_SEC; | |
printf("Total time taken by CPU: %f\n", total_time); | |
return 0; | |
} | |
/* vim: set filetype=c expandtab tabstop=4 sts=4 shiftwidth=4: */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment