0

所以我希望随机化调用某些方法的方式,以便每个实例只调用一次,并且调用每个方法。

所以说一个实例,它们按顺序调用:

方法2 方法4 方法3 方法1

但在下一个实例中,它们以不同的顺序调用:

方法3 方法2 方法1 方法4

我必须随机化顺序的代码如下所示:

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;
}
4

4 回答 4

2

根据@Aurand 的建议,您可以有一个将调用您的方法的开关和一个List<Integer>包含您要调用的方法的索引的开关,然后使用Collections.shuffle并调用switch您的方法来打乱列表元素。代码示例:

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;
        }
    }
}

尽管如此,问题仍然存在:为什么在现实世界的应用程序中需要这个?

于 2013-03-28T05:08:28.673 回答
1

就像是

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)
于 2013-03-28T05:06:04.323 回答
1

我的建议是在初始化ArrayList期间在所有方法名称中添加一个 & 。

然后使用获取一个随机数random(list.size())并将该元素从ArrayList.

使用一个switch案例,无论弹出什么方法名称,调用该方法。

继续这样做,直到列表变空。

于 2013-03-28T05:06:20.793 回答
0

可能您必须将状态(进行调用的顺序)保留在内部变量或数组中(以防您想拥有所有这些状态)。然后调整您的呼叫站点以使用此状态变量。

于 2013-03-28T05:05:37.183 回答