Please visit our sponsor
UNKNOWN //************************************** // Name: A better Random Number Generator // Description:This is a better random number generator than comes standard. It's from a very good book on algoritms. You should read it // By: Andy Williams // // // Inputs:None // // Returns:None // //Assumes:None // //Side Effects:None //This code is copyrighted and has limited warranties. //Please see http://www.Planet-Source-Code.com/xq/ASP/txtCodeId.239/lngWId.3/qx/vb/scripts/ShowCode.htm //for details. //************************************** #include <iostream.h> #include <time.h> void init_mm( ); int number_range( int from, int to ); int number_mm( void ); static int rgiState[2+55]; // leave this alone void main() { init_mm(); //seed the number generator int random = number_range( 10, 100 ); cout &lt;&lt; random &lt;&lt; endl; } int number_mm( void ) { int *piState; int iState1; int iState2; int iRand; piState = &rgiState;[2]; iState1 = piState[-2]; iState2 = piState[-1]; iRand = ( piState[iState1] + piState[iState2] ) & ( ( 1 &lt;&lt; 30 ) - 1 ); piState[iState1] = iRand; if ( ++iState1 == 55 ) iState1 = 0; if ( ++iState2 == 55 ) iState2 = 0; piState[-2] = iState1; piState[-1] = iState2; return iRand &gt;&gt; 6; } /* * Generate a random number. */ int number_range( int from, int to ) { int power; int number; if ( ( to = to - from + 1 ) &lt;= 1 ) return from; for ( power = 2; power &lt; to; power &lt;&lt;= 1 ) ; while ( ( number = number_mm( ) & ( power - 1 ) ) &gt;= to ) ; return from + number; } /* * This is the Mitchell-Moore algorithm from Knuth Volume II. */ void init_mm( ) { int *piState; int iState; piState = &rgiState;[2]; piState[-2] = 55 - 55; piState[-1] = 55 - 24; piState[0] = ( (int) time( NULL ) ) & ( ( 1 &lt;&lt; 30 ) - 1 ); piState[1] = 1; for ( iState = 2; iState &lt; 55; iState++ ) { piState[iState] = ( piState[iState-1] + piState[iState-2] ) & ( ( 1 &lt;&lt; 30 ) - 1 ); } return; }