没有重复的随机数组
Random arrays with no repetition
我必须创建 15 个问题,其中只有 10 个随机显示。(10 个数组超过 15 个数组)。我需要确保在随机过程中没有重复数组。
public static void main(String() args){
String question_1 = question_One();
//to question 15
String question_15 = question_fifteen();
String [] question = new String [14];
question[0] = question_1;
question[1] = question_2;
//to question 15
question[14] = question_15;
int random = (int) (Math.random()*11);
System.out.print(question[random]);
}
我会采用一系列问题,将其打乱,然后只采用前十个问题。但是,Java 中的数组非常有限,使用适当的 Collection
会容易得多,例如 ArrayList
:
// Build the question list:
List<String> questions = new ArrayList<>(15);
questions.add(question_1);
questions.add(question_2);
// etc...
// Shuffle it:
Collections.shuffle(questions);
// Ask the first ten:
List<String> questionsToAsk = questions.subList(0, 10);
编辑:
ArrayList
s 和 Collections
的使用只是为了方便。同样的逻辑也适用于数组,尽管它需要你自己实现其中的一些:
// Build the question list:
String[] questions = new String[15];
questions[0] = question_1;
questions[1] = question_2;
// etc...
// Shuffle the first 10 elements.
// Although the elements can be taken from indexes above 10,
// there no need to continue shuffling these indexes.
Random r = new Random();
for (int i = 0; i < 10; ++i) {
int swapIndex = r.nextInt(15 - i) + i;
String temp = questions[i];
questions[i] = questions[swapIndex];
questions[swapIndex] = temp;
// Ask the first ten:
String[] questionsToAsk = new String[10];
for (int i = 0; i < 10; ++i) {
questionsToAsk[i] = questions[i];
}
我必须创建 15 个问题,其中只有 10 个随机显示。(10 个数组超过 15 个数组)。我需要确保在随机过程中没有重复数组。
public static void main(String() args){
String question_1 = question_One();
//to question 15
String question_15 = question_fifteen();
String [] question = new String [14];
question[0] = question_1;
question[1] = question_2;
//to question 15
question[14] = question_15;
int random = (int) (Math.random()*11);
System.out.print(question[random]);
}
我会采用一系列问题,将其打乱,然后只采用前十个问题。但是,Java 中的数组非常有限,使用适当的 Collection
会容易得多,例如 ArrayList
:
// Build the question list:
List<String> questions = new ArrayList<>(15);
questions.add(question_1);
questions.add(question_2);
// etc...
// Shuffle it:
Collections.shuffle(questions);
// Ask the first ten:
List<String> questionsToAsk = questions.subList(0, 10);
编辑:
ArrayList
s 和 Collections
的使用只是为了方便。同样的逻辑也适用于数组,尽管它需要你自己实现其中的一些:
// Build the question list:
String[] questions = new String[15];
questions[0] = question_1;
questions[1] = question_2;
// etc...
// Shuffle the first 10 elements.
// Although the elements can be taken from indexes above 10,
// there no need to continue shuffling these indexes.
Random r = new Random();
for (int i = 0; i < 10; ++i) {
int swapIndex = r.nextInt(15 - i) + i;
String temp = questions[i];
questions[i] = questions[swapIndex];
questions[swapIndex] = temp;
// Ask the first ten:
String[] questionsToAsk = new String[10];
for (int i = 0; i < 10; ++i) {
questionsToAsk[i] = questions[i];
}