lundi 28 août 2023

How to shuffle a list of sequence numbers in bash

I want to generate the random numbers and then use it as the "index" to get the data from other array list.

Given a number 5, and then generate 5 numbers in the sequence of [1..5], and then shuffle them into the random order.

Here are two examples output after shuffling the numbers:

1, 3, 5, 2, 4
2, 5, 1, 4, 3

Gien a number 100, then generate 100 numbers in [1...100], then shuffle them using the same method.

Now define a shuffle function in bash:

shuffle_numbers() {
    local range="$1"
    
    # Use method from "Mark Setchell"
    # numbers=( $seq 100 | shuf )
    
    # The value of numbers should be:
    # 1, 3, 5, 2, 4
    # or
    # 2, 5, 1, 4, 3
    # or
    # ..other random orders if the $range is 5.
    # or
    # ... 100 random orders if the $range is 100...
    
    sprintf "%s" "$numbers"
}

How to implement the shuffle_numbers in bash?




Aucun commentaire:

Enregistrer un commentaire