// Michael S. Branicky, 18 February 2008: Translation into Java of // Michael S. Branicky, 04 February 2005 // compiles with g++ -lc -lm // // This code offered with no guarantees whatsoever. // /* #include #include #include #include #include */ public class rrhc { public static final int TEST=0; public static final int ELITISM=1; public static final int NUMTRIALS=100; public static int N=100000000; // number of generations public static int k=1; // number of individuals public static int EVALS; // number of fitness evaluations public static double pmut=0.01; // mutation probability // returns a uniformly distributed random double between 0.0 and 1.0 public static double myrand() { return Math.random(); } // returns 1 if queens q1 and q2 are attacking each other, 0 o.w. public static int attacking(int q1col, int q1row, int q2col, int q2row) { if (q1col==q2col) return(1); // same column if (q1row==q2row) return(1); // same row int coldiff=q1col-q2col; int rowdiff=q1row-q2row; if (Math.abs(coldiff)==Math.abs(rowdiff)) return(1); // same diagonal return(0); } // evaluates the fitness of an encoding, defined as the number of // non-attacking pairs of queens (28 - number of attacking pairs) // // the global variable EVALS keeps track of the number of times called public static int fitness(int encoding[]) { EVALS++; int E=28; for (int i=1; i<8; i++) { for (int j=i+1; j<=8; j++) { E-=attacking(i, encoding[i-1], j, encoding[j-1]); } } return(E); } // the following is useful in a variety of // returns the nth successor of an encoding public static void getsuccessor(int init[], int n, int succ[]) { n--; int remainder=(n%7); int quotient=(n-remainder)/7; // int newrow=1+((remainder+init[quotient]-1)%8); int newrow=init[quotient]+remainder+1; if (newrow>8) newrow-=8; for (int j=0; j<8; j++) { if (j==quotient) succ[j]=newrow; else succ[j]=init[j]; } } // copy each digit of an encoding with a prob. of error p (in place) // thus, if p=0., the string does not change; if p=1, it is randomized public static void mutate(int enc[], double p) { for(int i=1; i<=8; i++) { double r=myrand(); if (r bestE) { bestE=f; bestSuccIndex=i; } // The following line would add some randomness for equally-good ones // if ((f>bestE)||((f==bestE)&&(myrand()<0.1))) { bestE=f; bestSuccIndex=i; } } if (bestE>currE) { // climb hill // reassign current <-- best successor getsuccessor(curr, bestSuccIndex, succ); mutate2(succ, curr, 0.0); currE=bestE; } else { // random restart // pick a random board configuration mutate(curr,1.0); currE=fitness(curr); } } // for (int i=ELITISM; i