Search code examples
assemblyrandomx86-16tasmdosbox

How do i generate 2 random numbers, once within the range of 50 and 259, and once within 50 and 159?


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.


Solution

  • 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.