PRODOK Engineering


12 February 2007
by Max Wyss
filed under:

Quite regularly, there is a question on the mailing lists about random numbers, mainly for a unique identifier for a document.

Such random numbers are indeed not a big problem to implement, because JavaScript has the Math Object (because it is part of the Core, it is not described in the Acrobat JavaScript documentation), which contains the Math.random() method.

The Math.random() method returns a pseudo-random number between 0 and 1. This is not bad, but what if we want a random number between 0 and 10? Even that is easy, because we can multiply the random number and “scale” it to the range we need. In our example, it would be

    Math.random() * 10

But I want to roll the dices, and I can’t use something like 3.56342345.

Not a problem at all. The Math object also knows how to round to a full number. Math.round() rounds up or down, Math.ceil() always rounds up to the next whole number, and Math.floor() always rounds down the the next whole number (which means that it essentially cuts off everything after the decimal sign).

So, for rolling a dice, we use Math.ceil() on a random number scaled with 6.

    var dice = Math.ceil(Math.random() * 6) ;

We can generalize this and create a new function randrange(range), which gives us a random number between 1 and the value of range. This will look as follows:

    function randrange(range) {
    return Math.ceil(Math.random() * range) ;
    }

And we have our one-liner.

So good so far, but what about our randomly picked message of the day? Can we do that too in Acrobat?

This is pretty much the same, but we need a little bit of preparation. Our message texts must be stored in an array. And then, calling them is again very easy. We scale the random number to the length of the array, and use this as the index of the array element to display. And this will be another one-liner, in the function rndmsg(msgarray):

    var msgarr = new Array() ; //our array containing messages
    function rndmsg(msgarr) {
    return msgarr[Math.floor(Math.random() * msgarr.length)] ;
    ;

We have to define an Array object (msgarr) of the array containing the messages. We also must make sure that the elements of the array have continuous indices (which means that there must be no “holes” in the indices).

And to get back to our unique identification string for a documen, for example, we have a slightly weird possibility to create a numeric string, between 15 and 17 characters long, as defined in the function rndstring().

    function rndstring() {
    return Math.random().toString().substr(2) ;
    }

Note that this function does not return a number, but a string; in order to turn it into a number again, we would multiply the result with 1.

And that’s all about random randomness…

Feel free to use these pieces of code, but never forget and always mention where you found it.