One functionality of the program I am writing requires me to generate random numbers. However about 50% of these numbers won't be valid(which numbers are valid will be dependent on previous parts of my code) so my initial idea was to generate random numbers inside a while-loop until proper number is generated.
However, I am thinking if it is a good practice. Theoretically I should get the proper number within just a few repetitions(there is only 0,5^10 = 0,1% chance that the program will fail to do that within 10 repetitions) however it is still binding my program's performance to random number. So is it a bad practice despite probabilities being mostly insignificant?
There are work-around's that problem that doesn't require me to use loops but they would make that part of my code much more confusing. Someone could call them "over-engineering". Instead of having 4 lines of code to generate and check random number I would need 30-40 lines and declaring some new variables(probably arrays) to keep track of valid and invalid values. It seems easier to just generate a number and check if it's valid.
Aucun commentaire:
Enregistrer un commentaire