/ Published in: C
Functions for generating random numbers, flipping coins, rolling dice, etc.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <assert.h> //define NDEBUG if you want to remove asserts //the following function //returns a random non-negative integer less than h //h must obviously be less than or equal to the highest number //possible from the random number generator int rnd(int h){ if(!h)return 0;//making sure we don't divide by zero! } //rolls a virtual die //(die is the singular of dice) //returns a number 1-6 int rolldie(){ return rnd(6)+1; } //flips a virtual coin //returns 1 or 0 for heads or tails int flipcoin(){ } //returns a floating point number in range 0 to 1 double frand(){ } //returns random floating point number in range 0 to f double frnd(float f){ return frand()*f; } //returns 1 (true) at probability p //example: //prob(0.7) will be true 70% of the time int prob(float p){ if(frand()<p)return 1; return 0; } //returns distance between two points in 2 dimensions double dist2d(float x1,float y1,float x2,float y2){ float dx=x1-x2; float dy=y1-y2; } //returns distance between two points in 3 dimensions double dist3d(float x1,float y1,float z1,float x2,float y2,float z2){ float dx=x1-x2; float dy=y1-y2; float dz=z1-z2; } //Like % (modulus) but works "correctly" for negative values signed int zmod(signed int a,unsigned int b){ signed int c=0; if(!b)return c;//making sure we don't divide by zero if(a<0)--a; c=a%b; return c; } //returns volume of sphere having radius r //the parentheses may help compiler optimize double spherevolume(float r){ return (M_PI*4/3)*(r*r*r); } //returns surface area of sphere having radius r double spheresurface(float r){ return (M_PI*4)*(r*r); }