Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

Array methods example, sort by two dimensions

SystemVerilog Arrays

Runnable example from the Systemverilog Array Manipulation tutorial.

Open in IDE
testbench.sv
//--------------------------------------------------------------
// Author  : Admin, ChipVerify
// Website : www.chipverify.com
//--------------------------------------------------------------

class Register;
  string name;
  rand bit [3:0] rank;
  rand bit [3:0] pages;
  
  function new (string name);
    this.name = name;
  endfunction
  
  function void print();
    $display("name=%s rank=%0d pages=%0d", name, rank, pages);
  endfunction
  
endclass

module tb;
  Register rt[4];
  string name_arr[4] = '{"alexa", "siri", "google home", "cortana"};
  
  initial begin
    $display ("\n-------- Initial Values --------");
    foreach (rt[i]) begin
      rt[i] = new (name_arr[i]);
      rt[i].randomize();
      rt[i].print();
    end
    
    $display ("\n--------- Sort by name ------------");
    
    rt.sort(x) with (x.name);
    foreach (rt[i]) rt[i].print();
    
    $display ("\n--------- Sort by rank, pages -----------");
    
    rt.sort(x) with ( {x.rank, x.pages});
    foreach (rt[i]) rt[i].print();
  end
endmodule
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.