Getting Random Object from array which satisfies condition

Viewed 72

Say I have two arrays [1, 2, 3, 4, 5, 6] [true, false, true, false, false true];

I want to get a random number from the first list but only if the number corresponds to a true value in the array. Is there an fast, memory efficient way of doing this which - for my specific case - dosen't use Java.util.Arraylist?

3 Answers

You can use IntStream.filter to get only the values that are true and get a random value from that array. This is vastly more efficient if you need to obtain multiple random numbers.

int[] arr = {1, 2, 3, 4, 5, 6};
boolean[] good = {true, false, true, false, false true};
int[] choices = IntStream.range(0, arr.length).filter(i->good[i]).map(i->arr[i]).toArray();
int randVal = choices[(int)(Math.random()*choices.length)];
bool random_condition = false ;
int random_index;
do {
    Random random = new Random () ;
    random_index = random().nextInt(7);
    random_condition = condition_array [random_index]
while (random_condition = false);

With condition_array = [true, false, true, false, false true]

import java.util.Vector;
import java.util.concurrent.ThreadLocalRandom;

public static int getRandomInt() {
    int[] intArray = {1, 2, 3, 4, 5, 6};
    boolean[] boolArray = {true, false, true, false, false, true};
    Vector<Integer> choices = new Vector<>();
    for (int i = 0; i < boolArray.length; i++) {
        if (boolArray[i]) {
            choices.add(intArray[i]);
        }
    }
    return choices.get(ThreadLocalRandom.current().nextInt(0, choices.size()));
}

This is a linear solution that avoids java.util.ArrayList. That said, there are better ways to implement this without using two separate arrays, so I'd suggest reevaluating your design.

Related