I am working on an algorithm, which should group connected Arcs. The situation is described via code examples below.
I have Arcs:
public class Arc
{
public Point StartPoint { get; set; }
public Point EndPoint { get; set; }
public bool Visited { get; set; }
public Arc Successor { get; set; }
public Arc Predecessor { get; set; }
}
that consist of Points:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public override bool Equals(Object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((Point)obj);
}
protected bool Equals(Point other)
{
return X.Equals(other.X) && Y.Equals(other.Y);
}
public override int GetHashCode()
{
unchecked
{
return (X.GetHashCode() * 397) ^ Y.GetHashCode();
}
}
}
Given these Points and resulting Arcs:
var p1 = new Point {X = 0, Y = 0};
var p2 = new Point { X = 0, Y = 1 };
var p3 = new Point { X = 0, Y = 2 };
var p4 = new Point { X = 1, Y = 0 };
var p5 = new Point { X = 1, Y = 1 };
var arc1 = new Arc { StartPoint = p1, EndPoint = p2};
var arc2 = new Arc { StartPoint = p4, EndPoint = p5};
var arc3 = new Arc { StartPoint = p2, EndPoint = p3};
I would like to end up with groups of connected Arcs as a list of list:
var arcListOfList = new List<List<Arc>>();
This is the crude algorithm I came up with so far:
foreach (var arc in arcList)
{
var successor = arcList.FirstOrDefault(x => x.StartPoint.Equals(arc.EndPoint));
var predecessor = arcList.FirstOrDefault(x => x.EndPoint.Equals(arc.StartPoint));
arc.Successor = successor;
arc.Predecessor = predecessor;
}
Arc next;
do
{
next = arcList.FirstOrDefault(x => x.Visited == false);
var temp = new List<Arc>();
if (next == null) continue;
do
{
next.Visited = true;
temp.Add(next);
if (next.Successor != null)
{
next = next.Successor;
}
else
{
break;
}
} while (true);
arcListOfList.Add(temp);
} while (next != null);
I would appreciate any help/suggestions to improve it.
return (X.GetHashCode() * 397) ^ Y.GetHashCode();
Could someone give a quick reason why this is unchecked, and if 397 is just a magic number, why pick exactly 397? – RicHo Jul 16 at 17:12