Hash from two arrays

From Rosetta Code
Revision as of 04:08, 24 August 2007 by rosettacode>RrsVbp

o sole mio tv 15 amstrad www ilduce net ati firegl 3200 tango della gelosia singola milano confronto stampante lavatrice indesit 40cm sky italia key vivinatura y 1 2 argento volvo s60 teen blow job philips - 42pf9967 eau de toilette biotherm musica mp3 free o zone despre tine remix www rock 60 70 tango e cash the problem of cell 13 tv pcmcia exporto brasil paloma obsession adventure femmina stereo rz-32lz50 lg dale morena dragostea dintei de o zone tricologia wwww strade it vengaboys nd 3540 le cronache di narnia combat flight simulator 3 ragazze in web cam porno gemelle karafotis metaldetector v600 cellulari motorola vetro vicenza vivi con il tuo amore senza giacca e cravatta franc adventure 2 sony dcr hc22 la doppia vita di elena gall autoaccessori ancona lettore mp3 1gb fm jej czarne oczy ivan i delfin amstel replicatore porte italeri risultati esame avvocato soft macchina alberghi ad ore a roma razze bovine fotografie d epoca hyundai monitor tft 17 rototom sunsplash unlocked lg8110 kural matrox millenium g550 ragazze in camera dunbarton vetroceramica piani cottura gas treemme sony dcrhc39 ds-2000 salsa latina viagra 1 cpr 50 mg droga leggere esselunga novara simcity 4 patch kia sorento ex sesso in diretta memoria ram mac villaggi fine settimana camerota piastra in ghisa locandine cinematografiche firewire adapter run away lettera ad un amore papaveri e papare testi canzoni gianni celeste do right man hp officejet 7410 all in one il punto sano shox rosa juliaca stampare cd occhiali vista da donna fritz fon cristalle chanel superstar mp3 spandau chistes animados passion de gavilanes kalasnjikov confezioni bomboniera matrox ph sandviken tomb raider the angel of darkness - trailer 1 cacio gente guasta progdvb kiosque netgear ant24o5 zucconi home theatre jamo la traduzione della canzone di eamon www ipofisi amore senza domani moondance spartiti l esclusa pirandello riassunto e stato tanto tenpo fa gallerie di quadri amalfi oprah da vide van de sfros biancheria stoks free chess www brasile it driver usb 313 champion league risultato iqbal masih batteria fisio km0 mitsubishi space star auto km 0 hp desktop athlon 64 il buio della notte teddy bears sthlm umbre porsche cayenne oli cassian, nina philips televisori prezzi canzoni vasco rossi da scaricare nano plus 1 gb agriturismo bassano grappa cold fear ubisoft scheda madre asus pentium 4 socket 478 foto di umberta mazzoni basilea 2 benni benassy hit my heart eric pryds brendel bagatelle hotel forte dei marmi recensioni mastro don gesualdo command lettori divx per auto mercato imobiliare ott www al zarkawi com hotel 3 stelle strasburgo monologo benigni publicitario dimage xt minolta canti dell 800 alcott, louisa may jonathan rhys-meyers lover biliardo all italiana termometro orologi microsoft desktop bluetooth tom and gerry paul giamatti saint paul (liberia) passaporto rosso get medieval estefania pigazzi cd di franco califano www mexicana com mietta l immenso fotocopiatrice laser samsung 4100 graziani flecker, james elroy nokia 7610 prezzo samtron 98pdf you rais me up modem michelangelo cx nicon 2100 licenza microsoft xp remissivo canzone telefilm endangered species agenzia immobiliare bologna hdtv plasma 42 koul shen seggiolino auto per bambini konica z annunci sesso versilia citta europee niger tenniswta futurama - stagione uno moschettoni acciaio contatore sito ebai it cavolate opera buffa dedica battesimo gregorace imetec nostop vapor v ideo decapitazione

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)

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 }