2

I am creating a google form where I have three sets of values and I want to randomly select one value from all the three sets and print them as a question.

The extension of the script is ".gs"

I tried using RANDBETWEEN(low, high) but the script throws an error. Seems like this is for google sheets.

Requesting for some help on how to create one.

enter image description here

LearningToCode
  • 392
  • 5
  • 18
  • 1
    Possible duplicate of [Generate random number between two numbers in JavaScript](https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript) – TheMaster Nov 07 '18 at 17:20
  • Include your code as text - not as image. – TheMaster Nov 07 '18 at 17:21

2 Answers2

3

For you random number, you'll need to use the Math library:

var nums = Math.floor(Math.random() * 4) + 1;

That should give you a random number between 1 and 5.

Kambwili
  • 130
  • 7
  • How do you set the uppper and the lower limit ? – LearningToCode Nov 07 '18 at 17:22
  • Read a proper js reference like at Mozilla's website of W3Schools. Google it and it will give you some deeper understanding, but it's basically like this: The range starts from 0 (so 0-4 in our example) then the offset shifts to start at a number other than 0, which is 1 in your case. – Kambwili Nov 07 '18 at 17:28
1

Seems like a little bit of confusion here:

  • RANDBETWEEN(low, high) is a special Google Spreadsheet function.
  • Inside a Google Script, you must use plain JavaScript (plus a few custom Google functions, like the FormApp.create() function you're using.)

In JavaScript, Math.random() is a way of getting a (pseudo) random number, but it returns a float between 0 and 1. To convert that into an integer in a range we have to use a bit of math. It might be helpful to define your own getRandomInt function, like this:

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

Then later on you could call getRandomInt(5), returning 0, 1, 2, 3, or 4.

Dustin Michels
  • 2,951
  • 2
  • 19
  • 31