简体   繁体   中英

How do I integrate the random number generator code to randomize the questions in my coding?

I am using VS code and Android Studio for the virtual device. From the random number generated, I would like to make it match with the quiz.id, quiz.question and quiz.answer and display it.

For the random number generator code, I took it from online. The following code looks like this.

This is the script.js file.

let output = document.querySelector('h1');


function getRandomNumber(min, max) {
    let step1 = max - min + 1;
    let step2 = Math.random() * step1;
    let result = Math.floor(step2) + min;
    return result;
}

function createArrayOfNumbers(start, end){
    let myArray = [];

    for(let i = start; i<= end; i++){
        myArray.push(i);
    }

    return myArray;
}

let numbersArray = createArrayOfNumbers(1,3);

btn.addEventListener('click', () => {
    if(numbersArray.length == 0){
        output.innerText = 'No more random numbers';
        return;
    }
    let randomIndex = getRandomNumber(0,numbersArray.length-1);
    let randomNumber= numbersArray[randomIndex];
    numbersArray.splice(randomIndex, 1);
    output.innerText = randomNumber;
});

This is the index.html file.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button>Generate</button>
    <h1 style="text-align: center;"></h1>
    <script src="script.js"></script>
</body>
</html>

For my code, it looks like this.

import { StyleSheet, SafeAreaView, View, Text, TouchableOpacity, Alert } from 'react-native';
import { ScrollView } from 'react-native-gesture-handler';
import CheckBox from '@react-native-community/checkbox';
import { DetailsHeader, DetailsImage, DetailsParagraph } from "../Components/DetailsComponents";
import RadioButton from '../Components/RadioButton';
import {QuizArray} from '../Data/Questions';


const DetailsScreen = ({ route }) => {
    const [checked, setChecked] = useState(-1); //checked index of the answer
    const [quizNum, setQuizNum] = useState(0);  //the number of the current quiz in the array
    const [score, setScore] = useState(0);      //score result


    const props = route.params;
    const body = props.body.map((item,i) => {
        switch (item.type) {
            case "img":
                return <DetailsImage key={i} content={item.content} />;
            case "h1":
                return <DetailsHeader key={i} content={item.content} />;
            case "p":
                return <DetailsParagraph key={i} content={item.content} />;
                case "rbtn":
                    console.log(item.content)
                    console.log(item.ans)
                    return <RadioButton id="test" PROP={item.content} ans = {item.ans}  />;
        
        }
    });

    const showQuiz = (quiz) => {
        return (
            <View style={styles.quizview}>
                <Text style={styles.quiz_title}>
                    {quiz.id + '. ' + quiz.question}
                </Text>
                
                {quiz.answers.map((item, i) => {
                    return (
                        <View key={i} style={styles.quiz_cell}>
                            <CheckBox
                                disabled={false}
                                value={i === checked ? true : false}
                                onValueChange={
                                    //if newValue is true, i-the answer will be selected.
                                    (newValue) => newValue ? setChecked(i) : setChecked(-1)
                                }
                            />
                            <Text style={styles.quiz_answer}>{item}</Text>
                        </View>
                    );
                })}
            </View>
        );
    }

    const canShowNextQuiz = (quizNum < QuizArray.length) ? true : false;

    const onNext = () => {
        if (checked === -1) {
            //if user haven't selected any answer, will show alert dialog
            Alert.alert('Error', 'Please select one answer!');
            return;
        }
        //set <checked> variable as -1(nothing selected)
        setChecked(-1);

        
        const curr_quiz = QuizArray[quizNum]; //current question's information
        if (curr_quiz.correct_answer === curr_quiz.answers[checked]) {
            //if user selected the correct answer, the score will be increased by one
            setScore(score+1);
            console.log('current score:', score + 1);
        }
        else {
            console.log('current score:', score + 1);
        }

        //set <checked> variable as -1(nothing selected)
        setChecked(-1);



        if (canShowNextQuiz)
        {
            //if quizNum is small than the length of QuizArray, move to next quiz
            setQuizNum(quizNum + 1);
        }
    }

    const onRestart = () => {
        setChecked(-1);
        setQuizNum(0);
        setScore(0);

    }
    return (

        <SafeAreaView style={styles.safeArea}>
            <ScrollView>
                <View style={styles.header}>
                    <Text style={styles.title}>{props.title}</Text>
                    <Text style={styles.subtitle}>{props.subtitle}</Text>
                </View>
                
                {body}
                
                {canShowNextQuiz ?
                    <View>
                        {showQuiz(QuizArray[quizNum])}

                        <TouchableOpacity 
                            onPress={onNext} 
                            style={styles.nextbutton}>
                                <Text style={styles.button_text}>Next</Text>
                        </TouchableOpacity>
                    </View>
                    :
                    <View>
                        <Text style={styles.result_text}>The Quiz is over</Text>
                        <Text style={styles.result_text}>{'Your score is ' + score}</Text>
                        <TouchableOpacity 
                            onPress={onRestart} 
                            style={styles.nextbutton}>
                                <Text style={styles.button_text}>Restart</Text>
                        </TouchableOpacity>
                    </View>
                }
            </ScrollView>
        </SafeAreaView>
    )
};

const styles = StyleSheet.create({
    header: {
        marginVertical: 24,
    },

    imageWrapper: {
        height: 150,
        marginHorizontal: 40,
        marginTop: 24,
        borderRadius: 8,
        overflow: "hidden",
    },

    thumbnail: {
        flex: 1,
        width: null,
        height: null,
        backgroundColor: "lightgray"
    },

    title: {
        marginHorizontal: 24,
        marginBottom: 8,
        fontSize: 40,
        fontWeight: "bold",
    },

    subtitle: {
        marginHorizontal: 24,
        fontSize: 20,
        fontStyle: "italic",
        opacity: 0.5,
        marginBottom: -20,
    },

    quizview: {
        padding: 20,
    },
    quiz_title: {
        fontSize: 30,
        fontWeight: 'bold',
        paddingBottom: 20,
    },
    quiz_cell: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    quiz_answer: {
        fontSize: 20,
    },
    nextbutton: {
        height: 40,
        width: 250,
        alignItems: 'center',
        justifyContent: 'center',
        alignSelf: 'center',
        backgroundColor: 'green',
        borderRadius: 5,
    },
    button_text: {
        color: 'white',
    },
    result_text: {
        fontSize: 30,
        margin: 20,
        alignItems:'right',
    }
});

export default DetailsScreen;

This is the question.js file.

export const QuizArray = [
    {
        id: 1, 
        question: 'Which of these factors that contribute to stroke?',
        answers: ['High blood cholesterol', 'Smoking', 'Old Age', 'All of the above'],
        correct_answer: 'All of the above',
    },
    {
        id: 2, 
        question: 'Ischaemic Stroke is when blood clots occur in the brain?',
        answers: ['TRUE', 'FALSE'],
        correct_answer: 'TRUE',
    },

    {
        id: 3, 
        question: 'Which of the following are possible symptoms of stroke?',
        answers: ['Weakness in facial muscles', 'Vision impairment', 'Slurring of speech', 'All of the above'],
        correct_answer: 'All of the above',
    },
    
]

您需要编辑该前缀及其作品

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM