This namespace contains a bunch of useful methods to generate random lists and strings. It’s plain JavaScript so works on both Apps Script or client side JavaScript.

The main features are

  • creating random strings, arrays and grids
  • limiting used values using ranges, regular expressions and lists
  • shuffling strings and arrays
  • using seed values and phrases to create repeatable randomness
  • unshuffling previously shuffled arrays and strings using the seed values they were shuffled with

Why would you want this?

If you do any kind of random list or string creation, or you need to shuffle (and unshuffle) data both client and server side, you’ll find this set of functions very useful. For example you can create random test spreadsheet data, or even use the seeded shuffling as an aid for encryption (I use this in Generating coupon codes with expiry dates)

Using

If you are using Apps Script, the cLucky library is available here

1X-tyDMF_iILp3cQ4MMCY0GQwrOPHl8ocKtWhqVuw1u5PG5wMytL6mjOP

or you can get the source from github. If using from the Apps Script library, then you can define Lucky as

Examples

The list of methods and options appears at the end of this post, but the best way to demonstrate is simply to show some examples. Here’s a few examples of what you can do, starting with generating arrays of integers with various options. I’ll explain the show() function I’m using in these tests later. It’s just a way of displaying the results.

Lucky.get(options)

This method returns various arrays of random integers.

Get 2 arrays of length 10 populated with random numbers between 1 and 100

Get 2 arrays of length between 3 and 10, populated with random numbers between 1 and 5

Lucky.shuffle(array[,seed])

This will shuffle an array in random order

See

Being able to generate repeatable random number can be important for some applications, not least because if you can repeat random sequence used for shuffling, this also means you can unshuffle it if you know the seed it was shuffled with. MDN JavaScript documentation says this.

The Math.random() function returns a floating-point, pseudo-random number in the range [0, 1) that is, from 0 (inclusive) up to but not including 1 (exclusive), which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

 

But there is a hack that works on Apps Script and all the browsers I’ve tried, that allows you to generate repeatable random sequences by poking Math.seed.

Both Lucky.shuffle and Lucky.get accept a seed, so that means that there can also be a Lucky.unShuffle, which I’ll cover shortly. A seed is a non zero, numeric value that can be used to force the random number generator to return the same sequence when used. Lucky accepts both numeric and string values as a seed, so you can use a passphrase instead of a number if you prefer.

Get 2 arrays of length 10 populated with random numbers between 1 and 100. Since I’ve used the same seed with this, then the result is the same in both cases. A different seed will generate a different result.

Get 2 arrays of length between 6 and 15 populated with random numbers between 1 and 100. Since I’ve used the same seed with this, then the result is the same in both cases. A different seed will generate a different result. Note that the start of the arrays, which are different sizes, is the same.

Lucky.unShuffle(array, seed)

Now that we have a way of shuffling an array in a predictable away, restoring to the original order is a simple matter of reversing the shuffle by using the same seed as was used in the original shuffle, as per these examples.

We’ll use this array

And shuffle it using some seed

Shuffled array with seed

And magically, we can use the same seed to remember the original sequence

Unshuffled array with seed

Lucky.getString (options)

All the same techniques are available to manipulate strings, plus a few others that are specific to strings.

Generate 2 random strings of 10 characters using the characters a-z

String 0

String 1

Generate 2 random strings of between 7 and 18 characters using the characters A-S

String random size 0

String random size 1

Strings can also be shuffled

string shuffle

You can also use seeds with strings. Generate 2 strings of length 10, using some seed. Note that both strings are in the same order.

String seeded 0

String seeded 1

Generate a string of between 6 and 15 characters, using characters d-v. Since we’re using a seed, both strings will start with the same characters.

String seeded random size 0

String seeded random size 1

Seeds can be used with strings, to create strings that can be unshuffled again. Let’s use this string

Shuffling strings with seeds

Let’s shuffle using a seed

Shuffled string with seed

Using the same seed, we can get back to the original order.

Unshuffled string with seed

String as seeds

So far we’ve just used numbers as a seed. Lucky also supports a seed as a string , which may be more convenient, as per this example, which shuffles an unshuffles which a string seed.

strings as seeds

Shuffled string with string seed

Unshuffled string with string seed

Regular expressions to specify the qualifying character set

Using the options.min and options.max, you can specify the range of characters that can be used in a random string, but sometimes you need a more specific character set. You can use regular expressions to limit the character set to characters that match your regular expression.
Get two random strings of 30 characters consisting only of characters that can appear in words (that match the regex expression \w).

String with regex 0

String with regex 1

The other features such as seeding and variable size can also be used with regular expression character set selection.
Get two strings between 1 and 13 characters made with characters that match the regular expression [A-Gb#].

String random size with regex 0

String random size with regex 1

Character sets and regular expressions

By default, when using regular expressions, only standard ascii characters are included in the generated string. However you can also include extended ascii (for those accented characters), but UTF-8 encodings are not yet supported. You can get extended ascii by specifying {extendedAscii: true } in your options.

Using lists

Lists can be used to specify the character set. This means you can limit the characters included to those in a list. Whereas regular expressions can only be used with getString, Lists can be used with both get and getString.

Get two strings of between 12 and 13 characters made up only from the characters ‘abcdef’

String random size with list 0

String random size with list 1

One advantage of using lists is that you can introduce bias by having the same character repeated multiple times. This example uses the letter frequency in scrabble along with the average length of english words to make sentences of nonsense, that actually look a little like sentences.

string random size with scrabble list 0

string random size with scrabble list 1

To use lists with arrays, just populate the array with the members you want.
Get 2 arrays of between 5 and 10 members, made up from the members of the list, [‘george’,’john’,’paul’,’ringo’]

an array with a list 0

an array with a list 1

Seeds can be used with lists too.

Get 2 arrays of 6 members, made up from the members of the list, [‘george’,’john’,’paul’,’ringo’], but use a seed so it can be repeatable

an array with a list seeded 0

an array with a list seeded 1

Lucky.getGrid (options)

There’s also a built in way of creating a grid of random values. Useful for spreadsheets test data.

getting grid

All the options for seeding and lists etc are available here too. By default it will create a random number of each of boolean,date,string and number columns using the width and maxWidth properties to decide how many to make. It uses a list option to know which kind of data to make, the default is [“date”,”boolean”,”string”,”number”]. If you want a different set, you can do something like this:

If you want to keep the the columns to a specific list (not randomized), you can used the fixed option, for example

getting grid

There are some defaults for each of the data types, but you can change that too, using all the same parameters as covered previously, as in this example which will create 12 rows of 3 columns with random data driven by the options shown.

getting grid

See inheritance

In the getGrid() example, each type of column can have its own seed – meaning that you can reproduce the results for a particular column if you run it again. By default, if the main options have a seed mentioned, then this seed will be inherited by each column (unless they have their own) – like this the entire grid can be reproduced by setting a single seed, so for example, this will always produce the same grid as in the example below.

getting grid seed 1

getting grid seed 2

You can change the behavior for any of the individual columns, by turning that off. The example below would be able to repeat the grid for all columns except for string columns, which have inheritSeed turned off.

getting grid seed 3 – no string inheritance

Other stuff

There are a few other utilities in this namespace that can be handy

Get a random integer between 200 and 399

getRandBetween

Get a unique string of the recommended size

getUniqueString

Get a unique string of the minimum size that can work

getUniqueString shorter

Get a longer unique string of 20 characters

getUniqueString longer

Methods

 Lucky methods  description
 .get(options)  gets an array of random stuff as defined by the options
 .getString(options)  gets a random string as defined by the options
 .getGrid(options)  gets a random grid as defined by the options
 .shuffle(array|string[,seed])  shuffles an array or a string (repeatably if seed is specified)
 .unShuffle(array|string,seed)  can restore an array or string to its original order using the same seed it was shuffled with
 .getRandBetween (min,max[,func])  gets a random  integer between min and max using Math.random(), or some other function if supplied
 .getUniqueString([size])  gets a unique string of the given size

Options
Not all options apply to all methods. See the description and examples earlier for details
Lucky options type description

Lucky options  type  description
 max  number  the max value to allow in the generated array or integer array
 min  number  the min value to allow in the generated array or integer array
 size  number  the size of the string or array to generate, or the minimum size if maxSize is specified. For grids this refers to the number of rows in the grid.
 maxSize  number  where specified, will generate a string or array of a random length between size and maxSize
 seed  number|string  if specified, creates a repeatable random string or array
 width  number  used with getGrid to specify the minimum width of the grid, or the actual width if maxWidth is not specified
 maxWidth  number  where specified, will generate a grid of a random width between width and maxWidth
 list  array|string  a list of acceptable values or characters to randomize. This overrides max/min values. In the case of a grid, list is used to communicate the types of columns required. The default is [“boolean”,”string”,”number”,”date”]
 rx  RegExp  Any characters matching this expression will make the list of characters to randomize. This overrides both list and min/max
 extendedAscii  boolean  if true, then 8 bits ascii is used to match against an rx. The default is 7 bit standard ascii. Only relevant with an rx
 number  object  the properties above can be set in this object to set the behavior for generated columns of the type number with getGrid. Only relevant if ‘number’ is included in the list option of a getGrid request.
 boolean  object  the properties above can be set in this object to set the behavior for generated columns of the type boolean with getGrid. Only relevant if ‘boolean’ is included in the list option of a getGrid request.
 string  object  the properties above can be set in this object to set the behavior for generated columns of the type string with getGrid. Only relevant if ‘string’ is included in the list option of a getGrid request. min and max are ignored for boolean, but you can use a list of different numbers of trues and falses to introduce bias if required.
 date  object  the properties above can be set in this object to set the behavior for generated columns of the type date with getGrid. Only relevant if ‘date’ is included in the list option of a getGrid request.For a date, min and max should be set as a date object.

Showing results

All these examples used a function to log results. Of course these would be different depending on whether its apps script or browser based. Here’s both versions.

For more like this see Google Apps Scripts Snippets
Why not join our forum, follow the blog or follow me on twitter to ensure you get updates when they are available.