我测试了这一 Java方案,并做了以下工作:
import java.util.R以及om;
/** @author Daniel Trebbien */
// License: Public Domain
public class SO2965185 {
public static String r以及omFormat(final String templ) {
int i = templ.indexOf( { );
if (i < 0) {
return templ;
}
else {
R以及om r = new R以及om();
int prevI = 0;
StringBuilder sb = new StringBuilder();
do {
sb.append(templ, prevI, i);
int j = templ.indexOf( } , i + 1);
if (j < 0)
throw new java.util.MissingFormatArgumentException(templ.substring(i));
int pipeCount = 0;
for (int k = templ.indexOf( | , i + 1); i < k && k < j; k = templ.indexOf( | , k + 1))
++pipeCount;
if (pipeCount == 0) {
sb.append(templ, i + 1, j);
}
else {
String m0Selection;
final int m0 = r.nextInt(pipeCount + 1); // must pick one from each set
if (m0 >= pipeCount) {
m0Selection = templ.substring(templ.lastIndexOf( | , j - 1) + 1, j);
}
else {
int k = i + 1;
int m = m0;
for(; m > 0; --m)
k = templ.indexOf( | , k) + 1;
m0Selection = templ.substring(k, templ.indexOf( | , k + 1));
}
int selectionCount = 0;
for (int n = 0; n <= pipeCount; ++n) {
if (n == m0) {
if (selectionCount != 0)
sb.append(", ");
sb.append(m0Selection);
++selectionCount;
}
else if (r.nextBoolean()) {
int m = n;
if (selectionCount != 0)
sb.append(", ");
if (m >= pipeCount) {
sb.append(templ, templ.lastIndexOf( | , j - 1) + 1, j);
}
else {
int k = i + 1;
for(; m > 0; --m)
k = templ.indexOf( | , k) + 1;
sb.append(templ, k, templ.indexOf( | , k + 1));
}
++selectionCount;
}
}
}
prevI = j + 1;
i = templ.indexOf( { , j + 1);
} while(i >= 0);
return sb.toString();
}
}
public static void main(String[] args) {
System.out.println(r以及omFormat("test"));
System.out.println(r以及omFormat("{oneOption}"));
System.out.println(r以及omFormat("{first|second}"));
String s1 = "planets {Sun|Mercury|Venus|Earth|Mars|Jupiter|Saturn|Uranus|Neptune}{?|!|.}";
System.out.println(r以及omFormat(s1));
//System.out.println(r以及omFormat("jjj{test"));
}
}
该方案印刷了如下内容:
test
oneOption
first, second
planets Sun, Mercury, Jupiter, Neptune?, !, .
以及
test
oneOption
second
planets Sun, Jupiter, Saturn!, .
以及
test
oneOption
first
planets Venus, Earth, Jupiter, Saturn, Uranus, Neptune.
由于我最初为稍有不同的问题撰写了法典,你不得不宽恕我:
The code picks r以及om combinations of entries having at least one entry from each set. So, for a set with N entries, there are 2N - 1 combinations that can be generated. Also, keep in mind the probability that there are exactly M entries in the r以及om combination:
P(实际M 生成组合中的条目) = (N 选择M)除以2<<<><><>- 1)
例:N = 9 (>>>{>S.un.Mercury , >enus Homme , « Jupiter Saturn Uranuseptune}"
。
http://www.google.com/search?q=%289+2%F%2822%E9+1%29”rel=“nofollow noreferer”