google-sheetsgoogle-apps-scriptgoogle-forms

Insert multiple choice questions and shuffle choices for Google Forms


I took the content of the choices from Google Sheets, then randomly mixed them and put them into the options of a Multiple Choice question in Google Forms. The code is as follows:

// Function to create MultipleChoice questions
function createMultipleChoiceQuestions(form, ss, destinationSpss, numQ1, l) {
  var data = ss.getSheetByName("tests");
  var questions1 = data.getRange(2, 2, numQ1, 1).getValues(); // Lấy tất cả các câu hỏi phần 1
  var correctAnswers1 = data.getRange(2, 3, numQ1, 1).getValues(); // Lấy đáp án đúng phần 1
  var answers1 = data.getRange(2, 3, numQ1, 4).getValues(); // Lấy tất cả các đáp án phần 1
  var imgRanges1 = data.getRange(2, 33, numQ1, 1).getValues(); // Lấy tất cả các ID hình ảnh phần 1

  for (var j = 0; j < numQ1; j++) {
    var questionText1 = questions1[j][0];
    var imgRange1 = imgRanges1[j][0];

    if (imgRange1 !== "") {
      try {
        var blobSource1 = DriveApp.getFileById(imgRange1).getBlob();
        form.addImageItem().setImage(blobSource1).setTitle("Hình cho câu " + (j + 1)).setWidth(400);
      } catch (e) {
        Logger.log('Error getting file by ID: ' + imgRange1 + ' - ' + e.message);
      }
    }

    var cau1 = form.addMultipleChoiceItem().setTitle("Câu " + (j + 1) + ": " + questionText1).setRequired(true).setPoints(1);

    var correctAnswer1 = correctAnswers1[j][0];
    var choices1 = answers1[j].map((ans, i) => cau1.createChoice(String.fromCharCode(65 + i) + ". " + ans, ans === correctAnswer1));

    choices1 = shuffleArray(choices1);

    cau1.setChoices(choices1);
  }

In there, my shuffle function:

// Helper function to shuffle array
function shuffleArray(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

I have placed the indexes A, B, C, D at the beginning of each choice option, however I have placed them before merging so after forming the question, the options A, B, C, D sort randomly and not in order. I want: The options are still randomized, but the letter at the top of the options must always be arranged in order from A to D.


Solution

  • In your script, how about modifying it as follows?

    From:

    var choices1 = answers1[j].map((ans, i) => cau1.createChoice(String.fromCharCode(65 + i) + ". " + ans, ans === correctAnswer1));
    
    choices1 = shuffleArray(choices1);
    

    To:

    var choices1 = answers1[j].map(ans => cau1.createChoice(ans, ans === correctAnswer1));
    choices1 = shuffleArray(choices1).map((c, i) =>
      cau1.createChoice(`${String.fromCharCode(65 + i)}. ${c.getValue()}`, c.isCorrectAnswer())
    );