防止连续出现相同的随机输出

时间:2016-01-30 05:22:52

标签: java

我的代码应该只是问一个问题,但我想阻止它两次问同一个随机问题。

public static String askQuestion(){
    if (hasMoreQuestions() == true);{
        int oldq = 
        String[] Question = {"How are you today?","Do you enjoy the rain?","Meow?"};
        Random randomno = new Random();
        int nextq = randomno.nextInt(3);
        if (oldq == nextq){
            askQuestion();
        }
        oldq = nextq;

        return Question[nextq];
    }
}

这是我的尝试,我希望简单地将之前的输出与随机选择的新输出进行比较。但我是Java新手,我很难弄清楚实现这一目标的最佳方法是什么。

2 个答案:

答案 0 :(得分:3)

第一次尝试

您可以尝试检查不同的数字,然后只需在这些数字索引上打印问题,而不是递归调用相同的函数,例如:

import java.util.Random;
public class UniqueRandom {
    public static void main(String args[]) {
        Random r = new Random();
        int n1, n2;

        n1 = r.nextInt(3);
        do {
            n2 = r.nextInt(3);
        } while (n2 == n1);

        String question[] = {"How are you today?","Do you enjoy the rain?","Meow?"};

        System.out.println(question[n1]);
        System.out.println(question[n2]);
    }
}

打印:

How are you today?
Do you enjoy the rain?

第二次尝试

另一种方法是使用HashMap,您可以在其中保留唯一键,并在打印后删除元素,例如:

import java.util.Random;
import java.util.HashMap;
import java.util.Map;
public class UniqueRandom {
    public static void main(String args[]) {
        Random r = new Random();
        int n1, n2;
        String question[] = {"How are you today?","Do you enjoy the rain?","Meow?"};
        HashMap <Integer, String> map = new HashMap<Integer, String>();
        String q = null;
        for (int i = 0; i < question.length; i++) {
            map.put(i, question[i]); //Filling the map
        }

        do {
            n1 = r.nextInt(question.length);
            while (!map.containsKey(n1)) {
                n1 = r.nextInt(question.length);
            }
            q = map.get(n1);
            System.out.println(q); //Print the question
            map.remove(n1); //Remove it from set
        } while (map.size() > 0);
    }
}

这将始终打印一个独特的组合,无需重复提问。

How are you today?
Do you enjoy the rain?
Meow?

答案 1 :(得分:1)

首先,你必须意识到,通过干扰正态分布,你不会随意询问&#34;随机&#34;的问题。 Blah,等等,纯粹的胡说八道。我们都知道你的意思:你想提出从某个池中随机抽取的问题,该池不包括最近提出的问题。 这表明了一种非常简单的方法:从集合中抽取随机问题并将其呈现给用户。将其从集合中删除并将其存储为previousQuestion。在询问nextQuestion(当然成为previousQuestion)之后将其恢复到池中,依此类推。 如果使用某种类型的集合而不是数组,则更容易实现。

但是,如果你热衷于使用数组,那么你就可以逃避这样的事情(只添加你不熟悉的部分):

int prevQuestion = -1;
int nextQuestion = -1;
while (continuing) {
  while (nextQuestion == prevQuestion) {
    nextQuestion = randomno.nextInt(questions.length);
  }
  prevQuestion = nextQuestion;
  // ask nextQuestion and prompt to see if we're continuing
}