Scala快速生成上三角矩阵坐标 [英] Scala fast generation of upper triangular matrix coordinates

查看:100
本文介绍了Scala快速生成上三角矩阵坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一次尝试

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

给出

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

b的值只有一半有效,因此

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.

非常感谢.

推荐答案

您能做的最好的事情就是将所有内容粘贴在Array中,并在while循环中(或递归地)创建元素,以免产生任何开销for的通用机制. (实际上,使用两个数组可以更快,每个索引一个.)

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.

您已将这种标题称为并行处理",但是您可能要对内存子系统加重负担,以至于并行化不会对您有太大帮助.但是,当然,您总是可以将某些行拆分为不同的处理器.您需要某种方法,大于5才是一个好主意.

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.

这篇关于Scala快速生成上三角矩阵坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆