Skip to content

Instantly share code, notes, and snippets.

@Anticom
Last active December 27, 2016 21:50
Show Gist options
  • Save Anticom/2fa46e85a5ed173fe6a16c74235ced74 to your computer and use it in GitHub Desktop.
Save Anticom/2fa46e85a5ed173fe6a16c74235ced74 to your computer and use it in GitHub Desktop.
public class Foo {
//...
private List<Phrase> breed(List<Phrase> currentPopulation) {
List<Phrase> newPopulation = currentPopulation.subList(31, 95);
List<Phrase> breedingPool = new ArrayList<>(newPopulation);
//pick two random species
Random r = new Random();
for(int i = 0; i < 32; i++) {
int index1 = r.nextInt(breedingPool.size());
Phrase phrase1 = breedingPool.remove(index1);
int index2 = r.nextInt(breedingPool.size());
Phrase phrase2 = breedingPool.remove(index2);
newPopulation.add(sexytime(phrase1, phrase2));
}
return newPopulation;
}
public Phrase sexytime(Phrase first, Phrase second) {
Random r = new Random();
int crossoverPoint = r.nextInt(first.dna.size() - 1);
//determine whether 1st half of first + 2nd half of second or vice versa
List<Integer> newDNA;
if (r.nextBoolean()) {
newDNA = first.dna.subList(0, crossoverPoint);
newDNA.addAll(second.dna.subList(crossoverPoint + 1, second.dna.size()));
} else {
newDNA = second.dna.subList(0, crossoverPoint);
newDNA.addAll(first.dna.subList(crossoverPoint + 1, first.dna.size()));
}
return new Phrase(newDNA);
}
//...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment