Home > Mobile >  generate random number and fill them in array
generate random number and fill them in array

Time:05-14

i want to generate 10 random number between 1 and 100 and store them in an array

#!/bin/bash

for ((i=0; i<10; i  ))
do

done

CodePudding user response:

You can do this with shuf:

arr=( $(shuf -i 1-20 -n 10) )

This will print the first 10 of a random arrangement of the numbers 1 through 20, with no duplicates, and store them in a bash array variable arr.

If you want to do it in pure bash with no external programs, store the numbers as keys in an associative array and keep generating them until you have 10 elements (Which will all be unique), and use the keys as your normal array elements:

declare -A nums
while [[ ${#nums[@]} -ne 10 ]]; do nums[$((RANDOM % 20   1))]=1; done
arr=( "${!nums[@]}" )

CodePudding user response:

In bash, you can use the RANDOM variable

nums=()
for i in {1..10}; do
    nums =( $((1   RANDOM % 100)) )
done
  • Related