How do you tell a script you want to pick a random number but not the same as the last random number it picked?
![Photo](https://www.purezc.net/forums/uploads/profile/photo-thumb-134.png?_r=1704541549)
Random but not the same?
#1
Posted 27 April 2023 - 02:34 PM
#2
Posted 27 April 2023 - 04:32 PM
Store the last picked number in a variable and redo the random roll until it's not equal to the variable.
- Aslion likes this
#3
Posted 27 April 2023 - 08:02 PM
^
Just to visualize it for people:
int rand_num; int last_rand; while (rand_num == last_rand) { rand_num = Rand(x); } last_rand = rand_num;
- Colin likes this
#4
Posted 27 April 2023 - 09:18 PM
If you want it to give you a different random number in exactly one roll every time...
/* Generate some random number in some range of values, but never generate the same number twice in a row. If my range of random values is [0, N), first generate any arbitrary number from that range. The total number of possible values I should be able to generate for the next roll is N-1 since I want to exclude the previous result So when generating the next number, simply generate a value in the range [1, N). We'll ADD this value to the previous result to ensure we got a different value. If this new sum exceeds or equals N, subtract N to basically overflow the sum to some number strictly less than the previous result. For example, if my range is [0, 100) and I generated 42 last time, I'll generate some number in [1, 100): If the number is 1, my new result is 43 If the number is 57, my new result is 99 If the number is 58, the sum is 100, but the new result should wrap around back to 0 If the number if 99, the sum is 141, but the new result should wrap around back to 41 */ // initially... int limit = 100; // you should disallow limits of < 2 int last_value = Rand(limit); // generate a random number in [0, 100) // do this when generating a new value last_value = (last_value + Rand(limit - 1) + 1) % limit;
Because who knows? Maybe you will be lucky/unlucky enough to roll the same number every single time and have the game hang indefinitely, and we can't have that!
(My answer doesn't meaningfully improve anything, do what everyone else said, it's simpler )
EDIT: I also don't know ZScript so take my syntax with a massive heap of salt.
Edited by Colin, 28 April 2023 - 04:31 AM.
0 user(s) are reading this topic
0 members, 0 guests, 0 anonymous users