1

我正在尝试使用 TypeScript 编写测验。提出的问题应该随机挑选,我正在使用 Fisher-Yates Shuffle 来做到这一点——但它不会随机选择它们。

我究竟做错了什么?Fisher-Yates Shuffle 出现在问题之后。

interface Question {
    questionText: string;
    answers: [string, string, string, string],
    correctAnswerIndex: number
}
const questions: Question[] = [
    {
        questionText: 'Wie viele Lichtminuten ist die Sonne weg?',
        answers: ['1', '3', '6', '8'],
        correctAnswerIndex: 3
    }
   ]
const question = (Question: any) => {
    for (let i = Question.length -1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        const temp = Question[i];
        Question[i] = Question[j];
        Question[j] = temp;
    }
    return Question;
    };


const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
rl.on("close", function () {
    console.log("\nBYE BYE !!!");
    process.exit(0);
});
const askQuestion = (question: string) => new Promise<string>(resolve => rl.question(question, resolve));


async function main() {
    let correctAnswerCount=0;
    for (const question of questions.slice(0, 5)) {
        console.log(question.questionText);
        let i = 0;
        for (const answer of question.answers) {
            console.log(String.fromCharCode(97 + i) + ') ' + answer);
            i++;
        }
        
        const answer = await askQuestion("Richtige Antwort hier eingeben: ");
        if (answer === String.fromCharCode(97 + question.correctAnswerIndex)) {
            correctAnswerCount++;
            console.log('Richtig ')
           }
           
        else {
            console.log('Falsch ;(')
        }
        console.log("\n\n")
        
    }
    console.log('Score: '+ correctAnswerCount*1000000);
    rl.close()
    
}
main();

4

1 回答 1

-1

您确实定义了一个函数const question = (Question: any) => {,但您从未调用它!

修复变量名称,以免混淆阅读代码的每个人:

function shuffle<T>(arr: T[]): T[] {
    for (let i = arr.length -1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        const temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    return arr;
}

然后,像这样使用它

async function main() {
    shuffle(questions);
//  ^^^^^^^^^^^^^^^^^^^
    let correctAnswerCount = 0;
    for (const question of questions.slice(0, 5)) {
        console.log(question.questionText);
        …
于 2021-02-02T17:33:47.197 回答