random Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/random/ Wed, 08 Apr 2020 11:27:10 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 random Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/random/ 32 32 159787465 Generate a random string in Go (Golang) https://vikasboss.github.io/generate-random-string-golang/ https://vikasboss.github.io/generate-random-string-golang/#respond Wed, 08 Apr 2020 11:25:23 +0000 https://vikasboss.github.io/?p=1947 Overview ‘mat/rand’ package of golang contains a Intn function that can be used to generate a pseudo-random number between [0,n). Bracket at the end means that n is exclusive. This function can...

The post Generate a random string in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

‘mat/rand’ package of golang contains a Intn function that can be used to generate a pseudo-random number between [0,n). Bracket at the end means that n is exclusive. This function can be utilized to generate a random string from a character set.


To know more about what pseudo-random number means, checkout this post – https://vikasboss.github.io/generate-random-number-golang

Below is the signature of this method. It takes input a number n and will return a number x in range 0<=x<n.

func Intn(n int) int

Above function can be used to generate a random string. Basically we first select a charSet. Then we use the above function to generate a random number and then use that random number to get a random character from the charSet. This random character is added to a string until we have a random string of desired length.

Code

package main

import (
    "fmt"
    "math/rand"
    "strings"
    "time"
)

func main() {
    rand.Seed(time.Now().Unix())

    //Only lowercase
    charSet := "abcdedfghijklmnopqrst"
    var output strings.Builder
    length := 10
    for i := 0; i < length; i++ {
        random := rand.Intn(len(charSet))
        randomChar := charSet[random]
        output.WriteString(string(randomChar))
    }
    fmt.Println(output.String())
    output.Reset()

    //Lowercase and Uppercase Both
    charSet = "abcdedfghijklmnopqrstABCDEFGHIJKLMNOP"
    length = 20
    for i := 0; i < length; i++ {
        random := rand.Intn(len(charSet))
        randomChar := charSet[random]
        output.WriteString(string(randomChar))
    }
    fmt.Println(output.String())
}

Output:

Below is the output on my machine. On your's it might give a different output

himsemkpkd
nHaiEpccEdBfCFPtaBbi

In above program we are using character set as

abcdedfghijklmnopqrst and abcdedfghijklmnopqrstABCDEFGHIJKLMNOP

All the above characters in charSet were ASCII characters hence we were able to index a character in charSet string. But this could be problem if the charSet contains non-ASCII character.

In Golang string is a sequence of bytes. A string literal actually represents a UTF-8 sequence of bytes. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. All other characters are between 1 to 4 bytes. Due to this it is not possible to index a character in a string.  In GO, rune data type represents a Unicode point.  Once a string is converted to an array of rune then it is possible to index a character in that array of rune.

So in case, the character set contains some characters that are not ASCII they might occupy more than 1 bytes. In that case, we cannot use the above code to generate a random string as we cannot index into the charSet. For this case, we have to first convert a string into a rune array so that we can index into the rune array to the character and then incrementally form the random string.

As in the below example, our charSet contains a non-ASCII character '£'. This character occupies two bytes

package main

import (
    "fmt"
    "math/rand"
    "strings"
    "time"
)

func main() {
    rand.Seed(time.Now().Unix())
    //Only lowercase and £
    charSet := []rune("abcdedfghijklmnopqrst£")
    var output strings.Builder
    length := 10
    for i := 0; i < length; i++ {
        random := rand.Intn(len(charSet))
        randomChar := charSet[random]
        output.WriteRune(randomChar)
    }
    fmt.Println(output.String())
    output.Reset()
 
   //Lowercase and Uppercase Both and £
    charSet = []rune("abcdedfghijklmnopqrstABCDEFGHIJKLMNOP£")
    length = 20
    for i := 0; i < length; i++ {
        random := rand.Intn(len(charSet))
        randomChar := charSet[random]
        output.WriteRune(randomChar)
    }
    fmt.Println(output.String())
}

Output:

Below is the output on my machine. On yours it might give a different output

aidqpbse£j
rebhjblsePsLpGBPOhfB

The post Generate a random string in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/generate-random-string-golang/feed/ 0 1947
Generate a number in a given range in Go (Golang) https://vikasboss.github.io/random-number-range-golang/ https://vikasboss.github.io/random-number-range-golang/#respond Wed, 08 Apr 2020 11:23:49 +0000 https://vikasboss.github.io/?p=1944 Overview ‘mat/rand’ package of golang contains a Intn function that can be used to generate a random number between [0,n). Bracket at the end means that n is exclusive. To know more...

The post Generate a number in a given range in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

‘mat/rand’ package of golang contains a Intn function that can be used to generate a random number between [0,n). Bracket at the end means that n is exclusive.

To know more about what pseudo-random number means, checkout this post – https://vikasboss.github.io/generate-random-number-golang

Below is the signature of this method. It takes input a number n and will return a number x in range 0<=x<n.

func Intn(n int) int


Above function can also be used to generate a random number in range a to b too. See below program. It is used to generate a number between range a to b. We are also providing a seed value to the rand so that it generates different output everytime.

Code

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().Unix())

    //Generate a random number x where x is in range 5<=x<=20
    rangeLower := 5
    rangeUpper := 20
    randomNum := rangeLower + rand.Intn(rangeUpper-rangeLower+1)
    fmt.Println(randomNum)

    //Generate a random number x where x is in range 100<=x<=200
    rangeLower = 100
    rangeUpper = 200
    randomNum = rangeLower + rand.Intn(rangeUpper-rangeLower+1)
    fmt.Println(randomNum)
}

Output:

Number between 5<=x<=20
Number between 100<=x<=200

The post Generate a number in a given range in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/random-number-range-golang/feed/ 0 1944
Generate a random array/slice of n integers in Go (Golang) https://vikasboss.github.io/generate-random-array-slice-golang/ https://vikasboss.github.io/generate-random-array-slice-golang/#respond Thu, 02 Apr 2020 07:06:06 +0000 https://vikasboss.github.io/?p=1940 Overview math/rand package of GO provides a Perm method that can be used generate the pseudo-random slice of n integers. The array will be pseudo-random permutation of the integers in the range...

The post Generate a random array/slice of n integers in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

math/rand package of GO provides a Perm method that can be used generate the pseudo-random slice of n integers. The array will be pseudo-random permutation of the integers in the range [0,n).

To know more about what pseudo-random number means, checkout this post – https://vikasboss.github.io/generate-random-number-golang
Below is the signature of the function. It takes a number n as input and returns the permuted slice.

func Perm(n int) []int

Code:

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    //Provide seed
    rand.Seed(time.Now().Unix())

    //Generate a random array of length n
    fmt.Println(rand.Perm(10))
    fmt.Println(rand.Perm(10))
}

Output:

[6 0 1 5 9 4 2 3 7 8]
[9 8 5 0 3 4 6 7 2 1]

The post Generate a random array/slice of n integers in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/generate-random-array-slice-golang/feed/ 0 1940
Generate a random character in Go (Golang) https://vikasboss.github.io/generate-random-character-golang/ https://vikasboss.github.io/generate-random-character-golang/#respond Thu, 02 Apr 2020 07:02:14 +0000 https://vikasboss.github.io/?p=1933 Overview ‘mat/rand’ package of golang contains an Intn function that can be used to generate a random number between [0,n). The bracket at the end means that n is exclusive. To know...

The post Generate a random character in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

‘mat/rand’ package of golang contains an Intn function that can be used to generate a random number between [0,n). The bracket at the end means that n is exclusive.

To know more about what pseudo-random number means, check out this post – https://vikasboss.github.io/generate-random-number-golang

Below is the signature of this method. It takes input a number n and will return a number x in range 0<=x<n.

func Intn(n int) int

The above function can also be used to generate a random character too. See below program, it is used to generate a character. We are also providing a seed value to the rand so that it generates different output. It is used to generate:

  • Random character between lowercase a to z
  • Random character between uppercase A and Z
  • Random character between uppercase A and Z  and lowercase a to z

Code

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().Unix())

    //Generate a random character between lowercase a to z
    randomChar := 'a' + rune(rand.Intn(26))
    fmt.Println(string(randomChar))

    //Generate a random character between uppercase A and Z
    randomChar = 'A' + rune(rand.Intn(26))
    fmt.Println(string(randomChar))

    //Generate a random character between uppercase A and Z  and lowercase a to z
    randomInt := rand.Intn(2)
    if randomInt == 1 {
        randomChar = 'A' + rune(rand.Intn(26))
    } else {
        randomChar = 'a' + rune(rand.Intn(26))
    }
    fmt.Println(string(randomChar))
}

Output:

Will be lowercase between a to z
Will be uppercase between A to Z
Will be lowercase between a to z or uppsercase between A to Z

The post Generate a random character in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/generate-random-character-golang/feed/ 0 1933
Pick a random character in string in Go (Golang) https://vikasboss.github.io/pick-random-character-string-golang/ https://vikasboss.github.io/pick-random-character-string-golang/#respond Tue, 31 Mar 2020 15:59:17 +0000 https://vikasboss.github.io/?p=1918 Overview ‘mat/rand’ package of golang contains a Intn function that can be used to generate a pseudo-random number between [0,n). Bracket at the end means that n is exclusive. This function can...

The post Pick a random character in string in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

‘mat/rand’ package of golang contains a Intn function that can be used to generate a pseudo-random number between [0,n). Bracket at the end means that n is exclusive. This function can be utilized to pick a random element in a string. We can generate a random between 0 and length-1 of string. Then we can use that random number to index into the string and get the result.

But there is one problem in above approach. In Golang string is a sequence of bytes. A string literal actually represents a UTF-8 sequence of bytes. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. All other characters are between 1 -4 bytes. Due to this it is not possible to index a character in a string.  In GO, rune data type represents a Unicode point.  Once a string is converted to an array of rune then it is possible to index a character in that array of rune.

You can learn more the above issue here – https://vikasboss.github.io/number-characters-string-golang/

For this reason in below program for picking a random in a given string , we  are first converting a string into a rune array so that we can index into the rune array and then return the random character.

Code

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    in := "abcdedf£"
    inRune := []rune(in)
    randomIndex := rand.Intn(len(inRune))
    pick := inRune[randomIndex]
    fmt.Println(string(pick))
}

Output:

One of a,b,c,d,e,f,£

The post Pick a random character in string in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/pick-random-character-string-golang/feed/ 0 1918
Generate Random number in Go (Golang) https://vikasboss.github.io/generate-random-number-golang/ https://vikasboss.github.io/generate-random-number-golang/#respond Sat, 28 Mar 2020 20:54:59 +0000 https://vikasboss.github.io/?p=1889 Overview Go provide a ‘math/rand’ package which has inbuilt support for generating pseudo-random numbers. This package defines methods which can be used to generate A pseudo-random number within the range from 0...

The post Generate Random number in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
Overview

Go provide a ‘math/rand’ package which has inbuilt support for generating pseudo-random numbers. This package defines methods which can be used to generate

  • A pseudo-random number within the range from 0 to n
  • A pseudo-random number without range specified. The range will depend upon the type of int i.e int64, int32, uint64, etc

What is a pseudo-random number

Before proceeding let’s first understand what pseudo-random number means. Pseudo-random number is not truly random as its value is completed determined by the initial value known as seed.


To understand the role of seed, let’s first look at the very basic function which can generate a random number in range [0, n). The below function in the rand package can be used to generate pseudo-random number in range [0, n). Bracket at the end in [0,n) means that n is exclusive.

func Intn(n int) int

The above function returns an int value between 0 to n. Let’s write a program without seed value. We have passed 10, so below function will generate random numbers in range [0,10)

package main

import (
    "fmt"
    "math/rand"
)

func main() {
    fmt.Println(rand.Intn(10))
    fmt.Println(rand.Intn(10))
    fmt.Println(rand.Intn(10))
}

Try running above the program multiple times. It will give the same output every time. On my system, it gives below output

7
7
7

Now let’s try running the same program but first providing seed value.

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().Unix())
    
    fmt.Println(rand.Intn(10))
    fmt.Println(rand.Intn(10))
    fmt.Println(rand.Intn(10))

We are giving seed value as number of seconds which has elapsed till January 1, 1970, UTC.

rand.Seed(time.Now().Unix())

It gives different output each time you execute this program as seed value is different. That is what is meant when we say that go generates pseudo-random numbers.

Random Generator Functions in rand package

Now we have understood what pseudo-random number generation, let’s look at some of the function provided by the rand package for generation of random numbers. You can use any of these functions to generate a random number based on your requirements.

Pseudo-Random Number Generator Functions with range.

All functions take n as an argument and will panic if n<=0.

  • Intn(n int) – It returns a non-negative pseudo-random number in [0,n)
  • Int31n(n int32) – It returns a non-negative pseudo-random number in [0,n) but returns a int32
  • Int63n(n int64) – It returns a non-negative pseudo-random number in [0,n) but returns a int64

Pseudo Random Number Generator Functions without range.

  • Int() – returns a non-negative pseudo-random int
  • Int31() – returns a non-negative pseudo-random 31-bit integer as an int32
  • Int63() – returns a non-negative pseudo-random 63-bit integer as an int64
  • Uint32() – returns a pseudo-random 32-bit value as a uint32
  • Uint64() – returns a pseudo-random 64-bit value as a uint64

Pseudo Random Number Generator Functions with range for floats

  • Float64() – returns, as a float64, a pseudo-random number in [0.0,1.0)
  • Float32() – returns, as a float32, a pseudo-random number in [0.0,1.0)

Code

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed(time.Now().Unix())
    //Pseudo Random Number Generator Functions with range

    //1. Intn(n int)
    fmt.Printf("Intn: %d\n", rand.Intn(10))

    //2. Int31n(n int32)
    fmt.Printf("Int31n: %d\n", rand.Int31n(10))

    //3. Int64n(n int32)
    fmt.Printf("Int64n: %d\n", rand.Int63n(10))

    //Pseudo Random Number Generator Functions without range.

    //1. Int()
    fmt.Printf("Int: %d\n", rand.Int())

    //2. Int31()
    fmt.Printf("Int31: %d\n", rand.Int31())

    //3. Int63()
    fmt.Printf("Int63: %d\n", rand.Int63())
 
    //4. Uint32()
    fmt.Printf("Uint32: %d\n", rand.Uint32())

    //4. Uint64()
    fmt.Printf("Uint64: %d\n", rand.Uint64())

    //Pseudo Random Number Generator Functions with range for floats

    //1. Float64()
    fmt.Printf("Float64: %f\n", rand.Float64())

    //2. Float32()
    fmt.Printf("Float32: %f\n", rand.Float32())
}

Output:

Intn: 9
Int31n: 4
Int64n: 4
Int: 6567086139449890598
Int31: 402632083
Int63: 428924242891364663
Uint32: 1991553101
Uint64: 825780166485441015
Float64: 0.683701
Float32: 0.382141

The post Generate Random number in Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/generate-random-number-golang/feed/ 0 1889