Page 173 - 49A Field Guide to Genetic Programming
P. 173

B.3 Source Code                                               159


        202     ind = new char [ len ] ;
        203
        204     System . arraycopy ( buffer , 0 , ind , 0 , len ) ;
        205     return ( ind ) ;
        206   }
        207
        208   char [ ] [ ]  create random pop ( int n , int depth , double [ ]
                  f i t n e s s ) {
        209     char [ ] [ ] pop = new char [ n ] [ ] ;
        210     int i ;
        211
        212     for ( i = 0; i < n ; i ++ ) {
        213       pop [ i ] = create random indiv ( depth ) ;
        214       f i t n e s s [ i ] = f i t n e s s f u n c t i o n ( pop [ i ] ) ;
        215       }
        216     return ( pop ) ;
        217   }
        218
        219
        220   void s t a t s ( double [ ]  f i t n e s s , char [ ] [ ] pop , int gen ) {
        221     int i , best = rd . nextInt (POPSIZE) ;
        222     int node count = 0 ;
        223     fbestpop = f i t n e s s [ best ] ;
        224     favgpop = 0 . 0 ;
        225
        226     for ( i = 0; i < POPSIZE ; i ++ ) {
        227       node count +=  t r a v e r s e ( pop [ i ] , 0 ) ;
        228       favgpop += f i t n e s s [ i ] ;
        229       i f ( f i t n e s s [ i ] > fbestpop ) {
        230       best = i ;
        231       fbestpop = f i t n e s s [ i ] ;
        232       }
        233     }
        234     avg len = ( double ) node count / POPSIZE ;
        235     favgpop /= POPSIZE ;
        236     System . out . print ( ” Generation=”+gen+” Avg Fitness=”+(−favgpop
                    )+
        237                  ” Best Fitness=”+(−fbestpop )+” Avg Size=”+
                                 avg len+
        238                  ”\nBest In d i v i d u a l : ” ) ;
        239     p r i n t i n d i v ( pop [ best ] , 0 ) ;
        240     System . out . print ( ”\n” ) ;
        241     System . out . f l u s h ( ) ;
        242   }
        243
        244   int tournament ( double [ ]  f i t n e s s , int t s i z e ) {
        245     int best = rd . nextInt (POPSIZE) , i , competitor ;
        246     double  f b e s t = −1.0 e34 ;
        247
        248     for ( i = 0; i < t s i z e ; i ++ ) {
        249       competitor = rd . nextInt (POPSIZE) ;
        250       i f ( f i t n e s s [ competitor ] > f b e s t ) {
        251         f b e s t = f i t n e s s [ competitor ] ;
        252         best = competitor ;
        253       }
   168   169   170   171   172   173   174   175   176   177   178