Problem Statement: Execute Various Command randomly by matching its percentage.
like execute CommandA 50% of time and commandB 25% of the time and commandC 15% of time and etc etc and total percentage should be 100%.
My Question is- Execute CommandA A% of time, CommandB B%
of time, CommandC C% of time —– CommandZ Z% of time.
And total percentage should be 100% and at the end I can see
how much times each command is being executed and what is
the percentage of each command(means how many times each command is
being executed in terms of percentage) after total execution is complete.
Idea:-
Generate a random number between 1 and 100 and see if any of the percentage fall in the category
List<Double> comamndDistribution = new ArrayList<Double>();
/* Commands to execute. Here I have Z command
* and total percentage should be 100% (A+B+C+D+...+Z=100%)
*/
comamndDistribution.add(A%); // command A
comamndDistribution.add(B%); // command B
comamndDistribution.add(C%); // command C
comamndDistribution.add(D%); // command D
comamndDistribution.add(E%); // command E
-----------
-----------
comamndDistribution.add(Z%); // command Z
private Command getNextCommandToExecute() {
for (int i=0; i < 10000; i++) {
// generating a random number between 1 and 100
int random = r.nextInt(100-1) + 1;
/* My Question is- Execute CommandA A% of time, CommandB B%
of time, CommandC C% of time ----- Command Z Z% of time.
And total percentage should be 100% and at the end I can see
how much times each command is being executed and what is
the percentage of each command(means how many times each command is
being executed in terms of percentage) after total execution is complete.
*/
}
}
/* Get the next command to execute by maintaining the Percentage of
each command randomly*/
Command nextCommand = getNextCommandToExecute();
Let me make it more clear- My Question is- Execute CommandA A% of time, CommandB B% of time, CommandC C% of time —– Command N N% of time by using Random Number. And total percentage should be 100%.
P.S: I think this question has been asked few times, but it is not the way I wanted it. So I thought to put it again as a question by posting my code what I did so far.
Update:- I have updated the question by removing the previous code that I wrote with another logic so that people can understand it more.
I did it a similar way to Adam Liss, but it’s turned out more verbose.
Again, I thought you can’t rely on the provided commands always adding up to 100%, so I’ve coped with that, but my way requires a method call to renormalise proportions (so a little more error prone).
The output looks like this:
And generally distributes like this (different counts each run, of course).