Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将二进制转换为Ascii,但对所有位字符串得到相同的结果_Java_Binary_Ascii_Genetic Algorithm - Fatal编程技术网

Java 将二进制转换为Ascii,但对所有位字符串得到相同的结果

Java 将二进制转换为Ascii,但对所有位字符串得到相同的结果,java,binary,ascii,genetic-algorithm,Java,Binary,Ascii,Genetic Algorithm,我正在做一个小项目,我必须写一个遗传算法来进化我的名字和身份证号码。基本上,我是随机生成位字符串,然后将其生成为ascii字符的字符串,并进行测量以查看生成的结果有多接近。然后,我将对最好的10代进行变异,使其尽可能接近我的姓名和身份证 目前我遇到的问题是ascii生成。对于第一个位字符串,它可以正常工作,但是对于其余的位字符串,它只是重复它自己,尽管每个位字符串都不同。有人看到问题了吗?非常感谢您的帮助 迄今为止的代码: import java.util.Random ; public cl

我正在做一个小项目,我必须写一个遗传算法来进化我的名字和身份证号码。基本上,我是随机生成位字符串,然后将其生成为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) ;
        }
    }
}
import java.util.Random;
公共类遗传算法{
公共静态void main(字符串[]args)引发异常
{
int-popSize=0;
int-gen;
双重重复;
双交叉率;
双变位;
int seed=9005970;
字符串id=“John Connolly 00000000”;
int位=7*id.length();
字符串输出;
int-pop;
整数比特;
随机rand=新随机(种子);
ConvertToAscii convert=新的ConvertToAscii();
适应度=新适应度();
试一试{
popSize=Integer.parseInt(args[0]);
如果(popSize<0 | | popSize>100000)
{
System.out.print(“无效数字!人口比率必须使用介于0和100000之间的正数!”);
System.exit(1);//表示发生错误时系统退出
}
gen=Integer.parseInt(args[1]);
如果(发电机<0 | |发电机>100000)
{
System.out.println(“无效数字!生成率必须使用0到100000之间的正数!”);
系统出口(1);
}
repRate=Double.parseDouble(args[2]);
如果(重复率<0 | |重复率>1.0)
{
System.out.println(“无效数字!复制率必须使用0到1.0之间的正小数点!”;
系统出口(1);
}
crossRate=Double.parseDouble(args[3]);
如果(交叉率<0 | |交叉率>1.0)
{
System.out.println(“无效数字!交叉率必须使用0到1.0之间的正小数点!”;
系统出口(1);
}
mutRate=Double.parseDouble(args[4]);
如果(变率<0 | |变率>1.0)
{
System.out.println(“无效数字!突变率必须使用0到1.0之间的正小数点!”;
系统出口(1);
}
如果(重复速率+交叉速率+可变速率!=1.0)
{
System.out.println(“繁殖率、交叉率和变异率之和必须等于1.0!”);
系统出口(1);
}
输出=args[5];
java.io.File File=新的java.io.File(输出);
java.io.PrintWriter writeOut=新的java.io.PrintWriter(文件);
StringBuffer bitString=新的StringBuffer();
int-bestFit=0,fitness=0,totalFit=0;
字符串ascii=“”;
println(popSize+“”+gen+“”+repRate+“”+crossRate+“”+mutRate+“”+output+“”+seed);
用于(pop=0;pop
以下是转换代码:

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 ;
    }

}
公共类ConvertToAscii{
公共字符串binaryToASCII(StringBuffer位字符串)
{
字符串ascii=“”;
字符串byteString;
整数十进制;
int i=0,n=7;
int baseNumber=2;
炭纤维;
而(n 136)
{
十进制=32;
asciiChar=(字符)十进制;
}否则{
asciiChar=(字符)十进制;
}
ascii+=asciiChar;
}
返回ascii码;
}
}

您反复使用同一个StringBuffer,但从未清除它。将填充的第一个成员添加到StringBuffer,即前154个字符。。。然后第二个成员位于插槽155-308中,但是您的binaryToASCII()方法看起来永远不会超过插槽154


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

与dcsohl在其回答中所述一样,您在每次迭代中发送和计算相同的位字符串。我做了这项修改,还对代码进行了一些优化,以提高可读性、代码重用和正确的数据类型

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;
    }   
}
import java.util.Random;
公共类遗传算法{
公共静态void main(字符串[]args)引发异常
{
int-popSize=0;
int-gen;
双重重复;
双交叉率;
双突变
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();
    }

}