结构,队列,列表与x,y,时间值在c# ?计算它们的平均速度

本文关键字:计算 平均速度 列表 队列 时间 结构 | 更新日期: 2023-09-27 18:03:18

我最初有一个结构体来存储c#中的x,y和时间坐标,如

  struct handCoordinate {
         internal double x; 
         internal double y; 
         internal double time; 
  }

并计划使用队列来存储此数据。我需要计算这些数据的平均速度,并将下一项与前一项进行比较。使用队列来比较每个handCoordinate项目,然后使用列表,这有意义吗?下面是一个例子:

 handCoordinate(4.0, 0.01, 1.3)
 handCoordinate(-3.0, 0.02, 1.8)

换句话说,什么数据结构最适合访问这些元素?谢谢!(如果需要,我可以澄清更多)

结构,队列,列表与x,y,时间值在c# ?计算它们的平均速度

SortedList比Queue更有意义,因为您将遍历它以计算平均值。使用队列,您只能保证项目以与推送相同的顺序弹出。使用时间作为键的排序列表将保持项目的时间顺序,而不管它们插入的顺序是什么。排序列表也不需要删除项才能使用它们,这使得在其他计算需要时更容易重用这些项,而无需额外的数据结构。

public struct HandCoordinate
{
     public HandCoordinate(double x, double y, double time)
     {
         this.X = x;
         this.Y = y;
         this.Time= time;
     }
     public readonly double X;
     public readonly double Y;
     public readonly double Time;
}
...
private static double Velocity(HandCoordinate p1, HandCoordinate p2)
{
     var time = p2.Time - p1.Time;
     if (time <= 0)
     {
         throw new ArgumentException("Duplicate measurement");
     }
     var dx = p2.X - p1.X;
     var dy = p2.Y - p1.Y;
     var distance = Math.Sqrt(dx*dx + dy*dy);
     // note the possibility for overflow if your times are very close together.
     // You might need to use logarithms for the calculation.
     return distance/time; 
}
...
var points = new SortedList<double,HandCoordinate>();
points.Add(1.0, new HandCoordinate(1.0, 1.0, 1.0));
points.Add(1.1, new HandCoordinate(1.0, 2.0, 1.1));
..
var velocities = points.Values
                       .Skip(1)
                       // note: because of the skip i in the following is the offset
                       // from the second element and can be used directly to refer
                       // to the previous element
                       .Select((p,i) => Velocity(points.Values[i],p))
                       .ToList();