Monday, October 21, 2013

Interesting code snippet no.2

I was presented with a very interesting problem by someone - print out numbers from 0-100 and from 100-0 not using conditional statements and while loops. This is what i came up with:

#include 

using namespace std;


void endRecurence(unsigned int currVal, unsigned int endVal);
void countUpDown(unsigned int currVal, unsigned int endVal);

static void (*functionArray[2])(unsigned int, unsigned int) = {countUpDown, endRecurence};

void endRecurence(unsigned int currVal, unsigned int endVal)
{

}

void countUpDown(unsigned int currVal, unsigned int endVal)
{
   int isEqual =  static_cast(currVal) / static_cast(endVal);//will round up down.

   cout << currVal << endl;
   // You should check if isEqual is bigger then the dimensions of the array but we don't own if's :)
   ::functionArray[isEqual](currVal + 1, endVal);

   cout << currVal << endl;
}

int main()
{

    countUpDown(0, 100);

    return 0;
}

Basically we abuse two things - function pointers, and rounding up down by division and int conversion principles in c++, you can even do an elimination of + operator :)

Stack Overflow as a source

Addition algorithm in asm

i will provide a snippet for that in a later date :)


No comments:

Post a Comment