Add new quiz generator

This commit is contained in:
Thomas A. Christensen II 2022-09-24 18:55:26 -05:00
parent 309d3e18a0
commit f1879cb843

View file

@ -3,8 +3,16 @@
<h1>MillironX's Anatomy Quiz Generator</h1>
<h2>Quiz material weighting</h2>
<div id="weights"></div>
<hr />
<div>
<label for="num-questions">Number of questions </label>
<input id="num-questions" type="number" value="15" />
</div>
<hr />
<button onClick="generate_quiz">Generate!</button>
<hr />
<h2>Quiz</h2>
<ul id="quiz-terms"></ul>
<code id="quiz"></code>
<script>
const BoldTerms = {
@ -143,6 +151,73 @@
weights_spinner_div.append(form_div);
}
// Shamelessly stolen from
// https://github.com/trekhleb/javascript-algorithms/blob/master/src/algorithms/statistics/weighted-random/weightedRandom.js
function weighted_random(items, weights) {
const cumulativeWeights = [];
for (let i = 0; i < weights.length; i += 1) {
cumulativeWeights[i] = weights[i] + (cumulativeWeights[i - 1] || 0);
}
const maxCumulativeWeight =
cumulativeWeights[cumulativeWeights.length - 1];
const randomNumber = maxCumulativeWeight * Math.random();
for (let itemIndex = 0; itemIndex < items.length; itemIndex += 1) {
if (cumulativeWeights[itemIndex] >= randomNumber) {
return items[itemIndex];
}
}
}
// Shamelessly stolen from
// https://stackoverflow.com/a/15106541
function random_child(object) {
const keys = Object.keys(object);
const i = Math.floor(Math.random() * keys.length);
return {
key: keys[i],
object: object[keys[i]],
};
}
const terms_list = document.getElementById("quiz-terms");
function generate_quiz() {
let weights = [];
let types = [];
for (structure_type in BoldTerms) {
weights.push(
parseInt(document.getElementById(`${structure_type}-weight`).value)
);
types.push(structure_type);
}
const num_questions = document.getElementById("num-questions").value;
for (let i = 0; i <= num_questions; i += 1) {
// Pick the random category
const structure_type = weighted_random(types, weights);
// Pick a random structure from that category
const rand_structure = random_child(BoldTerms[structure_type]);
// Get the list of questions for that structure
const questions = structure_question(
rand_structure.key,
rand_structure.object
);
// Get a random question from that list
const rand_question =
questions[Math.floor(Math.random() * questions.length)];
// Add that structure to the list
let term_item = document.createElement("li");
term_item.innerHTML = rand_question;
terms_list.appendChild(term_item);
}
}
const terms = [
"scapula: glenoid cavity",
"scapula: neck",
@ -481,13 +556,6 @@
"Iliopsoas"
];
const terms_list = document.getElementById("quiz-terms");
for (let i = 0; i < 10; i++) {
let rand_term = terms[Math.floor(Math.random()*terms.length)];
let term_item = document.createElement("li");
term_item.innerHTML = rand_term;
terms_list.appendChild(term_item);
}
generate_quiz();
</script>
</body>