genetic-algorithmroulette-wheel-selection

Roulette wheel selection for function minimization


This question answers pseudocode for roulette wheel selection. But it's for maximization problem. But my problem is to minimize the value of fitness function. That means, individuals with low fitness get higher probability for being selected than individual with high fitness. How can I implement that?

Thanks in advance.


Solution

  • import java.util.Random;
    import java.util.Arrays;
    import java.util.Comparator;
    
    class MyComparator implements Comparator
    {
        public int compare(Object o1, Object o2)
        {
            Number n1 = (Number) o1;
            Number n2 = (Number) o2;
    
            if(n1.jump > n2.jump)
            {
                return 1;
            }
            else if(n1.jump < n2.jump)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }
    }
    
    
    class Number
    {
        public double i;
        public int pos;
        public double jump = 0;
    
    
        public Random r = new Random();
    
        public Number(int pos)
        {
            this.pos = pos;
    
            i = r.nextInt();
        }
    }
    
    
    public class Temp
    {
        public static  void main(String[] args)
        {
            Number[] n = new Number[50];
    
            double total = 0;
    
            for(int i=0; i<50; i++)
            {
                n[i] = new Number(i);
    
                total += n[i].i;
            }
    
            for(int i=0; i<50; i++)
            {
                n[i].jump = n[i].i/total;
            }
    
    
            Arrays.sort(n, new MyComparator());     
    
            for(int i=0; i<50; i++)
            {
                System.out.print(n[i].pos + ", ");
            }
    
            System.out.println();
    
            for(int i=0; i<50; i++)
            {
                n[i].jump = n[i].i / total;
                n[i].jump = 1-n[i].jump;
            }
    
            Arrays.sort(n, new MyComparator());     
    
            for(int i=0; i<50; i++)
            {
                System.out.print(n[i].pos + ", ");
            }
    
            System.out.println();   
        }
    }
    

    In above example, say Number class is your individual class, i is fitness, jump is the probability of being selected as parent. At first we compute the probability of being selected as parent like before. At this step, higher fitness will get higher probability. Then we subtract probability from 1. This gives lower fitness individual higher fitness (pseudo fitness for selection's sake). Now recalculate the probability. See, the order of being is totally reversed.