2

I'm working on a bash script to basically play Rock Paper Scissors against the CPU. The problem I'm having is that I can't get it to randomly pick between variables, instead it just picks the first variable noted. Here is the section of code that needs work:

r="rock"
p="paper"
s="scissors"
RPS=$r||$p||$s    #The line that needs to be fixed
#rps=$r||$p||$s works but only outputs rock...
echo $RPS

I've tried looking for ways to do this on forums but google only pops up forums for randomly picking lines from another file and not within the file itself.

2 Answers 2

4
declare -a values=(rock paper scissors)
echo "${values[$(( $RANDOM % ${#values[*]} ))]}"
Sign up to request clarification or add additional context in comments.

4 Comments

This solution is more throughout than mine for it does not hardcoded the size of the array (3).
That worked pretty well...now I'm just having a problem with it deciding wins, loss, and draw -_- If I pick Rock no matter what the Cpu picks it's a draw. If I pick Paper I always win. If I pick Scissors the CPU always wins...
Well I fixed that and everything is running great
An array subscript is already an arithmetic context so $(()) isn't necessary.
2

How about something like this:

choices=(rock paper cissors) # Define an array with 3 choices
RPS=${choices[$RANDOM%3]}    # Pick one at random

Discussion

Bash has a built-in variable called $RANDOM, which returns a random integer.

2 Comments

I knew bash had a built-in random function (just like batch) but I couldn't figure how to use it in the manner I needed, but thanks now I know how to use it better!
I ended up using this method and the program is running great!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.