Re:Interviewing programmers: coding test example explained
by grogers on Thursday June 03, 2010 @09:31AM
(#1401218)
Interesting, when I solved the problem originally on my own, I got to the exact same solution just with different variable names and braces. I suspect that this is probably the most common way to solve it.
[ Parent
| on HN ]
Re:Interviewing programmers: coding test example explained
by aplusbi on Thursday June 03, 2010 @09:41AM
(#1401240)
Yeah, I had almost exactly the same code. I'm sure most people did too. The only other "obvious" algorithm is the n^2 one.
Re:Interviewing programmers: coding test example explained
by RiderOfGiraffes on Thursday June 03, 2010 @09:48AM
(#1401266)
You will be surprised.
Re:Interviewing programmers: coding test example explained
by aplusbi on Thursday June 03, 2010 @10:10AM
(#1401339)
I like surprises! Looking forward to part 3...
Re:Interviewing programmers: coding test example explained
by Xurinos on Thursday June 03, 2010 @12:05PM
(#1401684)
I use do...while instead of the for loop, making the usual nasty C-programmer use of ++ in the right spots, but other than that, my solution is the same.
Edit: Correction... I also copy the '\0' character before exiting instead of making that a separate step. It has to do with the order of things. Here is the code:
char* read_ptr = s;
do {
if (*read_ptr != c) {
*s++ = *read_ptr;
}
} while (*read_ptr++ != '\0');
Re:Interviewing programmers: coding test example explained
by philwelch on Thursday June 03, 2010 @07:04PM
(#1402908)
You can use an inner loop to skip over removable chars in the source string but I didn't think that was n^2. (Code below for reference.) Am I wrong that my solution is n, or is there another obvious n^2 algorithm?
void condense_by_removing( char *z_terminated , char char_to_remove)
{
char * sp;
char * dp;
sp = dp = z_terminated;
while (*sp != '\0') {
while (*sp == char_to_remove){
sp++;
}
*dp = *sp;
dp++;
sp++;
}
*dp = *sp;
}