Of Code and Me

Somewhere to write down all the stuff I'm going to forget and then need

Euclidean Distance and Similarity in C# October 22, 2009

Filed under: Uncategorized — Rupert Bates @ 4:46 pm

Here are a couple of functions to calculate Euclidean distance between 2 points and similarity based on that distance. These are useful in the sort of algorithms described in the excellent book Programming Collective Intelligence

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace Algorithms
{
 public class Distance
 {
 /// <summary>
 /// Return the distance between 2 points
 /// </summary>
 public static double Euclidean(Point p1, Point p2)
 {
 return Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2));
 }

 /// <summary>
 /// Calculates the similarity between 2 points using Euclidean distance.
 /// Returns a value between 0 and 1 where 1 means they are identical
 /// </summary>
 public static double EuclideanSimilarity(Point p1, Point p2)
 {
 return 1/(1 + Euclidean(p1, p2));
 }
 }
}

And some tests:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Algorithms.Test
{
 [TestClass]
 public class TestDistance
 {
 [TestMethod]
 public void Test_Euclidean()
 {
 var p1 = new Point(5, 4);
 var p2 = new Point(4, 1);

 Assert.AreEqual(3.1622776601683795, Distance.Euclidean(p1, p2));

 }
 [TestMethod]
 public void Test_EuclideanSimilarity()
 {
 var p1 = new Point(5, 4);
 var p2 = new Point(4, 1);

 Assert.AreEqual(0.2402530733520421, Distance.EuclideanSimilarity(p1, p2));

 }
 }
}
Advertisements
 

Access RouteData for the current Route from a library class in asp.net mvc October 7, 2009

Filed under: Asp.Net,C#,MVC — Rupert Bates @ 1:20 pm

Sometimes it’s useful to be able to access the current RouteData from outside a controller, for instance in a library class. In webforms you could always do


HttpContext.Current

but in Asp.Net MVC it’s a bit less obvious how you get access to this data.

I’ve found the following code works:


RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));

Whether there is an easier way or not I don’t know, but this will do me for now…