3
$\begingroup$

First off. I am not a mathematician I am a linguist, a syntactician who is trying to say something about semantics, which in the case at hand can be largely understood to reduce to set theory. That being said I apologize beforehand if my question is "stupid" in any way. Nonetheless, I require help and i would be grateful if anyone could provide it:

The algorithm, the basis of which was by and large provided to me by a really nice user, is supposed to unify the sets within an input set iff they have no intersection. The resulting sets should then be again unified with each other, this time with no condition on their intersection holding, until there's nothing to unify with anymore. In the end I want all the resulting sets to be in one set. The sets should be sorted according to their size and free of dublicates. The latter is a problem. Deleteduplicates does not eliminate. Instead it creates subsets (?). Here's the code:

input = Flatten[
   Table[{Subscript[M, i], Subscript[W, j]}, {i, 1, 3}, {j, 1, 3}], 1];
outputs = {}; input[[]]
(* {{Subscript[M, 1], Subscript[W, 1]}, {Subscript[M, 1], 
  Subscript[W, 2]}, {Subscript[M, 1], Subscript[W, 3]}, {Subscript[M, 
  2], Subscript[W, 1]}, {Subscript[M, 2], Subscript[W, 
  2]}, {Subscript[M, 2], Subscript[W, 3]}, {Subscript[M, 3], 
  Subscript[W, 1]}, {Subscript[M, 3], Subscript[W, 2]}, {Subscript[M, 
  3], Subscript[W, 3]}} *)

  newset = {};
  For[i = 1, i < Length[input], i++,
    For[j = i + 1, j <= Length[input], j++,
      If[Intersection[input[[i]], input[[j]]] == {},
          AppendTo[newset, Union[input[[i]], input[[j]]]]
        ] (*close If*)
      ] (*close For*)
    ]; (*close For*)

newset = DeleteDuplicates[newset];
outputs = DeleteDuplicates[outputs];
AppendTo[outputs, newset];
input = newset;
(*close While*)

While[Length[input] > 0,
   newset = {};
   For[i = 1, i < Length[input], i++,
     For[j = i + 1, j <= Length[input], j++,
             AppendTo[newset, Union[input[[i]], input[[j]]]
         ] (*close If*)
       ] (*close For*)
     ]; (*close For*)

 newset = DeleteDuplicates[newset];
 outputs = DeleteDuplicates[outputs];
 AppendTo[outputs, newset];
 input = newset;
 ]; (*close While*)
Final = Flatten [outputs, 1];
Final = DeleteDuplicates[outputs];
Sort [Flatten [Final, 1]]
$\endgroup$
6
$\begingroup$

You need to use DeleteDuplicates after you Flatten the list, otherwise it will not work properly (if duplicates are in different sublists, then your DeleteDuplicates call will not find them).

The direct fix is therefore to change the last few lines to this:

Final = Flatten [outputs, 1]
DeleteDuplicates@Sort [Flatten [Final, 1]]
$\endgroup$
  • $\begingroup$ Thank you! Why is Flatten applied twice here? $\endgroup$ – user3201 Nov 5 at 23:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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