jocopa3
jocopa3

Reputation: 796

Call methods in a random unique order?

So I was looking to randomize the way certain methods are called, so that each one is only called once per instance and every single method is called.

So say one instance they are called in the order:

method2 method4 method3 method1

but in the next instance they are called in a different order:

method3 method2 method1 method4

The code that I have to randomize the order looks like this:

public void randomCalls(){
    int[] order = new int[4];

    for(int i=0; i<order.length; i++){
        order[i]=nextNumber(order);
    }
}

public int nextNumber(int[] array){
    Random r = new Random();
    int x = r.nextInt();
    for(int i=0; i<array.length; i++){
        if(arrayHasNumber(array,x)){
            x = nextNumber(array);
        }
    }
    return x;
}

public boolean arrayHasNumber(int[] array, int x){
    for(int i=0;i<array.length;i++){
        if(array[i]==x){
            return true;
        }
    }
    return false;
}

Upvotes: 0

Views: 2988

Answers (4)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Based on @Aurand suggestion, you can have a switch that will call your methods and a List<Integer> that will contain the indexes of the methods you want to invoke, then shuffle the list elements using Collections.shuffle and calling the switch to call your methods. Code sample:

final int METHODS_QUANTITY = 4;
List<Integer> lstIndexes = new ArrayList<Integer>();
for(int i = 1; i <= METHODS_QUANTITY; i++) {
    lstIndexes.add(i);
}
//you can change the condition for the number of times you want to execute it
while(true) {
    Collections.shuffle(lstIndexes);
    for(Integer index : lstIndexes) {
        switch(index) {
            case 1: method1(); break;
            case 2: method2(); break;
            case 3: method3(); break;
            case 4: method4(); break;
        }
    }
}

Still, the question stands: why would you need this on real world application?

Upvotes: 2

Rahul
Rahul

Reputation: 45070

My tip would be to go for an ArrayList & thrown in all the method names during initialization.

Then get a random number using random(list.size()) and pop that element out from the ArrayList.

Use a switch case, and whatever method name has popped out, call that method.

Keep doing this, till the list becomes empty.

Upvotes: 1

user1585395
user1585395

Reputation:

Something like

LinkedList methods
methods.add(1)
methods.add(2)
....

for(i=0; i<methods.size;i++)
r = random.next(methods.size)
switch(methods.get(r)) {
case 1: method1()
case 2: method2()
...
methods.remove(methods.get(r)

Upvotes: 1

TJR
TJR

Reputation: 58

Possibly you must retain the states (orders in which the calls were made) in an internal variable or in an array (in case you want to have all of them). And then tune your call site to use this state variable.

Upvotes: 0

Related Questions