0
$\begingroup$

How do i create 2 lists of RandomIntegers that are the same at certain points based on a condition.

For example there are three lists:

  • List A
  • List B
  • List C

List C already exists. I am trying to create A and B. A and B should be the same at position x if list C is equal to 4 at that position and should be a random number otherwise.

$\endgroup$
  • 1
    $\begingroup$ For positions where $C$ does not equal $4$, you say $A$ and $B$ should have the same value. What value? $\endgroup$ – David G. Stork Nov 1 '18 at 19:55
  • $\begingroup$ A RandomInteger as well but both should be the same $\endgroup$ – Bryan Nov 1 '18 at 19:56
2
$\begingroup$

An inelegant, but (hopefully) clear method:

myC = {3, 5, 4, 6, 7, 4, 8, 4};
myA = Table[RandomInteger[10] , Length[myC]];
myB = Table[RandomInteger[10] , Length[myC]];
Table[If[myC[[i]] == 4, myB[[i]] = myA[[i]]], {i, Length[myC]}];
$\endgroup$
1
$\begingroup$

You could find the positions where C is 4, and then make sure that A and B have the same value there:

toAB[c_, pos_, max_] := With[{f = Pick[Range@Length@c, c, pos]},
    {a,b} = RandomInteger[max, {2, Length@c}];
    a[[f]] = b[[f]] = RandomInteger[max, Length[f]];
    {a,b}
]

For example:

SeedRandom[1]
c = RandomInteger[10, 20]

{1, 4, 0, 7, 0, 0, 8, 6, 0, 4, 1, 8, 5, 1, 1, 1, 3, 2, 10, 1}

Then:

toAB[c, 4, 10]

{{6, 4, 2, 6, 4, 5, 4, 3, 0, 9, 3, 5, 3, 0, 3, 2, 3, 9, 5, 1}, {5, 4, 3, 9, 1, 0, 4, 4, 1, 9, 2, 7, 9, 9, 8, 10, 0, 10, 10, 7}}

Or, positions where C is 1:

toAB[c, 1, 10]

{{0, 6, 3, 2, 1, 1, 6, 1, 1, 6, 7, 6, 5, 10, 7, 10, 7, 9, 1, 3}, {0, 10, 3, 5, 2, 3, 1, 2, 5, 10, 7, 3, 6, 10, 7, 10, 10, 3, 4, 3}}

(note that the incremental time for creating additional random integers from a single RandomInteger call is negligible)

$\endgroup$
  • $\begingroup$ The Pick-trick is great! I would have used the significantly slower Flatten[Position[c,pos]]. $\endgroup$ – Henrik Schumacher Nov 1 '18 at 20:32
  • 1
    $\begingroup$ @Henrik In the old days, creating SparseArray objects and extracting properties was the fastest way to do this sort of thing. When Pick was optimized to work with packed arrays, Pick became the fastest, most straight-forward way. $\endgroup$ – Carl Woll Nov 1 '18 at 20:34
0
$\begingroup$

There are lots of ways of doing this. Here we make myA and myB random, find the places where c is 4 using the Position command, and then force myB to be the same as myA at all those places:

myC = {3, 5, 4, 6, 7, 4, 8, 4};
myA = RandomInteger[10, Length[myC]];
myB = RandomInteger[10, Length[myC]];
pos = Flatten[Position[myC, 4]];
myB[[pos]] = myA[[pos]];
$\endgroup$

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.