1
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ You want to store k pairs? $\endgroup$ – Kuba Mar 30 '14 at 9:39
1
$\begingroup$

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
$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – Shellp Mar 30 '14 at 10:15
  • $\begingroup$ @Shellp so you need to store them if you want to check if such pair was generated earlier. $\endgroup$ – Kuba Mar 30 '14 at 10:30
  • $\begingroup$ Thank you so much !! Your method is truly efficient and useful. $\endgroup$ – Shellp Mar 30 '14 at 11:03
0
$\begingroup$

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

$\endgroup$
  • $\begingroup$ @Kuba my mistake...misunderstood $\endgroup$ – ubpdqn Mar 30 '14 at 9:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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