Q1。我们可以生成 8 位唯一的 9-10 百万个数字字符串吗?
是的,您可以使用 10 位 1、2、3、4、5、6、7、8、9、0 生成 10000000 个 8 位唯一数字字符串
如果您为所有可能的组合编写正确的逻辑,您将不会得到任何重复,但为了安全起见,您可以使用 set。
当您收到 java.lang.OutOfMemoryError 错误时,这是因为您生成了这么多数字并将其保存在内存中。解决方案是您生成一些小块数字并将其保存到数据库中,然后清除列表并再次填充下一个数字块并保持重复,直到您将所有数字保存到数据库中。
Q2。如何在一个程序运行中生成 9 到 1000 万个唯一的“仅限数字”字符串?
这是一个组合代码,您可以使用它来实现您的目标
public class Combination{
public static int count = 0;
public static ArrayList<String> list;
public Combination(){
list = new ArrayList<String>();
}
public static void main(String[] args){
Combination c = new Combination();
Scanner sc = new Scanner(System.in);
String str = sc.next();
int num = sc.nextInt();
if(num>str.length()){
System.out.println("This combination is not possible");
System.out.println(num+" should be less than or equal to the length of the string "+str);
}else{
System.out.println("Processing....");
char[] array = new char[num];
c.fillNthCharacter(0,array,str);
System.out.println("Total combination = "+count);
}
}
public static void fillNthCharacter(int n,char[] array,String str){
for(int i=0;i<str.length();i++){
array[n]=str.charAt(i);
if(n<array.length-1){
fillNthCharacter(n+1,array,str);
}else{
count++;
//System.out.println(new String(array));
list.add(new String(array));
if(list.size()>100000){
//code to add into database
list.clear();
}
}
}
}
}