What I'm trying to accomplish is the following:
I wish to create a vector of integers, from a relatively small range, and ensure that none of the integers will be followed by the same integer.
i.e., This is a "legal" vector: [ 1 3 4 2 5 3 2 3 5 4 ]
and this is an "illegal" vector (since 5 follows 5): [ 1 3 4 2 5 5 2 3 5 4 ]
I've experimented with randi
, and all sorts of variations with randperm
, and I always get stuck when i try to generate a vector of around 100 elements, from a small range (i.e., integers between 1 and 5).
The function just runs for too long.
Here's one of the attempts that i've made:
function result = nonRepeatingRand(top, count)
result = randi(top, 1, count);
while any(diff(result) == 0)
result = randi(top, 1, count);
end
end
Any and all help will be much appreciated. Thanks !
As both RAND and RANDBETWEEN recalculate with every change on the worksheet, your list of random numbers will be continuously changing. To prevent this from happening, use Paste Special > Values to convert formulas to values as explained in How to stop random numbers from recalculating. Delete duplicates.
Generating a Set of Unique Random Numbers in Excel In a column, use =RAND() formula to generate a set of random numbers between 0 and 1. Once you have generated the random numbers, convert it into values, so that it won't recalculate again and again to make your workbook slow.
Algorithm (Steps)Create an empty list which is the resultant random numbers list. Use the for loop, to traverse the loop 15 times. Use the randint() function(Returns a random number within the specified range) of the random module, to generate a random number in the range in specified range i.e, from 1 to 100.
The kind of sequence you are looking for can be defined by generating differences from 1
to top - 1
and then computing the cumulative sum modulus top
, starting from a random initial value:
function result = nonRepeatingRand(top, count)
diff = randi(top - 1, 1, count);
result = rem(cumsum(diff) + randi(1, 1, count) - 1, top) + 1;
end
On my machine, this generates a non-repeating sequence of 10 million numbers out of 1:5 in 0.58 seconds.
you can use the following code for generate Non Repeating Random Numbers from 1 to M
randperm(M);
and for K Non Repeating Random Numbers from 1 to M
randperm(M, K);
enjoy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With