-4

I have something like this:

import java.util.Random;

public class gramatica {
public static void main(String[] args) {

    String [] Vt = {"S","R","L"};
    String [] Vn = {"a","b","c","d","e","f"};

    String [] S = {

            "aS","bS","cR","dL"
    };

    String[] R = {
            "dL","e"
    };

    String []L = {

            "fL","eL","d"
    };
    System.out.println(S[0]);
    String random = (S[new Random().nextInt(S.length)]);
    String chop = (S[new Random().nextInt(S.length)]);

    System.out.println("S->"+random);

If, after making the random selection from S, and getting, for example "cR", I want to replace instead of "R" some random selection from String[] R, how should I go about that? Example: Look i start with S , then i get random from S and if i got cR i replace only R with random from R string array. S->cR->cdL (instead of R i put dL)

4

1 回答 1

1

我认为这就是你想要的:

import java.util.Random;

public class gramatica {
  public static void main(String[] args) {

    String [] Vt = {"S","R","L"};
    String [] Vn = {"a","b","c","d","e","f"};

    String [] S = {

            "aS","bS","cR","dL"
    };

    String[] R = {
            "dL","e"
    };

    String []L = {

            "fL","eL","d"
    };
    //System.out.println(S[0]);
    String rule = "S";

    Random r = new Random();

    // Make a loop
    while(true) {
      if(rule.contains("S")) {
        rule = rule.replaceFirst("S", S[r.nextInt(S.length)]);
        continue;
      };
      if(rule.contains("R")) {
        rule = rule.replaceFirst("R", R[r.nextInt(R.length)]);
        continue;
      };
      if(rule.contains("L")) {
        rule = rule.replaceFirst("L", L[r.nextInt(L.length)]);
        continue;
      };

      // Nothing to change, break loop
      break;
    };

    // Now we got a random possible rule for S! :)
    System.out.println("S->"+rule);
  };
};

此代码将为您的语法生成一个随机的可能字符串。:)

于 2013-10-02T18:32:04.183 回答