Java 如何从{a1 | a2 | a3}格式字符串中获取N个随机字符串?
将此字符串作为输入:Java 如何从{a1 | a2 | a3}格式字符串中获取N个随机字符串?,java,algorithm,Java,Algorithm,将此字符串作为输入: string s1="planets {Sun|Mercury|Venus|Earth|Mars|Jupiter|Saturn|Uranus|Neptune}{?|!|.}" string s2="some text {morning,night,evening} some text{?|!|.}" 我如何从集合中随机选择N,然后用逗号连接它们。集合在{}之间定义,选项用|管道分隔 秩序得以维持。字符串可以有多个集合{} 一些输出可能是: string output1="
string s1="planets {Sun|Mercury|Venus|Earth|Mars|Jupiter|Saturn|Uranus|Neptune}{?|!|.}"
string s2="some text {morning,night,evening} some text{?|!|.}"
我如何从集合中随机选择N,然后用逗号连接它们。集合在{}之间定义,选项用|管道分隔
秩序得以维持。字符串可以有多个集合{}
一些输出可能是:
string output1="planets Sun, Venus.";
string output2="planets Neptune!";
string output3="planets Earth, Saturn, Uranus, Neptune.";
string output4="planets Uranus, Saturn.";// bad example, order is not correct
string output5="some text morning!";
Java 1.5将行星粘贴到一个数组中,并移除随机元素,直到有足够的元素为止。从算法上讲,有更可爱的解决方案,但对于处理的数据量来说,这是快速而简单的。我不确定java的语法,但它应该是这样的
string[] split = s.split("|");
Random r = new Random();
int first = r.nextInt(split.length);
string planets = "planets " + split[first++];
for (; first < split.length; first++)
{
if (r.nextInt(2) == 1)
planets += " " + split[first];
}
string[]split=s.split(“|”);
随机r=新随机();
int first=r.nextInt(拆分长度);
字符串planets=“planets”+拆分[first++];
对于(;first
我测试了这个Java程序,它可以工作:
import java.util.Random;
/** @author Daniel Trebbien */
// License: Public Domain
public class SO2965185 {
public static String randomFormat(final String templ) {
int i = templ.indexOf('{');
if (i < 0) {
return templ;
}
else {
Random r = new Random();
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(randomFormat("test"));
System.out.println(randomFormat("{oneOption}"));
System.out.println(randomFormat("{first|second}"));
String s1 = "planets {Sun|Mercury|Venus|Earth|Mars|Jupiter|Saturn|Uranus|Neptune}{?|!|.}";
System.out.println(randomFormat(s1));
//System.out.println(randomFormat("jjj{test"));
}
}
import java.util.Random;
/**@作者丹尼尔·特雷宾*/
//许可证:公共领域
公共类SO2965185{
公共静态字符串格式(最终字符串模板){
inti=temp.indexOf('{');
if(i<0){
返回模板;
}
否则{
随机r=新随机();
int-prevI=0;
StringBuilder sb=新的StringBuilder();
做{
某人附加(模板、上一页、下一页);
int j=temp.indexOf('}',i+1);
if(j<0)
抛出新的java.util.MissingFormatArgumentException(temp.substring(i));
int pipeCount=0;
对于(int k=temp.indexOf('|',i+1);i=管道计数){
m0Selection=temp.substring(temp.lastIndexOf(“|”,j-1)+1,j);
}
否则{
int k=i+1;
int m=m0;
对于(;m>0;--m)
k=模板索引(“|”,k)+1;
m0Selection=temp.substring(k,temp.indexOf('|',k+1));
}
int-selectionCount=0;
对于(int n=0;n=pipeCount){
sb.append(temp,temp.lastIndexOf('|',j-1)+1,j);
}
否则{
int k=i+1;
对于(;m>0;--m)
k=模板索引(“|”,k)+1;
sb.append(temp,k,temp.indexOf('|',k+1));
}
++选择计数;
}
}
}
prevI=j+1;
i=temp.indexOf('{',j+1);
}而(i>=0);
使某人返回字符串();
}
}
公共静态void main(字符串[]args){
System.out.println(随机格式(“测试”);
System.out.println(随机格式(“{oneOption}”);
System.out.println(随机格式(“{first | second}”);
字符串s1=“行星{太阳|水星|金星|地球|火星|木星|土星|天王星|海王星}{?|!|}”;
System.out.println(随机格式(s1));
//System.out.println(随机格式(“jjj{test”);
}
}
此程序打印如下内容:
test
oneOption
first, second
planets Sun, Mercury, Jupiter, Neptune?, !, .
测试
一种选择
第一,第二
行星太阳,水星,木星,海王星。
及
测试
一种选择
第二
行星太阳,木星,土星。
及
测试
一种选择
第一
行星金星,地球,木星,土星,天王星,海王星。
您必须稍微原谅这一混乱,因为我最初是为一个稍微不同的问题编写代码的:)
代码从每个集合中选择至少有一个条目的条目的随机组合。因此,对于一个有N个条目的集合,可以生成2N-1个组合。此外,请记住随机组合中有M个条目的概率:
p(在生成的组合中正好是M个条目)=(N选择M)除以(2N-1)
示例:N=9(“{太阳|水星|金星|地球|火星|木星|土星|天王星|海王星}”
)
p(生成的组合中正好有2个条目)=这里是另一个选项。这一个只从
{| | |}
集中选择1个元素,在{,,}
集中选择1到N个元素,并用逗号分隔它们。不错的编程挑战
public static String generateVariant(String s) {
Pattern p = Pattern.compile("[{]([^}]+)[}]");
Matcher m = p.matcher(s);
StringBuilder output = new StringBuilder();
int offset = 0;
while (m.find()) {
output.append(s.substring(offset, m.start()));
String[] choices = m.group(1).split("[|,]");
// if '|' used as separator, only echo 1 random choice
int n = m.group(1).contains("|") ? 1
: (int) (Math.random() * (choices.length - 1)) + 1;
// permutation with n random elements
int[] permutation = new int[choices.length];
for (int i = 0; i < choices.length; i++) {
permutation[i] = i;
}
for (int i=0; i<n; i++) {
int r = (int)(Math.random() * (choices.length - i)) + i;
int aux = permutation[r];
permutation[r] = permutation[i];
permutation[i] = aux;
}
// sort and echo first n
Arrays.sort(permutation, 0, n);
for (int i=0; i<n; i++) {
output.append((i == 0 ? "" : ", ") + choices[permutation[i]]);
}
offset = m.end();
}
output.append(s.substring(offset, s.length()));
return output.toString();
}
public static void main(String[] args) {
String s1 = "planets {Sun,Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune}{?|!|.}";
for (int i = 0; i < 10; i++) {
System.err.println(generateVariant(s1));
}
}
对于行星,只需写一个循环
result = empty list
For p in planets
throw a dice
If (dice > 3) // 50% probability, adjust as required
append p to result
If result is empty, start over // do this if you don't want result to be empty
这会按照给定的顺序给出一个行星的随机列表。不要使用正则表达式-对数组和随机数使用go我需要从字符串中获取{}集,可能需要正则表达式,是吗?同意-但主要部分是选择随机字符串,对吗?可能,选择{},然后选择随机数,然后放回定义{}的字符串中。最后一个部分对我来说也是很难的。你只需要在句子末尾加上1个标点符号——考虑使用“{”}来“选择一个”和{,},“选择一个或多个,并加入逗号”。实际上,这是个极好的主意。如果原始集合的大小是m,则考虑n和m n:如果n小于,则取m的n项;否则,从M.@ Grigs'中删除M—N项:我同意,但我会重申,对于这样一个小数据集,它实际上并不重要。哇,这是更复杂的,那么我就猜到了需要的解决方案。考虑使用正则表达式来定位模式来替代。使用“split()”还可以使代码更易于阅读(并避免了大量的“substring()”和“indexOf()”调用)。另一方面,我喜欢抛硬币来获得
public static String generateVariant(String s) {
Pattern p = Pattern.compile("[{]([^}]+)[}]");
Matcher m = p.matcher(s);
StringBuilder output = new StringBuilder();
int offset = 0;
while (m.find()) {
output.append(s.substring(offset, m.start()));
String[] choices = m.group(1).split("[|,]");
// if '|' used as separator, only echo 1 random choice
int n = m.group(1).contains("|") ? 1
: (int) (Math.random() * (choices.length - 1)) + 1;
// permutation with n random elements
int[] permutation = new int[choices.length];
for (int i = 0; i < choices.length; i++) {
permutation[i] = i;
}
for (int i=0; i<n; i++) {
int r = (int)(Math.random() * (choices.length - i)) + i;
int aux = permutation[r];
permutation[r] = permutation[i];
permutation[i] = aux;
}
// sort and echo first n
Arrays.sort(permutation, 0, n);
for (int i=0; i<n; i++) {
output.append((i == 0 ? "" : ", ") + choices[permutation[i]]);
}
offset = m.end();
}
output.append(s.substring(offset, s.length()));
return output.toString();
}
public static void main(String[] args) {
String s1 = "planets {Sun,Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune}{?|!|.}";
for (int i = 0; i < 10; i++) {
System.err.println(generateVariant(s1));
}
}
public static String generateVariant(String s) {
Pattern p = Pattern.compile("[{]([^}]+)[}]");
Matcher m = p.matcher(s);
StringBuilder output = new StringBuilder();
Random r = new Random();
int offset = 0;
while (m.find()) {
output.append(s.substring(offset, m.start()));
String[] choices = m.group(1).split("[|,]");
// if '|' used as separator, only echo 1 random choice
if (m.group(1).contains("|")) {
output.append(choices[r.nextInt(choices.length)]);
} else {
boolean first = true;
for (int i=0; i<choices.length; i++) {
if (r.nextBoolean()) {
output.append((first ? "" : ", ") + choices[i]);
first = false;
}
}
}
offset = m.end();
}
output.append(s.substring(offset, s.length()));
return output.toString();
}
result = empty list
For p in planets
throw a dice
If (dice > 3) // 50% probability, adjust as required
append p to result
If result is empty, start over // do this if you don't want result to be empty