Search code examples
algorithmgeneticfitness

Specific Genetic Algorithm Cost Function


I am assigned the task of creating a genetic algorithm which is an allocation problem where the object is to allocate components into two racks of equipment minimizing the degree of interconnect.

Basically what I have to do is read in a matrix A which is the Adjacency list of component connectivity. cij represents the number of connections between component i and component j. It should be symmetric each time. We have a population, all values are stored in 2D arrays, such is my implementation.

The matrix A read in is our adjacency matrix and the population is what will determine how we will bin the items. The racks are bin0 and bin1, if population[cij] = 0 the corresponding element in the matrix A read in is placed into bin0 and the same rule applies if population[cij] = 1.

Now the issue is to find the row in the population matrix which gives the smallest amount of interconnect, which is the sum of the weights between components in different bins.

This is an image of our base case:

Screen capture

... in which the matrix A read in is to the right, the population is shown below and the way the elements in the matrix A are binned is shown in the middle. As of yet I can calculate a penalty, this is a constraint given by the professor, I can also determine how many elements are in each bin, but calculating the cost as described and as shown in the picture so far eludes me. As of yet this is my cost function:

public static int[] calcCost(int[][] matrix, int[][] population){
int cost[] = new int[size];

for(int m=0;m<size;m++){
    for(int i=0; i<size; i++){
        for(int j=0; j<size; j++){
            //System.out.println(m + "\t" + i + "\t" + j);
            if(population[i][j] == 1){
                cost[m] += matrix[i][j];
                }
            }//end for 3
        }// end for 2
    }//end for 1
    //printArrayI(cost);
    return cost;
}

The idea is to have m keep track of where we are in the overall calculation and the elements i and j scan the rows and columns for connections in the population, when a connection is found the cost[i] should reflect that connection as the sum of the weights of the edges crossing the two bins. As of yet this does not work properly.


Solution

  • I have solved the problem, I was simply iterating wrong. Here is the solution I found.

    public static int[] calcCost(int[][] matrix, int[][] population){
    int cost[] = new int[size];
    
    for(int m=0;m<size;m++){
        for(int i=0; i<size; i++){
            if(population[m][i] == 0){
                for(int j=0; j<size; j++){
                    if(population[m][j] == 1){
                        cost[m] += matrix[i][j];
                        }
                    }
                }
            }// end for 2
        }//end for 1
        printArrayI(cost);
        return cost;
    }