Resalte elementos en la lista usando la coincidencia de patrones

Nov 27 2020

A partir de lo siguiente list:

list = {{a, b, c}, {d, e, f}, {g, h, i}, {b, c, d}, {c, a, m}, {c, d, n}};

Quiero resaltar elementos en listcuya intersección sea mayor que 2.

El siguiente código no puede obtener el resultado que quiero:

list //. 
   {{a___, x:{_, _, _}, b___, y:{_, _, _}, c___} /; 
      Length@Intersection[x, y] >= 2 :> 
         {a, Style[x, Gray], b, Style[y, Gray], c}}

El resultado deseado es

También lo consideré Gather, pero cambiará el orden de la lista.

Actualizado:
pensé en una forma, no elegante

list //. {a___,x:({_,_,_}|F[{_,_,_}]),b___,y:({_,_,_}),c___}/;
  Length[Intersection[x/.F->Identity,y]]>=2:>{a,F@x,b,F@y,c}
% /. F->Highlighted

Respuestas

3 kglr Nov 27 2020 at 00:57
rg = RelationGraph[UnsameQ @ ## && Length@Intersection[##] >= 2 &, list]

hl = VertexList @ EdgeList @ rg
{{a, b, c}, {b, c, d}, {c, a, m}, {c, d, n}}
list /. x : Alternatives @@ hl :> Style[x, Gray] 

list /. x : Alternatives @@ hl :> Highlighted[x, BaseStyle -> Red]

HighlightGraph[rg, hl]

También puede utilizar ConnectedComponentsy seleccionar componentes con más de 1 vértice:

ccs = Select[Length @ # >= 2 &] @ ConnectedComponents[rg]
 {{{a, b, c}, {b, c, d}, {c, a, m}, {c, d, n}}}
list /. x : Alternatives @@ # :> Highlighted[x, BaseStyle -> Red]& /@ ccs

2 MarcoB Nov 27 2020 at 00:44
ClearAll[formatList]
formatList[list_] := Module[{rules},
  rules =
    AssociationThread[
      list -> (If[Max[#] >= 2, Gray, Black] & /@ 
        Function[{element}, 
          Length@Intersection[element, #] & /@ 
           Complement[list, {element}]] /@ list)
    ];
  Style[#, rules[#]] & /@ list
]

formatList[list]

1 kglr Nov 27 2020 at 13:49

Una variante de la solución de OP que evita el anidamiento de Highlighted:

list //. {a___, x : ({_, _, _} | Highlighted[{_, _, _}, ___]), b___, 
    y : ({_, _, _}), c___} /; Length[Intersection[x /. Highlighted -> (# &), y]] >= 2 :> 
   {a, Highlighted[x /. Highlighted -> (# &)], b, Highlighted@y, c}

Mismo enfoque usando Style:

list //. {a___, x : ({_, _, _} | Style[{_, _, _}, ___]), b___, 
    y : ({_, _, _}), c___} /; Length[Intersection[x /. Style -> (# &), y]] >= 2 :> 
   {a, Style[x /. Style -> (# &), Gray], b, Style[y /. Style -> (# &), Gray], c}

1 cvgmt Nov 27 2020 at 16:02

Creo que la forma más fácil es seguir usando Gathery reordenar el índice. Aquí manejamos la situación general.

SeedRandom[400];
list = Table[RandomSample[Alphabet[], 3], 40];
newlist = Thread[Range[Length@list] -> list];
result = Gather[newlist, 
   Length[Intersection[Last@#1, Last@#2]] >= 2 &];
keys = Keys /@ result;
keyc = Thread[keys -> RandomColor[Length@keys]]
map[j_] := 
  MapAt[Style[#, Last@keyc[[j]], Bold] &, List /@ First@keyc[[j]]];
fig = Composition[Sequence @@ Table[map[j], {j, 1, Length@keyc}]]@
  list
Grid[Partition[fig, 8], Frame -> All]

1 kglr Nov 27 2020 at 17:52
list /. x : {__Symbol} /; 
  Max[Length[Intersection[x, #]] & /@ DeleteCases[list, x]] >= 2 :> 
    Style[x, Gray] 

Un método que utiliza GatherBy:

gb = Join @@ Select[Length@# > 1 &]@
   GatherBy[list, Function[x, Max[Length[Intersection[x, #]] & /@ DeleteCases[x][list]]]]
 {{a, b, c}, {b, c, d}, {c, a, m}, {c, d, n}}
list /. x : Alternatives @@ gb :> Style[x, Gray]

Por qué Gatherno funciona:

Tomando un ejemplo más simple:

list2 = Partition[Range@5, 3, 1];
GatherBy[list2, Function[x, Max[Length[Intersection[x, #]] & /@ 
  DeleteCases[x][list2]] >= 2]]
 {{{1, 2, 3}, {2, 3, 4}, {3, 4, 5}}}
Gather[list2, Length[Intersection[##]] >= 2 &]
{{{1, 2, 3}, {2, 3, 4}},
 {{3, 4, 5}}}

Gatherno realiza la función de prueba en todos los pares de la lista de entrada. Si la función de prueba se evalúa Truepara el par {p1, p2}(de modo que p1y p2se agrupan), el par {p1, p3}se prueba pero {p2, p3}se omite como se puede ver en la Tracesalida:

Trace[Gather[list2, Length[Intersection[##]] >= 2 &]] // Rest // Rest // Column

Tenga en cuenta que los triples {2, 3, 4}y {3, 4, 5}están sin comparación (porque {2, 3, 4}está ya reunidos }.

kglr Nov 27 2020 at 20:51

Otro enfoque más es tomar el Unionde 2 subconjuntos que satisfacen la condición:

highlighted = Union @@ Select[Length[Intersection @@ #] >= 2 &] @ Subsets[list, {2}]
{{a, b, c}, {b, c, d}, {c, a, m}, {c, d, n}}
list /. x : Alternatives @@ highlighted :> Style[x, Gray]