programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Way to execute something based off a percentage

Greenhorn
Posts: 16
1
Hi all,

I have some code that I want to execute a certain percent of the time in a for loop. These percents are defined as variables. Here is the pseudo-code

The way I currently have it implemented is something like this:

And this does work, however setting the percents isn't as simple as saying "Do this 20%, then this 30%". This is also simplified, I have about 15 functions I want to do, and changing 1 guy's percent means I have to change them all.

Does anyone know of a way I can define as the percents a simple "20%" instead of having each percent be a chunk of the 100?>

Marshal
Posts: 56605
172
If your random number is 0.1, you will execute all three methods. You need to add else after your if.
If your percent2 is 20, then you actually want the cumulative percentage. So make percent 2 equals to 20 + percent 1.

That might help.

Matt Herrington
Greenhorn
Posts: 16
1
Thanks, I meant "else if". That is a typo.

I was thinking something along those lines too... each percent is the sum of it and the previous one. Is there a clean way to code that? What I was thinking...

Bartender
Posts: 2700
Also if function2 takes 2 times more time then function1 then this algorithm will fail.

Campbell Ritchie
Marshal
Posts: 56605
172
You will also have problems if you try integer arithmetic; those percentages will all come out to 0.

I don't think you need the third if.

Bartender
Posts: 4181
22
One solution would be to add your functions as Runnables in an Array or List in a certain number of times (relative to the percentage). Then shuffle the List or Array. When it is time to run a function randomly access the Array or List and run it. Something like this:

This doesn't protect the user from certain things you need to take into account (... assumes 100 total 'percent': What if user defines func1 = 20, func2 = 30, func3 = 40? The functions will still be relatively distributed but not as a percentage...)

lowercase baba
Bartender
Posts: 12565
49
Wouter Oet wrote:Also if function2 takes 2 times more time then function1 then this algorithm will fail.
That depends on if you are looking for clock time or total number of executions.