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-services4-data-node"

export function main() {
    let value1 = RandomArray.pick([ 1, 2, 3, 4 ]); // Possible result: 3
}
Not available
import (
	rand "github.com/pip-services4/pip-services4-go/pip-services4-data-go/random"
)

func main() {
	value1 := rand.Array.Pick([]int{1, 2, 3, 4}) // Possible result: 3
}
Not available
from pip_services4_data.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 nextBoolean. 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.
nextBoolean() Generates a random Boolean value.
import { RandomBoolean } from "pip-services4-data-node"

export function main() {
    let value1 = RandomBoolean.nextBoolean();   // Possible result: True
    let value2 = RandomBoolean.chance(1, 3);    // Possible result: False
}
Not available
import (
	rand "github.com/pip-services4/pip-services4-go/pip-services4-data-go/random"
)

func main() {
	value1 := rand.Boolean.Next()       // Possible result: True
	value2 := rand.Boolean.Chance(1, 3) // Possible result: False
}
Not available
from pip_services4_data.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: nextDate and updateDatetime. The description and examples of their usage are found in the table and code below:

Method Description
nextDate(min_year: datetime, maxYear) Generates a random Date in the range ['minYear', 'maxYear']. This method generates dates without time (or time set to 00:00:00).
nextDatetime(min_year: datetime, maxYear) 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-services4-data-node"

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); 
}
Not available
import (
	"time"

	rand "github.com/pip-services4/pip-services4-go/pip-services4-data-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.DateTime.NextDate(time.Date(2010, 1, 1, 0, 0, 0, 0, time.Local), maxDate)

	// Possible result: 2012-01-03
	value2 := rand.DateTime.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.DateTime.NextDateTime(time.Date(2017, 1, 1, 0, 0, 0, 0, time.Local), maxDate)

	// Possible result: 2010-01-02 00:00:01
	value4 := rand.DateTime.UpdateDateTime(time.Date(2010, 1, 2, 0, 0, 0, 0, time.Local), 500)
}
Not available
```python from pip_services4_data.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
nextDouble(min: number, max: number) Generates a random double value in the range ['min_value', 'max_value.'], where min_value is optional.
updateDouble(value: number, range: number) Updates (drifts) a double value within a specified range.
import { RandomDouble } from "pip-services4-data-node"

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
}
Not available
import (
	rand "github.com/pip-services4/pip-services4-go/pip-services4-data-go/random"
)

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

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

	// Random value
	value3 := rand.Double.Update(10, 5) // Possible result: 8.051623143638789
}
Not available
from pip_services4_data.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
nextFloat(min: number, max: number) Generates a float in the range ['min', 'max']. If 'max' is omitted, then the range will be set to [0, 'min'].
updateFloat(value: number, range: number) Updates (drifts) a float value within a specified range.
import { RandomFloat } from "pip-services4-data-node"

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
}
Not available
import (
	rand "github.com/pip-services4/pip-services4-go/pip-services4-data-go/random"
)

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

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

	// Random value
	value3 := rand.Float.Update(10, 3) // Possible result: 7.73187440584417
}
Not available
from pip_services4_data.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
nextInteger(min: number, max: number) Generates an integer in the range ['min', 'max']. If 'max' is omitted, then the range will be set to [0, 'min'].
updateInteger(value: number, range: number) Updates (drifts) an integer value within the specified range.
import { RandomInteger } from "pip-services4-data-node"

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
}
Not available
import (
	rand "github.com/pip-services4/pip-services4-go/pip-services4-data-go/random"
)

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

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

	// Random value
	value3 := rand.Integer.Update(10, 3) // Possible result: 10
}
Not available
from pip_services4_data.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: string) Distorts a string by randomly replacing characters in it.
nextAlphaChar() Generates random alpha characted [A-Za-z].
nextString(minSize: number, minSize: number) Generates a random string consisting of upper and lower case letters (of the English alphabet), digits (0-9), and symbols ("_,.:-/.[].{},#-!,$=%.+^.&*-() ").
pick(values: list) Picks a random string from an array of strings.
pickChar(values: string) Picks a random character from a string.
import { RandomString } from "pip-services4-data-node"

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
}
Not available
import (
	rand "github.com/pip-services4/pip-services4-go/pip-services4-data-go/random"
)

func main() {
	value1 := rand.String.Distort("hello John")                   // Possible result: Hello john
	value2 := rand.String.NextAlphaChar()                         // Possible result: C
	value3 := rand.String.Next(5, 10)                             // Possible result .h*_N9}
	value4 := rand.String.Pick([]string{"A", "B", "C", "D", "E"}) // Possible result: c
	value5 := rand.String.PickChar("Jonathan")                    // Possible result: n
}
Not available
from pip_services4_data.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(minSize: number, maxSize: number) 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(minSize: number, maxSize: number) 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(minSize: number, maxSize: number) Generates a random word from available first names, last names, colors, things, adjectives, or verbs.
import { RandomText } from "pip-services4-data-node"

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
}
Not available
import (
	rand "github.com/pip-services4/pip-services4-go/pip-services4-data-go/random"
)

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