How to randomly pick two elements of an array of size 100?

Hi,

For Example:

int a[100];

foreach(a[i]) begin
a[i]=i;
end

Now i want to randomly pick any of two element values from the above array?

is there any method in an array?

There are many ways you could do this, but simplest would be to use a.shuffle(), then pick a[0] and a[1].

You could also do

int val1, val2;

std::randomize(val1,val2) with {unique {val1,val2}; val1 inside {a}; val2 inside {a};};

In reply to dave_59:

Hi Dave,

How to pick an element from an associative array randomly?
I have a requirement that I need to read from an already written location. I store the start address of that location as associative array index and length of that write as that index’s element.


int sa_and_dwlen_arry[int];

I will check the size before a read, but how to chose a start address and length randomly? Can we shuffle an associative array also? If so, the element should also move along with index, right?
Or I need to use array of struct where struct will contain both start address and length?

-mpattaje

In reply to pkoti0583:

Hello pkoti0583!!!

Here is one way to solve the question:

class packet;

	rand int array [];
	
	constraint array_elements_limit {
			
			foreach(array[i]) {
	
				array[i] inside {[1000:2000]};
																
					   }
															
				          }
									 
	constraint unique_elements_inside {
							
			foreach(array[i]) {
											
				unique {array};
																	
					   }

		                          }
		
	constraint array_size_limit {array.size inside {100};}
	
	
endclass

module pick_two_elements;

   initial 
	
	begin
		
	     packet pkt = new();
		
	     pkt.randomize();
		
	     $display("\nThe size of the array is : %0d", pkt.array.size);
					
	     foreach(pkt.array[i])
					
		begin
						
		   $display("\narray[%0d] = %0d",i,pkt.array[i]);
					
		end
					
	     $display("\nThe two random values picked from the array are : ");
					
	     repeat(2)
					
		begin
						
		     $display("\n%0d",pkt.array[$urandom_range(0,pkt.array.size - 1)]);
						
		end
						
	     $display("------------------------------------------------------------------");
					
	end

endmodule

Hope it helps :)