【问题标题】:Trying to fill boolean matrix with random values尝试用随机值填充布尔矩阵
【发布时间】:2013-12-01 23:37:58
【问题描述】:
while(MatriceLib.compteTrue(champsMine)!= nbMines)
       {
          int i = (int) Math.floor((Math.random()*(longueur-1)));
          int j = (int)Math.floor((Math.random()*(largeur-1)));
          champsMine[i][j] = true;
} 

champsMine 是布尔矩阵,布尔值位于随机位置。 compteTrue 正在返回矩阵中 true 数量的 int 值。 nbMines 是矩阵必须具有的真数。

问题是用值填充矩阵需要很长时间。

有没有办法提高效率?

【问题讨论】:

    标签: java loops random matrix boolean


    【解决方案1】:

    您没有发布很多代码,但看起来您每次通过循环都在计算数组中 true 元素的数量。这是缓慢的部分。相反,请考虑随时保持计数,例如:

    int count = 0; // or whatever the current count is, if there are already true elements
    while (count < nbMines) {
        int i = ...;
        int j = ...;
        if (!champsMine[i][j]) {
            ++ count;
            champsMine[i][j] = true;
        }
    }
    

    当然,随着剩余false 插槽数量的减少(增加已设置随机位置的机会),这将减慢速度。另一种方法是创建所有(i,j) 组合的数组/列表(网格中的每个单元格一个),随机打乱该列表,然后从该列表中获取第一个nbMines 坐标并将这些值设置为true。设置起来稍微复杂一些,但仍然很简单,并且速度非常快(填充列表然后对其进行改组保证您不会选择已经设置的坐标)。对于nbMines 大于网格单元数的可能性,自然也是安全的。

    【讨论】:

    • 你打败了我 :) 洗牌会更有效率,可能和 2 次调用 compteTrue 一样快。
    猜你喜欢
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多