Showing posts with label solution. Show all posts
Showing posts with label solution. Show all posts

Friday, May 9, 2008

Palindromes - Solution

There are multiple ways to solve this trivial problem.
For a beginner, there is one catch in this problem. How to make it case insensitive? Basically, we can do so by changing the string to all upper or all lowercase letters and then check for palindromes.

There maybe any number of ways to approach this problem. I'll list down the 2 ways that usually people apply.

1. Reverse the string and check if the strings are the same



There are quite a few things to learn here.
i> There are library functions available to check if a character is uppercase or lowercase. There are also functions to convert a character from uppercase to lowercase and visa-versa. You can find these functions is ctype.h header file.
ii> Note that we did not compare the reverse of the string with str using the '==' operator. Can you guess why? Basically, because the '==' operator returns true only if the two strings share the same memory location. So we use the 'compare' method in the 'string' class.


2. Compare the 1st against the last character, 2nd against the 2nd last character and so on till we reach the middle.
This one is simple. Here is the code.



Click on the images for code clarity.

Day 8 - Solution

The first way is to go by a Brute Force string matching technique.
I guess its useless to give the algorithm if you are giving the source code anyways.

So here is the program.



Now lets try to do the same using the built in features of the 'string' class. Remember, our strings are not (char *) any more, they are objects of the 'string' class. Check out how our whole function that we wrote above, is replaced with a single statement.

Prog:



Note: Click on the image for clarity in reading.

Monday, May 5, 2008

Day 6 - Solution

The problem here is to break the string into corresponding numbers.

There are 2 general ways of going about it.

1. Using String Streams.
String Streams are a mechanism of converting a string to a stream. So you can do things like write to the stream and read from the stream, very similar to how you use cout and the << operator to write to Standard Output Stream and cin and >> operator to read from the Standard Input Stream.

So we initialize a String Stream with our string - namely DOB.
We then read the day, the '/' character, the month, the '/' character and the year from it.

Check the Program.


Click on the image for a clearer view.


2. The 2nd way is using sscanf()
The syntax of sscanf is very similar to scanf, only that you need to specify the string that it needs to scan as the first argument. Note that sscanf() is a C compatible function so our string object (dob) won't work with it. We will have to convert it to a C compatible string. That is attained by using the c_str() functionality built in the string class.
eg string obj -> "12/3/00"
obj.c_str() => char * => "12/3/00\0"

You'll understand better by having a look at the program.



Click on the image for a clearer view.


The result of both the program is the same:-



If you know of any other ways, please bring it to my notice :)

Saturday, May 3, 2008

Day 5 Solution

There is nothing special about this problem. No holistic views, no boundary conditions. You guys know "Sorting" right! This problem is to make you use it.

The Algorithm
1. Sort the array from 0 to n-1
2. Return the n-2th element

---

So you can do your regular sorting thing and get the result.

I would like to use this opportunity to introduce you to some more of STL.

Check the program



There is a legacy trick of finding the size of an array in that problem.
Noticed how we did -
sizeof(heights)/sizeof(int)

to get the number of elements in the array!

Then, while converting that array into a vector, we need to give the range of the array. By range I mean, a pointer (or an iterator) from the beginning of the array to the end of the array. Now 'heights' will give us the pointer to the beginning of the array and 'heights + n' to the end.

But will 'heights + n' always give us the pointer to the end of the array?
It will in our case, but it wont for other arrays of other types.
Can you tell why?

Friday, May 2, 2008

Day 4 Solution

You can view the problem statement here.

Now you can imagine the gird to be a something like this


Point A could be your home and Point B your school/college.

So you would be thinking that (Ax - Bx) and (Ay - By) would give you your solution. But the solution could be negative as well. So you take the absolute value of (Ax - Bx) and (Ay - By) and add the two to get your answer.

Check the program.



























Now the catch is...
While writing/imagining the solution, did you imagine only the positive co-ordinate axis or all the 4 axes? As in, did you imagine only positive co-ordinates for X and Y or did you imagine the negative ones as well?



If you imagined the Negative Axes as well then congrats! You are someone who already looks at boundary conditions. And if you did not, then congrats! You can start looking at boundary conditions for every problem you solve from now on!

In our case, the solution works well no mater which quadrant we are in. But real life problems, I'm afraid, are not so forgiving.

So did you find this post insightful? Keep bringing on your comments. I am looking forward to some readers posting a snapshot of their solutions too!

Tuesday, April 29, 2008

Solution to Problem 2

You can view the problem statement here.

Why did I ask this question now?
Because there are 3 good things in this problem :-
1. You need to understand the problem.
2. There is a lot you can do to optimize the solution
3. If you don't optimize the solution, you may end up screwing your reputation in your job interview.

Remember, anyone can code. But the way anyone will differentiate between you and an average coder is on the basis of

  • How well you handle the boundary conditions. (Does your code fail for any input)

  • How efficient your code is.

  • And how well can you optimize your code.



Many people coming to this blog are students who would be writing programs in their job interviews soon. I can tell from personal experience that the sexiest of companies only ask for programmers who code keeping the above points in their mind.

Ok now coming back to the problem.

We can check for primality by iterating from 2 to (n-1) and if it is divisible by any number in between, we can be sure that it is not a prime number.



However, there is a lot of unnecessary iteration over here.
You might be thinking that, since we are starting from 2, we can stop iterating when i reaches (n/2).



Well you are right. But the number of iterations can be optimized further.

Consider, a number 21. Lets list down its divisors
1 x 21 = 21
3 x 7 = 21
7 x 3 = 21
21 x 1 = 21
After removing the first and the last case. We are left with only 3 x 7 and 7 x 3. Notice the repetition. Once we have 3 we dont need to go till 7 do we?
Now you would argue that, our program will automatically come out of the loop at 3 so there is no question of reaching all the way till 7. Well you are right again. But the problem doesn't come when the input is composite (A number that is not prime). The problem comes when the number is prime. Take 23 for example.
Try dividing it with :-
2 - No
3 - No
4 - No
5 - No
.
.
.
11 - No
And then we come out of the loop.

But do we really need to go all the way till 11?
No we don't.
Applying some common sense, you can sense that after the square root of the number, the order of multiplication starts changing.
Let me illustrate that with an example.

Consider n = 24
2 x 12 = 24
3 x 8 = 24
4 x 6 = 24
6 x 4 = 24
8 x 3 = 24
12 x 2 = 24

The divisors start repeating after i becomes greater than 5. Its basically because, i becomes > 4.89 or Square Root(24). So we only need to iterate till the square root of a number.

Here is the code for the problem.



Now coming back to the 3 points that I had mentioned earlier on why this problem is good.
1. You need to understand the problem. Did you know that, prime numbers can't be negative? I didn't know it when I was asked to write this program the first time.
2. There is a lot you can do to optimize the solution You already have an idea of the optimization now.
3. If you don't optimize the solution, you may end up screwing your reputation in your job interview. If you apply for a job in a company like Google, Microsoft, Trilogy or an uber-cool startup. They are really gonna see how well you are able to optimize your solutions.

Can you find out a way of making the function return still faster for a random input?
Thats your assignment.

Thats all for the day.
Trust you found the post interesting.

Full_Metal

Solution to Group 3 Problem

Group 3.

View the question here.

Here we want to practice a bit of recursion.
Whenever you go about writing recursive code, you have to keep two things in mind.
1. There must be a terminating condition.
2. As the number of recursions increase, the problem state should approach the terminating condition.

Lets see that with respect to this program.



Now lets come back to the 2 conditions that we discussed above.

1. There must be a terminating condition. As you see, the (if n < 10) is the terminating condition. It is a terminating condition because a number is returned if that condition is satisfied. (Unlike the default case which calls the function again)
2. As the number of recursions increase, the problem state should approach the terminating condition. This is also satisfied because, we keep dividing the number by 10 in the default condition. So the number will keep becoming smaller and smaller and finally become <10, and the terminating condition will be reached.

OK, so did you find a problem with the program above?
Yes? -> Great!
No? -> If you check the previous post, I have mentioned that whenever we write a program, we should check for boundary conditions. This program won't work for negative numbers.

How to make it work for negative numbers?
This is your assignment.

Request: Please take the quiz or leave your comment to help me make this site more useful. Thanks