473,854 Members | 1,879 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Programming Puzzle

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
271 20406
JKop wrote:
John Cochran posted:

1. 200 100
2. 44 100
3. 44 200
4. 100 200


I see! I thought that yous weren't paying attention to over/under-flow.
Nobody mentioned it at all, so I just pressumed. So is this non-undefined
behaviour?

For *unsigned integers*, the behaviour is well-defined both for overflow
and underflow (it wraps around). So you can get the maximum value of an
unsigned integer by using -1. This one is used *extensively*.

For example:
// Equivalent to unsigned long li=numeric_limi ts<unsigned long>::max();
unsigned long li=-1;
unsigned char uc=-1;

and so on.


Regards,

Ioannis Vranos
Nov 14 '05 #71
In <zo************ ****@newssvr27. news.prodigy.co m> "Mabden" <mabden@sbc_glo bal.net> writes:
"Foobarius Frobinium" <fo******@youre mailbox.com> wrote in message
news:a7******* *************** ****@posting.go ogle.com...
js*******@sanch arnet.in (Jatinder) wrote in message

news:<22****** *************** *****@posting.g oogle.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 <stdio.h>

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.


Chapter and verse, please.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #72
In <cb**********@o ravannahka.hels inki.fi> Joona I Palaste <pa*****@cc.hel sinki.fi> writes:
JKop <NU**@null.null > 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.


The only foolish assumption is that bits behave like water...
It *can* be done! Not with all kinds of variables, but with unsigned
integer types, it's easy.
If you can do it with unsigned integer types, you can do it with all kinds
of objects, by aliasing them with arrays of unsigned char.
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.


OTOH, if you're using pointers, there's nothing preventing you from
testing the pointers for equality, before starting, is there?

So, the method can be universally used in C, if there is a *good* reason.
And the only good reason I can imagine is the failure to allocate memory
for a temporary object (some objects can be greater than others, some
systems can have smaller memories than others...).

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #73
In <cb**********@u lysses.noc.ntua .gr> Ioannis Vranos <iv*@guesswh.at .grad.com> writes:
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?


C99 answer:

4 Some operators (the unary operator ~, and the binary operators
<<, >>, &, ^, and |, collectively described as bitwise
operators) are required to have operands that have integer
type. These operators return values that depend on the internal
representations of integers, and have implementation-defined
and undefined aspects for signed types.

Consider, for example, 0 ^ 0, whose result (an int with all bits set) is
a trap representation, as explicitly allowed by C99 for one's complement.

It's hard to find an example for two's complement using the ^ operator,
but it can be done with ~INT_MAX, if the representation with the sign
bit set and all the value bits reset is a trap representation (again,
explicitly allowed by C99 for two's complement and sign-magnitude).

Whether real world implementations have such trap representations is a
completely different story...

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #74
Dan Pop wrote:

In <cb**********@o ravannahka.hels inki.fi> Joona I Palaste <pa*****@cc.hel sinki.fi> writes:
JKop <NU**@null.null > 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.


The only foolish assumption is that bits behave like water...
It *can* be done! Not with all kinds of variables, but with unsigned
integer types, it's easy.


If you can do it with unsigned integer types, you can do it with all kinds
of objects, by aliasing them with arrays of unsigned char.
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.


Please describe (in code) a situation where two variables share the same memory
location.

OTOH, if you're using pointers, there's nothing preventing you from
testing the pointers for equality, before starting, is there?

So, the method can be universally used in C, if there is a *good* reason.
And the only good reason I can imagine is the failure to allocate memory
for a temporary object (some objects can be greater than others, some
systems can have smaller memories than others...).

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de

Nov 14 '05 #75
Jerry Coffin wrote:
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.


How can you _not_ remove an element from an array?

Here is a trivial case:

size_t count = 2;
int * array = (int *)malloc(sizeof (int) * count);
array[0] = 42;
array[1] = 9000;
array = (int *)realloc(array , sizeof(int) * (--count));

Are you saying that an element hasn't been removed?
Nov 14 '05 #76

"Julie" <ju***@nospam.c om> wrote in message
news:40******** *******@nospam. com...
Jerry Coffin wrote:
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.


How can you _not_ remove an element from an array?

Here is a trivial case:

size_t count = 2;
int * array = (int *)malloc(sizeof (int) * count);
array[0] = 42;
array[1] = 9000;
array = (int *)realloc(array , sizeof(int) * (--count));

Are you saying that an element hasn't been removed?


Well, that's not *really* removing an element from the array, it's simply
reallocating data storage. How would your example look if you wanted to
remove an element from other than the last position? You'd have to write
code to shift the other elements to the front of the array, not just resize
the memory allocation.

-Howard


Nov 14 '05 #77
Howard wrote:

"Julie" <ju***@nospam.c om> wrote in message
news:40******** *******@nospam. com...
Jerry Coffin wrote:
> 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.
How can you _not_ remove an element from an array?

Here is a trivial case:

size_t count = 2;
int * array = (int *)malloc(sizeof (int) * count);
array[0] = 42;
array[1] = 9000;
array = (int *)realloc(array , sizeof(int) * (--count));

Are you saying that an element hasn't been removed?


Well, that's not *really* removing an element from the array, it's simply
reallocating data storage.


Well, if that isn't removing, then I don't know what is... Reallocation is
merely an implementation detail, net result is that an element has been
removed.
How would your example look if you wanted to
remove an element from other than the last position? You'd have to write
code to shift the other elements to the front of the array, not just resize
the memory allocation.


Exactly. I started w/ the trivial case of removing the last element. Removing
any other position would merely involve calling memmove or similar to shift the
contents down and then reallocating.

Still sounds like removing an element from an array to me...
Nov 14 '05 #78

"Julie" <ju***@nospam.c om> wrote in message
news:40******** *******@nospam. com...
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 usingpointers and indirecting through them.

Please describe (in code) a situation where two variables share the same

memory location.


Just like described, using pointers. (References can also be used.)

void pswap( int* px, int* py )
{
*px = *px ^ ^py;
*py = *py ^ *px;
*px = *px ^ *py;
}

....calling code:...
int x = 3;
int* px = &x;
int* py = &x;
pswap( px, py );
-Howard
Nov 14 '05 #79
js*******@sanch arnet.in (Jatinder) wrote in message news:<22******* *************** ****@posting.go ogle.com>...
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.


#include <cstdio>
using namespace std;int main(){const char* s="#include <cstdio>%cusi ng
namespace std;int main(){const char*
s=%c%s%c;printf (s,10,34,s,34,1 0);}%c";printf( s,10,34,s,34,10 );}

Greetings, Bane.
Nov 14 '05 #80

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

270
3990
by: Jatinder | last post by:
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.
12
8493
by: G. | last post by:
Hi all, During my degree, BEng (Hons) Electronics and Communications Engineering, we did C programming every year, but I never kept it up, as I had no interest and didn't see the point. But now I really want to get back into it as I see a point with GNU/Linux. I want to get my old skills back and write something or help on some projects etc. I need some good books. I used to have one called "A Book On C", but sold it,
11
2232
by: John Salerno | last post by:
Similar to the Python Challenge, does anyone know of any other websites or books that have programming puzzles to solve? I found a book called "Puzzles for Hackers", but it seems like it might be a little advanced for me, and I've also read that it focuses too much on encryption and security issues and doesn't really have coding problems, exactly. But something like that book would be fun to have.
1
13123
by: xavier vazquez | last post by:
I have a problem with a program that does not working properly...when the program run is suppose to generate a cross word puzzle , when the outcome show the letter of the words overlap one intop of the other....how i can fix this the program look like this import java.util.ArrayList; import java.util.Random;
0
2032
by: xavier vazquez | last post by:
have a problem with a program that does not working properly...when the program run is suppose to generate a cross word puzzle , when the outcome show the letter of the words overlap one intop of the other....how i can fix this this run the random words for the program import javax.swing.JOptionPane; import java.util.ArrayList; import java.util.Random; public class CrossWordPuzzleTester {
44
3588
by: Jon Harrop | last post by:
Microsoft Research are developing a functional programming language called F# for .NET and I've been playing with it recently. I've uploaded some demos here: http://www.ffconsultancy.com/dotnet/fsharp/ I'm keen to see what Windows developers think of this language as we're considering using it to develop commercial applications on the Windows platform.
5
4477
by: ashish0799 | last post by:
HI I M ASHISH I WANT ALGORYTHMUS OF THIS PROBLEM Jigsaw puzzles. You would have solved many in your childhood and many people still like it in their old ages also. Now what you have got to do is to solve jigsaw puzzles using the computer. The jigsaw puzzle here is a square of dimension d (a puzzle with d^2 pieces) and the jigsaw pieces (all same dimensions) are of dimensions H x W (Which means the pieces have ‘H’ rows of ‘W’...
3
3213
by: oncue01 | last post by:
Word Puzzle Task You are going to search M words in an N × N puzzle. The words may have been placed in one of the four directions as from (i) left to right (E), (ii) right to left (W), (iii) up to bottom (S), or (iv) bottom to up (N). The program will print the starting place and the direction of each word. Limitations The number of words to be searched can be at most 100, the size of the puzzle N can be minimum 5 maximum 20....
4
20019
by: honey777 | last post by:
Problem: 15 Puzzle This is a common puzzle with a 4x4 playing space with 15 tiles, numbered 1 through 15. One "spot" is always left blank. Here is an example of the puzzle: The goal is to get the tiles in order, 1 through 15, from left to right, top to bottom, by just sliding tiles into the empty square. In this configuration, the goal would be to get the 14 and 15 to switch places, without affecting any of the other squares. Your...
13
3133
by: btkuhn | last post by:
Hi guys, I'm learning Python by teaching myself, and after going through several tutorials I feel like I've learned the basics. Since I'm not taking a class or anything, I've been doing challenges/programs to reinforce the material and improve my skills. I started out with stuff like "Guess my number" games, hangman, etc. and moved on to making poker and card games to work with classes. For GUIs I created games like minesweeper, and a...
0
9901
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11031
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10684
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10371
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9517
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7918
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7082
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
4159
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3188
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.