My boss’s boss’s pals wrote this: http://blog.exodusintel.com/2012/09/18/reversing-the-interview-process/
Its a story about how someone was asked a crazy fun C question in an interview and how the new team decided to try it.
After reading this and discussing it with coworkers, I decided to try it and of course the first thing that came to my mind was a way to use tail recursion to do it.
1 #include <stdio.h> 2 3 int c; 4 //auto func0 = [&] () -> int { c++; _strlen(s+1);}; 5 //auto funcn = [&] () -> int { return c; }; 6 int rs(char* s); 7 int go(char* s) { c++; return rs(s+1); } 8 int ret(char* s) { return c; } 9 int rs(char* s) { 10 int (*func[2]) (char *s) = {ret,go}; 11 char i = (*s>>7 | *s>>6 | *s>>5 | *s>>4 | *s>>3 | *s>>2 | *s>>1) & 1; 12 return func[i](s); 13 } 14 int _strlen(char* s) { 15 c = 0; 16 return rs(s); 17 } 18 19 int main(int argc, char* argv[]) { 20 printf("_strlen(%s): %d\n", argv[1], _strlen(argv[1])); 21 return 0; 22 }
After writing it, I went and looked at the other fella solutions for the second time. I should also mention that I haven’t written C on the job in 11 years, and when I did then, it was one tiny program which was quickly replaced with perl. I have never been anything other than an intro beginner C programmer.
Things I noticed after going back is that my solution is somewhat similar to Brandon and Zef’s solution, but I think both my use of function pointers and bit shifting are more elementary. I’m still not sure about how some parts of their solution works.