1

I am creating a random generator based from a number array list. However, I would like it to be unique so that random number cannot be used again. I have tried creating a 'USED' array list which will store the currently random generated number and then after generate another random then loop through the 'USED' array list and check if it has already been used. If it has then keep generating until there is number that hasn't been used.

Here is what I have so far.

generate.sh

#!/bin/bash

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

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

for i in "${NUMBER[@]}"; do
 let RANDNUMBER=$RANDOM%10
 for j in "${USED[@]}"; do
  if [ $j -eq $RANDOMNUMBER ]; then
   let RANDNUMBER=$RANDOM%10
  else
   echo ${NUMBER[$RANDNUMBER]} >> generated.txt
  fi
 done
done

When I run the script there are no errors, however there is nothing being outputted to the generated.txt file, it is blank.

Is there anything that I am missing? I hope you guys can help :) Thanks in advance.

  • Thanks for the edit. Could you also explain what the %10 in RANDNUMBER=$RANDOM%10 is supposed to do? Are you trying to do modulus 10? Do you need a specific type of number? – terdon Jan 13 '16 at 15:26
  • The %10 will generate a RANDOM number between 0-9. Yes, I need a specific number since the range of the NUMBERS array is between 0-9.` – Ryan Hawdon Jan 13 '16 at 15:27
1

A common way to shuffle a list is to loop over the elements and swap with another element at random.

#! /bin/bash -
list=(1 2 3 4 5 6 7 8 9 0)
random_list=("${list[@]}")
n=${#random_list[@]}
for ((i = 0; i < n; i++)); do
  (( r = RANDOM % n ))
  tmp=${random_list[i]}
  random_list[i]=${random_list[r]}
  random_list[r]=$tmp
done
printf '%s\n' "${random_list[@]}" > generated.txt

Having said that, FreeBSD sort has a -R option to sort randomly, I'd be surprised if OS/X sort didn't, so you should be able to do (assuming array elements don't contain newline characters):

printf '%s\n' "${list[@]}" | sort -R > generated.txt
| improve this answer | |
  • Hi, I have tested your answer and it is randomising the list however I only wanted those numbers in the list to displayed only once. Thanks – Ryan Hawdon Jan 13 '16 at 15:45
  • @RyanHawdon, sorry, there was a typo. It should be fixed now. – Stéphane Chazelas Jan 13 '16 at 15:50
  • Stéphane Chazelas Thank you so much !! It is working perfectly. You're a life saver :) – Ryan Hawdon Jan 13 '16 at 15:53
1

Two typos:

[ $j -eq $RANDOMNUMBER ] should be [[ $j -eq $RANDNUMBER ]]

It seems to work after making the corrections.

| improve this answer | |

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.