-1

I’d like to generate a random number in a given range depending if the input is + or -.

For a positive input I would get a positive number between x and y (4 and 42 actually), for a negative input a number between -6 and -72.

In other words, if the input is +, then rand(4,42), if the input is -, then rand(-6,-72).

I’m just not sure how to string it all together.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
  • The goal is that you add some code of your own to your question to show at least the research effort you made to solve this yourself. – Cyrus Mar 25 '18 at 12:11
  • 1
    Your question should also make clear that you're trying to do this in bash (not just using the "bash" tag). – rwp Mar 25 '18 at 12:40
  • It is good to use some formatting and spacing to make the post more readable. There is no need for "Thank you" notes. – Laurenz Albe Mar 25 '18 at 20:04
  • See also [Random number from a range in a Bash Script](https://stackoverflow.com/questions/2556190/random-number-from-a-range-in-a-bash-script) – agc Mar 26 '18 at 04:56

2 Answers2

0
function myrand() {
    MIN=$1
    MAX=$2
    DELTA=$(( $MAX - $MIN ))
    R=$(( $MIN + $(( RANDOM % $DELTA )) ))
    echo $R
}
echo $(( -1 * $(myrand 6 72) ))
echo $(myrand 4, 42)
  • While this code could solve the problem, it is best to add elaboration and explain how it works for people who might not understand this piece of code. – Papershine Mar 25 '18 at 13:01
  • 1
    Better yet, don't encourage off-topic questions by answering them . – chepner Mar 25 '18 at 14:21
0

Pure bash. Mostly uniform random numbers, (might skew a bit low, but probably good enough), as per OP spec. Feed it input from numbers.txt:

while read x; do echo $((x>=0?RANDOM%39+4:-RANDOM%67+6)); done < numbers.txt

How it works: the arithmetic expr?expr:expr conditional operator is used to test $x, and return an appropriate value, derived from the 15-bit built in $RANDOM variable.

agc
  • 7,973
  • 2
  • 29
  • 50