473,838 Members | 1,654 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 20376
>> >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?

You could also end up calling swap() on to pointers that just happen
to sometimes end up being equal unless you carefully test that it's not.
It may be preferable to make swap() robust enough to deal with this
situation.

#include "card_t.h" /* This is part of the program, NOT the implementation*/
#define DECKSIZE 52
....
int i,j;
card_t deck[DECKSIZE];

/* bogo-shuffle the cards */
for (i = 0; i < DECKSIZE; i++) {
for (j = 0; j < DECKSIZE; j++) {
/*
* DO NOT CHANGE THE LINE OF CODE BELOW.
* Note: rand() % 2 is used here because it is
* a poor random number generator in many
* implementations , and if it isn't possible to
* cheat, *THEY* will break your legs repeatedly
* and cut off your supply of semicolons.
*/
if (rand() % 2) {
swap(&deck[i], &deck[j]);
}
}
}

Now, you can put a "&& i !=j " clause in the if statement, but
some may object to that on efficiency grounds.

Gordon L. Burditt
Nov 14 '05 #131
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.
You could also end up calling swap() on to pointers that just happen
to sometimes end up being equal unless you carefully test that it's not.
It may be preferable to make swap() robust enough to deal with this
situation.


Yes, I realize all what you said -- however, my point was/is: if you
'implement the xor swap function that operates on two variables', you don't
need the check, because you can't have two variables that share the same memory
location. The check is therefore redundant, and not warranted. If you change
the definition to 'implement an xor swap function' or 'implement an xor swap
function that takes two parameters', then the check *would* be warranted.

In case you still can't see my points:

- The original precondition of two numbers (variables) is sufficient to
eliminate the need for the check.

- Two variables *cannot* share the same memory location.
Nov 14 '05 #132
Gordon Burditt wrote:
#include "card_t.h" /* This is part of the program, NOT the
#implementation */ define DECKSIZE 52
...
int i,j;
card_t deck[DECKSIZE];

/* bogo-shuffle the cards */
for (i = 0; i < DECKSIZE; i++) {
for (j = 0; j < DECKSIZE; j++) {
/*
* DO NOT CHANGE THE LINE OF CODE BELOW.
* Note: rand() % 2 is used here because it is
* a poor random number generator in many
* implementations , and if it isn't possible to
* cheat, *THEY* will break your legs repeatedly
* and cut off your supply of semicolons.
*/
if (rand() % 2) {
swap(&deck[i], &deck[j]);
}
}
}

Hi,

I apologize, for this might not be the topic of this thread, however I feel
compelled to comment on this bogo-shuffle: is that taken from a text on how
*not* to generate a random permutation?

a) The use of rand() % 2 is bad. In a different thread I came across a
random number generator that would produce a strictly alternating sequence
of bits when used this way. The funny comment indicates that the author was
acutally aware of this shortcoming.

b) The method has quadratic runtime in DECKSIZE. Clearly a random-shuffle
can and should be done in linear time.

c) Finally, even with a perfect random number generator, this method is
guaranteed *not* to give equal probabilities to the different permutations.
For small DECKSIZE, the difference is even noticable.
Best

Kai-Uwe
Nov 14 '05 #133

"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 -
Nov 14 '05 #134

"Ioannis Vranos" <iv*@guesswh.at .grad.com> wrote in message
news:cb******** **@ulysses.noc. ntua.gr...

You are right about that, however in reality a decent swap
implementation would check if the passed arguments have the same value
so as to avoid unneeded operations.


There are some algorithms for which the check itself is
an unneeded operation (i.e. which can be proved to be
"correct by construction") become inefficient if the swap
function itself makes such a redundant check. Various
sort algorithms belong to this category, because it is a
characteristic of the sort algorithm [and not a safety net
of swap] to compare items before swapping.

But then there are also some algorithms for which the
check is - if perhaps not redundant - but inefficient as
long as the swap preserves original value in the case of
self-swap.

[I know it's easy to code "more correctly", but] one such
algorithm would be string reversal which might be coded
so that the middle element will be "swapped" with itself
just before the algorithm tests for the termination. Then
you don't need to make an extra check every time before
entering the loop - you just enter the loop every time and
let it do the "right thing" even with strings of length one.

More examples can be found from permutation generation
algorithms, where a straightforward algorithm might benefit
from not having to make the check every time, even given
the cost of occasional self-swap.

- Risto -
Nov 14 '05 #135

"Ioannis Vranos" <iv*@guesswh.at .grad.com> wrote in message
news:cb******** **@ulysses.noc. ntua.gr...

That said, I would not place the equality/inequality check for the
possibility of the same variable passed in mind, but for efficiency.


Whoa!

Without check you have (assuming the temp var is in reg):

R = read memory * 2
W = write memory * 2

With check you have:

R = read memory * 2
C = compare registers
W = write memory * 2 * (1-p) where p = probability of match

For the equality-checking version to be more efficient you have...

C + W*2*(1-p) < W*2 => p > C/(W*2)

In other words, the probability of [arguments-have-the-same
value] should be higher than the ratio of the [comparison-cost]
and the [cost-of-two-writes]. I would guess that in most cases
comparing the arguments is really a pessimization.. .

Note that some systems can execute the writes in parallel,
and that a write and a compare both can be executed in one
cycle -> p = 1/1 which is a certain non-optimization. Also
note that the cost of the jump (which can be optimized away
if swap is a stand-alone function, but typically can not if it is
an inline function) has not even been factored in yet.

This is a micro-optimization at its finest!

- Risto -
Nov 14 '05 #136
Ioannis Vranos posted:
template<class T>
void swap(T &a, T &b)
{
if(a!=b)
{
// ...
}
}

Depends if you want a shallow swap or a deep swap. With my own template, I
was going for a shallow swap. Not how your example makes use of the !=
operator of the class, while mine doesn't even need a definiton of the class
at all. Then again, yours is probably a deep swap.

-JKop
Nov 14 '05 #137
JKop <NU**@null.null > scribbled the following
on comp.lang.c:
Ioannis Vranos posted:
template<class T>
void swap(T &a, T &b)
{
if(a!=b)
{
// ...
}
}
Depends if you want a shallow swap or a deep swap. With my own template, I
was going for a shallow swap. Not how your example makes use of the !=
operator of the class, while mine doesn't even need a definiton of the class
at all. Then again, yours is probably a deep swap.


If you're going to talk about C++-specific features, then please stop
crossposting to comp.lang.c. Thanks.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"A bee could, in effect, gather its junk. Llamas (no poor quadripeds) tune
and vow excitedly zooming."
- JIPsoft
Nov 14 '05 #138
In <tC************ *******@newssvr 29.news.prodigy .com> "Mabden" <mabden@sbc_glo bal.net> writes:
"Dan Pop" <Da*****@cern.c h> wrote in message
news:cb******* ****@sunnews.ce rn.ch...
In <zo************ ****@newssvr27. news.prodigy.co m> "Mabden"

<mabden@sbc_gl obal.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.


C:\TEMP>type test.c
#include <stdio.h>

int main(void) {
int *foo = NULL;

fprintf(stdout, "%i\n", *foo);
}
C:\TEMP>cl -c test.c
Microsoft (R) C/C++ Optimizing Compiler Version 8.00c
Copyright (c) Microsoft Corp 1984-1993. All rights reserved.

test.c
test.c(7) : warning C4035: 'main' : no return value


What part of "chapter and verse" was too difficult for you to understand?
Free clue: the C programming language is not defined by the behaviour of
one compiler or another.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #139
In <cb**********@u lysses.noc.ntua .gr> Ioannis Vranos <iv*@guesswh.at .grad.com> writes:
Mabden wrote:
C:\TEMP>type test.c
#include <stdio.h>

int main(void) {
int *foo = NULL;

fprintf(stdout, "%i\n", *foo);
}
C:\TEMP>cl -c test.c
Microsoft (R) C/C++ Optimizing Compiler Version 8.00c
Copyright (c) Microsoft Corp 1984-1993. All rights reserved.

test.c
test.c(7) : warning C4035: 'main' : no return value


In C90 a return statement is required, in C99 it is not.


Nope, in C90 a return statement is NOT required. Please restrict
yourself to topics you have a clue about.

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

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
8490
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
2230
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
13120
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
2031
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
3577
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
20015
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
3130
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
9854
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
9696
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10903
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
10290
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
9425
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
7827
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...
1
4482
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4063
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3131
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.