简体   繁体   English

查找n元组的最小值和最大值?

[英]Find min and max of n-tuple?

I have a tuple representing xy coordinates. 我有一个表示xy坐标的元组。 These tuples are then used to define the sizes of two boxes as seen here 然后,这些元组用于定义两个框的大小,如此处所示 这里 . Then I would like to create a bounding box surrounding these two boxes which then has the two points; 然后,我想围绕这两个框创建一个边界框,然后有两个点。 one for the bottom left and one for the top right. 一个用于左下,一个用于右上。 The bot-right point would have the x-coordinate min(p1.x, p3.x), y-coordinate = min(p1.y, p3.y). 机器人右点的x坐标为min(p1.x,p3.x),y坐标为min(p1.y,p3.y)。 The top-right point would have x=max(p2.x, p4.x), y=max(p2.y, p4.y) if I am not mistaken. 如果我没有记错的话,右上角的点将为x = max(p2.x,p4.x),y = max(p2.y,p4.y)。

The main problem that I have to is to find a way to get the min and max of n-tuples and derive these two new points for the outer bounding box in a rather pretty way. 我必须要解决的主要问题是找到一种方法来获取n元组的最小值和最大值,并以一种相当漂亮的方式导出外部边界框的这两个新点。

It is difficult to give a useful answer without knowing a bit more about the context and without seeing any sample code of what you have so far. 如果不对上下文有更多了解并且看不到到目前为止的任何示例代码,就很难给出有用的答案。 However, your four points are presumably four tuples: 但是,您的四个点大概是四个元组:

let p1 = (0, 5)
let p2 = (10, 15)
let p3 = (5, 0)
let p4 = (15, 10)

Now, if you just want to get the minimal X and Y values, you can create a list of all the points and use minBy : 现在,如果您只想获得最小的X和Y值,则可以创建所有点的列表并使用minBy

let ps = [p1; p2; p3; p4] 
let minX = ps |> List.minBy fst
let minY = ps |> List.minBy snd

In something similar to @TomasPetricek's answer, you can use LINQ in C#: 在类似于@TomasPetricek的答案中,可以在C#中使用LINQ:

var p1 = (0, 5);
var p2 = (10, 15);
var p3 = (5, 0);
var p4 = (15, 10);

var ps = new[] { p1, p2, p3, p4 };

var minX = ps.Select(p => p.Item1).Min();
var minY = ps.Select(p => p.Item2).Min();

Abusing the LINQ Aggregate method, you can compute the answer at once: 滥用LINQ Aggregate方法,您可以立即计算答案:

var ps = new[] { p2, p3, p4 };

var ans = ps.Aggregate((p1, p1), (rect, p) => ((Math.Min(rect.Item1.Item1,p.Item1),Math.Min(rect.Item1.Item2,p.Item2)),
                                               (Math.Max(rect.Item2.Item1,p.Item1),Math.Max(rect.Item2.Item2,p.Item2))));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM