简体   繁体   中英

Simple matrix calculation in Scala

Suppose I've got a matrix of integers a and need to create a new matrix b so that b[i, j] is sum of a[i, j] and its neighbors.

I define a matrix as Array[Array[Int]] and write a function foo to calculate b like this:

type Matrix = Array[Array[Int]]

def sumOfNeighbors(a: Matrix, x: Int, y: Int): Int = {

  val range = -1 to 1
  val deltas = range.flatMap { dx => range map {dy => (dx, dy)} }
                    .filter  { case (dx, dy) => dx != 0 || dy != 0 }

  val withinBounds: Int => Boolean = x => x >= 0 && x < a.size
  val coords = deltas.map {case (dx, dy) => (x + dx, y + dy)}
                     .filter {case (i, j) => withinBounds(i) && withinBounds(j)}

  coords.map{case (i, j) => a(i)(j)}.sum
}

def foo(a: Matrix): Matrix =
  a.zipWithIndex map {case (row, i) => 
    row.zipWithIndex.map {case (x, j) => x + sumOfNeighbors(a, i, j)} 
  }

Does it make sense ? How would you simplify this code ?

Your code does make sense, but there are a couple tools you could add that could make this expandable, depending on your resources.
If you combine Spark with your Scala code (if feasible) you can utilize some of the mean-shift packages available to Spark. Using RDDs you can do a lot of the same functions.
https://spark-packages.org/?q=tags%3Alsh

If this is just small-scale though, none of this is really necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM