/* The 3SUM problem: given a multiset S of n integers, are there * elements a, b, c in S such that a + b + c = 0? */ #include #include #include static bool search(long const *S, long n) { long i, j, k; for (i = 0; i < n; i++) for (j = 0; j < n; j++) for (k = 0; k < n; k++) if ((S[i] + S[j] + S[k]) == 0) return true; return false; } static void randomize(long *S, long n, float theta) { long i; for (i = 0; i < n; i++) { S[i] = (random() < (theta * RAND_MAX)) ? +1 : -1; } } int main(int argc, char *argv[]) { /* Default parameters. */ long n = 1000; float theta = 0.5; /* Override default random seed. */ if (argc > 1) srandom(atol(argv[1])); /* Override default size n of multiset S. */ if (argc > 2) n = atol(argv[2]); /* Override default bias of input distribution. */ if (argc > 3) theta = atof(argv[3]); /* Allocate the multiset. */ long S[n]; /* Initialize the multiset. */ randomize(S, n, theta); /* Kick off the search. */ return search(S, n); }