Hash from two arrays: Difference between revisions
mNo edit summary |
(Undo revision 7578 by Special:Contributions/RrsVbp (User talk:RrsVbp)) |
||
Line 1: | Line 1: | ||
{{task}} |
|||
[http://veggis.org.cn/resources/articles/sblocco-motorola.htm sblocco motorola a1000] [http://manoke.cn/topic/mischka/ mischka] [http://primonona.info/content/view/captiva-mp/ captiva mp3] [http://wedner.info/content/view/dondolino-prima.htm dondolino prima pappa] [http://veggis.org.cn/resources/articles/sex-moms.htm sex moms gyno] [http://svike.info/view/new/lasciami-sognare.htm lasciami sognare - il canto dell uomo solitario] [http://polex.com.cn/resources/articles/nb-nx.htm nb nx8220] [http://sneck.info/data/codice-controllo/ codice controllo rete tim wind] [http://polex.com.cn/resources/articles/www-ea.htm www ea games com] [http://manoke.cn/topic/giacche/ giacche 2004] [http://primonona.info/content/view/video-de/ video de michel vieth gratis] [http://veggis.org.cn/resources/articles/satellite-television.htm satellite television] [http://sneck.info/data/irc-napolo/ irc napolo chat] [http://primonona.info/content/view/focus-/ focus 1.6 tdci] [http://joperan.org/data/www-puntosnai/ www puntosnai it] [http://budget7i.info/lib/internet/ internet] [http://polex.com.cn/resources/articles/ragazza-cremona.htm ragazza cremona] [http://budget7i.info/lib/casa-sierra/ casa sierra] [http://veggis.org.cn/resources/articles/lg-edge.htm lg edge] [http://veggis.org.cn/resources/articles/www-sede.htm www sede future service esami ecdl it] [http://primonona.info/content/view/microsoft-windows/ microsoft windows server 2003 oem 5] [http://joperan.org/data/mini-gb/ mini 40gb] [http://funkall.us/images/small/navika-mp/ navika mp3] [http://primonona.info/content/view/scanny-network/ scanny network] [http://veggis.org.cn/resources/articles/dlink-hub.htm d-link hub 4 porte usb] [http://soler.net.cn/data/porno-annunci.htm porno annunci] [http://klohy.info/img/styles/videos-porno.htm videos porno full] [http://soler.net.cn/data/mit-avt.htm mit avt 1] [http://primonona.info/content/view/kiss-hdd/ kiss hdd] [http://budget7i.info/lib/elodie-michal/ elodie michal] [http://klohy.info/img/styles/un-uomo.htm un uomo da letto] [http://wedner.info/content/view/samaritan.htm samaritan] [http://svike.info/view/new/stampante-ink.htm stampante ink jet picturemate] [http://polex.com.cn/resources/articles/sexi-brytny.htm sexi brytny] [http://svike.info/view/new/zyxel.htm zyxel 560] [http://wedner.info/content/view/www-capo.htm www capo verde it] [http://sneck.info/data/pentax-espio/ pentax espio 115v] [http://klohy.info/img/styles/samsung-sfi.htm samsung sf-5100i fax laser] [http://joperan.org/data/robotics-k/ robotics 56k message] [http://polex.com.cn/resources/articles/la-marcia.htm la marcia dei legionari] [http://manoke.cn/topic/video-de/ video de decapitation de paul jonson] [http://primonona.info/content/view/www-spiaggialunga/ www spiaggialunga it] [http://manoke.cn/topic/porno/ porno] [http://wedner.info/content/view/warrior-queen.htm warrior queen] [http://wedner.info/content/view/canton-le.htm canton le 130] [http://funkall.us/images/small/frisbi/ frisbi] [http://manoke.cn/topic/fotografie-baglioni/ fotografie baglioni] [http://sneck.info/data/mercedes-/ mercedes 350 cls] [http://funkall.us/images/small/zion-y/ zion y lennox yo voy] [http://primonona.info/content/view/programmi-da/ programmi da scaricare musica] [http://klohy.info/img/styles/ricardo-montaner.htm ricardo montaner amarte es mi pecado] [http://polex.com.cn/resources/articles/genna-lee.htm genna lee nolin] [http://primonona.info/content/view/blue-angel/ blue angel] [http://wedner.info/content/view/testo-la.htm testo la cura] [http://xionny.cn/topic/drin-drin/ drin drin a rispondi] [http://sneck.info/data/book-ragazze/ book ragazze per foto nudo] [http://sneck.info/data/olimpus-u/ olimpus u mini digital] [http://veggis.org.cn/resources/articles/videocamera-panasonic.htm videocamera panasonic gs 250] [http://joperan.org/data/noleggio-camper/ noleggio camper sicilia] [http://svike.info/view/new/nuova-seat.htm nuova seat ibiza auto nuove] [http://budget7i.info/lib/quiz-patente/ quiz patente] [http://xionny.cn/topic/cd-montefiori/ cd montefiori cocktail] [http://soler.net.cn/data/dowson-s.htm dowson s creek] [http://sneck.info/data/ostaggio-italiano/ ostaggio italiano quattrocchi] [http://svike.info/view/new/the-music.htm the music of chance] [http://veggis.org.cn/resources/articles/dj-tommy.htm dj tommy vee stay] [http://soler.net.cn/data/fiat-bravo.htm fiat bravo 155 20v hgt] [http://joperan.org/data/andrews-virginia/ andrews virginia libri] [http://polex.com.cn/resources/articles/gobi-centrale.htm gobi centrale] [http://budget7i.info/lib/aldrovandi-ulisse/ aldrovandi, ulisse] [http://xionny.cn/topic/recensione-di/ recensione di madame bovary] [http://veggis.org.cn/resources/articles/mines.htm mines] [http://funkall.us/images/small/lupen-lll/ lupen lll] [http://budget7i.info/lib/labiau/ labiau] [http://polex.com.cn/resources/articles/immagine-varia.htm immagine varia sito] [http://wedner.info/content/view/pentagono-caserta.htm pentagono caserta] [http://klohy.info/img/styles/luca-alinari.htm luca alinari] [http://joperan.org/data/spille-pera/ spille pera] [http://joperan.org/data/finanziamento-perugia/ finanziamento perugia] [http://funkall.us/images/small/cochise/ cochise] [http://wedner.info/content/view/armillariella.htm armillariella] [http://xionny.cn/topic/guerra-tattica/ guerra tattica] [http://joperan.org/data/ghisalba/ ghisalba] [http://veggis.org.cn/resources/articles/tecnologie-educative.htm tecnologie educative] [http://primonona.info/content/view/sbloccare-cellulare/ sbloccare cellulare 3] [http://sneck.info/data/samsung-sf/ samsung sf-330] [http://soler.net.cn/data/philips-magic.htm philips magic 3] [http://polex.com.cn/resources/articles/navigatore-per.htm navigatore per palmare] [http://polex.com.cn/resources/articles/ozone-mai.htm ozone mai a ii] [http://klohy.info/img/styles/sexy-shop.htm sexy shop napoli] [http://joperan.org/data/kylie-minogue/ kylie minogue i believe in you] [http://polex.com.cn/resources/articles/eamon-solo.htm eamon solo] [http://joperan.org/data/borsa/ borsa] [http://wedner.info/content/view/termozeta-la.htm termozeta la veloce] [http://xionny.cn/topic/tettone-fotoi/ tettone fotoi] [http://klohy.info/img/styles/mazda-.htm mazda xedos 6 2.0i v6 24v] [http://funkall.us/images/small/phim-de/ phim de coi] [http://manoke.cn/topic/nokia-cellulari/ nokia cellulari 6100] [http://manoke.cn/topic/play/ play 2] [http://budget7i.info/lib/vietsex/ vietsex] [http://wedner.info/content/view/sapphire-.htm sapphire 9600 atlantis] [http://manoke.cn/topic/harry-potter/ harry potter il prigioniero di azkaban] [http://veggis.org.cn/resources/articles/casse-logitech.htm casse logitech thx] [http://klohy.info/img/styles/creative-i.htm creative i trigue 5600] [http://veggis.org.cn/resources/articles/bubble-soccer.htm bubble soccer] [http://veggis.org.cn/resources/articles/gpsmart-fortuna.htm gpsmart fortuna] [http://polex.com.cn/resources/articles/hidroneumaticos.htm hidroneumaticos] [http://polex.com.cn/resources/articles/stand-by.htm stand by me ben e king] [http://polex.com.cn/resources/articles/tiromancino-amore.htm tiromancino amore impossibile] [http://xionny.cn/topic/the-lions/ the lions sleeps tonight] [http://budget7i.info/lib/jimsplace/ jimsplace] [http://veggis.org.cn/resources/articles/heather-mcquaid.htm heather mcquaid] [http://manoke.cn/topic/cd-alan/ cd alan parsons] [http://joperan.org/data/turn-me/ turn me on de kevin little] [http://wedner.info/content/view/hotel-in.htm hotel in sousse] [http://manoke.cn/topic/pirandello-l/ pirandello l esclusa] [http://joperan.org/data/californication-tabs/ californication tabs] [http://funkall.us/images/small/indaco-dagli/ indaco dagli occhi dal cielo zucchero] [http://polex.com.cn/resources/articles/autocad-.htm autocad 2005 lt ita] [http://xionny.cn/topic/card-tv/ card tv] [http://joperan.org/data/aspirapolvere/ aspirapolvere 1400] [http://budget7i.info/lib/intervallo-qt/ intervallo qt lungo] [http://joperan.org/data/bulma-chichi/ bulma chichi c18] [http://sneck.info/data/wisin/ wisin] [http://primonona.info/content/view/bugle/ bugle] [http://manoke.cn/topic/trasferimento-a/ trasferimento a caldo] [http://soler.net.cn/data/ci-vorrebbe.htm ci vorrebbe un amico] [http://joperan.org/data/bilancia-antica/ bilancia antica] [http://funkall.us/images/small/concetto-di/ concetto di marketing] [http://klohy.info/img/styles/picro.htm picro] [http://budget7i.info/lib/yamaha-ns/ yamaha ns p240] [http://svike.info/view/new/svideo-scart.htm s-video scart jack] [http://klohy.info/img/styles/work.htm work] [http://svike.info/view/new/gps-pda.htm gps pda mio] [http://xionny.cn/topic/topless-nel/ topless nel grande fratello] [http://funkall.us/images/small/genziana/ genziana] [http://joperan.org/data/cambiolavoro/ cambiolavoro] [http://primonona.info/content/view/anello-elica/ anello elica] [http://soler.net.cn/data/ramazzotti-ti.htm ramazzotti ti sposero] [http://svike.info/view/new/second-sight.htm second sight] [http://soler.net.cn/data/ape-maia.htm ape maia in concerto mp3] [http://klohy.info/img/styles/dvd-sony.htm dvd sony] [http://funkall.us/images/small/nazionale-italiana/ nazionale italiana pallavolo] [http://sneck.info/data/la-cronaca/ la cronaca degli scandali] [http://joperan.org/data/ascolta-radio/ ascolta radio] [http://primonona.info/content/view/sota-industries/ sota industries] [http://polex.com.cn/resources/articles/motore-di.htm motore di ricerca mp3] [http://svike.info/view/new/casseforti-e.htm casseforti e armadi di sicurezza] [http://xionny.cn/topic/scarpe-northwave/ scarpe northwave] [http://soler.net.cn/data/videocamere-mini.htm videocamere mini dv e memory stick] [http://funkall.us/images/small/nissan-terrano/ nissan terrano 2 7 2000] [http://veggis.org.cn/resources/articles/prova-di.htm prova di italiano maturita 2003 04] [http://wedner.info/content/view/maxtor-diamondmax.htm maxtor diamondmax 300 hard disk e floppy] [http://joperan.org/data/quattro-morti/ quattro morti irrequieti] [http://polex.com.cn/resources/articles/quinto-vicentino.htm quinto vicentino] [http://polex.com.cn/resources/articles/custodia-rigida.htm custodia rigida chitarra] [http://klohy.info/img/styles/bullot-time.htm bullot time] [http://joperan.org/data/onkyo-dvd/ onkyo dvd 501] [http://primonona.info/content/view/un-matrimonio/ un matrimonio] [http://xionny.cn/topic/trasmettitore-segnale/ trasmettitore segnale telecomando] [http://sneck.info/data/leonardodavinci/ leonardodavinci] [http://klohy.info/img/styles/kay-tracid.htm kay tracid] [http://manoke.cn/topic/antenna-per/ antenna per radio] [http://primonona.info/content/view/designjet-plus/ designjet plus] [http://soler.net.cn/data/excite.htm excite] [http://soler.net.cn/data/www-dmc.htm www dmc com tr] [http://wedner.info/content/view/hair-cd.htm hair cd] [http://xionny.cn/topic/fighe-aperte/ fighe aperte] [http://primonona.info/content/view/su-puo/ su puo dare di piu] [http://polex.com.cn/resources/articles/e-stato.htm e stato tanto tempo fa di simone] [http://joperan.org/data/hits-of/ hits of the 90s. classic music video] [http://budget7i.info/lib/painkiller-pc/ painkiller pc] [http://wedner.info/content/view/sexmon.htm sexmon] [http://soler.net.cn/data/asus-antenna.htm asus antenna mouse gps e accessori] [http://klohy.info/img/styles/i-segreti.htm i segreti di twin peaks] [http://polex.com.cn/resources/articles/salvatore-spoto.htm salvatore spoto] [http://wedner.info/content/view/corporate-gifts.htm corporate gifts] [http://soler.net.cn/data/blondin.htm blondin] [http://xionny.cn/topic/defend/ defend] [http://budget7i.info/lib/verdetto-finale/ verdetto finale] [http://budget7i.info/lib/ipaq-hp/ ipaq hp 1930] [http://xionny.cn/topic/puta-con/ puta con] [http://polex.com.cn/resources/articles/motorola-c.htm motorola c350 driver win xp] [http://klohy.info/img/styles/corsi-recitazione.htm corsi recitazione pisa] [http://soler.net.cn/data/www-humortadela.htm www humortadela com br] [http://klohy.info/img/styles/brigitta-boobs.htm brigitta boobs] [http://manoke.cn/topic/orexina/ orexina] [http://wedner.info/content/view/aspire-wlmi.htm aspire 1522wlmi athlon 64] [http://funkall.us/images/small/scoobydoo-e/ scooby-doo e la casa dei fantasmi] [http://svike.info/view/new/vogatore-carnielli.htm vogatore carnielli skiff] [http://soler.net.cn/data/euro.htm euro2] [http://sneck.info/data/dumb/ dumb] [http://svike.info/view/new/nelly-futardo.htm nelly futardo] [http://primonona.info/content/view/chicas-speed/ chicas speed] [http://veggis.org.cn/resources/articles/greatest-hits.htm greatest hits blue cd musicali] [http://sneck.info/data/napoli-magazine/ napoli magazine com] [http://primonona.info/content/view/anita-dark/ anita dark] [http://polex.com.cn/resources/articles/wireless-monitor.htm wireless monitor] [http://sneck.info/data/student-microsoft/ student microsoft] [http://sneck.info/data/lettore-dvd/ lettore dvd divx portatile toshiba] {{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 11:44, 28 August 2007
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 }