How do I shuffle an array in TypeScript with the Fisher-Yates Shuffle?

892 Views Asked by At

I'm trying to code a quiz with TypeScript. The questions that are asked should be picked randomly and I'm using the Fisher-Yates Shuffle to do that – but it won't shuffle them.

What am I doing wrong? The Fisher-Yates Shuffle appears after the questions.

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();

1

There are 1 best solutions below

2
On

You did define a function const question = (Question: any) => { but you never called it!

Fix the variable names to not confuse everyone reading the code:

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;
}

Then, use it like

async function main() {
    shuffle(questions);
//  ^^^^^^^^^^^^^^^^^^^
    let correctAnswerCount = 0;
    for (const question of questions.slice(0, 5)) {
        console.log(question.questionText);
        …