简体   繁体   English

Scala快速生成上三角矩阵坐标

[英]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 b的值只有一半有效,因此

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 . 最好的办法是将所有内容粘贴在Array ,并在while循环中(或递归)创建元素,以免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. 您需要某种方式,大于5才是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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