This is my list:
list = {2.6135182051634342, -2.6690957180727297,
0.26060239174734157, -0.4182243295792278};
I wanna gather it every two number,which make this group's diffrence's absolute value is nearest 3.14.
We can see this distance martix.
DistanceMatrix[list,
DistanceFunction -> (First[Abs[#1 - #2]] &)] // MatrixForm
As we see.The $(1st,4th)$ and $(2nd,3rd)$ is we want to group.Implies we result is {{2.6135182051634342,-0.4182243295792278},{-2.6690957180727297,0.26060239174734157}}
But this code doesn't work,becuase the Nearest's first parameter cannot be a matrix.
mat = DistanceMatrix[list,
DistanceFunction -> (First[Abs[#1 - #2]] &)];
Position[mat, Nearest[mat, 3.14, 2]]
Or there are other more better method to do this?
Let's extended this topic.Assumption we have a list2 like this.But wanna group it every two element that make its sum nearest 100.So how to do it?
SeedRandom[2016317];
list2 = RandomSample[Range@100, 20];
DistanceMatrix[list,
DistanceFunction -> (First[Plus[#1, #2]] &)] // MatrixForm
Answer
f[l_List, nbr_Integer, near_Real] := Module[{k, f},
k = Subsets[Range@Length@l, {2}];
f = Nearest[# -> Range@Length@#] &[EuclideanDistance @@ l[[#]] & /@ k];
k[[f[near, nbr]]]
]
list = {2.6135182051634342, -2.6690957180727297,
0.26060239174734157, -0.4182243295792278};
f[list, 2, N@Pi]
(* {{1, 4}, {2, 3}} *)
Your other example:
SeedRandom[2016317];
list2 = RandomSample[Range@100, 20];
f[list2, 2, 100.]
(* {{14, 18}, {18, 20}} *)


Comments
Post a Comment