Forum Discussion

jessica_mitran's avatar
13 years ago

Generate random numbers in JScript

Hello,



Is there any way to generate random numbers in JScript scripts? I noticed that there is a Random() function in DelphiScript, but there are no analogous ones for JScript.



Jessica

4 Replies

  • karkadil's avatar
    karkadil
    Valued Contributor
    This JScript function will generate a random integer within a given interval




    function randInt(min, max)

    {

      return Math.round(Math.random()*(max-min)+min)

    }


    method Math.random() returns a random number between 0 and 1
  • Oferv's avatar
    Oferv
    Super Contributor
    Hi,



    is there a way to generate random number from a range of numbers but do it twice and make sure the first number won't be selected twice?



    for example:

    if i have the numbers:1,2,3,4,5,6,7,8,9 and the random function select the number 4,i want to run this function again and make sure that the number 4 won't be selected again



    Thanks
  • karkadil's avatar
    karkadil
    Valued Contributor
    Here is an example of such code using the randInt() function I provided earlier.




    function generateTwoNumbers()

    {

      var n1, n2;

      n1 = n2 = randInt(1, 9);

      

      while(n2 == n1)

      {

        n2 = randInt(1, 9);

      }

    }

  • Hi,





    I agree with Gennadiy - his solution is simple and clear. Also, if the number of elements to select is high, you may use a different approach:

    Use an array of N possible values (may be generated programmatically), pick an index randomly in the [0..N-1] range, use the value having that index, then delete the value from the array, and pick another random index in the [0..N-2] range. This can be done in a loop to generate lengthy values with different digits.