0

We have an array of random lenght and random numbers eg.

[12, 2345, 232, 52, 24]. 

And we Want to select only those defined by a binary number so eg.

5= 101 = [0, 0, 1, 0, 1] 

so the Array X which i want to get is

[0, 0, 232, 0, 24];

Example

int[] x = {12, 2345, 232, 52, 24};
int b = 5;
int[] X = eliminate(x, b);

//
x = [12, 2345, 232, 52, 24]
b = [ 0,    0,   1,  0,  1]
X = [ 0,    0, 232,  0, 24]

any quick way to do this?

Thanks

Mazmart
  • 2,703
  • 4
  • 17
  • 20

4 Answers4

3

Using a BitSet might help, for conversions between int and BitSet have a look here: BitSet to and from integer/long

Here's a quick hack using the Bits class from the link:

public static int[] eliminate( int[] x, int b) {
  BitSet bs = Bits.convert( b );
  int[] X = new int[x.length];

  for( int i = 0; i < x.length; i++){
    if( bs.get( x.length - (i + 1) ) ){
      X[i] = x[i];
    }
    else {
      X[i] = 0;
    }
  }

  return X;
}

Result would be:

x = [12, 2345, 232, 52, 24]
b = 5 (i.e. 101 binary)
X = [0, 0, 232, 0, 24]

Note that if you want to define bits directly, you can just set them in the BitSet.

Community
  • 1
  • 1
Thomas
  • 87,414
  • 12
  • 119
  • 157
1

Just a for-loop

int[] newarray = new int[length];
for(int i = 0; i < length; i++)
{
    if(b[i]==1)
       newarray[i] = x[i];
    else
       newarray[i] = 0;
}

Just make sure the length everywhere is consistent.

Loki
  • 4,065
  • 4
  • 29
  • 51
0

As this:

int i = 3;
int[] yourArray;
for (int i = 0; i < yourArray.length; i++) {
    yourArray[i] = yourArray[i] & i == i ? yourArray[i] : 0;
}
Alex Suo
  • 2,977
  • 1
  • 14
  • 22
0

Try this:

    String binSt = Integer.toBinaryString(5); // has no leading 0s
    byte[] x = {12, 21, 21, 52, 24};
    byte[] xResult = new byte[x.length];
    int offset = x.length - binSt.length(); // to simulate leading 0s
    for (int i = 0; i < xResult.length; i++) {
        xResult[i] = (i-offset < binSt.length() && i-offset >= 0 && binSt.charAt(i-offset) == '1' ? x[i] : 0);
    }
    System.out.println(Arrays.toString(xResult));
Angelo Fuchs
  • 9,825
  • 1
  • 35
  • 72