Hash join: Difference between revisions

Added Julia language
(→‎{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details)
(Added Julia language)
Line 1,462:
[28,"Alan","Zombies"]
[28,"Glory","Buffy"]</lang>
 
=={header|Julia}}==
{{works with|Julia|0.6}}
For dataframes there is a builtin function join:
<lang julia>using DataFrames
 
A = DataFrame(Age = [27, 18, 28, 18, 28], Name = ["Jonah", "Alan", "Glory", "Popeye", "Alan"])
B = DataFrame(Name = ["Jonah", "Jonah", "Alan", "Alan", "Glory"],
Nemesis = ["Whales", "Spiders", "Ghosts", "Zombies", "Buffy"])
AB = join(A, B, on = :Name)
 
@show A B AB</lang>
 
{{out}}
<pre>A = 5×2 DataFrames.DataFrame
│ Row │ Age │ Name │
├─────┼─────┼──────────┤
│ 1 │ 27 │ "Jonah" │
│ 2 │ 18 │ "Alan" │
│ 3 │ 28 │ "Glory" │
│ 4 │ 18 │ "Popeye" │
│ 5 │ 28 │ "Alan" │
B = 5×2 DataFrames.DataFrame
│ Row │ Name │ Nemesis │
├─────┼─────────┼───────────┤
│ 1 │ "Jonah" │ "Whales" │
│ 2 │ "Jonah" │ "Spiders" │
│ 3 │ "Alan" │ "Ghosts" │
│ 4 │ "Alan" │ "Zombies" │
│ 5 │ "Glory" │ "Buffy" │
AB = 7×3 DataFrames.DataFrame
│ Row │ Age │ Name │ Nemesis │
├─────┼─────┼─────────┼───────────┤
│ 1 │ 18 │ "Alan" │ "Ghosts" │
│ 2 │ 18 │ "Alan" │ "Zombies" │
│ 3 │ 28 │ "Alan" │ "Ghosts" │
│ 4 │ 28 │ "Alan" │ "Zombies" │
│ 5 │ 28 │ "Glory" │ "Buffy" │
│ 6 │ 27 │ "Jonah" │ "Whales" │
│ 7 │ 27 │ "Jonah" │ "Spiders" │</pre>
 
Following the task hint:
<lang julia>function hashjoin(A::Array, ja::Int, B::Array, jb::Int)
M = Dict(t[jb] => filter(l -> l[jb] == t[jb], B) for t in B)
return collect([a, b] for a in A for b in get(M, a[ja], ()))
end
 
table1 = [(27, "Jonah"),
(18, "Alan"),
(28, "Glory"),
(18, "Popeye"),
(28, "Alan")]
table2 = [("Jonah", "Whales"),
("Jonah", "Spiders"),
("Alan", "Ghosts"),
("Alan", "Zombies"),
("Glory", "Buffy")]
 
for r in hashjoin(table1, 2, table2, 1)
println(r)
end</lang>
 
{{out}}
<pre>Tuple{Any,String}[(27, "Jonah"), ("Jonah", "Whales")]
Tuple{Any,String}[(27, "Jonah"), ("Jonah", "Spiders")]
Tuple{Any,String}[(18, "Alan"), ("Alan", "Ghosts")]
Tuple{Any,String}[(18, "Alan"), ("Alan", "Zombies")]
Tuple{Any,String}[(28, "Glory"), ("Glory", "Buffy")]
Tuple{Any,String}[(28, "Alan"), ("Alan", "Ghosts")]
Tuple{Any,String}[(28, "Alan"), ("Alan", "Zombies")]</pre>
 
=={{header|Kotlin}}==
Anonymous user