I have a question. I have a piece of code that generates random numbers and then the motor moves those positions. However, sometimes, the random numbers are almost the same (e.g. 591 and 595). How can I make sure that there is always a distnace of for example 50 between 2 randomly generated numbers?
However, sometimes, the random numbers are almost the same (e.g. 591 and 595)
Random numbers should be random, and that will happen. They can even be equal! If you make a rule about a "distance between them" they will not be random.
Personally, I would avoid repeated calls to random - you can't predict how many times you'll have to call it. I would just call it once and map the value to a range that starts 50 away from the first one.
gutbag:
Personally, I would avoid repeated calls to random - you can't predict how many times you'll have to call it. I would just call it once and map the value to a range that starts 50 away from the first one.
How would you map a value to a number that is at least 50 higher or 50 lower than the first number?
If it's higher but not high enough: add 50. If it's lower but not low enough: subtract 50. Apply limits as needed. Should be random enough for OPs application.
If your range is 1000 and you need the 50 distance above or below, the right way would be to think that the range of the random next number is from 50 to 950. If the new number is greater than the old number, add 50. If less (or equal), subtract 50. If it goes over 1000 or under 0, have it wrap around. Simple forward logic, no risk for endless loop.