Programming Puzzle

J

Jatinder

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.
 
J

Joona I Palaste

Jatinder <[email protected]> scribbled the following
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.
 
C

Christian Bau

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

Assuming that these questions are from an interview for a programming
job, I must say that most of them are incredibly useless at finding a
good programmer. Take Q3: The correct answer is: Why would anyone want
to do that? Take Q10: You know the answer or you don't. If your name is
Gödel or Turing, you might find a solution on your own, but otherwise
this just tests some very obscure knowledge. I guess these questions are
only used to check your reaction to a stressful situation (which is also
an incredibly useless way at finding a good programmer).

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.
 
S

Siemel Naran

Joona I Palaste said:
Jatinder <[email protected]> scribbled the following

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.
Easy with some bitwise arithmetic.

x & (x-1) evaluates to zero if the number is an exact power of 2.
Easy peasy. Repeated addition will do the trick.


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.
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 }?
Should be covered in any basic data structures course.


Impossible without access into a no key access database.

What is Q9 about?
Google for "quine".

Bizarre stuff!
This one is actually a full-blown game.


And how is this any different from Q3?


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 "".
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.
 
A

Allan Bruce

Siemel Naran said:
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
 
C

CBFalconer

Allan said:
.... 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".
 
M

Mabden

Christian Bau said:
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...
 
J

Jerry Coffin

(e-mail address removed) (Jatinder) wrote in message
[ ... ]
Q1 Write a "Hello World" program in 'C' without using a semicolon.

One obvious method (open to a number of variations) is:

#include <stdio.h>

int main() {
if ( printf("Hello world"))
{}
}
Q2 Write a C++ program without using any loop (if, for, while etc) to
print numbers from 1 to 100 and 100 to 1;

Almost anything you'd normally do with iteration can also be done with
tail recursion.
Q3 C/C++ : Exchange two numbers without using a temporary variable.

This has come up about 4 weeks into every new semester for years, with
a slightly lighter treatment on a quarterly basis.
Q4 C/C++ : Find if the given number is a power of 2.

There are many ways. Pick N as a power of 2, and compare it to N-1
and see if something doesn't occur to you.
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.
Q6 C/C++ : Write a function in different ways that will return f(7) =
4 and f(4) = 7

Obvious:
int f(int x) {
if ( x == 7)
return 4;
if ( x == 4)
return 7;
}
Roughly as obvious is to use switch/case intsead.

Using arrays, you can do things like:

int f(int x) {
int rets[] = { 4, 7};
return rets[x>>2];
}

Or if you want to ensure defined results for inputs other than 4 or 7:

int f(int x) {
int rets[] = {4,7};
return rets[(x>>2)&1];
}

If you want to get clever with boolean values, you could try:

int f(int x) {
return (x==7*4)+(x==4*7);
}

or:

int f(int x) {
rturn (x==7*4)|(x==4*7);
}

If you prefer strictly bit-wise manipulation, you might prefer:

int f(int x) {
return x ^ 3;
}

I'm sure there are more variations as well.
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.
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.
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.

Much like Q3, but comes up a little further into the semster/quarter.
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.

If I'm figuring this correctly, it's a pretty boring game. If I go
first, I pick '1' on my first two moves, and you can't win. If I go
second, I pick '2' on my first three moves, and you can't win.

Tic-tac-toe quickly gets boring because neither player can win unless
his opponent makes a mistake. This is even worse, because the same is
true, BUT a player doesn't even have to look at what his opponent has
done to avoid a mistake. The only challenge is ensuring that you take
advantage when he does make a mistake, and (again, assuming I'm
figuring things correctly) that should be quite trivial.
Given an array (group) of numbers write all the possible sub groups of
this group.

Recursion is probably your friend on this one as well.

Q14 Convert (integer) number in binary without loops.

As mentioned wrt Q2, almost any iteration is trivially expressed as
tail recursion. The wording doesn't make it clear whether this is
supposed to be a conversion FROM binary or TO binary, but either is
pretty easy to do recursively.
 
S

Siemel Naran

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.
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?
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 %.
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.)
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.
 
J

Joona I Palaste

Siemel Naran <[email protected]> scribbled the following
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.

In C, the == operator returns 1 if the operands match or 0 if they
don't. Go from there.

--
/-- Joona Palaste ([email protected]) ------------- 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
 
I

Irrwahn Grausewitz

Joona I Palaste said:
Siemel Naran <[email protected]> scribbled the following



In C, the == operator returns 1 if the operands match or 0 if they
don't. Go from there.

Now f returns 2 if x equals 28, or 0 otherwise. Great solution. ;-)

Regards
 
J

Joona I Palaste

Irrwahn Grausewitz <[email protected]> scribbled the following
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 ([email protected]) ------------- 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
 
J

Joona I Palaste

Irrwahn Grausewitz <[email protected]> scribbled the following
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 ([email protected]) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"And according to Occam's Toothbrush, we only need to optimise the most frequent
instructions."
- Teemu Kerola
 
P

Prawit Chaivong

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.

Q3 & Q12

int main()
{
int a = 10;
int b = 20;

/* Swap here */

a ^= b;
b ^= a;
a ^= b;

/* Show value code */
/* .........
* .........
*/


return 0;
}

Please correct me, if I'm wrong. :)
 
I

Ioannis Vranos

Jatinder said:
Q3 C/C++ : Exchange two numbers without using a temporary variable.


Isn't the bitwise solution safe only for unsigned integrals?






Regards,

Ioannis Vranos
 
I

Ioannis Vranos

Siemel said:
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
 
I

Ioannis Vranos

CBFalconer said:
Illegal. No #include for prototype of variadic function, nor
EXIT_SUCCESS value, and exit is a void function. The compiler
should barf.



#include <stdio.h>
#include <stdlib.h>



int main (void)
{
if (printf("Hello World")) {}

/* Only needed for C90 compliance */
if (exit(EXIT_SUCCESS),1){}
}






Regards,

Ioannis Vranos
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top