1

我正在做一个小项目,我必须编写一个遗传算法来进化我的名字和身份证号码。基本上,我随机生成位字符串,然后必须将其生成为 ascii 字符串并测量以查看生成的接近程度。然后,我将对最好的 10 代进行变异,以使其尽可能接近我的姓名和身份。

我目前遇到的问题是 ascii 一代。它适用于第一个位串,但随后会重复其他位串,尽管每个位串都不同。任何人都可以看到问题吗?任何帮助深表感谢。

到目前为止的代码:

import java.util.Random ;

public class GeneticAlgorithm {

    public static void main(String[] args) throws Exception
    {
        int popSize = 0 ;
        int gen ;
        double repRate ;
        double crossRate ;
        double mutRate ;
        int seed = 9005970 ;
        String id = "John Connolly 00000000" ;
        int bits = 7 * id.length() ;
        String output ;
        int pop ;
        int bitGen ;

        Random rand = new Random(seed) ;
        ConvertToAscii convert = new ConvertToAscii() ;
        Fitness fit = new Fitness() ;

        try {
            popSize = Integer.parseInt(args[0]) ;
            if(popSize < 0 || popSize > 100000)
            {
                System.out.print("Invalid number! A positive number between 0 and 100000 must be used for the population rate!") ;
                System.exit(1) ; // Signifies system exit if error occurs
            }
            gen = Integer.parseInt(args[1]) ;
            if(gen < 0 || gen > 100000)
            {
                System.out.println("Invalid number! A positive number between 0 and 100000 must be used for the generation rate!") ;
                System.exit(1) ;
            }
            repRate = Double.parseDouble(args[2]) ;
            if(repRate < 0 || repRate > 1.0)
            {
                System.out.println("Invalid number! A positive decimal point number between 0 and 1.0 must be used for the reproduction rate!") ;
                System.exit(1) ;
            }
            crossRate = Double.parseDouble(args[3]) ;
            if(crossRate < 0 || crossRate > 1.0)
            {
                System.out.println("Invalid number! A positive decimal point number between 0 and 1.0 must be used for the crossover rate!") ;
                System.exit(1) ;
            }
            mutRate = Double.parseDouble(args[4]) ;
            if(mutRate < 0 || mutRate > 1.0)
            {
                System.out.println("Invalid number! A positive decimal point number between 0 and 1.0 must be used for the mutation rate!") ;
                System.exit(1) ;
            }
            if(repRate + crossRate + mutRate != 1.0)
            {
                System.out.println("The Reproduction Rate, Crossover Rate and Mutation Rate when sumed together must equal 1.0!") ;
                System.exit(1) ;
            }
            output = args[5] ;
            java.io.File file = new java.io.File(output);
            java.io.PrintWriter writeOut = new java.io.PrintWriter(file) ;
            StringBuffer bitString = new StringBuffer() ;
            int bestFit = 0, fitness = 0, totalFit = 0 ;
            String ascii = "" ;
            writeOut.println(popSize + " " + gen + " " + repRate + " " + crossRate + " " + mutRate + " " + output + " " + seed) ;
            for(pop = 0 ; pop < popSize ; pop++)
            {
                ascii = "" ;
                writeOut.print(pop + " ") ;
                for(int i = 0 ; i < bits ; i++)
                {
                    bitGen = rand.nextInt(2);
                    writeOut.print(bitGen) ;
                    bitString.append(bitGen) ;
                }
                ascii = convert.binaryToASCII(bitString) ;
                writeOut.print(" " + ascii) ;
                writeOut.println() ;
            }
            writeOut.close() ;
            System.exit(0) ;            

        } catch(ArrayIndexOutOfBoundsException e) {
            System.out.println("You have entered the incorrect number of arguments!") ;
            System.out.println("Please enter the required 6 arguments.") ;
            System.exit(1) ;
        } catch(NumberFormatException n) {
            System.out.println("Invalid argument type") ;
            System.exit(1) ;
        }
    }
}

这是转换代码:

public class ConvertToAscii {

    public String binaryToASCII(StringBuffer bitString)
    {
        String ascii = "" ;
        String byteString ;
        int decimal ;
        int i = 0, n = 7 ;
        int baseNumber = 2 ;
        char asciiChar ;
        while(n <= 154)
        {
            byteString = bitString.substring(i, n) ;
            decimal = Integer.parseInt(byteString, baseNumber) ;
            System.out.print(" " + decimal) ;
            i += 7 ;
            n += 7 ;
            if(decimal < 33 || decimal > 136)
            {
                decimal = 32 ;
                asciiChar = (char) decimal ;
            } else {
                asciiChar = (char) decimal ;
            }
            ascii += asciiChar ;
        }
        return ascii ;
    }

}
4

2 回答 2

2

您一遍又一遍地使用相同的 StringBuffer 并且永远不会清除它。您将人口的第一个成员添加到 StringBuffer,这是前 154 个字符......然后第二个成员位于插槽 155-308 中,但您的 binaryToASCII() 方法永远不会超过插槽 154。

每次尝试使用新的 StringBuffer (并且,如上所述,尝试使用 StringBuilder,因为它在非线程环境中更有效)。

于 2013-09-27T15:53:08.767 回答
1

就像 dcsohl 在他的回答中所说的那样,您在每次迭代中都发送和评估相同的 bitString。我做了这个更正,还对代码进行了一些优化,以提高可读性、代码重用和正确的数据类型。

import java.util.Random ;

public class GeneticAlgorithm {
    public static void main(String[] args) throws Exception
    {
        int popSize = 0 ;
        int gen ;
        double repRate ;
        double crossRate ;
        double mutRate ;
        int seed = 9005970 ;
        String id = "John Connolly 00000000" ;
        int bits = 7 * id.length() ;
        String output ;
        int pop ;
        int bitGen ;

        Random rand = new Random(seed) ;
        ConvertToAscii convert = new ConvertToAscii() ;
        Fitness fit = new Fitness() ;

        try {
            popSize = validateIntArg(args[0], "population rate");
            gen = validateIntArg(args[1], "generation rate");

            repRate = validateDoubleArg(args[2], "reproduction rate");
            crossRate = validateDoubleArg(args[3], "crossover rate");
            mutRate = validateDoubleArg(args[4], "mutationRate") ;

            if(repRate + crossRate + mutRate != 1.0)
            {
                System.out.println("The Reproduction Rate, Crossover Rate and Mutation Rate when sumed together must equal 1.0!") ;
                System.exit(1) ;
            }
            output = args[5] ;
            java.io.File file = new java.io.File(output);
            java.io.PrintWriter writeOut = new java.io.PrintWriter(file) ;
            StringBuilder bitString = new StringBuilder() ;

            int bestFit = 0, fitness = 0, totalFit = 0 ;
            String ascii = "" ;
            writeOut.println(popSize + " " + gen + " " + repRate + " " + crossRate + " " + mutRate + " " + output + " " + seed) ;

            for(pop = 0 ; pop < popSize ; pop++)
            {
                bitString.setLength(0);
                writeOut.print(pop + " ");
                for(int i = 0 ; i < bits ; i++)
                {
                    bitGen = rand.nextInt(2);
                    writeOut.print(bitGen);
                    bitString.append(bitGen);
                }
                ascii = convert.binaryToASCII(bitString) ;
                writeOut.print(" " + ascii) ;
                writeOut.println();
            }
            writeOut.close() ;
            System.exit(0) ;            

        } catch(ArrayIndexOutOfBoundsException e) {
            System.out.println("You have entered the incorrect number of arguments!") ;
            System.out.println("Please enter the required 6 arguments.") ;
            System.exit(1) ;
         } catch(NumberFormatException n) {
            System.out.println("Invalid argument type") ;
            System.exit(1) ;
       }
    }

    private static int validateIntArg(String arg, String argName) {
        int n = Integer.parseInt(arg);
        if (n < 0 || n > 100000) {
            System.out.print("Invalid number! A positive number between 0 and 100000 must be used for the " + argName + "!") ;
            System.exit(1);
        }

        return n;
    }   

    private static int validateDoubleArg(String arg, String argName) {
        double n = Double.parseDouble(arg);
        if (n < 0 || n > 100000) {
            System.out.print("Invalid number! A positive decimal point number between 0 and 1.0 must be used for the " + argName + "!") ;
            System.exit(1);
        }

        return n;
    }   
}

类 ConvertToAscii:

public class ConvertToAscii {

    public String binaryToASCII(StringBuilder bitString)
    {
        StringBuilder ascii = new StringBuilder();
        String byteString ;
        int decimal ;
        int i = 0, n = 7 ;
        int baseNumber = 2 ;
        char asciiChar ;
        while(n <= 154)
        {
            byteString = bitString.substring(i, n) ;
            decimal = Integer.parseInt(byteString, baseNumber) ;
            System.out.print(" " + decimal) ;
            i += 7 ;
            n += 7 ;
            if(decimal < 33 || decimal > 136)
            {
                decimal = 32 ;
            }
            asciiChar = (char) decimal ;
            ascii.append(asciiChar);
        }
        return ascii.toString();
    }

}
于 2013-09-27T16:17:04.500 回答