有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在JAVA中生成包含特定数字的不同随机数列表?

好的,这个场景是,我想生成一个由4distinct个随机数组成的列表,它将代表一个测验应用程序的4个随机选择。4个随机选择中的一个将是正确答案,因此我们已经知道正确选择的索引。此正确的索引或编号必须包含在随机编号列表中

<强> < EM >例如: < /强>考虑到长度为100的^ {< CD2>},包含一个问题的100个选择的{{CD3>}值,正确选择的^ {< CD4}}是^ {< CD5>}。现在我们想要这个问题的4个随机选择,包括索引45,这样索引列表将类似于{2,91,45,17}。此外,列表中不应包含重复的数字

你知道如何在Java中实现这一点吗


共 (3) 个答案

  1. # 1 楼答案

    对于Java 6及更新版本:

    final int maxNumber = 100;
    final int numbersToGenerate = 4;
    final int correctAnswer = 45;
    
    Set<Integer> possibleAnswers = new HashSet<>();
    Random random = new Random();
    
    // add correct answer
    possibleAnswers.add(correctAnswer);
    
    // add as much random answers as needed, the usage of a set prevents duplicates
    while(possibleAnswers.size() < numbersToGenerate) {
        possibleAnswers.add(random.nextInt(maxNumber));
    }
    
    // convert set to list and shuffle it
    List<Integer> answers = new ArrayList<Integer>(possibleAnswers);
    Collections.shuffle(answers, new Random(System.nanoTime()));
    

    对于低于6的Java版本,您必须编写自己的shuffle方法,因为据我所知,Collections.shuffle是在Java6中引入的

    我最初建议使用Java8的随机api,但在我的想法中发现了一个bug。如果生成的随机数数组包含正确答案,则该数组将不起作用。请谅解:

    不工作

    final int minNumber = 1;
    final int maxNumber = 100;
    final int numbersToGenerate = 3;
    
    final int[] ints = new Random().ints(minNumber, maxNumber)
    .distinct().limit(numbersToGenerate).toArray();
    
    List<Integer> possibleAnswers = asList(ints);
    possibleAnswers.add(correctAnswerIndex);
    Collections.shuffle(possibleAnswers, new Random(System.nanoTime()));
    

    不工作

  2. # 2 楼答案

    我根据你的需要写了一个完整的程序。不过,请看看我在做什么。通过一点上下文,我创建了以下内容:

         // initialize a random object once.
         Random random = new Random();
         // the question
         String question = "With what letter does the name start of the new president of the USA?";
         // here are some basic answers
         String[] answers = new String[] {
          "a",
          "b",
          "c",
          "d",
          "e",
          "f",
          "g",
          "h",
          "i",
          "j",
          "k"
         };
         // you already know the correct index of the array above, in this case it's d
         int index = 3;
         // this array will contain four answers, including correct one!
         String[] four = new String[4];
         // get answer index, we will place correct value in that index
         int answerIndex = random.nextInt(four.length);
         // now lets pick 4 answers!
         for (int i = 0; i < four.length; i++) {
          // we are at the answer index!
          if (i == answerIndex) {
           four[i] = answers[index];
           continue;
          }
          int randomIndex = random.nextInt(answers.length);
          for (int j = 0; j < four.length; j++) {
           // we got duplicate here!
           if (answers[randomIndex].equals(four[j])) {
            randomIndex = random.nextInt(answers.length);
            // redo this current iteration
            j = j - 1;
           }
          }
          four[i] = answers[randomIndex];
         }
    

    输出:

    e, c, d, h
    g, d, d, h
    d, g, e, f
    d, f, b, i
    g, d, a, b
    c, d, g, b
    h, d, e, k
    e, f, d, c
    k, d, e, h
    i, d, e, d
    

    如果你解释一下你在哪里使用它,以及一个简短的演示你已经编写的代码,这将很有帮助

  3. # 3 楼答案

    这门课可以帮助你

    public class RandomQuiz {
    
        //The number of possible answers
        private int size;
        //The number of possible indexes
        private int n;
        //The correct index
        private int correct;
    
        //Constructor
        public RandomQuiz(int size, int n, int correct) {
            this.size = size;
            this.n = n;
            this.correct = correct;
        }
    
        //Returns size number of shuffled random indexes
        public int[] getRandomIndexes() {
            //The result set
            int[] result = new int[size];
            //We start with the correct index in the first place, so random values will be entered starting from the second place
            int index = 1;
            //First thing's first
            result[0] = correct;
            Random random;
            while (index < size) {
                //We always decrease the number of seeds
                random = new Random(n - index);
                //Getting a random value
                int randomized = random.nextInt();
                //Ensuring the numbers are not duplicate
                for (int i = 0; i < index; i++) if (randomized >= result[i]) randomized++;
                result[index++] = randomized;
            }
            //Randomize where correct will be at the end:
            random = new Random(size);
            int newIndex = random.getNextInt();
            //If the new index of correct is bigger than 0
            //than swap it with the item located on newIndex
            if (newIndex > 0) {
                result[0] = result[newIndex];
                result[newIndex] = correct;
            }
            return result;
        }
    }
    

    编辑:

    在与安东的私人聊天中,他告诉我有些部分不清楚,即:

    • 为什么我要减少种子的数量
    • 为什么我会在一个周期内增加randomized

    种子的数量减少了,因为我们最多可以使用一次任何数量的种子。如果种子为100,则在选择第一个项目后,它将变为99,依此类推。回答第二个问题:如果选择了45,然后选择了一个至少45的数字,那么我们需要在这个数字上加1,以应对选择45后留下的差距。如果选择了一些数字,并且我们选择了一个新的数字,那么我们需要在这个数字上加上它下面的空白数字,也就是说,已经选择的更小或相等的数字的数量来处理所有的空白

    请注意,没有什么是针对个人的,如果其他人的正确答案也被否决,我会留下我在这里留下的评论。我不反对我的答案被否决,但反对否决总体上正确的答案