
//Program A48 ForLoop7
//Variation of the for statement
//with fractional increments.

package ejvol1;


public class ForLoop7
{		
    public static void main(String[] args)
    {
        String tab = "\t";
        //The index is declared as "double",
        //so it accepts a decimal  expression
        //in its increment.
        for(double i = 1; i<=2.01 ; i= i + 0.01 )
        {		
            System.out.println(i + tab + 2*i);
        }	
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



// Program 335 Drift3

// In this program we study drift
// in 1000 asexual  populations with constant size,
// one locus or enzyme, two alleles and no mutation.

package ejvol1;



import java.util.Random;

public class Drift3
{
		
    //Turn on  the random generator	
    static Random r  = new Random();


    // number of populations
    static int nPopulations = 1000;
    // population size, the same for all populations.
    static int size;
    static double po;
    // initial frequency of allele one,
    // the same for all populations.

    // actual frequency of allele one
    static int nOne[];
    // actual proportion of allele one
    static double p[];
    // number of generations
    static int nGen;
    // counts the number of allele1
    static double counterAllele1;
    // counts the number of times that allele1
    // was fixed.
    static double counterFixations;
    static double probFixation;
    // Record of the type of individuals
    // initial population:
    // allele1=true;
    // allele2=false;
    // The first entry is the pop subindex,
    // the second entry is the individual subindex
    static boolean population1[][],population2[][];
    // The distribution of p in the population
    static int distribp[];
    // We do not report every generation
    // but only when the generation is multiple of genSpace.
    static int genSpace ;
	
    public static void constructors()
    {
        p = new double[1000];
        nOne = new int[1000];
        distribp = new int[1000];
        population1 =new boolean[1000][1000];
        population2 =new boolean[1000][1000];	
    }
	

    public static void report( )
    {
        int distribution[] = new int[11];		
        for(int i= 0; i <= 10; i++)
        {
            distribution[i]=0;
            for(int j=0; j<10; j++)
                distribution[i]=  distribution[i]+  distribp[10*i +j]; 		
            System.out.print(distribution[i] + "\t" );			
        }
        System.out.println();
    }
	
    public static void initialization()
    {
        size = 100;
        po = 0.3;
        nGen = 500 ;
        genSpace = 5;
        counterAllele1 = 0;
        counterFixations=0;

        //All populations are initialized
        int n;
        n = (int) Math.ceil( po*size);
        for(int pop=0; pop<nPopulations; pop++)	
        {		
            //initial population:
            //allele1=true;
            //allele2=false;


            for(int ind=1; ind<=n ; ind++)
                    population1[pop][ind]=true;

            for(int ind=n+1; ind<=size ; ind++)
                    population1[pop][ind]=false;
        }

        for(int j=0; j < size; j++)	
                distribp[j]=0;	
        distribp[n]=nPopulations;
        report( );
    }
	
	
    public static void iteration(int pop)
    {	
        //Sampling procedure
        for(int j=0; j<size; j++)	
        {
            int  m = r.nextInt(size)+1 ;
            population2[pop][j]= population1[pop][m];

            if (population2[pop][j]==true)
                counterAllele1 = counterAllele1 +1;
        }
       p[pop]=counterAllele1/size;
       nOne[pop]= (int) counterAllele1;

       // System.out.println( nOne[pop] + p[pop]);

       /* String s4 = String.valueOf(p[pop]);
       String  s5=s4.replace(".", ",");
        System.out.println( s5);	 */

       //updating
       counterAllele1=0;
       for(int ind=0; ind<size; ind++)			
                population1[pop][ind]=  population2[pop][ind];	    	
    }

    public static void reInitialization( )
    {
        for(int i=0; i<size; i++)		
            distribp[i] = 0;
        for(int pop=0; pop<nPopulations; pop++)	
        {
            nOne[pop] = 0;
            p[pop]=0;
        }	
    }
	
    public static void thousandPopulations(int gen)
    {
        for(int pop=0; pop<nPopulations; pop++)	
        {	
            iteration(pop);
            /* System.out.println(pop +"\t"+
                  nOne[pop] + "\t"+ p[pop]); */

            distribp[nOne[pop]] = distribp[nOne[pop]]+1;		  			
        }	
        //System.out.println(gen);
        if (gen % genSpace  == 0 )  report( );
        reInitialization();
    }
	
    public static void main(String[] args) 	
    {
        constructors();
        initialization();
        for(int gen = 0; gen < nGen; gen++)
            thousandPopulations(gen);
    }
}//Program 335 Drift3




:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A357 Couple
//Keeps information in reference to
//the bodies of  a wife-husband couple
package ejvol1;


public class Couple 
{
    Body wife;
    Body husband;
    

    
    Couple(Body b1, Body b2)
    {
        wife = b1;
        husband = b2;
    }
    
    
    public static void main(String[] args)
    {
        Body bodyMary = new Body(1,2,3,4);
        Body bodyAlf= new Body(-1,-2,-3,-4);
        Couple c = new Couple(bodyMary, bodyAlf);
        
        Body.report("Mary", c.wife);
        Body.report("Alf", c.husband);
    }
}//End of Program A357 Couple



:::::::::::::  NEW PROGRAM  :::::::::::::


//Program A16 SumOfIntegers2
//This program introduces integers
//and their addition.

package ejvol1;

public class SumOfIntegers2
{		
    public static void main(String[] args)
    {
        //Declaration and initialization
        //of variables as integers.
        int x = 2;
        int y = 3;
        //Computation
        int result  = x+y; //result is declared as integer
        // Report
        System.out.print(" The sum of x =" + x + " and ");
        System.out.println( " y = " + y + " is " + result );	
    }	
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A58 GermanToEnglish
//Translator model.
package ejvol1;


public class GermanToEnglish 
{
    public static void main(String[] args)
    {
        //Targets
        String s1 = "Er hast ein Auto.";
        String s2 = "Er ist gut Fahrer.";
        String s3 = "Ich bin schlecht Fahrer.";
        String s4 = "Ich müsse fahren.";
        //Output
        String t = s1 + " " + s2 + " " + s3 + " " + s4; 
        System.out.println("German : " + t);
        t = t.replace("Auto", "car");
        t = t.replace("bin", "am");
        t = t.replace("Er", "He");
        t = t.replace("ein", "a");
        t = t.replace("Fahrer", "driver");
        t = t.replace("fahren", "drive");
        t = t.replace("gut", "good");
        t = t.replace("hast", "has");
        t = t.replace("Ich", "I");
        t = t.replace("ist", "is");
        t = t.replace("müsse", "must");
        t = t.replace("schlecht", "bad");
        t = t.replace("teuer", "expensive");
        System.out.println("English : " + t);
    }
   
}




:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A62 CopyPaste
// This program copies a substring
// from sOrigin and pastes it into sTarget.

package ejvol1;


public class CopyPaste
{
    
    public static void main(String[] args)
    {
        String sOrigin, sTarget, sMiddle, sInitial, sFinal;
        sOrigin = "abcdefghij";
        sTarget = "1234567890";
        System.out.println("Origin = " + sOrigin);
        System.out.println("Target = " + sTarget);
        // Let us copy into sMiddle
        // 4 characters of sOrigin
        // beginning with the second char:
        // initial point included: 2,
        // terminal point excluded: 6.
        sMiddle = sOrigin.substring(2, 6);
        System.out.println("sMiddle = " + sMiddle);        

        //We copy into sInitial the first 3 chars  of sTarget
        sInitial = sTarget.substring(0,3);
        System.out.println("sInitial = " + sInitial);
        //We copy into sFinal the last part of sTarget
        //beginning with the third char
        sFinal = sTarget.substring(3);
        System.out.println("sFinal = " + sFinal);
        // We concatenate sInitial,sMiddle and sFinal.
        String  sOutput = sInitial+sMiddle + sFinal;
        System.out.println("output = " + sOutput);
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



// Program 82 Arrays2
// Array to calculate and print cubes.	
package ejvol1;


public class Arrays2
{
   public static void main( String args[] )
   {
    // Declaration of an array with integer entries
    int data[];  // data is the name.

    // Assignation of the capacity of the array:
    // ten entries, beginning from zero.
    // data[i] can be defined for i from zero to 9
    // data[10] is not defined
      data = new int[ 10 ];

    // Assignation of each entry
    for(int i = 0; i<=9; i=i+1)
    {
        data[i] = i*i*i;
    }

    // The array is written to the console.
    for(int i = 0; i < 10; i++)
        System.out.println(  i + "	" + data[i] );
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * Program A18 StructuringProgramming
 * Some code is encapsulated into a function
 * or method.
 */
package ejvol1;


public class StructuredProgramming
{	

    //The next is  a method.
    //It encodes for a function with input 
    //two integers and output their sum.
    //The output is also integer and must be declared
    //explicitly before the name of the method.
    
    //The output of the method appears after
    //the reserved word "return".
    //The declaration of a method or a class
    //does not terminate with semicolon ";"
    public static int sum(int x, int y)  	 	
    {
        return  x+y;
    }
	
    
    //This is the main method.
    //This is the head of the class.
    public static void main(String[] args)
    {
        //Declaration and initialization
        //of variables
        int x = 2;
        int y = 3;
        //Invocation of a method
        int z = sum(x,y);
        // Report to the console
        System.out.print(" The sum of x =" + x + " and ");
        System.out.println( " y = " + y + " is " + z);
    }			
}//End of program A18 StructuringProgramming



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A280 Dialog
//Swing interface to capture data from the user.

package ejvol1;



import javax.swing.JOptionPane;
//Swing based code.

public class Dialog
{

public static void main(String[] args)
{
    // first string entered by user
    String string1;
    // second string entered by user
    String string2;

    // first parameter
    double parameter1;
    // second parameter
    double parameter2;

    // We open a dialog box;
    // We obtain   parameters from user;
    // parameters are read as   Strings.

    string1 = JOptionPane.showInputDialog(
       "Enter first decimal number. Use a Point." );

    // We obtain second parameter from user
    string2 = JOptionPane.showInputDialog(
       "Enter second decimal number. Use a Point." );

    // We convert   String to   double
    parameter1  = Double.parseDouble( string1 );
    parameter2  = Double.parseDouble( string2 );

    System.out.println("parameter1 = " + parameter1);
    System.out.println("parameter1 = " + parameter2);
}

}//End of Program A280 Dialog



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A49 ForLoop8
//The for statement
//with fractional increments

package ejvol1;


public class ForLoop8
{		
    public static void main(String[] args)
    {
        String tab = "\t";
        // The index is declared as "double".
        for(double i = 1; i<=2.05  ; i= i + 0.05 )
        {		
            System.out.println(i + tab + i*i );
        }	
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program 75 Replace5
//Replacement as a method.

package ejvol1;


public class Replace5
{
    // This method replaces string a by b
    // inside c.
    public static String
               replacement(String a, String b, String c)	
    {
        return c.replace(a,b);
    }

    // This is the head of the program.	
    public static void main(String[] args)
    {
        String a = "def";
        String b = "123";
        String c = "abcdefghi";
        // The method replacement is invoked
        String sOutput = replacement(a,b,c);
        // Report
        System.out.println("a =   " + a);
        System.out.println("b =   " + b);
        System.out.println("c =   " + c);
        System.out.println("Replacement done =  " + sOutput);
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A228 IntToChar
//Numbers as chars

package ejvol1;



public class IntToChar
{

	public static void main(String[] args)
	{	
            System.out.println("Int and its char "
                    + "representation");
            for(int i = 0; i <=9; i++)
            {
                //int i is converted to char z
                char z =  ( char ) ( i +48  );
                System.out.println(i + "\t"+ z);
            }
		
	}
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A63 CopyPaste2
// This program copies a substring
// from sOrigin and pastes it into sTarget.

package ejvol1;


public class CopyPaste2
{
    public static void main(String[] args)
    {
        String sOrigin, sTarget, sMiddle, sInitial, sFinal;
        sOrigin = "How does function appear in evolution?";
        sTarget = "appears as a byproduct "
                + "of reproduction under selection";
        System.out.println("Origin = " + sOrigin);
        System.out.println("Target = " + sTarget);
        // Let us copy into sMiddle
        // 4 characters of sOrigin:
        // initial point included: 9,
        // terminal point excluded: 18.
        sMiddle = sOrigin.substring(9, 18);
        System.out.println("sMiddle = " + sMiddle);
        // We copy into sFinal the last part of sTarget
        // beginning  with the zeroth char
        sFinal = sTarget.substring(0);
        System.out.println("sFinal = " + sFinal);
        // We concatenate sMiddle and sFinal.
        String  sOutput = sMiddle + sFinal;
        System.out.println("output = " + sOutput);
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A105 RandomMethods2
//How to   permutate methods.
//Use of the switch structure.
package ejvol1;


import java.util.Random;


public class RandomMethods2
{
    //Turn on of the random generator
    static Random r  = new Random();
	
    public static void zero()
    {
        System.out.print(0);	
    }

    public static void one()
    {
        System.out.print(1);	
    }

    public static void two()
    {
        System.out.print(2);	
    }

    public static void three()
    {
        System.out.print(3);	
    }

    public static void four()
    {
        System.out.print(4);	
    }

    public static void five()
    {
        System.out.print(5);	
    }

    public static void six()
    {
        System.out.print(6);	
    }

    public static void seven()
    {
        System.out.print(7);	
    }

    public static void eight()
    {
        System.out.print(8);	
    }

    public static void nine()
    {
        System.out.print(9);	
    }
	
    // switch multiple selection structure
    public static void permutator(int k)
    {
        switch (k)
        {
            case 0: zero(); break;
            case 1: one(); break;
            case 2: two(); break;
            case 3: three(); break;
            case 4: four(); break;
            case 5: five(); break;
            case 6: six(); break;
            case 7: seven() ; break;
            case 8: eight(); break;
            case 9: nine(); break;
        }
    }
	
	
    public static   void main(String[] args)
    {
        System.out.println("Test 1:");
        for(int k=0; k<=9; k++) permutator(k);
        System.out.println();
        System.out.println("Test 2:");
        for(int k=0; k<=9; k++) permutator(9-k);
        System.out.println();
        System.out.println("Random digits:");
        for(int k=0; k<=9; k++) permutator(r.nextInt(10));
        System.out.println();
    }
}//End of Program A105 RandomMethods2



:::::::::::::  NEW PROGRAM  :::::::::::::



// Program 306 StatTest2
// Simulation of a
// normally distributed random variable
// with arbitrary mean and deviation.

package ejvol1;


import java.util.Random;

public class StatTest2
{
    //Turn on  the random generator
    static Random r  = new Random(); 		

    
    public static void main( String args[])
    {
        // Definition of projected values
        double meanProj = 2;
        double deviationProj = 3;

        int n = 1000;
        double Data[] = new double[10001];
        //We generate n random numbers
        for(int i = 0; i < n;i++)
        {
            double s = r.nextGaussian() ;
            Data[i]= deviationProj* s +meanProj ;
            //System.out.println( Data[ i ]);
        }

        //Let us calculate the mean
        double sum = 0;

        for(int i = 0; i < n; i++ )
          sum = sum + Data[i];
        double mean = sum / n;
        // System.out.println( "Sum \t "+ sum);
        System.out.println( "Mean \t "+ mean);

        // Let us calculate the variance
        double sum2 = 0;
        for(int i = 0; i < n; i++ )
            sum2 = sum2 + (Data[i]-mean)*(Data[i]-mean);
        double var = sum2 / n;
        // System.out.println( "Variance \t "+ var);
        System.out.println( "Deviation \t "+ Math.pow( var, 0.5));
    }
}//End of Program 306 StatTest2



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A231 StringToNumber
//This program decodes strings into numbers.

package ejvol1;



public class StringToNumber
{

    private static double decoder(String s)
    {

        // We get the sign:
        char s1  =   s.charAt(0);
        int sign = Character.getNumericValue(s1);
        // We get the place of the point,
        // which implies multiples of ten.
        s1  =   s.charAt(1);
        int  point = Character.getNumericValue(s1);
        // We build the number with the other chars
        double number = 0;
        for(int j=2;j  <  11;j++ )
        {
            char s3  =   s.charAt(j);
            int  l = Character.getNumericValue(s3);	
            int k = j-1;
            int power = point-k;
            //number1 = l * 10^power
            double number1 = l * Math.pow(10,power);
            number = number + number1;
        }
        if (sign == 0) return (-1) *number;
            else return  number;
    }

    public static void main(String[] args)
    {		
        String s = "06123456789";
        double n = decoder(s);
        System.out.println("String = " + s + " Number = " + n);
    }

}//End of program A231 StringToNumber



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A361 Bugs
//We learn about inner classes,
//classes defined in within another one.

//This program defines the prototype
//Bug
//and many of its instances.
//Other inner classes are also defined
//to facilitate programming.

//WARNING:
//To stop the program use the red square or 
//the menu Run -> Stop run.

package ejvol1;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

public class Bugs   extends Applet
{
	
    //Class bugs  is an archetype.

    //Archetype means old-type, prototype.
    //The word archetype does not belong
    //in evolutionary biology,
    //but it belongs in paleontology.
    //We use here the word archetype as
    //a synonym of a plan or design,
    //of an idea.

    //The next instruction
    //constructs a real stuff, an instance, on the
    //image and resemblance of the archetype.

    static  Bugs  bugs   = new Bugs();


    private static final long serialVersionUID = 1L;

    // Definition of needed prototypes.
    // Prototypes come in UpperCase,
    // instances in lowerCase.

    // A bug has an address over the screen;

    public  class Address
    {
        int x; // x  coordinate
        int y; // y coordinate

        // The next is a method, a function
        // that  declares
        // how information is acquired.
        // It is a constructor.
        // It is overload by two possibilities.
        // a) The input is a list
        Address(int a, int b)
        {
            x= a;
            y= b;
        }	

        // b) The input is a structure
        Address(Address ad  )
        {
            x= ad.x;
            y= ad.y;
        }	

    }
	

    // Bugs can move in any of 9 directions:
    // 8 cardinal points + nothing.
    // A direction is implemented by  a move
    public  class Move
    {
        int x; // x coordinate
        int y; // y coordinate

        // The next is a method, a function
        // that  declares
        // how information is acquired.
        // It is a constructor.
        // It is overload by two possibilities.
        // a) The input is a list
        Move(int a, int b)
        {
            x= a;
            y= b;
        }	

        // b) The input is a structure
        Move(Move move)
        {
            x= move.x;
            y= move.y;
        }	

    }

    //BodyMeasure is defined
    int   width =4;


    //Constructor of the Bug class
    //Prototype definition:
    //How information is acquired


    public class Bug
    {
        //  Each bug has its number, address and color
        int number;
        Address address;	
        int color [];

        // We use various methods to acquire information
        Bug()
        { 		
            color = new int[4]; 	
        }

        Bug(int a, Address ad, int c[])
        {	
            number = a; //default
            address =   ad ;
            color = c;	
        }

        Bug(Bug b)
        {
            number = b.number;
            address = b.address;
            color = b.color;
        }
    }		
  		
    //Turn on  the random generator	
    Random r  = new Random();


    //Each bug lives over the screen,
    //with a given occupation matrix:
    boolean occupied[][];


    //This method is fired automatically
    // at the beginning
    @Override
    public void init()
    {

        //Measures of the window		
        int   xWin = 700;
        int   yWin = 800;	
        setSize(xWin,yWin);		
    }


    // Possibilities of movement
    static Move  vectMoves[ ];
    static Bug[] bug;
    static int nBugs;
    static int nRounds;

    public  void initializer( )
    {		
        vectMoves = new Move[9];	
        occupied = new boolean[200][100];
        bug = new Bug[10000];
    }

    //To avoid overwriting of bugs,
    //an occupation record is kept:	
    //The screen is divided in cells 4x4.
    //At the beginning every cell is empty=false.
    //Occupancy is recorded in occupied[][],
    //which is a boolean matrix.
    //A boolean  variable can be
    //true= occupied,  else false= not occupied.  	
    public void  occupationMatrix()
    {
        //System.out.println("occupationMatrix");
        for(int i = 0; i < 200; i++)
        { 
            for(int j = 0; j < 100; j++)
                occupied[i][j]= false;	
        }			
     }
		
		
    // Here we define 9 cardinal points
    public void moveDef( )
    {
        // System.out.println("MoveDef   ");
        final Move move1 =  new Move(0,1); 		
         vectMoves[0]   = move1 ;
        final Move move2 =  new Move(1,1); 		
         vectMoves[1]   = move2 ;
        final Move move3 =  new Move(1,0); 		
         vectMoves[2]   = move3 ;
        final Move move4 =  new Move(1,-1); 		
         vectMoves[3]   = move4 ;
        final Move move5 =  new Move(0,-1); 		
         vectMoves[4]   = move5 ;
        final Move move6 =  new Move(-1,-1); 		
         vectMoves[5]   = move6 ;
        final Move move7 =  new Move(-1,0); 		
         vectMoves[6]   = move7 ;
        final Move move8 =  new Move(-1,1); 		
         vectMoves[7]   = move8 ;
        final Move move9 =  new Move(0,0); 		
         vectMoves[8]   = move9 ;
        /* System.out.println(vectMoves[6].x);
         System.out.println(vectMoves[6].y);
         System.out.println(vectMoves[7].x);
         System.out.println(vectMoves[7].y); */
    }
		
    //An address is generated at random
    public Address  generateAddress( )
    {	
        Address   ad = bugs.new  Address (1,1);
        int m = r.nextInt(100);
        int n = r.nextInt(100);
        ad.x =m;
        ad.y = n;
        if (occupied[m][n] == true) generateAddress( );
        return ad;
    }
		
    //nBugs bugs are initialized		
    public void initialization(Graphics g)
    {
    System.out.println("initialization");
    for( int i = 0; i < nBugs;i++)
    {
        // an auxiliary bug is initialized	
        Bug  bug1 = bugs.new Bug();
        bug1.number = i;
        // An initial color is chosen
        int c1,c2,c3;


        // a color is assigned to each bug,
        // but different than white	
        c1 = r.nextInt(256);
        c2 = r.nextInt(256);
        c3 = r.nextInt(256);
        if (c1+c2+c3==765) c3=1;
        //colors are memorized.
        bug1.color [1]=c1;
        bug1.color [2]=c2;
        bug1.color [3]=c3;


        //The color is prepared	
        g.setColor( new Color(c1,c2,c3));
        

        // An initial position is chosen:
        // symbolic initialization
        Address   ad  = generateAddress();				
        bug1.address = ad;
        int m=ad.x;
        int n=ad.y;
        //The bug is  painted.
        //A Rectangle is defined by
        // the coordinates of the
        // superior right corner,
        // width and hight.
        // The cell is painted
        g.fillRect(width * m,width* n,width, width); 			
        // System.out.println("occupied = " + m + "  " + n );
        //Occupation is recorded
        occupied[m][n]= true;
        //The bug is memorized
        bug[i]= bug1;
     }
    }



    //Bugs move
    public void movement(Graphics g)
    {
        int number=-1;
        //Try and catch exception pair:

        try   // move
        {
            int  mo,no, m,n;	

            for( int i = 0; i < nBugs;i++)
            {
                number = i;
                Bug  bug1 = bug[i];

                mo = bug1.address.x;
                no = bug1.address.y;	    	

                //System.out.println("moveOn");
                //A move is generated	 at random

                //Select  which direction to move on
                //Throw a number from 0 to 9
                Move  move   = vectMoves[r.nextInt(9)];


                m = mo +  move.x;
                n = no -  move.y;
                //Barriers
                if (m<0)m=0;
                if (n<0)n=0;
                if (m>199)m=199;
                if (n>99)n=99;
                //is the target cell vacant?
                if(occupied[m][n] == false)
                {
                    //To move:
                    //the cell occupied by  the bug is cleared,
                    //the cell to be occupied is painted.

                    //The occupied cell is cleared=
                    //painted in white

                    // the white color is prepared
                    g.setColor(Color.white);
                    // The cell is cleared
                    g.fillRect(width*mo,width*no
                            ,width, width);
                    //Clearing is reported
                    occupied[mo][no] = false;



                    //Movement=repainting in the new place;
                    occupied[m][n] = true;
                    g.setColor( new Color(
                            bug1.color[1]
                            , bug1.color[2]
                            , bug1.color[3] ));
                    g.fillRect(width*m,width*n,width, width);

                    //Address is updated
                    bug[i].address.x = m;
                    bug[i].address.y = n;

                    //If movement is too fast, 
                    //nothing can be seen.
                    //To attune the velocity of movement,
                    //augment or diminish 
                    //the delay as   pleased	

                    // Execution thread is put to sleep
                    // during a delay in milliseconds
                    int delay =  2;
                    Thread.sleep( delay );
                } 
            }//end of for
        }//end of try

        catch ( InterruptedException exception )
        {
            System.out.println(   number+
                "Killed from outside" );
        }
     }


    public void dynamics(Graphics g)
    {
        for(int round= 0; round < nRounds;round++)
        {
            movement(g);
            System.out.println( "Round = " + round);
        }
    }


    @Override
    public void paint(Graphics g)
    {
        System.out.println( "Applet started");
        nBugs = 1000; //
        nRounds = 10000;
        initializer( );
        occupationMatrix();
        moveDef( );	
        initialization(g);
        dynamics(g);
    }
}//End of Program A361 Bugs



:::::::::::::  NEW PROGRAM  :::::::::::::



package ejvol1;


//Program A310 StatTest3

//  Analysis of variance
//  by simulation.
//  Random variables
//  are normally distributed.

// A 3x3 matrix is filled in  random numbers
// with a normal distribution
// with mean 2.222
// and standard deviation 1.483
// The distribution of
// anova stadigraphs is found.

import java.util.Random;


public class StatTest3
{

	
    //Turn on  the random generator
    static Random r  = new Random(); 	

    static int freqTable[] = new int[1000];		
    static int n;
    static  double meanProj ;
    static  double deviationProj ;
    static double M[][] = new double[3][3];
    static double means[] = new double[3];	
    
    //Experimental data (invented)
    static double mExp[][] = {{1,3,1},{2,4,1},{1,5,2}};

    //Initialization
    public static void freqTableToZero()
    {
       for(int i = 0; i < 1000; i++) freqTable[i]= 0;
    }

    //Print to console
    public static void reportM(double M[][])
    {
        for(int i = 0; i < 3; i++)
        {
            for(int j = 0; j < 3; j++)
                System.out.print(  M[i][j] + " \t");
                    
            System.out.println();
        }
            System.out.println();	
    }

//Fills a 3x3 matrix with random numbers
//with a normal distribution
//with mean 2.222
//and standard deviation 1.483
public static void randMatrix()
{
    double s;
    for(int i = 0; i < 3; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            s = deviationProj * r.nextGaussian()+meanProj;
            M[i][j]= s;
            //System.out.print(  M[i][j] + " \t");
        }
        //System.out.println();
     }
//System.out.println();	
}
		
//Calculation of the F stadigraph
public static double F(double M[][])
{
    // reportM(mExp);
    double ssw = 0;
    double meanxi ;
    for(int i = 0; i < 3; i++)
    {
        meanxi = 0;
        for(int j = 0; j < 3; j++)
            meanxi= meanxi + M[j][i];
        //Matrix[row][column]
        meanxi = meanxi/3;
        means[i]=meanxi;
        //System.out.println("meani " + means[i]);

        for(int j = 0; j < 3; j++)
        ssw = ssw + Math.pow((M[j][i]-meanxi),2);
    }

    double  mean = 0;
    for(int i = 0 ; i < 3; i++)
        for(int j = 0; j < 3; j++)
            mean = mean + M[j][i];
    mean = mean /9;

    double ssa = 0;			 		
    for(int i = 0; i < 3; i++)
        ssa = ssa + 3*Math.pow((means[i]-mean),2);
    double F = (ssa/2)/(ssw/6);
    return F;
    }
			
    //Print table
    private static void reportFreqTable(int k)
    {
        int m = 0;
        int i = 1;
        System.out.println( "FreqTable of F values"  );	
        System.out.println( "F" + "\t " + "frec"
              + "\t " + "Cumulated frec");
        while (m<k)
        {			  		
            m = m + freqTable[i];
            System.out.println(i+ "\t " + freqTable[i] + "\t " + m);	
            i = i+1;
        }
    }


    // Report of means and F value
    private static void FExp( )
    {			
        System.out.println("F exp = " + F(mExp));		
        // for(int i = 0; i < 3; i++)
        //System.out.println("meani " + means[i]);			
    }
		
    public static void main( String args[])
    {
        // Definition of projected values
        //According to the null hipothesis
        meanProj = 2.222;
        deviationProj = 1.483;
        freqTableToZero();
        int n = 1000 ;
        //We generate n random matrixes
        // filled in numbers that
        // follow a normal distribution
        // with mean meanProj and
        // deviation deviationProj
        for(int i = 0; i < n;i++)
        {			
            randMatrix();	
            // reportM(M);			
            // System.out.println( i + "\t " + "F = \t " + F());
            int d = (int)  Math.ceil(  F(M));
            freqTable[d]=freqTable[d]+1;
        }
        int k = n;
        reportFreqTable(k);
        // We calculate the F for the experiment
        FExp();
        /* What does ciel do?
         int d = (int)  Math.ceil(  1.2);
         System.out.println( d);
         d = (int)  Math.ceil(  1.7);
         System.out.println( d); */
    }
}//End of Program A310 StatTest3



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A116 Chains
/* We study a population of strings
    that interacts by collisions 
    that produce recombination.
    We are interesting in knowing
    the trend of elongation of strings.
    The program reports tha max (min) length
    of strings for each given generation.
 */

package ejvol1;



import java.util.Random;

public class Chains
{
    //Pre-declaration of global variables.
    //They are used all throughout the whole class.
	
    //Number of generations to run the experiment
    static int nGen = 20000;
    
    //Individuals are kept in the array
    //Individual[]. It is an array of strings.
    //The number of individuals must be
    //less than limit
    
    static int limit = 2000;
    static String Individual[ ];//Declaration
    // We consider a population
    // with a constant number of individuals:
    static int nIndiv = 100 ; 	


    // We keep track of the minumal and maximal  length
    // attained in the population
    static int ReportMin[], ReportMax[];


    //Turning on of the random generator
    static Random r  = new Random();

    //This method generates random chars
    private  static  Character  randomChar()   
    {
        return  ( char ) ( r.nextInt( 26 ) + 65  );
    }


    /* We generate nIndiv individuals (strings)
    with a random number of letters,
    less than 10. Sequences are
    completely random */
    private static void Initialization( )
    {
		
        //Formal declaration of our arrays.	
        Individual= new String[limit];
        ReportMin = new int[nGen];
        ReportMax = new int[nGen];
        for(int i = 0; i< nIndiv; i++)
        {
            ReportMin[i] = 0;
            ReportMax[i] = 0;
        }

        //System.out.println("ORIGINAL POPULATION");
        for(int i = 0; i < nIndiv; i++)
        {
            // Initialization 	in blank.
            Individual[i]="";

            // We generate a random number
            // in within 1 and 9.
            int number = r.nextInt(9)+1;
  		
            //An individual is assembled char by char		
            for(int j = 0; j < number; j++)
            {
                // We generate a random char
                Character c =  randomChar();
                //System.out.println( "char = " + c);
                // Char c is converted into a string s
                String s = "" + c;
                // s is concatenated to Individual[i]
                Individual[i] = Individual[i]+s;
            }
           /* System.out.println("Individual " +  i);
            System.out.println( Individual[i]);*/
        }
    }
	
    // This method  looks for a partner
    // different than l.
    private  static  int  chooseInd(int l)
    {

	// done = 1 is a flag that says that
	// we have found a different partner:
	int done = 0;
        int number=l;
        {
            while (done == 0)//partner has not been found
            {
                number = r.nextInt(nIndiv);
                if (number ==   l)
                      done = 0; //Continue searching
                else done = 1; //break 
            }
            return number;
	}
    }

    //A collision produces recombination
    private  static   void collision(int l, int k)
    {
        String s = Individual[l];
        String t = Individual[k];
        // A collision corresponds to
        // recombination.
        // We divide the strings in two
        // and recombine pieces:
        String  s1= s;
        String  s2 = "";
        int m= s.length();
        if (m>2)
        {
            int m1 = r.nextInt(m-1)+2 ;	
            s1= s.substring(0,m1);
            s2= s.substring( m1);		
            //System.out.println( s + " " + s1 + " " + s2);
        }

        String  t1= t;
        String  t2 = "";
        int n= t.length();
        if (n>2)
        { int n1 = r.nextInt(n-1)+2 ;	
            t1= t.substring(0,n1);
            t2= t.substring( n1);		
            //System.out.println( t + " " + t1 + " " + t2);
        }
        //Recombination
        Individual[l]=s1.concat(t2);
        Individual[k]=t1.concat(s2);

    }
	
    //Min and max lengths are recorded
    private static void Observation(int Gen)
    {	
        int m, Min, Max;

        Max = 0;
        Min = 32000;
        for(int j = 0; j < nIndiv; j++)
        {
            m =  Individual[j].length();
            /*System.out.println(  "The Individual  "
               + Individual(j) + " has length " + m); */
            if (m > Max)  Max = m;
            if (m < Min)   Min = m;
        }
        /*System.out.println(  "Generation " + Gen
         + " MinLength = " + Min + " MaxLength = " + Max);*/
        ReportMin[Gen] = Min;
        ReportMax[Gen] = Max;
    }

    //This method  executes collisions among chains
    private  static  void  dynamics(int gen)	
    {
        for(int i = 0; i < nIndiv; i++)
        {
            //individual i collides
            // with another one
            // chosen at random.

            
            int l = i;
            int k = chooseInd(l);
            
            String s = Individual[i];
            String t = Individual[k];
            //System.out.println( s + "\t " + t);
            
            collision(l,k);
            Observation(gen);
        }
    }
	

    //Min and max lengths are reported 
    public static void finalreport()		
    {
        System.out.println( "GEN, MIN and MAX VALUES");
        for(int gen = 0; gen < nGen; gen++)
            System.out.println(gen +"\t" +  ReportMin[gen]
                        +"\t" +  ReportMax[gen]);
    }
	
    
    //Initialization and dynamics			
    public static void main(String[] args)
    {	
        // We seed a population
        Initialization();
        for(int gen = 0; gen < nGen; gen++)
        {
            dynamics(gen);			
        }
        finalreport();	
    }
}//End of Program A116 Chains



:::::::::::::  NEW PROGRAM  :::::::::::::



//program A84 Arrays4
//Mean and variance of decimal data.
package ejvol1;


public class Arrays4
{
   public  static void main( String args[] )
   {
        //Declaration and assignation of the data array	
        double  Data[] = {1.1,5.2,2.3,4.4,7.5,8.6,9.7,5.8};
    		
        // Report of data.
        System.out.println( "Data are" );
        // To know the length of the array : Data.length
        for ( int i = 0; i < Data.length; i++ )
        {
            System.out.print( Data[ i ]);
            System.out.println(); //pass to the next datum
        }
        //   Let us calculate the mean
        double sum = 0;
        int n = Data.length;
        for ( int i = 0; i < n; i++ )
            sum = sum + Data[i]; 
        double mean = sum / n;
          System.out.println( "Sum \t "+ sum);
          System.out.println( "Mean \t "+ mean);
        //    Let us calculate the variance
        double sum2 = 0;
        for ( int i = 0; i < n; i++ )
         sum2 = sum2 + (Data[i]-mean)*(Data[i]-mean);
        double var = sum2 / n;
        System.out.println( "Variance \t "+ var);
        System.out.println( "Deviation \t "+ Math.sqrt(var));
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
Program A158 HardDisc
This program creates and/or rewrites a file
and save data to it.
 */
package ejvol1;



//Needed tools
import java.util.Formatter;
import java.io.FileNotFoundException;
import java.util.FormatterClosedException;


public class HardDisc
{
    //We write   data	 of different type
    static private Formatter output;

    // We open  file
    static  public void openFile()
    {
        try
        {
            //The file is created and a name is given.
            //A target directory also could be specified
            output = new Formatter( "Numbers.txt" );
        }
        catch ( SecurityException securityException )
        {
            System.err.println(
               "Permission denied"  
                       + securityException.toString());
            System.exit( 1 );
        }
        catch( FileNotFoundException filesNotFoundException )
        {
            System.err.println( "Creation of file failed." 
                + filesNotFoundException.getMessage());
            System.exit( 1 );
         }
    }


// We save data
static  public void writeDown()
{
    //try and catch pair
        try
        {
            // Data is fabricated and saved
            //Modify this at pleasure.
            for(int i = 0; i<10;i++)
            {
                int l = 2*i+1;
                double w = l;
                // Write  two data to file,
                // one integer and the other decimal (double)
                output.format( "%d   %.2f\n", l, w );
            }

        } // end try
        catch(FormatterClosedException formatterClosedException)
        {
            System.err.println( " Closing failure" 
            + formatterClosedException.getMessage());
        } // end catch
}


    // We close file
    static  public void closeFile()
    {
        output.close();
    }


    public static void main(String[] args)
    {
        openFile();
        writeDown();
        closeFile();
    }
}//Program A158 HardDisc



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A64 Deletion
// This program deletes from s1
// its first 3 characters.

package ejvol1;


public class Deletion
{
    public static void main(String[] args)
    {
        String s1, s2, s3;
        s1 = "Evolution = mutation + selection";
        System.out.println(s1);

        s2 = s1.substring(0,3);
        System.out.println("Substring to delete = " + s2);
        //s2 is replaced by the void string
        s3 = s1.replace(s2, "");
        System.out.println("Substring deleted: "  + s3);
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A74 Concatenation4
//Concatenation of 3 strings
//Structured programming.

package ejvol1;


 public class Concatenation4
{
    // This method concatenates a,  b and c
    public static String  glue(String a, String b, String c)

    {
        // The reserved word "return"
        // points to the output of the method glue.
        return a+b+c;
    }
	
    public static void main(String[] args)
    // This is the head of the program.
    {
        String a = "pqrst";
        String b = "123";
        String c = "ATCG";
        // the output of glue is placed in string c
        String sOutput = glue(a,b,c);
        //Report
        System.out.println("a =   " + a);
        System.out.println("b =   " + b);
        System.out.println("c =   " + c);
        System.out.println("a + b +c =   " + sOutput);
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::




//Program A288 Dialog4
//Event based programming.
//A JApplet with three inputs.
//AWT + JApplet + Swing based code.
package ejvol1;


import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JTextField;


//We declare that the class must 
//be armed with JApplet's tools
//and that must include a facility to 
//listened at the prompts of the User.
public class Dialog4 extends JApplet implements ActionListener
{
    private static final long serialVersionUID = 1L;

    //A label contains a message to the User
    private JLabel resize;
    private  JLabel invitation1; //message to the user
    //A textField reads the input from the User
    private  JTextField input1;  //input from the user
    private  JLabel invitation2;
    private JTextField  input2;
    private  JLabel invitation3;
    private JTextField  input3;
    private JLabel sum ;
   


@Override
public void init() 
{
    this.resize = new JLabel("Resize the applet for a better view!" );

    //Input machinary
    //Declaration
    // A Label displays an invitation to operate
    this.invitation1 = new JLabel("Input first parameter ");
    //A TextField is a place for writing.
    this.input1 = new JTextField( 10);
    this.invitation2 = new JLabel("Input second parameter ");
    this.input2 = new JTextField( 10);
    this.invitation3 = new JLabel("Input third parameter + enter ");
    this.input3 = new JTextField( 10);
    this.input3.addActionListener( this);

    this.sum = new JLabel("The sum is " );
    
    //Activation
    this.add(resize);
    this.add(invitation1);
    this.add(input1);
    this.add(invitation2);
    this.add(input2); 
    this.add(invitation3);
    this.add(input3); 
    this.add(sum);
    // Let Swing manage the layout.
    this.setLayout(new FlowLayout());
    
}

@Override  
public void actionPerformed(ActionEvent event)
{  
    // If the User presses enter into the second field
    //Read textField1 and textField2
    //Read as String and translated to Double
    Double num1 = Double.parseDouble(this.input1.getText() );
    Double num2 = Double.parseDouble(this.input2.getText() );
    Double num3 = Double.parseDouble(this.input3.getText() );
    Double result = num1 + num2 + num3;
    //The text of label sum is updated
    this.sum.setText("The sum is "  + result.toString());
    //Make a report to the console.
    // Here we report results.
    // We use the console
    // because we expect large volumes of data
    System.out.println("Number 1 " + "\t " + num1 );
    System.out.println("Number 2" + "\t " + num2 );
    System.out.println("Number 3" + "\t " + num3 );
    System.out.println("The sum is " + "\t " + result );
    System.out.println();
}
}//End of Program A288 Dialog4



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * Program A40 ForLoop5
 * The upper bound of integers in Java.
 * Assign to N a large value.
 * Check for a negative output.
 * To stop the program, click over a red square 
 * in the left bar.
 */
package ejvol1;


public class ForLoop5
{

    public static void main(String[] args)
    {		
        String tab = "\t";	
        int N= 10;		
	for(int i = 1; i<=N; i++ )
        {	
            System.out.println(i + tab + 1000 * i);
        }
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * Program A36 ForLoop2
 */
//Introduction of the for-control structure.
//The "for" instruction causes a loop
//to deal with repetitive tasks.
package ejvol1;


public class ForLoop2
{
		
    public static void main(String[] args)
    {			
        String tab = "\t";

        for(int i = 1; i<=7; i++)
        {		
            System.out.println(i + tab  + i*i);
        }
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A151 ToolBox2
//This is a test for the methods in ToolBox

package ejvol1;


public class ToolBox2 
{
    public  static void main(String[] args)
    {        
        //A method of class TopDown is invoked 
        System.out.println("Invokation of methods from ToolBox:");
        String a = "aaaa";
        String b = "aaaaaaaaabbbbb";
        String c = "cdfghhjk";
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println("c = " + c);
        String d = ToolBox.delete(a, b);
        System.out.println("Delete output = " + d);
        
        String s = ToolBox.insert(a, 5, c);
        System.out.println("Insert output = " + s);
        
        String i = ToolBox.inversion(c);
        System.out.println("Inversion output= " + i);
        
        String j = ToolBox.invert("fgh", c);
        System.out.println("Invert output = " + j);
        
        String k = ToolBox.substitution(a, c, b);
        System.out.println("Substitution output = " + k);  
    }   
}



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * Program A38 ForLoop4
 */
// Variation of the for statement.

package ejvol1;


public class ForLoop4
{
		
    public static void main(String[] args)
    {			
        String tab = "\t";			
        for(int i = 0; i<=20; i++)
            {		
                System.out.println(i + tab + i*i*1);
            }
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


//Program A25 DivisionByZero
//Division by zero

package ejvol1;

public class DivisionByZero
{		
    public static void main(String[] args)
    {
        //Declaration and initialization
        // of variables
        int x = 6;
        int y = 0;
        System.out.print(" The division of x =" + x 
                + " by  y = " + y  + " is ");
        //Computation
        int result  = x/y;
        // Report
        System.out.println(result);
    }	
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A100 RandomDNA
//Random  DNA string.
package ejvol1;


import java.util.Random;

public class RandomDNA
{
   public static void main( String args[] )
   {
        //We turn on the random generator:
        Random r  = new Random();
        // Definition of the alphabet
        char Alphabet[] = {'A','T','C','G'};
	
        // Generation of a DNA string 60 bases long
        for(int i= 0; i< 60; i++)
        {
            char ch =   Alphabet[ r.nextInt( 4 )];
            System.out.print (  ch);
        }
        System.out.println();
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A282 DrawString
//My first Applet
//This applet opens a window
//and paints a message.

package ejvol1;



//Tools to draw:
import java.awt.Graphics;
import javax.swing.JApplet;

public class DrawString extends JApplet
{

    private static final long serialVersionUID = 1L;

    public void paint( Graphics g )
    {
       super.paint( g ); // intention of drawing
       // draw a message at coordinates (10,25)
       g.drawString( "This is my first Applet.", 10, 25 );
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



// Program A267 LotkaVolterra4
// Study  of a prey-predator system.
// Logistic Lotka-Volterra equations.
// Stochastic model.

package ejvol1;

import java.util.Random;


public class LotkaVolterra4
{
    static int  nr, nw, max;
    static double e,rr,p,wr,wd;
	
    //Turn on of the random generator
    static Random r  = new Random();
		
    public static void initialization()
    {
        //Generates 500 rabbits,  50 wolfs
        nr = 500;
        nw = 50;
        //Rate of rabbit's reproduction
        rr = 0.1;
        //Maximum number of Rabbits
        max = 2000;	
        //Rate of predation
        p = 0.01;
        //Rate of wolf's death
        wd = 0.05;
        // Rate of wolf's reproduction
        wr = 0.9 * p ;
        //Titles
    }
	
    public static void dynamics()
    {
        //We run n generations		
        int  n = 2000;
        for(int i = 0; i < n; i++)
        {
            //Rabbits reproduce
            for(int j = 0; j < nr; j++)
            {
                // The process of reproduction
                // is ruled by a binomial
                // random variable m
                double s = r.nextDouble();
                if (s < rr * (1 - (nr / max))   ) nr = nr + 1;
            }
            //Rabbits are preyed, wolfs reproduce
            //Binomial random variables:
            //an encounter may or may not
            //produce a chase.
            for(int l = 0; l < nw; l++)
            {
                for(int j = 1; j < nr; j++)
                {
                    double s = r.nextDouble();
                   // a rabbit is predated
                    if (s < p) nr = nr - 1;
                    // a wolf is born
                    if (s < wr)  nw = nw + 1;
                }
            }
            //Wolfs die
            for(int j = 0; j < nw; j++)
            {
                double s = r.nextDouble();
                if (s < wd)  nw = nw - 1;
            }		
            System.out.println(i + "\t" + nr + "\t " + nw);
        }
    }
		
    public static void main(String[] args)
    {
        initialization();
        System.out.println("time, rabits and wolfs");
        dynamics();
    }
}//End of Program A267 LotkaVolterra4




:::::::::::::  NEW PROGRAM  :::::::::::::


//Program A43 TypeDouble
//The type double,
//to encode decimal numbers.
//Square roots are calculated.

package ejvol1;


public class TypeDouble
{
		
    public static void main(String[] args)
    {			
        String tab = "\t";			
        for(int i = 0; i<=15; i++)
        {	
            double r = i;
            //Square root of r
            double o = Math.sqrt(r);
            System.out.println(i + tab + o);
        }
    }  
}



:::::::::::::  NEW PROGRAM  :::::::::::::



// Program 81 Arrays
// We introduce one-dimensional arrays.	
package ejvol1;


public class Arrays
{
   public static void main( String args[] )
   {
    // Declaration of an array with integer entries
       int data[];  // data is the name.

    // Assignation of the capacity of the array:
    // ten entries, beginning from zero.
    // data[i] can be defined for i from zero to 9
    // data[10] is not defined
      data = new int[ 10 ];

    // Assignation of each entry
    for(int i = 0; i<=9; i=i+1)
    {
        data[i] = i*i;
    }

    // The array is written to the console.
    for(int i = 0; i < 10; i++)
        System.out.println(  i + "	" + data[i] );
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



// Program 323 StatTest6
// An incomplete block design.
// Duplex method

// Fills a 3x3 with random numbers
// with a normal distribution
// with mean 2.222
// and standard deviation 1.483

//A Kolmogorov Smirnov test is included

package ejvol1;

import java.util.Random;


public class StatTest6
{
    //Turn on  the random generator
    static Random r  = new Random(); 	

    static int freqtableColsRefilledMatrix[] = new int[10001];
    static int freqtableRowsRefilledMatrix[] = new int[10001];		
    static int freqtableColRandMatrix[] = new int[10001];
    static int freqtableRowsRandMatrix[] = new int[10001];
    static double cumColsRefilledMatrix[] = new double[10001];
    static double cumRowsRefilledMatrix[] = new double[10001];
    static double cumColRandMatrix[] = new double[10001];
    static double cumRowsRandMatrix[] = new double[10001];
		
    static double help[] = new double[25];
    static int nLim;
    static  double meanProj;
    static  double deviationProj;
    static double M[][] = new double[4][4];
    static double means[] = new double[4];
    static double Fcolumns;
    static double Frows;

    private static void freqtableToZero()
    {
        for(int i = 0; i<=1000; i++)
        {
            freqtableColsRefilledMatrix[i]=0;
            freqtableRowsRefilledMatrix[i]=0;
            freqtableColRandMatrix[i]=0;
            freqtableRowsRandMatrix[i]=0;
        }
    }

    private static void reportM( )
    {
        for(int i = 1; i<=3; i++)
        {
            for(int j = 1; j<=3; j++)
                System.out.print(  M[i][j] + " \t");
               
            System.out.println();
       }
        System.out.println();	
    }

//Fills a 3x3 with random numbers
//with a normal distribution
//with mean 2.222
//and standard deviation 1.483
private static void randMatrix()
{
    double s;
    for(int i = 1; i<=3; i++)
    {
        for(int j = 1; j<=3; j++)
        {
            s = deviationProj * r.nextGaussian()
                + meanProj;
            M[i][j]= s;
            //System.out.print(  M[i][j] + " \t");
        }
        //System.out.println();
    }
    //System.out.println();	
}
		

private static void FF()
{
    // reportM(mExp);
    /*GSi Great  Square under treatment i =
     (\sum^{n_i}_{j=1}X_{ij})^2 */
    double GS1 = Math.pow(M[1][1] + M[2][1]+M[3][1],2);
    double GS2 = Math.pow(M[1][2] + M[2][2]+M[3][2],2);
    double GS3 = Math.pow(M[1][3] + M[2][3]+M[3][3],2);
    //System.out.println("GS1 "+ GS1);
    //T= \sum^k_{i=1} \sum^{n_i}_{j=1} X_{ij}

    /*GS= Great  Square =
    (\sum^k_{i=1} \sum^{n_i}_{j=1} X_{ij})^2*/

    double GS = Math.pow(M[1][1]+M[2][1]+M[3][1]+
    M[1][2] +M[2][2] +M[3][2]+M[1][3]+M[2][3]
    +M[3][ 3],2);


    /*Among Columns SS =
     \sum^k_{i=1}\frac{GS_i}{ l_i}-\frac{GS}{N}.*/
    double ACSS = (GS1 / 3 + GS2 / 3 + GS3 / 3) - GS /9;

    /*Among columns DF =
    Among columns degrees of freedom= k-1= 3-1=2.*/


    /*Among columns Mean square=
     \frac{Among Columns SS}{Among columns DF}*/

    double ACMS = ACSS / 2;


    //The same but for rows or blocks


    double BGS1 = Math.pow(M[1][1] + M[1][2]+M[1][3],2);
    double BGS2 = Math.pow(M[2][1] + M[2][2]+M[2][3],2);
    double BGS3 = Math.pow(M[3][1] + M[3][2]+M[3][3],2);
				
    // System.out.println( "  BGS1 "+ BGS1);
    /*Among Rows SS =
    $\sum^k_{i=1}\frac{GS_i}{ k_i}-\frac{GS}{N}$ */

    double ARSS = (BGS1/3 + BGS2/3 + BGS3/3) - GS/9;
    // System.out.println( "ARSS " + ARSS);
    /*Among rows DF=
    Among rows degrees of freedom= l-1= 3-1=2.*/

    /*Among rows Mean square=
      \frac{Among Rows SS}{Among rows DF}*/

    double ARMS = ARSS / 2;
    // System.out.println( "ARMS " +ARMS);

    //Calculates the sum of the squares of   entries.


    double UIK = Math.pow(M[1][ 1] ,2)
    + Math.pow(M[2][ 1] ,2)
    + Math.pow(M[3][ 1] ,2)+ Math.pow(M[1][ 2],2)
    + Math.pow(M[2][ 2],2)
    + Math.pow(M[3][ 2],2) + Math.pow(M[1][ 3] ,2)
    +Math.pow( M[2][ 3] ,2) + Math.pow(M[3][ 3] ,2);


    //Total SS=Total Sum of Squares=
    //$\sum^k_{i=1}\sum^{n_i}_{j=1}[X_{ij}^2]-\frac{GS}{N}$

    double TotalSS = UIK - GS / 9;
    // System.out.println( "TotalSS " + TotalSS); //OK
    //Error SS=error sum of squares=
    //Total SS - Among columns SS -Among row SS

    double ERRORSS = TotalSS - ACSS - ARSS;

    //System.out.println( "ERRORSS " + ERRORSS);

    //Error DF= Total DF - Among groups DF - Among rows DF
    //=    8-2-2=4 .

    //Error Mean square= \frac{Error SS}{error DF}

    double EMS = ERRORSS / 4;
    //System.out.println( "EMS " + EMS);
      Fcolumns = ACMS / EMS;
      Frows = ARMS / EMS;
    //  System.out.println( Fcolumns  ); //OK	
    // System.out.println( Frows  ); //OK
			
}
		
private static void cum(int vect[], double cumvect[])
{

    int sum = 0;
    for(int i = 0; i<=nLim; i++)
    {
        sum = sum + vect[i];
        cumvect[i] = sum ;
    }

    for(int i = 0; i<=nLim; i++)
           cumvect[i] = cumvect[i] /sum;
}
		
		                    	 		
private static void cumulatives()
{
    cum(freqtableColsRefilledMatrix,cumColsRefilledMatrix);

    cum(freqtableRowsRefilledMatrix,cumRowsRefilledMatrix );

    cum(freqtableColRandMatrix,cumColRandMatrix);

    cum(freqtableRowsRandMatrix,cumRowsRandMatrix);	
}
		
private static void ksTestCols()
{
    System.out.println("Cumulative " +
                  " distributions for Columns");
    System.out.println(" i + RefilledMatrix+ " +
                  " RandomMatrix + diff" );	

    double dMax = 0;
    double c;
    for(int i = 1; i<=nLim; i++)
    {			  			 	
        c= Math.abs(cumColsRefilledMatrix[i]
             -cumColRandMatrix[i]);
        System.out.print (i+ "\t " + cumColsRefilledMatrix[i] +
                "\t " + cumColRandMatrix[i] + "\t " + c);  				 	

        System.out.println() ;
        if (c>dMax) dMax = c;	  	
    }
    System.out.print ("Max difference = " + dMax);
    System.out.println();
    //  dCritic for alpha = 0.05
    double h = 1.36/Math.sqrt(1000);
    System.out.print ("dCritic = " + h);
    System.out.println() ;
    if (dMax<=h) System.out.print("Cols: " +
                  "The two distributions are the same. ");
     else   System.out.print("Cols: " +
                  "The two distributions are different.");	

}		
		
private static void ksTestRows()
{
    System.out.println("Cumulative " +
        "distributions for Rows");
    System.out.println(" i + " +
        "RefilledMatrix+ RandomMatrix + dif" );	

    double dMax = 0;
    double c;
    for(int i = 1; i<=nLim; i++)
    {			  			

        c= Math.abs(cumRowsRefilledMatrix[i]
             -cumRowsRandMatrix[i]);
        System.out.print (i+ "\t " +
            cumRowsRefilledMatrix[i] +
            "\t " + cumRowsRandMatrix[i] +"\t " + c);  				 	

        System.out.println() ;
        if (c>dMax) dMax = c;	
    }
   System.out.print ("Max difference = " + dMax);
   System.out.println();
   //dCritic for alpha = 0.05
   double h = 1.36/Math.sqrt(1000);
   System.out.print ("dCritic = " + h);
   System.out.println() ;
   if (dMax<=h) System.out.print("Rows:" +
        "The two distributions are the same. ");
    else   System.out.print("Rows:" +
        " The two distributions are different.");	

}

// We copy the matrix into a vector
// The central entry is ignored.			
private static void meanVariance()
{			
    int  n =0;
    for(int i = 1; i<=3; i++)
    {
        for(int j = 1; j<=3; j++)
        {
            if ((!(i==2)) |(!(j==2)) )
            {
                    n = n +1;
                    help[n]= M[i][j];					

            }
        }			
    }
    //System.out.println( "count \t " + count);
/*for(int i = 1; i<=count; i++)
                System.out.println( help[i]); */
/* We calculate mean and deviation of the vector:
          Let us calculate the mean */
    double sum = 0;

    System.out.println( "n \t "+ n);

    for ( int i = 1; i <= n; i++ )
      sum = sum + help[i];
    double mean = sum / n;
      System.out.println( "Sum \t "+ sum);

    System.out.println( "Mean \t "+ mean);
    // Let us calculate the variance
    double sum2 = 0;

    for ( int i = 1; i <= n; i++ )
        sum2 = sum2 + (help[i]-mean)*(help[i]-mean);
    double var = sum2 / n;
    System.out.println( "Variance \t "+ var);
    meanProj = mean;
    deviationProj = Math.pow(var, 0.5);
    System.out.println("Deviation \t "+ deviationProj);
    System.out.println();
}
		
//Only the nonzero block matters
// This is an incomplete design:
// The central 0 is a provisional value:
// it stands in the place of a hole and
// it will be replaced by a random number.
// To that aim, we calculate the mean
// and variance of other data
// to design the normal distribution
// from which the random number will
// be sampled.
private static void initialization( )
{		
    final double mExp[][] = {{0,0,0,0},
                                      {0,5,8,6},
                                      {0,7,0,8},
                                      {0,4,7,3},
                                      };


    for(int i= 1; i<=3; i++)
            for(int j= 1; j<=3; j++)
                    M[i][j] = mExp[i][j];
    System.out.println( "Experimental matrix"  );
    System.out.println( "The central 0 is a hole"  );
    reportM();
    meanVariance();
    // The central 10 is replaced by
    // a random number.				   				

}

private static void completing( )
{
    M[2][2]=  deviationProj *
       r.nextGaussian()+meanProj ;
}
	

		
		
public static void main( String args[])
{
    // Definition of the exp matrix
    // calculation of projected values
    initialization();
     nLim = 1000 ;
    freqtableToZero();
    // We build n matrixes, in which
    // the void entry is filled
    // with a random number
    // and the statistics are calculated.
    for(int k=1; k<=nLim;k++)
    {
        completing();
        FF();
        int d = (int)  Math.ceil(  Fcolumns);
        freqtableColsRefilledMatrix[d]=
                 freqtableColsRefilledMatrix[d]+1;
        d = (int)  Math.ceil(  Frows);
        freqtableRowsRefilledMatrix[d]=
        freqtableRowsRefilledMatrix[d]+1; 			
    }



    //We generate n random matrixes
    // filled in numbers that
    // follow a normal distribution
    // with mean meanProj and
    // deviation deviationProj
    for(int i=1; i<=nLim;i++)
    {			
        randMatrix();	
        // reportM(M);			
        //System.out.println( i + "\t " + "F = \t " + F());
        FF();
        int d = (int)  Math.ceil(  Fcolumns);
        freqtableColRandMatrix[d]=freqtableColRandMatrix[d]+1;
        d = (int)  Math.ceil(  Frows);
        freqtableRowsRandMatrix[d]=freqtableRowsRandMatrix[d]+1;
    }		 	
    cumulatives();

    ksTestCols();
    ksTestRows();
    }
}//End of Program 323 StatTest6



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A54 Replace2
//Replacement of a substring with another one.

package ejvol1;


public class Replace2
{
    public static void main(String[] args)
    {
        //Declaration of type of variables
        String s1, s2;
        //Assignation
        s1 = "No limits to my imagination.";
        System.out.println(s1); //action
        s2 = s1.replace("limit", "barrier");
        System.out.println(s2); //action
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A215 Randgeneratorr10
//Back-copied from
//Program E159 whateverCTest.

//A source generates random number of type double
//with a given distribution
//but with the condition that the   numbers must have 
//a uniform distribution in within each one of  
//given intervals.
//A test for the claim is included.

package ejvol1;




import java.util.Random;

public class RandGeneratorr10
{


//Absolute frequencies are defined:
//The frequency of 0 is 3, that of 1 is 2,
//that of 3 is zero and that of 4 is 5.
private static final int Dist[] =  {3,2,0,5};
private static int nClasses = Dist.length;
private static double sizeSample;
private static final int sizeSimulation = 100000;
private static final double Events[] = 
	                    new double[sizeSimulation];


//Counters of simulated events are in count
private static final double count[] = new double[nClasses];
//Predicted distribution
private static final double Predict[] = new double[nClasses];
//Discrepancies line per line
private static final double criticalChi2 = 7.8;
private static final double Discrep[] = new double[nClasses];	
//Turn on of the random generator
private static final Random r  = new Random();
//A boolean variable has to values: true else false.
private static boolean printAll = false;

private static double min;
private static double max;
//The left border of intervals, less or equal to the
//minimum value of data.
private static double infLimit;
//Interval length
private static double intervalLength ;
//Max number of allowed classes
private static final int maxnClasses = 1000;
//Borders of the intervals
private static final double  Barriers[] = 
	                           new double[maxnClasses +1];
private static final double classMarkers[] =
	                           new double[maxnClasses];

//Distribution of the discrepancies
private static final double    FreqTable[][] = 
	                          new double[maxnClasses][2];


//Prints data in vector
private static void printVector(double Vect[])
{
    for ( int i = 0; i < Vect.length; i++ )
        System.out.println( i + "    " + Vect[ i ]  ); 
}


//Returns the size of the sample
private static double sizeSample()
{
    double s= 0;
    for(int i= 0; i < nClasses; i++)
    {
        if (Dist[i]> 0 ) 
            s = s +  Dist[i];    
    }
    return s;	
}

//Predicts what must be observed
private static void prediction()
{
    for(int i= 0; i < nClasses; i++)
    {
        double probSubI =  Dist[i] / sizeSample; 
        Predict[i] =  probSubI * sizeSimulation; 	   
    }
}


//Runs a chi^2-test to check the accuracy
//of our source of random numbers
//that must fit the distribution given by Dist
private static double chiTest()
{
    double d= 0;
    for(int i= 0; i < nClasses; i++)
    {
        if (Predict[i]> 0 ) 
           Discrep[i]  = 
                Math.pow((count[i] - Predict[i]),2)
                                          /Predict[i];    
        d = d + Discrep[i];
    }
    return d;	
}

//The range of discrepancies is evaluated
//and is used to calculate the length of each 
//interval to group Discrepancies.
public static double intervalLength()
{
    min=100000;
    max = 0;
    int lim = sizeSimulation;
    for(int i = 0; i < lim; i++)
    {
        if (Events[i] < min ) min = Events[i];
        if (Events[i] > max ) max = Events[i];
    }
    System.out.println( "min = " + min );
    System.out.println( "max = " + max );
    double range = max - min;
    double length = range /nClasses;
    return length;
}


//Prints the frequency table
private static void printFreqTable(double FreqTable[][], 
                                            int nClasses)
{
    System.out.println( "x and its absolute frequency" );
    for ( int i = 0; i <= nClasses; i++ )
        System.out.println( FreqTable[ i ][0]+ 
                           " "+ (int) (FreqTable[ i ][1]));        	
}


//Calculates the sum    of absolute frequencies 
//of a frequency table
private static void 
             sum(double FreqTable[][])
{
    double sum = 0;
    for ( int i = 0; i <= nClasses; i++ )
            sum = sum +  FreqTable[i][1];
    System.out.println( "Number of events = " + sum);
}	

//The border of each interval is calculated
private static void getBorders(double Vect[])
{
    Barriers[0] = infLimit;
    classMarkers[0] = infLimit + intervalLength/2;
    //Calculate maximal value of data
    double max = Vect[0];
    for(int j=1; j < Vect.length; j++) 
      if (Vect[j] > max)  max = Vect[j];
    System.out.println( "Max value = " + max);
    //Calculates number of classes
    nClasses =   (int) ((max- infLimit)/intervalLength) + 1;
    System.out.println( "Number of classes = " + nClasses);
    //Calculates interval borders and class markers
    for(int j=1; j <= nClasses; j++) 
    {
        Barriers[j] = Barriers[j-1] + intervalLength;
        classMarkers[j] = classMarkers[j-1] + intervalLength; 
    }
    /*System.out.println( "Borders are" );
    printVector(Barriers);
    System.out.println( "Class markers are" );
    printVector(classMarkers);*/
}

//Data are grouped into interval classes.
private static void group(double Vect[])
{
    intervalLength = intervalLength();
    infLimit = min - intervalLength/2;
    getBorders(Vect);
    int nData = sizeSimulation;
    //Class markers a re defined
    for(int j=0; j < nClasses; j++) 
    {	
        FreqTable[j][0] = classMarkers[j];
        FreqTable[j][1] = 0;
    }
    //Frequencies are calculated.
    for(int i=0; i< nData; i++)
    {
        for(int j=0; j < nClasses; j++)
        {
            if ((Vect[i] >= Barriers[j]) &
                (Vect[i] < Barriers[j+1]))
                FreqTable[j][1] =FreqTable[j][1] +1;	
        }

    }
}


//The claim that there is a uniform distribution
//in within each inner barrier is tested
private static void  test()
{
    group(Events);
    System.out.println("Frequency table of events");
    printFreqTable(FreqTable, nClasses);
    //Minor test for correct grouping
    sum(FreqTable);
    System.out.println("Frequencies   of events (for Excel)");
    for(int i = 0; i <= nClasses ; i++)
            System.out.println(i + "\t" + FreqTable[i][1]);
}


public static void main(String[] args)
{
    for (int i=0; i< Dist.length;i++) count[i]=0;

    for (int i = 0; i <  sizeSimulation;i++)
    {
        //A random decimal number in (0,10) is generated
        //r.nextDouble() generates a random decimal number
        //with a uniform distribution in within 0 and 1.
        double e = 10*r.nextDouble();	

        //Outputs are renamed
        if (e<3) 
            {e = e/3; count[0] = count[0]+1;}
        if ((3<= e )& (e<5)) 
            {e = 1+ (e-3)/2; count[1]=count[1]+1;}
        if ((5<= e )& (e<10))
            { e = 3 + (e-5)/5; count[3]=count[3]+1;}
        Events[i] = e;
    }
    printAll = false;
    if (printAll) 
    {
        System.out.println(" Simulated events");
        printVector(Events);
    }
    System.out.println("Observed in simulation values");
    printVector(count);
    sizeSample = sizeSample();
    prediction();
    System.out.println("Predicted values");
    printVector(Predict);
    double dExp = chiTest();
    System.out.println("Ho: observed values fit " +
                            "predicted ones");
    System.out.println("Discrepancies");
    printVector(Discrep); 
    System.out.println("Experimental discrepancy = " + dExp);
    System.out.println("Critical chi2 = " + criticalChi2);
    if (dExp >  criticalChi2)
        System.out.println("The event is extreme "
            + " according to Ho: invent another theory."); 
    else 
        System.out.println("Normal event according to Ho:" 
            + "there is no reason to reject Ho");
    //We open 10 classes for each interval
    nClasses = 10* nClasses;
    //test for uniformity in within integer borders
    System.out.println(" \nTEST zone");
    test();
}//End of main()
}//End of class A215 RandGeneratorr10



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A161 HardDisc2
//This program reads a  file
//and displays its content.
        
package ejvol1;


import java.io.File;
import java.io.FileNotFoundException;
import java.util.NoSuchElementException;
import java.util.Scanner;



public class  HardDisc2
{
    private static  Scanner input;

    // We open a file
    public  static  void openFile()
    {
        //try and catch pair
        try
        {
            input = new Scanner( new File( "Numbers.txt" ) );
        }
        catch ( FileNotFoundException fileNotFoundException )
        {
            System.err.println( "File does not exists." 
            + fileNotFoundException.getMessage());
            System.exit( 1 );
        }
    }

    
    // We read  record from file
    public  static  void readData()
    {	
        //try and catch pairs
        try
        {
            while ( input.hasNext() )
            {

                /* Data must be read in concordance with
                * the form as they were saved.
                * The writting procedure was:

                    {
                        //Modify this at pleasure
                        int l = 7*i+3;
                        double w = l;
                        // Write  new data to file,
                        // one integer and the other 
                        //decimal (double)
                        output.format( "%d   %.2f\n", l, w );
                   }

                * The reading procedure follows:	

                */
                for(int i = 0; i< 10;i++)
                {        	
                    int l = input.nextInt();
                    double w = input.nextDouble();
                    System.out.printf("%d   %.2f\n", l, w );
                }
            }
        }
        catch ( NoSuchElementException elementException )
        {
            System.err.println( "File is corrupted." 
            + elementException.getMessage());
            input.close();
            System.exit( 1 );
        }
        catch ( IllegalStateException stateException )
        {
            System.err.println( "Reading aborted."
            + stateException.toString());
            System.exit( 1 );
        }
     }


    // We close file and terminate application
    public static void closeFile()
    {
       if ( input != null )
          input.close(); //
    }

    public static void main(String[] args)
    {
       openFile();
       readData();
       closeFile();
    }
}//End of Program A161 HardDisc2



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * Program Q65 PrintSourceFiles
 * Use this program to get a copy in plain text
 * of all Java programs of a Netbeans project.
 * Programs can be printed to the console
 * and then copied to a text document.
 * Or they can be printed to a .txt file
 * that can be opened with whatever tex editor.
 * This file must be deleted before a second run
 * or results will get appended to the existent file.
 */

package ejvol1;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 *
 * @author jose
 */
public class PrintSourceFiles 

{
    
    /*
        Under Projects' tab:
        Right click on the name of the NetBeans project,
        select   properties:
        read and copy the project folder and 
        replace the path here for that found there:    
        */
    private static final String projectPath 
        = "/home/jose/jose15Sep16/AAAJOSEWORK/LastNetBeansProjects/eJVol1";
    //Source files are in SourcePackges with path /src
    //and the path to the folder with
    //java files is /java8totorial
    private static final String pathToSourceFiles 
            = projectPath + "/src/ejvol1";
    //Print to the console, output window,  of Netbeans?
    private static final boolean printToConsole = true;
    //Print to a .txt file?
    private static final boolean printToFile = true;
    //File in the same directory with java programs
    private static final String myOutputFile 
            = pathToSourceFiles +"/MyNetBeansProject.txt";
    
    private static List<File> filesInFolder;

    private static final StringBuffer myText 
            = new StringBuffer();


    

private static void printToConsoleFileNumberI(int i)
{
    String fileName = filesInFolder.get(i).getPath();
    try (Stream<String> stream 
            = Files.lines(Paths.get(fileName))) 
    {
        stream.forEach(System.out::println);

    } catch (IOException e) {
    }
}





private static void printFileNumberIToStringBuffer(int i)
{
    String fileName = filesInFolder.get(i).getPath();
    try (Stream<String> stream 
            = Files.lines(Paths.get(fileName))) 
    {
        stream.forEach(l 
                -> myText.append(l).append("\n")
        );

    } catch (IOException e) {
    }
    myText.append("\n\n\n:::::::::::::  "
            + "NEW PROGRAM  :::::::::::::\n\n\n");
}





public static void main(String[] args) 
        throws IOException 
{
    //Java 8 API by Example: Strings, 
    //Numbers, Math and Files
    //March 25, 2015
    //Benjamin Winterberg
    //http://winterbe.com/posts/2015/03/25/java8-examples-string-number-math-files/
    
    //Print the names of files of a 
    //directory to the console.
    //Use the output to know the path 
    //to the subdirectory with the Java files
    System.out.println("Files in given subdirectory");
    Files.walk(Paths.get(pathToSourceFiles))
        .filter(Files::isRegularFile)
        .forEach(System.out::println);

    
    
    //List with paths to files
    filesInFolder = Files.walk(Paths.get(pathToSourceFiles))
            .filter(Files::isRegularFile)
            .map(Path::toFile)
            .collect(Collectors.toList()); 
    
    

    //Files are printed to a stringBuffer
    IntStream.range(0, filesInFolder.size())
        .forEachOrdered((i) 
                    -> printFileNumberIToStringBuffer(i));
    
    if (printToConsole)
        //StringBuffer is printed to the console
        System.out.println(myText.toString());

        
    if (printToFile)
    {
        
        System.out.println(myText.toString());

        //StringBuffer is written to a file in the current directory 
        //How to Create New File in Java
        //January 20, 2015 by Lokesh Gupta
        //http://howtodoinjava.com/core-java/io/how-to-create-a-new-file-in-java/
        try (FileOutputStream out 
            = new FileOutputStream(myOutputFile)) 
        {
            out.write(myText.toString().getBytes());
        }   
    }
} 
    
}//End of main class Q65 PrintSourceFiles



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A146 TopDown2
//This program invokes some methods of another class
//in the same project and package.
package ejvol1;

public class TopDown2 
{
   
    public  static void main(String[] args)
    {        
        //A method of class TopDown is invoked 
        System.out.println("Invokation of another class"
                + " in the same project and package:");
        TopDown.task1();
        TopDown.task2();
        //?????
        //TopDown.task3();
    }
           
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A227 Die6
//We study the average of
//discrete dependent uniforms distributions,
//each one  with range from 1 to 9
//and mean 5.

package ejvol1;



import java.util.Random;

public class Die6
{
    // One can vary the number of trials,
    // by changing the variable length.
	
    static private int length;

	
    //The number of studied families is
    //nFamilies

    //Observed frequencies
    private static final double Obs[ ] = new double[9001]; 

    //Turn on of the random generator
    private static final Random r  = new Random();

    public static void main(String[] args)
    {

        //nUniforms = number of random variables.	
        // nUniforms can range from 1 to 1000
        int nUniforms = 10;
        int m = 9*nUniforms;

        for(int i = 1; i<= m; i++)
                Obs[i] = 0; //Initialization

        int factor = 5;
        length = m*factor;
        //Loop with many trials 
        for(int j = 1; j<= length ; j++)
        {
            
            double sum = 0;
            // We generate one random numbers
            //from 1 to 9
            int c = r.nextInt(9) +1;
            // and  make with it a sum with nUniforms terms:
            for(int k = 0; k< nUniforms; k++)
            {
                sum = sum + c;
            }
            double average = sum/nUniforms;
            int i = (int) average;
            
            //bookkeeping
            Obs[i] = Obs[i]+1;
        }
        System.out.println("Sums and their frequencies");
        for(int j = 1; j<= m; j++)
            System.out.println(j + "\t" + (int) Obs[j]); 		
    }
}//End of Program A227 Die6



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A225 Die5
//We study the average of
//discrete uniforms distributions,
//each one  with range from 1 to 9
//and mean 5.

package ejvol1;



import java.util.Random;

public class Die5
{
    // One can vary the number of trials,
    // by changing the variable length.
	
    static private int length;

	
    //The number of studied families is
    //nFamilies

    //Observed frequencies
    private static final double Obs[ ] = new double[9001]; 

    //Turn on of the random generator
    private static final Random r  = new Random();

    public static void main(String[] args)
    {

        //nUniforms = number of random variables.	
        // nUniforms can range from 1 to 1000
        int nUniforms = 10;
        int m = 9*nUniforms;

        for(int i = 1; i<= m; i++)
                Obs[i] = 0; //Initialization

        int factor = 5;
        length = m*factor;
        //Loop with many trials 
        for(int j = 1; j<= length ; j++)
        {
            // We generate nUniform random numbers
            //from 1 to 9
            double sum = 0;
            for(int k = 0; k< nUniforms; k++)
            {
                int c = r.nextInt(9) +1;
                // and we add them:
                sum = sum + c;
            }
            double average = sum/nUniforms;
            int i = (int) average;
            
            //bookkeeping
            Obs[i] = Obs[i]+1;
        }
        System.out.println("Sums and their frequencies");
        for(int j = 1; j<= m; j++)
            System.out.println(j + "\t" + (int) Obs[j]); 		
    }
}//End of Program A225 Die5



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A233 Equation

//Evolution of a population
//of strings that finds a root
//of a polynomial.

//Mutation + selection.

package ejvol1;

  

	
import java.util.Random;

public class Equation
{
    // Strings are at the same time
    // genotype and phenotype.

    // Pre-declaration of global variables.
    // They are used all throughout the whole class.
		
    // Individuals are kept in the array
    // Individual[]. It is an array of strings.
    // The number of individuals must be
    // less than limit

    private static final int POPSIZE = 100;
    static private double Fitness[];
    static private String Individual[ ];//Predeclaration
    // Order  is an array of integers.
    static private int Order[];//pre-declaration
    static private int Generation;
    static private int  nGen;
    static private int ReportMin[], ReportMax[];
    private  static int numberOfClones ;
    private static final double MUTATIONRATE = 0.2;
    private  static int Champ;

    // Turn on of the random generator
    private static final  Random RAND = new Random();
    private static final boolean  PRINT = false;

    // This method generates random chars
    // that represent digits
    private  static  Character  randomChar()
    {
        return  ( char ) ( RAND.nextInt( 10 ) + 48  );
    }


    private static void Initialization( )
    {
        /* We generate POPSIZE individuals (strings)
        Sequences are completely random */

        //Formal declaration of our array.	
        Individual= new String[POPSIZE];
        //System.out.PRINTln("ORIGINAL POPULATION");
        for(int i = 0; i< POPSIZE; i++)
        {
            //Initialization 	in blank.
            Individual[i]="";

            //An individual is assembled char by char		
            for(int j = 0; j<  9; j++)
            {
                // We generate a random numeric char
                Character c =  randomChar();
                //System.out.PRINTln( "char = " + c);
                // Char c is converted into a string s
                String s = c.toString();
                // s is concatenated to Individual[i]
                Individual[i] = Individual[i]+s;
            }
            // We add the place for a point.
            Character n =  randomChar();
            String s = n.toString();
            Individual[i] = s+Individual[i] ;

            //We add a sign: zero or one.
            n = (char) ( RAND.nextInt( 2 ) + 48  );
            s = n.toString();
            Individual[i] = s+Individual[i] ;
            //System.out.PRINT("Individual " +  i + "\t");
            // System.out.PRINTln( Individual[i]);
        }
	
	
        //Declarations and default initializations
	// of other arrays.
	
        Order= new int[POPSIZE];
        ReportMin= new int[POPSIZE];
        ReportMax= new int[POPSIZE];
        Fitness= new double[POPSIZE ];

        for(int i = 0; i< POPSIZE; i++)
        {
            Order[i]=0;
            ReportMin[i]=0;
            ReportMax[i]=0;
        }
    }
	
    //The encoded number is withdrawn
    private static double decoder(String s)
    {
        // We get the sign:
        char s1  =   s.charAt(0);
        int sign = Character.getNumericValue(s1);
        // We get the place of the point,
        // which implies multiples of ten.
        s1  =   s.charAt(1);
        int  point = Character.getNumericValue(s1);
        // We build the number with the other chars
        double number = 0;
        for(int j=2;j  <  11;j++ )
        {
            char s3  =   s.charAt(j);
            int  l = Character.getNumericValue(s3);	
            int k = j-1;
            int power = point-k;
            //number1 = l * 10^power
            double number1 =  l * Math.pow(10,power);
            number = number + number1;
        }
        if (sign == 0) return (-1) *number;
            else return  number;
    }

    //The method encodes the equation = 0 to solve.
    //Perfect solution must ne a root and output zero.
    //Other  numbers represents an error 
    private static double functionvalue(double b)
    {
        //Root = 0.75;
        return 4*b+3;	
        //Root = root = -4.71817809;	
        //return b*b*b*b*b + 4*b*b*b*b - 3*b*b*b + 2*b*b +b +1;
        //Root = 1;
        //return b*b - 2*b + 1;
    }

    
    //The fitness of each individual is calculated
    private static void fitness()
    {
       for(int i = 0; i< POPSIZE; i++)
        {
            // Individual[i] is a string,
            // it is a genotype.
            // b is a number: it is the phenotype
            double b = decoder(Individual[i]);
            double  fV = functionvalue(b);
            //Fitness(root) = 1
            //Others have Fitness less than 1
            Fitness[i] =    1/(1+fV * fV);
        }
    }
    
    
    //Strings are sorted by fitness	
    private static void Sorting()
    {
        
        fitness();
        
        for(int i = 0; i< POPSIZE;i++)
        {
            int champ = 0;
            for(int j = 0; j< POPSIZE; j++)
                if (Fitness[j] >= Fitness[champ])   champ = j;
            //The array Order classifies individuals by fitness.
            //The fittest, with less errors, go to the 0-th entry.
            Order[i] = champ;
            Fitness[champ] = 0;
        }
        
        
        String s = Individual[Order[0]];
        double b = decoder(s);
        double p = functionvalue(b);
        System.out.println("Gen = " + Generation + " best solution  = " 
        + b + " Error = " + p );
    }

    
    //The top   fill the world
    private  static void Cloning()
    {
        //Array to host cloned individuals
    String Individual2[ ] = new String[100]; 
    int   i=0;
    int   k=0;         //rank, 0 is the highest
    //Cloning
    while (i<POPSIZE)
    {
        int counter = numberOfClones;
        while ((counter>0) & (i<POPSIZE))
        {
            Individual2[i] = Individual[Order[k]];            
            i++;
            counter= counter-1;
        }
        k++;
    }

     
    //Cloned individuals become the official population
    for(int j = 0; j < POPSIZE; j++)
        Individual[j] = Individual2[j];
    if (PRINT) printPopulation();
    }
   
    private static void Reproduction()
    {
        //Individuals are sorted by fitness
        Sorting();
        //for(int i = 0; i<  10;i++)
        //System.out.PRINTln(  Individual(Order(i))

        //Fitest individuals are cloned
        Cloning();
    }

    
private static  String change(String a)
{
    for(int l = 0; l < a.length(); l++)
    {
        double s = RAND.nextDouble();
        if (s < MUTATIONRATE)
        {
            if (a.length()==1) return ""+randomChar();
            else
            {
                //In case of a ghost
                if ( (l<0) || (l > a.length()-1))
                {			
                     
                    return a;
                }
                a = a.substring(0, l) + randomChar()
                    +  a.substring(l + 1);	
            }
        }
    }
    return a;
}



    private static void Mutation()
    {
        for(int i=0; i < POPSIZE; i++)
       if (i != Champ) Individual[i] = change(Individual[i] );
    
    }
    


    private static void Dynamics()
    {
        //The top ten are allowed to  reproduce:
        //a child occupies the place of the shortest individual
        Reproduction();
        //The new population is subjected to mutation
        Mutation();        
    }


    private static void printPopulation()
    {
        //Cloned individuals become the official population
    for(int j = 0; j < POPSIZE; j++)
    {
         
        double b = decoder(Individual[j]);
        double  fV = functionvalue(b);
        double    myFitness =    1/(1+fV*fV);
        System.out.println( j + "  ->  "  + Individual[j] + "  ->  " +  myFitness);
        
    }
    System.out.println();
    }
    
    
    public static void main(String[] args)
    {	
        //To modify POPSIZE,
        // the method Copying()
        // must also be modified.
        Initialization( ) ;
        nGen = 400000;
        numberOfClones  = 10;
        //System.out.println("Root of 4*x + 3 = 0,  x = 0.75");
        for(int Gen = 0; Gen < nGen; Gen++)
        {	
            Generation = Gen;				
            Dynamics();
        } 						
    }
}//End of Program A233 Equation



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A111 Runs2
/* We study runs at random.
 We gauge the   number of trials
 that are necessary  to get for the first
 time  a run k units long, for varying k.
  */
package ejvol1;


import java.util.Random;

public class Runs2
{
    //Turning on of the random generator
    //Global declaration
    static Random r  = new Random();
			
    //This method throws coins
    //and returns the length of the first run.
    //That length might be a very large number,
    //so the output is encoded as long,
    //which is an integer of high capacity.
    private static long run()
    {
        // l is the landed face of a coin;
     	int l;
     	int runLength = 0;
     	// stop=1 says when a run gets   broken.
     	int stop = 0;
     	
     	while (stop == 0)
     	{
            l = r.nextInt(2);
            // Our runs must be of ones.
            if (l==1)
            {
                runLength = runLength + 1;
                //System.out.print( l);
            }
            else stop = 1;
     	}
     	//This is the report of the method
     	return runLength;
    }	
	 	
	
    //This method reports the number of
    //necessary trials to get for the first time
    //a run of the asked length.
    private static long tryAndTry(int askedLength)
    {						
        long runLength = 0;	
        long count =0;
         while (runLength < askedLength )
        {		
            count = count+1;
            runLength = run() ;
        }
        return  count;
    }
			
    // The askedLength is varied
    public static void main(String[] args)
    {
        int rounds = 20;
        for(int j = 1; j<= rounds; j++)
        {
            // We count the number of trials
            // that are necessary to get a run
            // askedLength units long.							
            int askedLength = j;	

            long count = tryAndTry(askedLength);
            System.out.println(askedLength  + "\t " +count);
        }
       }
    }//End of Program A111 Runs2



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A204 RandGenerator7
//Let us  count the number of boys in 
//a set of families in which the 
//probability of boy is p.
//Observed is compared to expected.

//This is a population study of 
//Bi(n,p) the binomial distribution
//on n families and probability of boy equal to p.

package ejvol1;


import java.util.Random;

public class RandGenerator7
{
    static private int n;
    static private double p;
	
    // The number of studied families is
    // nFamilies
	
    static private double nFamilies;
	
    // Turn on of the random generator
    static private Random r  = new Random();

    // Observed frequencies
    static private double Obs[ ];//Predeclaration
	
    // Expected frequencies
    static private double Exp[ ];//Predeclaration
	
	
    private  static void  expectedFrec()
    {
    for(int k=0; k<n; k++)
    {
        double nk = 1;	
        //Binomial coefficient
        for(int j=1; j<=k; j++)
                 nk = nk* (n-k+j)/j;
        System.out.println("Coefficient " + k + " \t " + nk);
        Exp[k]=  nk*Math.pow(p, k)*Math.pow(1-p,n- k);
        Exp[k]= Exp[k]*nFamilies;
     }
    
    }
	
    private  static void  chisquare()
    {
     double chi = 0;
     //length is int; 	
     for(int j = 0; j< n; j++)
      chi  = chi +  (Obs[j]-Exp[j])*(Obs[j]-Exp[j])/Exp[j];
     System.out.println("Number of families = "+ nFamilies);
     System.out.println("Number of children/family = "+ n);
     System.out.println("Observed chi-square = " + chi); 
     int df = n-2;
     System.out.println("Compare with chi.2 critical "
             + "with " + df + " degrees of freedom.");
    }
	
    public static void main(String[] args)
    {
        // number of children per family
        n= 6 ;
        // Probability of boy
        p = 0.5;
        //number of studied families
        nFamilies = Math.pow(2,n) * 10;
        // The observed distribution
        // is kept in Obs
        Obs= new double[(int) nFamilies]; //Declaration
        // The expected distribution
        // is kept in Exp
        Exp= new double[(int) nFamilies]; //Declaration

        for(int i = 0; i< n; i++)
                Obs[i] = 0; //Initialization

        for(int i = 0; i< n; i++)
                Exp[i] = 0; //Initialization

        // Total number of children


        // We generate nFamilies families
        for(int i = 0; i< nFamilies; i++)
        {		
            // We generate a random family.
            // nboys counts the number of boys
            int nBoys = 0;
            for(int j = 0; j< n; j++)
            {
                //We generate a random number
                // in within 0 and 1
                double  c = r.nextDouble();
                // We count boys
                if (c<p) nBoys = nBoys +1;
            }	
            Obs[nBoys] = Obs[nBoys]+1;
        }
        

        expectedFrec();
        System.out.println("Observed and Expected");
        for(int j = 0; j< n; j++)
             System.out.println(j + "\t" + Obs[j] + "\t" + Exp[j]);
        System.out.println();
       
        // We measure how good is the fitting
        // Greater chi-square values mean
        // worser fitting to a binomial distribution.
        chisquare();		
        }
}//End of Program A204 RandGenerator7



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A359 Family
//Keeps information about the bodies of
//the members of a family: wife, husband and child.
package ejvol1;

public class Family 
{
  
    Couple couple;
    Body child;
    
    Family(Couple c, Body b)
    {
        couple  = c;
        child = b;
    }    
    
    public static void main(String[] args)
    {
        Body bodyMary = new Body(1,2,3,4);
        Body bodyAlf= new Body(-1,-2,-3,-4);
        Couple c = new Couple(bodyMary, bodyAlf);
        
        Body bodyJr = new Body ( 11,12,13,14);
        
        Family f = new Family(c, bodyJr);
        Body.report("Mary", f.couple.wife);
        Body.report("Alf", f.couple.husband);
        Body.report("Jr", f.child);
    }
            
}//End of Prgram A359 Family



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A113 CosmicRays
/* We study a population of protons
    in the cosmic space
    that interacts with photons  by collisions.
    From a collision, a proton can gain
    else lose one quantum of energy.
    We are interested in knowing
    the trend of elongation of runs,
    i.e. of high energy,
    which might be similar to high complexity. */

package ejvol1;



	
import java.util.Random;

public class CosmicRays
{		
    // Pre-declaration of global variables.
    // They are used all throughout the whole class.
			
    // Protons are numbered and
    // their energy is  kept in the array
    // energy[].
    // The number of protons must be
    // less than limit
		
    static int limit = 2000;
    static int energy[ ];//Predeclaration
    // The population has
    // a constant number of protons:
    static int nProtons= 100 ;

    static int rounds ;

    // We keep track of the minimum and 	
    // maximum energy attained in the population
    static int ReportMin[], ReportMax[];


    // Turning on of the random generator
    static Random r  = new Random();

    /* We generate nProtons protons
        with no energy */
    private static void Initialization( )
    {			
        //Formal declaration of our arrays.	
        energy= new int[limit];
        ReportMin = new int[100001];
        ReportMax = new int[100001];
        for(int i = 1; i<= nProtons; i++)
        {
            ReportMin[i] = 0;
            ReportMax[i] = 0;
        }

        //System.out.println("ORIGINAL POPULATION");
        for(int i = 1; i<= nProtons; i++)
        {
            //Initialization 	in zero,		
            energy[i]=0;
        }
    }
	
		
    //For each generation, the min and max are recorded
    private static void Observation(int Gen)
    {			
        int m, Min, Max;

        Max = 0;
        Min = 1000000000;
        for(int j = 0; j< nProtons; j++)
        {
            m =  energy[j];
            /*System.out.println(  "The proton  "
                    + j + " has energy " + m); */
            if (m > Max)  Max = m;
            if (m < Min)   Min = m;
        }
        /* System.out.println(  "Generation " + Gen
         + " minEnergy = " + Min + " maxEnergy = " + Max); */
        ReportMin[Gen] = Min;
        ReportMax[Gen] = Max;
    }

    // This method  executes collisions	
    // among a finite number of protons
    // and abounding photons.
    private  static  void  dynamics(int gen)
    {
        for(int i = 0; i< nProtons; i++)
        {
            // proton i collides
            // with a photon.
            // The proton can gain
            // a quantum of energy
            // with probability 0.5
            // and can lose a quantum, if any,
            // with equal probability.

            int j = r.nextInt(2);
            if (j==1)			
               energy[i] = energy[i]+1;	
            else
                energy[i] = Math.max( energy[i]-1,0);	
            Observation(gen);
        }
    }
		

		
    //For the given generation, min and max numbers of
    //energy quanta among all protons is reported.
    public static void finalreport()		
    {
        System.out.println( "GEN, MIN and MAX VALUES");
        for(int Gen = 0; Gen < rounds; Gen++)
            System.out.println(Gen +"\t" +  ReportMin[Gen]
                        +"\t" +  ReportMax[Gen]);
    }
    
    
    //Initialization + dynamics
    public static void main(String[] args)
    {	
        // We seed a population of protons
        Initialization();
        // A round is a process in which
        // every proton collides once.
         rounds = 20000 ;	
        for(int i = 0; i < rounds; i++)
        {
            int gen = i;
            dynamics(gen);			
        }
            finalreport();	
    }
}//Program A113 CosmicRays



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A55 Replace
//Change of a period by a comma inside decimal numbers
package ejvol1;



public class Replace3
{		
    public static void main(String[] args)
    {
        String tab = "\t";
        String s1, s2,  s4, s5 ;

        for(double r1 = 1; r1<=2.05 ; r1= r1 + 0.05 )
        {
            double r2, r3 ;	
            r2= r1;
            

            //Conversion of   number r2 into the string s1
               s1 = String.valueOf(r2);	
            //Replacement in s1 of "." with ","	
            s2=s1.replace(".", ",");

            //Number r3 is the square of r1.
            r3= r1*r1;

           //conversion of number r3
           //into a string:
           s4 = String.valueOf(r3);
           //A period is replace by a comma
           s5=s4.replace(".", ",");
           //Report
           System.out.println(s2 + tab + s5);	
        }	
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A237 SelfSpoiler
//From time to time
//randomness betrays itself.
//We simulate a die with a uniform
//distribution, but in some cases,
//it generates data that
//do not fit a uniform distribution.
//The program reports:
//demanded length of a random sequence
//that does not fit a uniform distribution
//and
//the number of trials that were
//necessary to get such a sequence.

package ejvol1;



import java.util.Random;


public class SelfSpoiler
{
    // Turn on of the random generator
    static Random r  = new Random();
    // long is a very long integer
    static long trials ; // Number of trials.
    static int Observed[ ];//Predeclaration

    // The following is a chi2 table.
    // Signifcance 0.05.
    static double  Chi[]  = {
                            3.84,
                            5.99,
                            7.81,
                            9.48,
                            11.07,
                            12.59,
                            14.06,
                            15.5,
                            16.91,
                            18.30,
                            19.67,
                            21.02,
                            22.36,
                            23.68,
                            24.99,
                            26.29,
                            27.58,
                            28.86,
                            30.14,
                            31.41,
                            32.36,
                            33.92,
                            35.17,
                            36.41,
                            37.65,
                            38.88,
                            40.11,
                            41.33,
                            42.55,
                            43.77};
	
private static double  observedChisquare(int length, int nFaces)
{
    double chi = 0;

    //The die with five faces is associated to a distribution
    //that assigns a probability 1/5 to numbers 1 to 5.
    //Hence, a sequence  of landed faces
    //must have 1/5*length instances of each face.

    double Expected = length/nFaces;
    //Expected distribution is compared to observed one.
    //Discrepancy is approximately distributed 
    //as a chi square:
    for(int j = 1; j<= nFaces; j++)
        chi  = chi + (Observed[j]-Expected)
            *(Observed[j]-Expected)/Expected;
    //System.out.println("Observed chi-square = " + chi); 	
    return chi;
}	
	
	
public static void tryAndTry(int length, int nFaces)
 {
    // We count the number of trials
    //necessary to produce for the first
    // time a sequence that does not fit
    // a uniform distribution.
    trials = 0;

    // done = 1 is a flag that says
    //when we have succeeded
    int done = 0;

    while (done==0 )
    {
        trials = trials +1;
        //System.out.println(" Trial " + count);

        // Initialization
        for(int j = 1; j<= nFaces; j++)
            Observed[j] = 0;

        // We generate a random sequence	
        for(int j = 1; j<= length; j++)
        {
            // We choose a uniform distribution	
            // from 1 to nFaces, as in a die.
            int  c = r.nextInt(nFaces)+1;		
            //System.out.println(c ) ; 				
            //book keeping
            Observed[c] =Observed[c]+1;				
        }	

        // Report		
        // for(int j = 1; j<= nFaces; j++)
        //System.out.println(j + "\t" +Obs[j]);
        //We have succeed if
        // the distribution is not uniform.
        //Degrees of freedom: nFaces -1;
        //but Java counts from zero, hence
        int df = nFaces -2;
        /*System.out.println(chisquare(length,nFaces)
          + "\t "+ Chi[df]); */
        if (observedChisquare(length, nFaces) >= Chi[df])
        done = 1;				
    }		    		
 }
	
public static void main(String[] args)
{	
    //Number of faces, nFaces, of the die
    //must be less than 30.
    int nFaces = 6;
    // For each die, we generate
    // sequences of increasing length,
    // which is defined by length,
    // which is a multiple of nFaces.
    int rounds = 3000;		

    System.out.println("Length and trials to fail to be uniform"); 
    for(int j = 1; j<= rounds; j++)
    {
        //length =size of the random sequence			
        int length= nFaces*j;
        //Obs contains the frequency table.
        Observed = new int[51];
        //Let us make the simulation
        tryAndTry(length,nFaces);
        //System.out.println("Die with " + nFaces + " faces");
        //System.out.println("Sequences of length " + length);
        /* System.out.println("We succeed at the trial "
           + trials ); */
        	
        System.out.println(  length + "\t " + trials); 		
    }
}
}//End of Program A237 SelfSpoiler



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A142 TopDown
//Top-down approach
//to software design:
//a very fuzzy idea is conceived and written.


package ejvol1;

public class TopDown
{

    static public void subtask1()
    {
        System.out.println("I am subtask1");
    }


    static public void task1()
    {
        System.out.println("I am task 1");
        subtask1();
    }

    static public void task2()
    {
        System.out.println("I am task 2");
    }
	
    static private void task3()
    {
        System.out.println("I am task 3");	
    }
		
    public  static void main(String[] args)
    {
        // My general idea consists in three tasks
        task1();
        task2();
        task3();
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



package ejvol1;


//Program A271 Moths

/*
 Study of predation of moths by birds.
 Moths could be white or brown.
 Reproduction obeys a logistic model
 Two environments: clean and dirty.
 Discrete stochastic logistic model. 	
 */
	
import java.util.Random;

public class Moths
{
	
    static private int nwm, nbrm, nb ;
    static private double  mr;
    static private double  maxM, maxB, pwm, pbrm,bd;
    static private int max;
    static private int n;
    // Turn on of the random generator
    static private Random r  = new Random();
		
    public static void initialization()
    {
        //Generates   moths,
        //white moths
        nwm = 450;
        // brown moths
        nbrm = 450;
        //Generates 10 birds
        nb = 10;
        //Probability of moth's reproduction
        mr = 0.1;
        //Maximum number of Moths
        maxM = 2000;
        //Maximum number of Birds
        maxB = 20;
        //probability of predation on white moths
        pwm = 0.001;
        //probability of predation on brown moths
        pbrm = 0.001;
        //Probability of bird's death
        bd = 0.05;		
    }
	
	
    public static void dynamics()
    {
        for(int i = 0; i < n; i++)
        {			
            // White moths reproduce
            for(int j = 0; j< nwm; j++)
            {
                double s = r.nextDouble();
                if (s < mr * (1 - (nwm + nbrm) / maxM) )
                    nwm = nwm + 1;		
            }

            //Brown moths reproduce
            for(int j = 0; j < nbrm; j++)
            {
                double s = r.nextDouble();
                if (s < mr * (1 - (nwm + nbrm) / maxM) )
                    nbrm = nbrm + 1;		
            }

            //Moths are preyed, birds reproduce
            for(int l = 0; l < nb; l++)
            {		
                //White moths
                for(int j = 0; j < nwm; j++)
                {
                    double s = r.nextDouble();
                    // a white moth is predated
                    if (s < pwm) nwm = nwm - 1;
                    //birds reproduce
                    if ( s < 0.1 * pwm * (1 - nb / maxB))
                      nb = nb + 1;
                }
                //brown moths
                for(int j = 0; j < nbrm; j++)
                {
                    double s = r.nextDouble();
                    // a brown moth is predated
                    if (s < pbrm) nbrm = nbrm - 1;
                    //birds reproduce
                    if ( s < 0.1 * pbrm * (1 - nb / maxB))
                        nb = nb + 1;
                }		
            }

            
            //Birds die
            for(int j = 0; j < nb; j++)
            {
                double s = r.nextDouble();
                if (s < bd) nb = nb - 1;
            }

            System.out.println(i + "\t " +  nwm + "\t " 
                + nbrm + "\t " + nb);	
        }//end i for
    }
		
  
    public static void main(String[] args)
    {
        //We run n generations		
        n = 1000;
        System.out.println("time, white moths, brown moths and birds");
        initialization();
        dynamics();		
    }
}//End of Program A271 Moths



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A155 KeyPad2
//Dealing with exceptions.
//What to do when a number is demanded from the User
//but he writes a string that is not a number?

package ejvol1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; 

class KeyPad2 
{
    
    @SuppressWarnings("InfiniteRecursion")
    private static int readRadius()
    {
        //An int number will be inquired
        int r = 0;
        //Text to be captured
        String text; 
        //Tool to read
        BufferedReader br = new BufferedReader(
                new InputStreamReader(System.in)); 
        //Prompt for the User
        System.out.println("Write  the radius of a circle. "
                + "It must be and integer");
        try
        {
            //Input is read
            text = br.readLine(); 
            //OK if text is an integer
            r = Integer.parseInt(text); 
            
        }
        //If input is an integer, ignore this.
        //Otherwise, do this. 
        catch(IOException | NumberFormatException e)
        {
           //Repeat request
            r = readRadius();
        }  
        return r;
    }
    
    public static void main(String args[])
    {
        float PI = 3.1416f;
        System.out.println( "Click over the console." );
        int r= readRadius();
        System.out.println("Circle area is: " + PI*r*r );
        
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


//Program A51 Concatenation
//Concatenation of strings.

package ejvol1;

public class Concatenation
{
    
    public static void main(String[] args)
    {
        //  Declaration of type of variables.
        //  A declaration allots memory resources.
        String s1, s2, s3;
        //  Assignation
        s1 = "Java ";
        s2 = "for ";
        s3 = "biologists";
        //  Report to the console
        System.out.println(s1 + s2 +s3); //action		
        //  Declaration and assignment
        String s4 = s1+s2+s3;
        //Variation
        System.out.println(s4 + "!"); //action
    }

}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program 192 RandGenerator4
//Simulattion of a binomial distribution.

package ejvol1;


import java.util.Random;

public class RandGenerator4
{
    static Random r  = new Random();

    public static void main(String[] args)
    {
        // Probability of male
        double p = 0.3;

        for(int j = 0; j< 10; j++)
        {
            //We generate a random number
            //in within 0 and 1 
            //with a uniform distribution.
            double  c = r.nextDouble();
            //We verify gender
            if (c<p)
                System.out.println("A male is born");
            else
            System.out.println("A female is born");
        }
    }
}//Program 192 RandGenerator4



:::::::::::::  NEW PROGRAM  :::::::::::::



// Program 322 StatTest5
// An incomplete block design.
// Duplex method (see text).



package ejvol1;



import java.util.Random;


public class StatTest5
{
    //Study of an incomplete block design


    //Turn on  the random generator
    static Random r  = new Random(); 	

    static int freqTableC[] = new int[10001];
    static int freqTableR[] = new int[10001];
    static double help[] = new double[25];
    static  double meanProj;
    static  double deviationProj;
    static double M[][] = new double[4][4];
    static double means[] = new double[4];
    static double Fcolumns;
    static double Frows;

    
    public static void freqTableToZero()
    {
        for(int i = 0; i<=1000; i++)
        {
            freqTableC[i]= 0;
            freqTableR[i]= 0;
        }
    }

    
    public static void reportM( )
    {
        for(int i = 1; i<=3; i++)
        {
            for(int j = 1; j<=3; j++)
                System.out.print(  M[i][j] + " \t");
            System.out.println();
        }
        System.out.println();	
    }

    
    //Fills a 3x3 with random numbers
    //with a normal distribution
    //with mean 2.222
    //and standard deviation 1.483
    public static void randMatrix()
    {
        double s;
        for(int i = 1; i<=3; i++)
        {
            for(int j = 1; j<=3; j++)
            {
                s =  deviationProj * r.nextGaussian()
                        + meanProj;
                M[i][j]= s;
                //System.out.print(  M[i][j] + " \t");
            }
            //System.out.println();
        }
        //System.out.println();	
    }
		

public static void FF()
{
// reportM(mExp);
/*GSi Great  Square under treatment i =
 (\sum^{n_i}_{j=1}X_{ij})^2 */
double GS1 = Math.pow(M[1][1] + M[2][1]+M[3][1],2);
double GS2 = Math.pow(M[1][2] + M[2][2]+M[3][2],2);
double GS3 = Math.pow(M[1][3] + M[2][3]+M[3][3],2);
//System.out.println("GS1 "+ GS1);
//T= \sum^k_{i=1} \sum^{n_i}_{j=1} X_{ij}

/*GS= Great  Square =
(\sum^k_{i=1} \sum^{n_i}_{j=1} X_{ij})^2*/

double GS = Math.pow(M[1][1]+M[2][1]+M[3][1]+
M[1][2] +M[2][2] +M[3][2]+M[1][3]+M[2][3]
+M[3][ 3],2);


/*Among Columns SS =
 \sum^k_{i=1}\frac{GS_i}{ l_i}-\frac{GS}{N}.*/
double ACSS = (GS1 / 3 + GS2 / 3 + GS3 / 3) - GS /9;

/*Among columns DF =
Among columns degrees of freedom= k-1= 3-1=2.*/


/*Among columns Mean square=
 \frac{Among Columns SS}{Among columns DF}*/

double ACMS = ACSS / 2;


//The same but for rows or blocks


double BGS1 = Math.pow(M[1][1] + M[1][2]+M[1][3],2);
double BGS2 = Math.pow(M[2][1] + M[2][2]+M[2][3],2);
double BGS3 = Math.pow(M[3][1] + M[3][2]+M[3][3],2);

// System.out.println( "  BGS1 "+ BGS1);
/*Among Rows SS =
$\sum^k_{i=1}\frac{GS_i}{ k_i}-\frac{GS}{N}$ */

double ARSS = (BGS1/3 + BGS2/3 + BGS3/3) - GS/9;
// System.out.println( "ARSS " + ARSS);
/*Among rows DF=
Among rows degrees of freedom= l-1= 3-1=2.*/

/*Among rows Mean square=
  \frac{Among Rows SS}{Among rows DF}*/

double ARMS = ARSS / 2;
// System.out.println( "ARMS " +ARMS);

//Calculates the sum of the squares of   entries.


double UIK = Math.pow(M[1][ 1] ,2)
+ Math.pow(M[2][ 1] ,2)
+ Math.pow(M[3][ 1] ,2)+ Math.pow(M[1][ 2],2)
+ Math.pow(M[2][ 2],2)
+ Math.pow(M[3][ 2],2) + Math.pow(M[1][ 3] ,2)
+Math.pow( M[2][ 3] ,2) + Math.pow(M[3][ 3] ,2);


//Total SS=Total Sum of Squares=
//$\sum^k_{i=1}\sum^{n_i}_{j=1}[X_{ij}^2]-\frac{GS}{N}$

double TotalSS = UIK - GS / 9;
// System.out.println( "TotalSS " + TotalSS); //OK
//Error SS=error sum of squares=
//Total SS - Among columns SS -Among row SS

double ERRORSS = TotalSS - ACSS - ARSS;

//System.out.println( "ERRORSS " + ERRORSS);

//Error DF= Total DF - Among groups DF - Among rows DF
//=    8-2-2=4 .

//Error Mean square= \frac{Error SS}{error DF}

double EMS = ERRORSS / 4;
//System.out.println( "EMS " + EMS);
  Fcolumns = ACMS / EMS;
  Frows = ARMS / EMS;
//  System.out.println( Fcolumns  ); //OK	
// System.out.println( Frows  ); //OK

}
			
private static void reportFreqTable(int k)
{
    System.out.println( " i + Columns + Rows " );	
    int mc = 0;
    int mr = 0;
    int i = 1;
    while ((mc<k)| (mc < k))
    {			
     // System.out.println( "b "  );	
     mc = mc + freqTableC[i];
                             mr = mr + freqTableR[i];
    System.out.print (i+ "\t " + freqTableC[i] 
            + "\t " + freqTableR[i]);			 	


    /*System.out.println(i+ "\t " + freqTablec[i] +
     "\t " + mc + "\t "+ mr );	*/			
    System.out.println() ;
    i = i+1;
    }
}
		
		
// We copy the matrix into a vector
// The central entry is ignored.
// The code
// if (!(i==2)) |(!(j==2))
// means:
// if ( (it is false that (i =2))
// or (it is false that (j =2)))
// then do this and that
private static void meanVariance()
{			
    int  n =0;
    for(int i = 1; i<=3; i++)
    {
            for(int j = 1; j<=3; j++)
            {
                    if ((!(i==2)) |(!(j==2)) )
                    {
                            n = n +1;
                            help[n]= M[i][j];

                    }
            }			
    }
    //System.out.println( "count \t " + count);
    /*for(int i = 1; i<=count; i++)
        System.out.println( help[i]); */
    /* We calculate mean and deviation of the vector:
        Let us calculate the mean */
    double sum = 0;

    System.out.println( "n \t "+ n);

    for ( int i = 1; i <= n; i++ )
        sum = sum + help[i];
    double mean = sum / n;
        System.out.println( "Sum \t "+ sum);

    System.out.println( "Mean \t "+ mean);
    // Let us calculate the variance
    double sum2 = 0;
		
    for ( int i = 1; i <= n; i++ )
        sum2 = sum2 + (help[i]-mean)*(help[i]-mean);
    double var = sum2 / n;
    System.out.println( "Variance \t "+ var);
    meanProj = mean;
    deviationProj = Math.pow(var, 0.5);
    System.out.println( "Deviation \t "+ deviationProj);
    System.out.println();
}
		
    //Only the nonzero blocks matters
    // This is an incomplete design:
    // The central 0 is a provisional value:
    // it stands in the place of a hole and
    // it will be replaced by a random number.
    // To that aim, we calculate the mean
    // and variance of other data
    // to design the normal distribution
    // from which the random number will
    // be sampled.
    private static void initialization( )
    {		
        //The central 0 represents a hole and
        //will be is replaced by
        //a random number.
        final double mExp[][] = {{0,0,0,0},
                                {0,5,8,6},
                                {0,7,0,8},
                                {0,4,7,3},
                                };


        for(int i= 1; i<=3; i++)
                for(int j= 1; j<=3; j++)
                        M[i][j] = mExp[i][j];
        System.out.println( "Experimental matrix"  );
        System.out.println( "The central 0 is a hole"  );
        reportM();
        meanVariance();
    }
		
    private static void completing( )
    {
        M[2][2] = deviationProj *
             r.nextGaussian()+meanProj ;
    }
		
    public static void main( String args[])
    {
        // Definition of the exp matrix
        // calculation of projected values
        initialization();
        int n = 1000 ;
        freqTableToZero();
        // We build n matrixes, in which
        // the void entry is filled
        // with a random number
        // and the statistics are calculated.
        System.out.println( "Distribution of F values ");
        System.out.println( "for the refilled matrix");
        for(int k=1; k<=n;k++)
        {
            completing();
            FF();
            int d = (int)  Math.ceil(  Fcolumns);
            freqTableC[d]=freqTableC[d]+1;
            d = (int)  Math.ceil(  Frows);
            freqTableR[d]=freqTableR[d]+1; 			
        }

        int k =n;
        reportFreqTable(k);

        freqTableToZero();

        //We generate n random matrixes
        // filled in numbers that
        // follow a normal distribution
        // with mean meanProj and
        // deviation deviationProj
        System.out.println( "Distribution of F values ");
        System.out.println( "for the random  matrix");
        for(int i=1; i<=n;i++)
        {			
            randMatrix();	
            // reportM(M);			
            //System.out.println( i + "\t " + "F = \t " + F());
            FF();
            int d = (int)  Math.ceil(  Fcolumns);
            freqTableC[d]=freqTableC[d]+1;
            d = (int)  Math.ceil(  Frows);
            freqTableR[d]=freqTableR[d]+1;
        }
        k =n;
        reportFreqTable(k);
        // We calculate the F's for the experiment

        /* What does Math.ciel do?
         int d = (int)  Math.ceil(  1.2);
         System.out.println( d);
         d = (int)  Math.ceil(  1.7);
         System.out.println( d); */
       }
}//End of Program 322 StatTest5



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A121 Chars
//Strings 4 char long
package ejvol1;


import java.util.Random;

public class Chars
{
   public static void main( String args[] )
   {
        //We turn on the random generator:
        Random r  = new Random(); 	
        for(int j= 0; j<20; j++)
        {
            for(int i= 0; i<4; i++)
            {
                //Random lower char
                char ch =   ( char ) ( r.nextInt( 26 ) + 97 );
                System.out.print (ch);
            }
            System.out.println();
        }
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



// Program A354a Hand
// We define Hand as a prototype, as an object.
// It functions as a new  Java type.

package ejvol1;



public class Hand
{
		
 	
    /*The object Hand keeps the information
    of the lengths of
    the forefingerLength and the thumbLength */

    int forefingerLength;
    int thumbLength;
	
    // Constructor:
    // method that specifies how
    // a specific object acquires information.
	
    // A method is overloaded when its function
    // is implemented in various ways.
	
    // Hand has an overloaded constructor:
          
    
    //Void initialization to be filled in later
    public   Hand( )
    {

    }
	
    // Information is acquired
    // by an ordinary list
    public   Hand( int a, int b)
    {
        this.forefingerLength = a;
        thumbLength = b;
    }

    //Information is acquired
    //from structured data:
    public   Hand(Hand hand1)
    {
        forefingerLength = hand1.forefingerLength;
        thumbLength = hand1.thumbLength;
    }

    // An object may contain methods
    // that are specific to it.
    public void initialization()
    {
        // fake, symbolic initialization.
        forefingerLength = -5; 
        thumbLength = -3;
    }
}//End of Program A354a Hand



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A109 Runs
/* We study random runs
 of a distinguished face of a coin.
  */
package ejvol1;


import java.util.Random;

public class Runs
{
    //Turning on of the random generator
    //This declaration is prior to any method,
    //it is global definition and covers
    //All methods.
    static Random r  = new Random();
	
    public static void main(String[] args)
    {
        // Number of trials
        int trials = 10;
        System.out.println( "Length of runs");
        for(int i = 1; i<= trials; i++)
        {
            // l is the landed face of a coin;
            int l;
            int runLength = 0;
            // stop = 1 says when a run gets   broken.
            int stop = 0;

            while (stop == 0)
            {
                // a coin is thrown
                l = r.nextInt(2);
                //System.out.println( l);
                // Our runs must be of ones.
                if (l==1)
                {
                    runLength = runLength + 1;
                   
                }
                else stop = 1; //break the loop
            }
            //System.out.println( );
            System.out.println("   " +  i + "\t" + runLength);
            }
        }
}//End of Program A109 Runs



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * Program A17 ArithmeticsWithInt
 * Integer arithmetic operations.
 */
package ejvol1;


public class ArithmeticsWithInt 
{		
 public static void main(String[] args)
  {
	//Declaration and initialization
	// of variables
	int x = 7;
	int y = 2;
	//Computation
	int result1  = x*y;
	int result2  = x/y;
	int result3  = x-y;
	// Report
	System.out.print(" The multiplication of x =" + x );
	System.out.println( " and  y = " + y + " is " + result1);
	System.out.print(" The integer division of x =" + x );
	System.out.println( " by  y = " + y + " is " +  result2);
	System.out.print("  x =" + x );
	System.out.println( " minus  y = " + y + " is " + result3);	
  }	
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program   A11  PrintMyName
//This program  prints my name and birthday
//to the console.

//Package declaration
package ejvol1;


//Class declaration
public class PrintMyName
{	
    //The next is the main method
    public static void main(String[] args)
    {	
        System.out.println("I am JB, the Intelligent! ");
        System.out.println("My birthday: March the 5th! ");
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A201 RandGenerator6
//Binomial dist with a test to study
//the asymptotic problem.

package ejvol1;

import java.util.Random;

public class RandGenerator6
 {
	static Random r  = new Random();

	static double nTotal;
	
//Statistical test to see
//the fairness of the simulation		
public static void test(int Males, double p)
{
    //Statistical Z-test to see
    //the fairness of the simulation
    //Square root of p * (1 - p) / 1000
    double  sigmaP= Math.pow( (p * (1 - p)/1000), 0.5);
    double M = Males;
    double zObserved = (M/1000 - p) / sigmaP;
    System.out.println("The z of the experiment is " 
            + zObserved );
    double  s = 1.96;
    System.out.println("The critical z is   " + s);
    String A ;
    //Absolute value of zObserved
    if (Math.abs(zObserved ) < s)  A = "Yes";
      else A = "No";
    System.out.println( "Is the generator fair?  " + A);
}
	
 public static void main(String[] args)
 {
	// Probability of male
	double p = 0.2;
	int numberMales =0;
	nTotal = 60;
	for(int j = 0; j< nTotal; j++)
	{
	 //We generate a random number
	 // in within 0 and 1
	 double  c = r.nextDouble();
	 // We verify gender
	 if (c<p) numberMales  = numberMales +1;	
	}
	System.out.println("Males: " + numberMales );
    System.out.println("Females: " + (nTotal-numberMales));
    test(numberMales,p);
		}
}////End of Program 201 RandGenerator6



:::::::::::::  NEW PROGRAM  :::::::::::::



// Program A264 LotkaVolterra3
// Study  of a prey-predator system.
// Lotka-Volterra equations.
// Stochastic model.

package ejvol1;

import java.util.Random;


public class LotkaVolterra3
{
    static int  nr, nw;
    static double e,rr,p,wr,wd;
	
    //Turn on of the random generator
    static Random r  = new Random();
		
    public static void initialization()
    {
        //Generates 500 rabbits,  50 wolfs
        nr = 500;
        nw = 50;
        //Rate of rabbit's reproduction
        rr = 0.1;
        //Rate of predation
        p = 0.01;
        //Rate of wolf's death
        wd = 0.05;
        // Rate of wolf's reproduction
        wr = 0.7 * p ;
        //Titles
    }
	
    public static void dynamics()
    {
        //We run n generations		
        int  n = 2000;
        for(int i = 0; i < n; i++)
        {
            //Rabbits reproduce
            for(int j = 0; j < nr; j++)
            {
                // The process of reproduction
                // is ruled by a binomial
                // random variable m
                double s = r.nextDouble();
                if (s < rr) nr = nr + 1;
            }
            //Rabbits are preyed, wolfs reproduce
            //Binomial random variables:
            //an encounter may or may not
            //produce a chase.
            for(int l = 0; l < nw; l++)
            {
                for(int j = 1; j < nr; j++)
                {
                    double s = r.nextDouble();
                   // a rabbit is predated
                    if (s < p) nr = nr - 1;
                    // a wolf is born
                    if (s < wr)  nw = nw + 1;
                }
            }
            //Wolfs die
            for(int j = 0; j < nw; j++)
            {
                double s = r.nextDouble();
                if (s < wd)  nw = nw - 1;
            }		
            System.out.println(i + "\t" + nr + "\t " + nw);
        }
    }
		
    public static void main(String[] args)
    {
        initialization();
        System.out.println("time, rabits and wolfs");
        dynamics();
    }
}//End of Program A264 LotkaVolterra3



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A235 Equation2

//Evolution of a population
//of strings that finds a root
//of a polynomial.

//Mutation + recombination + selection.

package ejvol1;

	
import java.util.Random;

public class Equation2
{
    // Strings are at the same time
    // genotype and phenotype.

    // Pre-declaration of global variables.
    // They are used all throughout the whole class.
		
    // Individuals are kept in the array
    // Individual[]. It is an array of strings.
    // The number of individuals must be
    // less than limit

    private static final int POPSIZE = 100;
    static private double Fitness[];
    static private String Individual[ ];//Predeclaration
    // Order  is an array of integers.
    static private int Order[];//pre-declaration
    static private int Generation;
    static private int  nGen;
    static private int ReportMin[], ReportMax[];
    private  static int numberOfClones ;
    private static final double MUTATIONRATE = 0.2;
    private  static int Champ;

    // Turn on of the random generator
    private static final  Random RAND = new Random();
    private static final boolean  PRINT = false;

    // This method generates random chars
    // that represent digits
    private  static  Character  randomChar()
    {
        return  ( char ) ( RAND.nextInt( 10 ) + 48  );
    }


    private static void Initialization( )
    {
        /* We generate POPSIZE individuals (strings)
        Sequences are completely random */

        //Formal declaration of our array.	
        Individual= new String[POPSIZE];
        //System.out.PRINTln("ORIGINAL POPULATION");
        for(int i = 0; i< POPSIZE; i++)
        {
            //Initialization 	in blank.
            Individual[i]="";

            //An individual is assembled char by char		
            for(int j = 0; j<  9; j++)
            {
                // We generate a random numeric char
                Character c =  randomChar();
                //System.out.PRINTln( "char = " + c);
                // Char c is converted into a string s
                String s = c.toString();
                // s is concatenated to Individual[i]
                Individual[i] = Individual[i]+s;
            }
            // We add the place for a point.
            Character n =  randomChar();
            String s = n.toString();
            Individual[i] = s+Individual[i] ;

            //We add a sign: zero or one.
            n = (char) ( RAND.nextInt( 2 ) + 48  );
            s = n.toString();
            Individual[i] = s+Individual[i] ;
            //System.out.PRINT("Individual " +  i + "\t");
            // System.out.PRINTln( Individual[i]);
        }
	
	
        //Declarations and default initializations
	// of other arrays.
	
        Order= new int[POPSIZE];
        ReportMin= new int[POPSIZE];
        ReportMax= new int[POPSIZE];
        Fitness= new double[POPSIZE ];

        for(int i = 0; i< POPSIZE; i++)
        {
            Order[i]=0;
            ReportMin[i]=0;
            ReportMax[i]=0;
        }
    }
	
    //The encoded number is withdrawn
    private static double decoder(String s)
    {
        // We get the sign:
        char s1  =   s.charAt(0);
        int sign = Character.getNumericValue(s1);
        // We get the place of the point,
        // which implies multiples of ten.
        s1  =   s.charAt(1);
        int  point = Character.getNumericValue(s1);
        // We build the number with the other chars
        double number = 0;
        for(int j=2;j  <  11;j++ )
        {
            char s3  =   s.charAt(j);
            int  l = Character.getNumericValue(s3);	
            int k = j-1;
            int power = point-k;
            //number1 = l * 10^power
            double number1 =  l * Math.pow(10,power);
            number = number + number1;
        }
        if (sign == 0) return (-1) *number;
            else return  number;
    }

    //The method encodes the equation = 0 to solve.
    //Perfect solution must ne a root and output zero.
    //Other  numbers represents an error 
    private static double functionvalue(double b)
    {
        //Root = 0.75;
        return 4*b+3;	
        //Root = root = -4.71817809;	
        //return b*b*b*b*b + 4*b*b*b*b - 3*b*b*b + 2*b*b +b +1;
        //Root = 1;
        //return b*b - 2*b + 1;
    }

    
    //The fitness of each individual is calculated
    private static void fitness()
    {
       for(int i = 0; i< POPSIZE; i++)
        {
            // Individual[i] is a string,
            // it is a genotype.
            // b is a number: it is the phenotype
            double b = decoder(Individual[i]);
            double  fV = functionvalue(b);
            //Fitness(root) = 1
            //Others have Fitness less than 1
            Fitness[i] =    1/(1+fV * fV);
        }
    }
    
    
    //Strings are sorted by fitness	
    private static void Sorting()
    {
        
        fitness();
        
        for(int i = 0; i< POPSIZE;i++)
        {
            int champ = 0;
            for(int j = 0; j< POPSIZE; j++)
                if (Fitness[j] >= Fitness[champ])   champ = j;
            //The array Order classifies individuals by fitness.
            //The fittest, with less errors, go to the 0-th entry.
            Order[i] = champ;
            Fitness[champ] = 0;
        }
        
        
        String s = Individual[Order[0]];
        double b = decoder(s);
        double p = functionvalue(b);
        System.out.println("Gen = " + Generation + " best solution  = " 
        + b + " Error = " + p );
    }

    


    
    //The top   fill the world
    private  static void Cloning()
    {
        //Array to host cloned individuals
    String Individual2[ ] = new String[100]; 
    int   i=0;
    int   k=0;         //rank, 0 is the highest
    //Cloning
    while (i<POPSIZE)
    {
        int counter = numberOfClones;
        while ((counter>0) & (i<POPSIZE))
        {
            Individual2[i] = Individual[Order[k]];            
            i++;
            counter= counter-1;
        }
        k++;
    }

     
    //Cloned individuals become the official population
    for(int j = 0; j < POPSIZE; j++)
        Individual[j] = Individual2[j];
    if (PRINT) printPopulation();
    }
   
    private static void Reproduction()
    {
        //Individuals are sorted by fitness
        Sorting();
        //for(int i = 0; i<  10;i++)
        //System.out.PRINTln(  Individual(Order(i))

        //Fitest individuals are cloned
        Cloning();
    }

    
private static  String change(String a)
{
    for(int l = 0; l < a.length(); l++)
    {
        double s = RAND.nextDouble();
        if (s < MUTATIONRATE)
        {
            if (a.length()==1) return ""+randomChar();
            else
            {
                //In case of a ghost
                if ( (l<0) || (l > a.length()-1))
                {			
                     
                    return a;
                }
                a = a.substring(0, l) + randomChar()
                    +  a.substring(l + 1);	
            }
        }
    }
    return a;
}



    private static void Mutation()
    {
        for(int i=0; i < POPSIZE; i++)
       if (i != Champ) Individual[i] = change(Individual[i] );
    
    }
    



     
private static String recombinant(int i)
{ 	      
    //A partner for i is found    
    int j = RAND.nextInt(POPSIZE);
    //A place for recombination
    int lengthI =  Individual[i].length();
    int lengthJ =  Individual[j].length();
    int minLength = Math.min(lengthI,lengthJ);
    int place = RAND.nextInt(minLength);
    String recombinant = Individual[i].substring(0, place)
            + Individual[j].substring(place);
    /*
    System.out.PRINTln( "Inputs = " + Individual[i] 
            + "    " + Individual[j]
    + " Recombinant = " + recombinant);
    */
    return recombinant;   
}


//Two strings are taken as input 
//and one recombinant is produced
private static void Recombination()
{ 	
    
    
    //Array with recombinant individuals
    String Individual2[ ] = new String[100]; 
    for(int i = 0; i< POPSIZE; i++)
    {
        Individual2[i] = recombinant(i);
    }
    //Recombinants become the official population
    for(int i = 0; i< POPSIZE; i++)
    {
        Individual[i] = Individual2[i];
    }
    
}


    private static void Dynamics()
    {
        //The top ten are allowed to  reproduce:
        //a child occupies the place of the shortest individual
        Reproduction();
        //The new population is subjected to mutation
        Mutation();
        //Recombination();
    }


    private static void printPopulation()
    {
        //Cloned individuals become the official population
    for(int j = 0; j < POPSIZE; j++)
    {
         
        double b = decoder(Individual[j]);
        double  fV = functionvalue(b);
        double    myFitness =    1/(1+fV*fV);
        System.out.println( j + "  ->  "  + Individual[j] + "  ->  " +  myFitness);
        
    }
    System.out.println();
    }
    
    
    public static void main(String[] args)
    {	
        //To modify POPSIZE,
        // the method Copying()
        // must also be modified.
        Initialization( ) ;
        nGen = 400000;
        numberOfClones  = 10;
        //System.out.println("Root of 4*x + 3 = 0,  x = 0.75");
        for(int Gen = 0; Gen < nGen; Gen++)
        {	
            Generation = Gen;				
            Dynamics();
        } 						
    }
}//End of Program A235 Equation2



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A248 Markov3
//Markov Chains
//There is a rapid convergence to the equilibrium state.

package ejvol1;

import java.util.Random;

/**
 *
 * @author jose
 */
public class Markov3 
{
    
    static int X[] = new int[3000];
    //Probabilities
    static double  pa,paa,pb,pbb;
	
    //Turn on of the random generator
    static Random r  = new Random();
		
//Define probabilities of transition	
public static void initialization()
{		
    //Independent probabilties
    paa = 0.8;
    pbb = 0.7;
    // initial conditions
    pa = 0.25;
    pb = 0.75;
}
		
 public static void main(String[] args)
 {
    initialization();
    // Generation of 3000 individuals
    // some of type a other of type b
    int na = 0;
    int  nb = 0;
    for(int i = 0; i< 3000; i++)
    {
        double s = r.nextDouble();
        if (s < pa)  na = na + 1;		
         else nb = nb + 1;
    }	
				
			
    //Report the number of individuals in each state
    System.out.println("Initial condition");
    System.out.println("The number of individuals in " +
                        "state a is  " + na);
    System.out.println("The number of individuals in " +
                        "state b is  " + nb);
    
    System.out.println("Generation,    populations in "
                                    +"states A and    B  " );
 
    //Execute 1000 transitions
    for(int i = 0; i< 100;i++)
    {
        //Decide whether or not an individual
        //in state a must make a transition
        for(int j= 1; j<=na;j++)
        {
            double s = r.nextInt();
            if (s < paa)
            {	
                na = na - 1;
                nb = nb + 1;
            }
        }
				
        //Decide whether or not an individual
        // in state b must make a transition
        for(int j= 1; j<=nb;j++)
        {
            double s = r.nextDouble();
            if (s < pbb)
            {	
                nb = nb - 1;
                na = na + 1;
            }
        }	
        System.out.println( i + "\t"    + na + "\t"   + nb); 
    }    
    System.out.println("Final condition");
    System.out.println("The number of individuals in " +
                         "state a is  " + na);
    System.out.println("The number of individuals in " +
                        "state b is  " + nb);
   
}    
}//Program A248 Markov3



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A167 HardDisc3
//This program reads a  file in format .txt
//and displays its content.
        
package ejvol1;


import java.io.File;
import java.io.FileNotFoundException;
import java.util.NoSuchElementException;
import java.util.Scanner;



public class  HardDisc3
{
    private static  Scanner input;

    // We open a file
    public  static  void openFile()
    {
        //try and catch pair
        try
        {
            input = new Scanner( new File( "Numbers2.txt" ) );
        }
        catch ( FileNotFoundException fileNotFoundException )
        {
            System.err.println( "File does not exists." 
            + fileNotFoundException.getMessage());
            System.exit( 1 );
        }
    }

    
    // We read  record from file
    public  static  void readData()
    {	
        //try and catch pairs
        try
        {
            while ( input.hasNext() )
            {

                
                for(int i = 0; i< 1;i++)
                {        	
                    String t = input.next();
                    String s = input.next();
                    System.out.println(t + "\t" +s);
                }
            }
        }
        
        catch ( NoSuchElementException elementException )
        {
            System.err.println( "File is corrupted." 
            + elementException.getMessage());
            input.close();
            System.exit( 1 );
        }
        catch ( IllegalStateException stateException )
        {
            System.err.println( "Reading aborted."
            + stateException.toString());
            System.exit( 1 );
        }
     }


    // We close file and terminate application
    public static void closeFile()
    {
       if ( input != null )
          input.close(); //
    }

    public static void main(String[] args)
    {
       openFile();
       readData();
       closeFile();
    }
}//End of Program A167 HardDisc3



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A46 ForLoop6
// Variation of the for statement.
package ejvol1;


public class ForLoop6
{		
    public static void main(String[] args)
    {	
        String tab = "\t";			
            for(int i = 0; i<=100 ; i= i + 7 )
            {	
                System.out.println(i + tab + 1000 * i);
            }
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



// Program 342 Drawing2
// Two rectangles  and a line.

package ejvol1;

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;

public class Drawing2 extends Applet
{
    private static final long serialVersionUID = 1L;

    @Override
    public void paint (Graphics g)
    {
        g.setColor(Color.blue);
        //Initial and final points.
        g.drawLine(10,200,270,150);
        // A Rectangle is defined by
        // the coordinates of the
        // superior right corner,
        // width and hight.
        g.drawRect(10,15,100,100);
        g.fillRect(150,15,100,100);
        g.setColor(Color.red);
        // An ovale is defined by the
        // rect that encloses it.
        g.fillOval(150,20,20,20);
    }
}//End of Program 342 Drawing2



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A153 KeyPad
//We read and process data from the keypad.


package ejvol1;



import java.io.*;
import java.util.Scanner;


public class KeyPad
{
    public  static void main(String[] args) 	
            throws IOException
    {
        System.out.println( "Click over the console." );
        System.out.println( "Write something " );
        System.out.println( "and close with enter!" );
        //Service to read
        Scanner scan= new Scanner(System.in);
        //Read a line from the console
        String text= scan.nextLine();
        System.out.println("This is what you typed: "  
                + text);
        System.out.println( "Write a number " );
        //Read an int from the console
        int num1 = scan.nextInt();
        System.out.println( "Write another number " );
        int num2 = scan.nextInt();
        System.out.println(num2);
        int sum = num1 + num2;
        System.out.println(  num1 + " + "
                +  num2 + "  = " + sum);    
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



// Program 314 StatTest4
// Study of an anova design with blockage.
// Normally distributed random variables
// with given mean and deviation.



package ejvol1;



import java.util.Random;


public class StatTest4
{
    //	Turn on  the random generator
    static Random r  = new Random(); 	

    static int freqTableC[] = new int[10001];
    static int freqTableR[] = new int[10001];
    static  double meanProj ;
    static  double deviationProj ;
    static double M[][] = new double[4][4];
    static double means[] = new double[4];	
    static double Fcolumns  ;
    static double Frows ;

    
    public static void freqTableToZero()
    {
        for(int i = 0; i<=1000; i++)
        {
            freqTableC[i]= 0;
            freqTableR[i]= 0;
        }
    }

    
    public static void reportM( )
    {
        for(int i = 1; i<=3; i++)
        {
            for(int j = 1; j<=3; j++)
            	System.out.print(  M[i][j] + " \t");
            System.out.println();
        }
        System.out.println();	
    }
	
//	Fills a 3x3 with random numbers
//	with a normal distribution
//	with mean 2.222
//	and standard deviation 1.483
public static void randMatrix()
{
    double s;
    for(int i = 1; i<=3; i++)
    {
        for(int j = 1; j<=3; j++)
        {
            s=  deviationProj * r.nextGaussian()+meanProj;
            M[i][j]= s;
            //System.out.print(  M[i][j] + " \t");
        }
        //System.out.println();
    }
    //System.out.println();	
}
		
// reportM(mExp);
public static void FF()
{   
    
/*GSi Great  Square under treatment i =
(\sum^{n_i}_{j=1}X_{ij})^2 */
double GS1 = Math.pow(M[1][ 1] + M[2][ 1] + M[3][ 1], 2);
double GS2 = Math.pow(M[1][ 2] + M[2][ 2]+ M[3][ 2], 2 );
double GS3 = Math.pow(M[1][ 3] + M[2][ 3] + M[3][ 3], 2);
//System.out.println("GS1 "+ GS1);
//T= \sum^k_{i=1} \sum^{n_i}_{j=1} X_{ij}

/*GS= Great  Square =
(\sum^k_{i=1} \sum^{n_i}_{j=1} X_{ij})^2 */

double GS = Math.pow(M[1][1]+M[2][1]+M[3][1]+M[1][2]
            +M[2][2]+M[3][2]+M[1][3]+M[2][3]+M[3][ 3],2);

int n = 8;
//Among Columns SS =   \sum^k_{i=1}\frac{GS_i}{ l_i}
//                                          -\frac{GS}{N}.
double ACSS = (GS1 / 3 + GS2 / 3 + GS3 / 3) - GS /9;

//Among columns DF= Among columns degrees
//of freedom= k-1= 3-1=2.
//int ACDF = 2;

/*Among columns Mean square=
\frac{Among Columns SS}{Among columns DF}*/

double ACMS = ACSS / 2;


//The same but for rows or blocks


double BGS1 = Math.pow(M[1][ 1] + M[1][ 2] + M[1][ 3],2) ;
double BGS2 = Math.pow(M[2][ 1] + + M[2][ 2]+ M[2][ 3],2);
double BGS3 = Math.pow(M[3][ 1] + M[3][ 2] + M[3][ 3],2) ;
// System.out.println( "  BGS1 "+ BGS1);
//Among Rows SS = $\sum^k_{i=1}\frac{GS_i}
//{ k_i}-\frac{GS}{N}$

double ARSS = (BGS1 / 3 + BGS2 / 3 + BGS3 / 3) - GS / 9;
// System.out.println( "ARSS " + ARSS);
//Among rows DF= Among rows degrees of freedom= l-1= 3-1=2.

//Among rows Mean square=\frac{Among Rows SS}{Among rows DF}

double ARMS = ARSS / 2;
// System.out.println( "ARMS " +ARMS);

//Calculates the square of each entry and sums.


double UIK = Math.pow(M[1][ 1] ,2)+ Math.pow(M[2][ 1] ,2)
       + Math.pow(M[3][ 1] ,2)+ Math.pow(M[1][ 2],2)
       + Math.pow(M[2][ 2],2)
       + Math.pow(M[3][ 2],2) + Math.pow(M[1][ 3] ,2)
       +Math.pow( M[2][ 3] ,2) + Math.pow(M[3][ 3] ,2);


//Total SS=Total Sum of Squares=
//$\sum^k_{i=1} \sum^{n_i}_{j=1}[X_{ij}^2]-\frac{GS}{N}$

double TotalSS = UIK - GS / 9;
// System.out.println( "TotalSS " + TotalSS); //OK
//Error SS=error sum of squares=
//Total SS - Among columns SS -Among row SS

double ERRORSS = TotalSS - ACSS - ARSS;

//System.out.println( "ERRORSS " + ERRORSS);

//Error DF= Total DF - Among groups DF - Among rows DF
//=    8-2-2=4 .
//Error Mean square= \frac{Error SS}{error DF}

double EMS = ERRORSS / 4;
//System.out.println( "EMS " + EMS);
Fcolumns = ACMS / EMS;
Frows = ARMS / EMS;
//  System.out.println( Fcolumns  ); //OK	
// System.out.println( Frows  ); //OK

}
			
private static void reportFreqTable(int k)
{
    System.out.println( " F + freqTableColumns "
            + "+ freqTableRows " );	
    int mc = 0;
    int mr = 0;
    int i = 1;
    while ((mc<k)| (mc < k))
    {			
        // System.out.println( "b "  );	
        mc = mc + freqTableC[i];
        mr = mr + freqTableR[i];
        System.out.print(i+ "\t " + freqTableC[i] 
                + "\t " + freqTableR[i]);			 		
        //System.out.println(i+"\t "+freqTablec[i]
        //+"\t"+mc+"\t"+mr);				
        System.out.println() ;
        i = i+1;
    }
}

private static void FExp( )
{
    // Only the non zero blocks matters

    final double mExp[][] = {{0,0,0,0},
                            {0,5,8,6},
                            {0,7,10,8},
                            {0,4,7,3},
                            };
    for(int i= 1; i<=3; i++)
        for(int j= 1; j<=3; j++)
            M[i][j] = mExp[i][j];
    FF();
    System.out.println( "Experimental matrix"  );
    reportM();
    System.out.println( "Fcolumns " + Fcolumns  );  	
    System.out.println("Frows " +   Frows  );  					

}
		
// Definition of projected values
public static void main( String args[])
{		
    meanProj = 6.444;
    deviationProj = 2.1858;
    freqTableToZero();
    int n = 1000 ;
   //We generate n random matrixes
    // filled in numbers that
    // follow a normal distribution
    // with mean meanProj and
    // deviation deviationProj
    for(int i=1; i<=n;i++)
    {			
        randMatrix();	
        //reportM(M);			
        //System.out.println(i+"\t " + "F = \t " + F());
        FF();
        int d = (int)  Math.ceil(  Fcolumns);
        freqTableC[d]=freqTableC[d]+1;
        d = (int)  Math.ceil(  Frows);
        freqTableR[d]=freqTableR[d]+1;
    }
    int k =n;
    reportFreqTable(k);
    // We calculate the F's for the experiment
    FExp();
    /* What does Math.ciel do?
    int d = (int)  Math.ceil(  1.2);
    System.out.println( d);
    d = (int)  Math.ceil(  1.7);
    System.out.println( d); */
 }
}//End of Program A 314 StatTest4



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A218 Die2
//Mimicking a die of 5 faces
//with a die of 6 faces.

package ejvol1;


import java.util.Random;


public class Die2
{	
    //Turn on of the random generator
    static Random r  = new Random();
    //long is a very long integer
    static long nTrials = 0; // number of trials.
    static int Observed[ ] = new int[100];
        
    //size of the random sequence
    private static int length;
	
    //The distribution must be uniform on 1 to 5 inclusive.
    private static double  Obschisquare(int length)
    {
        double chi = 0;

        //The die with five faces is associated to a distribution
        //that assigns a probability 1/5 to numbers 1 to 5.
        //Hence, a sequence  of landed faces
        //must have 1/5*length instances of each face.

        double Expected = length/5;
        //Expected distribution is compared to observed one.
        //Discrepancy is approximately distributed 
        //as a chi square:
        for(int j = 1; j<= 5; j++)
            chi  = chi + (Observed[j]-Expected)
                *(Observed[j]-Expected)/Expected;
        //System.out.println("Observed chi-square = " + chi); 	
        return chi;
    }
	
    // While we have not succeed
    // try and try
    private static void tryAndTry(int length)
    {
        // done is a flag that says
        //when we have succeeded
        int done = 0;

        while (done==0 )
        {
            nTrials = nTrials +1;
            //System.out.println(" Trial " + nTrials);

            //Initialization
            for(int j = 1; j<= 6; j++)
                Observed[j] = 0;

            //We generate a random sequence		
            for(int j = 0; j<length ; j++)
            {
                //We choose a uniform distribution	
                //from 1 to 6, as in a die.

                int  c = r.nextInt(6)+1;			
                //System.out.print(c ); 				
                //book keeping
                Observed[c] = Observed[c]+1;		
            }	
            //Report		
            //for(int j = 1; j<= 6; j++)
            //System.out.println(j + "\t" + Observed[j]);
            //We have succeed if 6 did not land
            // and if the distribution is uniform.
            if ((Observed[6] == 0)&& (Obschisquare(length) <= 9.48) )
                    done = 1;				
        }// end of while.		    		
    }
	
    public static void main(String[] args)
    {
        int rounds = 15;
        System.out.println( "length +  number of Trials");
        for(int j = 1; j< rounds; j++)
        {
            length = 10 * j;
            //Find a sequence that mimicks a not charged 
            //die with 5 faces.
            tryAndTry(length);
            System.out.println( length + "\t " +nTrials);
        }
    }
}//End of Program A218 Die2



:::::::::::::  NEW PROGRAM  :::::::::::::



// Program 302 StatTest
// Mean and variance of
// the Java inbuilt normal random generator.

package ejvol1;



import java.util.Random;


public class StatTest
{	
    //Turn on  the random generator
    static Random r  = new Random(); 	

    static double Data[] = new double[10000];		
    static int n;

	
		
		
public static void main( String args[])
{

    int n = 10000;
    //We generate n random numbers
    for(int i = 0; i < n; i++)
    {
        double s = r.nextGaussian() ;
        Data[i]= s;
        //System.out.println( Data[ i ]);
    }

    //Let us calculate the mean
    double sum = 0;

    for(int i = 0; i < n; i++ )
        sum = sum + Data[i];
    double mean = sum / n;
    //System.out.println( "Sum \t "+ sum);
    System.out.println( "Mean \t "+ mean);

    // Let us calculate the variance
    double sum2 = 0;
    for(int i = 0; i < n; i++ )
        sum2 = sum2 + (Data[i]-mean)*(Data[i]-mean);
    double var = sum2 / n;
    //System.out.println( "Variance \t "+ var);
    System.out.println( "Deviation \t "+ Math.pow( var, 0.5));
}
}//End of Program 302 StatTest



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A223 Die4
//We study sums of
//discrete uniforms distributions,
//each one  with range from 1 to 9
//and mean 5.

package ejvol1;



import java.util.Random;

public class Die4
{
    // One can vary the number of trials,
    // by changing the variable length.
	
    static private int length;
    static private double n;
    static private double p;
	
    //The number of studied families is
    //nFamilies

    //Observed frequencies
    static private double Obs[ ] = new double[9001]; 

    //Turn on of the random generator
    static private Random r  = new Random();

    public static void main(String[] args)
    {

        //nUniforms = number of random variables.	
        // nUniforms can range from 1 to 1000
        int nUniforms = 10;
        int m = 9*nUniforms;

        for(int i = 1; i<= m; i++)
                Obs[i] = 0; //Initialization

        int factor = 5;
        length = m*factor;
        //Loop with many trials 
        for(int j = 1; j<= length ; j++)
        {
            // We generate nUniform random numbers
            //from 1 to 9
            int sum = 0;
            for(int k = 0; k< nUniforms; k++)
            {
                int c = r.nextInt(9) +1;
                // and we add them:
                sum = sum + c;
            }
            //bookkeeping
            Obs[sum] = Obs[sum]+1;
        }
        System.out.println("Sums and their frequencies");
        for(int j = 1; j<= m; j++)
            System.out.println(j + "\t" + (int) Obs[j]); 		
    }
}//End of Program A223 Die4



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A150 ToolBox
//An ensemble of  mutations

package ejvol1;

public class ToolBox
{


//This method takes substring a
//and posits it at place Start inside c
public static  String insert(String a, int Start, String c)
{
    // System.out.println("original c " + c);
    // System.out.println("original a " + a);
    // System.out.println("Start " + Start);
    String  s1, s2;

    //We copy  the left part of c
    s1 = c.substring(0, Start);
    //We copy  the right part of c
    s2 = c.substring(Start);
    //We concatenate the left part of c
    //to a to the right part of c

    String z = s1 + a + s2;
    //System.out.println("Substring a was inserted " + z);
    return z;
}


//This method replaces  substring a by b inside c
public static String
      substitution(String a, String b, String c)
{
    /*System.out.println("original a " + a);
    System.out.println("original b " + b);
    System.out.println("original c " + c);*/
    String z = c.replace(a,b);
    /*System.out.println("Replacement done: " + z);*/
    return z;
}

//This method deletes the first
//occurrence of a from c.
public static  String delete(String a, String c)
{
    String  b = "";
    return substitution(a, b, c);
}


//This method inverts a
static public   String inversion(String a)
{
    int  la;
    String  d;

    //We initialize the output
    d = "";

    //We get the length of a
    la = a.length();

    //We copy the first character to the last place
    //and so on.
    for(int  i = 0; i < la; i++)
    {
        String chari = a.substring(i,i+1);
        d = chari + d;
    }
    return d;
}


//This method inverts   substring a  inside c
public  static String invert( String a,  String c)
{
    //We invert a properly
    String d =  inversion(a);
    int l = a.length();
    //System.out.println("a has " + l  + " characters");
    //We capture the first occurrence of a inside c.
    //default initialization for the
    //place n where a begins.

    int Start= -1;
    int i=0;
    while (  i<c.length()-3 )
    {
        String z = c.substring(i,i+l);
        System.out.println( "z " + z);
        if (a.matches(z))  Start = i;
        i = i+1;
    }
    if (Start>0)
    {
        System.out.println("a begins after position " + Start);
        //We copy  the first part of c
        String sl = c. substring(0, Start);
        //System.out.println(  "The left part of c is " + s1);

        //We copy  the rightmost part of c
        String sr = c. substring(Start+3);	
        //We concatenate the left part of c
        //to d to the rightmost part of c
        return sl + d +sr;
    }
    else return c;
}

}//End of  class A150 ToolBox.



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A87 GeneticCode
// A simplified genetic code
package ejvol1;

public class GeneticCode
{	
   public  static void main( String args[] )
   {
        //Declaration and assignation of the array
        //There are 2 columns. Capacity unspecified.
        String  genCode[][] = { {"AUU","Ile"},
    		                {"UUA","Leu"},
    		                {"UAU","Tyr"},
    		                {"AUA","Arg"},
    		                {"AAU","Asn"},
    		                {"AAA","Lys"},
    		                {"UUU","Phe"},
    		                {"UAA","Term"}
    		               };

        //  Report of the code
        System.out.println( "The genetic code is" );
        //  One loop for the rows.
        //  To know the length of the array : genCode.length
        for ( int i = 0; i < genCode.length; i++ )
        {
            System.out.print( genCode[ i ][ 0 ]  +
                  "	" +
                  genCode[ i ][ 1 ] );
            System.out.println(); //pass to the next line
        }

        //  Now we simulate the action of a ribosome.
        //  Test RNA string
        String c = "AUUUUAUUAUAUAUAUAUAU"+
                 "AUAUAUAUAUAUUUAUAUAU"+
                 "AUAUUUAA";
       
        String dash = "-";
        //  We get the length of c:
        int lc = c.length();
        //  We get the number of codons:
        int nCodons = lc / 3;
        System.out.println( "Length   = " + lc);
        System.out.println( "Number of codons = " + nCodons);
         //Easy reading of c
        String cc = c;
        //Insert a dash to separate one codon from another.
        //Begin with the right end, move to the left,
        //and terminate at t he first codon.
        for(int i = nCodons-1; i >0;  i--)
        {
            String t  = cc.substring(0, 3*i);
            //Debugger line
            //System.out.println("t = " + t);
            //Dash is inserted
            cc = t + dash +  cc.substring(3*i);
            //System.out.println("cc = " + cc);
        }
        

        
        
        //  We translate codon by codon.
        //  The output sequence z is initialized
        String z = "";
        int start;
        for(int i = 0; i< nCodons ; i++)
    	{
            //We copy the ith codon of c into a
            start = 3 * i;	
            String a = c.substring(start,start+3);

            //We revise the Genetic code to know
            //the corresponding row m where a is located:
            int m = 0; //default initialization
		
            for( int  j = 0; j < genCode.length; j++ )		
            {
                if ( a.equals(genCode[ j ][ 0 ]) )
                {
                    m = j;
                    // If the codon is located in 
                    //the dictionary, exit the loop:
                    break;
                }
                		
            }
            //Debugging line
            //System.out.println( a + " " + m);
				
            //We consult the dictionary in the other column
            //and synthesize z by adding the equivalent value
            z = z + "-" + genCode[m][1];
            
	}
        z = z.substring(1);
        //Report
        System.out.println( "RNA and protein sequences:");
        System.out.println( cc + "\n" + z);
   }
}//End of program A87 GeneticCode



:::::::::::::  NEW PROGRAM  :::::::::::::


//Program A31 Tab
// How to use the tab
// to print columns of numbers
// in a format appropriate for
// Excel or for Open Office Calc.
		
package ejvol1;

public class Tab
{

		public static void main(String[] args)
    {
	// Here a tab sign is defined.	
			String tab = "\t";

  // Report to the console
	System.out.println("1" + tab + "1");
	System.out.println("2" + tab + "4");
	System.out.println("3" + tab + "9 ");
	System.out.println("4" + tab + "16 ");
	System.out.println("5" + tab + "25 ");
	System.out.println("6" + tab + "36 ");
	System.out.println("7" + tab + "49 ");
		}
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A72 Invsersion2
//This program inverts substring a
//in within string c.
package ejvol1;


public class Inversion2
{
public static void main(String[] args)
  {	
    String a = "important";	
    String c = "Inversion is important for sub-speciation";
    System.out.println("Original sequence =" +  c);
    System.out.println("Subsequence to be inverted =" +  a);
    int Start;
    String charI;
    //We get the length of a
    int la = a.length();
    //We initialize the output
    String  d = "";
    //To invert a, we copy each character of a,
    //one by one, and paste them together
    //in reversed order:
		
    for(int i = 0; i<la ; i++ )
    {
        Start = i;
        charI = a.substring(Start,Start + 1);
        d = charI + d;
    }
    System.out.println(" Inverted sub-sequence =" +  d);

    // The first part of c:
    String cLeft = c.substring(0,13);
    // The last part of c:
    String cRight = c.substring(22);
    // Concatenation
    String Inversion = cLeft + d +cRight;
    System.out.println(" Partially inverted sequence ="
                                             +  Inversion);
  }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A176 RandGenerator
//A generator of pseudo-random numbers

package ejvol1;


public class RandGenerator
{
    public static void main(String[] args)
    {			
        double x = 3.5;	
        String s4, s5;
        for(int i = 0; i<1000; i++)
         {		
            x = x*(4-x);
            // System.out.println(x);
            // conversion of number x
            // into a format appropriate for 
            //some versions of Excel:
            //s4 = String.valueOf(x);
            //s5=s4.replace(".", ",");
            System.out.println(  i + "\t" + x);	
         }
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * Program A34 ForLoop
 */
//Introduction of the for-control structure.
//The "for" instruction causes a loop
//to deal with repetitive tasks.
package ejvol1;


public class ForLoop
{
		
    public static void main(String[] args)
    {			
        String tab = "\t";

        for(int i = 1; i<7; i++)
        {		
            System.out.println(i + tab  + i*i);
        }
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



// Program 192 RandGenerator3
// Generates a discrete uniform distribution.
// with range from 1 to 10.
// Uniformity is verified with a chi-2 test.
package ejvol1;


import java.util.Random;

public class RandGenerator3 
{

    // One can vary the number of trials,
    // by changing the variable length.
	
    static int length;
	
    // Turn on of the random generator
    static private Random r  = new Random();


    static int Frec[ ];//Predeclaration
	
    public static void  chisquare()
    {
        double chi = 0;
        double Length = length;
        double expected = Length/10;
        for(int j = 1; j<= 10; j++)
            chi  = chi +  (Frec[j]-expected)
                      *(Frec[j]-expected)/expected;
        System.out.print("Number of trials = "+ length);
        System.out.print("  Observed chi-square = " + chi);
        if (chi<16.91 )System.out.println("  Uniform.");
        else System.out.println("  Non Uniform.");	  		
    }

    public static void main(String[] args)
    {
        // factor is a scale parameter
        int factor = 10000;
        Frec= new int[11];
        for(int i= 1; i<10; i++)
        { 
            length = i*factor;		
            for(int j = 1; j<= 10; j++)
                    Frec[j] = 0; //Initialization
            // We generate a random sequence
            for(int j = 1; j<= length ; j++)
            {
                // We generate a random number
                //from 1 to 10
                int c = r.nextInt(10) +1;
                //book keeping
                Frec[c] = Frec[c]+1;
            }
            // for(int j = 1; j<= 10; j++)
                  // System.out.println(j + "\t" + Frec[j]); 	
            // We measure how uniform is the distribution.
            // Greater chisquare values mean
            // lesser uniformity
            chisquare();
        }
    }
}//Program 192 RandGenerator3



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A66
// This program deletes from s1
// the last 3 characters.

package ejvol1;


public class Length
{	
    public static void main(String[] args)
    {
        String s1, s2;
        s1 = "Evolution = mutation + selection";
        System.out.println(s1);
        // The next method measures
        // the number of characters of a string.
        int n = s1.length();
        // Copy procedure		
        s2 = s1.substring(0,n-3);
        System.out.println(s2);
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A77 Chain
//Playing with methods.

package ejvol1;


public class Chain
{
    static String e;
    
    // This method concatenates a and b.
    //Its output is a String,
    // So it is declared as a String
    public static String  glue(String a, String b)
    {
        return a+b;
    }

    // This method replaces string e by f
    // inside g. Its output is a String
    // so the method is declared as String.
    public static String
          replacement(String e, String f, String g)
    {
        return g.replace(e,f);
    }
	
    //This methods reports results.
    //This method makes an action,
    //so its output is declared void.
    public static void  Report(String a,String b,
                         String c,String d, String sOutput)	
    {
        System.out.println("a =   " + a);
        System.out.println("b =   " + b);
        System.out.println("a+b =   " + e);
        System.out.println("c =   " + c);
        System.out.println("d =   " + d);
        System.out.println("In a+b, c is replaced by d =  " + sOutput);
    }

    // This is the head of the program.
    public static void main(String[] args)
    {
        String a = "123";
        String b = "def";
        String c= "23";
        String d = "bc";
        // We concatenate a to b
        e = glue(a,b);
        // We replace c by d inside e
        String sOutput = replacement(c,d,e);
        //Report
        Report(a,b,c,d,sOutput);	
    }
}//End of program  A77 Chain



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A220 Die3
//A die with 6 (7) faces
//tries to mimic a die with 5 faces.

package ejvol1;


import java.util.Random;

public class Die3
{

//Turn on   the random generator
private static final Random r  = new Random();
// Counts the number of trials
static private long count ; 

private static final int Observed[ ] = new int[50];

// The following is a chi2 table.
// Signifcance 0.05.
private static final double  Chi[]  = {
                        3.84,
                        5.99,
                        7.81,
                        9.48,
                        11.07,
                        12.59,
                        14.06,
                        15.5,
                        16.91,
                        18.30,
                        19.67,
                        21.02,
                        22.36,
                        23.68,
                        24.99,
                        26.29,
                        27.58,
                        28.86,
                        30.14,
                        31.41,
                        32.36,
                        33.92,
                        35.17,
                        36.41,
                        37.65,
                        38.88,
                        40.11,
                        41.33,
                        42.55,
                        43.77};
//This measures the error between
//expected and observed
//The distribution must be uniform on 1 to 5 inclusive.
private static double  observedChisquare(int length)
{
    double chi = 0;

    //The die with five faces is associated to a distribution
    //that assigns a probability 1/5 to numbers 1 to 5.
    //Hence, a sequence  of landed faces
    //must have 1/5*length instances of each face.

    double Expected = length/5;
    //Expected distribution is compared to observed one.
    //Discrepancy is approximately distributed 
    //as a chi square:
    for(int j = 1; j<= 5; j++)
        chi  = chi + (Observed[j]-Expected)
            *(Observed[j]-Expected)/Expected;
    //System.out.println("Observed chi-square = " + chi); 	
    return chi;
}


// While we have not succeed
// try and try
private  static void tryAndTry(int length, int nfaces)
{
    // done = 1 is flag that says
    //that we have succeeded
    int done = 0;	
    while (done == 0 )
    {
        count = count +1;
        //System.out.println(" Trial " + count);		
        // Initialization
        // This instruction must be changed
        // if nfaces>7
        for(int j = 1; j<= 7; j++)
            Observed[j] = 0;

        // We generate a random sequence		
        for(int j = 0; j< length; j++)
        {
            // We choose a uniform distribution	
            // from 1 to nfaces, as in a die.			
            int  c = r.nextInt(nfaces)+1;			
            // System.out.println(c ); 				
            //book keeping
            Observed[c] = Observed[c]+1;		
        }	
        // Report		
        // for(int j = 1; j<= nfaces; j++)
        // System.out.println(j + "\t" + Observed[j]);


        //Degrees of freedom: nfaces -1;
        //but Java counts from zero, hence
        int df = nfaces -2;
        //System.out.println(observedChisquare(length) 
        //+ "\t "+ Chi[df]);
        //If nfaces = 6:
        //We have succeed if 6   did not land
        // and if the distribution is uniform.
        //If nfaces = 7:
        //We have succeed if 6 and 7  did not land
        // and if the distribution is uniform.
        if ((Observed[6] +Observed[7] == 0)&&
            (observedChisquare(length) < Chi[df]) )
            done = 1;				
    }		    		
}

public static void main(String[] args)
{	
    //Number of faces, nfaces, of the die
    //must be less than 30.
    int rounds = 4;
    for(int nfaces  = 6;nfaces <=7;nfaces ++)
    {
        System.out.println("Die with " 
                + nfaces + " faces");
        System.out.println( "seq.length "
                + "+ number of trials until success");
        for(int j = 1; j< rounds; j++)
        {
            count = 0;
            //Observed contains the observed frequencies.
            //Let us make the simulation
            //length = size of the random sequence		
            int length= nfaces*j;
            // For each die, we generate
            // sequences of increasing length,
            // which is defined by length,
            // which is a multiple of nfaces.
            tryAndTry(length,nfaces);
            //System.out.println("Die with " 
            //      + nfaces + " faces" );
            //System.out.println("Sequences of length " 
            //      + length );
            //System.out.println("We succeed at the trial "
            //      + count );
            //System.out.println("length and trials");
            System.out.println(length + "\t"  +   count); 	
        }
        System.out.println();
    }
}
}//Program A220 Die3



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A275 Moths3
/*
    Study of predation of moths by birds.
    Moths could be white or brown.
    Reproduction obeys a logistic model
    Two environments: clean and dirty.
    Discrete stochastic logistic model.
    Mutation is included.	
*/

package ejvol1;


	
import java.util.Random;


public class Moths3
{	
    static private int nwm, nbrm, nb ;
    static private double  mr;
    static private double  maxM, maxB, pwm, pbrm,bd;
    static private int n;
    static private double mut;
    

    //Turn on of the random generator
    static private Random r  = new Random();
		
    public static void initialization()
    {
        //Number of generations
        n = 1000;
        //Generates   moths,
        //white moths
        nwm = 450;
        // brown moths
        nbrm = 450;
        //Generates birds
        nb = 10;
        //Probability of moth's reproduction
        mr = 0.1;
        //Mutation rate of moths
        mut = 0.01;
        //Maximum number of Moths
        maxM = 2000;
        //Maximum number of Birds
        maxB = 20;
        //probability of predation on white moths
        pwm = 0.001;
        //probability of predation on brown moths
        pbrm = 0.002;
        //Probability of bird's death
        bd = 0.05;		
    }
    
    public static void reinitialization()
    {	
        //probability of predation on white moths
        pwm = 0.002;
        //probability of predation on brown moths
        pbrm = 0.001;
        //Probability of bird's death		
    }
	 	
    public static void dynamics()
    {
        for(int i = 0; i < n; i++)
        {			
            // White moths reproduce and mutate
            for(int j = 0; j < nwm; j++)
            {
                double s = r.nextDouble();
                if (s < mr * (1 - (nwm + nbrm) / maxM) )
                {
                    //Reproduction
                    nwm = nwm + 1;
                    //Mutation
                    if (s < mut)
                    {
                        nbrm = nbrm + 1 ;
                        nwm = nwm-1;
                    }
                }			 		
            }

            //Brown moths reproduce and mutate
            for(int j = 0; j < nbrm; j++)
            {
                double s = r.nextDouble();
                if (s < mr * (1 - (nwm + nbrm) / maxM) )
                {
                    nbrm = nbrm + 1;
                    if (s < mut)
                    {
                        nbrm = nbrm - 1 ;
                        nwm = nwm+1;
                    }
                }		
            }// end j for

            
            //Moths are preyed, birds reproduce
            for(int l = 0; l < nb; l++)
            {		
                //White moths
                for(int j = 0; j < nwm; j++)
                {
                    double s = r.nextDouble();
                    // a white moth is preyed
                    if (s < pwm){ nwm = nwm - 1;}
                    //birds reproduce
                    if ( s < 0.1 * pwm * (1 - nb / maxB))
                        nb = nb + 1;
                }
                //brown moths
                for(int j = 0; j < nbrm; j++)
                {
                    double s = r.nextDouble();
                    // a brown moth is preyed
                    if (s < pbrm){ nbrm = nbrm - 1;}
                    //birds reproduce
                    if ( s < 0.1 * pbrm * (1 - nb / maxB))
                        nb = nb + 1;
                }		
            }
            


            //Birds die
            for(int j = 0; j < nb; j++)
            {
                double s = r.nextDouble();
                if (s < bd)
                    nb = nb - 1;
            }
            System.out.println(i + "\t " +  nwm + "\t " 
                + nbrm + "\t " + nb);	
        }//end i for
    }	
		
         
    public static void main(String[] args)
    {
        initialization();
        System.out.println("time, white moths, brown moths and birds");
        dynamics();	
        System.out.println("Contamination.");
        System.out.println("time, white moths, brown moths and birds");
        reinitialization();
        dynamics();
    }
}//End of Program A275 Moths3



:::::::::::::  NEW PROGRAM  :::::::::::::


//Program A53 Replace
//Replace operator of strings.
//Replacement of all instances of a substring 
//with another one.

package ejvol1;


public class Replace
{

    public static void main(String[] args)
    {
        //Declaration of type of variables
        String s1, s2;
        // Assignation
        s1 = "Mutation is the key to evolution.";
        System.out.println(s1); //action

        s2 = s1.replace("ion", "ate");
        System.out.println(s2); //action
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A126 Nonsense
//Random substitutions in tandem
package ejvol1;


import java.util.Random;

public class Nonsense
{
   public static void main( String args[] )
   {
        //We turn on the random generator:
        Random r  = new Random();
        //Original string
        String s = "meaning";

        int l = s.length();
        System.out.println (s + " length = " + l);

        // We want 30 substitutions in tandem	  	
        for (int i = 0; i<3000; i++)
        {
            // We choose at random a place
            // to make a substitution.
            int place = r.nextInt( l );
            // We choose a char at random
            char ch =   ( char ) ( r.nextInt( 26 ) + 97 );
            // We make a substitution
            s = s.substring(0, place) + ch + s.substring(place+1);
            System.out.println (s);
        }
    }
 }



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A138 Letterzymes2
//Evolution of a population
//of strings.
//Selection and mutation are implemented.

//Strings are at the same time
//genotype and phenotype.
//They are like ribozymes.


package ejvol1;



import java.util.Random;

public class Letterzymes2
{
    
//Pre-declaration of global variables.
//They are used all throughout the whole class.

//Individuals are kept in the array
//Individual[]. It is an array of strings.
//The number of individuals must be
//less than limit

private static final int limit = 1000;
//How many generation to run
private static final int  nGen = 2;
//Define here when a string is long enough
//to be purged
private static final int largeSize = 1;
static private String Individual[ ] = new String[100]; 
static private int NIndiv = 15;  
//Rank  keeps the rank of each individual.
static private int Rank[] = new int[limit];
static private String b;

static private int ReportMin[], ReportMax[];


//Turn on of the random generator
private static final Random r  = new Random();

//This method generates random chars
private  static  Character  randomChar()
{
    return  ( char ) ( r.nextInt( 26 ) + 65  );
}

/* We generate NIndiv individuals (strings)
 ten characters long.
 Sequences are completely random */
private static void Initialization( )
{	
    System.out.println("ORIGINAL POPULATION");
    for(int i = 0; i< NIndiv; i++)
    {
        //Initialization 	in blank.
        Individual[i]="";

        //An individual is assembled char by char		
        for(int j = 0; j< 10; j++)
        {
            //We generate a random char
            Character c =  randomChar();
            //System.out.println( "char = " + c);
            //Char c is converted into a string s
            String s = ""+c;
            //s is concatenated to Individual[i]
            Individual[i] = Individual[i]+s;
        }
        System.out.println("Individual " +  i);
        System.out.println( Individual[i]);
    }

    

    for(int i = 0; i< NIndiv; i++)
        Rank[i]=0;

    ReportMin= new int[nGen];
    ReportMax= new int[nGen];
    for(int gen = 0; gen < nGen; gen++)
    {
        ReportMax[gen]=0;
        ReportMin[gen]=0;
    }
         

                     
}
		

//This method takes substring a
//and posits it at place Start inside c
private  static  String
      Insert(String a, int Start, String c)
{
    
    String  s1, s2;
    //	We copy  the left part of c
    s1 = c.substring(0, Start);
    //	We copy  the right part of c
    s2 = c.substring(Start);
    // We concatenate the left part of c
    //to a to the right part of c
    String z = s1 + a + s2;
    /*System.out.println("Original c " + c);
    System.out.println("Original a " + a);
    System.out.println("Start " + Start);
    System.out.println("PosInsertion c = " + z); 
    */
    return z;
}

//The letters of "ALGAE" are inserted 
//into the string of individual i
private static  void feeding(int i)
{
    String a;
    // We measure the length of Individual[i]
    int l = Individual[i].length();
    //Null strings cannot feed anyhow
    if (l == 0) ; 
    else //Non null strings  feed on ALGAE
    {
        a = "A";
        int Start = r.nextInt(l);
        Individual[i] = Insert(a, Start, Individual[i]);
        a = "L";
        l = Individual[i].length();
        Start = r.nextInt(l);
        Individual[i] = Insert(a, Start, Individual[i]);
        a = "G";
        l = Individual[i].length();
        Start = r.nextInt(l);
        Individual[i] = Insert(a, Start, Individual[i]);
        a = "A";
        l = Individual[i].length();
        Start = r.nextInt(l);
        Individual[i] = Insert(a, Start, Individual[i]);
        a = "E";
        l = Individual[i].length();
        Start = r.nextInt(l);
        Individual[i] = Insert(a, Start, Individual[i]);
    }
}

	
//This Function replaces all occurrences of
//substring a by b inside c
private static String
Substitution(String a, String b, String c)
{
    String z = c.replace(a,b);
    /*System.out.println("original a " + a);
    System.out.println("Original b " + b);
    System.out.println("Original c " + c);
    System.out.println("replaced c " + z);
    */
    return z;
}


//This function or method deletes all occurrences 
//of a from c.
static private String Delete(String a, String c)
{
    b = "";
    return Substitution(a, b, c);
}


//Here we see what a PARA-SITE  does to individuals.
private  static void parasitation(int i)
{
    int l  =  Individual[i].length();	
    //The parasite deletes from the 
    //beginning of the individual
    //any substring   matching "PARA".
    //We copy to Beginning the first 
    //4 chars of Individual[i]
    if ( l > 4)
    {
        String Beginning =  Individual[i].substring(0,4);
        String s = "PARA";
        // We compare Beginning and s
        if (Beginning.equals(s))
            Individual[i] = Individual[i].substring(4);

        //The parasite deletes from the tail 
        //of the individual
        //any substring   matching "SITE".
        String Ending =  Individual[i].substring(4);	

        String t = "SITE";
        // We compare Ending and t
        if (Ending.equals(t))  Individual[i] = 
                    Individual[i].substring( 0,l - 4);
    }
 }


//In this method individuals are mutilated
//as a measure to hinder overgrowth.
//We delete from the original string
//a substring of a random length beginning with 
//a random Start position.
private static void Purge(int i)
{
    String c, s1, s2;
    int lc, Start, n;
    c = Individual[i];
    lc = c.length();
    if (lc > largeSize)
    {
        Start = r.nextInt(lc);
        //We copy  the first part of c
        s1 = c.substring(0, Start);
        // We throw a random number	
        n = r.nextInt(lc - Start+1);
        //We copy  the right part of c
        // after Start + n places
        s2 = c.substring( Start+ n);	
        //We concatenate the left part of c
        //to  the right part of c
        Individual[i] = s1 + s2;
    }
}


//Individuals are sorted by fitness.
//Fitness = length, as an indicator of complexity.
private static void Sorting()
{
    int   Champ;
    //Necessary default initialization
    int Fitness[] = new int[100];
    for(int i = 0; i< NIndiv; i++)
        Fitness[i] =0;
    //We define a fitness function equal to the length
    //of the string
    for(int i = 0; i< NIndiv; i++)
    {   
        String s = Individual[i];
        Fitness[i] = s.length();
        //System.out.println(Individual[i] + Fitness[i]);        
    }	
    //We sort individuals by fitness
    for(int i = 0; i< NIndiv;i++)
    {
        Champ = 0;
        for(int j = 0; j< NIndiv;j++)
            if (Fitness[j] > Fitness[Champ])   Champ = j;

        //The array Rank keeps a record of fitness
        //by decreasing order.
        Rank[i] = Champ;
        //The champ leaves the game
        Fitness[Champ] = 0;
        
    }
    /*
    //Report in decreasing order
    System.out.println("\nSorting :");
    for(int i = 0; i< NIndiv;i++)
        System.out.println(Individual[Rank[i]]);
    */
}


//The top ten fill the world
    private  static void Copying()
    {
        int   k;
        for(int i = 0; i< 10; i++)
        {
            int  l = 10*(10-i);
            for(int j = 0; j< 10; j++)
            {			
                k = l -j-1;
                Individual[k] = Individual[Rank[i]];
                /*System.out.println("Ind " + k 
                        + " replaced by top" + i);*/
                        
            }
        }

        //System.out.println(  "THE NEW POPULATION IS");

        // for(int i = 0; i <  NIndiv;i++)
        //System.out.println(  Individual[i]);
    }

private static void Reproduction()
{
    //Individuals are sorted by length
    Sorting();
    //for(int i = 0; i< 10;i++)
    //System.out.println(  Individual(Rank(i))
    //The top ten produce a copy that
    //substitutes the bottom ten.
    Copying();
}

// From individual i
// the fist n  chars are deleted
private static   void Deletion(int i)
{
    int l, n;	
    l = Individual[i].length();
    n = 0;
    if (l > 0)  n = r.nextInt(l);
    Individual[i] = Individual[i].substring(n);
 }

//This method inverts a
static private   String Inversion(String a)
{
    int  la = a.length();
    //Output
    String  d  = "";

    //We copy the first character of a to the last place
    //and so on.
    for(int  i = 0; i < la; i++)
     {
        char charI = a.charAt(i);
        d = charI + d;
     }
    return d;
}

//Local inversion of a substring inside individual i.
private static void innerInversion(int i)
{    
    String sLeft, sRight;
    int start;
    int n = -1;
    String c = Individual[i];
    int lc = c.length();
    if (lc > 1)
    {
        start = r.nextInt(lc);
        //We copy  the first part of c
        sLeft = c.substring(0, start);
        // We throw a random number	
        n = r.nextInt(lc - start+1);
        //Inner substring
        String a = c.substring(start, start + n);
        String d = Inversion(a);
        //We copy  the right part of c
        // after Start + n places
        sRight = c.substring( start+ n);	
        //We concatenate the left part of c
        //to  the right part of c
        Individual[i] = sLeft + d + sRight;
    }
    /*System.out.println("Input  =   " + c + "  " + n);
    System.out.println("Output  =  " + Individual[i]);   
    */
}

//We consider only two types of mutation:
//deletion of the beginning
//and inversion of an inner part.
private static void Mutation()
{ 	
    //Which mutation affects which individual
    //is a matter of gambling.
    //We throw a 0 else a 1
    for(int i = 0; i< NIndiv; i++)
    {
        int Luck = r.nextInt(2);
        if ( Luck == 1) Deletion(i);
        else  innerInversion(i);
    }
}

//This is the heart of the process
private static void Dynamics()
{
    //All individuals feed
    for(int i = 0; i< NIndiv; i++)
    {
        //The string Algae is digested and inserted
        //into the individual[i] char by char
        /*System.out.println( "The hungry individual "
                     + i + " is " + Individual[i]); */
        feeding(i);
        /*System.out.println(  "The full individual "
             + i + " is " + Individual(i)); */
        //All individuals are tested by the parasite,
        //which corrodes any  large substring
        //similar to it located at any end.
        parasitation(i);
        /*System.out.println(  "Pos-parasitation individual "
             + i + " is " + Individual(i));*/
        //Very long chains are attacked recurrently,
        //the same as very large fishes in the sea.
        Purge(i);
        /*System.out.println(  "The purged  individual "
             + i + " is " + Individual(i)); */
    }
    //The top ten are allowed to  reproduce:
    //a child occupies the place of the shortest individual
    Reproduction();
    //The new population is subjected to mutation
    Mutation();
}
	

private static void report(int gen )
{
    System.out.println("\nPopulation at gen = " + gen );
    for(int j = 0; j< NIndiv; j++)
    {
        System.out.println("Gen " + gen + " Ind "
                     + j +" " +  Individual[j]);	
    }
}

//Min and Max lengths are detected
private static void Observation(int gen)
{		
    int m, Min, Max;
    Max = 0;
    Min = 32000000;
    for(int j = 0; j< NIndiv; j++)
    {
        m =  Individual[j].length();
        /*System.out.println(  "The Individual  "
           + Individual(j) + " has length " + m);*/
        if (m > Max)  Max = m;
        if (m < Min)   Min = m;
    }
    
    /*System.out.println(  "Generation "  + Gen
    + " MinLength = " + Min + " MaxLength = " + Max);*/
    ReportMin[gen] = Min;
    ReportMax[gen] = Max;
}

public static void main(String[] args)
{		 					
    Initialization( );

    for(int gen = 0; gen < nGen; gen++)
    {				
        //System.out.println( "Beginning3");
        Dynamics();
        report(gen);
        //The aim of observation is to record
        //the minimum and maximum lengths
        //of the individuals in each generation.
        Observation(gen);		  	
    }
    //Report of the dynamics of min and max indicators.
    System.out.println( "GENERATION MIN AND MAX VALUES");
    for(int Gen = 0; Gen < nGen; Gen++)
        System.out.println( Gen + "\t" + ReportMin[Gen]
        + "\t" + ReportMax[Gen]);

}

}//End of Program A138 Letterzymes2



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A71 Inversion
//This program inverts string a.

package ejvol1;


public  class Inversion
{
    public static void main(String[] args)
    {	
        String a = "Inversion is important in sub-speciation";
	
        int Start;
        String charI;
        //We get the length of a
        int la = a.length();
        //Output
        String  d = "";
        //To invert a, we copy each character of a,
        //one by one, and paste them together
        //in reversed order:
		
        for(int i = 0; i < la ; i++)
        {
            Start = i;
            charI = a.substring(Start,Start + 1);
            //Char is pasted to the left
            d = charI + d;
        }
    System.out.println("Original sequence =" +  a);
    System.out.println("Inverted sequence =" +  d);
  }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A243 Markov
//A Markov Chain

package ejvol1;



import java.util.Random;

public class Markov
{	
    
    static int X[] = new int[3000];
    //Probabilities
    static double  pa,paa,pb,pbb;
	
    //Turn on of the random generator
    static Random r  = new Random();
		
//Define probabilities of transition	
public static void initialization()
{		
    //Independent probabilties
    paa = 0.8;
    pbb = 0.7;
    // initial conditions
    pa = 0.25;
    pb = 0.75;
}
		
 public static void main(String[] args)
 {
    initialization();
    // Generation of 3000 individuals
    // some of type a other of type b
    int na = 0;
    int  nb = 0;
    for(int i = 0; i< 3000; i++)
    {
        double s = r.nextDouble();
        if (s < pa)  na = na + 1;		
         else nb = nb + 1;
    }	
				
			
    //Report the number of individuals in each state
    System.out.println("Initial condition");
    System.out.println("The number of individuals in " +
                        "state a is  " + na);
    System.out.println("The number of individuals in " +
                        "state b is  " + nb);
    //Execute 1000 transitions
    for(int i = 0; i< 1000;i++)
    {
        //Decide whether or not an individual
        //in state a must make a transition
        for(int j= 1; j<=na;j++)
        {
            double s = r.nextInt();
            if (s < paa)
            {	
                na = na - 1;
                nb = nb + 1;
            }
        }
				
        //Decide whether or not an individual
        // in state b must make a transition
        for(int j= 1; j<=nb;j++)
        {
            double s = r.nextDouble();
            if (s < pbb)
            {	
                nb = nb - 1;
                na = na + 1;
            }
        }			 				
   }
   System.out.println("Final condition");
   System.out.println("The number of individuals in " +
                        "state a is  " + na);
   System.out.println("The number of individuals in " +
                        "state b is  " + nb);
   }	
}//End pf Program A243 Markov



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A256 Markov4
//Markov Chains
//There is a rapid convergence to the equilibrium state.
//Encapsulated code.

package ejvol1;

import java.util.Random;


public class Markov4 
{
    
    static private int X[] = new int[3000];
    //Probabilities
    static private double  pa,paa, pbb;
    static private int na = 0;
    static private int nb = 0;
	
    //Turn on the random generator
    static Random r  = new Random();
	
    //Define probabilities of transition.
    private static void setParameters()
    {
        //Independent probabilties
        paa = 0.8;
        pbb = 0.7;
        // initial conditions
        pa = 0.25; //pb = 1-pa;        
    }
    
	
private static void initialization()
{		
    // Generation of 3000 individuals
    // some of type a other of type b
    
    for(int i = 0; i< 3000; i++)
    {
        double s = r.nextDouble();
        if (s < pa)  na = na + 1;		
         else nb = nb + 1;
    }	
				
    //Report the number of individuals in each state
    System.out.println("Initial condition");
    System.out.println("The number of individuals in " +
                        "state a is  " + na);
    System.out.println("The number of individuals in " +
                        "state b is  " + nb);
    
    System.out.println("Generation,    populations in "
                                    +"states A and    B  " );
}

private static void dynamics()
{
//Execute 1000 transitions
    for(int i = 0; i< 100;i++)
    {
        //Decide whether or not an individual
        //in state a must make a transition
        for(int j= 1; j<=na;j++)
        {
            double s = r.nextInt();
            if (s < paa)
            {	
                na = na - 1;
                nb = nb + 1;
            }
        }
				
        //Decide whether or not an individual
        // in state b must make a transition
        for(int j= 1; j<=nb;j++)
        {
            double s = r.nextDouble();
            if (s < pbb)
            {	
                nb = nb - 1;
                na = na + 1;
            }
        }	
        System.out.println( i + "\t"    + na + "\t"   + nb); 
    }       
}
	
private static void report()
{
    System.out.println("Final condition");
    System.out.println("The number of individuals in " +
                         "state a is  " + na);
    System.out.println("The number of individuals in " +
                       "state b is  " + nb);
}


public static void main(String[] args)
{
    setParameters();
    initialization();
    dynamics();
    report();
}    
}//Program A256 Markov4



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A247 Markov2
//Markov Chains
//There is a rapid convergence to the equilibrium state.

package ejvol1;




import java.util.Random;

public class Markov2
{
    
    static int X[] = new int[3000];
    //Probabilities
    static double  pa,paa,pb,pbb;
	
    //Turn on of the random generator
    static Random r  = new Random();
		
//Define probabilities of transition	
public static void initialization()
{		
    //Independent probabilties
    paa = 0.8;
    pbb = 0.7;
    // initial conditions
    pa = 0.25;
    pb = 0.75;
}
		
 public static void main(String[] args)
 {
    initialization();
    // Generation of 3000 individuals
    // some of type a other of type b
    int na = 0;
    int  nb = 0;
    for(int i = 0; i< 3000; i++)
    {
        double s = r.nextDouble();
        if (s < pa)  na = na + 1;		
         else nb = nb + 1;
    }	
				
			
    //Report the number of individuals in each state
    System.out.println("Initial condition");
    System.out.println("The number of individuals in " +
                        "state a is  " + na);
    System.out.println("The number of individuals in " +
                        "state b is  " + nb);
    
    System.out.println("\tGeneration,    populations in "
                                    +"states A and    B  " );
 
    //Execute 1000 transitions
    for(int i = 0; i< 1000;i++)
    {
        //Decide whether or not an individual
        //in state a must make a transition
        for(int j= 1; j<=na;j++)
        {
            double s = r.nextInt();
            if (s < paa)
            {	
                na = na - 1;
                nb = nb + 1;
            }
        }
				
        //Decide whether or not an individual
        // in state b must make a transition
        for(int j= 1; j<=nb;j++)
        {
            double s = r.nextDouble();
            if (s < pbb)
            {	
                nb = nb - 1;
                na = na + 1;
            }
        }	
        
        int  l = i / 100;
        if( i == l * 100)
            System.out.println( i + "\t"    + na + "\t"   + nb);
 
    }    
    System.out.println("Final condition");
    System.out.println("The number of individuals in " +
                         "state a is  " + na);
    System.out.println("The number of individuals in " +
                        "state b is  " + nb);
   
}
}//End of Program A247 Markov2



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A68 Length2
//This program deletes from s1
//3 characters beginning with the (l-4)th one,
//where l is the length of s.

package ejvol1;



public class Length2
{
    public static void main(String[] args)
    {
        String s1, s2, s3, s4;
        s1 = "Evolution = mutation + selection";
        System.out.println("Original sentence: " + s1);
        int l = s1.length();

        //We copy into s2 the first part of s1
        s2 = s1.substring(0,l-4);
        System.out.println("Left tail: " + s2);
        //We copy into s3 the last part of s1
        s3 = s1.substring(l-1);

        //We concatenate s2 and s3.
        s4 = s2+s3;
        System.out.println("Deleted sentence: " + s4);
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//program A83 Arrays3
//Mean and variance of some data.
package ejvol1;


public class Arrays3
{
   public  static void main( String args[] )
   {
        //Declaration and assignation of the data array	
        int  Data[] = {1,5,2,4,7,8,9,5,6,3,5};
        // Report of data
        System.out.println( "Data are" );
        // To know the length of the array : Data.length
        for ( int i = 0; i < Data.length; i++ )
        {
            System.out.print( Data[ i ]);
            System.out.println(); //pass to the next datum
        }
        //Let us calculate the mean
        double sum = 0;
        int n = Data.length;
        for ( int i = 0; i < n; i++ )
            sum = sum + Data[i]; 
        double mean = sum / n;
        System.out.println( "Sum \t "+ sum);
        System.out.println( "Mean \t "+ mean);
        //Let us calculate the variance
        double sum2 = 0;
        for ( int i = 0; i < n; i++ )
         sum2 = sum2 + (Data[i]-mean)*(Data[i]-mean);
        double var = sum2 / n;
        System.out.println( "Variance \t "+ var);
        System.out.println( "Deviation \t "+ Math.sqrt(var));
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A208 RandGenerator
//Simulation of
//a normal distribution with 
//mean 25 and deviation 5

package ejvol1;

import java.util.Random;

public class RandGenerator8
{
    //Turn on of the random generator
    private static Random r  = new Random();

    private static int Frec[ ];//Predeclaration
	
    public static void main(String[] args)
    {
        //Size of the random sequence
        int size = 10000;
        // Frec contains the histogram.
        Frec= new int[50];
        // Initialization
        for(int j = 0; j< 50; j++)
                Frec[j] = 0;
        //We generate a random sequence
        for(int j = 0; j< size; j++)
        {
           // We choose a Gaussian distribution
           double d = r.nextGaussian() ;
           // System.out.println(d ) ; 	
           // Rescale numbers: mean 25, deviation 5-
           //Math.rint = approx. to the closest int
           int c = (int) Math.rint(5*d) + 25;	
           //book keeping
           Frec[c] = Frec[c]+1;
        }
        // Report		
        for(int j = 0; j< 50; j++)
            System.out.println(j + "\t" + Frec[j]); 			
    }
}//End of Program A208 RandGenerator



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A273 Moths2
/*
    Study of predation of moths by birds.
    Moths could be white or brown.
    Reproduction obeys a logistic model
    Two environments: clean and dirty.
    Discrete stochastic logistic model.
    Mutation is included.	
*/

package ejvol1;


	
import java.util.Random;


public class Moths2
{	
    static private int nwm, nbrm, nb ;
    static private double  mr;
    static private double  maxM, maxB, pwm, pbrm,bd;
    static private int n;
    static private double mut;
    

    //Turn on of the random generator
    static private Random r  = new Random();
		
    public static void initialization()
    {
        //Number of generations
        n = 1000;
        //Generates   moths,
        //white moths
        nwm = 450;
        // brown moths
        nbrm = 450;
        //Generates birds
        nb = 10;
        //Probability of moth's reproduction
        mr = 0.1;
        //Mutation rate of moths
        mut = 0.01;
        //Maximum number of Moths
        maxM = 2000;
        //Maximum number of Birds
        maxB = 20;
        //probability of predation on white moths
        pwm = 0.001;
        //probability of predation on brown moths
        pbrm = 0.002;
        //Probability of bird's death
        bd = 0.05;		
    }
	 	
    public static void dynamics()
    {
        for(int i = 0; i < n; i++)
        {			
            // White moths reproduce and mutate
            for(int j = 0; j < nwm; j++)
            {
                double s = r.nextDouble();
                if (s < mr * (1 - (nwm + nbrm) / maxM) )
                {
                    //Reproduction
                    nwm = nwm + 1;
                    //Mutation
                    if (s < mut)
                    {
                        nbrm = nbrm + 1 ;
                        nwm = nwm-1;
                    }
                }			 		
            }

            //Brown moths reproduce and mutate
            for(int j = 0; j < nbrm; j++)
            {
                double s = r.nextDouble();
                if (s < mr * (1 - (nwm + nbrm) / maxM) )
                {
                    nbrm = nbrm + 1;
                    if (s < mut)
                    {
                        nbrm = nbrm - 1 ;
                        nwm = nwm+1;
                    }
                }		
            }// end j for

            
            //Moths are preyed, birds reproduce
            for(int l = 0; l < nb; l++)
            {		
                //White moths
                for(int j = 0; j < nwm; j++)
                {
                    double s = r.nextDouble();
                    // a white moth is preyed
                    if (s < pwm){ nwm = nwm - 1;}
                    //birds reproduce
                    if ( s < 0.1 * pwm * (1 - nb / maxB))
                        nb = nb + 1;
                }
                //brown moths
                for(int j = 0; j < nbrm; j++)
                {
                    double s = r.nextDouble();
                    // a brown moth is preyed
                    if (s < pbrm){ nbrm = nbrm - 1;}
                    //birds reproduce
                    if ( s < 0.1 * pbrm * (1 - nb / maxB))
                        nb = nb + 1;
                }		
            }
            


            //Birds die
            for(int j = 0; j < nb; j++)
            {
                double s = r.nextDouble();
                if (s < bd)
                    nb = nb - 1;
            }
            System.out.println(i + "\t " +  nwm + "\t " 
                + nbrm + "\t " + nb);	
        }//end i for
    }	
		
         
    public static void main(String[] args)
    {
        initialization();
        System.out.println("time, white moths, brown moths and birds");
        dynamics();	
    }
}//End of Program A273 Moths2



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A140 Letterzymes2
//Evolution of a population
//of strings.
//Recombination is added to 
//selection and mutation.

//Strings are at the same time
//genotype and phenotype.
//They are like ribozymes.


package ejvol1;



import java.util.Random;

public class Letterzymes3
{
    
//Pre-declaration of global variables.
//They are used all throughout the whole class.

//Individuals are kept in the array
//Individual[]. It is an array of strings.
//The number of individuals must be
//less than limit

private static final int limit = 1000;
//How many generation to run
private static final int  nGen = 200;
//Define here when a string is long enough
//to be purged
private static final int largeSize = 1;
private static final String Individual[ ] = new String[100]; 
private static final int NIndiv = 15;  
//Rank  keeps the rank of each individual.
private static final int Rank[] = new int[limit];
static private String b;

static private int ReportMin[], ReportMax[];


//Turn on of the random generator
private static final Random r  = new Random();

//This method generates random chars
private  static  Character  randomChar()
{
    return  ( char ) ( r.nextInt( 26 ) + 65  );
}

/* We generate NIndiv individuals (strings)
 ten characters long.
 Sequences are completely random */
private static void Initialization( )
{	
    System.out.println("ORIGINAL POPULATION");
    for(int i = 0; i< NIndiv; i++)
    {
        //Initialization 	in blank.
        Individual[i]="";

        //An individual is assembled char by char		
        for(int j = 0; j< 10; j++)
        {
            //We generate a random char
            Character c =  randomChar();
            //System.out.println( "char = " + c);
            //Char c is converted into a string s
            String s = ""+c;
            //s is concatenated to Individual[i]
            Individual[i] = Individual[i]+s;
        }
        System.out.println("Individual " +  i);
        System.out.println( Individual[i]);
    }

    

    for(int i = 0; i< NIndiv; i++)
        Rank[i]=0;

    ReportMin= new int[nGen];
    ReportMax= new int[nGen];
    for(int gen = 0; gen < nGen; gen++)
    {
        ReportMax[gen]=0;
        ReportMin[gen]=0;
    }
         

                     
}
		

//This method takes substring a
//and posits it at place Start inside c
private  static  String
      Insert(String a, int Start, String c)
{
    
    String  s1, s2;
    //	We copy  the left part of c
    s1 = c.substring(0, Start);
    //	We copy  the right part of c
    s2 = c.substring(Start);
    // We concatenate the left part of c
    //to a to the right part of c
    String z = s1 + a + s2;
    /*System.out.println("Original c " + c);
    System.out.println("Original a " + a);
    System.out.println("Start " + Start);
    System.out.println("PosInsertion c = " + z); 
    */
    return z;
}

//The letters of "ALGAE" are inserted 
//into the string of individual i
private static  void feeding(int i)
{
    String a;
    // We measure the length of Individual[i]
    int l = Individual[i].length();
    //Null strings cannot feed anyhow
    if (l == 0) ; 
    else //Non null strings  feed on ALGAE
    {
        a = "A";
        int Start = r.nextInt(l);
        Individual[i] = Insert(a, Start, Individual[i]);
        a = "L";
        l = Individual[i].length();
        Start = r.nextInt(l);
        Individual[i] = Insert(a, Start, Individual[i]);
        a = "G";
        l = Individual[i].length();
        Start = r.nextInt(l);
        Individual[i] = Insert(a, Start, Individual[i]);
        a = "A";
        l = Individual[i].length();
        Start = r.nextInt(l);
        Individual[i] = Insert(a, Start, Individual[i]);
        a = "E";
        l = Individual[i].length();
        Start = r.nextInt(l);
        Individual[i] = Insert(a, Start, Individual[i]);
    }
}

	
//This Function replaces all occurrences of
//substring a by b inside c
private static String
Substitution(String a, String b, String c)
{
    String z = c.replace(a,b);
    /*System.out.println("original a " + a);
    System.out.println("Original b " + b);
    System.out.println("Original c " + c);
    System.out.println("replaced c " + z);
    */
    return z;
}


//This function or method deletes all occurrences 
//of a from c.
static private String Delete(String a, String c)
{
    b = "";
    return Substitution(a, b, c);
}


//Here we see what a PARA-SITE  does to individuals.
private  static void parasitation(int i)
{
    int l  =  Individual[i].length();	
    //The parasite deletes from the 
    //beginning of the individual
    //any substring   matching "PARA".
    //We copy to Beginning the first 
    //4 chars of Individual[i]
    if ( l > 4)
    {
        String Beginning =  Individual[i].substring(0,4);
        String s = "PARA";
        // We compare Beginning and s
        if (Beginning.equals(s))
            Individual[i] = Individual[i].substring(4);

        //The parasite deletes from the tail 
        //of the individual
        //any substring   matching "SITE".
        String Ending =  Individual[i].substring(4);	

        String t = "SITE";
        // We compare Ending and t
        if (Ending.equals(t))  Individual[i] = 
                    Individual[i].substring( 0,l - 4);
    }
 }


//In this method individuals are mutilated
//as a measure to hinder overgrowth.
//We delete from the original string
//a substring of a random length beginning with 
//a random Start position.
private static void Purge(int i)
{
    String c, s1, s2;
    int lc, Start, n;
    c = Individual[i];
    lc = c.length();
    if (lc > largeSize)
    {
        Start = r.nextInt(lc);
        //We copy  the first part of c
        s1 = c.substring(0, Start);
        // We throw a random number	
        n = r.nextInt(lc - Start+1);
        //We copy  the right part of c
        // after Start + n places
        s2 = c.substring( Start+ n);	
        //We concatenate the left part of c
        //to  the right part of c
        Individual[i] = s1 + s2;
    }
}


//Individuals are sorted by fitness.
//Fitness = length, as an indicator of complexity.
private static void Sorting()
{
    int   Champ;
    //Necessary default initialization
    int Fitness[] = new int[100];
    for(int i = 0; i< NIndiv; i++)
        Fitness[i] =0;
    //We define a fitness function equal to the length
    //of the string
    for(int i = 0; i< NIndiv; i++)
    {   
        String s = Individual[i];
        Fitness[i] = s.length();
        //System.out.println(Individual[i] + Fitness[i]);        
    }	
    //We sort individuals by fitness
    for(int i = 0; i< NIndiv;i++)
    {
        Champ = 0;
        for(int j = 0; j< NIndiv;j++)
            if (Fitness[j] > Fitness[Champ])   Champ = j;

        //The array Rank keeps a record of fitness
        //by decreasing order.
        Rank[i] = Champ;
        //The champ leaves the game
        Fitness[Champ] = 0;
        
    }
    /*
    //Report in decreasing order
    System.out.println("\nSorting :");
    for(int i = 0; i< NIndiv;i++)
        System.out.println(Individual[Rank[i]]);
    */
}


//The top ten fill the world
    private  static void Copying()
    {
        int   k;
        for(int i = 0; i< 10; i++)
        {
            int  l = 10*(10-i);
            for(int j = 0; j< 10; j++)
            {			
                k = l -j-1;
                Individual[k] = Individual[Rank[i]];
                /*System.out.println("Ind " + k 
                        + " replaced by top" + i);*/
                        
            }
        }

        //System.out.println(  "THE NEW POPULATION IS");

        // for(int i = 0; i <  NIndiv;i++)
        //System.out.println(  Individual[i]);
    }

private static void Reproduction()
{
    //Individuals are sorted by length
    Sorting();
    //for(int i = 0; i< 10;i++)
    //System.out.println(  Individual(Rank(i))
    //The top ten produce a copy that
    //substitutes the bottom ten.
    Copying();
}

// From individual i
// the fist n  chars are deleted
private static   void Deletion(int i)
{
    int l, n;	
    l = Individual[i].length();
    n = 0;
    if (l > 0)  n = r.nextInt(l);
    Individual[i] = Individual[i].substring(n);
 }

//This method inverts a
static private   String Inversion(String a)
{
    int  la = a.length();
    //Output
    String  d  = "";

    //We copy the first character of a to the last place
    //and so on.
    for(int  i = 0; i < la; i++)
     {
        char charI = a.charAt(i);
        d = charI + d;
     }
    return d;
}

//Local inversion of a substring inside individual i.
private static void innerInversion(int i)
{    
    String sLeft, sRight;
    int start;
    int n;
    String c = Individual[i];
    int lc = c.length();
    if (lc > 1)
    {
        start = r.nextInt(lc);
        //We copy  the first part of c
        sLeft = c.substring(0, start);
        // We throw a random number	
        n = r.nextInt(lc - start+1);
        //Inner substring
        String a = c.substring(start, start + n);
        String d = Inversion(a);
        //We copy  the right part of c
        // after Start + n places
        sRight = c.substring( start+ n);	
        //We concatenate the left part of c
        //to  the right part of c
        Individual[i] = sLeft + d + sRight;
    }
    /*System.out.println("Input  =   " + c + "  " + n);
    System.out.println("Output  =  " + Individual[i]);   
    */
}

//We consider only two types of mutation:
//deletion of the beginning
//and inversion of an inner part.
private static void Mutation()
{ 	
    //Which mutation affects which individual
    //is a matter of gambling.
    //We throw a 0 else a 1
    for(int i = 0; i< NIndiv; i++)
    {
        int Luck = r.nextInt(2);
        if ( Luck == 1) Deletion(i);
        else  innerInversion(i);
    }
}

private static String recombinant(int i)
{ 	   
    
    int n = Individual.length;
    //A partner for i is found    
    int j = r.nextInt(n);
     
    //A place for recombination
    int lengthI =  Individual[i].length();
    int lengthJ =  Individual[j].length();
    int minLength = Math.min(lengthI,lengthJ);
    int place = r.nextInt(minLength);
    String recombinant = Individual[i].substring(0, place)
            + Individual[j].substring(place);
    /*
    System.out.println( "Inputs = " + Individual[i] 
            + "    " + Individual[j]
    + " Recombinant = " + recombinant);
    */
    return recombinant;   
}


//Two strings are taken as input 
//and one recombinant is produced
private static void Recombination()
{ 	
    
    
    //Array with recombinant individuals
    String Individual2[ ] = new String[100]; 
    for(int i = 0; i< NIndiv; i++)
    {
        Individual2[i] = recombinant(i);
    }
    //Recombinants become the official population
    for(int i = 0; i< NIndiv; i++)
    {
        Individual[i] = Individual2[i];
    }
    
}



//This is the heart of the process
private static void Dynamics()
{
    //All individuals feed
    for(int i = 0; i< NIndiv; i++)
    {
        //The string Algae is digested and inserted
        //into the individual[i] char by char
        /*System.out.println( "The hungry individual "
                     + i + " is " + Individual[i]); */
        feeding(i);
        /*System.out.println(  "The full individual "
             + i + " is " + Individual(i)); */
        //All individuals are tested by the parasite,
        //which corrodes any  large substring
        //similar to it located at any end.
        parasitation(i);
        /*System.out.println(  "Pos-parasitation individual "
             + i + " is " + Individual(i));*/
        //Very long chains are attacked recurrently,
        //the same as very large fishes in the sea.
        Purge(i);
        /*System.out.println(  "The purged  individual "
             + i + " is " + Individual(i)); */
    }
    //The top ten are allowed to  reproduce:
    //a child occupies the place of the shortest individual
    Reproduction();
    //The new population is subjected to mutation
    Mutation();
    Recombination();
}
	

private static void report(int gen )
{
    System.out.println("\nPopulation at gen = " + gen );
    for(int j = 0; j< NIndiv; j++)
    {
        System.out.println("Gen " + gen + " Ind "
                     + j +" " +  Individual[j]);	
    }
}

//Min and Max lengths are detected
private static void Observation(int gen)
{		
    int m, Min, Max;
    Max = 0;
    Min = 32000000;
    for(int j = 0; j< NIndiv; j++)
    {
        m =  Individual[j].length();
        /*System.out.println(  "The Individual  "
           + Individual(j) + " has length " + m);*/
        if (m > Max)  Max = m;
        if (m < Min)   Min = m;
    }
    
    /*System.out.println(  "Generation "  + Gen
    + " MinLength = " + Min + " MaxLength = " + Max);*/
    ReportMin[gen] = Min;
    ReportMax[gen] = Max;
}

public static void main(String[] args)
{		 					
    Initialization( );

    for(int gen = 0; gen < nGen; gen++)
    {				
        //System.out.println( "Beginning3");
        Dynamics();
        report(gen);
        //The aim of observation is to record
        //the minimum and maximum lengths
        //of the individuals in each generation.
        Observation(gen);		  	
    }
    //Report of the dynamics of min and max indicators.
    System.out.println( "GENERATION MIN AND MAX VALUES");
    for(int Gen = 0; Gen < nGen; Gen++)
        System.out.println( Gen + "\t" + ReportMin[Gen]
        + "\t" + ReportMax[Gen]);

}

}//End of Program A140 Letterzymes3



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ejvol1;


// Program 185 FreqTable
// Mean and variance of a
// table of absolute frequencies.

public class FreqTable
{

   public  static void main( String args[] )
   {
        //Frequecy table: datum  and its frequency.
        int  Data[][] = {{3, 3},
    		         {4, 3},
    		         {5, 2},
    		         {6, 2},
    		         {7, 1},
    		         {8, 1}};
    		

        // Report of input data
        System.out.println( "Datum and its frequency" );
        for ( int i = 0; i < Data.length; i++ )
        {
            System.out.println( Data[ i ][0]+
                           "\t "+ Data[ i ][1]);        	
        }
        // Let us calculate the mean
        double sum = 0;
        //Number of data
        int n = 0;
        for ( int i = 0; i < Data.length; i++ )
        {
            sum = sum + Data[i][0]*Data[i][1];
            n  = n + Data[i][1];
        }
        double mean = sum / n;
        System.out.println( "Sum \t "+ sum);
        System.out.println( "Mean \t "+ mean);
        // Let us calculate the variance
        double sum2 = 0;
        for ( int i = 0; i < Data.length; i++ )
        sum2 = sum2 + Data[i][1]*(Data[i][0]-mean)
                                      *(Data[i][0]-mean);
       double var = sum2 / n;
                   System.out.println( "Variance \t "+ var);
   }
}//End of Program 185 FreqTable



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A346 Drawing5
//This class  draws a moving  face
//with blinking eyes.

package ejvol1;


import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
		
public class Drawing5 extends Applet
{
	
private static final long serialVersionUID = 1L;
	
    public void drawFace(Graphics g, int k)
    {
        //face
        g.setColor(Color.pink);			
        g.fillOval(15+k,15,100,150);
        //hair
        g.setColor(Color.black);
        g.fillRect(3+k,3,130,35);
        //mouth
        g.setColor(Color.red);
        g.fillOval(50+k,120,30,20);
        //eyes
        g.setColor(Color.blue);
        g.fillOval(30+k,50,30,20);
        g.fillOval(70+k,50,30,20);
        //nose
        g.setColor(Color.red);
        g.drawRect(55+k,70,20,40);	
    }

    public void  eraseface(Graphics g,int k)
    {
        //face
        g.setColor(Color.white);			
        g.fillOval(15+k,15,100,150);
        //hair
        //g.setColor(Color.black);
        g.fillRect(3+k,3,130,35);
        //mouth
        //g.setColor(Color.red);
        g.fillOval(50+k,120,30,20);
        //eyes
        //g.setColor(Color.blue);
        g.fillOval(30+k,50,30,20);
        g.fillOval(70+k,50,30,20);
        //nose
        //g.setColor(Color.red);
        g.drawRect(55+k,70,20,40);		
    }

    
    public void closeEyes (Graphics g, int k)
    {
        // We erase eyes:
        // eyes are painted in pink
        g.setColor(Color.pink);
        g.fillOval(30+k,50,30,20);
        g.fillOval(70+k,50,30,20);
        // We draw smaller eyes
        g.setColor(Color.blue);
        g.fillOval(30+k,65,30,5);
        g.fillOval(70+k,65,30,5);
    }

    public void openEyes (Graphics g, int k)
    {
        // small eyes are erased
        // We draw smaller eyes
        g.setColor(Color.pink);
        g.fillOval(30+k,65,30,5);
        g.fillOval(70+k,65,30,5);
        //We redraw eyes:
        // eyes are drawing in blue
        // and normal size
        g.setColor(Color.blue);
        g.fillOval(30+k,50,30,20);
        g.fillOval(70+k,50,30,20);

    }

    public void delay(long l1,int l)
    {			
      while  (System.nanoTime() < l1 + l) {delay(l1,l);}
    }

    @Override
    public void  paint (Graphics g)
    {
        drawFace(g,0);
        // This loop controls the numbers
        // of cycles of the graphic
        for(int kl = 0; kl<5; kl++)
        {				
            // k is the horizontal jump
            int k = 10*kl;
            //We erase everything
            g.clearRect(0,0,200,200);
            // We draw face in the new place
            drawFace(g,k);
            // This loop controls the   blinking number
            for(int i=0; i<2; i++)
            {
                // A delay must be introduced to make
                //  movement visible for a human being.
                System.out.print("Cycle = " + kl);
                System.out.println(". Blinking = " + i );		


                long  l1 = System.nanoTime();

                int l = 500;
                for(int j=0; j<4000000; j++)	
                    delay(l1,l);

                closeEyes(g, k);

                //A delay is inserted			
                l1 = System.nanoTime();				
                l = l*40;
                for(int j=0; j<2000000; j++)	
                         delay(l1,l);

                openEyes(g,k);			   	    	
            }	
        }
        System.out.println("Job done.");
    }
}//End of Program A346 Drawing5



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A69 Duplication
//This program duplicates the substring
//of a from points 3 to 7.

package ejvol1;


public class Duplication
{
    public static void main(String[] args)
    {
        String a, c, s1, s2;
        a = "Duplication is the key to amplification";
        System.out.println("Original string = " + a);
        //String to duplicate
        c= a.substring(3, 7);
        System.out.println("Substring to duplicate = " + c);
        //We copy  the first part of a
        s1 = a.substring(0, 7);
        System.out.println("The left part of c is = " + s1);

        //We copy  the right part of a
        s2 = a.substring(7);
        System.out.println("The Right part of a is = " + s2);

        //We concatenate the left part of c
        // to  a to the right part of c
        String Duplication = s1   + c + s2;
        System.out.println("Duplication = " + Duplication);
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A90 GeneticCode2
//A simplified genetic code.
//Structured version.
package ejvol1;

public class GeneticCode2
{	
    //Variables that are declared at this heading
    //are global to enable global invokation.
    
    //Declaration and assignation of the array
    //There are 2 columns. Capacity unspecified.
    
    //Static = use permanent memory
    //Final = unmodifiable.
    private static final String  genCode[][] = { {"AUU","Ile"},
    		                {"UUA","Leu"},
    		                {"UAU","Tyr"},
    		                {"AUA","Arg"},
    		                {"AAU","Asn"},
    		                {"AAA","Lys"},
    		                {"UUU","Phe"},
    		                {"UAA","Term"}
    		               };
    
    //RNA string
    private static final String c = "AUUUUAUUAUAUAUAUAUAU"+
                 "AUAUAUAUAUAUUUAUAUAU"+
                 "AUAUUUAA";
    
    private static final String dash = "-";
    
    private static int nCodons;
    
    private static String cc;

    //Initial setting is reported.
    //This method reports nothing: that is why it is void
    private static void report()
    {
        System.out.println( "The genetic code is" );
        //  One loop for the rows.
        //  To know the length of the array : genCode.length
        for ( int i = 0; i < genCode.length; i++ )
        {
            System.out.print( genCode[ i ][ 0 ]  +
                  "	" +
                  genCode[ i ][ 1 ] );
            System.out.println(); //pass to the next line
        }

        // We get the length of c.
        //This a local variable, cannot be invoked outside
        //this method.
        int lc = c.length();
        //  We get the number of codons:
        nCodons = lc / 3;
        System.out.println( "Length   = " + lc);
        System.out.println( "Number of codons = " + nCodons);
         //Copy of c for easy reading
        cc = c;
        //Insert a dash to separate one codon from another.
        //Begin with the right end, move to the left,
        //and terminate at t he first codon.
        for(int i = nCodons-1; i >0;  i--)
        {
            String t  = cc.substring(0, 3*i);
            //Debugger line
            //System.out.println("t = " + t);
            //Dash is inserted
            cc = t + dash +  cc.substring(3*i);
            //System.out.println("cc = " + cc);
        }
    }
    
    //RNA string c is translated into a
    //polypeptide chain that is also a string.
    //This method demands a string to be returned.
    private static String  translation(String c)
    {
        //We translate codon by codon.
        //The output sequence z is initialized
        String z = "";
        int start;
        for(int i = 0; i< nCodons ; i++)
    	{
            //We copy the ith codon of c into a
            start = 3 * i;	
            String a = c.substring(start,start+3);

            //We revise the Genetic code to know
            //the corresponding row m where a is located:
            int m = 0; //default initialization
		
            for( int  j = 0; j < genCode.length; j++ )		
            {
                if ( a.equals(genCode[ j ][ 0 ]) )
                {
                    m = j;
                    // If the codon is located in 
                    //the dictionary, exit the loop:
                    break;
                }
                		
            }
            //Debugging line
            //System.out.println( a + " " + m);
				
            //We consult the dictionary in the other column
            //and synthesize z by adding the equivalent value
            z = z + "-" + genCode[m][1];
            
	}
        //First dash is deleted
        z = z.substring(1);
        return z;
    }
        
    
   public  static void main( String args[] )
   {
        
        report();
        String z = translation(c);
        //Final report
        System.out.println( "RNA and protein sequences:");
        System.out.println( cc + "\n" + z);
   }
}//End of program A90 GeneticCode2



:::::::::::::  NEW PROGRAM  :::::::::::::


// Program 262 LotkaVolterra2
// Study  of a prey-predator system.
// Deterministic model.
// Lotka-Volerra equations.
// Periodicity observed.
// Compatible with all versions of Excel and Cal.

package ejvol1;



public class LotkaVolterra2
{
    static double nr, nw, e, m,p,l,  k;
		
    public static void initialization()
    {
        //Generates 500 rabbits,  50 wolfs
        nr = 500;
        nw = 50;
        // Rate of rabbit's reproduction
        m = 0.1;
        // Rate of predation
        p = 0.01;
        // Rate of wolf's death
        k = 0.05;
        // Rate of wolf reproduction
        l= 0.1 * p ;
    }
	
    public static void dynamics()
    {
        String s1,s2,s3,s4;
        //We run N generations
        int n = 1000;
        for(int  i = 0; i< n;i++)
        {
            //Rabbits reproduce
            nr = nr + m* nr;
            //Rabbits are preyed on
            nr = nr - p * nr * nw;
            //Wolfs reproduce
            nw = nw + l* nr * nw;
            //Wolfs die
            nw = nw - k * nw;

            //Decimal with point.
            //System.out.println(i + "\t"
            //        +  nr + "\t " +  nw);
            
            
            //Decimal numbers with comma.
            //Conversion of number nr, nw
            //into a format appropriate for Excel:

            s1 = String.valueOf(nr);
            s2 = s1.replace(".", ",");
            s3 = String.valueOf(nw);
            s4 = s3.replace(".", ",");
            
            System.out.println(i + "\t"
                    +  s2 + "\t " +  s4); 
        }
    }

    
    public static void main(String[] args)
    {
        initialization();
        System.out.println("time, rabits and wolfs");
        dynamics();
    }
}//End opf Program 262 LotkaVolterra2



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A52 Concatenation2
//Concatenation of strings
package ejvol1;


public class Concatenation2
{
 
    public static void main(String[] args)
    {
        //Declaration of type of variables
	String s0, s1, s2, s3, s4;
        //Assignation
        s0 = "My aim is to become ";
        s1 = "the best ";
        s2 = "simulator ";
        s3 = "of evolution ";
        s4 = "in the history of the world";	
        //Declaration and assignment
        String s5 = s0 + s1+s2+s3 +s4;
        System.out.println(s5 + "!"); //action
    }
}




:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A57 Replace4
//Simplified version of program A55

package ejvol1;



public class Replace4
{
    public static void main(String[] args)
    {	
        String tab = "\t";		
        for(double i = 1; i<=2.05 ; i= i + 0.05 )
        {	
            String s1 = String.valueOf(i);
            String s2=s1.replace(".", ",");
            String s3,s4;	
            //We calculate the square of i:
            s3 = String.valueOf(i*i);
            s4=s3.replace(".", ",");
            System.out.println(s2 + tab + s4);
        }	
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


//Program   A7  EJVol1
// This is my first program.
//It prints a message to the console.
// printSomething is the name of this class.
//A7 is the reference number of this program along this series.

//To run this program:
//Click over here and apply Shift + F11
//and then Shift + F6.

//Package declaration
package ejvol1;


//Class declaration
public class EJVol1
{	

	//The next is the main method
	public static void main(String[] args)
	{	
	
		  // This is a comment.
		
		  // Comments help to understand programs.
		
		  // The next line contains an instruction
		  // that prints a message on the console:
		
		  System.out.println("I am starting up! ");
	
	}
}



:::::::::::::  NEW PROGRAM  :::::::::::::


//Program A293 Interface2
//Interface for birds vs moths.
//AWT based code.

package ejvol1;

import java.awt.*;
import java.applet.Applet;


public class Interface2 extends Applet
{
	
    private static final long serialVersionUID = 1L;

    Label invitation1; //message to the user
    TextField input1;  //input from the user
    Label invitation2;
    TextField input2;
    Label invitation3;
    TextField input3;
    Label invitation4; //message to the user
    TextField input4;  //input from the user
    Label invitation5;
    TextField input5;
    Label invitation6;
    TextField input6;
    Label invitation7; //message to the user
    TextField input7;  //input from the user
    Label invitation8;
    TextField input8;
    Label invitation9;
    TextField input9;
    Label invitation10;
    TextField input10;
    Label invitation11;
    TextField input11;
    static int n,nw,nbr, nb; //working variables
    static double     mr, mut;
    static double  maxM, maxB, pw, pbr,bd;
	
	

    @Override
    public  void   init()
{
    
    //Input machinery
    //Declaration
    // A Label displays an invitation to operate
    invitation1 = new Label("Number of generations");
    //A TextField is a place for writing.
    input1 = new TextField( "1000");
    invitation2 = new Label("Initial number of white moths");
    input2 = new TextField( "450");
    invitation3 = new Label("Initial number of brown moths");
    input3 = new TextField( "450");
    invitation4 = new Label("Initial number of birds");
    //A TextField is a place for writing.
    input4 = new TextField( "10");
    invitation5 = new Label("Reproduction rate  of moths");
    input5 = new TextField( "0.1");
    invitation6 = new Label("Moth's mutation rate");
    input6 = new TextField( "0.01");
    invitation7 = new Label("Max number of moths");
    //A TextField is a place for writing.
    input7 = new TextField( "2000");
    invitation8 = new Label("Max number of birds");
    input8 = new TextField( "20");
    invitation9 = new Label("Predation rate on white moths");
    input9 = new TextField( "0.001");
           // A Label displays an invitation to operate
    invitation10 = new Label("Predation rate on brown moths");
    //A TextField is a place for writing.
    input10 = new TextField( "0.002");
    invitation11 = new Label("Bird's rate of death  + ENTER");
    input11 = new TextField( "0.05");

    // activation
    add(invitation1);
    add(input1);
    add(invitation2);
    add(input2);
    add(invitation3);
    add(input3);
    add(invitation4);
    add(input4);
    add(invitation5);
    add(input5);
    add(invitation6);
    add(input6);
    add(invitation7);
    add(input7);
    add(invitation8);
    add(input8);
    add(invitation9);
    add(input9);
    add(invitation10);
    add(input10);
    add(invitation11);
    add(input11);
  }

//This is the listening instrument of the interface:
//The system reads parameters
//if the user presses enter into the ELEVENTH field.
//This method is deprecated because a better technology
//was developed since 1996 and comes in three versions:
//1) AWT + Applet improved, simple and effective:
//Internet Programming with Java Course.Applets
//http://www.nakov.com/inetjava/lectures/part-2-applets/InetJava-2.1-2.2-Introduction-to-AWT-and-Applets.html
//2) Swing, very good and robust: keep working with this series.
//3) JavaFX, released in 1914. Modern and very powerfull 
//but  a bit inmature as yet (2015):.
//If you aim at great things wih Java programming,
//JavaFX is your must.
//Find a soft introduction in Vol XII Fossils, in this series.

@SuppressWarnings( "deprecation" )
    @Override
public boolean action(Event event, Object o)
  {	
    if (event.target == input11)
    {
        //We read textFields
        n = Integer.parseInt(input1.getText() );
        nw = Integer.parseInt(input2.getText() );
        nbr=Integer.parseInt(input3.getText() );
        nb = Integer.parseInt(input4.getText() );
        mr = Double.parseDouble(input5.getText() );
        mut= Double.parseDouble(input6.getText() );
        maxM = Double.parseDouble(input7.getText() );
        maxB = Double.parseDouble(input8.getText() );
        pw= Double.parseDouble(input9.getText() );
        pbr = Double.parseDouble(input10.getText() );
        bd = Double.parseDouble(input11.getText() );
        //We call the simulation.
        Interface.master(nw, nbr, mr, mut, maxM, maxB,
        nb, pw, pbr, bd, n);
   }
   //Indicate to the system that the action
   //of the user has been processed.
   return true;
  }
}//End of Program A293 Interface2



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A135 Letterzymes
//Evolution with letterzymes step 1:
//initialization of  a population.
package ejvol1;



import java.util.Random;

public class Letterzymes
{	
    // Declaration of global variables.
    // They are used all throughout the whole class.

    // Individual  is an array of strings.
    static String Individual[ ];//Declaration
    static int NIndiv ; //declaration
    static String PatternParasite, PatternFood;
    // Order  is an array of integers.
    static int Order[];
    static String b;
    static int Gen;
    static int ReportMin[], ReportMax[];


    // Turn on of the random generator
    static Random r  = new Random();

    // This method generates random upper chars	
    private  static  Character  randomChar()
    {
        return  ( char ) ( r.nextInt( 26 ) + 65  );
    }

    /* We generate NIndiv individuals (strings)
	 ten characters long.
	 Sequences are completely random */
    private static void Initialization( )
    {	
        //Formal declaration of our array.	
        Individual = new String[100];
        for(int i = 0; i< NIndiv; i++)
        {
            //Initialization 	in blank.
            Individual[i]="";

            //An individual is assembled char by char		
            for(int j = 0; j< 10; j++)
            {
                //We generate a random char
                Character c =  randomChar();
                //System.out.println( "char = " + c);
                //Char c is converted into a string s
                String s = ""+c;
                //s is concatenated to Individual[i]
                Individual[i] = Individual[i]+s;
            }
            System.out.println("Individual " +  i);
            System.out.println( Individual[i]);
        }

        //We generate a parasite pattern
        PatternParasite = "PARASITE";
        //We generate a food pattern
        PatternFood = "ALGAE";	
    }



    public static void main(String[] args)
    {		 			
        //The population has NIndiv members, NIndiv >10
        NIndiv = 15;
        Individual= new String[NIndiv]; 		
        Initialization( );
    }
}//End of Program A135 Letterzymes




:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A213 RandGenerator9
// A source generates random integers
// with a given distribution.

package ejvol1;

//Program A213 RandGenerator9
// A source generates random integers
// with a given distribution.

import java.util.Random;

public class RandGenerator9
{
    // Absolute frequencies are defined:
    static int Table[] =  {3,2,0,5};
	
    // Counters are in count
    static int count[] = new int[4];
	
    // Turn on of the random generator
    static Random r  = new Random();

    public static void main(String[] args)
    {
        for (int i=0; i<Table.length;i++) 
            count[i]=0;
        
        for (int i=0; i< 10000;i++)
        {
            //A random integer less than 10 is generated
            //with a uniform distribution
            int n = r.nextInt(10);
            //Outputs are renamed
            if (n<3) count[0]=count[0]+1;
            if ((3<= n )& (n<5)) count[1]=count[1]+1;
            if ((5<= n )& (n<10)) count[3]=count[3]+1;
        }
        for (int i=0; i<Table.length;i++)
                System.out.println(i + "\t" + count[i]);
    }
}//Program A213 RandGenerator9 



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * Program A37 ForLoop3
 */
// Variation of the for statement.

package ejvol1;


public class ForLoop3
{
		
    public static void main(String[] args)
    {			
        String tab = "\t";			
        for(int i = 0; i<=10; i++)
            {		
                System.out.println(i + tab + i*i);
            }
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::




//Program A287 Dialog3
//Event based programming.
//A dialog with two inputs.
//AWT + JApplet + Swing based code.
package ejvol1;


import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JTextField;


//We declare that the class must 
//be armed with JApplet's tools
//and that must include a facility to 
//listened at the prompts of the User.
public class Dialog3 extends JApplet implements ActionListener
{
    private static final long serialVersionUID = 1L;

    //A label contains a message to the User
    private JLabel resize;
    private  JLabel invitation1; //message to the user
    //A textField reads the input from the User
    private  JTextField input1;  //input from the user
    private  JLabel invitation2;
    private JTextField  input2;
    private JLabel sum ;
   


@Override
public void init() 
{
    this.resize = new JLabel("Resize the applet for a better view!" );

    //Input machinary
    //Declaration
    // A Label displays an invitation to operate
    this.invitation1 = new JLabel("Input first parameter ");
    //A TextField is a place for writing.
    this.input1 = new JTextField( 10);
    this.invitation2 = new JLabel("Input second parameter + enter ");

    this.sum = new JLabel("The sum is " );
    this.input2 = new JTextField( 10);
    this.input2.addActionListener( this);

    //Activation
    this.add(resize);
    this.add(invitation1);
    this.add(input1);
    this.add(invitation2);
    this.add(input2);    
    this.add(sum);
    // Let Swing manage the layout.
    this.setLayout(new FlowLayout());
    
}

@Override  
public void actionPerformed(ActionEvent event)
{  
    // If the User presses enter into the second field
    //Read textField1 and textField2
    //Read as String and translated to Double
    Double num1 = Double.parseDouble(this.input1.getText() );
    Double num2 = Double.parseDouble(this.input2.getText() );
    Double result = num1 + num2;
    //The text of label sum is updated
    this.sum.setText("The sum is "  + result.toString());
    //Make a report to the console.
    // Here we report results.
    // We use the console
    // because we expect large volumes of data
    System.out.println("Number 1 " + "\t " + num1 );
    System.out.println("Number 2" + "\t " + num2 );

    System.out.println("The sum is " + "\t " + result );
    System.out.println();
}
}//End of Program A287 Dialog3



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A170 PrintVectors
//Threading: part two of two.
//This program creates instances of Vector
//and commands to run them in different threads.
package ejvol1;



import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;

public class PrintVectors
{
   public static void main( String[] args )
   {
        // We create and name each instance or runnable
        Vector vec1 = new Vector(0, 5);
        Vector vec2 = new Vector(1, 50 );

        System.out.println( "Program started" );

        //Mandatory initialization
        ExecutorService threadExecutor =
            Executors.newCachedThreadPool();

        // threads are started
        threadExecutor.execute( vec1 );
        threadExecutor.execute( vec2 );


        //  threads are killed if tasks are completed.
        threadExecutor.shutdown();

   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


//Program A291 Interface

/*
Study of predation of moths by birds.
Moths could be white or brown.	
Two environments: clean and dirty.
Discrete  stochastic logistic model.
Mutation is included.
Positional bug has been corrected. 	
AWT + Applet interface.
*/

package ejvol1;


import java.util.Random;
public class Interface
{	
    static int n, nw, nbr, nb;
    static double   mr, mut;
    static double  maxM, maxB, pw, pbr,bd;
	
	
    //Turn on of the random generator
    static Random r  = new Random();


    private static void report()
    {
        //We report results to the console.
        System.out.println("n" + "\t " + n );
        System.out.println("nw" + "\t " + nw );
        System.out.println("nbr" + "\t " + nbr );
        System.out.println("nb" + "\t " + nb );
        System.out.println("mr" + "\t " + mr );
        System.out.println("mut" + "\t " + mut );
        System.out.println("maxM" + "\t " + maxM );
        System.out.println("maxB" + "\t " + maxB );
        System.out.println("pw" + "\t " + pw );
        System.out.println("pbr" + "\t " + pbr );
        System.out.println("pd" + "\t " + bd );
    }

    private static void reinitialization()
    {	
        //probability of predation on white moths
        double tr = pw;
        pw = pbr;
        //probability of predation on brown moths
        pbr = tr;
        //Probability of bird's death		
    }
	
    private static void whiteReproduce()	
    {
        //White moths reproduce and mutate		
        double s = r.nextDouble();
        if (s < mr * (1 - (nw + nbr) / maxM) )
        {
            nw = nw + 1;
            if (s < mut)
            {
                nbr = nbr + 1 ;
                nw = nw-1;
            }
        }	
    }
	
    private static void brownReproduce( )
    {
        //Brown moths reproduce and mutate

        double s = r.nextDouble();
        if (s < mr * (1 - (nw + nbr) / maxM) )
        {
            nbr = nbr + 1;
            if (s < mut)
            {
                nbr = nbr - 1 ;
                nw = nw+1;
            }
        }
    }
	

	
    private static void dynamics( )
    {
        for(int i = 0; i < n; i++)
        {	
            // Reproduction is assigned
            // by a binomial random variable ( a coin)
            // to white else brown moths
            // in proportion to their numbers
						
            double totalMoths = nw + nbr;
            double probWhite = nw/totalMoths;
            for(int k = 0; k < totalMoths; k++)
            {
                double s = r.nextDouble();
                if (s < probWhite ) whiteReproduce();
                    else brownReproduce();
            }
		
            //Moths are preyed, birds reproduce
            for(int l = 0; l < nb; l++)
            {		
                //White moths
                for(int j = 0; j < nw; j++)
                {
                    double  s = r.nextDouble();
                    // a white moth is predated
                    if (s < pw){ nw = nw - 1;}
                    //birds reproduce
                    if ( s < 0.1 * pw * (1 - nb / maxB))
                    nb = nb + 1;
                }
                //brown moths
                for(int j = 0; j < nbr; j++)
                {
                    double  s = r.nextDouble();
                    // a brown moth is predated
                    if (s < pbr) nbr = nbr - 1;
                    //birds reproduce
                    if ( s < 0.1 * pbr * (1 - nb / maxB))
                    nb = nb + 1;
                }		
            }

		
            //Birds die
            for(int j = 0; j < nb; j++)
            {
                double   s = r.nextDouble();
                if (s < bd)  nb = nb - 1;
            }



            System.out.println(nw + "\t " + nbr + "\t " + nb);			
        }//end i for
    }	
		
    public static void master( 
        int nwa, int nbra,
        double mra, double muta,
         double  maxMa, double maxBa,  int nba, double pwa,
         double pbra, double bda,   final int na)
    {
		
        //Observe the new form as we initialize
        //Generates   moths,
        //white moths
        nw = nwa;
        // brown moths
        nbr = nbra;
        //Generates 10 birds
        nb = nba;
        //Probability of moth's reproduction
        mr = mra;
        // Mutation rate of moths
        mut = muta;
        //Maximum number of Moths
        maxM = maxMa;
        //Maximum number of Birds
        maxB = maxBa;
        //probability of predation on white moths
        pw = pwa;
        //probability of predation on brown moths
        pbr = pbra;
        //Probability of bird's death
        bd = bda;
        //Number of generations
        n = na;
			
        report();	
        dynamics();	
        // Here a change of environment is simulated:
        // the predation rates are interchanged:
        // white moths that before were invisible
        // now had become visible because
        // of blackening of their skin.
        // Now, brown moths are conspicuous.
        reinitialization();
        dynamics();
    }
}//Program A291 Interface



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A344 Drawing4
//This class  draws a face with blinking eyes.

package ejvol1;


import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;

public class Drawing4 extends Applet
{
    private static final long serialVersionUID = 1L;
		

	
    public void drawFace(Graphics g)
    {
        //face
        g.setColor(Color.pink);			
        g.fillOval(15,15,100,150);
        //hair
        g.setColor(Color.black);
        g.fillRect(3,3,130,35);
        //mouth
        g.setColor(Color.red);
        g.fillOval(50,120,30,20);
        //eyes
        g.setColor(Color.blue);
        g.fillOval(30,50,30,20);
        g.fillOval(70,50,30,20);
        //nose
        g.setColor(Color.red);
        g.drawRect(55,70,20,40);	
    }
			
    public void closeEyes (Graphics g)
    {
        // We erase eyes:
        // eyes are painted in pink
        g.setColor(Color.pink);
        g.fillOval(30,50,30,20);
        g.fillOval(70,50,30,20);
        // We draw smaller eyes
        g.setColor(Color.blue);
        g.fillOval(30,65,30,5);
        g.fillOval(70,65,30,5);
    }
			
    public void openEyes (Graphics g)
    {
        // small eyes are erased
        // We draw smaller eyes
        g.setColor(Color.pink);
        g.fillOval(30,65,30,5);
        g.fillOval(70,65,30,5);
        // We redraw eyes:
        // eyes are drawing in blue
        // and normal size
        g.setColor(Color.blue);
        g.fillOval(30,50,30,20);
        g.fillOval(70,50,30,20); 	
    }
			
    public void delay(long l1,int l)
    {
        while  (System.nanoTime() < l1 + l) {delay(l1,l);}
    }

    @Override
    public void  paint (Graphics g)
    {
        drawFace(g);
        // This loop control the   blinking number
        for(int i=0; i<4; i++)
        {
            // A delay must be introduced to
            // make movement visible for a human being.
            System.out.println(i);				
            long  l1 = System.nanoTime();

            int l = 500;
            for(int j=0; j<4000000; j++)	
             delay(l1,l);

            closeEyes(g);
            // The next loop creates a delay,
            // the duration of the delay is regulated
            // by the upper limit of j.

            l1 = System.nanoTime();				
            l = l*40;
            for(int j=0; j<2000000; j++)	
                delay(l1,l);
            openEyes(g);			   	    	
        }	
        System.out.println("Job done.");	
    }
}//End of Program A344 Drawing4



:::::::::::::  NEW PROGRAM  :::::::::::::


//Program A26 DivisionByZero2
//This program divides two integers.
//It is robust against
//division by zero.

package ejvol1;


public class DivisionByZero2
{		
    public static void main(String[] args)
    {
        //Declaration and initialization
        // of variables
        int x = 7;
        int y = 0;
        //Logical testing: == instead of =
        if (y == 0) //If divison by zero is proposed	
          System.out.println(
                  "The division by zero is forbidden");
        else //If y is different than 0, do this:
          {	
           //Computation and report
           System.out.print(" The integer division of x ="
                                + x );
           System.out.println( " by y = " + y + " is " + x/y);
          }
     }	
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A104 RandomMethods
//Permutation of order of execution
//of methods.
package ejvol1;


public class RandomMethods
{

    public static void zero()
    {
        System.out.print(0);	
    }

    public static void one()
    {
        System.out.print(1);	
    }

    public static void two()
    {
        System.out.print(2);	
    }

    public static void three()
    {
        System.out.print(3);	
    }

    public static void four()
    {
        System.out.print(4);	
    }

    public static void five()
    {
        System.out.print(5);	
    }

    public static void six()
    {
        System.out.print(6);	
    }

    public static void seven()
    {
        System.out.print(7);	
    }

    public static void eight()
    {
        System.out.print(8);	
    }

    public static void nine()
    {
        System.out.print(9);	
    }


    public static void main(String[] args)
    {
        // Let us write 345:	
        three();
        four();
        five();
        System.out.println();
    }
}//End of Program A104 RandomMethods



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A190 RandGenerator2
//Generates a discrete uniform distribution
//from one to ten.

package ejvol1;




import java.util.Random;

public class RandGenerator2
{

    // Turn on of the random generator
    static Random r  = new Random();


    static int Frec[ ];//Predeclaration

    public static void  chisquare()
    {
        double chi = 0;
        for(int j = 1; j<= 10; j++)
         chi  = chi +  (Frec[j]-100)*(Frec[j]-100)/100;
        System.out.println("Calculated chi-square = " + chi); 	
    }
	
    public static void main(String[] args)
    {
        Frec= new int[11];
        for(int j = 1; j<= 10; j++)
                Frec[j] = 0;
        for(int j = 0; j< 1000; j++)
        {
           // We generate a random sequence
           int c = r.nextInt(10) +1;
           Frec[c] = Frec[c]+1;
        }
        System.out.println("j, observed and "
                + "expected frequencies");
        for(int j = 1; j<= 10; j++)
            System.out.println(j + "\t" + Frec[j] + "\t100"); 	
        chisquare();
    }
}//End of Program A190 RandGenerator2



:::::::::::::  NEW PROGRAM  :::::::::::::



// Program 332 Drift2

// In this program we study drift
// in 1000 asexual  populations with constant size,
// one locus or enzyme, two alleles and no mutation.

package ejvol1;



import java.util.Random;

public class Drift2
{
		
    //Turn on  the random generator	
    static Random r  = new Random();


    // number of populations
    static int nPopulations = 1000;
    // population size, the same for all populations.
    static int size;
    static double po;
    // initial frequency of allele one,
    // the same for all populations.

    // actual frequency of allele one
    static int nOne[];
    // actual proportion of allele one
    static double p[];
    // number of generations
    static int nGen;
    // counts the number of allele1
    static double counterAllele1;
    // counts the number of times that allele1
    // was fixed.
    static double counterFixations;
    static double probFixation;
    // Record of the type of individuals
    // initial population:
    // allele1=true;
    // allele2=false;
    // The first entry is the pop subindex,
    // the second entry is the individual subindex
    static boolean population1[][],population2[][];
    // The distribution of p in the population
    static int distribp[];
    // We do not report every generation
    // but only when the generation is multiple of genSpace.
    static int genSpace ;
	
    public static void constructors()
    {
        p = new double[1000];
        nOne = new int[1000];
        distribp = new int[1000];
        population1 =new boolean[1000][1000];
        population2 =new boolean[1000][1000];	
    }
	

    public static void report( )
    {	
        for(int i=0; i<size; i++)		
            System.out.print(distribp[i] + "\t" );	
        System.out.println(); 	
    }
	
    public static void initialization()
    {
        size = 100;
        po = 0.8;
        nGen = 500 ;
        genSpace = 5;
        counterAllele1 = 0;
        counterFixations=0;

        //All populations are initialized
        int n;
        n = (int) Math.ceil( po*size);
        for(int pop=0; pop<nPopulations; pop++)	
        {		
            //initial population:
            //allele1=true;
            //allele2=false;


            for(int ind=1; ind<=n ; ind++)
                    population1[pop][ind]=true;

            for(int ind=n+1; ind<=size ; ind++)
                    population1[pop][ind]=false;
        }

        for(int j=0; j < size; j++)	
                distribp[j]=0;	
        distribp[n]=nPopulations;
        report( );
    }
	
	
    public static void iteration(int pop)
    {	
        //Sampling procedure
        for(int j=0; j<size; j++)	
        {
            int  m = r.nextInt(size)+1 ;
            population2[pop][j]= population1[pop][m];

            if (population2[pop][j]==true)
                counterAllele1 = counterAllele1 +1;
        }
       p[pop]=counterAllele1/size;
       nOne[pop]= (int) counterAllele1;

       // System.out.println( nOne[pop] + p[pop]);

       /* String s4 = String.valueOf(p[pop]);
       String  s5=s4.replace(".", ",");
        System.out.println( s5);	 */

       //updating
       counterAllele1=0;
       for(int ind=0; ind<size; ind++)			
                population1[pop][ind]=  population2[pop][ind];	    	
    }

    public static void reInitialization( )
    {
        for(int i=0; i<size; i++)		
            distribp[i] = 0;
        for(int pop=0; pop<nPopulations; pop++)	
        {
            nOne[pop] = 0;
            p[pop]=0;
        }	
    }
	
    public static void thousandPopulations(int gen)
    {
        for(int pop=0; pop<nPopulations; pop++)	
        {	
            iteration(pop);
            /* System.out.println(pop +"\t"+
                  nOne[pop] + "\t"+ p[pop]); */

            distribp[nOne[pop]] = distribp[nOne[pop]]+1;		  			
        }	
        //System.out.println(gen);
        if (gen % genSpace  == 0 )  report( );
        reInitialization();
    }
	
    public static void main(String[] args) 	
    {
        constructors();
        initialization();
        for(int gen = 0; gen < nGen; gen++)
            thousandPopulations(gen);
    }
}//Program 332 Drift2




:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A169 Vector
//Threading: part one of two.
//This class defines a prototype
//of a vector of odd numbers
//else even numbers.
package ejvol1;

//In threads, classes are called runnables.

public class Vector implements Runnable
{
    //Each instance has its name
    private final String vectorName;

    int l, limit;

    //Constructor
    //Prototype definition
    //k=0, even numbers
    //k =1, odd numbers
    public Vector( int k, int lim )
    {
        if (k==0)  vectorName = "evenNumbers"; 
         else vectorName = "oddNumbers";
        l=k;
        limit = lim;
    }

    // The vector is calculated and printed
    public void task(int k, int limit)
    {
        // Try and catch exception pair:

        int vec[] = new int[1000];
        try   // do this task
        {
            for(int j=0; j<=limit; j++)
            {
                vec[j]= 2*j+k;	
                //Thread is put to sleep
                //during s milliseconds
                int s = 2;
                Thread.sleep( s );
            }
            System.out.println(vectorName);
            
            for(int j=0; j<=limit; j++)
            {
                System.out.println( vec[j]);	

            }
        }
        catch ( InterruptedException exception )
        {
            System.out.println(   vectorName+
              "Killed from outside" );
        }
    }

    //This is the 'main method' of the
    //prototype constructor.
    @Override
    public void run()
    {	
        task(l, limit);
        //l defines parity, limit is the number
        // of entries in the vector.
    }
}//End of Program A169 Vector


/* Alternate version of the class Vector

//Program A169 Vector
//Threading: part one of two.
//This class defines a prototype
//of a vector of odd numbers
//else even numbers.
package ejvol1;


//This class defines a prototype
//of a vector of odd numbers
// else even numbers.
public class Vector implements Runnable
{
    //Each instance has its name
    private final String vectorName;

    int l, limit;

    //Constructor
    //Prototype definition
    //k=0, even numbers
    //k =1, odd numbers
    public Vector( int k, int lim )
    {
        if (k==0) vectorName = "evenNumbers"; 
        else vectorName = "oddNumbers";
        l=k;
        limit = lim;
    }

    // The vector is calculates and printed
    public void task(int k, int limit)
    {
        // Try and catch exception pair:

        int vec[] = new int[1000];
        try   // do this task
        {
            for(int j=0; j<=limit; j++)
            {
                vec[j]= 2*j+k;	
            }
            System.out.println(   vectorName);
            for(int j=0; j<=limit; j++)
            {
                System.out.println( vec[j]);	
                //Thread is put to sleep during k milliseconds
                int s = 2;
                Thread.sleep( s );
            }
        }
        catch ( InterruptedException exception )
        {
            System.out.println(   vectorName+
              "Killed from outside" );
        }
    }

    //This is the 'main method' of the
    //prototype constructor.
    public void run()
    {	
        task(l, limit);
        //l defines parity,
        //limit is the number
        // of entries in the vector.
    }
}
*/



:::::::::::::  NEW PROGRAM  :::::::::::::



package ejvol1;

//Program A285 Dialog2
//Event based programming.
//A dialog with two inputs.
//AWT + Applet based code.


//Silence this line to know wich items come from awt:
//they will appear in red.
import java.awt.*;
//Silence this line to know wich items come from Applet
import java.applet.Applet;


//We declare that the class must 
//be armed with Applet's tools.
public class Dialog2 extends Applet
{
    private static final long serialVersionUID = 1L;

    //A label contains a message to the User
    private static Label resize;
    private static Label invitation1; //message to the user
    //A textField reads the input from the User
    private static TextField input1;  //input from the user
    private static Label invitation2;
    private static TextField input2;
    private static double num1, num2; //working variables
    private static Label sum ;
    private static Double result;

    
@Override
public  void   init()
{
    resize = new Label("Resize the applet for a better view!" );
    //Elements must be added to the Applet
    add(resize);
    //Input machinary
    //Declaration
    // A Label displays an invitation to operate
    invitation1 = new Label("Input first parameter ");
    //A TextField is a place for writing.
    input1 = new TextField( 10);
    invitation2 = new Label("Input second parameter + enter ");
    sum = new Label("The sum is " );
    input2 = new TextField( 10);
    //Activation
    add(invitation1);
    add(input1);
    add(invitation2);
    add(input2);
    add(sum);
}


//Report to the console
public void report()
{
    // Here we report results.
    // We use the console
    // because we expect large volumes of data
    System.out.println("Number 1 " + "\t " + num1 );
    System.out.println("Number 2" + "\t " + num2 );
    result = num1 + num2;
    System.out.println("The sum is" + "\t " + result );
}

//What to do if the User demands attention
//This code is outmoded and deprecated but is simple.
@Override
@SuppressWarnings( "deprecation" )
public boolean action(Event event, Object o)
{	
    // If the User presses enter into the second field
    if (event.target == input2)
    {
        //Read textField1 and textField2
        //Read as String and translated to Double
        num1 = Double.parseDouble(input1.getText() );
        num2 = Double.parseDouble(input2.getText() );
        result = num1+num2;
        //The text of label sum is updated
        sum.setText("The sum is "  + result.toString());
        //Make a report to the console.
        report();
    }
    //We indicate to the system that the action
    //of the User has been processed.
    return true;
}
}//End of Program A285 Dialog2




:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A343 Drawing3
//This class draws a face.

package ejvol1;

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
		
public class Drawing3 extends Applet	
{
    private static final long serialVersionUID = 1L;

    public void paint (Graphics g)
    {
        //The face.
        g.setColor(Color.pink);			
        g.fillOval(15,15,100,150);
        //The hair.
        g.setColor(Color.black);
        g.fillRect(3,3,130,35);
        // The mouth
        g.setColor(Color.red);
        g.fillOval(50,120,30,20);
        // The eyes
        g.setColor(Color.blue);
        g.fillOval(30,50,30,20);
        g.fillOval(70,50,30,20);
        // The nose
        g.setColor(Color.red);
        g.drawRect(55,70,20,40);
     }
}//End of Program A343 Drawing3



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A97 RandomGenerator
//Generation of random numbers and chars

package ejvol1;

//The generation of random numbers
//is supported by the class Random,
//so, that class must be activated.
import java.util.Random;


public class RandomGenerator


{
   public static void main( String args[] )
   {
        //A sequence of random numbers is generated as follows:
        //We turn on the random gebnerator:
        Random r  = new Random();
        //  We invoke the next random number,
        // each time it is needed.
        //  The parameter 6 means that the random numbers
        // will be in within 0 and 5.
        // Generated numbers are integers.
        System.out.println( "Random number " + r.nextInt(6));
        System.out.println( "Random number " + r.nextInt(6));
        System.out.println( "Random number " + r.nextInt(6));
        System.out.println( "Random number " + r.nextInt(6));
        System.out.println( "Random number " + r.nextInt(6));
        System.out.println( "Random number " + r.nextInt(6));
        System.out.println( "Random number " + r.nextInt(6));
        System.out.println( "Random number " + r.nextInt(6));
        System.out.println( "Random number " + r.nextInt(6));
        System.out.println( "Random number " + r.nextInt(6));
	
	
        // For a large sequence, a loop is necessary
        System.out.print("Simulation of a die: \n");
        for ( int i = 1; i <= 20; i++ )
        {
            // To simulate a die, we add 1.
            // Observe that the symbol +
            // is used in two very different senses:
            System.out.print( 1 + r.nextInt( 6 ) + "  " );
        }
        System.out.println();

        //This is type char for letters
        //Strings are surrounded b two marks,
        //chars by one.
        char c = 'j';
        System.out.println("This is a char = " + c);

        // ALPHABET = upper case chars(ascii code):
        System.out.print("ALPHABET = " );
        for ( int i = 65; i <= 90; i++ )
        {
            char ch = ( char) (i);
            System.out.print(ch + " ");
        }

        System.out.println( );


        //Alphabet
        //Lower case chars (ascii code):
        // Alphabet = upper case chars(ascii code):
        System.out.print("Alphabet = " );

        for ( int i = 97; i <= 122; i++ )
        {
            char ch = ( char) (i);
            System.out.print(ch + " ");
        }
        System.out.println();

        //A random upper case char:
        char ch =   ( char ) ( r.nextInt( 26 ) + 65 );
        System.out.println("Random Upper char = " +   ch );

        //A random lower case char:
        ch =  ( char ) (  r.nextInt( 26 ) + 97 );
        System.out.println("Random lower char = " + ch );
   }
} //End of Program A97 RandomGenerator




:::::::::::::  NEW PROGRAM  :::::::::::::


// Program 260 LotkaVolterra
// Study  of a prey-predator system.
// Deterministic model.
// Lotka-Volerra equations.

package ejvol1;



public class LotkaVolterra
{
    static double nr, nw, e, m,p,l,  k;
		
    public static void initialization()
    {
        //Generates 500 rabbits,  50 wolfs
        nr = 500;
        nw = 50;
        // Rate of rabbit's reproduction
        m = 0.1;
        // Rate of predation
        p = 0.01;
        // Rate of wolf's death
        k = 0.05;
        // Rate of wolf reproduction
        l= 0.1 * p ;
    }
	
    public static void dynamics()
    {
        //We run N generations
        int n = 1000;
        for(int  i = 0; i< n;i++)
        {
            //Rabbits reproduce
            nr = nr + m* nr;
            //Rabbits are preyed on
            nr = nr - p * nr * nw;
            //Wolfs reproduce
            nw = nw + l* nr * nw;
            //Wolfs die
            nw = nw - k * nw;

            System.out.println(i + "\t"
                    +  nr + "\t " +  nw);
        }
    }

    public static void main(String[] args)
    {
        initialization();
        System.out.println("time, rabits and wolfs");
        dynamics();
    }
}//End opf Program 260 LotkaVolterra



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program 199 RandGenerator5
// Binomial dist with a z-test.

package ejvol1;


import java.util.Random;

public class RandGenerator5
{
	static Random r  = new Random();

 public static void test(int Males, double p)
 {
    //Statistical z-test to see
    //the fairness of the simulation
    //Square root of p * (1 - p) / 1000
    double  sigmaP= Math.pow( (p * (1 - p)/1000), 0.5);
    double M = Males;
    double zObserved = (M/1000 - p) / sigmaP;
    System.out.println("The z of the experiment is " 
            + zObserved );
    double  s = 1.96;
    System.out.println("The critical z is   " + s);
    String A ;
    //Absolute value of zObserved
    if (Math.abs(zObserved ) < s)  A = "Yes";
      else A = "No";
    System.out.println( "Is the generator fair?  " + A);
 }
	
public static void main(String[] args)
{
    // Probability of male
    double p = 0.2;
    int numberMales =0;
    int total = 1000;
    for(int j = 0; j< total; j++)
    {
        //We generate a random number
        //in within 0 and 1
        double  c = r.nextDouble();
        // We verify gender
        if (c<p) numberMales  = numberMales +1;	
    }
    System.out.println("Males: " + numberMales );
    System.out.println("Females: " 
            + (total - numberMales) );
    test(numberMales,p);
}
}//End of Program 199 RandGenerator5



:::::::::::::  NEW PROGRAM  :::::::::::::




package ejvol1;

// Program A354c Body
//A body is composed of an arm and a neckLength

public class Body  extends Arm
{



    private Arm arm;
    int neckLength;


        
        
    // How does Body acquires data?
    // Many  forms are possible, some follow.

	
    //Void instantiation  to be filled in later 
    Body(  )
    {
	
    }
      
    //From an arm and a neckLength
    Body( Arm arm,  int d )
    {
	this.arm = arm;
	this.neckLength = d;
    }
           
    //From a hand, an elbowLength and a neckLength
    Body( Hand h,  int c, int d )
    {
	this.arm = new Arm();
	this.arm.hand = h;
        this.arm.elbowLength = c;
	this.neckLength = d;
    }       
    
       
    //From  forefingerLength, thumbLength,
    //elbowLength and neckLength
    Body( int a, int b, int c, int d )
    {
        this.arm = new Arm(a,b,c);
        this.neckLength = d;
    }




//Object is reported to console
public static void report(String name, Body body )
{
System.out.println("==== " + name + " =====");
System.out.println("Arm:");
System.out.println("     Hand:");
System.out.print("          ForfingerLength = ");

System.out.println(body.arm.hand.forefingerLength);
System.out.print("          ThumbLength     = ");
System.out.println(body.arm.hand.thumbLength);
System.out.print("          ElbowLength     = ");
System.out.println(body.arm.elbowLength);
System.out.print("     NeckLength           = ");
System.out.println(body.neckLength);
}


//This is how to deal with our objects 
public static void main(String[] args)
{	
    // We provide information in  a list
    final Body bodyJohn = new Body(11,12,13,14) ;
    String name = "John";
    report( name, bodyJohn );

    // Construction and
    //symbolic initialization
    Body bodyJoseph = new Body(-1,-2,-3,-4);
    name = "Joseph";
    //Real initialization
    //Substructured input
    final Hand  hand1 = new Hand(7,5);
    //True partial initialization
    bodyJoseph.arm.hand = hand1;		
    report( name, bodyJoseph );	
    
    //Structured initialization
    final Body bodyPeter = new Body(hand1, 40, 25);
    report( name, bodyPeter );	
    
    //Cloning
    final Body bodyLukas = bodyJoseph;
    report( name, bodyLukas );
    
    //Void initialization
    final Body bodySteven = new Body();
    //Activate next line and add a point
    //to see the editor hints.
    //Select a hint with arrows + return.
    //bodySteven
    //report( name, bodySteven );  
}
}//End of Program A354c Body



:::::::::::::  NEW PROGRAM  :::::::::::::


//Program A13 SumOfIntegers
//This program introduces integers
//and their addition.

package ejvol1;

public class SumOfIntegers
{		
    public static void main(String[] args)
    {
        //Declaration and initialization
        // of variables as integers.
        int x = 2;
        int y = 3;
        //Computation
        int result  = x+y; //result is declared as integer
         // Report
        System.out.println(" The sum of x =" + x + " and ");
        System.out.println( " y = " + y + " is " + result );	
    }	
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A354b Arm
//The object Arm is composite:
//it has a hand and an elbowLength

package ejvol1;





public class Arm  extends Hand
{

    //It is assumed that hand is in the same package
    Hand hand;
    int elbowLength;

    //Void initialziation
    public Arm ()
    {

    }

    //Initialization from and ordinary list
    public Arm (int a, int b, int c)
    {
       this.hand = new Hand();
       hand.forefingerLength =  a;
       hand.thumbLength = b;
       this.elbowLength = c;
    }	
}//End of Program A354b Arm



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A98 RandomGenerator2
//Random chars

package ejvol1;

import java.util.Random;
public class RandomGenerator2
{
    public static void main( String args[] )
    {
        //We turn on the random generator:
        Random r  = new Random();

        //Upper case chars
        for(int i= 1; i<=20; i++)
        {
            char ch =   ( char ) ( r.nextInt( 26 ) + 65 );
            System.out.print (  ch + "  " );
        }
        //Change of car
        System.out.println();

        //Lower case chars
        for(int i= 1; i<=20; i++)
        {
            char ch =   ( char ) ( r.nextInt( 26 ) + 97 );
            System.out.print (  ch + "  " );
        }
        System.out.println();
    }
   
}//End of Program A98 RandomGenerator2



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * Program A22 StructuringProgramming3
 * Encapsulation may become a mania.
 */
package ejvol1;


public class StructuredProgramming3
{	

    //The next is  a method.
    //It encodes for a function with input 
    //two integers and output their sum.
    //The output is also integer and must be declared
    //explicitly before the name of the method.
    
    //The output of the method appears after
    //the reserved word "return".
    //The declaration of a method or a class
    //does not terminate with semicolon ";"
    public static int sum(int x, int y)  	 	
    {
        return  x+y;
    }
	
    
    public static int multiplication(int x, int y)  	 	
    {
        return  x*y;
    }
    
    public static int subtraction(int x, int y)  	 	
    {
        return  x-y;
    }
    
    public static int division(int x, int y)  	 	
    {
        return  x/y;
    }
    
    //This method reports to the console
    // some information about x,y and 
    //arithmetic operations with them
    public static void report(int x, int y, 
            int z1, int z2, int z3, int z4) 	
    {
        System.out.print(" The sum of x =" + x + " and ");
        System.out.println( " y = " + y + " is " + z1);
        System.out.print(" The multiplication of x =" + x );
	System.out.println( " and  y = " + y + " is " + z2);
	System.out.print(" The integer division of x =" + x );
	System.out.println( " by  y = " + y + " is " +  z3);
	System.out.print("  x =" + x );
	System.out.println( " minus  y = " + y + " is " + z4);
    }
    
    //This is the main method.
    //This is the head of the class.
    public static void main(String[] args)
    {
        //Declaration and initialization
        //of variables
        int x = 2;
        int y = 3;
        //Invocation of a method
        int z1 = sum(x,y);
        int z2 = multiplication(x,y);
        int z3 = division(x,y);
        int z4 = subtraction(x,y);
        //Report to the console
        report( x, y, z1,  z2,  z3,  z4);
        	
    }			
}//End of program A22 StructuringProgramming3



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A73 Concatenation3
//Concatenation.
//Structured version.

package ejvol1;

public class Concatenation3
{
    // This method concatenates a and b
    // to produce a result that shall be invoked
    //as glue(a,b) and that is of String type.
    public static String  glue(String a, String b)
    {
        // The reserved word "return"
        // points to the output of the method glue.
        return a+b;
    }

    // This is the head of the program.
    public static void main(String[] args)
    {
        String a = "pqrst";
        String b = "123";
        // The output of glue is placed in string c
        String c = glue(a,b);
        // Report
        System.out.println("a =   " + a);
        System.out.println("b =   " + b);
        System.out.println("a + b =   " + c);
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



package ejvol1;


//Program A348 Drawing6
//This class  draws a moving face with blinking eyes.
//Vertical movement.
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
		
public class Drawing6 extends Applet	
{

private static final long serialVersionUID = 1L;
	
public void drawFace(Graphics g, int k)
{
    //face
    g.setColor(Color.pink);			
    g.fillOval(15,15+k,100,150);
    //hair
    g.setColor(Color.black);
    g.fillRect(3,3+k,130,35);
    //mouth
    g.setColor(Color.red);
    g.fillOval(50,120+k,30,20);
    //eyes
    g.setColor(Color.blue);
    g.fillOval(30,50+k,30,20);
    g.fillOval(70,50+k,30,20);
    //nose
    g.setColor(Color.red);
    g.drawRect(55,70+k,20,40);	
}
			
public void  eraseface(Graphics g,int k)
{
    // face
    g.setColor(Color.white);			
    g.fillOval(15,15+k,100,150);
    //hair
    //g.setColor(Color.black);
    g.fillRect(3,3+k,130,35);
    //mouth
    //g.setColor(Color.red);
    g.fillOval(50,120+k,30,20);
    //eyes
    //g.setColor(Color.blue);
    g.fillOval(30,50+k,30,20);
    g.fillOval(70,50+k,30,20);
    //nose
    //g.setColor(Color.red);
    g.drawRect(55,70+k,20,40);		
}
			
public void closeEyes (Graphics g, int k)
{
    // We erase eyes:
    // eyes are painted in pink
    g.setColor(Color.pink);
    g.fillOval(30,50+k,30,20);
    g.fillOval(70,50+k,30,20);
    // We draw smaller eyes
    g.setColor(Color.blue);
    g.fillOval(30,65+k,30,5);
    g.fillOval(70,65+k,30,5);
}
			
public void openEyes (Graphics g, int k)
{
    // small eyes are erased
    // We draw smaller eyes
    g.setColor(Color.pink);
    g.fillOval(30,65+k,30,5);
    g.fillOval(70,65+k,30,5);
    //We redraw eyes:
    // eyes are drawing in blue
    // and normal size
    g.setColor(Color.blue);
    g.fillOval(30,50+k,30,20);
    g.fillOval(70,50+k,30,20);

}
			
public void delay(long l1,int l)
{			
  while  (System.nanoTime() < l1 + l) {delay(l1,l);}
}
			
@Override
public void  paint (Graphics g)
{
    drawFace(g,0);
    // This loop controls the numbers
    // of cycles of the graphic
    for(int kl = 0; kl < 5; kl++)
    {				
        // k is the vertical jump
        int k = 10*kl;
        //We erase everything
        g.clearRect(0,0,200,200);
        // We draw face in the new place
        drawFace(g,k);
        // This loop controls blinking 
        for(int i = 0; i < 2; i++)
        {
            // A delay must be introduced to make
            // movement visible for a human being.
            System.out.print("Cycle = " + kl);
            System.out.println(". Blinking = " + i );			

            long  l1 = System.nanoTime();

            int l = 500;
            for(int j=0; j<4000000; j++)	
                delay(l1,l);

            closeEyes(g, k);

            //A delay is inserted			
            l1 = System.nanoTime();				
            l = l*40;
            for(int j=0; j<2000000; j++)	
                delay(l1,l);

            openEyes(g,k);			   	    	
        }	
    }
    System.out.println("Job done.");
}
}//End of Program A348 Drawing6



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A60
//Copying a substring.
//Warning: Java begins conting with 0
package ejvol1;


public class Copy
{
    public static void main(String[] args)
    {
        String s1, s2, s3;
        s1 = "Selection is the key to function.";
        System.out.println("Original string = " + s1);

        // Let us copy into s2 the part of s1
        // that begins at the fourth character:
        s2 = s1.substring(4);
        System.out.println("Copied substing2= " +s2);

        // Let us copy into s3 the part of s1
        // that begins at the fourth character
        // and ends   at the eighth one excluded:
        s3 = s1.substring(4,8);
        System.out.println("Copied substing3= " + s3);
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A101 RandomRNA
//Random  RNA string.
package ejvol1;


import java.util.Random;

public class RandomRNA
{
   public static void main( String args[] )
   {
        //We turn on the random generator:
        Random r  = new Random();
        // Definition of the alphabet
        char Alphabet[] = {'U','T','C','G'};
	
        // Generation of a RNA string 25 bases long
        for(int i= 0; i< 25; i++)
        {
            char ch =   Alphabet[ r.nextInt( 4 )];
            System.out.print (  ch);
        }
        System.out.println();
   }
}



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A339 Drawing
//This class draws a line.

package ejvol1;



import java.applet.Applet;
import java.awt.Graphics;

		
public class Drawing extends Applet
{
    private static final long serialVersionUID = 1L;

    @Override
    public void paint (Graphics g)
    {
        g.drawLine(10,10,230,95);
    }
}



:::::::::::::  NEW PROGRAM  :::::::::::::


/*
 * Program A19 StructuringProgramming2
 * Some code is encapsulated into methods
 */
package ejvol1;


public class StructuredProgramming2
{	

    //The next is  a method.
    //It encodes for a function with input 
    //two integers and output their sum.
    //The output is also integer and must be declared
    //explicitly before the name of the method.
    
    //The output of the method appears after
    //the reserved word "return".
    //The declaration of a method or a class
    //does not terminate with semicolon ";"
    public static int sum(int x, int y)  	 	
    {
        return  x+y;
    }
	
    
    public static int multiplication(int x, int y)  	 	
    {
        return  x*y;
    }
    
    public static int subtraction(int x, int y)  	 	
    {
        return  x-y;
    }
    
    public static int division(int x, int y)  	 	
    {
        return  x/y;
    }
    
    //This is the main method.
    //This is the head of the class.
    public static void main(String[] args)
    {
        //Declaration and initialization
        //of variables
        int x = 2;
        int y = 3;
        //Invocation of a method
        int z1 = sum(x,y);
        int z2 = multiplication(x,y);
        int z3 = subtraction(x,y);
        int z4 = division(x,y);
        // Report to the console
        System.out.print(" The sum of x =" + x + " and ");
        System.out.println( " y = " + y + " is " + z1);
        System.out.print(" The multiplication of x =" + x );
	System.out.println( " and  y = " + y + " is " + z2);
	System.out.print(" The integer division of x =" + x );
	System.out.println( " by  y = " + y + " is " +  z3);
	System.out.print("  x =" + x );
	System.out.println( " minus  y = " + y + " is " + z4);	
    }			
}//End of program A19 StructuringProgramming2



:::::::::::::  NEW PROGRAM  :::::::::::::



package ejvol1;


// Program 328 Drift

// In this program we study drift
// in one asexual  population with constant size,
// one locus or enzyme, two alleles and no mutation.

//One allele is eroded and the other is fixed.
//Reported: Repetition + final frequency of allele1
//and the probability of fixation of allele1 for a given
//initial probability of allele1

import java.util.Random;

public class Drift 
{

		
    //Turn on  the random generator	
    static Random r  = new Random();

	
    static int size; //population size.
    static double po; // initial probability of allele one
    static int nGen; //number of generations
    static double counterAllele1;
    static double counterFixations;
    static double nRepetitions;
    static double probFixation;
    //Individuals have one of two alleles
    //True: allele1; false = allele2 
    static boolean individual1[],individual2[];

    
    public static void initialization()
    {
     size = 100;
     po = 0.8;
     nGen = 200;
     counterAllele1 = 0;
     counterFixations=0;
     nRepetitions=1;
     individual1 =new boolean[1001];
     individual2 =new boolean[1001];
     System.out.println("Initial probability of allele1 = " 
             + po);	

    }
	
    //One population during nGen generations.
    //The new generation is generated by random sampling.
    public static double dynamics()
    {
        System.out.println("Generation "
                + "+ relative frequency of allele1");
        //Local probability of fixation
        double f = 0;
        for(int i=0;  i < nGen; i++)
        {
            counterAllele1=0;
            //Sampling procedure
            for(int j=0; j < size; j++)	
            {
                int  m = r.nextInt(size) ;
                individual2[j]= individual1[m];

                if (individual2[j] == true)
                    counterAllele1 = counterAllele1 +1;
            }
            f=counterAllele1/size;
            System.out.println(i + "\t" + f);

            /* String s4 = String.valueOf(p);
            String  s5=s4.replace(".", ",");
             System.out.println( s5);	 */

            
            for(int j= 0; j <  size; j++)			
                individual1[j]= individual2[j];
        }
        return f;
    }
	
    //For each repetition, 
    public static void repetitions()
    {
        //System.out.println("Repetition + final frequency of allele1");
        for(int j=0; j < nRepetitions; j++)	
        {
            
            //initial population:
            //allele1=true;
            //allele2=false;
            //All have allele2
            for(int i=0; i< size; i++)
                    individual1[i]=false;
            //Some get allele1
            int n = (int) Math.ceil( po*size);
            for(int i = 0; i < n ; i++)
            {
                individual1[i]=true;
            }
            //frequency of fixation after dynamics
            double f = dynamics();
            System.out.println(j + "\t" + f);
                if(f==1)counterFixations=counterFixations +1;
        }
        probFixation = counterFixations/nRepetitions;
        System.out.println("probFixation = " + probFixation);	
    }

    public static void main(String[] args) 	
    {
        initialization();
        repetitions();
    }
}//End of Program 328 Drift



:::::::::::::  NEW PROGRAM  :::::::::::::



//Program A216 Die
//A  source of random numbers simulates
//a face with 6 faces.
//Can it  simulate   a die with 5 faces?
//Yes, sometimes it does.
//We count  how many trials are 
//necessary to produce a sequence 15 numbers long 
//that mimicks a die with 5 faces.



package ejvol1;


import java.util.Random;

public class Die
{

    //Turn on of the random generator
    private static Random r  = new Random();
	
        
    //size of the random sequence
    private static int length= 15;
                 
    //Count counters the trials
    private static int count;
    //Absolute frequencies of faces 1 to 6
    //that appeared in the sequence.
    static int Observed[ ] = new int[7]; 
    //Criticak chi
    static private double criticalChi2 = 9.48;
	
    public static double  Obschisquare(int length)
    {
        double chi = 0;

        //The die with five faces is associated to a distribution
        //that assigns a probability 1/5 to numbers 1 to 5.
        //Hence, a sequence  of landed faces
        //must have 1/5*length instances of each face.

        double Expected = length/5;
        //Expected distribution is compared to observed one.
        //Discrepancy is approximately distributed 
        //as a chi square:
        for(int j = 1; j<= 5; j++)
            chi  = chi + (Observed[j]-Expected)
                *(Observed[j]-Expected)/Expected;
        System.out.println("Observed chi-square = " + chi); 	
        return chi;
    }
	
    //Sequences are generated with a uiform distribution
    //in within 1 and 6 included
    public static void tryAndTry(int length)
    {
        count = count +1;
        System.out.print(" Trial " + count + "  ");
        // Initialization
        for(int j = 1; j<= 6; j++)
                Observed[j] = 0;
		
        //We generate a random sequence
        for(int j = 0; j< length; j++)
        {
            // We choose a uniform distribution	
            // from 1 to 6, as in a die.
            int c = r.nextInt(6)+1;
            System.out.print(c ) ; 				
            // bookkeeping
            Observed[c] = Observed[c]+1;
        }
		
        // Report		
        // for(int j = 1; j<= 6; j++)
        // System.out.println(j + "\t" + Observed[j]);

        if (Observed[6] > 0)
        {
            //System.out.println("It landed 6"); 
            System.out.println(" Sequence with a 6");                      
            tryAndTry(length);				
        }
        else 
        {
            System.out.println(" Sequence WITHOUT a 6"); 
            //A uniform distribution  
            //with support 1...5 is needed.
            if (Obschisquare(length) >= criticalChi2) 
            {
                System.out.println(" NON UNIFORM distribution ");
                tryAndTry(length);	

            }
            else
                System.out.println(" Uniform distribution ");
        }	
    }
	
        
    public static void main(String[] args)
    {
        tryAndTry(length);
        System.out.println("We succeed at the trial " + count);
    }
}//End of Program A216 Die



:::::::::::::  NEW PROGRAM  :::::::::::::


