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 » Thu Sep 15, 2016 8:47 am

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: 338
Joined: Mon Nov 30, 2015 1:55 pm

Re: Function to generate random within specific range

Post by cero » Thu Sep 15, 2016 8:49 am

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 » Thu Sep 15, 2016 9:25 am

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 » Thu Sep 15, 2016 9:37 am

P.S you've just helped me no end! I'm really grateful :)

cero
Very interested
Posts: 338
Joined: Mon Nov 30, 2015 1:55 pm

Re: Function to generate random within specific range

Post by cero » Thu Sep 15, 2016 9:48 am

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

Post Reply