我有问题。我使用SkiaSharp创建了TriangleGrid。在绘制网格时,我将每个三角形信息保存在字典中。字典看起来像这样:
public class TriangleRegistryObject
{
public float x1 { get; set; }
public float y1 { get; set; }
public float x2 { get; set; }
public float y2 { get; set; }
public float x3 { get; set; }
public float y3 { get; set; }
public bool Selected { get; set; }
public bool Visible { get; set; }
}
现在,当我选择一个三角形时,我将布尔值Selected
设置为true
。最后,我要检查我选择的三角形是否相互连接。我以为我可以数出连接的线路。这是一个示例图片:
现在,我想计算Selected=true
处的紫色线。
我有每个坐标(x1,y1)(x2,y2)和(x3,y3)。
更新:
这是我使用的代码,它为我返回0!
public static bool ValidLayout()
{
bool IsValid;
int sharedEdges;
int SelectedTriangles = TriangleRegistry.Count(tr => tr.Value.Selected.Equals(true));
var triangles = new List<TriangleRegistryList>();
foreach (KeyValuePair<string, TriangleRegistryObject> row in TriangleRegistry.Where(n => n.Value.Selected == true).ToList())
{
triangles.Add(new TriangleRegistryList { x1 = row.Value.x1,
y1 = row.Value.y1,
x2 = row.Value.x2,
y2 = row.Value.y2,
x3 = row.Value.x3,
y3 = row.Value.y3
});
}
sharedEdges = triangles.GetKCombs(2).Where(t => t.First().IsAdjacentTo(t.Skip(1).Take(1).Single())).Count();
if (sharedEdges >= (SelectedTriangles - 1))
{
IsValid = true;
}
else
{
IsValid = false;
}
return IsValid;
}
但是我不知道如何相互比较坐标以计算连接的线数!
有人可以帮我吗?
答案 0 :(得分:2)
这是一个非常简单的解决方案。绝对不是最有效的方法,但是可以完成工作。
我已经为您的三角形类添加了一个方法,如果该方法与另一个三角形共享至少2个顶点,则该方法返回true。
我还使用了一种找到不同排列的方法,该方法与所讨论的here略有不同。
public class Program
{
public static void Main()
{
var triangles = new List<TriangleRegistryObject>{
new TriangleRegistryObject{x1=10,y1=10, x2=12,y2=10, x3=1,y3=11},
new TriangleRegistryObject{x1=9,y1=11, x2=11,y2=11, x3=10,y3=10},
new TriangleRegistryObject{x1=9,y1=11, x2=11,y2=11, x3=10,y3=12},
new TriangleRegistryObject{x1=34,y1=14, x2=15,y2=11, x3=10,y3=12},
};
var sharedEdges = triangles.GetPairs().Where(t => t.first.IsAdjacentTo(t.second)).Count();
Console.WriteLine($"Number shared edges: {sharedEdges}");
}
}
public class TriangleRegistryObject
{
public float x1 { get; set; }
public float y1 { get; set; }
public float x2 { get; set; }
public float y2 { get; set; }
public float x3 { get; set; }
public float y3 { get; set; }
public bool Selected { get; set; }
public bool Visible { get; set; }
public IEnumerable<(float x, float y)> GetPoints()
{
yield return (x1, y1);
yield return (x2, y2);
yield return (x3, y3);
}
public bool IsAdjacentTo(TriangleRegistryObject other)
{
return this.GetPoints().Intersect(other.GetPoints()).Count() >= 2;
}
}
public static class EnumerableExtensions
{
public static IEnumerable<(T first, T second)> GetPairs<T>(this IEnumerable<T> list)
{
return list.SelectMany((value, index) => list.Skip(index + 1),
(first, second) => (first, second));
}
}