[Date Index]
[Thread Index]
[Author Index]
Re: Filtering a list of list for certain elements that are neighbours
*To*: mathgroup at smc.vnet.net
*Subject*: [mg88857] Re: [mg88834] Filtering a list of list for certain elements that are neighbours
*From*: "W_Craig Carter" <ccarter at mit.edu>
*Date*: Mon, 19 May 2008 05:18:19 -0400 (EDT)
*References*: <200805181134.HAA23914@smc.vnet.net>
Hello Steven,
I have a solution that you can generalize (and generalize to sublists
greater than 3).
Here is the short answer:
neighboring[a_, b_, list_List] :=
Or @@ Map[MatchQ[#, Sort[{a, b}]] &,
Map[Sort, Rest[Transpose[{list, RotateRight[list]}]]]]
notNeighboring[a_, b_, list_List] := Not[neighboring[a, b, list]]
Select[mylist, notNeighboring[a, b, #] &]
(*returns {{a, c, b}, {b, c, a}} *)
Select[mylist, neighboring[a, b, #] &]
(*returns {{a, b, c}, {b, a, c}, {c, a, b}, {c, b, a}}*)
(*===this method works only for symbols, for strings use StringMatchQ==*)
The long answer is something like this:
Transpose[{mylist, RotateRight[list]}] (*forms neigboring pairs*)
result =Rest[Transpose[{mylist, RotateRight[list]}] ] (*discounts the
end matching case*)
(*Sort[] ensures that each pair is in a cannonical order*)
Map[MatchQ[#,Sort[{a,b}]&,result] (*is a list of true or falses*)
Thus,
test = Table[RandomChoice[{aa, bb, cc, dd, ww, xx, yy, zz}, 5], {4}]
test // MatrixForm
(*
returns for example
{{dd, ww, cc, bb, bb}, {dd, xx, dd, cc, dd}, {zz, aa, aa, aa,
cc}, {ww, ww, cc, bb, ww}}
*)
Select[test, neighboring[ww, cc, #] &]
(*
returns
{{dd, ww, cc, bb, bb}, {ww, ww, cc, bb, ww}}
*)
On Sun, May 18, 2008 at 7:34 AM, Steven Siew <stevensiew2 at gmail.com> wrote:
> I have a list of lists
>
> mylist={{a,b,c},{a,c,b},{b,a,c},{b,c,a},{c,a,b},{c,b,a}}
>
> I want to filter out all lists that have "a being a neighbor to b".
>
> I am looking for the following result.
>
> {{a,c,b},{b,c,a}}
>
>
> For this toy example, I can probably do it by hand but my real problem
> has 120 lists in a list. And I need to filter out various combination
> of letters like "s cannot be next to d" , "s cannot be next to j" , "c
> cannot be next to j" , "h cannot be next to d" and "h cannot be next
> to s".
>
>
--
W. Craig Carter
Prev by Date:
**Re: Re: NthSubset function of Combinatorica package**
Next by Date:
**Re: Filtering a list of list for certain elements that are neighbours**
Previous by thread:
**Re: Filtering a list of list for certain elements that are neighbours**
Next by thread:
**Re: Filtering a list of list for certain elements that are neighbours**
| |