加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Scala中生成懒惰的“螺旋”

发布时间:2020-12-16 18:10:27 所属栏目:安全 来源:网络整理
导读:任务: 对于2D阵列中的给定位置,生成位于半径内的周围位置的列表. 例如: input: (1,1)radius: 1output: ( (0,0),(1,(2,(0,1),2),2) ). 我写了类似的东西 def getPositions(x:Int,y:Int,r:Int) = { for(radius - 1 to r) yield { List( for (dx - -radius to
任务:
对于2D阵列中的给定位置,生成位于半径内的周围位置的列表.

例如:

input: (1,1)
radius: 1
output: ( (0,0),(1,(2,(0,1),2),2) ).

我写了类似的东西

def getPositions(x:Int,y:Int,r:Int) = {
  for(radius <- 1 to r) yield {
    List(
      for (dx <- -radius to radius) yield Pair(x + dx,y - radius),for (dx <- -radius to radius) yield Pair(x + dx,y + radius),for (dy <- -radius to radius) yield Pair(x + radius,y + dy),for (dy <- -radius to radius) yield Pair(x - radius,y + dy)
    )
  }
}

在这段代码中,getPositions不返回一系列点数,而是返回点序列的Tuple4序列.
如何“连接”代码中列出的4个生成器?或者我的任务有更简洁的解决方案吗? (我对scala很新).

附:
这实际上是我的星际机器人.

解决方法

你需要压扁List(两次),所以这样做:

def getPositions(x:Int,y + dy)
    ).flatten
  }
}.flatten

不过,这不是一个“懒惰”的螺旋.

编辑

那个懒惰:

def P(i:Int,j:Int) = { print("eval"); Pair(i,j) }

def lazyPositions(x:Int,r:Int) = {
  (1 to r).toStream.flatMap{ radius =>

    (-radius to radius).toStream.map(dx => P(x + dx,y - radius)) #:::
    (-radius to radius).toStream.map(dx => P(x + dx,y + radius)) #:::
    (-radius to radius).toStream.map(dy => P(x + radius,y + dy)) #:::
    (-radius to radius).toStream.map(dy => P(x - radius,y + dy))
  }
}


print(lazyPositions(1,1,1).take(3).toList) # prints exactly three times ‘eval’.

我用def P方法来显示真正的懒惰.每次,你都会创建一个Pair,它会被调用.在懒惰的解决方案中,您只需按需提供此功能.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读