Home Technical Talk

generate random number ranged (1,n) with some numbers excluded

polycounter lvl 14
Offline / Send Message
Belias polycounter lvl 14
Hello, i have a little question, how to generate a random number from 1 to 30 with (4,5,9,10,17,19,2) excluded ?

solution 1 : generate some kind of dataset of the numbers you want included and then get then use Random.Range(0, data.Count - 1) as the index of that dataset

solution 2 : or brute-force it and just keep generating random numbers between 1 and 30 until you get a number that isn't excluded

any better solution ?

Replies

  • ElleKitty
    Options
    Offline / Send Message
    ElleKitty polycounter lvl 3
    Depends on how big your array will be. If you go with the solution 1, you will have to enter numbers into the dataset manually. If you do the solution 2, then this operation will be variably expensive; it will sometimes land perfectly, and it will cycle for long times otherwise.

    It seems that you're working with Unity here, I was always the Gamemaker person. It had a 'choose' function where it would pick one of supplied numbers, neat as they could have been both hardcoded or variables. I dont know Unity very well, but I would personally look for something like this the first. But yes, this would be closer to the solution 1 in essence.

    Sorry not to be of more help. Maybe someone else will know more.
  • Parkar
    Options
    Offline / Send Message
    Parkar polycounter lvl 18
    Since you have just 23 numbers I would just use solution 1.

    Another similar solution that's more suitable if you have a huge range (Say thousands or millions) but still a short number of excluded numbers is to trade execution speed vs memory use and instead of keeping a table of the included values keep a table of the excluded numbers instead (make sure they are in order).

    Then pick a random number within full range - number of excluded values. Then you loop over the excluded numbers in a loop. For each number in the excluded table you compare it to your randomly generated value starting at the lowest excluded value. If it is lower you have found your random number. If it is equal or higher you add 1 to your random number and continue to the next excluded number.

    Your second solution is not something I would recommend. As ElleKitty writes you will get a random execution time. In fact unless the random generator is guaranteed to generate all numbers in the range within a reasonable amount of queries you could theoretically never finish.

    Also something to consider is if the excluded or included numbers are geneated in a systematic fashion you may be able to calculate the random number instead.
Sign In or Register to comment.