Last active
June 23, 2022 21:58
-
-
Save Yamo93/73670cf13c00a76009b74442cdfc4b01 to your computer and use it in GitHub Desktop.
A class which can generate all possible combinations for a question with x true/false statements. For example, a question with 5 true/false statements can have 2^5 (32) possible combinations.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AnswerGenerator { | |
combinations = []; | |
combinationNumber = -1; | |
generateCombinations(numOfStatements = 5) { | |
const combinations = []; | |
const numOfPossibleCombinations = 2 ** numOfStatements; | |
for (let i = 0; i < numOfPossibleCombinations; i++) { | |
// for every number, convert it to binary | |
const binary = i.toString(2); // 16 => 10000 | |
const padded = binary.padStart(numOfStatements, '0'); // 0 => 00000 | |
const combination = []; | |
for (let j = 0; j < numOfStatements; j++) { | |
if (padded[j] === '1') { | |
combination.push(true); | |
} else { | |
combination.push(false); | |
} | |
} | |
combinations.push(combination); | |
} | |
this.combinations = combinations; | |
return combinations; | |
} | |
fillFormWithCombination() { | |
if (!this.combinations.length) { | |
throw new Error('Combinations must be generated first.'); | |
} | |
// look in local storage after combination number | |
let combinationNumber = localStorage.getItem('combinationNumber'); | |
if (combinationNumber) { | |
// parse into integer | |
combinationNumber = parseInt(combinationNumber, 10); | |
} | |
if (!combinationNumber || combinationNumber < 0) { | |
// if it is was not set, or set to -1, set it to 0 | |
combinationNumber = 0; | |
} | |
this.combinationNumber = combinationNumber; | |
const combination = this.combinations[combinationNumber]; | |
const checkboxes = document.querySelectorAll('input[type=checkbox]'); | |
for (let i = 0; i < combination.length; i++) { | |
checkboxes[i].checked = combination[i]; | |
} | |
this.combinationNumber++; | |
localStorage.setItem('combinationNumber', this.combinationNumber.toString()); | |
} | |
resetCombinationNumber() { | |
this.combinationNumber = -1; | |
localStorage.setItem('combinationNumber', -1); | |
} | |
} | |
const answerGenerator = new AnswerGenerator(); | |
answerGenerator.generateCombinations(); | |
answerGenerator.fillFormWithCombination(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment