Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.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 生成字符串排列和组合的智能方法_Java_Algorithm_Combinations_Permutation - Fatal编程技术网

Java 生成字符串排列和组合的智能方法

Java 生成字符串排列和组合的智能方法,java,algorithm,combinations,permutation,Java,Algorithm,Combinations,Permutation,我想根据给定的数据库生成以下字符串序列 String database[] = {'a', 'b', 'c'}; 我只能想出一个相当“愚蠢”的解决方案 a b c aa ab ac ba bb bc ca cb cc aaa ... 公共类JavaApplication21{ /** *@param指定命令行参数 */ 公共静态void main(字符串[]args){ char[]数据库={'a','b','c'}; 字符串query=“a”; StringBuilder查询\u sb=新

我想根据给定的
数据库
生成以下字符串序列

String database[] = {'a', 'b', 'c'};
我只能想出一个相当“愚蠢”的解决方案

a
b
c
aa
ab
ac
ba
bb
bc
ca
cb
cc
aaa
...
公共类JavaApplication21{
/**
*@param指定命令行参数
*/
公共静态void main(字符串[]args){
char[]数据库={'a','b','c'};
字符串query=“a”;
StringBuilder查询\u sb=新的StringBuilder(查询);
for(int a=0;a
这个解决方案相当愚蠢。从这个意义上讲,它是不可伸缩的

  • 如果我增加
    数据库的大小会怎样
  • 如果我的最终目标打印字符串长度需要为N怎么办

  • 有没有智能代码可以以一种非常智能的方式生成可缩放的排列和组合字符串?

    这闻起来像是二进制计数:

    • 001
    • 010
    • 011
    • 一百
    • 101
    我的第一反应是使用二进制计数器作为字符的“位图”来生成那些可能的值。然而,这里有几个关于使用递归的相关问题的极好答案。看


    您应该检查以下答案:

    要获取此代码,请执行以下操作:

    public class JavaApplication21 {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            char[] database = {'a', 'b', 'c'};
    
            String query = "a";
            StringBuilder query_sb = new StringBuilder(query);
            for (int a = 0; a < database.length; a++) {
                query_sb.setCharAt(0, database[a]);
                query = query_sb.toString();                    
                System.out.println(query);            
            }
    
            query = "aa";
            query_sb = new StringBuilder(query);
            for (int a = 0; a < database.length; a++) {
                query_sb.setCharAt(0, database[a]);    
                for (int b = 0; b < database.length; b++) {    
                    query_sb.setCharAt(1, database[b]);    
                    query = query_sb.toString();                    
                    System.out.println(query);
                }
            }
    
            query = "aaa";
            query_sb = new StringBuilder(query);
            for (int a = 0; a < database.length; a++) {
                query_sb.setCharAt(0, database[a]);    
                for (int b = 0; b < database.length; b++) {    
                    query_sb.setCharAt(1, database[b]);    
                    for (int c = 0; c < database.length; c++) {                    
                        query_sb.setCharAt(2, database[c]);                        
                        query = query_sb.toString();                    
                        System.out.println(query);
                    }
                }
            }
        }
    }
    
    公共静态字符串[]getAllList(字符串[]元素,int lengthOfList)
    {
    //长度为1的列表只是原始元素
    if(lengthOfList==1)返回元素;
    否则{
    //使用上面计算的元素数初始化返回的列表
    String[]allLists=新字符串[(int)Math.pow(elements.length,lengthOfList)];
    //递归——获取长度为3、长度为2的所有列表,一直到1
    String[]allsublist=getAllList(元素,lengthOfList-1);
    //将子列表附加到每个元素
    int-arrayIndex=0;
    for(int i=0;i对于(int i=1;i好的,所以置换的最佳解决方案是递归。假设字符串中有n个不同的字母。这将产生n个子问题,从每个唯一的字母开始的每组置换一个子问题。创建一个方法
    置换前缀(string thePrefix,string theString)
    这将解决这些单独的问题。创建另一个方法
    列表置换(字符串)
    实现如下

    public static String[] getAllLists(String[] elements, int lengthOfList)
    {
    
        //lists of length 1 are just the original elements
        if(lengthOfList == 1) return elements; 
        else {
            //initialize our returned list with the number of elements calculated above
            String[] allLists = new String[(int)Math.pow(elements.length, lengthOfList)];
    
            //the recursion--get all lists of length 3, length 2, all the way up to 1
            String[] allSublists = getAllLists(elements, lengthOfList - 1);
    
            //append the sublists to each element
            int arrayIndex = 0;
    
            for(int i = 0; i < elements.length; i++){
                for(int j = 0; j < allSublists.length; j++){
                    //add the newly appended combination to the list
                    allLists[arrayIndex] = elements[i] + allSublists[j];
                    arrayIndex++;
                }
            }
            return allLists;
        }
    }
    
    public static void main(String[] args){
        String[] database = {"a","b","c"};
        for(int i=1; i<=database.length; i++){
            String[] result = getAllLists(database, i);
            for(int j=0; j<result.length; j++){
                System.out.println(result[j]);
            }
        }
    }
    
    void permutationsWithPrefix(字符串thePrefix,字符串theString){
    如果(!theString.length)println(thePrefix+theString);
    for(int i=0;i
    置换生成器的Java实现:-

    void permutationsWithPrefix(String thePrefix, String theString) {
       if ( !theString.length ) println(thePrefix + theString);
       for(int i = 0; i < theString.length; i ++ ) {
          char c = theString.charAt(i);
          String workingOn = theString.subString(0, i) + theString.subString(i+1);   
          permutationsWithPrefix(prefix + c, workingOn);
       }
    } 
    
    void listPermutations(String theString) {
       permutationsWithPrefix("", theString);
    }
    
    公共类置换{
    公共静态void permGen(字符[]s,整数i,整数k,字符[]buff){
    
    如果(i我在面试中遇到了这个问题。下面是我使用递归实现的解决方案

    public class Permutations {
    
    
        public static void permGen(char[] s,int i,int k,char[] buff) {
            if(i<k) {
                for(int j=0;j<s.length;j++) {
    
                    buff[i] = s[j];
                    permGen(s,i+1,k,buff);
                }
            }       
            else {
    
             System.out.println(String.valueOf(buff)); 
    
            }
    
        }
    
        public static void main(String[] args) {
            char[] database = {'a', 'b', 'c'};
            char[] buff = new char[database.length];
            int k = database.length;
            for(int i=1;i<=k;i++) {
                permGen(database,0,i,buff);
            }
    
    }
    
    }
    
    公共类密码破解程序{
    私有列表文档计算(字符串输入字符串){
    List totalList=新的ArrayList();
    
    对于(int i=1;i对于任何寻找非递归选项的人,这里是一个数字排列的示例(可以很容易地调整为
    char
    numberOfAgents
    是列数,数字集是
    0
    numberOfActions

    public class PasswordCracker {
    
    private List<String> doComputations(String inputString) {
    
        List<String> totalList =  new ArrayList<String>();
        for (int i = 1; i <= inputString.length(); i++) {
    
            totalList.addAll(getCombinationsPerLength(inputString, i));
        }
        return totalList;
    
    }
    
    private ArrayList<String> getCombinationsPerLength(
            String inputString, int i) {
    
        ArrayList<String> combinations = new ArrayList<String>();
    
        if (i == 1) {
    
            char [] charArray = inputString.toCharArray();
            for (int j = 0; j < charArray.length; j++) {
                combinations.add(((Character)charArray[j]).toString());
            }
            return combinations;
        }
        for (int j = 0; j < inputString.length(); j++) {
    
            ArrayList<String> combs = getCombinationsPerLength(inputString, i-1);
            for (String string : combs) {
                combinations.add(inputString.charAt(j) + string);
            }
        }
    
        return combinations;
    }
    public static void main(String args[]) {
    
        String testString = "abc";
        PasswordCracker crackerTest = new PasswordCracker();
        System.out.println(crackerTest.doComputations(testString));
    
    }
    }
    
    int numberOfAgents=5;
    int numberOfActions=8;
    字节[][]组合=新字节[(int)Math.pow(numberOfActions,numberOfAgents)][numberOfAgents];
    //每列都要分开做
    对于(字节j=0;j//如果需要重复,请使用ARRAYLIST而不是SET!!
    导入java.util.*;
    公共类置换{
    公共静态void main(字符串[]args){
    扫描仪输入=新扫描仪(系统输入);
    System.out.println(“输入字符串”);
    Set se=find(在.nextLine()中);
    
        int numberOfAgents=5;
        int numberOfActions = 8;
        byte[][]combinations = new byte[(int)Math.pow(numberOfActions,numberOfAgents)][numberOfAgents];
    
        // do each column separately
        for (byte j = 0; j < numberOfAgents; j++) {
            // for this column, repeat each option in the set 'reps' times
            int reps = (int) Math.pow(numberOfActions, j);
    
            // for each column, repeat the whole set of options until we reach the end
            int counter=0;
            while(counter<combinations.length) {
                // for each option
                for (byte i = 0; i < numberOfActions; i++) {
                    // save each option 'reps' times
                    for (int k = 0; k < reps; k++)
                        combinations[counter + i * reps + k][j] = i;
                }
                // increase counter by 'reps' times amount of actions
                counter+=reps*numberOfActions;
            }
        }
    
        // print
        for(byte[] setOfActions : combinations) {
            for (byte b : setOfActions)
                System.out.print(b);
            System.out.println();
        }
    
    // IF YOU NEED REPEATITION USE ARRAYLIST INSTEAD OF SET!!
    
    import java.util.*;
    public class Permutation {
    
        public static void main(String[] args) {
            Scanner in=new Scanner(System.in);
            System.out.println("ENTER A STRING");
            Set<String> se=find(in.nextLine());
            System.out.println((se));
        }
        public static Set<String> find(String s)
        {
            Set<String> ss=new HashSet<String>();
            if(s==null)
            {
                return null;
            }
            if(s.length()==0)
            {
                ss.add("");
            }
            else
            {
                char c=s.charAt(0);
                String st=s.substring(1);
                Set<String> qq=find(st);
                for(String str:qq)
                {
                    for(int i=0;i<=str.length();i++)
                    {
                        ss.add(comb(str,c,i));
                    }
                }
            }
            return ss;
    
        }
        public static String comb(String s,char c,int i)
        {
            String start=s.substring(0,i);
            String end=s.substring(i);
            return start+c+end;
        }
    
    }
    
    
    // IF YOU NEED REPEATITION USE ARRAYLIST INSTEAD OF SET!!