# How to get unique values of list of struct based on condition?

I have a list of struct as shown

``````struct probs
A::Tuple{Int64, Int64}; C::Tuple{Int64, Int64}; Cost::Int64
end
pop_vect = [probs((rand(1:20),rand(1:20)),(rand(1:20),rand(1:20)), rand(1:20)) for i = 1:100]
``````

Now I want to get unique values of `pop_vect` so that the Cost is unique.

``````unique(pop_vect)
``````

doesn’t help at all. Thanks for help in advance.

If I understand your question correctly, this should do what you are expecting:

``````unique(prob -> prob.Cost, pop_vect)
``````

This applies the function in the first argument (i.e., checking the cost) to the vector `pop_vect` and then returns all unique elements based on the output of that function.

2 Likes

On second thought, I may have misunderstood what you are looking for. It is possible that what you are expecting is something along the lines of

``````function isonly(obj, itr)
return count(x -> x == obj, itr) == 1
end

costs = [prob.Cost for prob in pop_vect]
answers = [prob for prob in pop_vect if isonly(prob.Cost, costs)]
``````

The previous solution gives one instance of each cost, but this instead gives the list of elements of `pop_vect` for which the cost is the only such cost. As an example, if you generated 10 samples

``````10-element Vector{probs}:
probs((7, 12), (19, 7), 1)
probs((4, 18), (18, 8), 6)
probs((1, 1), (5, 1), 20)
probs((18, 17), (10, 8), 12)
probs((20, 6), (14, 15), 15)
probs((19, 19), (10, 6), 1)
probs((19, 4), (3, 9), 15)
probs((1, 15), (18, 20), 9)
probs((10, 1), (1, 6), 8)
probs((13, 5), (12, 20), 4)
``````

the above code would return

``````6-element Vector{probs}:
probs((4, 18), (18, 8), 6)
probs((1, 1), (5, 1), 20)
probs((18, 17), (10, 8), 12)
probs((1, 15), (18, 20), 9)
probs((10, 1), (1, 6), 8)
probs((13, 5), (12, 20), 4)
``````

Please check which of these solutions matches your desired behavior!

2 Likes