Associate
- Joined
- 3 Jun 2009
- Posts
- 1,348
- Location
- London
C:\Program Files (x86)\CAPCOM\RESIDENT EVIL 5
Do not go to presontpans![]()
// Get adjacent vertices by colour.
var groupings = from v in vertex.Neighbours
where !v.IsEmpty
group v by v.Colour into vs
select new
{
Colour = vs.Key,
Vertices = vs
};
// Consider each colour separately.
foreach (var grouping in groupings.ToArray())
{
// Get distinct adjacent groups.
var neighbours = grouping.Vertices;
var groups = (from v in neighbours
select v.Group).Distinct();
int groupCount = groups.Count();
int neighbourCount = neighbours.Count();
if (groupCount == neighbourCount)
{
// We have as many adjacent groups as vertices, so no splitting is
// necessary.
// If there are more than one neighbour and group, then the current vertex
// cannot have been joining them; hence it must have been of a different
// colour. Otherwise, we must establish whether that group used to contain
// the current vertex.
if (neighbourCount == 1)
{
var group = neighbours.First().Group;
bool isInGroup = group.Contains(vertex);
if (isInGroup)
{
group.Update();
updatedGroups.Add(group);
}
}
}
else
{
// We have fewer groups than vertices, so we need to check that they are
// contiguous and split them if not.
// Examine each neighbouring group and generate a new group from its
// vertices.
foreach (var group in groups.ToArray())
{
var newGroups = Group.GetGroups(group);
if (newGroups.Count() > 1)
{
// This group needs to be split.
// Find a neighbour in this group whose (new) group is largest.
var largestGroup = newGroups.Aggregate((g1, g2) => g1.Count < g2.Count ? g2 : g1);
var largestGroupVertex = (from v in largestGroup
where neighbours.Contains(v)
select v).First();
// Keep the original group for members of this new group and update it
// from the vertex found (discarding the new group itself).
largestGroupVertex.Group.Update(largestGroupVertex);
// Use the new groups for all other vertices.
newGroups.Except(largestGroup).ForEach(g => g.ForEach(v => v.Group = g));
createdGroups.Add(newGroups.Except(largestGroup));
updatedGroups.Add(largestGroupVertex.Group);
}
}
}
}