I'm working on an assembly 8086 project for class and needed a way to generate 2 random numbers, once within 50 and 259 and once within 50 and 159.
How do i generate 2 random numbers, once within the range of 50 and 259, and once within 50 and 159?
-
https://stackoverflow.com/a/47613489/3857942 is an answer in the section _Related Question? Possible Issues_. Simple LCG PRNG with a function srandsystime that seeds a Linear Congruent Generator (LCG) based Pseudo Random Number Generator (PRNG). There is a function rand that gets the next random number from the LCG in range of 0 and 65535. `rand2num1to10` is an example of converting a value returned by rand and making it a num from 1 to 10. – Michael Petch May 23 '19 at 14:38
-
1The general equation to generate a random value within a range `lower` to `upper` (inclusive) is `rndvalue = (rand() % (upper-lower+1)) + lower;` . Note: There is a deficiency in using this in that there is [modulo bias](https://stackoverflow.com/questions/10984974/why-do-people-say-there-is-modulo-bias-when-using-a-random-number-generator). – Michael Petch May 23 '19 at 15:06
1 Answers
For a project for a class; I'd assume you don't need anything good (e.g. don't need something intended for security/cryptography, don't care about bias, etc).
With this in mind; I'd just get the current date ("int 0x1A, ah = 0x04") and the current ticks since midnight ("int 0x1A, ah = 0x00") from the BIOS; and merge them together (with XOR) to get a seed for a pseudo-random number generator.
Once you have a seed, just do some mathematical acrobatics - e.g. multiply "seed+1" by a large prime number, then divide it by a slightly smaller prime number (to get a result and a remainder); then XOR the result, remainder and original together to get a new seed and return the lowest 16 bits as the next random number.
If you do need it to be good (rather than just working) you need to describe the requirements.
Anyway; once you have code to get a "random" 16-bit integer you can shift it right or mask it to get a "random" value from 0 to 255, then add 50 to it to get a value from 50 to 305, then retry if it's greater than 259 so that you end up with a value from 50 to 259. In the same way you can shift or mask to get a value from 0 to 127, add 50, then retry if it's larger than 159; to get a value that's from 50 to 159.

- 35,656
- 2
- 39
- 66