3
votes

What is the best way to randomly sample an associative array? I have tried the following but the randomize method always fails.

std::randomize(idx) with {assoc_array.exists(idx);};

I guess I can call next method a random number of times starting from the first element of the associative array to achieve what's needed. However, is there a better way? Why wouldn't the constrained randomization above work?

1

1 Answers

6
votes

The problem is when you have a function call in a constraint, the input arguments to the function are randomized first, and then the result is treated like a state variable when passed to the function. If the function returns false, the constraint fails, and idx is left unmodified. If it happens to choose an idx that does exist, then the constraint passes. I'm assuming the probability of picking an idx that exists is very low.

What I suggest is to put all of the indexes into an array, and then randomly select one of them

typedef bit [11:0] index_type; // or whatever your index type is
int assoc_array[index_type];
index_type idx, index_list[$];
...
index_list = assoc_array.find_index() with ('1);
std::randomize(idx) with {idx inside {index_list}};