473,889 Members | 1,656 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 20435
In <cb***********@ ulysses.noc.ntu a.gr> Ioannis Vranos <iv*@guesswh.at .grad.com> writes:
Dan Pop wrote:
Even under severe space concerns there is
always space for a *temporary* variable. If there are space concerns to
the extreme, then we should write numbers in its memory directly. :-)

Imagine that the universal swap function has the following interface:

void swap(void *p, void *q, size_t size);

What are you going to do if malloc(size) fails?


That is not much universal in my C++ world, since for non-POD types such
a generic function would invoke undefined behaviour.


Your C++ world is irrelevant once you cross-post to comp.lang.c.
For POD types, I would use a char/unsigned char array of fixed size (or
VLA in your world) or a char/unsigned char in the extreme, if malloc()
family failed.


You must be a first class idiot if you *rely* on being able to use
a VLA of the same size as a failed malloc request. And you have
no recovery strategy after the attempt to allocate it fails: your program
has already invoked undefined behaviour and has, probably, crashed and
burned. So, forget about VLAs. Using a *small*, statically allocated
buffer or a single unsigned char object are, however, valid alternatives.

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

"Dan Pop" <Da*****@cern.c h> wrote in message
news:cb******** **@sunnews.cern .ch...
In <cb***********@ ulysses.noc.ntu a.gr> Ioannis Vranos <iv*@guesswh.at .grad.com> writes:
Dan Pop wrote:
Even under severe space concerns there is
always space for a *temporary* variable. If there are space concerns to
the extreme, then we should write numbers in its memory directly. :-)
Imagine that the universal swap function has the following interface:

void swap(void *p, void *q, size_t size);

What are you going to do if malloc(size) fails?
That is not much universal in my C++ world, since for non-POD types such
a generic function would invoke undefined behaviour.


Your C++ world is irrelevant once you cross-post to comp.lang.c.


Well, why the heck are you cross-posting to C++ if C++ is irrelevant?
For POD types, I would use a char/unsigned char array of fixed size (or
VLA in your world) or a char/unsigned char in the extreme, if malloc()
family failed.
You must be a first class idiot if you *rely* on being able to use


This is the second time in a row you're resorted to insults. Care to keep
the discussion llimited to the subject?
a VLA of the same size as a failed malloc request. And you have
no recovery strategy after the attempt to allocate it fails: your program
has already invoked undefined behaviour and has, probably, crashed and
burned. So, forget about VLAs. Using a *small*, statically allocated
buffer or a single unsigned char object are, however, valid alternatives.

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

Nov 14 '05 #152
Dan Pop wrote:
For POD types, I would use a char/unsigned char array of fixed size (or
VLA in your world) or a char/unsigned char in the extreme, if malloc()
family failed.

You must be a first class idiot if you *rely* on being able to use
a VLA of the same size as a failed malloc request.

For accuracy, I was talking about VLA with a small fixed size (instead
of a built in array), however VLAs are a mess so I would not use it
anyway (and also C99 is not one of my favourite standards).
And you have
no recovery strategy after the attempt to allocate it fails: your program
has already invoked undefined behaviour and has, probably, crashed and
burned. So, forget about VLAs. Using a *small*, statically allocated
buffer or a single unsigned char object are, however, valid alternatives.


Yes or single char ones.


Regards,

Ioannis Vranos
Nov 14 '05 #153
Risto Lankinen wrote:

"Julie" <ju***@nospam.c om> wrote in message
news:40******** *******@nospam. com...

Please describe a situation where two variables share the same memory
location.


There is a doubly-linked-list algorithm that uses the same
memory location for both forward and backward pointers.
They are stored as XORred, and given the address of an
anchor node, the chain of nodes can be traversed at either
direction.

- Risto -


Could you please post the relevant code that sets up two variables that share
the same memory location?

Thanks
Nov 14 '05 #154
In <OQ************ ********@bgtnsc 04-news.ops.worldn et.att.net> "Howard" <al*****@hotmai l.com> writes:

"Dan Pop" <Da*****@cern.c h> wrote in message
news:cb******* ***@sunnews.cer n.ch...
In <cb***********@ ulysses.noc.ntu a.gr> Ioannis Vranos

<iv*@guesswh.a t.grad.com> writes:
>Dan Pop wrote:
>
>>>Even under severe space concerns there is
>>>always space for a *temporary* variable. If there are space concerns to
>>>the extreme, then we should write numbers in its memory directly. :-)
>>
>>
>> Imagine that the universal swap function has the following interface:
>>
>> void swap(void *p, void *q, size_t size);
>>
>> What are you going to do if malloc(size) fails?
>
>That is not much universal in my C++ world, since for non-POD types such
>a generic function would invoke undefined behaviour.


Your C++ world is irrelevant once you cross-post to comp.lang.c.


Well, why the heck are you cross-posting to C++ if C++ is irrelevant?


For the simple reason that C and C++ have a common subset and it is
perfectly possible to talk about swapping in the context of this common
subset.

If the OP wanted a discussion including the C++ features outside this
common subset s/he wouldn't have cross-posted to c.l.c in the first place.

Or am I missing something?

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #155
In <cb***********@ ulysses.noc.ntu a.gr> Ioannis Vranos <iv*@guesswh.at .grad.com> writes:
Dan Pop wrote:
For POD types, I would use a char/unsigned char array of fixed size (or
VLA in your world) or a char/unsigned char in the extreme, if malloc()
family failed.

You must be a first class idiot if you *rely* on being able to use
a VLA of the same size as a failed malloc request.

For accuracy, I was talking about VLA with a small fixed size (instead


What is a *variable* length array with a small *fixed* size? Looks like
an oxymoron to me...
of a built in array), however VLAs are a mess so I would not use it
anyway (and also C99 is not one of my favourite standards).


VLAs are far from being a mess. It's the availability of conforming C99
implementations that renders them useless for portable programming.
And you have
no recovery strategy after the attempt to allocate it fails: your program
has already invoked undefined behaviour and has, probably, crashed and
burned. So, forget about VLAs. Using a *small*, statically allocated
buffer or a single unsigned char object are, however, valid alternatives.


Yes or single char ones.


Nope, plain char is NOT exempt from trap representations . Furthermore,
even without trap representations , plain char can have padding bits and
a -0 may become a +0 when copied via a char on one's complement and
sign-magnitude implementations :

3 If the implementation supports negative zeros, they shall be
generated only by:

- the &, |, ^, ~, <<, and >> operators with arguments that
produce such a value;

- the +, -, *, /, and % operators where one argument is a negative
zero and the result is zero;

- compound assignment operators based on the above cases.

It is unspecified whether these cases actually generate a
negative zero or a normal zero, and whether a negative zero
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^
becomes a normal zero when stored in an object.
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^

So, when thinking in terms of accessing value representations on a
byte by byte basis, the *one and only* type suitable for the job is
unsigned char: no padding bits, no trap representations , all values
from 0 to 2 ** CHAR_BIT - 1 represented in pure binary.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #156
Julie <ju***@nospam.c om> wrote in message news:<40******* ********@nospam .com>...
Gordon Burditt wrote:
> >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.


A union?


Nope -- a union is still a single variable, with just different ways to access
it.

Could you please provide your preferred definition of "variable".
I wish to understand why you think a union member is not one.
Nov 14 '05 #157
Dan Pop wrote:

What is a *variable* length array with a small *fixed* size? Looks like
an oxymoron to me...

C++'s std::vector for example is of variable length, however usage in
the style:
vector<int> somearray(5);

is too common.
Nope, plain char is NOT exempt from trap representations . Furthermore,
even without trap representations , plain char can have padding bits and
a -0 may become a +0 when copied via a char on one's complement and
sign-magnitude implementations :


I do not know/have understood what "trap representations " actually are,
however in C++98 it is guaranteed to be safe to read POD types as
sequences of chars and unsigned chars:
"For any complete POD object type T, whether or not the object holds a
valid value of type T, the underlying bytes (1.7) making up the object
can be copied into an array of char or unsigned char.36) If the content
of the array of char or unsigned char is copied back into the object,
the object shall subsequently hold its original value.

[Example:

#define N sizeof(T)
char buf[N];
T obj; // obj initialized to its original value
memcpy(buf, &obj, N); // between these two calls to memcpy,
// obj might be modified
memcpy(&obj, buf, N); // at this point, each subobject of obj of
// scalar type
// holds its original value
—end example]

For any POD type T, if two pointers to T point to distinct T objects
obj1 and obj2, if the value of obj1 is copied into obj2, using the
memcpy library function, obj2 shall subsequently hold the same value as
obj1.

[Example:
T* t1p;
T* t2p;
// provided that t2p points to an initialized object ...
memcpy(t1p, t2p, sizeof(T)); // at this point, every subobject of POD
//type in *t1p contains
// the same value as the corresponding subobject in *t2p
—end example]"


Regards,

Ioannis Vranos
Nov 14 '05 #158
kal
Da*****@cern.ch (Dan Pop) wrote in message news:<cb******* ***@sunnews.cer n.ch>...
In <2k***********@ uni-berlin.de> "Alex Fraser" <me@privacy.net > writes:
"Dan Pop" <Da*****@cern.c h> wrote in message
news:cb******* ****@sunnews.ce rn.ch...
Consider, for example, 0 ^ 0, whose result (an int with all bits set)

[...]

*cough*


Indeed! A first class brain fart...


Ah! Merci beaucoup. I have been trying to understand that.
Nov 14 '05 #159
Dingo wrote:

Julie <ju***@nospam.c om> wrote in message news:<40******* ********@nospam .com>...
Gordon Burditt wrote:

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

A union?


Nope -- a union is still a single variable, with just different ways to access
it.

Could you please provide your preferred definition of "variable".
I wish to understand why you think a union member is not one.


I'll retract my statement -- I'll agree that a union does allow for two
variables to share the same memory address.
Nov 14 '05 #160

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
8494
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
13128
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
2033
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
3589
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
3215
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
20022
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
3135
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
9969
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
11203
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...
1
10896
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10443
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...
1
7999
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
7151
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();...
0
5830
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6029
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3257
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.