-1

Using a bash script, I want to choose a random number from such a list: [0, X, 2X, 3X, 4X, ..., Y] where Y=k*X and k is an integer. X and Y are just some input numbers by the user. To clarify the question, here is an example:

X=2
#Y=10*X
Y=20
# The <desired_command> to choose a random number from [0, 2, 4, 6, 8, ..., 20] --> sample output=12
desired_command

How can I do this?

  • 2
    Possible duplicate of [How to generate random number in Bash?](https://stackoverflow.com/questions/1194882/how-to-generate-random-number-in-bash) – jonrsharpe Oct 22 '19 at 09:22
  • @jonrsharpe I want to solve the alignment issue here not the range. I think this link doesn't tackle with the alignment problem – Arghavan Mohammadhassani Oct 22 '19 at 09:46
  • The answer on the duplicate **also** shows you how to get it within a range, which I think is what you mean by "alignment problem". This is just basic arithmetic - get a number in the range `[0, Y / X]` using modulo (`%`), then multiply by `X`. – jonrsharpe Oct 22 '19 at 09:47
  • `[0, X, 2X, 3X, 4X, ..., Y]` - just multiply the random number from the list `[0,1,2,3,4...Y]` by `X`?? – KamilCuk Oct 22 '19 at 09:50
  • @KamilCuk No. Since Y is the end of the range not YX – Arghavan Mohammadhassani Oct 22 '19 at 10:50
  • @jonrsharpe Think it works – Arghavan Mohammadhassani Oct 22 '19 at 10:51
  • `of these numbers can be` - your post if very unclear. Is this somehow a generated list? What examples can be given for `X` and `Y`? Do you want to generate a list of multiplicities of a number up to a given number and choose a random number from that list? Is the list of the numbers in random order? The "aligned to a fixed value" I believe is the most confusing part, can you rephrase it? – KamilCuk Oct 22 '19 at 10:53
  • @KamilCuk I want to generate a list of multiplicities of a number (i.e. X) up to a given number (i.e. Y) and choose a random number from that list (i.e. the desired output) – Arghavan Mohammadhassani Oct 22 '19 at 11:17

2 Answers2

1

You can use this command:

echo $(($(shuf -i 0-$((Y/X)) -n1)*X))
1
# x positive integer
# y positive integer y >= x
x=11
y=34
echo $(((RANDOM % (y/x+1)) * x))

Kamoo
  • 832
  • 4
  • 11