public class PhraseOMatic//注意不能再字符串“”中间加换行符,否则不能编译并运行
{
public static void main (String[] args){
String [] name = {"小鸟","雷洛","核桃","AL","土豆","不二"};
String [] diyiju = {"今天早上","今天中午","今天晚上","今天下午","今天凌晨"};
String [] dierju = {"在路边","在沙滩上","在河边","在山上","在超市里","在空中"};
String [] disanju = {"和蚂蚁跳舞。","和便便亲嘴。","和蚂蚱赛跑。","和兔子吃烧烤。"};
//计算每一组有多少个名词术语
int mingzi = name.length;
int diyi = diyiju.length;
int dier = dierju.length;
int disan = disanju.length;
//产生随机数字
int ming = (int) (Math.random()*mingzi);
int yi = (int) (Math.random()*diyi);
int er = (int) (Math.random()*dier);
int san = (int) (Math.random()*disan);
//组合出扯淡的句子
String phrase = name[ming]+diyiju[yi]+dierju[er]+disanju[san];
System.out.println(phrase);
}
}
给每一个词加权。
这段代码其实是从0~length 中随机到一个下标 然后拼接。
比如你要使{"小鸟","雷洛","核桃","AL","土豆","不二"};这么中的小鸟出现的概率大一点,
你就可以从0~2*length的范围去取随机数,然后0~length 都是取小鸟,其余的对应。
如果概率很复杂,那么就得用很复杂的if else 去匹配,
建议写一个方法,String getOne(String[] value, double[] weight)去解决
第二个参数是权重
//组合出扯淡的句子
String phrase1 = getOne(name, new int[]{0,0,0,0,0,1}) +
getOne(diyiju, new int[]{0,0,0,1,0}) +
getOne(dierju, new int[]{0,1,0,0,0,1}) +
getOne(disanju, new int[]{1,0,0,0});
//组合出扯淡的句子
String phrase2 = getOne(name, new double[]{0,0,0.1,0.2,0.3,0.4}) +
getOne(diyiju, new double[]{0.1,0.1,0.1,0.1,0.6}) +
getOne(dierju, new double[]{0.25,0.1,0.1,0.25,0.15,0.15}) +
getOne(disanju, new double[]{0.2,0.2,0.25,0.25});
public static String getOne(String[] values, int[] weights) {
int sum = 0;
for (int weight:weights) {
sum += weight;
}
double weight = 0;
double ran = Math.random();
for (int i=0; i<weights.length; i++) {
weight += weights[i]*1.0/sum;
if (weight >= ran) {
return values[i];
}
}
return values[values.length - 1];
}
public static String getOne(String[] values, double[] weights) {
double weight = 0;
double ran = Math.random();
for (int i=0; i<weights.length; i++) {
weight += weights[i];
if (weight >= ran) {
return values[i];
}
}
return values[values.length - 1];
}