Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Bash to Generate Lotto Numbers

Tags:

arrays

bash

uniq

I've got a simple bash script that generates the following:

These are your winning lottery numbers: 
 27  6   29  17  15  47
 19  16  33  15  20  14
 29  34  48  19  33  40

Here is the code for it:

#!/bin/bash

tickets="$1"

function get_tickets { printf "How many tickets are you going to get? "; read tickets;}

function gen_numbers { printf "\nThese are your winning lottery numbers: \n"; 

    for ((z=1 ; z<=tickets ; z++)); do
         for ((i=0; i<6; i++ )); do 
            x=`echo $[ 1 + $[ RANDOM % 49 ]]`; 
            printf "\t $x"; 
         done;
         printf "\n" 
    done; 
    printf "\n"; }


############################
if [[ -z $tickets ]]  ; then
    get_tickets
    gen_numbers
else
    gen_numbers
fi

My question is, does anyone know how to modify it to prevent duplicate numbers on each row from appearing? I am guess I'd use uniq, and an array, but am not sure how that would look. Any advice would be appreciated; thanks!

  • This is just a script for fun.
like image 807
tlaffoon Avatar asked Feb 04 '26 23:02

tlaffoon


1 Answers

Your attempt is pretty good. However, I think it can be easier and safer to get random values by using the shuf command:

$ shuf -i 1-49 -n18 | xargs -n6
39 42 43 7 14 23
10 27 5 13 49 8
31 36 19 47 28 4

shuf -i X-Y -nZ gives Z random numbers in between X and Y. Then xargs -nT formats them in groups of T numbers per line.


Update

Now I see the comment:

Yes; to avoid duplicate numbers within a row (by ticket).

In that case, you can simply do shuf -i 1-49 -n6 to get 6 random numbers. The output is line separated, so you can use tr '\n' ' ' to make it space separated.

In case you want many rows, for example 5, you can do:

for i in {1..5}; do shuf -i 1-49 -n6; done | xargs -n6

Sample output:

$ for i in {1..5}; do shuf -i 1-49 -n6; done | xargs -n6
4 45 12 42 37 46
42 20 29 22 12 5
40 41 14 28 4 2
35 24 16 22 2 39
14 46 47 20 21 41
like image 127
fedorqui 'SO stop harming' Avatar answered Feb 07 '26 21:02

fedorqui 'SO stop harming'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!