Generate random numbers with exceptions

Robert

I want to generate a pair of random numbers withing a range but also the pair must not be contained in an array of pairs I have, so you can basically think of the task as generating a random pair with exceptions. I know you can do it with a loop but I've been told it's possible with only one level of indentation. I've been searching around for something similar, so far no results. Your help would be much obliged, cheers.

ndnenkov

Very inefficient, but expressive and short:

range = (1..3).to_a
undesired_pairs = [[1, 1], [2, 2], [3, 3]]
(range.product(range) - undesired_pairs).sample # => [1, 3]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related