【问题标题】:Get random element from array without repeats in Java在Java中从数组中获取随机元素而不重复
【发布时间】:2018-10-23 14:31:03
【问题描述】:

我正在创建一个基于 Java GUI 的程序,但我有一系列问题。在单击JButton 后,我需要创建一个获取下一个问题的方法。下一个问题应随机选择,不应重复先前提出的问题。请看下面的代码——getNextQuestion 将如何实现?

public class QuestionBank {

    String [] questions;
    int currQuestionIndex;

    public QuestionBank() {
        questions = new String [10]; //increase array size if you will add more questions
        questions[0]= "Which three words describe you best?";
        questions[1]= "Which is your best feature?";
        questions[2]= "Which common saying or phrase describes you?";
        questions[3]= "What’s the best thing that’s happened to you this week?";
        questions[4]= "Who was your role model when you were a child?";
        questions[5]= "Who was your favorite teacher and why?";
        questions[6]= "What was your favorite subject at school?";
        questions[7]= "What did you want to be when you grew up?";
        questions[8]= "If you could have one wish come true what would it be?";
        questions[9]= "Which would you prefer — three wishes over five years or one wish right now?";
        //add more questions
    }

    public String getNextQuestion() {
        //get the next question, randomly from the array and without repeats
    }
}

【问题讨论】:

  • 问题可以重复吗?
  • 递增 currQuestionIndex 并验证它没有超出范围...
  • @MadProgrammer - 你错过了'从数组中随机...'
  • @zlakad 不同的是?!很抱歉很难看到问题
  • @MadProgrammer 检查 OP 的源代码注释

标签: java


【解决方案1】:

如果您想以不重复的随机顺序从集合中获取项目(如 cmets 中所述),您可以先打乱集合,然后正常遍历集合。

在 Java 中,与数组相比,打乱 ArrayList 更容易,因此请考虑以下事项:

public class QuestionBank {

    List<String> questions;
    int currQuestionIndex;

    public QuestionBank() {
        questions = new ArrayList<>(); // no size needed
        questions.add("Which three words describe you best?");
        questions.add("Which is your best feature?");
        // add more questions
        currQuestionIndex = 0; // it's 0 by default but this makes it explicit
        Collections.shuffle(questions); // shuffle all questions
    }

    public String getNextQuestion() {
        // get the next question, randomly from the list and without repeats
        if (currQuestionIndex >= questions.size()) {
            return null; // no more questions!
        }
        String nextQuestion = questions.get(currQuestionIndex);
        currQuestionIndex++; // move forward in the shuffled list
        return nextQuestion;
    }
}

如果您必须使用数组而不是 List,请参阅 this question on shuffling an array。策略的其余部分保持不变。

【讨论】:

  • 可能的原因是 OP 不允许使用 ArrayListSet 或所有可以使这变得简单的非常好的东西
  • 非常感谢您
【解决方案2】:

如果您想使用int currQuestionIndex 访问数组中的下一个问题,请确保在构造函数中对其进行初始化!

public QuestionBank() {
    // Initialise and define 'questions' String array here ...
    this.currQuestionIndex = 0;
}

假设你只想访问问题数组中的当前字符串,然后在下次调用该方法时前进到下一个问题:

public String getNextQuestion() {
    // Wrap around when we overshoot the array
    if (currQuestionIndex > questions.length)
        currQuestionIndex = 0;

    currQuestionIndex++;
    return questions[currQuestionIndex-1];
}

也可以随机选择一个问题,确保你import java.util.Random

public String getRandomQuestion() {
    Random rand = new Random();
    return questions[rand.nextInt(questions.length)];
}

【讨论】:

    【解决方案3】:

    使用Queue 怎么样?

    import java.util.*;
    
    public class QuestionBank {
    
        static Queue<String> questions;
    
        public QuestionBank() {
            List<String> tmpQuestions = new ArrayList<>(); // no size needed
            tmpQuestions.add("Which three words describe you best?");
            tmpQuestions.add("Which is your best feature?");
            tmpQuestions.add("Which common saying or phrase describes you?");
            tmpQuestions.add( "What’s the best thing that’s happened to you this week?");
            tmpQuestions.add("Who was your role model when you were a child?");
            tmpQuestions.add("Who was your favorite teacher and why?");
            tmpQuestions.add("What was your favorite subject at school?");
            tmpQuestions.add("What did you want to be when you grew up?");
            tmpQuestions.add("If you could have one wish come true what would it be?");
            tmpQuestions.add( "Which would you prefer — three wishes over five years or one wish right now?");
            Collections.shuffle(tmpQuestions, new Random()); // shuffle all questions
    

    使用pkpnd 建议的ArrayDeque 和following reason

            questions = new ArrayDeque<>(tmpQuestions); 
        }
        public String getNextQuestion() {
            // get the next question, from the randomly populated queue
            if (questions.isEmpty()) {
                return null; // no more questions!
            }
            return questions.remove();
        }
    
        public static void main(String[] args) {
            QuestionBank qb = new QuestionBank();
            String question;
            while((question = qb.getNextQuestion()) != null){
                System.out.println(question);
            }
        }
    }
    

    输出是:

        // 1st execution
    Who was your role model when you were a child?
    What?s the best thing that?s happened to you this week?
    Which common saying or phrase describes you?
    Which is your best feature?
    Which three words describe you best?
    What was your favorite subject at school?
    Which would you prefer ? three wishes over five years or one wish right now?
    If you could have one wish come true what would it be?
    Who was your favorite teacher and why?
    What did you want to be when you grew up?
    
    //2nd execution
    Which common saying or phrase describes you?
    What did you want to be when you grew up?
    What?s the best thing that?s happened to you this week?
    Which three words describe you best?
    What was your favorite subject at school?
    Which would you prefer ? three wishes over five years or one wish right now?
    Who was your role model when you were a child?
    Which is your best feature?
    Who was your favorite teacher and why?
    If you could have one wish come true what would it be?
    
    //3rd execution and so on ....
    What?s the best thing that?s happened to you this week?
    Which common saying or phrase describes you?
    Which is your best feature?
    What was your favorite subject at school?
    Which would you prefer ? three wishes over five years or one wish right now?
    If you could have one wish come true what would it be?
    What did you want to be when you grew up?
    Which three words describe you best?
    Who was your role model when you were a child?
    Who was your favorite teacher and why?
    

    【讨论】:

      猜你喜欢
      • 2014-08-25
      • 2015-04-12
      • 2011-11-01
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      相关资源
      最近更新 更多