I am having a problem with the Quiz part of my Application. I need a 100 question per category, but I just need to display 20 question to be answer by the user. That 100 question used to randomize the questions to have different questions to display. How do i limit the question?
You can create an int. Every time you open a random question you set your int + 1. And if your int is 20, you stop opening a new question.
I'm not sure exactly what you're asking, but:
Let's assume you have a Java/Android "Quiz" app, and you want to randomly select and display 20 questions from a list of 100.
Let's also assume that your 100 questions are stored in a Java "List<>".
Finally, let's assume you have a "Question" class that contains both the question and the corresponding answer.
Then one possible solution might be:
// Fetch 20 random questions
List<Question> selectedQuestions = new ArrayList<Question>();
Random random = new Random();
for (int i=0; i < 20; i++) {
int idx = random.nextInt(questionsList.size());
selectedQuestions.add( questionsList.get(idx));
}
// Display these questions
return selectedQuestions;
Related
I have a little question concerning the usage of
Android Resouce by ID / Change image onClick / no change of imageView
I have established my images picked randomly here, using:
#Override
public void onClick(View v) {
Log.d("MYAPP", "Like-Button clicked");
/*imageViewMeasurement.setImageResource(R.drawable.p13);*/
TypedArray images = getResources().obtainTypedArray(R.array.images_primes);
int chosenImageNumber = (int) (Math.random() * images.length());
// setImageResource to the random chosenImageNumber
imageViewMeasurement.setImageResource(images.getResourceId(chosenImageNumber, R.color.colorPrimaryDark));
images.recycle();
// Confirmation if the random generator picked a Number from the array
String chosenImageNumberTest = String.valueOf(chosenImageNumber);
Log.d("MYAPP Choice Number", chosenImageNumberTest);
}
This runs through an array of 40 images and will be repeated one time. So every image will be shown two times (?).
That's the question:
When I use a pool of 40 images randomly for 80 picks, do I get every image two times (draw with cover), or is every try a new random out of those 40 images (draw without replacement), so the reult could be number 1 for 4 times and number 38 for 0 times? Is there an other function that prevents to such a behaviour?
Best,
tigercode
As I understand your code, you would NOT get every image twice, you would get some images multiple times and some images might not even come at all.
Don't use Random if you don't actually want Random. By the laws of probability you'd only have a chance of getting the same image twice, not a certainty.
You could use a boolean array to keep track of which numbers have already been used (if index n is true this means the number has already been taken e.g.).
Edit: The comment below from vims liu is right. It's much more efficient run time wise to define a list of indexes and shuffle the list.
So better use the following solutions, even if it won't make a big differences considering your numbers are quite small.
List<Integer> indexes = Arrays.asList(1,2,3,4,5,6,7,8,9,10); //...
Collections.shuffle(indexes);
You can then iterate through the indexes list and use the current number as current index.
Sorry for answering late, and sorry for a beginner question, I'm new to android developing.
I changed my code (and write my comment what I understood it does:
#Override
public void onClick(View v)
Log.d("MYAPP", "Like-Button clicked");
// 1. Get the array of images in the images_primes XML-List AS int (number of every image in array)
TypedArray images = getResources().obtainTypedArray(R.array.images_primes);
// 2. Takes an array-list and shuffles it
List<Integer> indexes = Arrays.asList(1,2,3,4,5,6,7,8,9,10); //...
Collections.shuffle(indexes);
// Great, it shuffles! ;-)
Log.d("MYAPP", indexes);
// 3. takes the number from the shuffled image list
int chosenImageNumber = (int) (indexes);
// 2. Old code: picks a number out of the image array from 1. / commented out
//int chosenImageNumber = (int) (Math.random() * images.length());
// 4. setImageResource to the random chosenImageNumber
imageViewMeasurement.setImageResource(images.getResourceId(chosenImageNumber, R.color.colorPrimaryDark));
images.recycle();
// Confirmation if the random generator picked a Number from the array
String chosenImageNumberTest = String.valueOf(chosenImageNumber);
Log.d("MYAPP Choice Number", chosenImageNumberTest);
}
Step 1: Open the list of images (as items), use it as array (1,2,3)
Step 2: Have a second number of arrays (possible to connect 1 and 2), SHUFFLE! :-)
Step 3: Here is my problem. If I got that right, I get a string-list from step 2, which numbers I can't use as Int (Error "Integer to int" won't work) -> result should be a number (?)
Step 4: Number from 3 should be used to pick out an image from list / array from 1.
I think, there is a thinking error on my side.
Thanks for your help in advance,
tigercode
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Both of the codes below give me the same exact answers. I was just wondering which would be better programming practice for readability and maintainability. Would less lines of code be best? Would one affect the functionality of the program more than the other? any suggestions would be very much appreciated as I just want to learn the best practices for programming.
Here are the codes:
for (int i = 0; i < db.getAllDecks().size(); i++)
{
String CardCount = String.format("(%s)",db.getCardsForDeck(i+1).size());
adapter2.add(db.getAllDecks().get(i).getDeck_name());
adapter3.add(CardCount);
}
or
for (Deck deck: deckList) {
String deckName = deck.getDeck_name();
adapter2.add(deckName);
int count = db.getCardIds(deck).length;
String strCount = Integer.toString(count);
adapter3.add(strCount);
}
Overall, I think the second code is clearer, and more readable.
It contains moe variable names that is able to tell what exactly it is used for, such as deckName, count and strCount. I can clearly see that you are getting every deck's name and card count and put them in different (list?) adapters.
For the first one, I apparently needed more time to comprehend what it is doing. So IMO, the second one!
Also if you could just rename getDeck_name to getDeckName that would be better for people to read. getDeckName follows the naming convention for naming Java methods i.e. camelCase.
if you want to get data from simple list thnn foreach loop is good to use but,,, if you want to data from exact position or to store from id than for-loop is better ..
and there is NO difference by performance wise both are same as well, as i know.
as my suggestion use for loop :)
As per this book Code Complete - Steve McConnell's
for loop is good choice when you need a loop that executes a specified number of times.
foreach loop is useful for performing an operation on each member of an array or the container.
for more visit : Google books - Code Complete
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I just wanna ask for help in getting the index of the given values inside the arraylist. For example I have
arraylist brand contains {"a","b","c","d","e"}
and another
arraylist chosen contains {"a","c","e"}
how will I know the index of the values in arraylist chosen in arraylist brands? Thank you.
I have tried
for (int j=0; j<checkSelected.length; j++)
{
for (int i = 0; i < Brands.size(); i++)
{
checkSelected[i] = true;
}
}
What I am trying to do is to get the index of my values in my chosen arraylist to to the arraylist brand so that will be easy to set the value of that index in true in the other arraylist. But in my code above it only gets the size of the of my arraylist.
Just iterate over chosen and get every index.
for(String chosenElement : chosen) {
int index = brand.indexOf(chosenElement);
// Do something with the index
}
This works not only with lists of String but with every type where equals() is properly overwritten.
Iterate over the 'chosen' list and use indexOf(Object) for each object.
there are methodes indexOf and contains. Check them out
I'm creating a simple quiz game. In this game, the question and the respective answers will be randomly generated. I created a list "q" to the questions.
And for the answers, I created various lists with 4 strings each one. For example, if the question is the 0 in the q list, the answers for this questions will be in the list "a0", right? But I'm having some problem to get the strings in the list of answers. I've tried this:
while(true){
Integer nxt = rng.nextInt(6);
if (!generated.contains(nxt))
{
generated.add(nxt);
textView1.setText(((ArrayList<String>) q).get(nxt));
String x;
x = ("a" +nxt);
Collections.shuffle((x));
btn1.setText(((ArrayList<String>) x).get(0));
btn2.setText(((ArrayList<String>) x).get(1));
btn3.setText(((ArrayList<String>) x).get(2));
btn4.setText(((ArrayList<String>) x).get(3));
break;
}
}
I created a string "x" to get the right list. If the "nxt" is 4, the buttons texts will get the strings in the list a4.
But in my code, the "Collections.shuffle" and the "setText" try to find the list "x". It's not going in the way I imagined.
How can I fix it?
*My idea is check the string of the button clicked and compare with another list of RIGHT answers. In that way, I can attributte the right answer and the other 3 wrong.
I made a similar quiz app (King of Math) a few days ago.
Calculate the correct answers
Add the correct answer to your answers-list
Calculate fake answers, add them to the answers-list
Shuffle the list
Get the id of the correct answer. It is in the range [0, max_answers)
If an answer has been selected, you check if the selected id (0, 1, 2, 3) is the one of the correct answer. If it is, the user picked the right one, otherwise he didn't.
PS: sorry for the self-promotion.
I would be surprised if this code would compile and/or run correctly at all. You are trying to use the content of a String as an variable name, cast that variable to an ArrayList<String> and then to access the elements. This is wrong on so many levels that you should consider doing a few Java tutorials again.
If you do or feel that you can continue anyways, try this approach: You shouldn't store the questions and answers in a separate list, but together in a class.
class Question
{
//...
// maybe id and other stuff belonging to a question
//...
String questionText;
// separate because you need to tell the correct answer apart from the wrong ones later
// you could also just always use the first one in a set of answers.
String correctAnswerText;
ArrayList<String> wrongAnswerTexts;
}
Then you can store your questions in an ArrayList<Question> in your app and set an answer as follows:
//...
// set up ArrayList<Question> questions here
//...
int nxt = rng.nextInt(6);
//...
// make sure your list is actually long enough for the generated index
//...
Question nextQuestion = questions.get(nxt);
//...
// make sure the retrieved object is valid
//...
// set the question text to nextQuestion.questionText;
//...
ArrayList<String> allAnswers = new ArrayList<String>();
allAnswers.add(nextQuestion.correctAnswerText);
allAnswers.addAll(nextQuestion.wrongAnswerTexts);
Collections.shuffle(allAnswers);
btn1.setText(allAnswers.get(0));
btn2.setText(allAnswers.get(1));
btn3.setText(allAnswers.get(2));
btn4.setText(allAnswers.get(3));
I am developing an application which involves a quiz in it. I have used a viewflipper for displaying question, as i press the next button it flips to next question. However, I wish to display these questions randomly. I have parsed an xml and displayed the questions n its options !
Assuming that all your questions stored in array or some data structure e.g. ArrayList
You need to define a single random object only once in your activity
e.g.
Random random = new Random();
Get the next question index:
int nextQuestionIndex = random.nextInt(n); // where n is the total number of questions