【发布时间】:2016-07-27 20:36:41
【问题描述】:
快速提问:
我有一堆(云)坐标,我倾向于找到整个坐标的四个角坐标。我的意思是:
MyDesiredResult = { SmallestX, BiggestY, BiggestX, SmallestY }
我使用这个旧例程来获得我的价值观,它是正确的一个:
double smallestX = MyCloud[0].X; // assing X of first element to my result controller
var tempCoordPoint = MyCloud[0]; // assign first element to my result controller
for (int i = 0; i < MyCloud.Count; i++)
{
if (smallestX > MyCloud[i].X) // find minimum X
{
smallestX = MyCloud[i].X;
tempCoordPoint = MyCloud[i];
}
}
MyResult.Add(tempCoordPoint); // add to my list
但是,我需要这样做 四次(对于四次结果)。因此,我试图通过将其更改为仅使用一次的 New Routine 来优化我的代码:
List<CoordPoint> MySortedList = MyCloud.Select(c => new CoordPoint { X = c.X, Y = c.Y, Z = c.Z, Color = c.Color }).ToList();
MySortedList.Sort((c1, c2) => c1.X.CompareTo(c2.X)); // sort on X
var temp = MySortedList[MySortedList.Count - 1]; // hold biggest X in a temp variable
MyResult.Add(MySortedList[0]); // add smallest X to my result
MySortedList.Sort((c1, c2) => c1.Y.CompareTo(c2.Y)); ; // sort on Y
MyResult.Add(MySortedList[MySortedList.Count - 1]); // add biggest Y to my result
MyResult.Add(temp); // add biggest X to my result
MyResult.Add(MySortedList[0]); // add smallest Y to my result
但它给出了不同的结果。我想显示一个示例输入、当前输出和所需的输出。我可以跳过样本输入(巨大的负载)并显示结果。谁能指出我做错了什么?
对于相同的输入:
旧例程的结果:
(0, 4), (15, 12), (23, 6), (19, 0)
新例程的结果:
(0, 4), (18, 12), (23, 6), (18, 0)
【问题讨论】:
-
你说两个不同的代码 sn-ps 产生不同的结果,但没有说明正确的结果是什么。
-
@Servy 我做到了。请参阅结果部分之前的“P.S 旧例程是正确的!”。新套路不应该导致不同的结果!这就是问题所在。
-
你的问题的基本前提不应该是在后文中。
-
@Servy 感谢您的指出。我将编辑我的帖子。但你知道,我认为我有更好的讨论。我刚刚注意到这两个结果都是有效的。因为两者都是
{ SmallestX, BiggestY, BiggestX, SmallestY }的形式。但是,如何使用更简单的新例程找到正确的角点来解决我的问题呢?嗯..
标签: c# algorithm sorting design-patterns logic