~fkfd/hamrs

461bf6609bdbca0fccb0af3c4d205e246ad79a01 — Frederick Yin 5 months ago 49deda4
Move shuffle_options to poolfile
2 files changed, 20 insertions(+), 17 deletions(-)

M src/poolfile.rs
M src/quiz.rs
M src/poolfile.rs => src/poolfile.rs +20 -0
@@ 1,6 1,9 @@
use std::fs;

use json::JsonValue;
use rand::prelude::*;

use crate::util::*;

pub struct Question {
    pub id: String,


@@ 61,3 64,20 @@ pub fn correct_answer(question: &Question) -> &str {
        _ => "<cannot find correct answer>",
    }
}

// return clone of question where four options are shuffled
// and correct answer is adjusted accordingly
pub fn shuffle_options(question: &Question) -> Question {
    // map ABCD to a random permutation
    let mut rng = thread_rng();
    let mut mapping: Vec<usize> = vec![0, 1, 2, 3];
    mapping.shuffle(&mut rng);

    let options = vec!['A', 'B', 'C', 'D'];
    Question {
        id: question.id.clone(),
        question: question.question.clone(),
        options: Vec::from_iter(mapping.iter().map(|i| question.options[*i].clone())),
        correct: options[mapping[abcd_to_1234(question.correct)]],
    }
}

M src/quiz.rs => src/quiz.rs +0 -17
@@ 116,20 116,3 @@ fn ask_question(question: &Question) -> Answer {
        }
    }
}

// return clone of question where four options are shuffled
// and correct answer is adjusted accordingly
fn shuffle_options(question: &Question) -> Question {
    // map ABCD to a random permutation
    let mut rng = thread_rng();
    let mut mapping: Vec<usize> = vec![0, 1, 2, 3];
    mapping.shuffle(&mut rng);

    let options = vec!['A', 'B', 'C', 'D'];
    Question {
        id: question.id.clone(),
        question: question.question.clone(),
        options: Vec::from_iter(mapping.iter().map(|i| question.options[*i].clone())),
        correct: options[mapping[abcd_to_1234(question.correct)]],
    }
}