Sunday, April 17, 2011

Little Bit of Randomness


// it would be wise to seed in a different function
// srand(time(0));

int rand(int min, int max) {
  return (rand() % (max-min+1))+min;


public int rand(int min, int max) {
  return new java.util.Random().nextInt(max-min+1)+min;


function rand(min, max) {
  return Math.floor(Math.random() * (max-min+1))+min;

In order to add a random decimal, you would need to divide the generated number by a certain succession of 10s and add it to the desired variable. Keep in mind these functions run off the pseudo-random algorithm on the running computer, so the results may vary. This is simply a simpler, faster, and efficient alternative than an external library.

No comments:

Post a Comment