BLOG

Viewing by Entry / Main
27 May, 2009
Code War 2009 Round 1 Question 2 Answer

And so it continues... hope you had fun with the last question, there are a few approaches and the two teams were quite different on the night. Here is a nice compact solution in AS3, which saves a bit of effort by comparing the squares of the distances rather than the distances themselves:

package {
import flash.display.Sprite;
import flash.text.TextField;

public class MatchingDistance extends Sprite {
	
	public function MatchingDistance() {
		var source : Array = [[1,2],[4,1],[5,6],[20,2],[7,9],[6,13],[20,12],[11,19],[12,20],[3,11],[6,7],
			[8,5],[18,8],[3,9],[13,2],[2,11],[10,17],[9,8],[14,17],[19,3]];
		var hist : Object = {};
		var dist2 : Number;
		var max : Number = 0;
		var f : TextField = new TextField();
		
		for (var i : Number = source.length - 1; i >= 1; i--)
			for (var j : Number = i - 1; j >= 0; j--) {
				dist2 = Math.pow(source[i][0] - source[j][0], 2) + 
					Math.pow(source[i][1] - source[j][1], 2);
				hist[dist2] = hist[dist2] ? hist[dist2] + 1 : 1;
				max = Math.max(hist[dist2], max);
			}
		
		f.text = 'The answer is ' + max.toString(); f.scaleX = f.scaleY = 6;
		addChild(f);
	}
}
}

The correct answer is seven: the size of the largest set of point pairs with the same distance between them.

I just realised I don't have the final version of the next question from the night, I'll ping Phil and post it up when he sends it through (again, Phil is responsible for all the great questions this year).

Robin

No comments

Post Your Comments