Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Chromosome {
- private String binaryRepresentation;
- int fitness = 0;
- public Chromosome() {
- this.setBinaryRepresentation(this.generateRandomChromosome());
- }
- private String generateRandomChromosome() {
- String chromosome = "";
- for (int i = 1; i <= 40; i++) {
- chromosome += ((int) (Math.random() * 10)) % 2;
- }
- return chromosome;
- }
- public String getBinaryRepresentation() {
- return this.binaryRepresentation;
- }
- private void setBinaryRepresentation(String binaryRepresentation) {
- this.binaryRepresentation = binaryRepresentation;
- }
- public String getHexadecimalRepresentation() {
- return this.gettoHexString(this.getBinaryRepresentation());
- }
- public String gettoHexString(String ss) {
- String toBuild = "";
- String toRet = "";
- int endi = ss.length();
- int begi = endi;
- for (int ii = 0; ii < ss.length() - 4; ii += 4) {
- endi = ss.length() - ii;
- begi = endi - 4;
- String test = ss.substring(begi, endi);
- toBuild += Long.toHexString(Long.parseLong(test, 2));
- }
- endi = begi;
- begi = 0;
- toBuild += Long.toHexString(Long.parseLong(ss.substring(begi, endi), 2));
- for (int ii = toBuild.length(); ii >= 1; ii--) {
- toRet += toBuild.substring(ii - 1, ii);
- }
- return toRet;
- }
- public int getFitness(GeneticKey geneticKey) {
- int b = 0;
- int h = 0;
- for (int i = 0; i < geneticKey.getChromosome().getBinaryRepresentation().length(); i++) {
- if (binaryRepresentation.charAt(i) == geneticKey.getChromosome().getBinaryRepresentation().charAt(i)) {
- b++;
- }
- }
- for (int i = 0; i < geneticKey.getChromosome().getHexadecimalRepresentation().length(); i++) {
- if (getHexadecimalRepresentation().charAt(i) == geneticKey.getChromosome().getHexadecimalRepresentation().charAt(i)) {
- h++;
- }
- }
- return fitness = (h + 1) * (b * b);
- }
- // public void verificarFitness(Chromosome cromosoma) {
- // if (cromosoma.getFitness() == GeneticKey.getFitness()) {
- // System.out.println("Hola");
- // } else {
- // System.out.println("Chau");
- // }
- // }
- public boolean mutate(String binaryRepresentation) {
- ArrayList<String> uniques = new ArrayList<String>();
- String indices = "";
- for (int i = 1; i <= 4; i++) {
- indices += ((int) (Math.random() * 10)) % 2;
- }
- return uniques.add(indices);
- }
- public String crossOver() {
- String A = "HelloWorld";
- String B = "zzzzzXxxxx";
- String C = A.substring(0, 4) + B.substring(5, 9);
- String D = B.substring(0, 4) + A.substring(5, 9);
- String E = A.substring(0, (int) (Math.random())) + B.substring((int) (Math.random()), 9);
- return C + D + E;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement