简体   繁体   English

在布尔数组中迭代trues的快速方法

[英]Fast way of iterate over trues in boolean array

I have a big array of booleans and i need just to work with the true elements, and need theyer index. 我有一大堆布尔值,我只需要处理真正的元素,并需要theyer索引。

for (int x = 0; x < cells.length; x++) {
        for (int y = 0; y < cells[0].length; y++) {

                if (cells[x][y]) {
                    g.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
                }

        }
    }

so how can i do that without the two foor loops and save the time? 那么如果没有两个foor循环我怎么能这样做并节省时间?

I'd say this is the best you can get. 我会说这是你能得到的最好的。

You are already using a primitive array and I expect primitive boolean type. 您已经在使用原始数组,我希望原始布尔类型。

The only thing I could suggest is saving cells.length and cells[0].length in final variables before the loops, it could save some time, but the compiler may already optimize this on its own. 我唯一能建议的是在循环之前保存final变量中的cells.lengthcells[0].length ,它可以节省一些时间,但编译器可能已经自己优化了这个。

不幸的是,由于你的要求,你被困在O(n) ......意思是,你必须观察一次数组中的每个值,找到具有true值的所有cells

您可以实现一些数组包装器 ,它将链接true值(以设置操作的成本),这样您就可以只迭代true索引。

We can do by this, Convert int[array] to String and find index where 1 present. 我们可以这样做,将int [array]转换为String并找到1存在的索引。 Based on index perform the operation. 基于索引执行操作。

String arrayStr=Arrays.toString(cells[0].length);

String booleanVal="1";
int index = word.indexOf(booleanVal);

    while(index >= 0) {

                if (cells[x][index]) {
                    g.fillRect(x * cellSize, index * cellSize, cellSize, cellSize);
                }

    index = word.indexOf(arrayStr, index+1);
}

By this your inner for loop with run n/4 times. 通过这个你的内部for循环运行n / 4次。 It save time.. 它节省时间..

Pass a integer value for |cells[0].length/2|. 为| cells [0] .length / 2 |传递一个整数值。

/********************* */ / ********************* * /

for (int y=0, oddOccurLeft = cells[0].length/2,oddOccurRight = cells[0].length/2, evenOccurLeft=cells[0].length/2,evenOccurRight=cells[0].length/2; ;y++ ) {

    if (cells[x][oddOccurLeft]) {
                    g.fillRect(x * cellSize, oddOccurLeft * cellSize, cellSize, cellSize);
    }

    if (cells[x][oddOccurRight]) {
                    g.fillRect(x * cellSize, oddOccurRight * cellSize, cellSize, cellSize);
    }

    if (cells[x][evenOccurLeft]) {
                    g.fillRect(x * cellSize, evenOccurLeft * cellSize, cellSize, cellSize);
    }

    if (cells[x][evenOccurRight]) {
                    g.fillRect(x * cellSize, evenOccurRight * cellSize, cellSize, cellSize);
    }

    ***if(oddOccurLeft<0 && oddOccurRight<0 && oddOccurRight>cells[0].length && evenOccurLeft>cells[0].length && evenOccurRight>cells[0].length)
        break;***

    oddOccurLeft=oddOccurLeft-y*2+1;
    oddOccurRight=oddOccurRight+y*2+1;

    evenOccurLeft=evenOccurLeft-y*2;
    evenOccurRight=evenOccurRight+y*2;

   }

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

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