Monday, July 16, 2007

Recreational Coding and ideas in problem solving ....

It was after ages that I had sat down to code... code for fun that is!

Coding at work is fun but it is still work. "Recreational Coding", on the other hand, is theraputic and fun. So here is what I was trying to solve:

"On an m x n array, arrange numbers 1 to m x n, or 0 to (m x n - 1) , in a spiral."

For example, a 3 x 3 array (m = n = 3 ) will look like:

1 2 3
8 9 4
7 6 5


There are a variety of ways to solve this, my first attempt involved crazy matrix manipulation and wrapping a linear (1 row) m x n array to the matrix. Well, lets just say when 'm' was not equal to 'n' this one bombed big time ... remember those "Array out of bounds" exceptions. Yeah!

Well anyways, the next time I did what came naturally. I thought about 'walking' around the matrix and instead of thinking about a row-column layout, I though more from a co-ordinate geometry view point.

What emerged was a general rule which went something like this:


Walk 'm' Left
Reduce 'n' by 1
Walk 'n' Down
Reduce 'm' by 1
Walk 'm' Right
Reduce 'n' by 1
Walk 'n' up
Reduce 'm' by 1


So there you have it! With a little bit of pretty printing and some 'spint n shine' - the code was ready. But that was not the end of it ... here is the next question that emerged that I have not been able to answer so far (have not looked in google for any of this yet) ....

....so now we have a solution, can we get this in a more elegant way? I mean instead of walking Left, Down, Right and Up in a spiral can we generate the co-ordinates using 'step' we are at?

More precisely - Is there a function of 'i' which gives us a Row and and a function of 'i' which gives us a value of Col where 'i' ranges from 1 ... m x n ????

For example:
i Row Col
--- ---- ----
1 0 0
2 0 1
3 0 2
4 1 2
5 2 2
6 2 1
7 2 0
8 1 0
9 1 1

No comments: