我一直在嘗試制作一種方法來混洗多項選擇題選項(A、B、C、D)并更新與新順序匹配的正確答案,但您不能使用陣列和 collections.shuffle。
uj5u.com熱心網友回復:
改組的演算法可能如下所示:
- 創建兩個
StringBuilder實體,一個是輸入字串的副本,另一個是混洗資料的累加器。 - 在回圈中,計算 中的隨機位置
copy,將該位置的字符追加到accumulator并洗掉,copy直到副本不為空
public static String shuffle(String str) {
if (null == str || str.length() < 2) {
return str; // nothing to shuffle, return as is
}
StringBuilder copy = new StringBuilder(str);
StringBuilder acc = new StringBuilder();
Random random = new Random();
while (copy.length() > 0) {
int pos = random.nextInt(copy.length());
acc.append(copy.charAt(pos));
copy.deleteCharAt(pos);
}
return acc.toString();
}
測驗:
for (int i = 0; i < 10; i ) {
System.out.println(i " ABCD -> " shuffle("ABCD"));
}
輸出:
0 ABCD -> BDCA
1 ABCD -> BCAD
2 ABCD -> DBCA
3 ABCD -> DCAB
4 ABCD -> BCAD
5 ABCD -> CDBA
6 ABCD -> BACD
7 ABCD -> ACDB
8 ABCD -> ADBC
9 ABCD -> CDAB
使用一個版本List<Character>來保存副本,String而不是StringBuilder:
public static String shuffle(String str) {
if (null == str || str.length() < 2) {
return str;
}
List<Character> copy = new ArrayList<>();
for (int i = 0; i < str.length(); i ) {
copy.add(str.charAt(i));
}
Random random = new Random();
String result = "";
while (copy.size() > 0) {
int pos = random.nextInt(copy.size());
result = copy.get(pos);
copy.remove(pos);
}
return result;
}
uj5u.com熱心網友回復:
改組演算法的另一個版本:
- 將所有字串字符復制到中間字符緩沖區
- 迭代此緩沖區并將每個字符與隨機索引處的元素交換
- 從該緩沖區創建結果字串
此解決方案的 Java 代碼:
public static String shuffle(String str, Random random) {
CharBuffer chars = CharBuffer.wrap(str.toCharArray());
for (int i = 0; i < chars.capacity(); i ) {
int index = random.nextInt(chars.capacity());
char tmp = chars.get(index);
chars.put(index, chars.get(i));
chars.put(i, tmp);
}
return chars.toString();
}
PS,這在我的機器上比使用 StringBuilder 或 Lists 快 10 倍。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/330960.html
