An efficient code to determine if a set is a subset of another set

前端 未结 4 2398
悲哀的现实
悲哀的现实 2021-02-20 04:27

I am looking for an efficient way to determine if a set is a subset of another set in Matlab or Mathematica.

Example: Set A = [1 2 3 4] Set B = [4 3] Set C = [3 4 1] Set

4条回答
  •  囚心锁ツ
    2021-02-20 05:06

    In Mathematica I propose using Alternatives for this.

    For example, if we have a set {1, 2, 3, 4} and we wish to test if set x is a subset we could use: MatchQ[x, {(1|2|3|4) ..}]. The advantage of this construct is that as soon as an element which does not belong is found the test will stop and return False.

    We can package this method as follows:

    maximal[sets_] :=
      Module[{f},
        f[x__] := (f[Union @ Alternatives @ x ..] = Sequence[]; {x});
        f @@@ sets
      ]
    
    maximal @ {{1, 2, 3, 4}, {4, 3}, {5, 1}, {3, 4, 1}, {4, 3, 2, 1}}
    
    {{1, 2, 3, 4}, {5, 1}}
    

提交回复
热议问题