Sunday, May 11, 2008

Minesweeper

If you are designing a minesweeper game, you would need to mark each block with how many mines are adjacent to it.

Write a program that places mines in a square grid. And marks each block with the number of mines adjacent to it.

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.

Problem 9 - Palindromes

Write a program to find if a string is a palindrome.
Make it case insensitive.

Eg. "MADAM" - returns true
"ROB" - returns false
"Madam" - returns true
"mADaM" - returns true
"WhaWha"- returns false

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.

Tuesday, May 6, 2008

Day 8 - Substring

You are given two strings - haystack and needle.
You have to find the position of the first occurrence of needle in haystack.
Write a function that takes haystack and needle as input and returns the position of the first occurrence of needle or -1 if needle is not found in haystack.

Eg.

haystack = "Once upon a time, there lived a little boy named Jingle!"
needle = "up"
Return Value = 5

If needle = "fox"
Return Value = -1

Day 7 - Solution

In a hurry today.
Please see the code!



click on the image for clarity.

Monday, May 5, 2008

Day 7 - Who Won?

You are given an array of strings containing a 3 letter country name followed by a hyphen (-) and A 3 digit number. These strings represent the number of points earned by the students of the respective country in a programming competition.
NOTE: There are only 3 countries participating, India, China and USA. The 3 letter code for the countries are IND, CHI and USA respectively.

Write a function that calculates the total number of points scored by the students of IND, CHI and USA and returns a string in the same format with the country code followed by a hyphen followed by the total points scored by the country which has the highest points.

eg
INPUT -> ["IND-32","CHI-33","USA-29","USA-30","IND-12","CHI-34"]
OUTPUT -> "CHI-67"

NOTE: It is guaranteed that the sum of the scores won't be equal.

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 :)

Day 6 - Question : Breaking Strings

You are given a string containing a string Date of Birth in DD/MM/YYYY format. Eg "15/08/1947". Write a function that takes the string as an input and returns a vector containing 3 elements:
v[0] = Day as an integer
v[1] = Month as an integer
v[2] = Year as an integer

eg:
INPUT : "15/08/1947"
Output: [15, 8, 1947]

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?

Day 5 - The second tallest student

Problem - You are given an integer array of heights of students in a class. Write a function that returns the height of the 2nd tallest child in the class.

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!

Day 4 problem - Whats the distance

Here is todays problem.

You have a square grid extending infinitely in all directions. Your home is at point (hx,hy). You have to reach your college located at point (cx, cy). You can only travel parallel to the direction of the X or the Y axis and each step is 1 unit long. Write a program to find the number of steps between your home and your college.

Write it now. Test it. And come back later to check the solution.

Thursday, May 1, 2008

Solution to Day 3 problem.

View the problem statement here.

This problem is very simple, yet I have included it because I want the readers to start using some STL in their C++ programs.

What is STL?
It stands for Standard Template Library. This library has a lot of classes and functions that can replace a lot of data structures and algorithms that we use on a regular basis.

In order to solve our problem we can use the following algorithm
1. Set height[0] as RES
2. Loop through height, from begin to end
if current_element in height is < RES
set RES to current_element

3. Return RES


So, how do we use STL to do this?
We use STLs Algorithms.

--------------------------------------------------------
#include<algorithm>
#include<vector>

int minHeight(vector<int> height)
{
return *min_element(height.begin(),height.end()) ;
}
--------------------------------------------------------

OK OK, that seems to be too much too soon.
So lets break it down.

Q1. Whats that vector thingy? We were supposed to have an array as an input!
Ans. Vector is an STL class. Vectors are a replacement for Arrays. The <int> tells that its an array of int(s).

Q2. What is min_element?
Ans. min_element is a pre-defined* function in algorithm.h that returns a pointer to the minimum element in a specified range.

Q3. So height.begin(), height.end() are ranges right?
Ans. Exactly. height.begin() returns a pointer to the beginning of the array and height.end() returns a pointer to 1 past the end of the array. Between begin() and end() we have covered the whole array.

We will be talking a lot about using STL subsequently.
You can try the program out and let me know if there are any doubts.


* functions are declared not defined in header files. They are defined in the respective libraries.

Note: In reality, min_element() returns something called an iterator which is similar to a pointer and you don't have to bother much about it right now. STL is a very simple to use library with easy syntax, but the way it is taught in books is a bit daunting. So don't bother much about the syntax if you are reading it for the first time. Just see a few examples and learn from them.