I have to create 15 question where only 10 will be display randomly.(10 array over 15 array). I need to make sure that there is no duplication of array during the random process.
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]);
}
I'd take the array of questions, shuffle it, and then just take the first ten questions form it. Arrays in Java are extremely limited, though, and this would be much easier to do with a proper Collection
, e.g., an 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);
EDIT:
The usage of ArrayList
s and Collections
is just a convenience. The same logic should also stand with arrays, although it will require you to implement some of it yourself:
// 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];
}