1

I have an ArrayList of an object from where I want items of a particular position, but everytime I launch the Activity the retrieved position should be randomize and also won't repeat until every position Item is completely retrieved. I used this method:

public static int getRandomNumber(ArrayList<Integer> arr)
            throws IllegalArgumentException {
        try {
            Random random = new Random();
            int select = random.nextInt(arr.size());
            int randomnum = arr.get(select);
            GlobalData.randList.remove(select);
            return randomnum;
        } catch (IllegalArgumentException e) {

            for (int i = 0; i < arr.size(); i++) {

                GlobalData.randList.add(i);

            }
            return 0;
        }

but its not working,like duplicate number is coming, there may be a reason because everytime I am re launching the activity. I did it in oncreate instead of onResume but its not working as I expected? Is there any other way to work with it? Any solution?

Reyjohn
  • 2,654
  • 9
  • 37
  • 63

2 Answers2

2

Use Collections.shuffle() to shuffle the array. Use another variable to track the current position in the array. Each time you retrieve a new value increment the variable. Once you reach the end of the array re-shuffle it.

Reference: Shuffling algorithms

public class RandomArray {
    ArrayList<Integer> array = null;
    int position = 0;

    public RandomArray(ArrayList<Integer> arr) {
        array = arr;
        position = arr.size();
    }

    public int getNext() {
        if (position == array.size()) {
           position = 0;
           Collections.shuffle(array);
        }
        return array.get(position++);
    }
}
Frohnzie
  • 3,559
  • 1
  • 21
  • 24
1

If you don't care about the original order, you can try this:

Object[] array = new Object[10];    // say 10 objects
int remain = array.length;
Random rnd = new Random();

public Object next () {
    if (remain == 0) {
        return null;
    } else {
        int i = rnd.nextInt(remain--);
        Object tmp = array[i];
        array[i] = array[remain];
        array[remain] = tmp;
        return tmp;
    }
}

You can also do similar thing with ArrayList.

Well, in this way, it is faster than shuffle() method. shuffle() has the time complexity of O(n) while my code is O(1).

Community
  • 1
  • 1
shuangwhywhy
  • 5,475
  • 2
  • 18
  • 28