JAVA PROGRAMS OF VOL I VERSION 3, 16/IX/2016. //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; pop199)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 (m2) { 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 filesInFolder; private static final StringBuffer myText = new StringBuffer(); private static void printToConsoleFileNumberI(int i) { String fileName = filesInFolder.get(i).getPath(); try (Stream 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 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 (i0) & (i 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 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= 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 (i0) & (i 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 ((mc0) { 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; i7 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 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 ::::::::::::: //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; pop199)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 (m2) { 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 filesInFolder; private static final StringBuffer myText = new StringBuffer(); private static void printToConsoleFileNumberI(int i) { String fileName = filesInFolder.get(i).getPath(); try (Stream 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 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 (i0) & (i 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 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= 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 (i0) & (i 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 ((mc0) { 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; i7 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 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 //::::::::::::::::::::: END OF VOL I ::::::::::::::::::::::::::