WeBWorK Problems

Generate Different Random Numbers

Generate Different Random Numbers

by Curtis Card -
Number of replies: 2

Can anyone explain how to force the generation of two different random numbers. If when

$a = random(-4,5,1);
$b = random(-5,6,1);

we get  $a  and $b are equal, how can I create a loop that will force one of them, say $b, to be a different random number? Or is there a better way to accomplish this.

This comes from the recently published Rogawski problem set.  The code assumes that $a and $b are different and fails to recognize the correct answer when they are equal.

In reply to Curtis Card

Re: Generate Different Random Numbers

by Gavin LaRose -
Hi Curtis,

I've usually done this by taking

$a = random(-4,5,1);
$b = $a + non_zero_random(-1,1,1);

I try to avoid loops with ambiguous termination conditions (e.g.,

$a = random(-4,5,1);
$b = random(-5,6,1);
while ($a == $b) { $b = random(-5,6,1); }

) because of my well-demonstrated inability to anticipate cases when the loop won't terminate as I expect.

Gavin
In reply to Gavin LaRose

Re: Generate Different Random Numbers

by Rob Owen -
I actually wrote an extensive routine that will let you choose random variables, in a systematized way, to defeat that sort of thing. The invocation is kind of nightmarish -- I chose it the way I did for a reason, although I'm no longer convinced this was the right way -- but if you don't mind cutting and pasting you can do something like this:

randomListByRef( sub { my $arr; my ($C,$P,$R) = @_;
return ( byOr($arr, @_) && gcd($P,$R) == 1 ); },
[~~$aConst, 2, 7], [~~$aPower, 2, 7], [~~$aRoot, 2, 7] );


which would let you pick three new numbers $aConst, $aPower and $aRoot from 2-7 such that a) at least one of them is different from their original/current value [that's the byOr function call] and b) aPower and aRoot are relatively prime [that's the gcd part]. If anyone's interested, I'd be happy to provide the code for it.

[The random loop terminates stochastically, btw; in general, I've found that if the right combination of random numbers can't be found in 100 guesses, I probably programmed the condition wrong.]