English 中文(简体)
如何从显示的1{a> ́2 ́3}格式中抽取N随机探测?
原标题:How to get N random string from a {a1|a2|a3} format string?

(a) 采取下列行动:

string s1="planets {Sun|Mercury|Venus|Earth|Mars|Jupiter|Saturn|Uranus|Neptune}{?|!|.}"
string s2="some text {morning,night,evening} some text{?|!|.}"

How would I choose randomly N from the set, then join them with comma. The set is defined between {} and options are separated with | pipe The order is maintained. String can have multiple sets {}.

一些产出可以是:

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

最佳回答

将地球划入一个阵列,除去随机元素,直到你有足够的空间。 有一些截断的解决办法,从算法的角度讲,但就你重新处理的数据数量而言,这种解决办法是迅速和简单的。

问题回答

我不相信 j的辛子——但应该如此。

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];
}

这是另一种选择。 仅从<条码>>>>>>>>>>>>>>>>、<>/代码”中选择1至1项内容,并将其与对应体分开。 尼斯方案拟订的挑战。

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));
    }
}

是的,产生一种变异性超过<代码>>>>>>>>>>>>>>>/代码。 这里是一个较短、更简单的版本,选择数目的分配不再统一(由Daniel Trebbien回答):

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();
}

我测试了这一 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”

就地球而言,仅写一 lo。

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

这提供了按顺序排列的随机地球清单。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签