明经CAD社区

 找回密码
 注册

QQ登录

只需一步,快速开始

搜索
查看: 14656|回复: 24

[几何] [推荐]几何算法相关

    [复制链接]
发表于 2010-7-4 20:44 | 显示全部楼层 |阅读模式
本帖最后由 作者 于 2010-7-5 7:52:27 编辑

一、从凸包开始(概念)

在ObjectArx.net论坛看到highflybird的帖子,关于凸包求解的Arx版本

原帖见http://www.objectarx.net/forum.php?mod=viewthread&tid=1697

和highflybird的观点相同,几何算法对于Cad二次开发的初学者应该是一个门槛跨过去就是海阔天空:)

相关的链接在以后贴上

 

二维凸包的概念是几何算法的开篇

http://baike.baidu.com/view/707209.htm

概念:

1.1 点集Q的凸包(convex hull)是指一个最小凸多边形,满足Q中的点或者在多边形边上或者在其内。右图中由红色线段表示的多边形就是点集Q={p0,p1,...p12}的凸包。

1.2 一组平面上的点,求一个包含所有点的最小的凸多边形,这就是凸包问题了。这可以形象地想成这样:在地上放置一些不可移动的木桩,用一根绳子把他们尽量紧地圈起来,这就是凸包了。

相关的算法网上很多,不过,起码NetApi里很少看到有人做

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册

x

评分

参与人数 1威望 +1 明经币 +2 金钱 +20 贡献 +5 激情 +5 收起 理由
lzx838 + 1 + 2 + 20 + 5 + 5 【精华】好文章

查看全部评分

发表于 2022-4-25 10:25 | 显示全部楼层
好东西 值得学习
发表于 2020-3-14 20:52 | 显示全部楼层

强!顶~!向大佬学习
发表于 2022-4-26 21:25 | 显示全部楼层
过来膜拜大佬……
 楼主| 发表于 2010-7-4 20:54 | 显示全部楼层
本帖最后由 作者 于 2010-7-4 21:16:07 编辑

二、维护一个循环链表
理解算法后,先不要慌着看代码,最好自己先想想,脑袋里有点映像
这里首先贴上的是循环链表,我的感觉:这种方式解决点集的求解问题要更好些
当然,如果有更好的方法,欢迎一起来讨论

循环链表的概念可以看看这里:
http://student.zjzk.cn/course_ware/data_structure/web/xianxingbiao/xianxingbiao2.3.2.htm
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace TlsCad.Collections
  6. {
  7.     /// <summary>
  8.     /// 环链表节点
  9.     /// </summary>
  10.     /// <typeparam name="T"></typeparam>
  11.     public class LoopListNode<T>
  12.     {
  13.         public T Value { get; set; }
  14.         /// <summary>
  15.         /// 上一个节点
  16.         /// </summary>
  17.         public LoopListNode<T> Previous {internal set; get; }
  18.         /// <summary>
  19.         /// 下一个节点
  20.         /// </summary>
  21.         public LoopListNode<T> Next {internal set; get; }
  22.         /// <summary>
  23.         ///
  24.         /// </summary>
  25.         public LoopList<T> List {internal set; get; }
  26.         public LoopListNode(T value)
  27.         {
  28.             Value = value;
  29.         }
  30.     }
  31.     /// <summary>
  32.     /// 环链表
  33.     /// </summary>
  34.     /// <typeparam name="T"></typeparam>
  35.     public class LoopList<T> : IEnumerable<T>, IFormattable
  36.     {
  37.         /// <summary>
  38.         /// 节点数
  39.         /// </summary>
  40.         public int Count { get; private set; }
  41.         /// <summary>
  42.         /// 首节点
  43.         /// </summary>
  44.         public LoopListNode<T> First { get; private set; }
  45.         /// <summary>
  46.         /// 尾节点
  47.         /// </summary>
  48.         public LoopListNode<T> Last
  49.         {
  50.             get
  51.             {
  52.                 if (First == null)
  53.                     return null;
  54.                 else
  55.                     return First.Previous;
  56.             }
  57.         }
  58.         public bool SetFirst(LoopListNode<T> node)
  59.         {
  60.             if (Contains(node))
  61.             {
  62.                 First = node;
  63.                 return true;
  64.             }
  65.             return false;
  66.         }
  67.         /// <summary>
  68.         /// 交换两个节点的值
  69.         /// </summary>
  70.         /// <param name="node1"></param>
  71.         /// <param name="node2"></param>
  72.         public void Swap(LoopListNode<T> node1, LoopListNode<T> node2)
  73.         {
  74.             T value = node1.Value;
  75.             node1.Value = node2.Value;
  76.             node2.Value = value;
  77.         }
  78.         /// <summary>
  79.         /// 在首节点之前插入节点,并设置新节点为首节点
  80.         /// </summary>
  81.         /// <param name="value"></param>
  82.         /// <returns></returns>
  83.         public LoopListNode<T> AddFirst(T value)
  84.         {
  85.             LoopListNode<T> node = new LoopListNode<T>(value);
  86.             node.List = this;
  87.             if (Count == 0)
  88.             {
  89.                 First = node;
  90.                 First.Previous = First.Next = node;
  91.             }
  92.             else
  93.             {
  94.                 LoopListNode<T> last = Last;
  95.                 First.Previous = last.Next = node;
  96.                 node.Next = First;
  97.                 node.Previous = last;
  98.                 First = node;
  99.             }
  100.             Count++;
  101.             return First;
  102.         }
  103.         /// <summary>
  104.         ///  在尾节点之后插入节点,并设置新节点为尾节点
  105.         /// </summary>
  106.         /// <param name="value"></param>
  107.         /// <returns></returns>
  108.         public LoopListNode<T> Add(T value)
  109.         {
  110.             LoopListNode<T> node = new LoopListNode<T>(value);
  111.             node.List = this;
  112.             if (Count == 0)
  113.             {
  114.                 First = node;
  115.                 First.Previous = First.Next = node;
  116.             }
  117.             else
  118.             {
  119.                 LoopListNode<T> last = Last;
  120.                 First.Previous = last.Next = node;
  121.                 node.Next = First;
  122.                 node.Previous = last;
  123.             }
  124.             Count++;
  125.             return Last;
  126.         }
  127.         /// <summary>
  128.         /// 删除首节点
  129.         /// </summary>
  130.         /// <returns></returns>
  131.         public bool RemoveFirst()
  132.         {
  133.             switch (Count)
  134.             {
  135.                 case 0:
  136.                     return false;
  137.                 case 1:
  138.                     First = null;
  139.                     break;
  140.                 default:
  141.                     LoopListNode<T> last = Last;
  142.                     First = First.Next;
  143.                     First.Previous = last;
  144.                     last.Next = First;
  145.                     break;
  146.             }
  147.             Count--;
  148.             return true;
  149.         }
  150.         /// <summary>
  151.         /// 删除尾节点
  152.         /// </summary>
  153.         /// <returns></returns>
  154.         public bool RemoveLast()
  155.         {
  156.             switch (Count)
  157.             {
  158.                 case 0:
  159.                     return false;
  160.                 case 1:
  161.                     First = null;
  162.                     break;
  163.                 default:
  164.                     LoopListNode<T> last = Last.Previous;
  165.                     last.Next = First;
  166.                     First.Previous = last;
  167.                     break;
  168.             }
  169.             Count--;
  170.             return true;
  171.         }
  172.         /// <summary>
  173.         /// 删除节点
  174.         /// </summary>
  175.         /// <param name="node"></param>
  176.         /// <returns></returns>
  177.         public bool Remove(LoopListNode<T> node)
  178.         {
  179.             if (Contains(node))
  180.             {
  181.                 if (Count == 1)
  182.                 {
  183.                     First = null;
  184.                 }
  185.                 else
  186.                 {
  187.                     if (node == First)
  188.                     {
  189.                         RemoveFirst();
  190.                     }
  191.                     else
  192.                     {
  193.                         node.Next.Previous = node.Previous;
  194.                         node.Previous.Next = node.Next;
  195.                     }
  196.                 }
  197.                 Count--;
  198.                 return true;
  199.             }
  200.             return false;
  201.         }
  202.         public bool Contains(LoopListNode<T> node)
  203.         {
  204.             return node != null && node.List == this;
  205.         }
  206.         public bool Contains(T value)
  207.         {
  208.             LoopListNode<T> node = First;
  209.             if (node == null)
  210.                 return false;
  211.             for (int i = 0; i < Count;i++ )
  212.             {
  213.                 if (node.Value.Equals(value))
  214.                     return true;
  215.             }
  216.             return false;
  217.         }
  218.         public LoopListNode<T> AddBefore(LoopListNode<T> node, T value)
  219.         {
  220.             if (node == First)
  221.             {
  222.                 return AddFirst(value);
  223.             }
  224.             else
  225.             {
  226.                 LoopListNode<T> tnode = new LoopListNode<T>(value);
  227.                 node.Previous.Next = tnode;
  228.                 tnode.Previous = node.Previous;
  229.                 node.Previous = tnode;
  230.                 tnode.Next = node;
  231.                 Count++;
  232.                 return tnode;
  233.             }
  234.         }
  235.         public LoopListNode<T> AddAfter(LoopListNode<T> node, T value)
  236.         {
  237.             LoopListNode<T> tnode = new LoopListNode<T>(value);
  238.             node.Next.Previous = tnode;
  239.             tnode.Next = node.Next;
  240.             node.Next = tnode;
  241.             tnode.Previous = node;
  242.             Count++;
  243.             return tnode;
  244.         }
  245.         /// <summary>
  246.         /// 链接两节点,并去除这两个节点间的所有节点
  247.         /// </summary>
  248.         /// <param name="from"></param>
  249.         /// <param name="to"></param>
  250.         public void LinkTo(LoopListNode<T> from, LoopListNode<T> to)
  251.         {
  252.             if (from != to && Contains(from) && Contains(to))
  253.             {
  254.                 LoopListNode<T> node = from.Next;
  255.                 bool isFirstChanged = false;
  256.                 int number = 0;
  257.                 while (node != to)
  258.                 {
  259.                     if (node == First)
  260.                         isFirstChanged = true;
  261.                     node = node.Next;
  262.                     number++;
  263.                 }
  264.                 from.Next = to;
  265.                 to.Previous = from;
  266.                 if (number > 0 && isFirstChanged)
  267.                     First = to;
  268.                 Count -= number;
  269.             }
  270.         }
  271.         /// <summary>
  272.         /// 链接两节点,并去除这两个节点间的所有节点
  273.         /// </summary>
  274.         /// <param name="from"></param>
  275.         /// <param name="to"></param>
  276.         /// <param name="number"></param>
  277.         public void LinkTo(LoopListNode<T> from, LoopListNode<T> to, int number)
  278.         {
  279.             if (from != to && Contains(from) && Contains(to))
  280.             {
  281.                 from.Next = to;
  282.                 to.Previous = from;
  283.                 First = to;
  284.                 Count -= number;
  285.             }
  286.         }
  287.         /// <summary>
  288.         /// 链接两节点,并去除这两个节点间的所有节点
  289.         /// </summary>
  290.         /// <param name="from"></param>
  291.         /// <param name="to"></param>
  292.         /// <param name="number"></param>
  293.         public void LinkTo(LoopListNode<T> from, LoopListNode<T> to, int number, bool isFirstChanged)
  294.         {
  295.             if (from != to && Contains(from) && Contains(to))
  296.             {
  297.                 from.Next = to;
  298.                 to.Previous = from;
  299.                 if (isFirstChanged)
  300.                     First = to;
  301.                 Count -= number;
  302.             }
  303.         }
  304.         #region IEnumerable<T> 成员
  305.         /// <summary>
  306.         /// 获取节点的查询器
  307.         /// </summary>
  308.         /// <param name="from"></param>
  309.         /// <returns></returns>
  310.         public IEnumerable<LoopListNode<T>> GetNodes(LoopListNode<T> from)
  311.         {
  312.             LoopListNode<T> node = from;
  313.             for (int i = 0; i < Count; i++)
  314.             {
  315.                 yield return node;
  316.                 node = node.Next;
  317.             }
  318.         }
  319.         /// <summary>
  320.         /// 获取节点的查询器
  321.         /// </summary>
  322.         /// <param name="from"></param>
  323.         /// <returns></returns>
  324.         public IEnumerable<LoopListNode<T>> GetNodes()
  325.         {
  326.             LoopListNode<T> node = First;
  327.             for (int i = 0; i < Count; i++)
  328.             {
  329.                 yield return node;
  330.                 node = node.Next;
  331.             }
  332.         }
  333.         /// <summary>
  334.         /// 获取节点值的查询器
  335.         /// </summary>
  336.         /// <param name="from"></param>
  337.         /// <returns></returns>
  338.         public IEnumerator<T> GetEnumerator()
  339.         {
  340.             LoopListNode<T> node = First;
  341.             for (int i = 0; i < Count; i++)
  342.             {
  343.                 yield return node.Value;
  344.                 node = node.Next;
  345.             }
  346.         }
  347.         IEnumerator<T> IEnumerable<T>.GetEnumerator()
  348.         {
  349.             return GetEnumerator();
  350.         }
  351.         #region IEnumerable 成员
  352.         System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  353.         {
  354.             return GetEnumerator();
  355.         }
  356.         #endregion
  357.         #endregion
  358.         #region IFormattable 成员
  359.         public override string ToString()
  360.         {
  361.             string s = "( ";
  362.             foreach (T value in this)
  363.             {
  364.                 s += value.ToString() + " ";
  365.             }
  366.             return s + ")";
  367.         }
  368.         string IFormattable.ToString(string format, IFormatProvider formatProvider)
  369.         {
  370.             return ToString();
  371.         }
  372.         #endregion
  373.     }
  374. }
 楼主| 发表于 2010-7-4 21:25 | 显示全部楼层
三、凸包类
这里放上的是三种计算凸包的算法实现
算法的关键是:
1、组成凸包的点应为左手系或右手系,判断方式是按行列式计算三点构成的面积
引:使用行列式(Determinant)来定义三角形面积,可以展开并化简为
Area(P1, P2, P3) = (x1y2 - x1y3 - x2y1 + x3y1 + x2y3 - x3y2) / 2
但请注意,上式并非单纯计算三角形的面积,而是「有向面积」(Signed Area),它不仅告诉我们给定3点所构成三角形的大小,而且告诉我们这3点的相对方向。当Area(P1, P2, P3) 的值是负数时,这代表P1->2->3的走向是逆时针方向。反之,若 Area(P1, P2, P3)的值是正数,则代表这3点的走向是顺时针方向。若 Area(P1, P2, P3)为零,则代表这3点共线。因此Area这个函数在求凸包的运算中有极大的用途,可用来判断哪些点是凸包上的点,以及应用直线连结哪些点。事实上,本程序亦广泛运用这个函数。
概念相关http://home.pacific.net.hk/~kfzhou/Hulls.html
2、代码中实际实现的是左手系的凸包,核心是维护该循环链表始终为左手系

代码:
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. using Autodesk.AutoCAD.Geometry;
  5. namespace TlsCad.Collections
  6. {
  7.     public class ConvexHull2d : LoopList<Point2d>
  8.     {
  9.         #region Eval
  10.         internal void GrahamEval(List<Point2d> pnts)
  11.         {
  12.             //先找到一个基准点(XY均最小)
  13.             int i, n = 0;
  14.             for (i = 1; i < pnts.Count; i++)
  15.             {
  16.                 if (pnts[i].Y < pnts[n].Y || (pnts[i].Y == pnts[n].Y && pnts[i].X < pnts[n].X))
  17.                     n = i;
  18.             }
  19.             Point2d ptBase = pnts[n];
  20.             
  21.             //按各点与基准点的极角和极长排序
  22.             var q2 =
  23.                 from p in pnts
  24.                 let v = p - ptBase
  25.                 orderby v.Angle, v.Length
  26.                 select p;
  27.             List<Point2d> ptlst = q2.ToList();
  28.             ptlst.Remove(ptBase);
  29.             //首先放入前三点
  30.             Add(ptBase);
  31.             if (ptlst.Count < 3)
  32.             {
  33.                 ptlst.ForEach(p => Add(p));
  34.                 return;
  35.             }
  36.             Add(ptlst[0]);
  37.             Add(ptlst[1]);
  38.             //如果共线
  39.             for (i = 2; i < ptlst.Count; i++)
  40.             {
  41.                 if (GetArea(First.Next.Value, Last.Value, ptlst[i]) == 0)
  42.                     Last.Value = ptlst[i];
  43.                 else
  44.                     break;
  45.             };
  46.             //依次与链表末端比较
  47.             for (; i < ptlst.Count; i++)
  48.             {
  49.                 //如果当前点在链表末端的顺时针方向
  50.                 int num = 0;
  51.                 LoopListNode<Point2d> node = Last;
  52.                 while (IsClockWise(node.Previous.Value, node.Value, ptlst[i]))
  53.                 {
  54.                     node = node.Previous;
  55.                     num++;
  56.                 }
  57.                 LinkTo(node, First, num);
  58.                 Add(ptlst[i]);
  59.             }
  60.         }
  61.         internal void MelkmanEval(List<Point2d> pnts)
  62.         {
  63.             //按坐标排序,保证方向性
  64.             var q1 =
  65.                 from p in pnts
  66.                 orderby p.X
  67.                 select p;
  68.             List<Point2d> ptlst = q1.ToList();
  69.             switch (ptlst.Count)
  70.             {
  71.                 case 0:
  72.                     return;
  73.                 case 1:
  74.                     Add(ptlst[0]);
  75.                     return;
  76.                 default:
  77.                     Add(ptlst[0]);
  78.                     Add(ptlst[1]);
  79.                     break;
  80.             }
  81.             //如果共线
  82.             int i = 2;
  83.             if (First.Value.X == Last.Value.X)
  84.             {
  85.                 for (; i < ptlst.Count; i++)
  86.                 {
  87.                     if (ptlst[i].X == Last.Value.X)
  88.                     {
  89.                         double y = ptlst[i].Y;
  90.                         if (y > Last.Value.Y)
  91.                             Last.Value = ptlst[i];
  92.                         else if (y < First.Value.Y)
  93.                             First.Value = ptlst[i];
  94.                         i++;
  95.                     }
  96.                     else
  97.                     {
  98.                         break;
  99.                     }
  100.                 }
  101.             }
  102.             for (; i < ptlst.Count; i++)
  103.             {
  104.                 if (GetArea(First.Value, Last.Value, ptlst[i]) == 0)
  105.                     Last.Value = ptlst[i];
  106.                 else
  107.                     break;
  108.             }
  109.             if (i == ptlst.Count)
  110.                 return;
  111.             //保证逆时针方向
  112.             if (IsClockWise(First.Value, Last.Value, ptlst[i]))
  113.                 Swap(First, Last);
  114.             AddFirst(ptlst[i]);
  115.             //依次比较
  116.             for (i++; i < ptlst.Count; i++)
  117.             {
  118.                 Point2d pnt = ptlst[i];
  119.                 int num = 0;
  120.                 LoopListNode<Point2d> from= First, to = First;
  121.                 //做左链
  122.                 while (IsClockWise(to.Next.Value, pnt, to.Value))
  123.                 {
  124.                     to = to.Next;
  125.                     num++;
  126.                 }
  127.                 //做右链
  128.                 while (IsClockWise(from.Previous.Value, from.Value, pnt))
  129.                 {
  130.                     from = from.Previous;
  131.                     num++;
  132.                 }
  133.                 LinkTo(from, to, num - 1);
  134.                 AddFirst(pnt);
  135.             }
  136.         }
  137.         internal void JarvisEval(List<Point2d> pnts)
  138.         {
  139.             switch (pnts.Count)
  140.             {
  141.                 case 0:
  142.                     return;
  143.                 case 1:
  144.                     Add(pnts[0]);
  145.                     return;
  146.                 case 2:
  147.                     Add(pnts[0]);
  148.                     Add(pnts[1]);
  149.                     return;
  150.                 default:
  151.                     Add(pnts[0]);
  152.                     Add(pnts[1]);
  153.                     break;
  154.             }
  155.             int i = 2;
  156.             List<Point2d> tpnts = new List<Point2d> { First.Value, Last.Value };
  157.             for (; i < pnts.Count; i++)
  158.             {
  159.                 if (GetArea(First.Value, Last.Value, pnts[i]) == 0)
  160.                     tpnts.Add(pnts[i]);
  161.                 else
  162.                     break;
  163.             }
  164.             var q1 =
  165.                 from p in tpnts
  166.                 orderby p.X, p.Y
  167.                 select p;
  168.             First.Value = q1.First();
  169.             Last.Value = q1.Last();
  170.             if (i == pnts.Count)
  171.                 return;
  172.             //保证逆时针方向
  173.             if (IsClockWise(First.Value, Last.Value, pnts[i]))
  174.                 Swap(First, Last);
  175.             AddFirst(pnts[i]);
  176.             for (i++; i < pnts.Count; i++)
  177.             {
  178.                 Point2d pnt = pnts[i];
  179.                 Vector2d vec1 = Last.Value - pnt;
  180.                 Vector2d vec2 = First.Value - pnt;
  181.                 bool iscw1 = false;
  182.                 bool iscw2 = IsClockWise(vec1, vec2);
  183.                 LoopListNode<Point2d> from = null, to = null;
  184.                 int num = 0;
  185.                 foreach (var node in GetNodes())
  186.                 {
  187.                     vec1 = vec2;
  188.                     vec2 = node.Next.Value - pnt;
  189.                     iscw1 = iscw2;
  190.                     iscw2 = IsClockWise(vec1, vec2);
  191.                     if (iscw1)
  192.                     {
  193.                         if (iscw2)
  194.                             num++;
  195.                         else
  196.                             to = node;
  197.                     }
  198.                     else if (iscw2)
  199.                     {
  200.                         from = node;
  201.                     }
  202.                 }
  203.                 if (from != null)
  204.                 {
  205.                     LinkTo(from, to, num);
  206.                     Add(pnt);
  207.                 }
  208.             }
  209.         }
  210.         #endregion
  211.         public bool IsOutside(Point2d pnt)
  212.         {
  213.             foreach (var node in GetNodes())
  214.             {
  215.                 if(IsClockWise(node.Value, node.Next.Value, pnt))
  216.                     return true;
  217.             }
  218.             return false;
  219.         }
  220.         public bool IsInside(Point2d pnt)
  221.         {
  222.             foreach (var node in GetNodes())
  223.             {
  224.                 if (IsClockWise(node.Value, pnt, node.Next.Value))
  225.                     return true;
  226.             }
  227.             return false;
  228.         }
  229.         public bool IsOn(Point2d pnt)
  230.         {
  231.             foreach (var node in GetNodes())
  232.             {
  233.                 using (var ls2d = new LineSegment2d(node.Value, node.Next.Value))
  234.                 {
  235.                     if (ls2d.IsOn(pnt))
  236.                         return true;
  237.                 }
  238.             }
  239.             return false;
  240.         }
  241.         //public double GetMaxDistance(out LoopList<Point2d> ptlst)
  242.         //{
  243.         //}
  244.         private static double GetArea(Point2d ptBase, Point2d pt1, Point2d pt2)
  245.         {
  246.             return (pt2 - ptBase).DotProduct((pt1 - ptBase).GetPerpendicularVector());
  247.         }
  248.         private static bool IsClockWise(Point2d ptBase, Point2d pt1, Point2d pt2)
  249.         {
  250.             return GetArea(ptBase, pt1, pt2) <= 0;
  251.         }
  252.         private static double GetArea(Vector2d vecBase, Vector2d vec)
  253.         {
  254.             return vec.DotProduct(vecBase.GetPerpendicularVector());
  255.         }
  256.         private static bool IsClockWise(Vector2d vecBase, Vector2d vec)
  257.         {
  258.             return GetArea(vecBase, vec) <= 0;
  259.         }
  260.     }
  261. }

 楼主| 发表于 2010-7-4 21:32 | 显示全部楼层
相关的测试代码和扩展函数
  1.         [CommandMethod("tt1")]
  2.         public void test21()
  3.         {
  4.             Document doc = Application.DocumentManager.MdiActiveDocument;
  5.             Editor ed = doc.Editor;
  6.             Random rand = new Random();
  7.             int num = Convert.ToInt32(ed.GetString("\ninput number of points:").StringResult);
  8.             using (DBTransaction tr = new DBTransaction())
  9.             {
  10.                 tr.Database.Pdmode = 35;
  11.                 tr.Database.Pdsize = -2;
  12.                 var pnts =
  13.                     Enumerable.Range(0, num).Select
  14.                     (
  15.                         i =>
  16.                         {
  17.                             Point3d pnt = new Point3d(rand.NextDouble() * 100, rand.NextDouble() * 100, 0);
  18.                             DBPoint dpnt = new DBPoint(pnt);
  19.                             return dpnt;
  20.                         }
  21.                     );
  22.                 tr.OpenCurrentSpace(OpenMode.ForWrite);
  23.                 tr.AddEntity(pnts);
  24.             }
  25.         }
  26.         /// <summary>
  27.         /// 这段测试演示凸包和最小包围圆的函数用法,
  28.         /// 测试前请打开新的图形文件(dwg)并画上点,
  29.         /// 这段代码不会产生任何实体
  30.         /// </summary>
  31.         [CommandMethod("tt2")]
  32.         public static void test22()
  33.         {
  34.             Document doc = Application.DocumentManager.MdiActiveDocument;
  35.             Editor ed = doc.Editor;
  36.             Database db = doc.Database;
  37.             int num = 0;
  38.             double total = 0;
  39.             List<Point2d> pnts;
  40.             Stopwatch watch = new Stopwatch();
  41.             watch.Reset();
  42.             watch.Start();
  43.             var resSel = ed.SelectAll(new ResultList { { 0, "point" } });
  44.             num = resSel.Value.Count;
  45.             watch.Stop();
  46.             ed.WriteMessage("\n总共{0}个点", num);
  47.             ed.WriteMessage("\n选择集耗用的时间:{0}(ms)", watch.ElapsedMilliseconds);
  48.             total += watch.ElapsedMilliseconds;
  49.             watch.Reset();
  50.             watch.Start();
  51.             using (Transaction tr = db.TransactionManager.StartTransaction())
  52.             {
  53.                 pnts =
  54.                     resSel.Value.GetObjectIds()
  55.                     .Select(id => ((DBPoint)tr.GetObject(id, OpenMode.ForRead)).Position)
  56.                     .Select(pt => new Point2d(pt.X, pt.Y)).ToList();
  57.                 watch.Stop();
  58.                 ed.WriteMessage("\n打开并转换为二维点耗时:{0}毫秒", watch.ElapsedMilliseconds);
  59.                 total += watch.ElapsedMilliseconds;
  60.                 watch.Reset();
  61.                 watch.Start();
  62.                 LoopList<Point2d> ptlst;
  63.                 CircularArc2d ca2d = pnts.GetMinCircle(out ptlst);
  64.                 watch.Stop();
  65.                 ed.DrawVectors(ca2d.GetSamplePoints(1000), 5);
  66.                 ed.WriteMessage("\n最小包围圆计算耗时:{0}毫秒\n通过了{1}点:\n{2}", watch.ElapsedMilliseconds, ptlst.Count, ptlst);
  67.                 total += watch.ElapsedMilliseconds;
  68.             }
  69.             watch.Reset();
  70.             watch.Start();
  71.             ConvexHull2d pchMelkman = pnts.GetConvexHull();
  72.             watch.Stop();
  73.             ed.WriteMessage("\nMelkman计算凸包耗时:{0}毫秒 凸包点数:{1}", watch.ElapsedMilliseconds, pchMelkman.Count);
  74.             total += watch.ElapsedMilliseconds;
  75.             watch.Reset();
  76.             watch.Start();
  77.             ConvexHull2d pchJarvis = pnts.GetConvexHull2();
  78.             watch.Stop();
  79.             ed.WriteMessage("\nJarvis计算凸包耗时:{0}毫秒 凸包点数:{1}", watch.ElapsedMilliseconds, pchJarvis.Count);
  80.             total += watch.ElapsedMilliseconds;
  81.             watch.Reset();
  82.             watch.Start();
  83.             ConvexHull2d pchGraham = pnts.GetConvexHull3();
  84.             watch.Stop();
  85.             ed.WriteMessage("\nGraham计算凸包耗时:{0}毫秒 凸包点数:{1}", watch.ElapsedMilliseconds, pchGraham.Count);
  86.             total += watch.ElapsedMilliseconds;
  87.             ed.WriteMessage("\n总耗时:{0}毫秒", total);
  88.             ed.DrawVectors(pchMelkman, 4);
  89.             ed.DrawPoints(pchMelkman, 1, 1, 32);
  90.             ed.DrawPoints(pchJarvis, 2, 2, 32);
  91.             ed.DrawPoints(pchGraham, 3, 3, 32);
  92.         }
  93.         [CommandMethod("tt3")]
  94.         public void test23()
  95.         {
  96.             Stopwatch watch = new Stopwatch();
  97.             using (DBTransaction tr = new DBTransaction())
  98.             {
  99.                 var resSel = tr.Editor.SelectAll();
  100.                 if (resSel.Status == PromptStatus.OK)
  101.                 {
  102.                     var ss = resSel.Value;
  103.                     int num = ss.Count;
  104.                     watch.Start();
  105.                     resSel.Value.ForEach(OpenMode.ForWrite, ent => ent.Erase());
  106.                     watch.Stop();
  107.                     tr.Editor.WriteMessage("\n{0} Entitys Erase Time:{1}(ms)", num, watch.ElapsedMilliseconds);
  108.                 }
  109.                 tr.ZoomWindow(new Point3d(-10, -10, 0), new Point3d(110, 110, 0));
  110.             }
  111.         }
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Runtime.InteropServices;
  6. using System.Reflection;
  7. using Autodesk.AutoCAD.Runtime;
  8. using Autodesk.AutoCAD.Geometry;
  9. using Autodesk.AutoCAD.EditorInput;
  10. using Autodesk.AutoCAD.DatabaseServices;
  11. using Autodesk.AutoCAD.ApplicationServices;
  12. namespace TlsCad.ExtendMethods
  13. {
  14.     public static class EditorEx
  15.     {
  16.         /// <summary>
  17.         /// 2009版本提供了acedCmd函数的封装
  18.         /// </summary>
  19.         private static MethodInfo _runCommand =
  20.             typeof(Editor).GetMethod(
  21.                 "RunCommand",
  22.                 BindingFlags.NonPublic | BindingFlags.Instance);
  23.         /// <summary>
  24.         /// 反射调用AutoCad命令(2009版本以上)
  25.         /// </summary>
  26.         /// <param name="editor">Editor对象</param>
  27.         /// <param name="args">参数</param>
  28.         /// <returns></returns>
  29.         public static PromptStatus Command(this Editor editor, params object[] args)
  30.         {
  31.             return (PromptStatus)_runCommand.Invoke(editor, new object[] { args });
  32.         }
  33.         public static void DrawVectors(this Editor editor, IEnumerable<Point2d> pnts, short colorIndex)
  34.         {
  35.             var itor = pnts.GetEnumerator();
  36.             if (!itor.MoveNext())
  37.                 return;
  38.             TypedValue tvFirst = new TypedValue((int)LispDataType.Point2d, itor.Current);
  39.             ResultBuffer rb =
  40.                 new ResultBuffer
  41.                 {
  42.                     new TypedValue((int)LispDataType.Int16, colorIndex),
  43.                 };
  44.             TypedValue tv1;
  45.             TypedValue tv2 = tvFirst;
  46.             while (itor.MoveNext())
  47.             {
  48.                 tv1 = tv2;
  49.                 tv2 = new TypedValue((int)LispDataType.Point2d, itor.Current);
  50.                 rb.Add(tv1);
  51.                 rb.Add(tv2);
  52.             }
  53.             rb.Add(tv2);
  54.             rb.Add(tvFirst);
  55.             editor.DrawVectors(rb, Matrix3d.Identity);
  56.         }
  57.         public static void DrawPoints(this Editor editor, IEnumerable<Point2d> pnts, short colorIndex, double radius, int numEdges)
  58.         {
  59.             foreach (Point2d pnt in pnts)
  60.             {
  61.                 editor.DrawPoint(pnt, colorIndex, radius, numEdges);
  62.             }
  63.         }
  64.         public static void DrawPoint(this Editor editor, Point2d pnt, short colorIndex, double radius, int numEdges)
  65.         {
  66.             Vector2d vec = Vector2d.XAxis * radius;
  67.             double angle = Math.PI * 2 / numEdges;
  68.             List<Point2d> pnts = new List<Point2d>();
  69.             pnts.Add(pnt + vec);
  70.             for (int i = 1; i < numEdges; i++)
  71.             {
  72.                 pnts.Add(pnt + vec.RotateBy(angle * i));
  73.             }
  74.             editor.DrawVectors(pnts, colorIndex);
  75.         }
  76.     }
  77. }

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册

x
 楼主| 发表于 2010-7-5 14:38 | 显示全部楼层
四、最小包围圆
相关的讨论链接:
http://bbs.mjtd.com/forum.php?mod=viewthread&tid=55997
http://www.objectarx.net/forum.php?mod=viewthread&tid=4870
相关的概念和算法描述就直接贴过来了,:)
以下部分摘录自:汪卫,王文平,汪嘉业,求一个包含点集所有点的最小圆的算法,软件学报,2000,11(9):1237-1240

     求一个最小圆包含给定点集所有点的问题是人们在实践和理论上都十分感兴趣的一个问题.由于这个圆的圆心是到点集中最远点最近的一个点,因而在规划某些设施时很有实用价值.
     这个圆心也可看成是点集的中心.此外,在图形学中,圆也常可取作边界盒,使用它可减少很多不必要的计算.
     在空间数据库中可将该问题用于建立空间数据的索引以提高查询速度[1,2].这个问题看起来十分简单,但用直观的算法去解此问题,其复杂性可达O(n4),其中n为点集中点的数目.
     有关此问题的讨论在计算几何的专著及论文中未见报道[3~5].
     本文提出了一种新的算法并证明了这种算法的时间复杂性为O(|lg(d/R)|*n),其中R是所求的最小圆的半径,d为点集中不在圆周上但距圆周最近的点到圆周的距离.
1、算 法
第1步.在点集中任取3点A,B,C.
第2步.作一个包含A,B,C三点的最小圆.圆周可能通过这3点(如图1所示),也可能只通过其中两点,但包含第3点.后一种情况圆周上的两点一定是位于圆的一条直径的两端.
第3步.在点集中找出距离第2步所建圆圆心最远的点D.若D点已在圆内或圆周上,则该圆即为所求的圆,算法结束.否则,执行第4步.
第4步.在A,B,C,D中选3个点,使由它们生成的一个包含这4点的圆为最小.这3点成为新的A,B和C,返回执行第2步. 若在第4步生成的圆的圆周只通过A,B,C,D中的两点,则圆周上的两点取成新的A和B,从另两点中任取一点作为新的C.

2、算法正确性
本节要证明上述算法一定能终止,且最后一次求得的圆即是所要求的包含点集所有点的最小圆.
引理1.算法第4步所生成的圆的半径随着迭代过程递增. 证明:因为第4步每一次生成的圆是包含原来的A,B,C三点,又要加上圆外的一点,而上一次生成的圆是包含A,B,C的最小圆,因而新圆的半径一定比原来的圆半径要大.
定理1.上述算法是收敛的,且最后得到包含点集所有点的最小圆. 证明:因为在点集中任取3点或两点生成的包含这3点或两点的最小圆的个数是有限的.由引理1可知,算法进行过程中所生成的圆的半径是递增的,因而经过有限次迭代后,可求得这些最小圆中半径最大的一个.从算法第3步可知,只有当点集中所有点都在由3个点或两个点生成的最小圆内时,算法才结束,因而最后得到的圆一定是包含点集中所有点的最小圆.

代码
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using TlsCad.Collections;
  6. using Autodesk.AutoCAD.Geometry;
  7. namespace TlsCad.ExtendMethods
  8. {
  9.     public static class PointEx
  10.     {
  11.         #region PointList
  12.         /// <summary>
  13.         /// 判断点是否属于圆
  14.         /// </summary>
  15.         /// <param name="ca2d"></param>
  16.         /// <param name="pnt"></param>
  17.         /// <returns></returns>
  18.         public static bool IsPartOf(this CircularArc2d ca2d, Point2d pnt)
  19.         {
  20.             return ca2d.IsOn(pnt) || ca2d.IsInside(pnt);
  21.         }
  22.         /// <summary>
  23.         /// 按两点返回最小包围圆
  24.         /// </summary>
  25.         /// <param name="pt1"></param>
  26.         /// <param name="pt2"></param>
  27.         /// <param name="ptlst">输出圆上的点</param>
  28.         /// <returns></returns>
  29.         public static CircularArc2d GetMinCircle(Point2d pt1, Point2d pt2, out LoopList<Point2d> ptlst)
  30.         {
  31.             ptlst = new LoopList<Point2d> { pt1, pt2 };
  32.             return
  33.                 new CircularArc2d
  34.                 (
  35.                     (pt1 + pt2.GetAsVector()) / 2,
  36.                     pt1.GetDistanceTo(pt2) / 2
  37.                 );
  38.         }
  39.         /// <summary>
  40.         /// 按三点返回最小包围圆
  41.         /// </summary>
  42.         /// <param name="pt1"></param>
  43.         /// <param name="pt2"></param>
  44.         /// <param name="pt3"></param>
  45.         /// <param name="ptlst">输出圆上的点</param>
  46.         /// <returns></returns>
  47.         public static CircularArc2d GetMinCircle(Point2d pt1, Point2d pt2, Point2d pt3, out LoopList<Point2d> ptlst)
  48.         {
  49.             ptlst =
  50.                 new LoopList<Point2d> { pt1, pt2, pt3 };
  51.             //遍历各点与下一点的向量长度,找到距离最大的两个点
  52.             double maxLength;
  53.             LoopListNode<Point2d> maxNode =
  54.                 ptlst.GetNodes().FindByMaxKey
  55.                 (
  56.                     out maxLength,
  57.                     node => node.Value.GetDistanceTo(node.Next.Value)
  58.                 );
  59.             //以两点做最小包围圆
  60.             LoopList<Point2d> tptlst;
  61.             CircularArc2d ca2d =
  62.                 GetMinCircle(maxNode.Value, maxNode.Next.Value, out tptlst);
  63.             //如果另一点属于该圆
  64.             if (ca2d.IsPartOf(maxNode.Previous.Value))
  65.             {
  66.                 //返回
  67.                 ptlst = tptlst;
  68.                 return ca2d;
  69.             }
  70.             //否则按三点做圆
  71.             ptlst.SetFirst(maxNode);
  72.             ca2d = new CircularArc2d(pt1, pt2, pt3);
  73.             ca2d.SetAngles(0, Math.PI * 2);
  74.             return ca2d;
  75.         }
  76.         /// <summary>
  77.         /// 按四点返回最小包围圆
  78.         /// </summary>
  79.         /// <param name="pt1"></param>
  80.         /// <param name="pt2"></param>
  81.         /// <param name="pt3"></param>
  82.         /// <param name="pt4"></param>
  83.         /// <param name="ptlst">输出圆上的点</param>
  84.         /// <returns></returns>
  85.         public static CircularArc2d GetMinCircle(Point2d pt1, Point2d pt2, Point2d pt3, Point2d pt4, out LoopList<Point2d> ptlst)
  86.         {
  87.             LoopList<Point2d> iniptlst =
  88.                 new LoopList<Point2d> { pt1, pt2, pt3, pt4 };
  89.             ptlst = null;
  90.             CircularArc2d ca2d = null;
  91.             //遍历C43的组合,环链表的优势在这里
  92.             foreach (LoopListNode<Point2d> firstNode in iniptlst.GetNodes())
  93.             {
  94.                 //获取各组合下三点的最小包围圆
  95.                 LoopListNode<Point2d> secondNode = firstNode.Next;
  96.                 LoopListNode<Point2d> thirdNode = secondNode.Next;
  97.                 LoopList<Point2d> tptlst;
  98.                 CircularArc2d tca2d = GetMinCircle(firstNode.Value, secondNode.Value, thirdNode.Value, out tptlst);
  99.                 //如果另一点属于该圆,并且半径小于当前值就把它做为候选解
  100.                 if (tca2d.IsPartOf(firstNode.Previous.Value))
  101.                 {
  102.                     if (ca2d == null || tca2d.Radius < ca2d.Radius)
  103.                     {
  104.                         ca2d = tca2d;
  105.                         ptlst = tptlst;
  106.                     }
  107.                 }
  108.             }
  109.             //返回直径最小的圆
  110.             return ca2d;
  111.         }
  112.         /// <summary>
  113.         /// 按点集返回最小包围圆
  114.         /// </summary>
  115.         /// <param name="pnts"></param>
  116.         /// <param name="ptlst">输出圆上的点</param>
  117.         /// <returns></returns>
  118.         public static CircularArc2d GetMinCircle(this List<Point2d> pnts, out LoopList<Point2d> ptlst)
  119.         {
  120.             //点数较小时直接返回
  121.             switch (pnts.Count)
  122.             {
  123.                 case 0:
  124.                     ptlst = new LoopList<Point2d>();
  125.                     return null;
  126.                 case 1:
  127.                     ptlst = new LoopList<Point2d> { pnts[0] };
  128.                     return new CircularArc2d(pnts[0], 0);
  129.                 case 2:
  130.                     return GetMinCircle(pnts[0], pnts[1], out ptlst);
  131.                 case 3:
  132.                     return GetMinCircle(pnts[0], pnts[1], pnts[2], out ptlst);
  133.                 case 4:
  134.                     return GetMinCircle(pnts[0], pnts[1], pnts[2], pnts[3], out ptlst);
  135.             }
  136.             //按前三点计算最小包围圆
  137.             Point2d[] tpnts = new Point2d[4];
  138.             pnts.CopyTo(0, tpnts, 0, 3);
  139.             CircularArc2d ca2d = GetMinCircle(tpnts[0], tpnts[1], tpnts[2], out ptlst);
  140.             //找到点集中距离圆心的最远点为第四点
  141.             tpnts[3] = pnts.FindByMaxKey(pnt => pnt.GetDistanceTo(ca2d.Center));
  142.             //如果最远点属于圆结束
  143.             while (!ca2d.IsPartOf(tpnts[3]))
  144.             {
  145.                 //如果最远点不属于圆,按此四点计算最小包围圆
  146.                 ca2d = GetMinCircle(tpnts[0], tpnts[1], tpnts[2], tpnts[3], out ptlst);
  147.                 //将结果作为新的前三点
  148.                 if (ptlst.Count == 3)
  149.                 {
  150.                     tpnts[2] = ptlst.Last.Value;
  151.                 }
  152.                 else
  153.                 {
  154.                     //如果计算的结果只有两个点
  155.                     //选择上一步计算的圆心为基准,找出点集中圆心的最远点作为第三点
  156.                     //似乎是算法的问题?这里第三点不能任意选择,否则无法收敛
  157.                     //tpnts[2] = pnts.GetMaxBy(pnt => pnt.GetDistanceTo(ca2d.Center));
  158.                     //if (ca2d.IsPartOf(tpnts[2]))
  159.                     //    return ca2d;
  160.                     //看来是理解有误,第三点应该取另两点中距离圆心较远的点
  161.                     //但按算法中描述的任选其中一点的话,还是无法收敛......
  162.                     tpnts[2] =
  163.                         tpnts.Except(ptlst)
  164.                         .FindByMaxKey(pnt => ca2d.Center.GetDistanceTo(pnt));
  165.                 }
  166.                 tpnts[0] = ptlst.First.Value;
  167.                 tpnts[1] = ptlst.First.Next.Value;
  168.                 //按此三点计算最小包围圆
  169.                 ca2d = GetMinCircle(tpnts[0], tpnts[1], tpnts[2], out ptlst);
  170.                 //找到点集中圆心的最远点为第四点
  171.                 tpnts[3] = pnts.FindByMaxKey(pnt => pnt.GetDistanceTo(ca2d.Center));
  172.             }
  173.             return ca2d;
  174.         }
  175.         public static ConvexHull2d GetConvexHull(this List<Point2d> pnts)
  176.         {
  177.             ConvexHull2d ch2d = new ConvexHull2d();
  178.             ch2d.MelkmanEval(pnts);
  179.             return ch2d;
  180.         }
  181.         public static ConvexHull2d GetConvexHull2(this List<Point2d> pnts)
  182.         {
  183.             ConvexHull2d ch2d = new ConvexHull2d();
  184.             ch2d.JarvisEval(pnts);
  185.             return ch2d;
  186.         }
  187.         public static ConvexHull2d GetConvexHull3(this List<Point2d> pnts)
  188.         {
  189.             ConvexHull2d ch2d = new ConvexHull2d();
  190.             ch2d.GrahamEval(pnts);
  191.             return ch2d;
  192.         }
  193.         #endregion
  194.     }
  195. }

 楼主| 发表于 2010-7-5 14:46 | 显示全部楼层
相关的扩展函数和效果(测试代码见4楼)
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace TlsCad.ExtendMethods
  6. {
  7.     public static class LinqEx
  8.     {
  9.         /// <summary>
  10.         /// 按转换函数找出序列中最大键值的对应值
  11.         /// </summary>
  12.         /// <typeparam name="TValue"></typeparam>
  13.         /// <typeparam name="TKey"></typeparam>
  14.         /// <param name="enumerable"></param>
  15.         /// <param name="func"></param>
  16.         /// <returns></returns>
  17.         public static TValue FindByMaxKey<TValue, TKey>(this IEnumerable<TValue> enumerable, Func<TValue, TKey> func)
  18.             where TKey : IComparable<TKey>
  19.         {
  20.             var itor = enumerable.GetEnumerator();
  21.             if (!itor.MoveNext())
  22.                 throw new ArgumentNullException();
  23.             TValue value = itor.Current;
  24.             TKey key = func(value);
  25.             while (itor.MoveNext())
  26.             {
  27.                 TKey tkey = func(itor.Current);
  28.                 if (tkey.CompareTo(key) > 0)
  29.                 {
  30.                     key = tkey;
  31.                     value = itor.Current;
  32.                 }
  33.             }
  34.             return value;
  35.         }
  36.         /// <summary>
  37.         /// 按转换函数找出序列中最大键值的对应值
  38.         /// </summary>
  39.         /// <typeparam name="TValue"></typeparam>
  40.         /// <typeparam name="TKey"></typeparam>
  41.         /// <param name="enumerable"></param>
  42.         /// <param name="maxResult">对应的最大键值</param>
  43.         /// <param name="func"></param>
  44.         /// <returns></returns>
  45.         public static TValue FindByMaxKey<TValue, TKey>(this IEnumerable<TValue> enumerable, out TKey maxResult, Func<TValue, TKey> func)
  46.             where TKey : IComparable<TKey>
  47.         {
  48.             var itor = enumerable.GetEnumerator();
  49.             if (!itor.MoveNext())
  50.                 throw new ArgumentNullException();
  51.             TValue value = itor.Current;
  52.             TKey key = func(value);
  53.             while (itor.MoveNext())
  54.             {
  55.                 TKey tkey = func(itor.Current);
  56.                 if (tkey.CompareTo(key) > 0)
  57.                 {
  58.                     key = tkey;
  59.                     value = itor.Current;
  60.                 }
  61.             }
  62.             maxResult = key;
  63.             return value;
  64.         }
  65.         /// <summary>
  66.         /// 按转换函数找出序列中最小键值的对应值
  67.         /// </summary>
  68.         /// <typeparam name="TValue"></typeparam>
  69.         /// <typeparam name="TKey"></typeparam>
  70.         /// <param name="enumerable"></param>
  71.         /// <param name="maxResult">对应的最小键值</param>
  72.         /// <param name="func"></param>
  73.         /// <returns></returns>
  74.         public static TValue FindByMinKey<TValue, TKey>(this IEnumerable<TValue> enumerable, out TKey minKey, Func<TValue, TKey> func)
  75.             where TKey : IComparable<TKey>
  76.         {
  77.             var itor = enumerable.GetEnumerator();
  78.             if (!itor.MoveNext())
  79.                 throw new ArgumentNullException();
  80.             TValue value = itor.Current;
  81.             TKey key = func(value);
  82.             while (itor.MoveNext())
  83.             {
  84.                 TKey tkey = func(itor.Current);
  85.                 if (tkey.CompareTo(key) < 0)
  86.                 {
  87.                     key = tkey;
  88.                     value = itor.Current;
  89.                 }
  90.             }
  91.             minKey = key;
  92.             return value;
  93.         }
  94.         /// <summary>
  95.         /// 按转换函数找出序列中最小键值的对应值
  96.         /// </summary>
  97.         /// <typeparam name="TValue"></typeparam>
  98.         /// <typeparam name="TKey"></typeparam>
  99.         /// <param name="enumerable"></param>
  100.         /// <param name="func"></param>
  101.         /// <returns></returns>
  102.         public static TValue FindByMinKey<TValue, TKey>(this IEnumerable<TValue> enumerable, Func<TValue, TKey> func)
  103.             where TKey : IComparable<TKey>
  104.         {
  105.             var itor = enumerable.GetEnumerator();
  106.             if (!itor.MoveNext())
  107.                 throw new ArgumentNullException();
  108.             TValue value = itor.Current;
  109.             TKey key = func(value);
  110.             while (itor.MoveNext())
  111.             {
  112.                 TKey tkey = func(itor.Current);
  113.                 if (tkey.CompareTo(key) < 0)
  114.                 {
  115.                     key = tkey;
  116.                     value = itor.Current;
  117.                 }
  118.             }
  119.             return value;
  120.         }
  121.         /// <summary>
  122.         /// 按转换函数找出序列中最(小/大)键值的对应值
  123.         /// </summary>
  124.         /// <typeparam name="TValue"></typeparam>
  125.         /// <typeparam name="TKey"></typeparam>
  126.         /// <param name="enumerable"></param>
  127.         /// <param name="func"></param>
  128.         /// <returns></returns>
  129.         public static TValue[] FindByMKeys<TValue, TKey>(this IEnumerable<TValue> enumerable, Func<TValue, TKey> func)
  130.             where TKey : IComparable<TKey>
  131.         {
  132.             var itor = enumerable.GetEnumerator();
  133.             if (!itor.MoveNext())
  134.                 throw new ArgumentNullException();
  135.             
  136.             TValue[] values = new TValue[2];
  137.             values[0] = values[1] = itor.Current;
  138.             TKey minKey = func(values[0]);
  139.             TKey maxKey = minKey;
  140.             while (itor.MoveNext())
  141.             {
  142.                 TKey tkey = func(itor.Current);
  143.                 if (tkey.CompareTo(minKey) < 0)
  144.                 {
  145.                     minKey = tkey;
  146.                     values[0] = itor.Current;
  147.                 }
  148.                 else if (tkey.CompareTo(maxKey) > 0)
  149.                 {
  150.                     maxKey = tkey;
  151.                     values[1] = itor.Current;
  152.                 }
  153.             }
  154.             return values;
  155.         }
  156.         /// <summary>
  157.         /// 按比较器找出序列中最(小/大)键值的对应值
  158.         /// </summary>
  159.         /// <typeparam name="TValue"></typeparam>
  160.         /// <param name="enumerable"></param>
  161.         /// <param name="comparison"></param>
  162.         /// <returns></returns>
  163.         public static TValue[] FindByMKeys<TValue>(this IEnumerable<TValue> enumerable, Comparison<TValue> comparison)
  164.         {
  165.             var itor = enumerable.GetEnumerator();
  166.             if (!itor.MoveNext())
  167.                 throw new ArgumentNullException();
  168.             TValue[] values = new TValue[2];
  169.             values[0] = values[1] = itor.Current;
  170.             while (itor.MoveNext())
  171.             {
  172.                 if (comparison(itor.Current, values[0]) < 0)
  173.                 {
  174.                     values[0] = itor.Current;
  175.                 }
  176.                 else if (comparison(itor.Current, values[0]) > 0)
  177.                 {
  178.                     values[1] = itor.Current;
  179.                 }
  180.             }
  181.             return values;
  182.         }
  183.         /// <summary>
  184.         /// 按转换函数找出序列中最(小/大)键值的对应键值
  185.         /// </summary>
  186.         /// <typeparam name="TValue"></typeparam>
  187.         /// <typeparam name="TKey"></typeparam>
  188.         /// <param name="enumerable"></param>
  189.         /// <param name="func"></param>
  190.         /// <returns></returns>
  191.         public static TKey[] FindMKeys<TValue, TKey>(this IEnumerable<TValue> enumerable, Func<TValue, TKey> func)
  192.             where TKey : IComparable<TKey>
  193.         {
  194.             var itor = enumerable.GetEnumerator();
  195.             if (!itor.MoveNext())
  196.                 throw new ArgumentNullException();
  197.             TKey[] keys = new TKey[2];
  198.             keys[0] = keys[1] = func(itor.Current);
  199.             while (itor.MoveNext())
  200.             {
  201.                 TKey tkey = func(itor.Current);
  202.                 if (tkey.CompareTo(keys[0]) < 0)
  203.                 {
  204.                     keys[0] = tkey;
  205.                 }
  206.                 else if (tkey.CompareTo(keys[1]) > 0)
  207.                 {
  208.                     keys[1] = tkey;
  209.                 }
  210.             }
  211.             return keys;
  212.         }
  213.     }
  214. }

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册

x
发表于 2010-7-6 23:45 | 显示全部楼层
用于CAD的什么版本啊?我用CAD2008,无法编译通过,比如DBTransaction类就无法识别,是版本错误还是少引用了什么文件?
 楼主| 发表于 2010-7-7 06:45 | 显示全部楼层

DBTransaction:

http://bbs.mjtd.com/forum.php?mod=viewthread&tid=76123

不过这是个较老的版本,

tt3测试命令的

tr.ZoomWindow(new Point3d(-10, -10, 0), new Point3d(110, 110, 0));

还是不能用

不过,这是个纯测试代码,可以去掉

另外版本为:VS2008+ACad2008,上面的代码用到了很多C#3.0的语法,如果是VS2005,就要改很多了

发表于 2010-7-7 15:40 | 显示全部楼层

前来学习

 

发表于 2010-7-10 10:06 | 显示全部楼层
顶!!!!!
您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|CAD论坛|CAD教程|CAD下载|联系我们|关于明经|明经通道 ( 粤ICP备05003914号 )  
©2000-2023 明经通道 版权所有 本站代码,在未取得本站及作者授权的情况下,不得用于商业用途

GMT+8, 2024-4-20 04:19 , Processed in 0.225987 second(s), 25 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表