hash_join.sf 694 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Hash_join
  4. #
  5. func hashJoin(table1, index1, table2, index2) {
  6. var a = Arr.new;
  7. var h = Hash.new;
  8.  
  9. # hash phase
  10. table1.each { |s|
  11. h{s[index1]} := [] -> append(s);
  12. };
  13.  
  14. # join phase
  15. table2.each { |r|
  16. a += h{r[index2]}.map{[_,r]};
  17. };
  18.  
  19. return a;
  20. }
  21.  
  22. var t1 = [[27, "Jonah"],
  23. [18, "Alan"],
  24. [28, "Glory"],
  25. [18, "Popeye"],
  26. [28, "Alan"]];
  27.  
  28. var t2 = [["Jonah", "Whales"],
  29. ["Jonah", "Spiders"],
  30. ["Alan", "Ghosts"],
  31. ["Alan", "Zombies"],
  32. ["Glory", "Buffy"]];
  33.  
  34. hashJoin(t1, 1, t2, 0).each { .dump.say };