Randomly take an int element from an integer array

I have an Integer array and I want to randomly take an element from those who are not null. I have tried this but after the else, I cannot use return because the method is int. But I don't know what to write after else in order to return at the beginning and take a new random element.

3 answers

  • answered 2021-05-15 15:17 Daniel

    You could make your method recursive:

    private Random x = new Random();
    
    public int getRandomPosition(){
        int b = x.nextInt(sizeOfArray);
        if (myArray[b] != null){
           return b;
        }
        // else {
        return getRandomPosition();
    }
    

    or using a while-loop

    private Random x = new Random();
    
    public int getRandomPosition(){
        Integer result = null; 
        do {
          int index = x.nextInt(sizeOfArray);
          result = myArray[index];
        } while (result == null);
        return result.intValue();
    }
    

    Theoretically, however, the method could run indefinitely if you're really unlucky. Therefore, it probably makes sense to include a counter, so for example only try max. 20 times, then return null:

    private Random x = new Random();
    
    public int getRandomPosition(){
        Integer result = null; 
        int tries = 0;
        do {
          int index = x.nextInt(sizeOfArray);
          result = myArray[index];
        } while (result == null && ++tries < 20);
        return result.intValue();
    }
    

  • answered 2021-05-15 15:27 XYZ

    You can achieve this by using a loop.

    public int getRandomPosition(){
        Random random = new Random();
        int randomIdx = random.nextInt(2 * number0fCardPairs);
    
        // while array at randomIdx is null, continue getting new randomIdx
        while (array[randomIdx] == null) {
            randomIdx = random.nextInt(2 * number0fCardPairs);
        }
    
        return randomIdx;
    }
    

    Note that if all the elements inside the array are null, it will be an infinite loop. Hope you find this helpful!

  • answered 2021-05-16 13:35 Most Needed Rabbit

    You can do:

    Integer[] myArray = {1,2,3,null,5};
    
    List<Integer> nonNullIntegers = Arrays.stream(myArray)
            .filter(Objects::nonNull)
            .collect(Collectors.toList());
    
    Random random = new Random();
    Integer randomInteger = nonNullIntegers.get(random.nextInt(nonNullIntegers.size()));