0

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]);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Yogesh M
  • 43
  • 2
  • 9
  • 2
    Hint: if you don't want any repetition, you're really shuffling. Look at `Arrays.asList` and `Collections.shuffle`. – Jon Skeet May 17 '15 at 07:32

1 Answers1

3

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 ArrayLists 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];
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Is there any way to do without arraylist, becuase i have not learn that. – Yogesh M May 17 '15 at 09:18
  • Is there any way to do without arraylist, because i have not learn that. i need to apply thing that i learn, such as Math.random etc.. – Yogesh M May 17 '15 at 09:24