1
Programming / Re: Random number generator in 6502 assembly
« on: September 30, 2020, 01:05:24 pm »
Here's something that I found that doesn't need division. It's pretty much what Bregalad was suggesting.
EDIT: As other people have said, if the period's too short this can cause problems, but there are algorithms you can use that fit pretty nicely on the 6502 and have periods on the order of 232, which is probably long enough that it's fine.
Code: [Select]
random_in_range:
sta scratch
clc
sbc #1
ora #1
ldx #$FF
;determine which mask to use by counting leading zeroes
@count: inx
rol a
bcc @count
;loop until random <= range-1
@try: jsr random
and mask_bytes, x
cmp scratch
bcs @try
rts
mask_bytes: .db $FF, $7F, $3F, $1F, $0F, $07, $03, $01
EDIT: As other people have said, if the period's too short this can cause problems, but there are algorithms you can use that fit pretty nicely on the 6502 and have periods on the order of 232, which is probably long enough that it's fine.