java 生成 10 位数字的所有组合,没有任何重复
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16375776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generate all combinations of 10 digits without any repetition
提问by Omar Mustafa
I am having an assignment about creating password through Java:
我有一个关于通过 Java 创建密码的作业:
Suppose you work in a safe selling company and your manager asked you to create a list of all the ten digit numbers between 0000000000 and 9999999999 without repeating a digit in the same number. What is the method to do this algorithm in JAVA?
假设您在一家安全销售公司工作,您的经理要求您创建一个列表,其中包含 0000000000 和 9999999999 之间的所有十位数字,并且同一数字中的数字不重复。在JAVA中做这个算法的方法是什么?
Here's what I've done so far:
这是我到目前为止所做的:
public static long generateNumber()
{
String s1 = "33333";
double d = Math.random();
d=d*100000.0;
int i = (int) d;
String s2 = String.valueOf(i);
String s3=s1+s2;
long m = Long.parseLong(s3);
return m;
}
回答by MisterS
If you're looking for ten digit numbers without any duplicate digits, you're effectively looking to generate all permutations of all digits, i.e. the string "0123456789"
.
如果您正在寻找没有任何重复数字的十位数字,您实际上是在寻找生成所有数字的所有排列,即字符串"0123456789"
.
There are other threads on SO to help you with this, for example these
SO上还有其他线程可以帮助您解决此问题,例如这些
回答by Bohemian
A simplstic way that uses little code is:
使用少量代码的简单方法是:
List<Long> combos = new ArrayList<>();
Set<Character> chars = new HashSet<>();
for (long i = 1000000000; i < 9999999999L; i++) {
chars.clear();
for (char c : String.valueOf(i).toCharArray()) {
chars.add(c);
}
if ((chars).size() == 10) {
combos.add(i);
}
}
Not very effeicient, but does the job.
不是很有效,但可以完成工作。
回答by Jeremy Unruh
Using a shuffling technique:
使用混洗技术:
public static void main(String[] args) {
List<Integer> passwords = Arrays.asList( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 );
for (int i = 0; i < 10; i ++)
{
Collections.shuffle(passwords);
String p = toFlatString(passwords);
System.out.println(p);
}
}
private static String toFlatString(List<Integer> list) {
StringBuilder sb = new StringBuilder();
for (int i : list)
sb.append(i);
return sb.toString();
}
Output:2651803497 2936745018 7064918235 1594670823 4035872619 6432971850 6387925401 7103649285 9712380645 9321574806
输出:2651803497 2936745018 7064918235 1594670823 4035872619 6432971850 6387925401 7103649285 964918235 971527380 80