Scala fast generation of upper triangular matrix c

2019-05-24 15:12发布

As a first attempt consider

for (a <- 1 to 5; b <- 1 to 5; if a < b) yield (a,b)

which gives

Vector((1,2), (1,3), (1,4), (1,5), 
              (2,3), (2,4), (2,5), 
                     (3,4), (3,5), 
                            (4,5))

Only half of the values for b have effect, hence

for (a <- 1 to 5; b <- a+1 to 5) yield (a,b)

also delivers the same upper triangular matrix coordinates.

To ask though on faster approaches to generate this vector of coordinates.

Many Thanks.

1条回答
霸刀☆藐视天下
2楼-- · 2019-05-24 15:34

The best you can do is stick everything in an Array and and create the elements in a while loop (or recursively) to avoid any overhead from the generic machinery of for. (Actually, you'd be even faster with two arrays, one for each index.)

val a = {
  val temp = new Array[(Int, Int)](5*4/2)
  var k = 0
  var i = 1
  while (i <= 5) {
    var j = i+1
    while (j <= 5) {
      temp(k) = (i,j)
       j += 1
       k += 1
    }
    i += 1
  }
  temp
}

But you shouldn't go to all this trouble unless you have good reason to believe that your other method isn't working adequately.

You've titled this "parallel processing", but you're probably going to tax your memory subsystem so heavily that parallelization isn't going to help you much. But of course you can always split up some of the lines onto different processors. You need something way, way larger than 5 for that to be a good idea.

查看更多
登录 后发表回答