scala list LineSegment

时间:2015-02-22 21:59:45

标签: list scala grouping

我有一个由一组点组成的多边形,我想通过组合相应点的列表然后将最后一个点与第一个点组合来找到该多边形的线段列表

例如:点数列表 - (p1,p2,p3,p4,p5,p6)      lineSegments列表 - ((p1,p2),(p2,p3),(p3,p4),(p4,p5),(p5,p6),(p6,p1))

sealed trait Shape

case class Point(x: Int, y: Int) extends Shape {
//require(x != null & y !=null, "null values for point")
}

case class LineSegment(point1: Point, point2: Point)  extends Shape {
 require(point1 != point2)

class Group(val children: Shape*) extends Shape {
 require(children != null, "null children in " + getClass.getSimpleName)
 require(!children.contains(null), "null child in " +
 getClass.getSimpleName) }


 object Group {
 def apply(children: Shape*) = new Group(children: _*)
 def unapply(g: Group) = Some(g.children)
 }

 /** A special case of a group consisting only of Points. */
  case class Polygon(override val children: Point*) 
   extends Group(children:   _*){
   require(children != null)

    def findLineSegments(poylgon: Polygon): List[LineSegment] = {
     val points  = children.toList
     val lineSegmentList = points.grouped(2).toList
     return lineSegmentList
    } }

  // polygon example
  val simplePolygon = Polygon(
   Point(50, 50),
   Point(60, 100),
   Point(100, 110),
   Point(120, 60)
   )

我正在定义行为findLineSegment以对相应的点进行分组,但我得到的是List [list(points)] ..如何将此列表转换为LineSegments列表?

2 个答案:

答案 0 :(得分:4)

您可以使用自身的轮播版本zip列表,然后映射到LineSegments

(points zip ((points drop 1) ::: (points take 1))) map LineSegment.tupled

您可能也对sliding方法感兴趣:

points.sliding(2).map { case List(a, b) => LineSegment(a, b) } 
    :+ LineSegment(points.last, points.head)

答案 1 :(得分:2)

最简单的方法可能如下。

val rot1 = simplePolygon.drop(1) ++ simplePolygon.take(1)
for ((pi,pj) <- simplePolygon zip rot1) yield LineSegment(pi, pj)

在这里,您可以通过删除一个元素并将其添加回最后来创建第二个列表。

然后,您通过压缩它们来一次遍历两个列表,并在每个步骤中将两个点关联到新的LineSegment中。 (这是一个案例类,所以我们实际上在这里调用了伴随对象的apply方法。)