How do you get all the unique elements of an array? Is there an array method that do it?
I know there is an array method called “unique()” but this does not actually return the ‘unique’ elements of the array but rather return a ‘unique version of the array’, where all elements are unique.
For example, let’s say the array is,
int array = {2,5,6,5,1};
If you use the unique method, the output is,
{2,5,6,1}
Notice that the array size has reduced to 4. The elements are now unique. Index 4 of the original array has been removed because it is equal to index 1.
This is not what I want.
What I want is to return only the unique elements of the array like this,
{2,6,1}
Notice that the element whose value is 5 is not included since it is not unique within the array.
It’s possible to write a code to do this, but what I’m asking is if there’s already a system task or an existing array method available that do this?
As Dave said, the answer is No, I liked the problem so did a small code to do what you wanted (I see you already said you can do it yourself anyway).
module m;
int array[] = {2,5,6,5,1};
int u_q [$];
int t_q [$];
initial begin : test
foreach (array[i]) begin : b1
t_q = array.find with (item == array[i]);
if (t_q.size == 1)
u_q.push_back (array[i]);
end : b1
$display ("orig: %p u_q: %p", array, u_q);
end : test
endmodule : m
@Srini:
Thanks for the code.
I asked the question because, you know, in programming, it’s better to have the least number of lines that can do the same thing than to have a code with so many lines. It is beneficial for code readability and debugging.
Anyway, like Dave said, there’s no built-in method for it so the only option is to write a code.