4
$\begingroup$

Assume that

A = Permutations[{1, 2, 3}]

enter image description here

AND $$C=\{1,2\}$$ I want to apply this process $X=C\subset A$ The output is $$X=\{1,2,3\},\{2,1,3\}$$

How can the array row be selected according to the elements in the subset

My attempts

Select[{{1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 
   1}}, MemberQ[1, 2, #] &]

The output is

enter image description here

a = Permutations[{1, 2, 3, 4, 5, 6, 7, 8}]; c = {2, 3, 4} Select[a, ContainsAll[#[[1 ;; 2 ;; 3]], c] &] 

How can the answer be generalized?

$\endgroup$
4
  • $\begingroup$ Could you explain the operation you are doing? I don't understand how to arrive at the output you indicated. $\endgroup$
    – MarcoB
    May 10, 2022 at 17:04
  • 2
    $\begingroup$ My guess is that he is only checking the first two elements of each triple. $\endgroup$
    – Carl Woll
    May 10, 2022 at 17:10
  • $\begingroup$ I need to checking the first two elements of each triple $\endgroup$ May 10, 2022 at 17:15
  • $\begingroup$ @MarcoB I need to checking the first two elements of each triple $\endgroup$ May 10, 2022 at 17:16

2 Answers 2

7
$\begingroup$
a = Permutations[{1, 2, 3}]
c = {1, 2}

Select[a, ContainsAll[#[[1 ;; 2]], c] &]

(* Out: {{1, 2, 3}, {2, 1, 3}} *)
$\endgroup$
3
  • $\begingroup$ Many thanks for this valuable help: this is what I was looking for. I am grateful to you $\endgroup$ May 10, 2022 at 17:24
  • $\begingroup$ a = Permutations[{1, 2, 3, 4, 5, 6, 7, 8}]; c = {2, 3, 4} Select[a, ContainsAll[#[[1 ;; 2 ;; 3]], c] &] How can the answer be generalized? $\endgroup$ May 10, 2022 at 17:47
  • $\begingroup$ @Math-babylon To check the first three elements of the sets, you should use ContainsAll[ #[[1;;3]], c]& instead. Look up Part in the documentation. $\endgroup$
    – MarcoB
    May 10, 2022 at 17:59
3
$\begingroup$

Using SubsetQ:

a = Permutations[{1, 2, 3}];
c = {1, 2};

Pick[a, SubsetQ[#, c] & /@ a[[All, 1 ;; 2]]]

OR

Select[a, SubsetQ[#[[1 ;; 2]], c] &]

Using OrderlessPatternSequence:

Pick[a, MatchQ[#[[1 ;; 2]], {OrderlessPatternSequence[
      Sequence @@ c]}] & /@ a]

OR

Select[MatchQ[#[[1 ;; 2]], {OrderlessPatternSequence[
      Sequence @@ c]}] &][a]

Result:

{{1, 2, 3}, {2, 1, 3}}

$\endgroup$
2
  • $\begingroup$ a = Permutations[{1, 2, 3, 4, 5, 6, 7, 8}]; c = {2, 3, 4} How can the answer be generalized? $\endgroup$ May 10, 2022 at 17:51
  • $\begingroup$ As an example: Pick[a, SubsetQ[#, c] & /@ a[[All, 1 ;; Length@c]]] would have 720 entries. $\endgroup$
    – Syed
    May 10, 2022 at 17:58

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.