473,839 Members | 1,509 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 20382

On Mon, 28 Jun 2004, Branimir Maksimovic wrote:

Jatinder wrote:
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 );}


% cat > test.cpp
#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 );}
% g++ test.cpp
test.cpp:2:46: warning: multi-line string literals are deprecated
% ./a.out
#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 );}
Certainly doesn't look like an "exact copy" to me. Besides
which, it doesn't work on my DeathStation 9000.
A trivial application of my 'quine' program produces the
C program reproduced below my signature line. (Now I just have
to figure out how to make 'usenetify2' interface with 'quine',
and I've got a winner! ;-))

-Arthur
http://www.contrib.andrew.cmu.edu/~a...ftware/quine.c

#include <stdio.h>
void quine(void)
{
static char q[] = {
'0',
'}', ';', '\n', ' ', ' ', ' ', ' ', 'i', 'n', 't',
' ', 'i', ';', '\n', ' ', ' ', ' ', ' ', 'p', 'u',
't', 's', '(', '"', '\\', 'n', '#', 'i', 'n', 'c',
'l', 'u', 'd', 'e', ' ', '<', 's', 't', 'd', 'i',
'o', '.', 'h', '>', '\\', 'n', '\\', 'n', '"', ')',
';', '\n', ' ', ' ', ' ', ' ', 'p', 'u', 't', 's',
'(', '"', 'v', 'o', 'i', 'd', ' ', 'q', 'u', 'i',
'n', 'e', '(', 'v', 'o', 'i', 'd', ')', '\\', 'n',
'{', '\\', 'n', ' ', ' ', ' ', ' ', 's', 't', 'a',
't', 'i', 'c', ' ', 'c', 'h', 'a', 'r', ' ', 'q',
'[', ']', ' ', '=', ' ', '{', '"', ')', ';', '\n',
' ', ' ', ' ', ' ', 'f', 'o', 'r', ' ', '(', 'i',
'=', '0', ';', ' ', 'q', '[', 'i', ']', ';', ' ',
'+', '+', 'i', ')', ' ', '{', '\n', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', 'i', 'n', 't', ' ', 'n',
'l', ' ', '=', ' ', '(', 'i', '%', '1', '0', ')',
'?', ' ', '\'', ' ', '\'', ':', ' ', '\'', '\\', 'n',
'\'', ';', '\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', 'i', 'f', ' ', '(', 'q', '[', 'i', ']', ' ',
'=', '=', ' ', '\'', '\\', 'n', '\'', ')', '\n', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'p',
'r', 'i', 'n', 't', 'f', '(', '"', '\'', '\\', '\\',
'n', '\'', ',', '%', 'c', '"', ',', ' ', 'n', 'l',
')', ';', '\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', 'e', 'l', 's', 'e', ' ', 'i', 'f', ' ', '(',
'q', '[', 'i', ']', ' ', '=', '=', ' ', '\'', '\\',
't', '\'', ')', '\n', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', 'p', 'r', 'i', 'n', 't', 'f',
'(', '"', '\'', '\\', '\\', 't', '\'', ',', '%', 'c',
'"', ',', ' ', 'n', 'l', ')', ';', '\n', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', 'e', 'l', 's', 'e',
' ', 'i', 'f', ' ', '(', 'q', '[', 'i', ']', ' ',
'=', '=', ' ', '\'', '\\', '\'', '\'', ')', '\n', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'p',
'r', 'i', 'n', 't', 'f', '(', '"', '\'', '\\', '\\',
'\'', '\'', ',', '%', 'c', '"', ',', ' ', 'n', 'l',
')', ';', '\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', 'e', 'l', 's', 'e', ' ', 'i', 'f', ' ', '(',
'q', '[', 'i', ']', ' ', '=', '=', ' ', '\'', '\\',
'\\', '\'', ')', '\n', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', 'p', 'r', 'i', 'n', 't', 'f',
'(', '"', '\'', '\\', '\\', '\\', '\\', '\'', ',', '%',
'c', '"', ',', ' ', 'n', 'l', ')', ';', '\n', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', 'e', 'l', 's',
'e', '\n', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', 'p', 'r', 'i', 'n', 't', 'f', '(', '"',
'\'', '%', 'c', '\'', ',', '%', 'c', '"', ',', ' ',
'q', '[', 'i', ']', ',', ' ', 'n', 'l', ')', ';',
'\n', ' ', ' ', ' ', ' ', '}', '\n', ' ', ' ', ' ',
' ', 'f', 'p', 'u', 't', 's', '(', 'q', ',', ' ',
's', 't', 'd', 'o', 'u', 't', ')', ';', '\n', '}',
'\n', '\n', 'i', 'n', 't', ' ', 'm', 'a', 'i', 'n',
'(', ')', '\n', '{', '\n', ' ', ' ', ' ', ' ', 'q',
'u', 'i', 'n', 'e', '(', ')', ';', '\n', ' ', ' ',
' ', ' ', 'r', 'e', 't', 'u', 'r', 'n', ' ', '0',
';', '\n', '}', '\n', '\n', 0};
int i;
puts("\n#includ e <stdio.h>\n\n") ;
puts("void quine(void)\n{\ n static char q[] = {");
for (i=0; q[i]; ++i) {
int nl = (i%10)? ' ': '\n';
if (q[i] == '\n')
printf("'\\n',% c", nl);
else if (q[i] == '\t')
printf("'\\t',% c", nl);
else if (q[i] == '\'')
printf("'\\'',% c", nl);
else if (q[i] == '\\')
printf("'\\\\', %c", nl);
else
printf("'%c',%c ", q[i], nl);
}
fputs(q, stdout);
}

int main()
{
quine();
return 0;
}

Nov 14 '05 #101
>Dan Pop wrote:
void swap(int *p, int *q) { ... } [snippage] swap(&i, &i);

In article <40************ ***@nospam.com> Julie <ju***@nospam.c om> wrote:Just because you have two pointers that _point_ to the same address, this
doesn't mean that they (the variables here which are still the **pointers**)
share the same memory location.


As I see it, there are *four* variables in the swap() function: p,
q, *p, and *q. It also happens to be the case that two of these
variables -- *p and *q -- are potentially the same single variable,
the "i" in the call above.

The C99 standard, at least, does not seem to define the term
"variable", so one is free to use it to mean whatever one likes.
If you prefer to reserve the word only for "p" and "q" themselves,
and not refer to *p and *q as "variables" , that is your right --
but there will be confusion when communicating with those who *do*
call *p and *q "variables" .

(It is possible that the current C++ standard defines the term
"variable" in such a way that swap() has only two. I have not been
keeping up with C++.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #102
Ioannis Vranos <iv*@guesswh.at .grad.com> wrote in news:cbpreo$6tu $4
@ulysses.noc.nt ua.gr:
josh wrote:
Julie wrote:
Please describe (in code) a situation where two variables share the
same memory
location.

union
{
int x;
int y;
} a;

&a.x == &a.y



That was good :-)


Although somewhat misleading... the variable is a, not x or y..... (to be
pedantic.....)
Nov 14 '05 #103

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

I think the non-temporary requirement is not for space concerns but to
find out how c00l we are. :-) 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. :-)


Oh, I see I'm carrying my argument over from another thread with that point.
We had another recent thread regarding this issue, and I got mixed up as to
where this discussion originated (esp. since at some point the subject line
changed...for *some* reason! :-)).

-Howard

Nov 14 '05 #104
Howard wrote:
Oh, I see I'm carrying my argument over from another thread with that point.
We had another recent thread regarding this issue, and I got mixed up as to
where this discussion originated (esp. since at some point the subject line
changed...for *some* reason! :-)).

Well, at some point I considered the "thing" to be more accurate than
the original term used. :-)


Regards,

Ioannis Vranos
Nov 14 '05 #105
Howard wrote:

"Julie" <ju***@nospam.c om> wrote in message
news:40******** *******@nospam. com...
Yes, but the two variables are pointers, and they do not share the same

memory
location -- they may *point* to the same location.

So, I still haven't seen two variables that share the same memory

location. I
think that you can probably do it w/ placement new (C++ only!), but using

(C++)
references or pointers, you can't have two variables that share the same

memory
location.


Geez, give me a break! What I've shown exhibits *exactly* the kind of
problem that can happen when trying to swap two integers using the xor
technique. Just because someone used terminology that suggested the two
variables themselves had the same memory location, surely you knew what was
meant! The problem is when both memory locations are the same, which can
happen if using pointers or references. That's all that was meant, not that
there were two *different* variables occupying the *same* memory.
-Howard


Break given.

Your example doesn't swap two integers, it swaps one.

I know exactly what is meant -- using the xor technique on two variables will
never fail; using the xor technique on the same variable (same literal
variable, reference, or pointer -- still all *ONE* variable) will fail for most
cases.

You have given example(s) of the latter, *not* the former. There is no
disagreement on the latter.
Nov 14 '05 #106
Ioannis Vranos wrote:

Julie wrote:
How can you _not_ remove an element from an array?

Here is a trivial case:
Since you use the malloc() family and this is cross posted to clc, I
assume you use C.


You assume wrong.

malloc is part of C **AND** C++.

size_t count = 2;
int * array = (int *)malloc(sizeof (int) * count);


In C this casting is not needed.


however it is valid, and required in C++.
array[0] = 42;
array[1] = 9000;
array = (int *)realloc(array , sizeof(int) * (--count));


In C this casting is not needed.


however it is valid, and required in C++.
Nov 14 '05 #107
Howard wrote:

"Julie" <ju***@nospam.c om> wrote in message
news:40******** *******@nospam. com...
Here is the point in my version of 'plain English': you can't have two
variables that share the same memory address (excluding placement new).

So, if
the precondition for swap is that it operates on two variables, then it

will
always work provided the precondition is met.


So who ever sid the procondition was that you were swapping two non-pointer,
non-reference variables? If you're writing the swap as a function, you have
to use references or pointers, or else you'll only be swapping local copies.
That's what makes this an important consideration, because those pointer or
references parameters could be referring to the same memory location. The
swap function need to contain a check to handle that specific case.

-Howard


All that was said was that there were two variables (originally numbers) that
were to be swapped. Your examples use 1 variable, aliased 1 or more times.

Write your code with 2 variables where the xor trick fails, excluding placement
new.
Nov 14 '05 #108
Ioannis Vranos wrote:

Dan Pop wrote:
Since you seem to be unable to understand plain English:

#include <stdio.h>

void swap(int *p, int *q) { ... }

int main()
{
int i = 10;
swap(&i, &i);
printf("%d\n", i);
return 0;
}

Try this code for different implementations of the swap function, using
a temp var and using in-place swapping. Compare the results.

This example is trivial, but the situation can realistically arise in more
complex algorithms.


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.

Regards,

Ioannis Vranos


or simply state the precondition that the swap operates on 2 variables, no
check is necessary or warranted.
Nov 14 '05 #109
Julie wrote:
Since you use the malloc() family and this is cross posted to clc, I
assume you use C.

You assume wrong.

malloc is part of C **AND** C++.

In C this casting is not needed.

however it is valid, and required in C++.

In C this casting is not needed.
however it is valid, and required in C++.

Ok, Ok. :-)


Regards,

Ioannis Vranos
Nov 14 '05 #110

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
9697
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
10906
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
10647
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
9426
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...
0
7017
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
5682
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
5866
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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
4064
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.