# Vector entry matching problem

I have a list composed by vectors. Let's say with five entries in each one. The list can have any dimension.

file =
{{1, 0, -1, 1, 0}, {-1, 0, -1, 0, 0}, {1, 0, 1, 0, 0}, {1, 0, -1, 0, 1},
{1, 0, -1, 1, 0}, {-1, 0, 1, 0, 0}, {1, 0, 1, 0, 0}, {1, 0, 0, 0, 0},
{0, 0, 1, 0, 0}, {1, 0, 1, 1, 0}};


The first three components of each vector are in the set {-1, 0, 1}. The 4th and 5th are either 0 or 1.

I want to add the 4th and 5th entry in all the vectors are identical in the first three entries.

I though to compare the first three entries using HammingDistance; something like

If[Length[file] != 0,
DeleteCases[
Flatten[
Table[
If[
i != j &&
HammingDistance[Drop[file[[i]], -2], Drop[file[[j]], -2]] ==0,
{file[[i]][[1]], file[[i]][[2]],file[[i]][[3]],file[[i]][[4]], file[[i]][[5]]},
0],
{i, 1, Length[file]}, {j,1, i}],
1],
0],
0]


but this only selects vectors in which the pattern is found more than once. Any idea of how to match and clutter all vectors with the same first 3 entries?

• What about: Map[(Append[#[[1 ;; 3]], Total@#[[4 ;; 5]]]) &, Gather[dat, #1[[1 ;; 3]] == #2[[1 ;; 3]] &], {2}] Commented Sep 17, 2020 at 11:31

Try this.

file={{1,0,-1,1,0},{-1,0,-1,0,0},{1,0,1,0,0},{1,0,-1,0,1},{1,0,-1,1,0},{-1,0,1,0,0},
{1,0,1,0,0},{1,0,0,0,0},{0,0,1,0,0},{1,0,1,1,0}};
grouped=Split[Sort[file],Take[#1,3]==Take[#2,3]&]
Map[Join[Take[#[[1]],3],Drop[Total[#],3]]&,grouped]


which displays

{{{-1,0,-1,0,0}},{{-1,0,1,0,0}},{{0,0,1,0,0}},{{1,0,-1,0,1},{1,0,-1,1,0},
{1,0,-1,1,0}},{{1,0,0,0,0}},{{1,0,1,0,0},{1,0,1,0,0},{1,0,1,1,0}}}


showing how it grouped together vectors with common first three elements

and then

{{-1,0,-1,0,0},{-1,0,1,0,0},{0,0,1,0,0},{1,0,-1,2,1},{1,0,0,0,0},{1,0,1,1,0}}


showing how it totaled the last two elements in each group.

KeyValueMap[Join] @ GroupBy[file, (Take[#, 3] &) -> (Drop[#, 3] &), Total]

 {{1, 0, -1, 2, 1}, {-1, 0, -1, 0, 0}, {1, 0, 1, 1, 0}, {-1, 0, 1, 0,  0},
{1, 0, 0, 0, 0}, {0, 0, 1, 0, 0}}


or

KeyValueMap[Join] @ Merge[Total] @ Map[Association[Rule @@ TakeDrop[#, 3]] &] @ file

 {{1, 0, -1, 2, 1}, {-1, 0, -1, 0, 0}, {1, 0, 1, 1, 0}, {-1, 0, 1, 0,  0},
{1, 0, 0, 0, 0}, {0, 0, 1, 0, 0}}