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.