的理念是:第一產生與每個0-9隨機字符串一次,而不是與0開始,則:1.取代數字將另一個或2.replace 2個七段與另一箇中的一個。
import java.util.Random;
public class Main {
public static void main(String[] args) {
System.out.println(generateRandomString());
System.out.println(generateRandomString());
}
public static String generateRandomString() {
String alphabet = "";
String result = "";
Random random = new Random();
// build a random string construct will 0-9 and each digital appear once
for (int i = 0; i < 10; i++) {
int index = random.nextInt(alphabet.length());
if (i == 0) { // first cannot be 0
index = random.nextInt(alphabet.length() - 1) + 1;
}
String c = alphabet.substring(index, index + 1);
result += c;
alphabet = alphabet.replace(c, "");
}
return random.nextInt(2) == 0 ? shuffle1(random, result) : shuffle2(random, result);
}
// One of the digits has to be in the String 2 times and one has to not be there at all.
private static String shuffle1(Random random, String result) {
int from = random.nextInt(10);
int to = random.nextInt(9) + 1;
while (from == to) {
to = random.nextInt(9) + 1;
}
result = result.replace(result.substring(to, to + 1), result.substring(from, from + 1));
return result;
}
// One digit has to be there 3 times, and 2 other digits can not be there at all
private static String shuffle2(Random random, String result) {
int from = random.nextInt(10);
int to1 = random.nextInt(9) + 1;
int to2 = random.nextInt(9) + 1;
while (from == to1) {
to1 = random.nextInt(9) + 1;
}
while (from == to2 || to2 == to1) {
to2 = random.nextInt(9) + 1;
}
result = result.replace(result.substring(to1, to1 + 1), result.substring(from, from + 1));
result = result.replace(result.substring(to2, to2 + 1), result.substring(from, from + 1));
return result;
}
}
來源
2016-01-08 03:12:29
xfx
在你的兩個例子中,多次出現的數字順序出現。這是規範的一部分嗎?或者「1030456078」仍然是你的「出現三次」情況的有效例子? –
這個問題似乎有兩個部分:生成數字和驗證數字。正如@sprinter指出的那樣,您可以解決驗證問題,然後隨機生成一串10位數字並檢查它們。 –
順序的出現只是巧合,因爲我把數字從我的腦海中拉出來,然後寫下來。事實上,他們可以在任何地方。感謝您指出了這一點。 – user5760519