2

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.

3
  • How large is the range? Depending on the possible combinations an easy solution might be to generate all possible pairs, then use Array#sample to grab a random one from there. Next you can delete the pair so it will not be fetched again. Commented Oct 18, 2015 at 8:49
  • Are you drawing elements of each pair with or without replacement? For example, could you randomly select [5,5] (with replacement)? If you've drawn [4,5], would [3,5] be a valid draw? Lastly, why the rush to select an answer? Commented Oct 18, 2015 at 9:24
  • The range will be relatively small, max 20 by 20. And yes, that would be a valid draw. I had selected a random answer so quickly because I had a deadline to catch and he had met it. Commented Oct 18, 2015 at 11:00

2 Answers 2

3

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] 
Sign up to request clarification or add additional context in comments.

Comments

0

Another solution: Create a random pair until you have a result, that is not in undesired_pairs:

undesired_pairs = [[1, 1], [2, 2], [3, 3]] until ! undesired_pairs.include?(hit =[rand(3)+1,rand(3)+1]) end p hit 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.