Array Manipulation Methods in SystemVerilog

System Verilog offers several built-in methods to work with arrays. These methods can be applied to static, dynamic arrays and queue, providing flexibility in managing data. Here’s a look at each of these methods and how they work:

1. find() and find_index() Methods

The find method searches for elements in an array that satisfy a given condition and returns them in a new array. The find_index method, similarly, returns an array of indices of elements that match the condition. The with keyword in System Verilog is used in conjunction with array methods like find and find_index to specify the condition or filter expression for the search. It allows you to define a lambda-like inline function that evaluates each element of the array against the given condition.

  • Syntax:
  • Example:

Output:

2. min() and max() Methods

The min and max methods return the minimum and maximum values in the array, respectively.

  • Syntax:
  • Example:

3. sum() Method

The sum method calculates the sum of all elements in the array.

  • Syntax:
  • Example:

4. product() Method

The product method calculates the product of all elements in the array.

  • Syntax:
  • Example:

5. sort() Method

The sort method sorts the array in ascending order. This is useful when you need to organize data or perform binary search operations on sorted arrays.

  • Syntax:
  • Example:

You can also use a comparison function to customize sorting behavior:

6. rsort() Method

The rsort method sorts the array in descending order.

  • Syntax:
  • Example:

7. reverse() Method

The reverse method reverses the order of elements in the array, making it useful when you need to invert the order of elements without sorting.

  • Syntax:
  • Example:

8. shuffle() Method

The shuffle method randomly shuffles the elements of the array. It’s commonly used in verification for creating randomized test cases.

  • Syntax:
  • Example:

9. unique() Method

The unique method removes duplicate elements from the array, keeping only the first occurrence of each element.

  • Syntax:
  • Example:

10. and() and or() Methods

The and and or methods return the bitwise AND or OR of all elements in the array. These methods are handy when you need to apply logical operations across an array of values.

  • Syntax:
  • Example:

Practical Example: Using Array Methods in SystemVerilog

Let’s look at an example to see how some of these methods can be applied in practice. The code below demonstrates initializing an array and using different array manipulation methods:

Output: