Forcing a randomly generated number to always be odd
Forum rules
Before asking on how to use a ZDoom feature, read the ZDoom wiki first. This forum is archived - please use this set of forums to ask new questions.
Before asking on how to use a ZDoom feature, read the ZDoom wiki first. This forum is archived - please use this set of forums to ask new questions.
Forcing a randomly generated number to always be odd
I want to generate a random number and have its result always guaranteed to be an odd number. How do I do this?
- InsanityBringer
- Posts: 3392
- Joined: Thu Jul 05, 2007 4:53 pm
- Location: opening the forbidden box
Re: Forcing a randomly generated number to always be odd
A cheap and silly way would probably work like this:
Code: Select all
if (randVal % 2 == 0) //check if it's even
{
randVal++; //make it not even if that is the case
}
Re: Forcing a randomly generated number to always be odd
I was going to suggest checking if it was divisible by 2 and if is re-roll but IB's suggestion of simply increasing any even number by 1 is much neater because it avoids the re-roll (which, although unlikely, could lead to a long loop of randomly generated even numbers being rejected).
Re: Forcing a randomly generated number to always be odd
Okay thanks... and what if I want the result to be guaranteed even? Sorry but I'm dumb.
Re: Forcing a randomly generated number to always be odd
2*n - 1, where n is an integer.Nash wrote:I want to generate a random number and have its result always guaranteed to be an odd number. How do I do this?
Re: Forcing a randomly generated number to always be odd
Yeah, that's the basic idea. Take a (integer) number, multiply it by two, you'll be sure to have an even number. Take an even number, add or subtract an odd number (such as 1), and you'll be sure to have an odd number.
For example, if you want an odd number between 1 and 99 included, you can use rand(1, 50)*2-1 or rand(0, 49)*2+1.
For example, if you want an odd number between 1 and 99 included, you can use rand(1, 50)*2-1 or rand(0, 49)*2+1.
Re: Forcing a randomly generated number to always be odd
Or (randval & ~1) for even and ((randval & ~1) + 1) for odd. To get a random odd number between N and M, ((rand(N, M-1) & ~1) + 1). Has the advantage of the number being a little more obvious. (And possibly marginal execution speed increase.)
Re: Forcing a randomly generated number to always be odd
Just use rand(N, M-1) | 1 Odd numbers always have the first bit set, and even numbers always have it cleared.DavidPH wrote:To get a random odd number between N and M, ((rand(N, M-1) & ~1) + 1)