Reputation: 438
public static GetRandomFunc() {
switch((int)(Math.random()*NUM_FUNCTIONS) {
case 0:
functionA();
break;
case 1:
functionB();
break;
case 2:
functionC();
break;
// ...
}
}
I want to call GetRandomFunc() in main randomly until each function has been called once and then it ends. How do I make sure a function would be called once only, and if all has been called, it prints out System.out.println("All done")
Upvotes: 3
Views: 124
Reputation: 1184
create a list containing 0,1 and 2. shuffle it and iterate over it to call each function once but in random order.
List<Integer> integers = Arrays.asList(0,1,2);
Collections.shuffle(integers)
for (Integer i: integers){
GetRandomFunc(i)
}
and your function will be
public static GetRandomFunc(int index) {
switch(index) {
case 0:
functionA();
break;
case 1:
functionB();
break;
case 2:
functionC();
break;
// ...
}
}
Upvotes: 5
Reputation: 2926
Make a list of the functions and take from it at random. When it's empty, you can be sure you used every function exactly once.
public interface Function { void execute(); }
public static runFunctionsRandomly(List<Function> functions) {
while (!functions.isEmpty()) {
int index = Math.random() * functions.size();
Function f = functions.get(index);
f.execute();
functions.remove(index);
}
}
class ExampleFunction implements Function {
void execute() {
System.out.println("Hello world!");
}
}
...
Upvotes: 3
Reputation: 691775
Use a list of Runnable
s (or of Integers mapping to each function, as you did in your code), shuffle it, then iterate through the list and call each function.
http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#shuffle%28java.util.List%29
Upvotes: 3