How to avoid "doubling up" in a RNG?
2 views (last 30 days)
Show older comments
So, I've found a way to get my code to run 6 times through, but I've encountered a different problem. Since I'm using a random number generator to select which squares to turn the 0 to a 1, it's possible for my random number generator to select the same square twice. I want to ensure that the squares selected are unique. Once again, any help would be appreciated. EDIT: I have to use a for loop, not a while loop
x = zeros(10,10);
for i = 1:6
m = randi(10)
n = randi(10)
if x(m,n) == 0
x(m,n) = 1;
elseif x(m,n) == 1
end
end
3 Comments
David Fletcher
on 3 Apr 2021
Edited: David Fletcher
on 3 Apr 2021
Ahh, the vagaries of education. You could always break the for loop on the six ones condition, if only to highlight the asinine.
x = zeros(10,10);
for iter=1:inf
m = randi(10)
n = randi(10)
x(m,n) = 1;
if sum(x,'All')>5
break
end
end
Answers (1)
the cyclist
on 3 Apr 2021
Here is one way to do what I think you mean:
x = zeros(10,10);
% For M and N, select 6 random integers from 1:10.
M = randperm(10,6);
N = randperm(10,6);
for i = 1:6
% Select each (m,n) in order from (M,N)
m = M(i);
n = N(i);
if x(m,n) == 0
GB(m,n) = 1;
elseif x(m,n) == 1
end
end
2 Comments
Walter Roberson
on 3 Apr 2021
??
What is GB here?
The code you used cannot set two values in the same row (or the same column), so it does not need to do the test. However, the original homework seems to have the possibility that multiple values in the same row could occur.
the cyclist
on 3 Apr 2021
sigh
I'm guessing that @Connor K Riggs changed the code in their question. I copy/pasted the original, and did nothing other than change it so that there would be no repeated (m,n) values.
Caveat emptor my answer.
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!