47.9k views
4 votes
Write a public member function removeRandom that removes a random element from the ArrayBag. This method should also return a boolean indicating whether an element was actually removed

1 Answer

0 votes

Answer:

Step-by-step explanation:

The following code is written in Java. It is a function that takes in the ArrayList called ArrayBag as a parameter and randomly removes one of the elements in the ArrayList. As long as the ArrayBag has at least 1 element it will return true otherwise it will return false.

public static boolean removeRandom(ArrayList ArrayBag) {

Random rand = new Random();

if (ArrayBag.size() > 0) {

int randomNumber = rand.nextInt(ArrayBag.size());

ArrayBag.remove(randomNumber);

return true;

} else {

return false;

}

}

User Doin
by
5.0k points