Anonymous user
Hash join: Difference between revisions
→{{header|Mathematica}}
Line 532:
{{works with|Mathematica|10}}
<lang mathematica>hashJoin[table1_List,table1colindex_Integer,table2_List,table2colindex_Integer]:=Module[{h,f,t1,t2,tmp},
t1=If[table1colindex != 1,table1[[All,Prepend[Delete[Range@Length@table1[[1]],table1colindex],table1colindex]]],table1];
t2=If[table2colindex != 1, table2[[All,Prepend[Delete[Range@Length@table2[[1]],table2colindex],table2colindex]]],table2];
h = GroupBy[table2, First];▼
f[{a_, b_List}] := {a, #} & /@ b;▼
If[Length[t1]>Length[t2],tmp=t1;t1=t2;t2=tmp;];
Partition[Flatten[Map[f, {#[[1]], h[#[[2]]]} & /@ table1▼
</lang>▼
]],Length[t1[[1]]]+Length[t2[[1]]]-1]
▲];</lang>
Sample run:
<pre>
table1 = {{18, "Alan", 1}, {27, "Jonah", 2}, {28, "Alan", 3}, {28,
"Glory", 4}};
table2 = {{"Alan", "Ghosts"}, {"Alan", "Zombies"}, {"Glory",
hashJoin[table1, table2] // TableForm▼
"Buffy"}, {"Jonah", "Spiders"}, {"Jonah", "Whales"}};
table1colindex = 2;
table2colindex = 1;
▲hashJoin[table1, table1colindex, table2, table2colindex] // TableForm
Ghosts Alan 18 1
Ghosts Alan 28 3
Zombies Alan 18 1
Zombies Alan 28 3
Spiders Jonah 27 2
Whales Jonah 27 2
table1 = {{18, "Alan", 1}, {27, "Jonah", 2}, {28, "Alan", 3}, {28,
"Glory", 4}};
table2 = {{33, "Alan", "Ghosts"}, {34, "Alan", "Zombies"}, {35,
"Glory", "Buffy"}, {36, "Jonah", "Spiders"}, {37, "Jonah",
"Whales"}};
table1colindex = 2;
table2colindex = 2;
hashJoin[table1, table1colindex, table2, table2colindex] // TableForm
33 Ghosts Alan 18 1
33 Ghosts Alan 28 3
34 Zombies Alan 18 1
34 Zombies Alan 28 3
35 Buffy Glory 28 4
36 Spiders Jonah 27 2
37 Whales Jonah 27 2
table1 = {{19, "Zorro", 8}, {17, "Zorro", 7}, {17, "Zorro", 9}, {18,
"Alan", 1}, {27, "Jonah", 2}, {28, "Alan", 3}, {28, "Glory", 4}};
table2 = {{33, "Alan", "Ghosts"}, {34, "Alan", "Zombies"}, {35,
"Glory", "Buffy"}, {36, "Jonah", "Spiders"}, {37, "Jonah",
"Whales"}, {39, "Zorro", "Fox"}};
table1colindex = 2;
table2colindex = 2;
hashJoin[table1, table1colindex, table2, table2colindex] // TableForm
19 8 Zorro 39 Fox
18 Alan Ghosts▼
17 7 Zorro 39 Fox
18 Alan Zombies▼
17 9 Zorro 39 Fox
27 Jonah Spiders▼
▲18 1 Alan 33 Ghosts
27 Jonah Whales▼
▲27 2 Jonah 36 Spiders
28 Alan Zombies▼
▲27 2 Jonah 37 Whales
▲28 Glory Buffy
28 4 Glory 35 Buffy
</pre>
|