435,561 Members | 3,265 Online
Need help? Post your question and get tips & solutions from a community of 435,561 IT Pros & Developers. It's quick & easy.

# Programming Puzzle

 P: n/a I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles. Programming Puzzles Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions. Q1 Write a "Hello World" program in 'C' without using a semicolon. Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; Q3 C/C++ : Exchange two numbers without using a temporary variable. Q4 C/C++ : Find if the given number is a power of 2. Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator. Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7 Q7 Remove duplicates in array Q8 Finding if there is any loop inside linked list. Q9 Remove duplicates in an no key access database without using an array Q10 Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed. Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly. Q12 Swap two numbers without using a third variable. Given an array (group) of numbers write all the possible sub groups of this group. Q14 Convert (integer) number in binary without loops. Q3,12 are similar , Q7 is simple & I know there answer For the Rest please Help Wiating for reply. Nov 14 '05 #1
271 Replies

 P: n/a Jatinder scribbled the following on comp.lang.c: I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles. Programming Puzzles Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions. Q1 Write a "Hello World" program in 'C' without using a semicolon. Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; Q3 C/C++ : Exchange two numbers without using a temporary variable. Done to death here on comp.lang.c. Q4 C/C++ : Find if the given number is a power of 2. Easy with some bitwise arithmetic. Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator. Easy peasy. Repeated addition will do the trick. Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7 int f(int x) { return x==4 ? 7 : x==7 ? 4 : 0; } Q7 Remove duplicates in array You can't remove anything from an array. You can only modify the values of its elements. Q8 Finding if there is any loop inside linked list. Should be covered in any basic data structures course. Q9 Remove duplicates in an no key access database without using an array Impossible without access into a no key access database. Q10 Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed. Google for "quine". Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly. This one is actually a full-blown game. Q12 Swap two numbers without using a third variable. And how is this any different from Q3? Given an array (group) of numbers write all the possible sub groups of this group. Search for the definition of a "power set". The algorithm shoudln't be too hard to figure out. Q14 Convert (integer) number in binary without loops. Already done here on comp.lang.c. -- /-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\ \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/ "This isn't right. This isn't even wrong." - Wolfgang Pauli Nov 14 '05 #2

 P: n/a "Joona I Palaste" wrote in message news:cbkf50\$a76 Jatinder scribbled the following Q1 Write a "Hello World" program in 'C' without using a semicolon. Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; Q3 C/C++ : Exchange two numbers without using a temporary variable. Done to death here on comp.lang.c. Not familiar with the first two. Q1, how? Is #define SEMICOLON ; valid? Q2, is recursion a valid answer? Or even just writing the numbers explicitly printf("1\n2"), etc? For Q3 one can use ^= 3 times, though I wonder if this is faster than the usual one with a temp variable and 3 assignments on various platforms. Q4 C/C++ : Find if the given number is a power of 2. Easy with some bitwise arithmetic. x & (x-1) evaluates to zero if the number is an exact power of 2. Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator. Easy peasy. Repeated addition will do the trick. Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7 int f(int x) { return x==4 ? 7 : x==7 ? 4 : 0; } Another is realize 4 = %100 and 7 = %111 in binary, so leave the leftmost bit on, and flip the other 2. Thus: return x ^ %11, or return x ^ 3. Q7 Remove duplicates in array You can't remove anything from an array. You can only modify the values of its elements. Fine, then how to replace the duplicates with NULL or the like, or move the elements one down so that { 1, 2, 1, 1, 4, 3 } becomes { 1, 2, 4, 3, anything, anything }? Q8 Finding if there is any loop inside linked list. Should be covered in any basic data structures course. Q9 Remove duplicates in an no key access database without using an array Impossible without access into a no key access database. What is Q9 about? Q10 Write a program whose printed output is an exact copy of the source. Needless to say, merely echoing the actual source file is not allowed. Google for "quine". Bizarre stuff! Q11 From a 'pool' of numbers (four '1's, four '2's .... four '6's), each player selects a number and adds it to the total. Once a number is used, it must be removed from the pool. The winner is the person whose number makes the total equal 31 exactly. This one is actually a full-blown game. Q12 Swap two numbers without using a third variable. And how is this any different from Q3? Given an array (group) of numbers write all the possible sub groups of this group. Search for the definition of a "power set". The algorithm shoudln't be too hard to figure out. Someone posted something like this in the C++ newsgroup. If you have 3 numbers 1, 2, 3 then make a number of 3 bits %000. Then just add 1 until you max out. So you get %000, %001, %010, %011, %100, %101, %110, %111. If the bit is 0 it means that number is not in the group and if the bit it 1 it means the number is in the group, so %001 is the group "1", and %011 is the group "1,2", and %101 is the group "1,3". In C++ you could maybe use std::bitset. But I think you could do it using recursion too. So f(3,1) prints the combinations "3,..." and f(3,0) prints combinations without the 3. The part in ... is the combinations with 2 numbers, so f(2,1) prints "2,..." and f(2,0) prints "...". The second ... is the combinations with 1 numbers, just "1" and "". Q14 Convert (integer) number in binary without loops. Already done here on comp.lang.c. How, if not recursion? Maybe even lookup tables, which I used to implement a fast lgdown(x) function which gives log to base 2 of x. Nov 14 '05 #4

 P: n/a "Siemel Naran" wrote in message news:bg*******************@bgtnsc05-news.ops.worldnet.att.net... "Joona I Palaste" wrote in message news:cbkf50\$a76 Jatinder scribbled the following Q1 Write a "Hello World" program in 'C' without using a semicolon. Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; Q3 C/C++ : Exchange two numbers without using a temporary variable. Done to death here on comp.lang.c. Not familiar with the first two. Q1, how? Is #define SEMICOLON ; valid? no, but consider this int main (void) { if (printf("Hello World")) {} if (exit(EXIT_SUCCESS)) {} } Allan Nov 14 '05 #5

 P: n/a Allan Bruce wrote: .... snip ... no, but consider this int main (void) { if (printf("Hello World")) {} if (exit(EXIT_SUCCESS)) {} } Illegal. No #include for prototype of variadic function, nor EXIT_SUCCESS value, and exit is a void function. The compiler should barf. I am trying to construct something that revolves around: if (printf("Hello ") - printf("World\n")) {...} which statement could cause either "Hello World" or "WorldHello". -- Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net) Available for consulting/temporary embedded and systems. USE worldnet address! Nov 14 '05 #7

 P: n/a "Christian Bau" wrote in message news:ch*********************************@slb-newsm1.svr.pol.co.uk... In article <22**************************@posting.google.com >, js*******@sancharnet.in (Jatinder) wrote: Programming Puzzles Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions. Q1 Write a "Hello World" program in 'C' without using a semicolon. Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; Q3 C/C++ : Exchange two numbers without using a temporary variable. [snip] If I was given this list of questions, I would tell them that most of them are pointless and then examine Q11, because it is the only interesting one. Maybe a different response if you are desperate for a job. Maybe you would get the job for walking out... Nov 14 '05 #8

 P: n/a "Mabden" wrote in message news:B5uDc.6258 Maybe you would get the job for walking out... That might be too out of the box :). Nov 14 '05 #9

 P: n/a "Jerry Coffin" wrote in message news:b2*************************@posting.google.co m... Almost anything you'd normally do with iteration can also be done with tail recursion. What is "tail" recursion? Are there other types of recursion? Any the question says not to use loops. But to me, recursion is a loop, just expressed differently. Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator. One is to just add x together 7 times. Those of us who remember writing multiplication routines for old processors that didn't have multiply instructions can easily reduce that to (x<<2)|(x<<1)|x. Those who've studied Booth's algorithm might try (x<<3)-x, though without extra bits for the intermediate value, this can overflow. Are these methods faster than x*7 on modern processors? Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7 If you want to get clever with boolean values, you could try: int f(int x) { return (x==7*4)+(x==4*7); } Huh? I'm sure there are more variations as well. Probably something with mod or %. Q7 Remove duplicates in array You can't really "remove" an element from an array, so this is poorly defined. If it was a C++ vector (for example) std::sort and std::unique would render it trivial, as would inserting the elements into an std::set, and then copying them back out. Doing it quickly while retaining the original order is a little more challenging. The sort method is O(N*lg(N)) + O(N) if we use comparison sort. But doing it in place without changing the order seems to be an O(N^2) algorithm, with the outer loop i running from [0, N) and the inner loop j running from [0, i). (Seems most people run the inner loop from [i+1, N) and then they run into problems of how to detect if you've not seen the element already.) Q8 Finding if there is any loop inside linked list. One obvious way would be to create a set of pointers to nodes. Walk the list, inserting each node's address into the set. Quit when you reach a node with next == NULL (there's no loop) or a node whose address is already in the set (there's a loop). There's an alternative that saves memory, but basically destroys the list if it does contain a loop: as you walk the list, modify each 'next' pointer to point at the previous node. Eventually, you'll reach either a node with next==NULL, in which case there's no loop, or else you'll get back to the original head of the list (in which case there's a loop, and you've wreaked havoc on your list). If the list doesn't contain a loop, you can re-walk it, again reversing each pointer, to restore the original list. Better yet, just ensure the list is constructed sanely, and you'll know the answer up-front. There's another. Have two iterators, first one pointing to first element, the second pointing to the second. The second one is the fast iterator and you increment it twice in each iteration. The first iterator is the slow iterator and you increment it once in each iteration. If the list is not circular the fast iterator will hit NULL at some point. If the list is circular the fast iterator will equal to the slow iterator at some point. Nov 14 '05 #11

 P: n/a Siemel Naran scribbled the following on comp.lang.c: "Jerry Coffin" wrote in message news:b2*************************@posting.google.co m... Almost anything you'd normally do with iteration can also be done with tail recursion. What is "tail" recursion? Are there other types of recursion? Tail recursion is first doing the computation, then recursing. Head recursion is the other way around. Any the question says not to use loops. But to me, recursion is a loop, just expressed differently. They're clearly different concepts. At least in C, recursion has a separate local scope for all levels, while looping reuses the same local scope for all iterations. > Q6 C/C++ : Write a function in different ways that will return f(7) = > 4 and f(4) = 7 If you want to get clever with boolean values, you could try: int f(int x) { return (x==7*4)+(x==4*7); } Huh? In C, the == operator returns 1 if the operands match or 0 if they don't. Go from there. -- /-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\ \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/ "The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners." - Ernst Jan Plugge Nov 14 '05 #12

 P: n/a "Siemel Naran" wrote:"Jerry Coffin" wrote in messagenews:b2*************************@posting.google.c om... > Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator. If you want to get clever with boolean values, you could try: int f(int x) { return (x==7*4)+(x==4*7); }Huh? I'm pretty sure Jerry meant to write: return (x==7)*4 + (x==4)*7; Regards -- Irrwahn Grausewitz (ir*******@freenet.de) welcome to clc: http://www.ungerhu.com/jxh/clc.welcome.txt clc faq-list : http://www.faqs.org/faqs/C-faq/faq/ clc OT guide : http://benpfaff.org/writings/clc/off-topic.html Nov 14 '05 #13

 P: n/a Joona I Palaste wrote:Siemel Naran scribbled the followingon comp.lang.c: "Jerry Coffin" wrote in message news:b2*************************@posting.google.co m... > Q6 C/C++ : Write a function in different ways that will return f(7) = > 4 and f(4) = 7 If you want to get clever with boolean values, you could try: int f(int x) { return (x==7*4)+(x==4*7); } Huh?In C, the == operator returns 1 if the operands match or 0 if theydon't. Go from there. Now f returns 2 if x equals 28, or 0 otherwise. Great solution. ;-) Regards -- Irrwahn Grausewitz (ir*******@freenet.de) welcome to clc: http://www.ungerhu.com/jxh/clc.welcome.txt clc faq-list : http://www.faqs.org/faqs/C-faq/faq/ clc OT guide : http://benpfaff.org/writings/clc/off-topic.html Nov 14 '05 #14

 P: n/a Irrwahn Grausewitz scribbled the following on comp.lang.c: "Siemel Naran" wrote:"Jerry Coffin" wrote in messagenews:b2*************************@posting.google. com... > Q5 C/C++ : Multiply x by 7 without using multiplication (*) operator. If you want to get clever with boolean values, you could try: int f(int x) { return (x==7*4)+(x==4*7); }Huh? I'm pretty sure Jerry meant to write: return (x==7)*4 + (x==4)*7; Dang! I didn't spot that in my original reply. Jerry's original code is equivalent to return (x==28)+(x==28), which will return 2 if x==28 but 0 if not. -- /-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\ \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/ "You can pick your friends, you can pick your nose, but you can't pick your relatives." - MAD Magazine Nov 14 '05 #15

 P: n/a Irrwahn Grausewitz scribbled the following on comp.lang.c: Joona I Palaste wrote:Siemel Naran scribbled the followingon comp.lang.c: "Jerry Coffin" wrote in message news:b2*************************@posting.google.co m... > Q6 C/C++ : Write a function in different ways that will return f(7) = > 4 and f(4) = 7 If you want to get clever with boolean values, you could try: int f(int x) { return (x==7*4)+(x==4*7); } Huh?In C, the == operator returns 1 if the operands match or 0 if theydon't. Go from there. Now f returns 2 if x equals 28, or 0 otherwise. Great solution. ;-) Yes, I noticed it myself later, as you can see. In my defense, it was Jerry who wrote the incorrect code, I just failed to correct it... =) -- /-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\ \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/ "And according to Occam's Toothbrush, we only need to optimise the most frequent instructions." - Teemu Kerola Nov 14 '05 #16

 P: n/a Jerry Coffin wrote: js*******@sancharnet.in (Jatinder) wrote in message news:<22**************************@posting.google. com>... {snip] Q6 C/C++ : Write a function in different ways that will return f(7) =4 and f(4) = 7 [snip] I'm sure there are more variations as well. int f(int x) { return 11 - x; } boa [snip] Nov 14 '05 #18

 P: n/a Jatinder wrote: Q3 C/C++ : Exchange two numbers without using a temporary variable. Isn't the bitwise solution safe only for unsigned integrals? Regards, Ioannis Vranos Nov 14 '05 #19

 P: n/a Siemel Naran wrote: Q4 C/C++ : Find if the given number is a power of 2.Easy with some bitwise arithmetic. x & (x-1) evaluates to zero if the number is an exact power of 2. The OP cross posted both in clc++ and clc, and the set of questions obviously consider C as a subset of C++, a dangerous thing to do but anyway. However in both cases bitwise operations are guaranteed to be safe only on unsigned integrals, so the above had better include the remark: "where x is of unsigned integral type". Regards, Ioannis Vranos Nov 14 '05 #20

 P: n/a CBFalconer wrote: int main (void){ if (printf("Hello World")) {} if (exit(EXIT_SUCCESS)) {}} Illegal. No #include for prototype of variadic function, nor EXIT_SUCCESS value, and exit is a void function. The compiler should barf. #include #include int main (void) { if (printf("Hello World")) {} /* Only needed for C90 compliance */ if (exit(EXIT_SUCCESS),1){} } Regards, Ioannis Vranos Nov 14 '05 #21

 P: n/a Ioannis Vranos wrote: Jatinder wrote: Q3 C/C++ : Exchange two numbers without using a temporary variable. Isn't the bitwise solution safe only for unsigned integrals? I just checked the standard, it is safe for both integral and enumeration types. Regards, Ioannis Vranos Nov 14 '05 #22

 P: n/a Ioannis Vranos wrote: However in both cases bitwise operations are guaranteed to be safe only on unsigned integrals, so the above had better include the remark: "where x is of unsigned integral type". Just checked the C++98 standard, and they are valid for both integral types and enumerations so what I said above is not needed. Regards, Ioannis Vranos Nov 14 '05 #23

 P: n/a On Sat, 26 Jun 2004, Jatinder wrote: I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles. Programming Puzzles Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions. [bunch of questions snipped] Learn to use a search engine. The answer to the questions and many other questions are readily available on the internet. You just need to learn to search for them. Hint: http://groups.google.ca. -- Send e-mail to: darrell at cs dot toronto dot edu Don't send e-mail to vi************@whitehouse.gov Nov 14 '05 #24

 P: n/a "Siemel Naran" wrote in message news:... "Jerry Coffin" wrote in message news:b2*************************@posting.google.co m... Almost anything you'd normally do with iteration can also be done with tail recursion. What is "tail" recursion? Are there other types of recursion? Tail recursion is when the recursive call is the final step of an algorithm. If the recursive call isn't the final step, it's not tail recursion. In some cases, of course, an algorithm with some other execution pattern can be converted to a tail-recursive form, but others can't (especially those that include two or more recursive calls). Any the question says not to use loops. But to me, recursion is a loop, just expressed differently. Both certainly express the concept of repeated execution of some set of instructions. I'm less certain of characterizing all iteration as a loop though. [ ... ] Are these methods faster than x*7 on modern processors? Sometimes they are, other times they're not. The correct answer will often depend as much on surrounding instructions as it does on the processor. Q6 C/C++ : Write a function in different ways that will return f(7) = 4 and f(4) = 7 If you want to get clever with boolean values, you could try: int f(int x) { return (x==7*4)+(x==4*7); } Huh? As has already been noted, I mis-parenthesized that. It should have been "return (x==7)*4+(x==4)*7;" It's based on the fact that in C a 'true' result has the value 1, and a 'false' result has the value 0. C++ has a type specifically for booleans, but for backward compatibility it still allows them to be implicitly converted to integer types. I'm sure there are more variations as well. Probably something with mod or %. Maybe -- OTOH, that's sort of the basis of the 'x^3' version. There's another. Have two iterators, first one pointing to first element, the second pointing to the second. The second one is the fast iterator and you increment it twice in each iteration. The first iterator is the slow iterator and you increment it once in each iteration. If the list is not circular the fast iterator will hit NULL at some point. If the list is circular the fast iterator will equal to the slow iterator at some point. Yes -- I'd seen that posted elsewhere so I didn't repost it, but it IS pretty clever. -- Later, Jerry. The universe is a figment of its own imagination. Nov 14 '05 #25

 P: n/a Siemel Naran wrote: "Mabden" wrote in message news:B5uDc.6258 Maybe you would get the job for walking out... That might be too out of the box :). A job interview is for finding a match. The company is also under the microscope. Would you really want to work for a company who gives this as the big programming test? Nov 14 '05 #26

 P: n/a js*******@sancharnet.in (Jatinder) wrote in message news:<22**************************@posting.google. com>... I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles. Programming Puzzles Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions. Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; I'll try it in C, should be portable to C++: #include int p(int x, int i) { (x > 100) && (i = -1); (x > 0 && x < 101) && printf("%d\n", x); (x > 0) && p(x + i, i); return 1; } int main(void) { p(1, 1); return 0; } Gregory Pietsch Nov 14 '05 #27

 P: n/a js*******@sancharnet.in (Jatinder) wrote in message news:<22**************************@posting.google. com>... I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles. Programming Puzzles Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions. Q3 (the same as the other you mentioned, basically) took me less than a minute to solve, and I'm only 16: /* vim:ts=4 */ #include int main(void) { int foo = 87; int bar = 56; foo += bar; bar = foo - bar; foo = foo - bar; fprintf(stdout, "%i, %i\n", foo, bar); } Try other values for foo & bar, even negatives and zero. You mentioned MS often use these sorts of puzzles to test their programmers. I got an even better one to stump even the best MS programmers: /* vim:ts=4 */ #include int main(void) { int *foo = NULL; fprintf(stdout, "%i\n", *foo); } What will happen if I compile and run this program?? Nov 14 '05 #28

 P: n/a Am I the only person here that thinks it's complete bullshit to think you can swap the values of two variables without a temporary variable?! It simply cannot be done. Why? Consider this, you have two containers, each of capacity 3 litres. Each of them is filled with 2 litres of water. Swap the water from the containers. Okay... let's just poor all of one of them into the other. Mammy mammy! It was an accident, I didn't realize you can't put 4 litres of water into a 3 litre container. Fools. -JKop Nov 14 '05 #29

 P: n/a JKop scribbled the following on comp.lang.c: Am I the only person here that thinks it's complete bullshit to think you can swap the values of two variables without a temporary variable?! It simply cannot be done. Why? Consider this, you have two containers, each of capacity 3 litres. Each of them is filled with 2 litres of water. Swap the water from the containers. Okay... let's just poor all of one of them into the other. Mammy mammy! It was an accident, I didn't realize you can't put 4 litres of water into a 3 litre container. Fools. It *can* be done! Not with all kinds of variables, but with unsigned integer types, it's easy. Not one, but *two* ways to do it have been shown in this thread. Of course it will break down if those variables happen to share the same memory location, which can be the case if using pointers and indirecting through them. -- /-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\ \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/ "I am not very happy acting pleased whenever prominent scientists overmagnify intellectual enlightenment." - Anon Nov 14 '05 #30

 P: n/a Joona I Palaste wrote: JKop scribbled the following on comp.lang.c:Am I the only person here that thinks it's complete bullshit to think youcan swap the values of two variables without a temporary variable?! Itsimply cannot be done. Why? Consider this, you have two containers, each ofcapacity 3 litres. Each of them is filled with 2 litres of water. Swap thewater from the containers. Okay... let's just poor all of one of them intothe other. Mammy mammy! It was an accident, I didn't realize you can't put 4litres of water into a 3 litre container.Fools. It *can* be done! Not with all kinds of variables, but with unsigned integer types, it's easy. Not one, but *two* ways to do it have been shown in this thread. Of course it will break down if those variables happen to share the same memory location, which can be the case if using pointers and indirecting through them. The "xor" method works on all unsigned integer types, and [OT] if you program in assembler, it works on any two memory locations or registers unless you cause a trap along the way. [/OT] However the arithemetic method upthread, i.e. foo += bar; bar = foo - bar; foo = foo - bar; may fail if you get unsigned integer overflow, at least I think *may* fail. This may be the case of the container not being able to hold 4 litres. What does the C-standard say about unsigned integer overflow? NPL PS. - [OT] there are, of course, languages which do not have the "exlusive OR" operator. But they're not C [/OT] Nov 14 '05 #31

 P: n/a Nick Landsberg scribbled the following on comp.lang.c: Joona I Palaste wrote: JKop scribbled the following on comp.lang.c:Am I the only person here that thinks it's complete bullshit to think youcan swap the values of two variables without a temporary variable?! Itsimply cannot be done. Why? Consider this, you have two containers, each ofcapacity 3 litres. Each of them is filled with 2 litres of water. Swap thewater from the containers. Okay... let's just poor all of one of them intothe other. Mammy mammy! It was an accident, I didn't realize you can't put 4litres of water into a 3 litre container.Fools. It *can* be done! Not with all kinds of variables, but with unsigned integer types, it's easy. Not one, but *two* ways to do it have been shown in this thread. Of course it will break down if those variables happen to share the same memory location, which can be the case if using pointers and indirecting through them. The "xor" method works on all unsigned integer types, and [OT] if you program in assembler, it works on any two memory locations or registers unless you cause a trap along the way. [/OT] The "xor" method will *not* work on two variables with the same memory location. You'd expect the swap to be a no-op, but it ends up setting both variables to 0, because it "xors" the first variable with itself, yielding 0, and then keeps "xorring" this 0 with itself. -- /-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\ \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/ Nov 14 '05 #32

 P: n/a Joona I Palaste wrote: Nick Landsberg scribbled the following on comp.lang.c:Joona I Palaste wrote:JKop scribbled the followingon comp.lang.c:Am I the only person here that thinks it's complete bullshit to think youcan swap the values of two variables without a temporary variable?! Itsimply cannot be done. Why? Consider this, you have two containers, each ofcapacity 3 litres. Each of them is filled with 2 litres of water. Swap thewater from the containers. Okay... let's just poor all of one of them intothe other. Mammy mammy! It was an accident, I didn't realize you can't put 4litres of water into a 3 litre container.Fools.It *can* be done! Not with all kinds of variables, but with unsignedinteger types, it's easy. Not one, but *two* ways to do it have beenshown in this thread. Of course it will break down if those variableshappen to share the same memory location, which can be the case if usingpointers and indirecting through them.The "xor" method works on all unsigned integer types,and [OT] if you program in assembler, it works onany two memory locations or registers unless youcause a trap along the way. [/OT] The "xor" method will *not* work on two variables with the same memory location. You'd expect the swap to be a no-op, but it ends up setting both variables to 0, because it "xors" the first variable with itself, yielding 0, and then keeps "xorring" this 0 with itself. You are correct. I should have said two different/distinct memory locations. -- "It is impossible to make anything foolproof because fools are so ingenious" - A. Bloch Nov 14 '05 #33

 P: n/a "Wayne Rasmussen" wrote in message news:40***************@gomonarch.com... Siemel Naran wrote: "Mabden" wrote in message news:B5uDc.6258 Maybe you would get the job for walking out... That might be too out of the box :). A job interview is for finding a match. The company is also under the microscope. Would you really want to work for a company who gives this as the big programming test? I just "interviewed" with a company in Los Angeles (that little country between Mexico and USA). They didn't even talk to me at all. They handed me a "personality test", which also included an intelligence test (and I've been through Mensa testing - it was hard), and sat me in a room for 2 hours. At the end they took the answer sheet and said they'd get back to me. I passed the test, I guess, because I get to go back next week for another 2 hour programming test. If I pass that, I get to move to round three which is to face a panel of their programmers in a room for questioning. I'm guessing it'll be about 2 hours... Whee... -- Mabden p.s. Here's one I missed: What is the next letter in this sequence: A F Z U G L T ? 1. O 2. C 3. X 4. N p.p.s. I figured it out later. ("You think you're better than me?!!") Nov 14 '05 #34

 P: n/a "boa" wrote in message news:21*****************@juliett.dax.net... Jerry Coffin wrote: js*******@sancharnet.in (Jatinder) wrote in message news:<22**************************@posting.google. com>... {snip]Q6 C/C++ : Write a function in different ways that will return f(7) =4 and f(4) = 7 [snip] I'm sure there are more variations as well. int f(int x) { return 11 - x; } Very nice! -- Mabden Nov 14 '05 #35

 P: n/a Mabden scribbled the following on comp.lang.c: "Wayne Rasmussen" wrote in message news:40***************@gomonarch.com... Siemel Naran wrote: > "Mabden" wrote in message news:B5uDc.6258 > > Maybe you would get the job for walking out... > > That might be too out of the box :). A job interview is for finding a match. The company is also under the microscope. Would you really want to work for a company who gives this as the big programming test? I just "interviewed" with a company in Los Angeles (that little country between Mexico and USA). They didn't even talk to me at all. They handed me a "personality test", which also included an intelligence test (and I've been through Mensa testing - it was hard), and sat me in a room for 2 hours. At the end they took the answer sheet and said they'd get back to me. I passed the test, I guess, because I get to go back next week for another 2 hour programming test. If I pass that, I get to move to round three which is to face a panel of their programmers in a room for questioning. I'm guessing it'll be about 2 hours... Whee... Unbelievable. I rmemember *my* latest job interview. The company's CEO and I sat in the corridor of a Finnish technology enterprise building, where the company's offices were located at the time, and talked for a few hours about what I'm like as an employee. Later, I, the CEO and the company's chief programmer met in a restaurant and talked about what I am like as a programmer. The company paid for my dinner. Then I was going about minding my own business when I got a call that I had got the job. That's all there was to it. No tests, no panel hearings, just a few hours of talk. -- /-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\ \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/ "Hasta la Vista, Abie!" - Bart Simpson Nov 14 '05 #36

 P: n/a "Foobarius Frobinium" wrote in message news:a7**************************@posting.google.c om... js*******@sancharnet.in (Jatinder) wrote in message news:<22**************************@posting.google. com>... You mentioned MS often use these sorts of puzzles to test their programmers. I got an even better one to stump even the best MS programmers: #include int main(void) { int *foo = NULL; fprintf(stdout, "%i\n", *foo); } What will happen if I compile and run this program?? You'll get a warning saying main() has no return value. Nov 14 '05 #37

 P: n/a "Nick Landsberg" wrote in message news:uC*******************@bgtnsc05-news.ops.worldnet.att.net... The "xor" method will *not* work on two variables with the same memory location. You'd expect the swap to be a no-op, but it ends up setting both variables to 0, because it "xors" the first variable with itself, yielding 0, and then keeps "xorring" this 0 with itself. You are correct. I should have said two different/distinct memory locations. Uuuuhhh... if the two "variables" point to the same location, then the swap is done! -- Mabden Nov 14 '05 #38

 P: n/a "Joona I Palaste" wrote in message news:cb**********@oravannahka.helsinki.fi... Mabden scribbled the following on comp.lang.c: "Wayne Rasmussen" wrote in message news:40***************@gomonarch.com... Siemel Naran wrote: > "Mabden" wrote in message news:B5uDc.6258 > > Maybe you would get the job for walking out... > > That might be too out of the box :). A job interview is for finding a match. The company is also under the microscope. Would you really want to work for a company who gives this as the big programming test? I just "interviewed" with a company in Los Angeles (that little country between Mexico and USA). They didn't even talk to me at all. They handed me a "personality test", which also included an intelligence test (and I've been through Mensa testing - it was hard), and sat me in a room for 2 hours. At the end they took the answer sheet and said they'd get back to me. I passed the test, I guess, because I get to go back next week for another 2 hour programming test. If I pass that, I get to move to round three which is to face a panel of their programmers in a room for questioning. I'm guessing it'll be about 2 hours... Whee... Unbelievable. I rmemember *my* latest job interview. The company's CEO and I sat in the corridor of a Finnish technology enterprise building, where the company's offices were located at the time, and talked for a few hours about what I'm like as an employee. Later, I, the CEO and the company's chief programmer met in a restaurant and talked about what I am like as a programmer. The company paid for my dinner. Then I was going about minding my own business when I got a call that I had got the job. That's all there was to it. No tests, no panel hearings, just a few hours of talk. Yup. Those are the best kinds of "interviews", and generally only happen for highly-qualified candidates. My last 2 jobs were like that, and both were 6 figure programming jobs. Ah, those were the days... Those BS interviews asking about how to twiddle bits are a waste of time. If I can't recall an exact algorithm, I just look it up in one of my many reference books, including the 3 volumes of Knuth. The overall approach to solving a problem and how I think about designing a solution is what's really important. Don't sweat the small things, that's what junior programmers are for. Nov 14 '05 #39

 P: n/a Joona I Palaste wrote: It *can* be done! Not with all kinds of variables, but with unsigned integer types, I had somewhere in my mind the unsigned restriction, but then I checked the standard and saw that xor is safe to be applied on both integral types and enumerations. Then how does this unsigned restriction come? "5.12 Bitwise exclusive OR operator exclusive-or-expression: and-expression exclusive-or-expression ^ and-expression The usual arithmetic conversions are performed; the result is the bitwise exclusive OR function of the operands. The operator applies only to integral or enumeration operands." Regards, Ioannis Vranos Nov 14 '05 #40

 P: n/a Joona I Palaste wrote: It *can* be done! Not with all kinds of variables, but with unsigned integer types, I had somewhere in my mind the unsigned restriction, but then I checked the standard and saw that XOR is safe to be applied on both integral types and enumerations. Then how does this unsigned restriction come? "5.12 Bitwise exclusive OR operator exclusive-or-expression: and-expression exclusive-or-expression ^ and-expression The usual arithmetic conversions are performed; the result is the bitwise exclusive OR function of the operands. The operator applies only to integral or enumeration operands." Regards, Ioannis Vranos Nov 14 '05 #41

 P: n/a Jatinder wrote: I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles. Programming Puzzles Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions. Ok I couldn't resist so I 'll give my answers to these questions. As a poster has done previously, where "C" is mentioned I consider C++98 (I view these from clc++). Q1 Write a "Hello World" program in 'C' without using a semicolon. #include int main() { if(std::cout<<"Hello World!\n") {} } Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; #include template inline void printinc(T i, const T limit) { std::cout< inline void printdec(T i, const T limit) { std::cout<limit) printdec(--i, limit); } int main() { using namespace std; printinc(1, 100); cout< int main() { using std::swap; int x=1, y=2; swap(x,y); } Q4 C/C++ : Find if the given number is a power of 2. #include #include #include bool IsPowerOfTwo(unsigned long x) { using namespace std; // It is safe for unusual implementations where bytes // are more than 8 bits. bitset::digits>bitRep=x; unsigned nonZeroBits=0; for(size_t i=0; i int main() { using namespace std; int x=3, temp=x; x<<=3; x-=temp; cout< int main() { using std::swap; int x=1, y=2; swap(x,y); } :-P Given an array (group) of numbers write all the possible sub groups of this group. std::next_permutation and std::prev_permutation. An example: #include #include #include int main() { using namespace std; string s="abcd"; do cout<

 P: n/a Ioannis Vranos wrote: Well some errata. :-) Q1 Write a "Hello World" program in 'C' without using a semicolon. #include int main() { if(std::cout<<"Hello World!\n") {} } Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; Note: There is a restriction for if statements, but if statements do not constitute a loop. #include template inline void printinc(T i, const T limit) { std::cout< inline void printdec(T i, const T limit) { std::cout<limit) printdec(--i, limit); } int main() { using namespace std; printinc(1, 100); cout< #include #include bool IsPowerOfTwo(unsigned long x) { using namespace std; // It is safe for unusual implementations where bytes // are more than 8 bits. bitset::digits>bitRep=x; bitset::digits*sizeof(x)>bitRep=x; unsigned nonZeroBits=0; for(size_t i=0; i

 P: n/a Jatinder wrote: I found these questions on a web site and wish to share with all of u out there,Can SomeOne Solve these Porgramming puzzles. Programming Puzzles Some companies certainly ask for these things. Specially Microsoft. Here are my favorite puzzles. Don't send me emails asking for the solutions. Ok I couldn't resist so I 'll give my answers to these questions. As a poster has done previously, where "C" is mentioned I consider C++98 (I view these from clc++). Q1 Write a "Hello World" program in 'C' without using a semicolon. #include int main() { if(std::cout<<"Hello World!\n") {} } Q2 Write a C++ program without using any loop (if, for, while etc) to print numbers from 1 to 100 and 100 to 1; Note: There is a restriction for if statements, but if statements do not constitute a loop. #include template inline void printinc(T i, const T limit) { std::cout< inline void printdec(T i, const T limit) { std::cout<limit) printdec(--i, limit); } int main() { using namespace std; printinc(1, 100); cout< int main() { using std::swap; int x=1, y=2; swap(x,y); } Q4 C/C++ : Find if the given number is a power of 2. #include #include #include bool IsPowerOfTwo(unsigned long x) { using namespace std; // It is safe for unusual implementations where bytes // are more than 8 bits. bitset::digits*sizeof(x)>bitRep=x; unsigned nonZeroBits=0; for(size_t i=0; i int main() { using namespace std; int x=3, temp=x; x<<=3; x-=temp; cout< int main() { using std::swap; int x=1, y=2; swap(x,y); } :-P Given an array (group) of numbers write all the possible sub groups of this group. std::next_permutation and std::prev_permutation. An example: #include #include #include int main() { using namespace std; string s="abcd"; do cout<

 P: n/a Ioannis Vranos wrote: > Given an array (group) of numbers write all the possible sub groups of > this group. std::next_permutation and std::prev_permutation. An example: #include #include #include int main() { using namespace std; int array[4]={1,2,3,4}; for(int*p=array, *r=&array[4]; p!=r; --r) { vectortemparray(p,r); do { for(vector::size_type i=0; i