Search code examples
javagenetic-algorithmtraveling-salesman

JAVA Genetic Algorithm initialization


I am trying to work on a TSP genetic algorithm. I am new to GA and i have read lots of documents about it. I know it need to create initialization then find out the fitness of each individual then do mutation and so on. However, I am really new to JAVA programming. I am not sure how to create the initialization(initialise all individual of population to all valid tour without repeat). P.s. some resources code and tutorial online are too difficult for me.

That's what i got so far. Please point out what do i need and what i have done wrong and what else i need to add in code.

private void initialize(){

for(int i =0; i< population.length; i++){


  for(int j =0; j < population[i].length; j++){

  }
 }

Solution

  • Your question has very little to do with genetic algorithms in general, and much to with initializing a collection of permutations in Java.

    Typically, answers to a TSP are encoded as a list of cities to visit. So, for 4 cities, this could look like [0, 1, 2, 3], meaning "visit the first, then the second, then the third, and then the fourth". All valid answers are permutations of this base answer.. If you are interested in a round-trip (where you finally go from the last city to the first), then you can avoid some symmetries by only shuffling the last N-1 elements.

    Let's program the simple permutation approach in Java:

    // initialize an ArrayList of n integers, from 0 to N-1
    ArrayList<Integer> base = new ArrayList<>();
    for (int i=0; i<n; i++) base.add(i);
    
    // initialize each answer to a permutation of the base answer
    Random r = new Random(); // use a seed if you want repeatable runs
    for (Individual p : population) {
      int[] perm = new int[base.size()];
      Collections.shuffle(base, r);
      base.toArray(perm);
      p.setAnswer(perm);
    }
    

    I am assuming that, instead of a 2D array of int, you use actual Individual objects that contain not only an answer, but also fitness and other attributes.