Random numbers from x to y (except z)
micma
Member Posts: 66
Hey GS Community,
I need help with some random number generation. I'm trying to choose a random number from random(x,y) but I don't want it to choose z (in the range of x,y). Any way I can do this? Probably some mathematical function that I am not aware of.
Thanks,
Micma
Comments
Three ways you can do this, depending on how random you want it to be.
Make a table containing all the numbers you want it to pick from. So if you wanted a number from the list of 1, 2, 3, 5, 6, you'd make a table with each number in its own row. Then you can do random(1,tableRowCount(game.Table)) and look at what's in the corresponding table row. This method is particularly good if you want the numbers picked to not repeat, as you can delete the table row that's picked and it won't come up again.
Do two randoms - random(1,3) and random(5,6). Then do a random(1,2) to pick which of them is the number chosen.
Put your random number chooser in a loop. Have the loop condition be "while self.Random is 0 or 4, change attribute self.Random to random(1,5)". This way, however, can potentially lead to an infinite loop if the computer happens to pick 4 every time.
The first way is the best way, but I've had reason to use the second before.
Contact me for custom work - Expert GS developer with 15 years of GS experience - Skype: armelline.support
The only problem with number 2 is that I am only choosing between 3 numbers. I could just have a self.number to be either 1 or 2 and if it is 1 it is the one number or if it is 2 it is the other. Thanks for your help!
You can express a range of numbers, excluding a particular number, with a single line of fairly simply code, I've not got access to GameSalad right now but pretty sure it would be as simple as something like this . . .
mod(X+rand(0,2),3)+1
(where X is the number you don't want).
Yep, something like that.
@micma - I've even got a demo posted in the Spare Code thread that excludes the previously chosen row in a table the next time to game randomly chooses a row... You may be able to alter that to fit your needs.
My GameSalad Academy Courses! ◦ Check out my quality templates! ◦ Add me on Skype: braydon_sfx