Coder challenge!

May 25, 2005 19:56

So, the main() function is unnecessary. Now, the big question becomes "how complex programs can you create without defining functions at all?" (If you've taken concurrent programming at Waterloo, you'd learn that arbitrary restrictions like this is known as "structured programming", although in my opinion, "constrained programming" would be a better description.) In the global space you have very little control of execution flow. ?, && and || work fine, but loops and anything like that won't work. Still, with some clever use of functors and such, it is not entirely impossible to do something useful. Take this primality tester for instance:

#include
#include
#include
#include
using namespace std;
int num=printf("What number do you want to test?\n");
int a = scanf("%d",&num);
int b = (num<2 || num>1000000) ? printf("Out of range\n") : 0;

int c = b && (exit(0),1); //how's that for flow control, eh?

int d = printf("Testing %d for primality...\n",num);
vector nums(1001,1);

//use partial_sums to add up the elements, so nums become {1,1,2,3,4,5...}
vector::iterator qq = partial_sum(nums.begin()+1,nums.end(),nums.begin()+1);

//bind num and first element of modulus to calculate nums%x for all x of interest
int qwe=(transform(nums.begin()+2,nums.end(),nums.begin()+2,bind1st(modulus(),num)),0);

//test all the remainders for non-zeroness
bool isprime = accumulate(nums.begin()+2,nums.begin()+min(1000,num),true,logical_and());

int q = printf(isprime?"%d is a prime\n":"%d is not a prime\n",num);
int end = (exit(0),1);
int main;

So.. anybody else want to give it a shot?

programming

Previous post Next post
Up