Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Assume following code :

Do[
   i1 = RandomInteger[{1, 5}];
   i2 = RandomInteger[{1, 5}];
   While[i1 == i2,  i2 = RandomInteger[{1, 5}]] 
   , {k, 1, 4}];`

This code makes two RandomIntegers which are i1 and i2. I have used While loop to avoid making repeated Random numbers in each iteration. But I don't know how it is possible to avoid making repeated Random numbers in whole iterations. For example, following result is the answer after 4 iteration and it is not acceptable :

 i1=1, i2=2
 i1=3, i2=2
 i1=1, i2=2
 i1,4, i2=1 

i1=1 and i2=2 are repeated twice after 4 iterations.

I would be appreciated if someone could help me with this problem.

share|improve this question
    
You want to store k pairs? –  Kuba Mar 30 at 9:39

2 Answers 2

up vote 1 down vote accepted

Memory inefficient approach:

RandomSample[
             DeleteCases[Tuples[Range[5], {2}], {n_, n_}],
             5]

or alternatively with Subsets.

RandomSample[Join[{##}, Reverse /@ {##}] & @@ Subsets[Range[5], {2}], 5]

Time inefficient approach:

list = {};
Do[
 While[
    While[Equal @@ ({i, j} = RandomInteger[5, 2])];
    MemberQ[list, {i, j}]
    ]
   list = Join[list, {{i, j}}];
 , {5}]

list
share|improve this answer
    
In fact, I don't want to store the i1 and i2 ! i1 and i2 are inputs for another loop and calculation. I just want to make different random Integers(i1 not equal to i2) in each iteration and for next iterations, I want different i1 and i2 from those which are made in previous itarations. –  Shellp Mar 30 at 10:15
    
@Shellp so you need to store them if you want to check if such pair was generated earlier. –  Kuba Mar 30 at 10:30
    
Thank you so much !! Your method is truly efficient and useful. –  Shellp Mar 30 at 11:03

EDIT (after Kuba comment)

You can use RandomSample ,e.g

If the aim is sampling from {1,2,3,4,5}^2:

RandomSample[Tuples[Range[5], 2]]

yielding

{{4, 2}, {4, 3}, {1, 4}, {5, 3}, {1, 1}, {5, 1}, {2, 1}, {2, 4}, {2, 
  5}, {5, 2}, {1, 2}, {1, 5}, {3, 3}, {4, 5}, {5, 5}, {3, 4}, {2, 
  2}, {5, 4}, {3, 5}, {1, 3}, {4, 1}, {3, 2}, {2, 3}, {3, 1}, {4, 4}}

Clearly any sample of length >25 must have a repeated pair

If the diagonal elements are 'bad pairs' then:

RandomSample[
 With[{tup = Tuples[Range[5], 2]}, 
  Pick[tup, Not[First@# == Last@#] & /@ tup]]]

This was an uglier way than Kuba's DeleteCases

share|improve this answer
    
@Kuba my mistake...misunderstood –  ubpdqn Mar 30 at 9:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.