Powtórne losowanie pytań z listy bez powtórzeń.

0

Witam,
W oparciu o poradniki internetowe stworzyłem taką o to aplikację Quizu:

Moje pytanie brzmi: jak dodać do takiej aplikacji losowanie pytań w następujący sposób:

-Pobranie np. 5 pytań z listy 100 dostępnych (bez powtórzeń)
-Przy poprawnej odpowiedzi przejście do kolejnego pytania
-Przy błędnej odpowiedzi powrót do pytania pierwszego i ponowne wyświetlenie TYCH SAMYCH pytań.

QuizActivity.java


package com.codinginflow.b_quiz;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.BoringLayout;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Random;

public class QuizActivity extends AppCompatActivity {



    private QuestionLibrary mQuestionLibrary = new QuestionLibrary();

    private TextView mScoreView;
    private TextView mQuestionView;
    private Button mButtonChoice1;
    private Button mButtonChoice2;
    private TextView countdownText;
    private Button countdownButton;

    private CountDownTimer countDownTimer;
    private long timeLeftInMilliseconds = 150000;
    private boolean timerRunning;


    private String mAnswer;
    private int mScore = 0;
    private int mQuestionNumber = 0;

    private int mQuestionLenght = mQuestionLibrary.mQuestions.length;
    Random r;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);

        countdownText = findViewById(R.id.countdown_text);
        countdownButton = findViewById(R.id.countdown_button);

        countdownButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startStop();
            }
        });

        r = new Random();

        mScoreView = (TextView)findViewById(R.id.score);
        mQuestionView = (TextView)findViewById(R.id.question);
        mButtonChoice1 = (Button)findViewById(R.id.choice1);
        mButtonChoice2 = (Button)findViewById(R.id.choice2);


        updateQuestion(r.nextInt(mQuestionLenght));



        //Start of Button Listener for Button1
        mButtonChoice1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                //My logic for Button goes in here

                if (mButtonChoice1.getText() == mAnswer){
                    mScore = mScore + 1;
                    updateScore(mScore);
                    updateQuestion(r.nextInt(mQuestionLenght));
                    //This line of code is optiona
                    Toast.makeText(QuizActivity.this, "DOBRZE", Toast.LENGTH_SHORT).show();

                }else {
                    Toast.makeText(QuizActivity.this, "ŹLE", Toast.LENGTH_SHORT).show();
                    updateQuestion(r.nextInt(mQuestionLenght));
                }
            }
        });

        //End of Button Listener for Button1

        //Start of Button Listener for Button2
        mButtonChoice2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                //My logic for Button goes in here

                if (mButtonChoice2.getText() == mAnswer){
                    mScore = mScore + 1;
                    updateScore(mScore);
                    updateQuestion(r.nextInt(mQuestionLenght));
                    //This line of code is optiona
                    Toast.makeText(QuizActivity.this, "DOBRZE", Toast.LENGTH_SHORT).show();

                }else {
                    Toast.makeText(QuizActivity.this, "ŹLE", Toast.LENGTH_SHORT).show();
                    updateQuestion(r.nextInt(mQuestionLenght));
                }
            }
        });

        //End of Button Listener for Button2



    }

    private void updateQuestion(int num){
        mQuestionView.setText(mQuestionLibrary.getQuestion(num));
        mButtonChoice1.setText(mQuestionLibrary.getChoice1(num));
        mButtonChoice2.setText(mQuestionLibrary.getChoice2(num));

        mAnswer = mQuestionLibrary.getCorrectAnswer(num);
        mQuestionNumber++;
    }


    private void updateScore(int point) {
        mScoreView.setText("" + mScore);
    }

    public void startStop(){
        if (timerRunning){
            stopTimer();
        }
        else{
            startTimer();
        }
    }

    public void startTimer() {
        countDownTimer = new CountDownTimer(timeLeftInMilliseconds, 1000) {
            @Override
            public void onTick(long l) {
                timeLeftInMilliseconds = l;
                updateTimer();
            }

            @Override
            public void onFinish() {

            }
        }.start();
        countdownButton.setText("PAUZA");
        timerRunning = true;
    }

    public void stopTimer(){
        countDownTimer.cancel();
        countdownButton.setText("START");
        timerRunning = false;

    }

    public void updateTimer(){
        int minutes = (int)timeLeftInMilliseconds / 60000;
        int seconds = (int)timeLeftInMilliseconds % 60000 / 1000;

        String timeLeftText;

        timeLeftText = "" + minutes;
        timeLeftText += ":";
        if (seconds < 10) timeLeftText += "0";
        timeLeftText += seconds;

        countdownText.setText(timeLeftText);
    }
}

**
QuestionLibrary.java**

package com.codinginflow.b_quiz;

public class QuestionLibrary {

    public String mQuestions [] = {
            "Bratobójcą czy królobójcą, Jaime Lannister NIE był?",
            "Azot czy fosfor, w powietrzu znajdziesz?",
            "Piotr czy Paweł, kto stoi przy bramie do nieba?",
            "Żółty czy niebieski, do którego kosza wrzucisz papier?",
            "Schodami czy windą, do nieba zabiorą mnie?",
            "Długopisu czy ołówka, gumką nie zmażesz?",
            "Łódź czy żółć, więcej polskich znaków zawiera słowo?",
            "Kofeiny czy kokainy, czego nie ma w kawie?",
            "Piątek czy sobota, szósty dzień tygodnia to?"
    };


    private String mChoices [][] = {
            {"Bratobójcą", "Królobójcą"},
            {"Azot", "Fosfor"},
            {"Piotr", "Paweł"},
            {"Żółty", "Niebieski"},
            {"Schodami", "Windą"},
            {"Długopisu", "Ołówka"},
            {"Łódź", "Żółć"},
            {"Kofeiny", "Kokainy"},
            {"Piątek", "Sobota"}
    };



    private String mCorrectAnswers[] = {"Królobójcą", "Fosfor", "Paweł", "Żółty","Schodami","Ołówka","Łódź","Kofeiny","Piątek"};




    public String getQuestion(int a) {
        String question = mQuestions[a];
        return question;
    }


    public String getChoice1(int a) {
        String choice0 = mChoices[a][0];
        return choice0;
    }


    public String getChoice2(int a) {
        String choice1 = mChoices[a][1];
        return choice1;
    }


    public String getCorrectAnswer(int a) {
        String answer = mCorrectAnswers[a];
        return answer;
    }

}

activity_quiz.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_quiz"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.codinginflow.b_quiz.QuizActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:layout_marginBottom="40dp">

        <TextView
            android:id="@+id/score_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:text="Wynik"
            android:textSize="20sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/score"
            android:layout_alignParentRight="true"
            android:text="0"
            android:textSize="20sp"/>

    </RelativeLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:text="Which thing is alive?"
        android:textSize="20sp"
        android:padding="8dp"
        android:layout_marginBottom="40dp"
        android:id="@+id/question"/>


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="bird"
        android:background="#0091EA"
        android:textColor="#fff"
        android:padding="8dp"
        android:layout_marginBottom="24dp"
        android:id="@+id/choice1"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="door"
        android:background="#0091EA"
        android:textColor="#fff"
        android:padding="8dp"
        android:layout_marginBottom="24dp"
        android:id="@+id/choice2"/>


    <TextView
        android:id="@+id/countdown_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_alignParentEnd="true"
        android:text="02:30"
        android:textColor="@android:color/black"
        android:textSize="40sp" />

    <Button
        android:id="@+id/countdown_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="24dp"
        android:layout_marginLeft="16dp"
        android:background="#B71C1C"
        android:padding="8dp"
        android:text="START"
        android:textColor="#fff" />

</LinearLayout>

P.S Dodam tylko, że nie jestem programistą ani nawet studentem informatyki, więc prosiłbym o w miarę łopatologiczne rozwiązanie :D Chciałbym stworzyć ten quiz żeby pograć ze znajomymi :D

0

Możesz w środku metody losującej, skopiować listę pytań i z niej (skopiowanej) wylosować pięć, usuwając każdy po losowaniu i zwrócić, np. jako listę. W Random jest nextInt:

        Random rn = new Random();
        int index = rn.nextInt(lst.size());

PS Pytania Masz boskie:-)

0

@lion137
Edit: teraz zrozumiałem o co chodzi z pytaniami, dzięki :D

Dzięki za rozwiązanie, przetestuję :)

0

"Chyba jednak nie rozumiem tego rozwiązania" Po prostu, topornie Losujesz i Usuwasz elementy, Używaj ArrayList zamiast tablic, dużo wygodniej:

import java.util.ArrayList;
import java.util.Random;

public class Example {

    public static ArrayList<String> questions(ArrayList<String> lst) {
        ArrayList<String> newLst = new ArrayList<String>(lst);
        ArrayList<String> output = new ArrayList<>();
        Random rn = new Random();
        int index;
        for (int i = 0; i < 5; i++) {
            index = rn.nextInt(newLst.size());
            output.add(newLst.get(index));
            newLst.remove(index);
        }
        return output;
    }

    public static void main(String [] args) {

        ArrayList<String> lst  = new ArrayList<>();
        lst.add("quest1");
        lst.add("quest2");
        lst.add("quest3");
        lst.add("quest4");
        lst.add("quest5");
        lst.add("quest6");
        lst.add("quest7");
        lst.add("quest8");
        System.out.println(questions(lst));
    }
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1