Finding unique values

Changed my question

Am having two lists

list1 = [
           a: [{:t, 1}, {:s, 1}], 
           a: [{:t, 2}, {:s, 1}, {:g, 1}]
          ]

list2 = [
           a: [{:t, 2}, {:s, 1}] 
          ]

Now I just want to see if list2 is a member of list1. As we can see list2 is not a member of list1 because the :t value is different in both cases.

Can there be any way that we compare these two based on the atoms and if that’s true or false.

so the above will give us true as list2 is in list1

It’s not clear to me what are the criteria for the output. Have you tried writing down more examples and maybe unit tests for this?

2 Likes

I have changed my structure a bit so now i am having two lists

list1 = [
           a: [{:t, 1}, {:s, 1}], 
           a: [{:t, 2}, {:s, 1}, {:g, 1}]
          ]

list2 = [
           a: [{:t, 2}, {:s, 1}] 
          ]

Now i just want to see if list2 is the member of list1. As we can see list2 is not member of list1 because the :t value is different in both cases.

Can there be any way that we compare these two based on the atoms and if that’s true or false.

so the above will give us true as list2 is in list1

So to have a true return you would need to:

  1. Have matching keyword list keys;
  2. Have a second list that’s contained inside the list in the first list?

If I’m understanding correctly, you don’t want the comparison affected by the innermost integer values? So we can use Enum.map/2 with Kernel.elem/2 to remove the irrelevant data. Then maybe Enum.all?/2 to check the top level lists - something like this?

comp_1 = Enum.map(list_1, &elem(&1, 0))
comp_2 = Enum.map(list_2, &elem(&1, 0))

Enum.all?(comp_2, &(&1 in comp_1))

But this uses quadratic time complexity due to the data structure you are using, which must traverse the whole list to check for membership. You will probably want to involve another transformation involving Map or MapSet if this is to be run on large lists.

Sorry, but your explanation is unclear and we’re still trying to guess what you’re trying to achieve.

I don’t think you meant that. You can check list membership with in like so: 1 in [1, 2, 3].

As we can see list2 is not member of list1
(…)
so the above will give us true as list2 is in list1

This seems self-contradictory. Unless you meant a subset?

1 Like