问题
I'm new to GoogleAppsScript and now making quizzes in google form and spreadsheet by using GAS.
I want to shuffle items in a MultipleChoiceItem when the google form is reloaded.
A part of my current scirpt, slightly modified form this code, is presented below.
//vars from spreadsheet
var form = FormApp.openById(id);
var ss = SpreadsheetApp.openById(question_bank_ID);
var text = sheet.getSheetValues(questions[i]+1, 2, 1, 1)[0][0];
var options = sheet.getSheetValues(questions[i]+1, 5, 1, 5)[0];
var ans = sheet2.getSheetValues(questions[i]+1, 5, 1, 5)[0];
//MultipleChoiceItem
var mc = form.addMultipleChoiceItem().setTitle(text);
mc.setPoints(1) // set point
// add choices with isCorrect
while (options[options.length - 1] === "") {
options.pop();
}
mc.setChoices(options.map(function (options, i) {
return mc.createChoice(options, ans[i]);
}
)
)
Could someone please tell me a solution? Thanks for your help!
回答1:
- In order to shuffle your values each time your form is reloaded, you need to bind to your form a script with an
onOpen
trigger - Retrieve all questions and for each question retrieve the choices
- Use a shuffle function to randomize the choices
- Assign the shuffled choices back to the question
Sample:
function onOpen(){
form = FormApp.getActiveForm();
var questions = form.getItems();
for (var i =0; i < questions.length; i++){
var question = questions[i];
var choices = question.asMultipleChoiceItem().getChoices();
var newChoices = shuffle(choices);
question.asMultipleChoiceItem().setChoices(newChoices);
}
}
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
UPDATE:
If you want to give to every user the same quiz but with randomized questions, there is no direct way to do it - so far there is no method of the kind setShuffleItems
.
All you can do for the moment is a workaround, e.g. you can bind to the sample above an installable time-driven trigger which would shuffle the items in desired intervals (the minimum is one minute). This does not guarantee that each user will see a different quiz, but at least each minute the quiz will be different.
来源:https://stackoverflow.com/questions/60112365/can-i-randomize-items-in-multiplechoiceitem