I have an array of 10 elements. How do I output these in random order without repeating.
-
Please add some more detail to the question. Is this testbench code? Does it need to synthesize? What are the "elements"? – zennehoy Sep 27 '13 at 11:11
-
The technique is simple: use a pseudo random number generator to address your array, store if one has already been used, in which case you take the next. The implementation is highly dependent on whether it should be synthesizable or not... – BennyBarns Sep 27 '13 at 11:47
-
@zennehoy this has to be a synthesize-able . Elements are integers in my case. – user2239827 Sep 30 '13 at 04:29
-
@BennyBarns It has to be a synthesizeable code. – user2239827 Sep 30 '13 at 04:30
4 Answers
For a testbench, use the OSVVM random library to generate random indexes into your array. Or you could shuffle it (using the Fischer-Yates Algorithm in concert with the random library).
If it's something you need to synthesize, then put the array into a RAM block, and generate random addresses (for example using a linear feedback shift register).
Be aware that none of these is properly random, only pseudo-random. If you're attempting anything remotely cryptographic, they are unlikely to be what your want.

- 16,395
- 1
- 38
- 56
For testbenches, OSVVM's RandomPkg makes this easy.
library osvvm ;
use osvvm.RandomPkg.all ;
...
RandProc : process
variable RV : RandomPtype ;
variable IndexVals : integer_vector(0 to 9) := (others => integer'low) ;
begin
for i in IndexVals'range loop
-- min max ExcludeList
IndexVals(i) := RV.RandInt( 0, 9, IndexVals) ;
end loop ;
The problem gets more interesting if successive randomly generated permutations of 10 elements need to be different from the previous one. For that I would use the coverage model. Although, 10 is around the maximum number of permutations I would want to do this way though as there are n! permutations and the coverage model will require storage for each permutation generated.

- 3,601
- 10
- 20
A good way to get close to randomness is by using a linear feedback shift register.

- 3,384
- 4
- 31
- 45
If this is for simulation only, you can use the uniform procedure from ieee.math_real to get a real number between 0 and 1, and scale it to the index range of your array.

- 1