我知道已经存在大量类似的问题,但没有一个能解决我的问题
给定一个字符数组,我希望能够
我想生成特定长度的这些字符的所有可能组合的列表。对于列表中的每个项目,我想将其写入输出文件中的单独行。
请注意,此代码应适用于large 组数字。 (我想在 36 长字符的数据集上使用它,并想要生成一个 32 长的字符串)我知道有 6.3340286662e+49 个可能的答案,并希望这个函数生成全部。
这是一些输入/输出示例:
输入:
int[] a ={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9','0'};
calc(a,32);
457abe9e7d27439681d62f4e0de1f5e1
4adaw435kj546bjk34k4j234kj23f7t3
awdf5e13h4kj546j43k13i3kj24b32hj
12ibj3jk2b4kj23b4kj23b432kjb4uui
etc..
我真的不知道应该如何构建算法 到目前为止,这是我的代码,我知道它并不多,我将在处理它时附加更多代码:
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Random;
public class generator {
public static void gen(int[] i, int l) {
FileWriter fileWriter = new FileWriter("out.txt");
PrintWriter printWriter = new PrintWriter(fileWriter);
//printWriter.print("Some String");
boolean gotAll = false;
Random rand = new Random();
while (!gotAll) {
String newStr = "";
//not the best way to algorithmically get all possible outcomes
for (int y = 0; y < l; y++) {
//randomly generating characters from array
newStr += i[rand.nextInt(i.length)];
}
//need to check for duplicate generation
printWriter.println(newStr);
}
}
public static void main(String[] args) {
int[] i = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
try {
gen(i, 32);
} catch (IOException e) {
e.printStackTrace();
}
}
}
我能想到的获得所有可能结果的最佳方法是不断随机生成数字,直到找到所有数字。这显然非常耗时和资源密集(解决方案将不可避免地如此)。
public class A
{
private static char[] alphabet = {'a', 'b', 'c', '1', '2'};
private static StringBuilder partialSolution = new StringBuilder();
private static void bt(int maxIndex, int index)
{
if( index == maxIndex )
{
String solution = partialSolution.toString();
System.out.println(solution);
}
else
{
for(char c: alphabet)
{
// Extend partial solution
partialSolution.append(c);
bt(maxIndex, index+1);
final int lastCharIndex = partialSolution.length()-1;
// Backtrack
partialSolution.deleteCharAt(lastCharIndex);
}
}
}
private static void btCaller(int maxIndex)
{
bt(maxIndex, 0);
}
public static void main(String[] args)
{
btCaller(3);
}
}