3
$\begingroup$

How can we extract from the list

lsts = {{1, 2, 3}, {1, 2, 4}, {1, 8, 3, 7}, {1, 8, 9, 100}, {7, 8, 1, 3}, {1, 7, 3, 8}, {0, 0, 7, 0}, {1, 0, 2, 4}, {1}, {8}, {1, 2}, {9, 8, 5, 8},{1,1,3,3,3,7,7,7,7,8,9,9}}

those sublists that contain the same elements as the specified list

{1, 3, 7, 8}

and have the same number of elements, without altering the original order of the elements in the list

to get the result:

{{1, 8, 3, 7}, {7, 8, 1, 3}, {1, 7, 3, 8}}

My approach is as follows:

lsts = {{1, 2, 3}, {1, 2, 4}, {1, 8, 3, 7}, {1, 8, 9, 100}, {7, 8, 1, 
   3}, {1, 7, 3, 8}, {0, 0, 7, 0}, {1, 0, 2, 4}, {1}, {8}, {1, 2}, {9,
    8, 5, 8}, {1, 1, 3, 3, 3, 7, 7, 7, 7, 8, 9, 9}}
target = {1, 3, 7, 8}
result = Select[lsts, Sort@# == Sort@target &]

What other methods can be used to achieve this requirement?

$\endgroup$
1
  • 3
    $\begingroup$ Sort the target when it is defined target = Sort@{1, 3, 7, 8}; so you don't need to Sort the target for each comparison. $\endgroup$
    – Bob Hanlon
    Commented Apr 29 at 2:55

4 Answers 4

5
$\begingroup$
list =
  {{1, 2, 3}, {1, 2, 4}, {1, 8, 3, 7}, {1, 8, 9, 100}, 
   {7, 8, 1, 3}, {1, 7, 3, 8}, {0, 0, 7, 0}, 
   {1, 0, 2, 4}, {1}, {8}, {1, 2}, {9, 8, 5, 8}, 
   {1, 1, 3, 3, 3, 7, 7, 7, 7, 8, 9, 9}};

target = {1, 3, 7, 8};

Select[list, ContainsExactly @ target]

{{1, 8, 3, 7}, {7, 8, 1, 3}, {1, 7, 3, 8}}

Cases[list, {OrderlessPatternSequence @@ target}]

{{1, 8, 3, 7}, {7, 8, 1, 3}, {1, 7, 3, 8}}

via Position using Extract

p = Position[list, x_ /; ContainsExactly[x, target], 1]

{{3}, {5}, {6}}

Extract[list, p]

{{1, 8, 3, 7}, {7, 8, 1, 3}, {1, 7, 3, 8}}

$\endgroup$
4
$\begingroup$

What other methods can be used to achieve this requirement?

I am sure there are at least 10 different ways to do this. One could be

Select[lsts, Length[Union[#, target]] == Length[#] &]

enter image description here

$\endgroup$
1
  • $\begingroup$ Select[lsts,Norm[#]==Norm[target]&] $\endgroup$
    – Bill
    Commented Apr 29 at 3:04
4
$\begingroup$

Since you are looking for any permutation of elements, you can do the following:

lsts = {{1, 2, 3}, {1, 2, 4}, {1, 8, 3, 7}, {1, 8, 9, 100}, {7, 8, 1, 
    3}, {1, 7, 3, 8}, {0, 0, 7, 0}, {1, 0, 2, 4}, {1}, {8}, {1, 
    2}, {9, 8, 5, 8}, {1, 1, 3, 3, 3, 7, 7, 7, 7, 8, 9, 9}};

elems = {1, 3, 7, 8};
p = Permutations[elems, {Length@elems}];

Select[lsts, MemberQ[p, #] &]

{{1, 8, 3, 7}, {7, 8, 1, 3}, {1, 7, 3, 8}}

$\endgroup$
2
$\begingroup$

Select[lsts, ContainsAll[#, {1, 3, 7, 8}] && Length[#] == 4 &]

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.