gpt4 book ai didi

list - scala 列表 LineSegment

转载 作者:行者123 更新时间:2023-12-02 08:29:24 24 4
gpt4 key购买 nike

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

例如:点列表 - (p1,p2,p3,p4,p5,p6) 线段列表 - ((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 列表?

最佳答案

您可以zip 列表及其自身的旋转版本,然后映射到LineSegments:

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

您可能还对滑动方法感兴趣:

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

关于list - scala 列表 LineSegment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28663788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com