Krishna
Krishna

Reputation: 1362

Weighted randomization based on runtime data in System Verilog

Is there a way to do weighted randomization in System Verilog based on runtime data. Say, I have a queue of integers and a queue of weights (unsigned integers) and wish to select a random integer from the first queue as per the weights in the second queue.

int data[$] = '{10, 20, 30};
uint_t weights[$] = '{100, 200, 300};

Any random construct expects the weights hardcoded as in

constraint range { Var dist { [0:1] := 50 , [2:7] := 50 }; } 

But in my case, I need to pick an element from an unknown number of elements.

PS: Assume the number of elements and weights will be the same always.

Upvotes: 0

Views: 893

Answers (1)

dave_59
dave_59

Reputation: 42698

Unfortunately, the dist constraint only lets you choose from a fixed number of values.

Two approaches I can think of are

  1. Push each data value into a queue using the weight as a repetition count. In your example, you wind up with a queue of 600 values. Randomly pick an index into the queue. The selected element has the distribution you want. An example is posted here.
  2. Create an array of ranges for each weight. For your example the array would be uint_t ranges[][2]'{{0,99},{100,299},{300,599}}. Then you could do the following in a constraint

    index inside {[0:weights.sum()-1]}; foreach (data[ii]) index inside {[ranges[ii][0]:ranges[ii][1]} -> value == date[ii];

Upvotes: 1

Related Questions