从String []中替换一些随机选择

时间:2013-10-02 18:13:32

标签: java grammar

我有这样的事情:

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

如果在从S中进行随机选择并获得,例如“cR”之后,我想从String [] R中替换“R”而不是一些随机选择,我应该怎么做呢? 例: 看我从S开始,然后我从S得到随机,如果我得到cR我只用R字符串中的随机替换R. S-> cR-> cdL(而不是R i put dL)

1 个答案:

答案 0 :(得分: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);
  };
};

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