Wednesday, January 04, 2006

C Coding Problem

So I couldn't help but stop thinking about this simple coding problem I was presented with. What I have down is what I think is the answer although I have not tried to compile the code. I don't believe I solved the problem in-time but at least now I have an answer written down for next time.
Input: He^ll^^^oW^or^ld^^^^^
Output: HelloWorld

So the goal is to write a function that processes the input and returns an output as mentioned above. I accomplish this by reading through the characters once, and using two pointers to keep track of what I'm reading and what I'm writing.
void func(char* p)
{
char* currread = p;
char* currwrite = 0;
while(currread++)
{
if(!currwrite && *curread=='^')
currwrite=currread;
if(currwrite && *currread!='^')
{
*currwrite = * currread;
++currwrite;
}
}
currwrite=0;
}

This is probably the easiest to visualize and follow solution, another way is to use strcpy and copy the strings to currlocation from currlocation+1 to length-currlocation each time a ^ is encountered. From my discussion with a cohort, window's implementation of strcpy boils down to only a few assembly instructions so that may turn out more efficient.

No comments: