Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Random [-x..x] && !NULL

Name: Anonymous 2012-01-19 12:22

Fellow Progs,
any idea to nicely implement this ?

First idea...ugly

get random value
if value is zero
  get random value
done

Second idea

get random positive value
make coin toss
if coin shows head
  value *= -1

But there must be something easiert / nicer

thanks alot.

Name: Anonymous 2012-01-19 13:24

>>4
Your first variant may not be constant time.

/* returns a random range between x and y, both inclusive, that's not 0 */
int randrange_nonzero(int x, int y)
{
        int n = rand() % (y - x) + x;
        return n + (n>=0);
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List