Randomness

How to generate random values with the Commons’ Random package.

Key takeaways

Random package The Commons module offers the Random package, which contains a set of classes and methods that can be used to generate different types of random values such as Booleans, doubles, datetimes, floats and integers.

Introduction

In this tutorial, we will learn how to use the Random package available in the Commons module. This package contains a set of classes and methods that can be used to generate different types of random values, such as Booleans, doubles, floats, and integers. It also offers methods to generate different types of texts such as names and surnames, and methods to randomly select an element from an array or text.

Random value generation

In this section, we will see how to use each of the methods available in the Random package through the use of examples. Each example will show its possible result as a comment.

a) Random arrays

The RandomArray class provides a way to randomly choose an element from an array via its pick method. The following example shows how to use it.

import { RandomArray } from "pip-services3-commons-nodex";


export function main() {
    let value1 = RandomArray.pick([ 1, 2, 3, 4 ]); // Possible result: 3
}

using PipServices3.Commons.Random;

namespace ExampleApp
{

    class Program
    {
        static void Main(string[] args)
        {
            var value1 = RandomArray.Pick(new int[] { 1, 2, 3, 4 }); // Possible result: 3
        }
    }
}

package main

import (
	rand "github.com/pip-services3-go/pip-services3-commons-go/random"
)

func main() {
	value1 := rand.RandomArray.Pick([]int{1, 2, 3, 4}) // Possible result: 3
}

import 'package:pip_services3_commons/pip_services3_commons.dart';

void main(List<String> arguments) {
  var value1 = RandomArray.pick([1, 2, 3, 4]); // Possible result: 3
}


from pip_services3_commons.random import RandomArray

value1 = RandomArray.pick([1, 2, 3, 4]) # Possible result: 3
Not available

b) Random Booleans

The RandomBoolean class offers two methods namely chance and next_boolean. The following table and examples explain how to use both of them.

Method Description
chance(chance: float, maxChances: float) Calculates “chance” out of “max chances”. Example: 1 chance out of 3 chances (or 33.3%). It returns true or false for a settled chance.
next_boolean() Generates a random Boolean value.
import { RandomBoolean } from "pip-services3-commons-nodex";


export function main() {
    let value1 = RandomBoolean.nextBoolean();   // Possible result: True
    let value2 = RandomBoolean.chance(1, 3);    // Possible result: False
}

using PipServices3.Commons.Random;

namespace ExampleApp
{

    class Program
    {
        static void Main(string[] args)
        {
            var value1 = RandomBoolean.NextBoolean();   // Possible result: True
            var value2 = RandomBoolean.Chance(1, 3);    // Possible result: False
        }
    }
}

package main

import (
	rand "github.com/pip-services3-go/pip-services3-commons-go/random"
)

func main() {
	value1 := rand.RandomBoolean.NextBoolean()   // Possible result: True
	value2 := rand.RandomBoolean.Chance(1,3)      // Possible result: False
}

import 'package:pip_services3_commons/pip_services3_commons.dart';

void main(List<String> arguments) {
  var value1 = RandomBoolean.nextBoolean(); // Possible result: True
  var value2 = RandomBoolean.chance(1, 3); // Possible result: False
}


from pip_services3_commons.random import RandomBoolean

value1 = RandomBoolean.next_boolean()   # Possible result: True
value2 = RandomBoolean.chance(1,3)      # Possible result: False
Not available

c) Random DateTimes

The RandomDateTime class contains two methods: next_date and update_datetime. The description and examples of their usage are found in the table and code below:

Method Description
next_date(min_year: datetime, max_year: datetime = None) Generates a random Date in the range [‘minYear’, ‘maxYear’]. This method generates dates without time (or time set to 00:00:00).
next_datetime(min_year: datetime, max_year: datetime = None) Generates a random Date and time in the range [‘minYear’, ‘maxYear’]. This method generates dates without time (or time set to 00:00:00).
import { RandomDateTime } from "pip-services3-commons-nodex";


export function main() {
    // Possible result: 2015-01-05 00:00:00
    let value1 = RandomDateTime.nextDate(new Date(2010, 1, 1));

    // Possible result: 2012-01-03
    let value2 = RandomDateTime.nextDate(new Date(2010, 1, 1), new Date(2015, 1, 1));

    // Possible result: 2020-03-11 11:20:32
    let value3 = RandomDateTime.nextDate(new Date(2017, 1, 1));

    // Possible result: 2010-01-02 00:00:01
    let value4 = RandomDateTime.updateDateTime(new Date(2010, 1, 2), 50); 
}
using PipServices3.Commons.Random;

using System;

namespace ExampleApp
{

    class Program
    {
        static void Main(string[] args)
        {
            // Possible result: 2015-01-05 00:00:00
            var value1 = RandomDateTime.NextDate(new DateTime(2010, 1, 1));

            // Possible result: 2012-01-03
            var value2 = RandomDateTime.NextDate(new DateTime(2010, 1, 1), new DateTime(2015, 1, 1));

            // Possible result: 2020-03-11 11:20:32
            var value3 = RandomDateTime.NextDate(new DateTime(2017, 1, 1));
            
            // Possible result: 2010-01-02 00:00:01
            var value4 = RandomDateTime.UpdateDateTime(new DateTime(2010, 1, 2), 50); 
        }
    }
}

package main

import (
	"fmt"
	"time"

	rand "github.com/pip-services3-go/pip-services3-commons-go/random"
)

func main() {
	maxDate := time.Date(2050, 1, 1, 0, 0, 0, 0, time.Local)

    // Possible result: 2015-01-05 00:00:00
	value1 := rand.RandomDateTime.NextDate(time.Date(2010, 1, 1, 0, 0, 0, 0, time.Local), maxDate)  

    // Possible result: 2012-01-03
	value2 := rand.RandomDateTime.NextDate(time.Date(2010, 1, 1, 0, 0, 0, 0, time.Local), time.Date(2015, 1, 1, 0, 0, 0, 0, time.Local))

    // Possible result: 2020-03-11 11:20:32
	value3 := rand.RandomDateTime.NextDateTime(time.Date(2017, 1, 1, 0, 0, 0, 0, time.Local), maxDate)

    // Possible result: 2010-01-02 00:00:01
	value4 := rand.RandomDateTime.UpdateDateTime(time.Date(2010, 1, 2, 0, 0, 0, 0, time.Local), 500)
}

import 'package:pip_services3_commons/pip_services3_commons.dart';

void main(List<String> arguments) {
  // Possible result: 2015-01-05 00:00:00
  var value1 = RandomDateTime.nextDate(DateTime(2010, 1, 1));

  // Possible result: 2012-01-03
  var value2 =
      RandomDateTime.nextDate(DateTime(2010, 1, 1), DateTime(2015, 1, 1));

  // Possible result: 2020-03-11 11:20:32
  var value3 = RandomDateTime.nextDate(DateTime(2017, 1, 1));

  // Possible result: 2010-01-02 00:00:01
  var value4 = RandomDateTime.updateDateTime(DateTime(2010, 1, 2), 50);
}

from pip_services3_commons.random import RandomDateTime
import datetime

value1 = RandomDateTime.next_date(datetime.datetime(2010,1,1))   # Possible result: 2002-01-05 00:00:00
value2 = RandomDateTime.next_date(datetime.datetime(2010,1,1), datetime.datetime(2015,1,1))   # Possible result: 2008-01-03
value3 = RandomDateTime.next_datetime(datetime.datetime(2017,1,1))   # Possible result: 2007-03-11 11:20:32
value4 = RandomDateTime.update_datetime(datetime.datetime(2010,1,2)) # Possible result: 2010-02-05 11:33:23
Not available

d) Random doubles

The RandomDouble class has two methods that can be used to generate random double values. The table and code below explain them.

Method Description
next_double(mmin: float, mmax: float = None) Generates a random double value in the range [‘min_value’, ‘max_value.’], where min_value is optional.
update_double(value: float, rrange: float = None) Updates (drifts) a double value within a specified range.
import { RandomDouble } from "pip-services3-commons-nodex";


export function main() {
    // Random value between 5 and 10
    let value1 = RandomDouble.nextDouble(5, 10);      // Possible result: 7.3252274575446155

    // Random value lower than 10
    let value2 = RandomDouble.nextDouble(10);      // Possible result: 8.104104435251225

    // Random value 
    let value3 = RandomDouble.updateDouble(10, 5);      // Possible result: 8.051623143638789
}

using PipServices3.Commons.Random;

namespace ExampleApp
{

    class Program
    {
        static void Main(string[] args)
        {
            // Random value between 5 and 10
            var value1 = RandomDouble.NextDouble(5, 10);      // Possible result: 7.3252274575446155

            // Random value lower than 10
            var value2 = RandomDouble.NextDouble(10);      // Possible result: 8.104104435251225

            // Random value 
            var value3 = RandomDouble.UpdateDouble(10, 5);      // Possible result: 8.051623143638789
        }
    }
}

package main

import (
	rand "github.com/pip-services3-go/pip-services3-commons-go/random"
)

func main() {
	value1 := rand.RandomDouble.NextDouble(5, 10) // Possible result: 7.3252274575446155

	// Random value lower than 10
	value2 := rand.RandomDouble.NextDouble(10, 11) // Possible result: 10.104104435251225

	// Random value
	value3 := rand.RandomDouble.UpdateDouble(10, 5) // Possible result: 8.051623143638789
}

import 'package:pip_services3_commons/pip_services3_commons.dart';

void main(List<String> arguments) {
  // Random value between 5 and 10
  var value1 =
      RandomDouble.nextDouble(5, 10); // Possible result: 7.3252274575446155

  // Random value lower than 10
  var value2 =
      RandomDouble.nextDouble(10); // Possible result: 8.104104435251225

  // Random value
  var value3 =
      RandomDouble.updateDouble(10, 5); // Possible result: 8.051623143638789
}


from pip_services3_commons.random import RandomDouble

# Random value between 5 and 10
value1 = RandomDouble.next_double(5, 10)      # Possible result: 7.3252274575446155

# Random value lower than 10
value2 = RandomDouble.next_double(10)      # Possible result: 8.104104435251225

# Random value 
value3 = RandomDouble.update_double(10, 5)      # Possible result: 8.051623143638789
Not available

e) Random floats

The RandomFloat class contains two methods that can be used to obtain random floats. The table and code below describe their usage.

Method Description
next_float(min: float, max: float = None) Generates a float in the range [‘min’, ‘max’]. If ‘max’ is omitted, then the range will be set to [0, ‘min’].
update_float(value: float, range: float = None) Updates (drifts) a float value within a specified range.
import { RandomFloat } from "pip-services3-commons-nodex";


export function main() {
    // Random value between 5 and 10
    let value1 = RandomFloat.nextFloat(5, 10);     // Possible result: 8.109282778264653

    // Random value lower than 10
    let value2 = RandomFloat.nextFloat(10);        // Possible result: 5.281760648272185

    // Random value
    let value3 = RandomFloat.updateFloat(10, 3);   // Possible result: 7.731874405844179
}

using PipServices3.Commons.Random;

namespace ExampleApp
{

    class Program
    {
        static void Main(string[] args)
        {
            // Random value between 5 and 10
            var value1 = RandomFloat.NextFloat(5, 10);     // Possible result: 8.109282778264653

            // Random value lower than 10
            var value2 = RandomFloat.NextFloat(10);        // Possible result: 5.281760648272185

            // Random value
            var value3 = RandomFloat.UpdateFloat(10, 3);   // Possible result: 7.731874405844179
        }
    }
}

package main

import (
	rand "github.com/pip-services3-go/pip-services3-commons-go/random"
)

func main() {
	// Random value between 5 and 10
	value1 := rand.RandomFloat.NextFloat(5, 10) // Possible result: 8.109282778264653

	// Random value lower than 10
	value2 := rand.RandomFloat.NextFloat(10, 15) // Possible result: 14.281760648272185

	// Random value
	value3 := rand.RandomFloat.UpdateFloat(10, 3) // Possible result: 7.73187440584417
}

import 'package:pip_services3_commons/pip_services3_commons.dart';

void main(List<String> arguments) {
  // Random value between 5 and 10
  var value1 =
      RandomFloat.nextFloat(5, 10); // Possible result: 8.109282778264653

  // Random value lower than 10
  var value2 = RandomFloat.nextFloat(10); // Possible result: 5.281760648272185

  // Random value
  var value3 =
      RandomFloat.updateFloat(10, 3); // Possible result: 7.731874405844179
}


from pip_services3_commons.random import RandomFloat

# Random value between 5 and 10
value1 = RandomFloat.next_float(5, 10)     # Possible result: 8.109282778264653

# Random value lower than 10
value2 = RandomFloat.next_float(10)        # Possible result: 5.281760648272185

# Random value
value3 = RandomFloat.update_float(10, 3)   # Possible result: 7.731874405844179
Not available

f) Random integers

The RandomInteger class has two methods for generating random integers. Their usage is explained in the following table and code:

Method Description
next_integer(min: int, max: int = None) Generates an integer in the range [‘min’, ‘max’]. If ‘max’ is omitted, then the range will be set to [0, ‘min’].
update_integer(value: int, range: int = None) Updates (drifts) an integer value within the specified range.
import { RandomInteger } from "pip-services3-commons-nodex";


export function main() {
    // Random value between 5 and 10
    let value1 = RandomInteger.nextInteger(5, 10);     // Possible result: 5

    // Random value lower than 10
    let value2 = RandomInteger.nextInteger(10);        // Possible result: 4

    // Random value
    let value3 = RandomInteger.updateInteger(10, 3);   // Possible result: 12
}
using PipServices3.Commons.Random;

namespace ExampleApp
{

    class Program
    {
        static void Main(string[] args)
        {
            // Random value between 5 and 10
            var value1 = RandomInteger.NextInteger(5, 10);     // Possible result: 5

            // Random value lower than 10
            var value2 = RandomInteger.NextInteger(10);        // Possible result: 4

            // Random value
            var value3 = RandomInteger.UpdateInteger(10, 3);   // Possible result: 12
        }
    }
}

package main

import (
	rand "github.com/pip-services3-go/pip-services3-commons-go/random"
)

func main() {
	// Random value between 5 and 10
	value1 := rand.RandomInteger.NextInteger(5, 10) // Possible result: 7

	// Random value lower than 10
	value2 := rand.RandomInteger.NextInteger(10, 15) // Possible result: 11

	// Random value
	value3 := rand.RandomInteger.UpdateInteger(10, 3) // Possible result: 10
}

import 'package:pip_services3_commons/pip_services3_commons.dart';

void main(List<String> arguments) {
  // Random value between 5 and 10
  var value1 = RandomInteger.nextInteger(5, 10); // Possible result: 5

  // Random value lower than 10
  var value2 = RandomInteger.nextInteger(10); // Possible result: 4

  // Random value
  var value3 = RandomInteger.updateInteger(10, 3); // Possible result: 12
}

from pip_services3_commons.random import RandomInteger

# Random value between 5 and 10
value1 = RandomInteger.next_integer(5, 10)     # Possible result: 5

# Random value lower than 10
value2 = RandomInteger.next_integer(10)        # Possible result: 4

# Random value
value3 = RandomInteger.update_integer(10, 3)   # Possible result: 12
Not available

g) Random strings

The RandomString class presents methods that can be used to create random strings and to randomly pick a character from a string or an array of strings. The following table and code explain their usage:

Method Description
distort(value: str) Distorts a string by randomly replacing characters in it.
next_alpha_char() Generates random alpha characted [A-Za-z].
next_string(min_size: int, min_size: int) Generates a random string consisting of upper and lower case letters (of the English alphabet), digits (0-9), and symbols ("_,.:-/.[].{},#-!,$=%.+^.&*-() “).
pick(values: List[str]) Picks a random string from an array of strings.
pick_char(values: str) Picks a random character from a string.
import { RandomString } from "pip-services3-commons-nodex";


export function main() {
    let value1 = RandomString.distort("hello John"); // Possible result: Hello john
    let value2 = RandomString.nextAlphaChar(); // Possible result: C
    let value3 = RandomString.nextString(5, 10); // Possible result .h*_N9}
    let value4 = RandomString.pick([ "A", "B", "C", "D", "E" ]); // Possible result: c
}

using PipServices3.Commons.Random;

using System;

namespace ExampleApp
{

    class Program
    {
        static void Main(string[] args)
        {
            var value1 = RandomString.Distort("hello John"); // Possible result: Hello john
            var value2 = RandomString.NextAlphaChar(); // Possible result: C
            var value3 = RandomString.NextString(5, 10); // Possible result .h*_N9}
            var value4 = RandomString.Pick(new string[] { "A", "B", "C", "D", "E" }); // Possible result: c
        }
    }
}

package main

import (
	"fmt"

	rand "github.com/pip-services3-go/pip-services3-commons-go/random"
)

func main() {
	value1 := rand.RandomString.Distort("hello John")                   // Possible result: Hello john
	value2 := rand.RandomString.NextAlphaChar()                         // Possible result: C
	value3 := rand.RandomString.NextString(5, 10)                       // Possible result .h*_N9}
	value4 := rand.RandomString.Pick([]string{"A", "B", "C", "D", "E"}) // Possible result: c
	value5 := rand.RandomString.PickChar("Jonathan")                    // Possible result: n
}

import 'package:pip_services3_commons/pip_services3_commons.dart';

void main(List<String> arguments) {
  var value1 =
      RandomString.distort('hello John'); // Possible result: Hello john
  var value2 = RandomString.nextAlphaChar(); // Possible result: C
  var value3 = RandomString.nextString(5, 10); // Possible result .h*_N9}
  var value4 =
      RandomString.pick(['A', 'B', 'C', 'D', 'E']); // Possible result: c
}


from pip_services3_commons.random import RandomString

value1 = RandomString.distort("hello John") # Possible result: Hello john
value2 = RandomString.next_alpha_char() # Possible result: C
value3 = RandomString.next_string(5,10) # Possible result .h*_N9}
value4 = RandomString.pick(["A","B","C", "D", "E"]) # Possible result: c
value5 = RandomString.pick_char("Jonathan") # Possible result: n
Not available

h) Random texts

The RandomText class can be used to generate different types of random texts. The options include colors, names, nouns, adjectives, verbs, phrases, full names, words, phone numbers, email addresses, and texts. The following table summarizes all the methods in this class and the examples after it show how to use each of them.

Method Description
adjective() Generates a random adjective. The result value is capitalized.
color() Generates a random color name. The result value is capitalized.
email() Generates a random email address.
noun() Generates a random person’s name with the following structure:
    (optional) prefix + first name + second name + (optional suffix)
phone() Generates a random phone number with the format: (XXX) XXX-YYYY.
phrase(min_size: int, max_size: int = None) Generates a random phrase that consists of a few words separated by spaces. The first word is capitalized, and the following ones are not.
text(min_size: int, max_size: int = None) Generates a random text, consisting of first names, last names, colors, things, adjectives, verbs, and punctuation marks.
verb() Generates a random verb. The result value is capitalized.
word() Generates a random word from available first names, last names, colors, things, adjectives, or verbs.
words(min_size: int, max_size: int = None) Generates a random word from available first names, last names, colors, things, adjectives, or verbs.
import { RandomText } from "pip-services3-commons-nodex";


export function main() {
    let value1 = RandomText.adjective();    // Possible result: Small
    let value2 = RandomText.color();        // Possible result: White
    let value3 = RandomText.email();        // Possible result: NickStay @Hotel.com
    let value4 = RandomText.fullName();     // Possible result; Dr.Pamela Smith
    let value5 = RandomText.noun();         // Possible result: Car
    let value6 = RandomText.phone();        // Possible result: (147) 371 - 7084
    let value7 = RandomText.phrase(3);      // Possible result: Large
    let value8 = RandomText.word();         // Possible result: Hurry
    let value9 = RandomText.verb();         // Possible result: Lay
    let value10 = RandomText.text(5, 20);   // Possible result: Small carmack large
}

using PipServices3.Commons.Random;

using System;

namespace ExampleApp
{

    class Program
    {
        static void Main(string[] args)
        {
            var value1 = RandomText.Adjective(); // Possible result: Small
            var value2 = RandomText.Color(); // Possible result: White
            var value3 = RandomText.Email(); // Possible result: NickStay@Hotel.com
            var value4 = RandomText.Words(3, 5); // Possible result: WriteSmithCarPamela
            var value5 = RandomText.Word(); // Possible result: Car
            var value6 = RandomText.Phone(); // Possible result: (147) 371-7084
            var value7 = RandomText.Phrase(3); // Possible result: Large
            var value8 = RandomText.Name();     // Possible result: Hurry Johns
            var value9 = RandomText.Verb();      // Possible result: Lay
            var value10 = RandomText.Text(5, 20);    // Possible result: Small carmack large
        }
    }
}

package main

import (
	rand "github.com/pip-services3-go/pip-services3-commons-go/random"
)

func main() {
	value1 := rand.RandomText.Adjective()  // Possible result: Small
	value2 := rand.RandomText.Color()      // Possible result: White
	value3 := rand.RandomText.Email()      // Possible result: NickStay@Hotel.com
	value4 := rand.RandomText.FullName()   // Possible result; Dr. Pamela Smith
	value5 := rand.RandomText.Word()       // Possible result: Car
	value6 := rand.RandomText.Phone()      // Possible result: (147) 371-7084
	value7 := rand.RandomText.Phrase(3, 7) // Possible result: Large
	value8 := rand.RandomText.Words(3, 5)  // Possible result: HurryJohns
	value9 := rand.RandomText.Verb()       // Possible result: Lay
	value10 := rand.RandomText.Text(5, 20) // Possible result: Small carmack large
}

import 'package:pip_services3_commons/pip_services3_commons.dart';

void main(List<String> arguments) {
  var value1 = RandomText.adjective(); // Possible result: Small
  var value2 = RandomText.color(); // Possible result: White
  var value3 = RandomText.email(); // Possible result: NickStay @Hotel.com
  var value4 = RandomText.fullName(); // Possible result; Dr.Pamela Smith
  var value5 = RandomText.noun(); // Possible result: Car
  var value6 = RandomText.phone(); // Possible result: (147) 371 - 7084
  var value7 = RandomText.phrase(3); // Possible result: Large
  var value8 = RandomText.word(); // Possible result: Hurry
  var value9 = RandomText.verb(); // Possible result: Lay
  var value10 = RandomText.text(5, 20); // Possible result: Small carmack large
}

from pip_services3_commons.random import RandomText

value1 = RandomText.adjective() # Possible result: Small
value2 = RandomText.color() # Possible result: White
value3 = RandomText.email() # Possible result: NickStay@Hotel.com
value4 = RandomText.full_name() # Possible result; Dr. Pamela Smith
value5 = RandomText.noun() # Possible result: Car
value6 = RandomText.phone() # Possible result: (147) 371-7084
value7 = RandomText.phrase(3) # Possible result: Large
value8 = RandomText.name()      # Possible result: Hurry Johns
value9 = RandomText.verb()      # Possible result: Lay
value10 = RandomText.text(5,20)    # Possible result: Small carmack large
Not available

Wrapping up

In this tutorial, we have learned to use the Random package available in the Commons module. This package provides a set of classes that we can use to generate different types of random values such as integers, Booleans, doubles, floats, strings, datetimes, arrays and texts.