You are viewing [info]aathitude's journal

entries friends calendar user info Previous Previous Next Next
Avinash Atreya's Journal - GCJ Problem, writing code, python, XP - all of it
aathitude
[info]aathitude
Add to Memories
Share
GCJ Problem, writing code, python, XP - all of it
Whatever code you write, you always write it better if you write it again. This has never failed to be true in my case. Very often I have been happy to have deleted programs (by mistake) because they have been so much better on the second run.

Coming to the point, Swaroop took part in the Google Code Jam ( don't ask me why I didn't, I honestly don't know) and gave me what he thought was the toughest question of the second round.

Now I have Gopal for company to hack around ( boy! am I happy ) and we decided to try some XP on it. No marks for guessing which language we chose - python of course. Ya now I know, GCJ had only C++ and Java :P

The concept of pair programming, at least the way we tried it, is very simple. Two people take up a problem simultaneously and try their own approaches in parallel. In sometime, it becomes evident that one approach has a better chance of succeeding than the other, and then you sit together and write code further. It does work really well, in most cases.

Being not at all new to programming contests ( that's how I got my job @ Y! - through a programming contest ) I know a damn and dirty way of solving any problem you give me - game trees and recursion. The philosophy is very simple - "When in doubt, use brute force". Put more technically, at any point in a problem, you have a finite number of paths you can follow. If you follow all of them at every point ( use recursion ), you will cover all possible solution paths. This is hopelessly inefficient as it is O(n^n) and uses recursion, but there has hardly been a problem it cant solve. There are some problems you can only solve that way, the 8 queens problem for instance. Then you do what is called alpha pruning and reduce the number of trees. Will post on it sometime.

So this problem got solved too, and Gopal and I got together and optimised and reduced the execution time from 65 seconds to 3.5 seconds as it often happens with alpha pruning - some branches of the tree just need not be there.

Coming back to my original point, the solution I had was way better the second time around: I solved the same problem today evening in 20 minutes writing 25 lines of python code using good old for-loops and it has sub second execution times even in python!

It makes me feel silly now that I ever tried to use recursion for this.

As they say, hindsight is always 20-20!


The problem:
You are given a sequence. You need to compute the minimum number of moves ( numbers in the sequence you need to change) you need to turn the sequence to an AP( Arithmetic Progression )

Disclaimer: The original problem statement is different and is an IP of TopCoder.

The solution:
def computeMinMoves(sequence):
	length = len(sequence)
	minmoves = length - 2#any sequence can be converted to an AP in n-2 moves
	for i in range(length):
		for j in range(i+2,length):
			if ( sequence[j] - sequence[i] ) % (j -i) == 0:
				moves = 0
				useless = False
				d = (sequence[j] - sequence[i])/(j-i)
				newsequence = sequence[:]
				for k in range(length):
					if k < i:
						newsequence[k] = sequence[i] - (i-k)*d
					elif k > j:
						newsequence[k] = sequence[j] + (k-j)*d
					elif k > i and k < j:
						newsequence[k] = sequence[i] + (k-i)*d
					if newsequence[k] != sequence[k]:
							moves = moves + 1
					if moves > minmoves:
						useless = True
						break
				if useless == True:
					continue
				if moves < minmoves:
					minmoves = moves
					#print "sequence: ",newsequence,"Moves: ",moves
	return minmoves


[Update] Changed the loop for j to range(i+2.length). For j = i+1, if we are producing an AP using only 2 numbers, we are getting minmoves = length -2, which is what it will return anyway, if it doesn't find a better solution. If there is another number apart from these 2 that falls in the same AP, that would be taken care of by the loop :). The code keeps getting better ;)

Tags: , ,
Current Mood: geeky geeky
Current Music: pal

Comments
swaroopch From: [info]swaroopch Date: March 12th, 2005 05:26 pm (UTC) (Link)

Elegant solution!

Yikes, this looks so easy now *after* you have tweaked it so much.
Could you have done it in 20 minutes (like in GICJ05) ? :P

P.S. Next time, you and Gopal want to hack on something, you _better_ ping me!

- Swaroop
www.swaroopch.info
aathitude From: [info]aathitude Date: March 12th, 2005 05:35 pm (UTC) (Link)

Re: Elegant solution!

Could you have done it in 20 minutes (like in GICJ05) ? :P
Right now, prolly not. Prolly yes, if solving programming contests and programming puzzles were a way of life, like it was 2 years ago :)
Next time, you and Gopal want to hack on something, you _better_ ping me!
We'll consider it :P

mansu From: [info]mansu Date: March 12th, 2005 06:25 pm (UTC) (Link)
oh God!
How stupid of me.
When i always tried my hand at a programming contest, all i used to end up was a recursive solution or one with trees and searching.
But i always was not happy with my solution because i wanted to use heuristics to solve the problem.And most of the time i sed to believe that people used to solve problems that way.
Some how i never cared to look at others solutions.unfortunately i was never able to break the ice.

Looking at your post i am atleast satisfied that i made it a bit furthur in my journey.
aathitude From: [info]aathitude Date: March 14th, 2005 04:40 am (UTC) (Link)
People do solve problems the other way, like I have done above. Recursion is difficult to get a hang of, and once you do, it's addictive. The important thing is to use your discretion to decide when to use it and when not to.
From: [info]hyperbrain Date: March 13th, 2005 01:50 am (UTC) (Link)
Cool piece of coding! Strangely though, I don't think I would have ever thought of using recursion for such a problem....
aathitude From: [info]aathitude Date: March 14th, 2005 04:42 am (UTC) (Link)
Hindsight is always 20-20!
Recursion does appeal to a wide variety of problems and is often addictive because it follows all paths and solves the problem for you. Also, it is closer to the mathematical representation and is intuitive. If are at it long enough, a non recursive solution will dawn on you!
(Deleted comment)
aathitude From: [info]aathitude Date: March 14th, 2005 04:43 am (UTC) (Link)
Sorry for not posting comments in-between the code. Do you know python? Even otherwise, if you know C, python must be easy to read!
From: (Anonymous) Date: March 14th, 2005 04:30 am (UTC) (Link)

Turned out to be waay more simple...

The final code turned out to be waay more simple that the recursion idea.

But the interesting thing about the code is the evolution of it from the original a,b,c - change 'a','b', or 'c' to make it an AP into what we see above. Right now it looks like a complicated far fetched algorithm - but it did start in the simplest possible way and evolved into a recursive form. Interestingly the for loop above is an extension of the third case of the original algorithm - ie modify 'b' to match 'a' and 'c' ..
aathitude From: [info]aathitude Date: March 14th, 2005 04:45 am (UTC) (Link)

Re: Turned out to be waay more simple...

I agree about the evolution. That's why I decided to start off saying code is always better when you write it again - that really was the essence - rather than talking about tree traversal!
mekin From: [info]mekin Date: April 27th, 2005 06:55 am (UTC) (Link)
dint know u were on LJ :)

For contests the brute-force approach generally works - mostly after good amount of optimization. Its only when you are optimizing tht you are really thinking of the problem & considering various cases

.. but the approach has never gone down well with me .. i just cant get myself to start writing code before i have figured the solution .. which takes much longer .. no wonder i only did well in the long duration contests
aathitude From: [info]aathitude Date: April 27th, 2005 07:02 am (UTC) (Link)
dint know u were on LJ :)
I knew you were! :P Seen you on blore. Adding you on :)

Writing code actually helps me think clearly. That is the reason I love prototyping languages like python, the pieces fall in place as you write and rewrite code. There are no sentiments attached with old code, it gets thrown away :P. When you know you are writing throw away prototypes, it doesn't hurt to write some throw away code :P A better understanding of the problem is the takeaway.

rohan_kini From: [info]rohan_kini Date: July 2nd, 2005 07:31 am (UTC) (Link)

not exaaaaactly ...

Thats not what pair programming is all about.

Pairing is more about both of you working on the solution at the same time, together. So both of you sit together and check out the problem, decide on a design, solution and go ahead. If you and your pair have a difference in opinion, then you try one solution and if required another and then go ahead with the best solution.

Although this may sound redundant, and like a waste of time, pairing is an awesome way to do stuff and I have noticed that its one way to churn out good code. Lotsa fun too.

But then yeah, you can be 'agile' about the whole thing and try out whatever works for u :-)
12 comments or Leave a comment
profile
Avinash Atreya
User: [info]aathitude
Name: Avinash Atreya
calendar
Back June 2009
123456
78910111213
14151617181920
21222324252627
282930
page summary
tags