给定矩阵单元的邻居

时间:2017-07-18 06:53:21

标签: scala matrix

假设我需要枚举Vector[Vector[Int]]

中给定单元格的所有邻居
type Matrix = Vector[Vector[Int]]
def neighbors(i: Int, j: Int, m: Matrix): Seq[Int] = ???

我正在写neighbors

def neighbors(i: Int, j: Int, m: Matrix): Seq[Int] = for {
  dx <- -1 to 1
  dy <- -1 to 1
  if (dx | dy) != 0 && m.indices.contains(i + dx) && m(i).indices.contains(j + dy)
} yield m(i + dx)(j + dy)

这个实现看起来很好,但有点尴尬。你能建议更好的解决方案吗?

1 个答案:

答案 0 :(得分:2)

不简单 - 二手升降机

def neighbors(i: Int, j: Int, m: Matrix): Seq[Int] = (-1 to 1).flatMap {
    y => (-1 to 1).map { x => (x, y) }
  }.withFilter {
    case (x, y) => x != 0 || y != 0
  }.flatMap {
    case (x, y) => m.lift(i).flatMap(x => x.lift(y))
  }