In my project, i have a list that is “randomly” generated. It generates its elements (ints) at a random range and adds a random amount of those ints to the list. However, i’d like those elements to be generated not as randomly as they currently are: i want to have some particular “settings” for the generation (such as setting a threshold of allowed duplicates, to exclude some ints, etc).
Currently my code does it by using if statements. For example: if i want to avoid having a list of ints that amounts to 100, an if statement checks for whether the sum of all ints in the lists amounts to 100 (using a simple sum method) and if so does something that i want it to.
I was wondering if there are some other ways to do that, other than running a bunch of if statement checks.
One approach would be to generate a list of valid ints which fullfill your requirements in advance. Then you can simply shuffle that list.
Be aware that by using random generation you might run into unexpected results (all of which you will have to test).
For example: if your rules state that only 0 and 1 are allowed then a series of 1000 ints with 999 ones and a single zero is valid. Thus my suggestion of shuffling instead of trying to trim down the random result afterwards. You’ll have full control over how the result will look like while retaining a feeling of randomness.
Thank you for your answer, @_geo1 ! The approach that you suggested didn’t cross my mind. It makes sense, as potentially the performance hit that a “on-the-go” generation (and in my current code check) would cause would become far less noticable and the entire operation would be easier to control.
I’m fully aware of that as my current code already has what you might call “unexpected results”. There are some aspects of it that i need some more advice (not a readily made solution) on, but it’s very different from what i’m asking about in this thread, so i think i’ll just make another one for that issue in particular.
I understand the logic behind your suggestion and your advice is very helpful. Thank you again!