 # Group items in (single) list with the closest item in this list

Hello everyone,

I am running into a problem with my script which i do not know how to solve myself, so i hope someone can help me out!
The problem is that i have a list, in my case, 4 polycurves (see image below). And i want to group these PolyCurves in pairs by the closest item in the list (and then not use that item anymore)

Thanks in advance! nearestPairs.dyn (16.7 KB)

``````s = PolyCurve.ByJoinedCurves(List.Shuffle(
(Rectangle.ByWidthLength(10..20..#5,5).Translate
(0..40..#5,0..40..#5,0))).Explode());

def cns(cr:var[]..[], oc:var[]..[])
{
a = List.SetDifference(List.RestOfItems(cr),oc);
b = cr.DistanceTo(a);
c = List.SortByKey(a,b)["sorted list"];
return List.FirstItem(c);
};

s;
nearestPairs = [Imperative]
{
t = [];
i = 0;
while (List.Count(t)<List.Count(s))
{
d = cns(List.ShiftIndices(s,-i),t);
t = List.AddItemToEnd(d,t);
i = i + 1;
}
return List.Transpose([s,t]);
};``````
2 Likes

Hi Vikram,

That solution didnt really work for me, but i got this working !
(Nontheless thank you very much for your help )

1 Like