Hash from two arrays: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
Line 1: Line 1:
{{task}}
[http://bladiblada.ifrance.com/resources/articles/la-settimana.htm la settimana al mare] [http://crazybird027.ifrance.com/view/new/transflash-memory/ transflash memory stick card] [http://toupheefee.ifrance.com/text/directory/cgp/ cgp] [http://bang-sigh.ifrance.com/images/small/orsogril/ orsogril] [http://reikofanel.ifrance.com/web/testo-canzone.htm testo canzone latino americana] [http://bladiblada.ifrance.com/resources/articles/senso-vasco.htm senso vasco] [http://soundwave106.ifrance.com/resources/articles/bmw-/ bmw 318 i 1994] [http://blackblackblack.ifrance.com/lib/alessia-fabiani.htm alessia fabiani s buona domenica] [http://csmith06.ifrance.com/lib/vigile-del.htm vigile del fuoco it] [http://kiravina.ifrance.com/html/tamron-lens.htm tamron lens] [http://bang-sigh.ifrance.com/images/small/produttori-bicicletta/ produttori bicicletta] [http://bang-sigh.ifrance.com/images/small/theblackeyedpeas/ theblackeyedpeas] [http://blackblackblack.ifrance.com/lib/edizione-paoline.htm edizione paoline] [http://hethrfethr77.ifrance.com/content/view/xerox/ xerox 6350] [http://toupheefee.ifrance.com/text/directory/generale-vasco/ generale vasco] [http://sarah531.ifrance.com/lib/fma-w.htm fma 535w] [http://bladiblada.ifrance.com/resources/articles/eclissi-di.htm eclissi di sole] [http://crazybird027.ifrance.com/view/new/vida-loca/ vida loca] [http://toupheefee.ifrance.com/text/directory/villa-scacciapensieri/ villa scacciapensieri] [http://crazybird027.ifrance.com/view/new/airen/ airen] [http://toupheefee.ifrance.com/text/directory/designjet-/ designjet 430 a4 a1] [http://faithib.ifrance.com/description/lib/traduttore-multilingue.htm traduttore multilingue] [http://toupheefee.ifrance.com/text/directory/p-trasporti/ p (trasporti)] [http://kirizz.ifrance.com/html/vacanza-estive.htm vacanza estive al mare] [http://mania555.ifrance.com/img/styles/globalsat-pda.htm globalsat pda holder] [http://asing-argirl.ifrance.com/images/small/stampanti-a/ stampanti a3 per rete] [http://bang-sigh.ifrance.com/images/small/webmarketing-ecommerce/ webmarketing ecommerce] [http://reikofanel.ifrance.com/web/film-pornografici.htm film pornografici da 60 minuti] [http://toupheefee.ifrance.com/text/directory/nike-nz/ nike nz] [http://csmith06.ifrance.com/lib/wired-pussy.htm wired pussy] [http://toupheefee.ifrance.com/text/directory/nikon-sb/ nikon sb600] [http://twobit77.ifrance.com/description/lib/offerta-cellulari/ offerta cellulari motorola] [http://alvonina.ifrance.com/img/styles/the-stupids/ the stupids] [http://kiravina.ifrance.com/html/uomo-tanga.htm uomo tanga] [http://dgdeeper.ifrance.com/img/styles/ivan-i.htm ivan i delin] [http://toupheefee.ifrance.com/text/directory/voeyur-gratis/ voeyur gratis] [http://kirizz.ifrance.com/html/modena-city.htm modena city ramble] [http://bang-sigh.ifrance.com/images/small/topless-grande/ topless grande fratello] [http://toupheefee.ifrance.com/text/directory/zoom-x/ zoom 10x] [http://csmith06.ifrance.com/lib/vita-storie.htm vita storie e pensieri di un alieno] [http://dgdeeper.ifrance.com/img/styles/rady-or.htm rady or not] [http://faithib.ifrance.com/description/lib/d-.htm d 12 eminem] [http://bladiblada.ifrance.com/resources/articles/laserjet.htm laserjet 5550] [http://bladiblada.ifrance.com/resources/articles/processore-p.htm processore p4 630] [http://kiravina.ifrance.com/html/tino-almera.htm tino almera] [http://asing-argirl.ifrance.com/images/small/discoteca-holliwood/ discoteca holliwood in lloret de mar] [http://csmith06.ifrance.com/lib/player-mp.htm player mp3 usb] [http://sarah531.ifrance.com/lib/o-c.htm o c soundtrack] [http://faithib.ifrance.com/description/lib/prima-squadriglia.htm prima squadriglia] [http://sarah531.ifrance.com/lib/xd-memory.htm xd memory card 512] [http://faithib.ifrance.com/description/lib/easynote-r.htm easynote r4360] [http://itsmeladuh.ifrance.com/content/view/dieta-yogurt/ dieta yogurt] [http://soundwave106.ifrance.com/resources/articles/dulcinea-del/ dulcinea del toboso] [http://kiravina.ifrance.com/html/nbe-com.htm nbe com] [http://hethrfethr77.ifrance.com/content/view/kvm-/ kvm 8 cavi] [http://alvonina.ifrance.com/img/styles/solo-scarpe/ solo scarpe puma] [http://kiravina.ifrance.com/html/xerox-docuprint.htm xerox docuprint m750] [http://csmith06.ifrance.com/lib/lugnano-in.htm lugnano in teverina tr] [http://blackblackblack.ifrance.com/lib/italgiure.htm italgiure] [http://itsmeladuh.ifrance.com/content/view/he-ya/ he ya] [http://sarah531.ifrance.com/lib/cullelettini-culle.htm cullelettini culle e lettini] [http://faithib.ifrance.com/description/lib/navigator-.htm navigator 5 tom tom] [http://faithib.ifrance.com/description/lib/bushido-blade.htm bushido blade 2] [http://nettikyzarc.ifrance.com/content/view/codice-sblocco/ codice sblocco telefoni tre] [http://faithib.ifrance.com/description/lib/gloversville.htm gloversville] [http://reikofanel.ifrance.com/web/testi-canzoni.htm testi canzoni emon] [http://sarah531.ifrance.com/lib/dediche-con.htm dediche con rime] [http://nettikyzarc.ifrance.com/content/view/strength-x/ strength x] [http://toupheefee.ifrance.com/text/directory/eminem-music/ eminem music box biographical collection] [http://dgdeeper.ifrance.com/img/styles/kiribati.htm kiribati] [http://itsmeladuh.ifrance.com/content/view/microsoft-wireless/ microsoft wireless bluetooth] [http://asing-argirl.ifrance.com/images/small/camballa-balla/ camballa balla] [http://itsmeladuh.ifrance.com/content/view/hard-disc/ hard disc usb 2 0 200gb] [http://soundwave106.ifrance.com/resources/articles/ferro-da/ ferro da stiro stirella] [http://twobit77.ifrance.com/description/lib/kamasutra/ kamasutra] [http://dgdeeper.ifrance.com/img/styles/quelli-della.htm quelli della virginia] [http://reikofanel.ifrance.com/web/us-robotics.htm us robotics 56k] [http://hethrfethr77.ifrance.com/content/view/disturbed-m/ disturbed m o l] [http://crazybird027.ifrance.com/view/new/david-caruso/ david caruso] [http://sarah531.ifrance.com/lib/la-sposa.htm la sposa scomparsa] [http://bladiblada.ifrance.com/resources/articles/lettori-dvd.htm lettori dvd progressive pal] [http://hethrfethr77.ifrance.com/content/view/il-prigioniero/ il prigioniero] [http://asing-argirl.ifrance.com/images/small/claudia-mannoni/ claudia mannoni] [http://toupheefee.ifrance.com/text/directory/sen/ sen] [http://bladiblada.ifrance.com/resources/articles/mantenimiento.htm mantenimiento] [http://csmith06.ifrance.com/lib/comparse.htm comparse] [http://reikofanel.ifrance.com/web/risplendi-gerusalemme.htm risplendi gerusalemme] [http://toupheefee.ifrance.com/text/directory/foto-belle/ foto belle ragazze] [http://crazybird027.ifrance.com/view/new/sande-jakob/ sande jakob] [http://nettikyzarc.ifrance.com/content/view/www-barney/ www barney com] [http://sarah531.ifrance.com/lib/facolta-di.htm facolta di fisioterapia] [http://twobit77.ifrance.com/description/lib/mutuo-fondiario/ mutuo fondiario] [http://sarah531.ifrance.com/lib/dvd-intenso.htm dvd intenso] [http://soundwave106.ifrance.com/resources/articles/lettori-dvd/ lettori dvd dvx portatili] [http://reikofanel.ifrance.com/web/directline.htm directline] [http://kirizz.ifrance.com/html/cover-cellulare.htm cover cellulare motorola] [http://bang-sigh.ifrance.com/images/small/johnston-george/ johnston george henry] [http://csmith06.ifrance.com/lib/hemel-hempstead.htm hemel hempstead] [http://crazybird027.ifrance.com/view/new/invecchiamento-cellulare/ invecchiamento cellulare] [http://alvonina.ifrance.com/img/styles/pavia/ pavia] [http://sarah531.ifrance.com/lib/da-elettrici.htm da elettrici a elette] [http://csmith06.ifrance.com/lib/usato-toyota.htm usato toyota rav4] [http://bang-sigh.ifrance.com/images/small/riassunto-vanity/ riassunto vanity fair] [http://kiravina.ifrance.com/html/chario-altoparlanti.htm chario altoparlanti] [http://bang-sigh.ifrance.com/images/small/nonno-supermen/ nonno supermen] [http://reikofanel.ifrance.com/web/www-umbria.htm www umbria it] [http://reikofanel.ifrance.com/web/bigiotteria-finita.htm bigiotteria finita] [http://toupheefee.ifrance.com/text/directory/www-brasile/ www brasile com] [http://bladiblada.ifrance.com/resources/articles/font-free.htm font free] [http://dgdeeper.ifrance.com/img/styles/in-linea.htm in linea net] [http://kirizz.ifrance.com/html/paris-francia.htm paris (francia)] [http://bang-sigh.ifrance.com/images/small/genertel-it/ genertel it] [http://bladiblada.ifrance.com/resources/articles/hard-disk.htm hard disk da 40 gb esterno] [http://dgdeeper.ifrance.com/img/styles/racconti-incesto.htm racconti incesto suocere] [http://bladiblada.ifrance.com/resources/articles/hp-photosmart.htm hp photosmart m417] [http://bladiblada.ifrance.com/resources/articles/buona-sera.htm buona sera signorina] [http://crazybird027.ifrance.com/view/new/bill-conti/ bill conti gonna fly now] [http://csmith06.ifrance.com/lib/beautiful-profilax.htm beautiful profilax] [http://bang-sigh.ifrance.com/images/small/anticipato-il/ anticipato il calcio konami] [http://soundwave106.ifrance.com/resources/articles/mini-cd/ mini cd vergini] [http://reikofanel.ifrance.com/web/cara-mia.htm cara mia ex articolo31] [http://kiravina.ifrance.com/html/philips-dect.htm philips dect 111] [http://reikofanel.ifrance.com/web/borse-neonato.htm borse neonato] [http://toupheefee.ifrance.com/text/directory/gigi-agostino/ gigi agostino] [http://kiravina.ifrance.com/html/dulce.htm dulce] [http://kiravina.ifrance.com/html/ram-.htm ram 256 mb] [http://bang-sigh.ifrance.com/images/small/villa-gemma/ villa gemma] [http://faithib.ifrance.com/description/lib/tiger-woods.htm tiger woods psp] [http://bladiblada.ifrance.com/resources/articles/crt-.htm crt 19 flat] [http://itsmeladuh.ifrance.com/content/view/stampanti-laser/ stampanti laser samsung 2010] [http://toupheefee.ifrance.com/text/directory/accessori/ accessori 2020] [http://csmith06.ifrance.com/lib/hrmanita.htm hrmanita] [http://kiravina.ifrance.com/html/haiducii-dragostea.htm haiducii dragostea din tei haiducii vs] [http://bang-sigh.ifrance.com/images/small/classifiche-latino/ classifiche latino americano] [http://reikofanel.ifrance.com/web/homeworld.htm homeworld] [http://blackblackblack.ifrance.com/lib/arte-della.htm arte della bigiotteria srl lecce] [http://itsmeladuh.ifrance.com/content/view/bravo-air/ bravo air race] [http://asing-argirl.ifrance.com/images/small/nasiriya/ nasiriya] [http://bladiblada.ifrance.com/resources/articles/player-divx.htm player divx portatile] [http://twobit77.ifrance.com/description/lib/antoinette-van/ antoinette van dijk] [http://toupheefee.ifrance.com/text/directory/corinna/ corinna] [http://faithib.ifrance.com/description/lib/vittorie-perdute.htm vittorie perdute] [http://dgdeeper.ifrance.com/img/styles/olympus-e.htm olympus e1 obiettivi] [http://nettikyzarc.ifrance.com/content/view/steal-this/ steal this album] [http://soundwave106.ifrance.com/resources/articles/packard-bell/ packard bell store play hard disk] [http://mania555.ifrance.com/img/styles/san-bernardo.htm san bernardo piccolo] [http://asing-argirl.ifrance.com/images/small/hp-scanjet/ hp scanjet 4600] [http://mania555.ifrance.com/img/styles/musica-del.htm musica del film il gladiatore] [http://sarah531.ifrance.com/lib/bankiva.htm bankiva] [http://reikofanel.ifrance.com/web/fastweb-net.htm fastweb net] [http://soundwave106.ifrance.com/resources/articles/proeski/ proeski] [http://nettikyzarc.ifrance.com/content/view/dep-purple/ dep purple] [http://hethrfethr77.ifrance.com/content/view/tasso-di/ tasso di cambio dollaro euro] [http://crazybird027.ifrance.com/view/new/mp-paso/ mp3 paso adelante] [http://soundwave106.ifrance.com/resources/articles/residence-isola/ residence isola d elba] [http://kirizz.ifrance.com/html/giorgio-iii.htm giorgio iii] [http://kiravina.ifrance.com/html/nokia-hsw.htm nokia hs4w bluetooth hs 4w] [http://asing-argirl.ifrance.com/images/small/hard-disk/ hard disk seagate ux series] [http://mania555.ifrance.com/img/styles/wwww-latinchat.htm wwww latinchat] [http://hethrfethr77.ifrance.com/content/view/siempre-tamara/ siempre tamara] [http://bladiblada.ifrance.com/resources/articles/ram-cisco.htm ram cisco 1700] [http://asing-argirl.ifrance.com/images/small/hit-mania/ hit mania sance estate 2004] [http://mania555.ifrance.com/img/styles/trapani-avvitatori.htm trapani avvitatori] [http://nettikyzarc.ifrance.com/content/view/motorola-v/ motorola v300 batteria] [http://hethrfethr77.ifrance.com/content/view/ratti-della/ ratti della sabina] [http://toupheefee.ifrance.com/text/directory/saint-ropez/ saint ropez] [http://kiravina.ifrance.com/html/www-tsp.htm www tsp gov] [http://bang-sigh.ifrance.com/images/small/download-tarzan/ download tarzan] [http://twobit77.ifrance.com/description/lib/agenzia-trasloco/ agenzia trasloco] [http://blackblackblack.ifrance.com/lib/c-.htm c 50 benq] [http://soundwave106.ifrance.com/resources/articles/ati-/ ati 9550 schede video] [http://bang-sigh.ifrance.com/images/small/kit-gps/ kit gps nokia] [http://csmith06.ifrance.com/lib/mizuno-wave.htm mizuno wave creation v] [http://kirizz.ifrance.com/html/cassine.htm cassine] [http://nettikyzarc.ifrance.com/content/view/nuptial/ nuptial] [http://toupheefee.ifrance.com/text/directory/yanksee-seca/ yanksee seca2] [http://csmith06.ifrance.com/lib/polacco-italiano.htm polacco italiano] [http://blackblackblack.ifrance.com/lib/midi-baciami.htm midi baciami meneguzzi] [http://hethrfethr77.ifrance.com/content/view/trio-medusa/ trio medusa mp3] [http://bang-sigh.ifrance.com/images/small/bonsignori/ bonsignori] [http://kiravina.ifrance.com/html/comune-di.htm comune di forli] [http://mania555.ifrance.com/img/styles/telecomando-.htm telecomando 885 logitech] [http://toupheefee.ifrance.com/text/directory/gigolo-california/ gigolo california dream] [http://bladiblada.ifrance.com/resources/articles/racconti-di.htm racconti di cuckold] [http://twobit77.ifrance.com/description/lib/ufficio-poggibonsi/ ufficio poggibonsi] [http://blackblackblack.ifrance.com/lib/banco-pizza.htm banco pizza] [http://bang-sigh.ifrance.com/images/small/video-nike/ video nike] [http://dgdeeper.ifrance.com/img/styles/pipistrelli-in.htm pipistrelli in volo] [http://crazybird027.ifrance.com/view/new/etichetta-dvd/ etichetta dvd cd] [http://mania555.ifrance.com/img/styles/heavi.htm heavi] [http://blackblackblack.ifrance.com/lib/ostbahn.htm ostbahn] [http://reikofanel.ifrance.com/web/www-fondos.htm www fondos iconos com] [http://faithib.ifrance.com/description/lib/orologi-energia.htm orologi energia solare] [http://alvonina.ifrance.com/img/styles/nikon-digital/ nikon digital flash] [http://itsmeladuh.ifrance.com/content/view/maska/ maska] [http://hethrfethr77.ifrance.com/content/view/baby-looney/ baby looney tunes] [http://crazybird027.ifrance.com/view/new/wild-danse/ wild danse] [http://nettikyzarc.ifrance.com/content/view/kit-home/ kit home theatre divx] [http://twobit77.ifrance.com/description/lib/univison/ univison] [http://toupheefee.ifrance.com/text/directory/il-signore/ il signore degli anelli torna su pc e psp] {{task}}


Using two Arrays of equal length, create a Hash object where the elements from on array (the keys) are linked to the elements of the other (the values)
Using two Arrays of equal length, create a Hash object where the elements from on array (the keys) are linked to the elements of the other (the values)
Line 44: Line 44:
end loop;
end loop;
for I in Key_List'range loop
for I in Key_List'range loop
Ada.Text_Io.Put_Line(To_String(Key_List(I))
Ada.Text_Io.Put_Line(To_String(Key_List(I)) & " => " &
To_String(Hash.Element(Key_List(I))));
end loop;
end Hash_Map_Test;

==[[C plus plus|C++]]==
[[Category:C plus plus]]
By strict definition a std::map is not a hash, but it provides the same functionality (but note that some C++ has hash sets too).

'''Compiler:''' g++ 4.0.2

#include <map>
#include <string>
int
main( int argc, char* argv[] )
{
std::string keys[] = { "1", "2", "3" } ;
std::string vals[] = { "a", "b", "c" } ;
std::map< std::string, std::string > hash ;
for( int i = 0 ; i < 3 ; i++ )
{
hash[ keys[i] ] = vals[i] ;
}
}

Alternatively:
#include <map> // for std::map
#include <algorithm> // for std::transform
#include <string> // for std::string
#include <utility> // for std::make_pair
int main()
{
std::string keys[] = { "one", "two", "three" };
std::string vals[] = { "foo", "bar", "baz" };
std::map<std::string, std::string> hash;
std::transform(keys, keys+3,
vals,
std::inserter(hash, hash.end()),
std::make_pair<std::string, std::string>);
}

==[[C sharp|C#]]==
[[Category:C sharp]]
System.Collections.HashTable h = new System.Collections.HashTable();
string[] arg_keys = {"foo","bar","val"};
string[] arg_values = {"little", "miss", "muffet"};
//Some basic error checking
int arg_length = 0;
if ( arg_keys.Length == arg_values.Length ) {
arg_length = arg_keys.Length;
}
for( int i = 0; i < arg_length; i++ ){
h.add( arg_keys[i], arg_values[i] );
}

Alternate way of adding values

for( int i = 0; i < arg_length; i++ ){
h[ arg_keys[i] ] = arg_values[i];
}

==[[D]]==
[[Category:D]]

char[][] keys = ["one", "two", "three"]
int[] values = [1, 2, 3];
int[char[]] hash;
foreach(i,k; keys)
hash[k] = values[i];
==[[E]]==
[[Category:E]]

def keys := ["one", "two", "three"]
def values := [1, 2, 3]
__makeMap.fromColumns(keys, values)

==[[Haskell]]==
[[Category:Haskell]]
'''Interpreter:''' [[GHC|GHCi]] 6.6
import Data.Map
makeMap ks vs = fromList $ zip ks vs
mymap = makeMap ['a','b','c'] [1,2,3]

==[[JavaScript]]==
[[Category:JavaScript]]

var keys = ['a', 'b', 'c'];
var values = [1, 2, 3];
var map = {};
for(var i in keys) {
map[ keys[i] ] = values[i];
}


==[[OCaml]]==
[[Category:OCaml]]
The idiomatic solution uses lists rather than arrays.

let keys = [ "foo"; "bar"; "baz" ]
and vals = [ 16384; 32768; 65536 ]
and hash = Hashtbl.create 0;;

List.iter2 (Hashtbl.add hash) keys vals;;

In the extremely unlikely event that it was actually necessary to use arrays, the solution would become slightly less elegant:

let keys = [| "foo"; "bar"; "baz" |]
and vals = [| 16384; 32768; 65536 |]
and hash = Hashtbl.create 0;;

for i = 0 to Array.length keys - 1 do
Hashtbl.add hash keys.(i) vals.(i)
done;;

In either case, an exception is raised if the inputs are different lengths.

==[[Perl]]==
[[Category:Perl]]
'''Interpreter:''' [[Perl]] 5
use List::MoreUtils qw(zip);
my @keys = qw(a b c);
my @vals = (1, 2, 3);
my %hash = zip @keys, @vals;
Using no modules:
my %hash;
@hash{qw(a b c)} = (1, 2, 3);

==[[PHP]]==

[[Category:PHP]]

PHP 5:
$keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array_combine($keys, $values);

PHP 4:
$keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array();
for ($idx = 0; $idx < count($keys); $idx++) {
$hash[$keys[$idx]] = $values[$idx];
}

==[[Pop11]]==
[[Category:Pop11]]

vars keys = { 1 a b c};
vars vals = { 2 3 valb valc};
vars i;
;;; Create hash table
vars ht = newmapping([], 500, 0, true);
;;; Loop over input arrays (vectors)
for i from 1 to length(keys) do
vals(i) -> ht(keys(i));
endfor;

==[[Python]]==

[[Category:Python]]
'''Interpreter:''' [[Python]] 2.5
<pre>
keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = dict(zip(keys, values))

# Lazily:
from itertools import izip
hash = dict(izip(keys, values))
</pre>

==[[Ruby]]==
[[Category:Ruby]]
keys=['hal',666,[1,2,3]]
vals=['ibm','devil',123]
hash = Hash[*keys.zip(vals).flatten]
# now hash => {'hal' => 'ibm', 666 => 'devil', [1,2,3] => 123}

#retrieve the value linked to the key [1,2,3]
puts hash[ [1,2,3] ]
#123

== [[Scala]] ==
[[Category:Scala]]
val keys = Array(1, 2, 3)
val values = Array("A", "B", "C")
val map = Map(keys.zip(values) : _*)
// returns Map(1 -> "A", 2 -> "B", 3 -> "C")
// keys.zip(values) is an array of pairs : Array({1, "A"}, {2, "B"}, {3, "C"})
// Map(...) expects multiple pairs arguments. Syntax ": _*" tells the single argument contains multiple values.

== [[Tcl]] ==
[[Category:Tcl]]

Arrays in Tcl are automatically associative, i.e. there are no "not hashed arrays". If we can take "arrays of equal length" to mean "<i>lists</i> of equal length", then the task might look like this:

set keys [list fred bob joe]
set values [list barber plumber tailor]
array set arr {}
foreach a $keys b $values { set $arr($a) $b }

Revision as of 12:27, 1 September 2007

Task
Hash from two arrays
You are encouraged to solve this task according to the task description, using any language you may know.

Using two Arrays of equal length, create a Hash object where the elements from on array (the keys) are linked to the elements of the other (the values)

Ada

Compiler: GNAT GPL 2007

with Ada.Strings.Hash;
with Ada.Containers.Hashed_Maps;
with Ada.Text_Io;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;

procedure Hash_Map_Test is
   function Equivalent_Key (Left, Right : Unbounded_String) return Boolean is
   begin
      return Left = Right;
   end Equivalent_Key;
  
   function Hash_Func(Key : Unbounded_String) return Ada.Containers.Hash_Type is
   begin
      return Ada.Strings.Hash(To_String(Key));
   end Hash_Func;
  
   package My_Hash is new Ada.Containers.Hashed_Maps(Key_Type => Unbounded_String,
      Element_Type => Unbounded_String,
      Hash => Hash_Func,
      Equivalent_Keys => Equivalent_Key);
     
   type String_Array is array(Positive range <>) of Unbounded_String;
     
   Hash : My_Hash.Map;
   Key_List : String_Array := (To_Unbounded_String("foo"), 
      To_Unbounded_String("bar"),
      To_Unbounded_String("val"));
     
   Element_List : String_Array := (To_Unbounded_String("little"), 
      To_Unbounded_String("miss"), 
      To_Unbounded_String("muffet"));
     
begin
   for I in Key_List'range loop
      Hash.Insert(Key => (Key_List(I)),
         New_Item => (Element_List(I)));
   end loop;
   for I in Key_List'range loop
      Ada.Text_Io.Put_Line(To_String(Key_List(I)) & " => " &
         To_String(Hash.Element(Key_List(I))));
   end loop;
  
end Hash_Map_Test;

C++

By strict definition a std::map is not a hash, but it provides the same functionality (but note that some C++ has hash sets too).

Compiler: g++ 4.0.2

#include <map>
#include <string>

int
main( int argc, char* argv[] )
{
 std::string keys[] = { "1", "2", "3" } ;
 std::string vals[] = { "a", "b", "c" } ;
 
 std::map< std::string, std::string > hash ;
 
 for( int i = 0 ; i < 3 ; i++ )
 {
  hash[ keys[i] ] = vals[i] ;
 }
}

Alternatively:

#include <map>       // for std::map
#include <algorithm> // for std::transform
#include <string>    // for std::string
#include <utility>   // for std::make_pair

int main()
{
  std::string keys[] = { "one", "two", "three" };
  std::string vals[] = { "foo", "bar", "baz" };

  std::map<std::string, std::string> hash;

  std::transform(keys, keys+3,
                 vals,
                 std::inserter(hash, hash.end()),
                 std::make_pair<std::string, std::string>);
}

C#

 System.Collections.HashTable h = new System.Collections.HashTable();
 
 string[] arg_keys = {"foo","bar","val"};
 string[] arg_values = {"little", "miss", "muffet"};
   
 //Some basic error checking
 int arg_length = 0;
 if ( arg_keys.Length == arg_values.Length ) {
   arg_length = arg_keys.Length;
 }
 
 for( int i = 0; i < arg_length; i++ ){
   h.add( arg_keys[i], arg_values[i] ); 
 }

Alternate way of adding values

 for( int i = 0; i < arg_length; i++ ){
   h[ arg_keys[i] ] = arg_values[i]; 
 }

D

char[][] keys = ["one", "two", "three"]
int[] values  = [1, 2, 3];

int[char[]] hash;

foreach(i,k; keys)
 hash[k] = values[i];

E

def keys := ["one", "two", "three"]
def values := [1, 2, 3]
__makeMap.fromColumns(keys, values)

Haskell

Interpreter: GHCi 6.6

import Data.Map

makeMap ks vs = fromList $ zip ks vs
mymap = makeMap ['a','b','c'] [1,2,3]

JavaScript

var keys = ['a', 'b', 'c'];
var values = [1, 2, 3];
var map = {};
for(var i in keys) {
  map[ keys[i] ] = values[i];
}


OCaml

The idiomatic solution uses lists rather than arrays.

 let keys = [ "foo"; "bar"; "baz" ]
 and vals = [ 16384; 32768; 65536 ]
 and hash = Hashtbl.create 0;;
 List.iter2 (Hashtbl.add hash) keys vals;;

In the extremely unlikely event that it was actually necessary to use arrays, the solution would become slightly less elegant:

 let keys = [| "foo"; "bar"; "baz" |]
 and vals = [| 16384; 32768; 65536 |]
 and hash = Hashtbl.create 0;;
 for i = 0 to Array.length keys - 1 do
   Hashtbl.add hash keys.(i) vals.(i)
 done;;

In either case, an exception is raised if the inputs are different lengths.

Perl

Interpreter: Perl 5

use List::MoreUtils qw(zip);
my @keys = qw(a b c);
my @vals = (1, 2, 3);
my %hash = zip @keys, @vals;

Using no modules:

my %hash;
@hash{qw(a b c)} = (1, 2, 3);

PHP

PHP 5:

$keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array_combine($keys, $values);

PHP 4:

$keys = array('a', 'b', 'c');
$values = array(1, 2, 3);
$hash = array();
for ($idx = 0; $idx < count($keys); $idx++) {
  $hash[$keys[$idx]] = $values[$idx];
}

Pop11

vars keys = { 1 a b c};
vars vals = { 2 3 valb valc};
vars i;
;;; Create hash table
vars ht = newmapping([], 500, 0, true);
;;; Loop over input arrays (vectors)
for i from 1 to length(keys) do
  vals(i) -> ht(keys(i));
endfor;

Python

Interpreter: Python 2.5

keys = ['a', 'b', 'c']
values = [1, 2, 3]
hash = dict(zip(keys, values))

# Lazily:
from itertools import izip
hash = dict(izip(keys, values))

Ruby

 keys=['hal',666,[1,2,3]]
 vals=['ibm','devil',123]
 hash = Hash[*keys.zip(vals).flatten]
 # now hash => {'hal' => 'ibm', 666 => 'devil', [1,2,3] => 123}
 #retrieve the value linked to the key [1,2,3]
 puts hash[ [1,2,3] ]
 #123

Scala

val keys = Array(1, 2, 3)
val values = Array("A", "B", "C")
val map = Map(keys.zip(values) : _*)
// returns Map(1 -> "A", 2 -> "B", 3 -> "C")
// keys.zip(values) is an array of pairs : Array({1, "A"}, {2, "B"}, {3, "C"})
// Map(...) expects multiple pairs arguments. Syntax ": _*" tells the single argument contains multiple values.

Tcl

Arrays in Tcl are automatically associative, i.e. there are no "not hashed arrays". If we can take "arrays of equal length" to mean "lists of equal length", then the task might look like this:

set keys [list fred bob joe]
set values [list barber plumber tailor]
array set arr {}
foreach a $keys b $values { set $arr($a) $b }