Created
May 14, 2017 18:38
-
-
Save Aspie96/d55ffb2f855aa87d719705ac8fda3c19 to your computer and use it in GitHub Desktop.
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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
typedef int (*Comparer)(void*, void*); | |
typedef int (*Generator)(void*); | |
int test1(Comparer comparer, void *obj1, void *obj2) { | |
int res1, res2; | |
res1 = comparer(obj1, obj2); | |
res2 = comparer(obj2, obj1); | |
if(res1 < 0) { | |
return res2 > 0; | |
} | |
if(res1 == 0) { | |
return res2 == 0; | |
} | |
if(res1 > 0) { | |
return res2 < 0; | |
} | |
} | |
int test2(Comparer comparer, void *obj1, void *obj2, void *obj3) { | |
int res1, res2, res3; | |
res1 = comparer(obj1, obj2); | |
res2 = comparer(obj2, obj3); | |
res3 = comparer(obj3, obj1); | |
int allUp = res1 >= 0 && res2 >= 0 && res3 >= 0; | |
int allDown = res1 <= 0 && res2 <= 0 && res3 <= 0; | |
return !((res1 || res2 || res3) && (allUp || allDown)); | |
} | |
int test_comparable(Comparer comparer, Generator generator, size_t size, int tries) { | |
int i; | |
void *obj1, *obj2, *obj3; | |
obj1 = malloc(size); | |
obj2 = malloc(size); | |
obj3 = malloc(size); | |
for(i = 0; i < tries; i++) { | |
generator(obj1); | |
generator(obj2); | |
generator(obj3); | |
if(!(test1(comparer, obj1, obj2) && test1(comparer, obj2, obj3) && test1(comparer, obj3, obj1) && test2(comparer, obj1, obj2, obj3))) { | |
return 0; | |
} | |
} | |
return 1; | |
} | |
int my_comparer(void *pt1, void *pt2) { | |
int n1, n2; | |
n1 = *((int*)pt1); | |
n2 = *((int*)pt2); | |
if(n1 < n2) { | |
return -1; | |
} | |
if(n1 == n2) { | |
return 0; | |
} | |
return 1; | |
} | |
int my_generator(void *pt) { | |
static int initialized = 0; | |
if(!initialized) { | |
srand(time(NULL) | rand()); | |
initialized = 1; | |
} | |
*((int*)pt) = rand(); | |
} | |
int main() { | |
if(test_comparable(my_comparer, my_generator, sizeof(int), 1000)) { | |
printf("Success!\n"); | |
} else { | |
printf("Fail!\n"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment