Reputation: 25
I have a String[] array of 300+ questions. When I start my "Test Activity" it creates a test with the "whole" lenght of the array (300). However, I would like to use only 115 questions (randomly) from that array. Is this possible to do?
This is my loop code, which I assume is the responsible for the quantity of questions used.?
//This is my FOR Loop
public void shuffleChapterRandomTest() {
shuffledPositionChapterRandomTest = new String[chapterRandomTestQuestions.length];
for (int k = 0; k < shuffledPositionChapterRandomTest.length; k++) {
shuffledPositionChapterRandomTest[k] = String.valueOf(k);
}
Collections.shuffle(Arrays.asList(shuffledPositionChapterRandomTest));
Log.i("TAG", "shuffle: " + shuffledPositionChapterRandomTest[0] + " " + shuffledPositionChapterRandomTest[1]);
}
Upvotes: 1
Views: 64
Reputation: 9919
You're almost there, but I think all your shuffled array does is hold a String value of an index, rather than the question. It can be simplified if chapterRandomTestQuestions
is that array of string questions.
Create a random list of Strings
from the array and return the shuffled questions that can be iterated over as necessary :
public List<String> shuffleChapterRandomTest() {
final List<String> randomQuestions = Arrays.asList(chapterRandomTestQuestions);
Collections.shuffle(randomQuestions);
return randomQuestions.subList(0, 115);
}
This assumes there are greater than 115 items in the list, so a little unsafe (you could return randomQuestions.subList(0, Math.min(chapterRandomTestQuestions.length, 115))
to stop this issue), otherwise it will throw an IndexOutOfBoundsException
Upvotes: 1