StudentCoder
StudentCoder

Reputation: 25

randomly remove element from array java

I am removing elements from an array in the below code. In this particular code I am removing the element at pos 2. How would I go about removing a random element in this array?

public class QuestionOneA2 {

public static void main(String[] args) {
    int size = 5;
    int pos = 2;

    String[] countries = {"Brazil", "France", "Germany", "Canada", "Italy", "England"};

        for (int i = 0; i < size; i++) {
            if(i == pos) {
                countries[i] = countries[size];
            }
            System.out.println(countries[i]);
        }   
    }
}

Upvotes: 1

Views: 4406

Answers (3)

ungive
ungive

Reputation: 71

In case you do not mind the order of the elements, you can also achieve this behaviour in constant time:

public <E> E removeRandom(List<E> list, Random random) {
    if (list.isEmpty())
        throw new IllegalArgumentException();

    int index = random.nextInt(list.size());
    int lastIndex = list.size() - 1;

    E element = list.get(index);
    list.set(index, list.get(lastIndex));
    list.remove(lastIndex);

    return element;
}

Upvotes: 0

Idos
Idos

Reputation: 15320

Remove this element:

int randomLocation = new Random().nextInt(countries.length);
// countries[randomLocation]  <--- this is the "random" element.

Or in 1 line:

countries[(new Random()).nextInt(countries.length)];

So in order to actually remove the element you can use ArrayUtils: First import these

import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;

And then:

countries = ArrayUtils.removeElement(countries, countries[(new Random()).nextInt(countries.length)]);

If you really don't want to use ArrayUtils then you can use:

List<String> list = new ArrayList<String>(Arrays.asList(countries));
list.removeAll(Arrays.asList(countries[(new Random()).nextInt(countries.length)]));
countries = list.toArray(countries);

Upvotes: 1

Diogo Rocha
Diogo Rocha

Reputation: 10625

Random r = new Random();
int result = r.nextInt(size);
//and select/remove countries[result]

This give you a pseudo-random number between 0 and 5 (exclusive). Be careful with your size variable, I think it's not well defined.

Upvotes: 1

Related Questions