TransWikia.com

Vector entry matching problem

Mathematica Asked on December 22, 2020

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?

2 Answers

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.

Answered by Bill on December 22, 2020

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}}

Answered by kglr on December 22, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP