Function to generate random within specific range

SGDK only sub forum

Moderator: Stef

Post Reply
matteus
Very interested
Posts: 336
Joined: Mon Feb 04, 2008 1:41 pm

Function to generate random within specific range

Post by matteus »

Code: Select all

u16 randomNumberGenerator(u16 finishInt) {
    u16 x = 0;
    do {
        x = random();
    } while (x <= 0 || x > finishInt);
        return x - 1;
}
Is this the best way to be doing it?

u16 randomNumberGenerator(10) would give me random 1 to 10
cero
Very interested
Posts: 340
Joined: Mon Nov 30, 2015 1:55 pm

Re: Function to generate random within specific range

Post by cero »

No, that's really wasteful, and can run infinite time. Hint: modulo operator.
matteus
Very interested
Posts: 336
Joined: Mon Feb 04, 2008 1:41 pm

Re: Function to generate random within specific range

Post by matteus »

Code: Select all

x = (random()%finishInt-1)+1;

Is this right?
matteus
Very interested
Posts: 336
Joined: Mon Feb 04, 2008 1:41 pm

Re: Function to generate random within specific range

Post by matteus »

P.S you've just helped me no end! I'm really grateful :)
cero
Very interested
Posts: 340
Joined: Mon Nov 30, 2015 1:55 pm

Re: Function to generate random within specific range

Post by cero »

I would add a couple parenthesis (), otherwise the calculation order may not be what you expect.
Post Reply