Misunderstanding how randi() works and should be used

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By ceige

I am attempting to create a sort of random item generator. I have a database that stores the base stats for an item. When the item is created in the world, a function randomizes the item’s stats. Here is an example of my code:

toughness = randi() % (toughness + 3) + (toughness - 3)

Before this point in the code, toughness can be one of 4 values: 1, 2, 3, and 5. Now this is my understanding of how this should work, given toughness == 1 before this line of code, I would think that a random integer between -2 and 4 would be chosen. Sometimes, it chooses 0.

For the purposes of my code this is okay, toughness can be 0. However, it will throw an error saying “Division by Zero in operator ‘%’” and it points to this line of code. So I’m assuming this is not good code, but I’m not entirely sure why.

What exactly is randi() doing here? From my point of view, I don’t see any division so I’m clearly misunderstanding how this works. Is there a better way for me to implement this? Perhaps a way that doesn’t allow it to choose zero? Or is there something else I could use so that zero would be an allowable solution?

Thanks in advance for your time and consideration.

:bust_in_silhouette: Reply From: kidscancode

randi() is not your problem. This just produces a random integer.

I don’t see any division

The % operator gives the remainder after division. When toughness is -3, you’re asking “what’s the remainder when I divide by 0”?

Using your formula, when toughness is 1, you’re doing randi() % 4, which results in either 0, 1, 2, or 3. You then add -2, resulting in -2, -1, 0, or 1.

Now you have your problem. If toughness is -1, then randi() % 2 is either 0 or 1. Adding -4 gives either -4 or -3. Boom, division by 0.

Okay I think I see where I went wrong now. Thank you very much for your help!

ceige | 2020-04-18 23:25