PackageChapter2;/*** A "individual" represents a single candidate solution. The core piece of * information about an individual are its "chromosome", which are an encoding of * a possible solution to The problem at hand. A chromosome can be a string, an * array, a list, etc-in this class, and the chromosome is an integer array. * A individual position in the chromosome was called a gene, and these is the * atomic pieces of the solution that can be manipulated or mutated. When the * chromosome was a string, as in the this case, each character or set of characters * can was a gene. * * An individual also have a "fitness" score; This is a number, represents * how good a solution to the problem this individual is. The meaning of the * Fitness score would vary based on the problem at hand. * * @authorBkanber **/ Public classIndividual {Private int[] chromosome; Private DoubleFitness =-1; /*** Initializes individual with specific chromosome * *@paramchromosome * The chromosome to give individual*/ PublicIndividual (int[] chromosome) { //Create Individual chromosome This. chromosome =chromosome; } /*** initializes random individual. * * This constructor assumes the chromosome are made entirely of 0s and * 1s, which may isn't always being the CAs E sure to modify as * necessary. This constructor also assumes the a "random" chromosome means * simply picking random zeroes and ones, which also may Not being the case * (for instance, in a traveling salesman problem, this would is an invalid * solution). * * @paramChromosomelength * The length of the individuals chromosome*/ PublicIndividual (intchromosomelength) { This. chromosome =New int[Chromosomelength]; for(intGene = 0; Gene < chromosomelength; gene++) { if(0.5 <Math.random ()) { This. Setgene (Gene, 1); } Else { This. Setgene (Gene, 0); } } } /*** Gets individual ' s chromosome * *@returnThe individual ' s chromosome*/ Public int[] Getchromosome () {return This. Chromosome; } /*** Gets individual ' s chromosome length * *@returnThe individual ' s chromosome length*/ Public intgetchromosomelength () {return This. Chromosome.length; } /*** Set gene at offset * *@paramGene *@paramOffset *@returnGene*/ Public voidSetgene (intOffsetintgene) { This. chromosome[offset] =Gene; } /*** Get gene at offset * *@paramOffset *@returnGene*/ Public intGetgene (intoffset) { return This. Chromosome[offset]; } /*** Store individual ' s fitness * *@paramFitness * The Individuals fitness*/ Public voidSetfitness (DoubleFitness) { This. Fitness =Fitness; } /*** Gets individual ' s fitness * *@returnThe individual ' s fitness*/ Public Doublegetfitness () {return This. Fitness; } /*** Display the chromosome as a string. * * @returnstring representation of the chromosome*/ Publicstring toString () {string output= ""; for(intGene = 0; Gene < This. chromosome.length; gene++) {Output+= This. Chromosome[gene]; } returnoutput; }}
Genetic algorithm Individual