Pergunta

In Java, I have a BitSet bigger in size than an array (100000 > 2000). Array contains positive integers from range [1; 100000]. I want to intersect given array and bitset. Obviously intersection will be of size less than the size of an array, so I want to store it as an array. My code below:

BitSet b = new BitSet(100000);
int[] a = new int[2000];
// fill in b with some bits and a with positive integers in range from [1; 100000]

// intersect array a and bitset b and keep result in separate array
int[] intersection = new int[a.length];
int c = 0, i = 0, j = b.nextSetBit(0);
while (i < a.length && j >= 0) {
    if (a[i] < j) i++;
    else if (a[i] > j) j = b.nextSetBit(j+1);
    else {
        intersection[c] = j;
        i++; j = b.nextSetBit(j+1); c++;
    }
}

// usually intersection is less than a array in size so cut it
int[] zip = new int[c];
System.arraycopy(intersection, 0, zip, 0, c);

Is it possible to get faster in time code than the presented above one?

EDIT array a is sorted, for example a = { 2, 115, 116, 2034, 26748 }.

Foi útil?

Solução

This is definitely simpler, and I think may be faster, because it only accesses those elements of b whose index is in a. It does not scan the whole of b looking for the next set bit.

  public static int[] intersect(BitSet b, int[] a){
    int[] rawResult = new int[a.length];
    int c = 0;
    for(int i : a){
      if(b.get(i)){
        rawResult[c] = i;
        c++;
      }
    }
    int[] result = new int[c];
    System.arraycopy(rawResult, 0, result, 0, c);
    return result;
  }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top