0

Suppose a script like this

#!/bin/bash
array[0]="123"
array[1]="333"
array[2]="5566"
array[3]="135"
array[4]="68"
array[5]="45"
array[6]="78"
array[7]="32"
array[8]="190"

number()
{
size=${#array[@]}
index=$(($RANDOM % $size))
sleep 0.5s
echo  Lucky number is ... ${array[$index]}
}

for i in {1..21}; do number; done

Is ok..I want to get random number in the interval,but show also a lot of dups

Lucky number is ... 135
Lucky number is ... 135
Lucky number is ... 5566
Lucky number is ... 78
Lucky number is ... 190
Lucky number is ... 333
Lucky number is ... 190
Lucky number is ... 135
Lucky number is ... 5566
Lucky number is ... 333
Lucky number is ... 45
Lucky number is ... 45
Lucky number is ... 68
Lucky number is ... 68
Lucky number is ... 333
Lucky number is ... 78
Lucky number is ... 78
Lucky number is ... 5566
Lucky number is ... 78
Lucky number is ... 333
Lucky number is ... 135

I want a result like this

Lucky number is ... 135
Lucky number is ... 5566
Lucky number is ... 78
Lucky number is ... 190
Lucky number is ... 333
Lucky number is ... 45
Lucky number is ... 68

So we can get the "Lucky number" without dups,unique Someone know how to do? Editing the script and reduced 21 to 9 don't change,I get even duplicates.

Lucky number is ... 135
Lucky number is ... 68
Lucky number is ... 45
Lucky number is ... 333
Lucky number is ... 78
Lucky number is ... 135
Lucky number is ... 135
Lucky number is ... 333
Lucky number is ... 32
  • 1
    you asked for 21 random numbers from a set of 9 numbers ... I'm not sure what you expected to happen there? – Jeff Schaller Jun 24 '19 at 23:59
  • I have reduced 21 to 9 and is the same thing. Give me a 9 numbers but with some repeat for one or more times – elbarna Jun 25 '19 at 0:00
  • do an unset array[index] after you’ve echoed your Lucky number ? or piping your output to the uniq command ? – LL3 Jun 25 '19 at 0:17
2

Treat the list like a deck of cards. Shuffle the numbers, then read them out one at a time.

See Simple method to shuffle the elements of an array in BASH shell?.

#!/bin/bash
array=("123" "333" "5566" "135" "68" "45" "78" "32" "190")

shuffle() {
    array=($(shuf -e "${array[@]}"))
    index=0
}

number() {
   size=${#array[@]}
   sleep 0.5s

   if (( index >= size )) ; then
      shuffle
   fi

   echo Lucky number is ... ${array[$index]}
   index=$((index + 1))
}

for i in {1..21}; do number; done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.