简体   繁体   中英

Scala fast generation of upper triangular matrix coordinates

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.

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.

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