Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I'm trying to solve a heuristic search in Mathematica 9. I get a list of succesor nodes called open with two nodes and a heuristic value, e.g.,

open={{node1,node2,H1},...,{node2,node1,Hi},...,{noden,noden,Hn}}

I need to select only when the two firts elements are the same (no matter order) but where the heuristic is lower. Following the code that I used for sort the elements by the first item

Sort[open, #1[[1]] < #2[[1]] &]

I try to select cases when the same first and second numbers and the heuristic value where lower:

Select[open, #1[[1]]==#2[[1]] &&  #1[[2]] == #2[[2]] && #1[[3]]< #2[[3]] &]

But, returns {}...

My list

open = {{1, 2, 3}, {2, 1, 5}, {1, 2, 2}, {3, 4, 5}, {4, 3, 2}};

Between {1, 2, 3}, {1, 2, 2}, and {2, 1, 5} then choose {1, 2, 2} that has the lower heuristic. And, between {3, 4, 5} and {4, 3, 2} then {4, 3, 2}...

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

Thanks,

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

You can try something like this:

First[Sort[#, #1[[3]] < #2[[3]] &]]&/@Gather[open, Complement[Most[#1], Most[#2]] === {}&]

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

this is a combination of two functions: First you gather the same edges and then you sort them according to their weight and take the first element (which has the lowest value.)

share|improve this answer
    
Thanks, but can you explain me a little deeper what did you do? especially, the last part... –  Jotasmall Jun 5 '13 at 14:22
    
@user7892 If you mean the Complement[Most[#1], Most[#2]] === {} part, it's just a way using basic principles from set theory for gathering the same edges. –  Spawn1701D Jun 5 '13 at 15:22
    
I did an effort to get it...yeah, in that part, you drop out the ones with same two firsts member. Thanks again, –  Jotasmall Jun 5 '13 at 19:47
add comment

A combination of GatherBy[] and SortBy[] does the trick:

First[SortBy[#, Last]] & /@
GatherBy[{{1, 2, 3}, {2, 1, 5}, {1, 2, 2}, {3, 4, 5}, {4, 3, 2}}, Sort[Take[#, 2]] &]
   {{1, 2, 2}, {4, 3, 2}}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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