Hash from two arrays: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
(revert spam)
Line 1: Line 1:
{{task}}
[http://saibso.org/top.htm top 10 1985] [http://davte.info/library/html/mfc-cn.htm mfc 3340cn] [http://chaba.info/rs-mmc/ rs mmc 256 dv nokia 6680] [http://davte.info/library/html/olivia-del.htm olivia del rio video] [http://helmed.info/topic/arctic/ arctic 5] [http://amohseni.info/img/styles/siemens-sl/ siemens sl 100] [http://bloprofeldi.info/lib/www-americatv.htm www americatv com] [http://nobinters.org/catene-damore.htm catene damore] [http://saibso.org/ram-ddr.htm ram ddr ii 512] [http://nobinters.org/messaggio-festa.htm messaggio festa donna] [http://bloprofeldi.info/lib/anonima-peccati.htm anonima peccati] [http://kinunia.cn/rotten-porno.htm rotten porno] [http://amohseni.info/img/styles/isla-negra/ isla negra] [http://bloprofeldi.info/lib/pagamento-rav.htm pagamento rav] [http://chaba.info/hotels-/ hotels - lituania] [http://ustall.org/web/sapphire-radeon.htm sapphire radeon x850 pro] [http://ustall.org/web/da-tavolo.htm da tavolo orologi] [http://saibso.org/franco-zeffirelli.htm franco zeffirelli la traviata] [http://ustall.org/web/ponderano.htm ponderano] [http://kinunia.cn/sony-.htm sony - dscv3] [http://nobinters.org/modem-v.htm modem v92 usb] [http://bloprofeldi.info/lib/kisskiss.htm kiss-kiss] [http://nobinters.org/ciambelle.htm ciambelle] [http://ustall.org/web/lied-vom.htm lied vom] [http://saibso.org/fuori-strada.htm fuori strada subaru] [http://nobinters.org/baggio-e.htm baggio e le donne] [http://nobinters.org/tastierino-ps.htm tastierino ps2] [http://helmed.info/topic/stoffa/ stoffa] [http://chaba.info/comincero-da/ comincero da te] [http://kinunia.cn/prestito-cesano.htm prestito cesano maderno] [http://nobinters.org/un-piacevole.htm un piacevole imbroglio] [http://saibso.org/lesbo-toscana.htm lesbo toscana] [http://bloprofeldi.info/lib/cartoni-sexi.htm cartoni sexi gratis] [http://amohseni.info/img/styles/nokia/ nokia 3310] [http://ustall.org/web/lost-in.htm lost in translation film dvd] [http://helmed.info/topic/cinema-uci/ cinema uci casalecchio di reno] [http://helmed.info/topic/lanier/ lanier 5813] [http://bloprofeldi.info/lib/giochi-di.htm giochi di guerra gratis] [http://bloprofeldi.info/lib/cambiolavoro.htm cambiolavoro] [http://bloprofeldi.info/lib/inviare-suoneria.htm inviare suoneria] [http://psisemiya.com/images/small/tappetino-playstation/ tappetino playstation 2] [http://davte.info/library/html/www-lg.htm www lg it] [http://chaba.info/natura-toscana/ natura toscana vacanza] [http://ustall.org/web/pensione-a.htm pensione a catania] [http://helmed.info/topic/judas/ judas] [http://amohseni.info/img/styles/esame-avvocati/ esame avvocati genova 2004] [http://amohseni.info/img/styles/alpacca/ alpacca] [http://saibso.org/usb-tuner.htm usb tuner] [http://helmed.info/topic/c-s/ c s a palermo] [http://ashythro.info/library/html/fagiani-starne/ fagiani starne] [http://nobinters.org/dj-console.htm dj console] [http://chaba.info/danza-invisible/ danza invisible] [http://helmed.info/topic/foto-gattini/ foto gattini] [http://amohseni.info/img/styles/cool-boarders/ cool boarders 3] [http://psisemiya.com/images/small/under-pressure/ under pressure] [http://helmed.info/topic/taube-otto/ taube, otto von-] [http://saibso.org/georges-bizet.htm georges bizet] [http://nobinters.org/gratis-film.htm gratis film lesbo] [http://nobinters.org/la-gentilezza.htm la gentilezza del tocco] [http://kinunia.cn/donne-che.htm donne che cercano uomo relazione sesso] [http://ashythro.info/library/html/portugalia-milano/ portugalia milano natal] [http://nobinters.org/kenzo-eau.htm kenzo eau] [http://chaba.info/testi-alanis/ testi alanis morisette] [http://kinunia.cn/trials.htm trials] [http://psisemiya.com/images/small/activa-si/ activa si computer] [http://chaba.info/messaggi-personali/ messaggi personali] [http://davte.info/library/html/philips-.htm philips 19 lcd 190s6] [http://nobinters.org/sunrise-com.htm sunrise com] [http://chaba.info/audizioni-attori/ audizioni attori] [http://davte.info/library/html/anello-topazio.htm anello topazio azzurro] [http://saibso.org/soggiorni-linguistici.htm soggiorni linguistici spagna] [http://bloprofeldi.info/lib/kenwood-sw.htm kenwood sw 18 ht] [http://ustall.org/web/benq-pb.htm benq pb 6210] [http://bloprofeldi.info/lib/d-onofrio.htm d onofrio] [http://ustall.org/web/traduttore-italiano.htm traduttore italiano spagnolo] [http://ustall.org/web/jail.htm jail] [http://ashythro.info/library/html/kit-home/ kit home theatre con divx] [http://ustall.org/web/mutuo-woolwich.htm mutuo woolwich] [http://amohseni.info/img/styles/audio-comico/ audio comico zelig] [http://chaba.info/pomp-it/ pomp it up] [http://ustall.org/web/mack-the.htm mack the knife] [http://amohseni.info/img/styles/gorgol/ gorgol] [http://psisemiya.com/images/small/archiviosex/ archiviosex] [http://bloprofeldi.info/lib/calendario-sonia.htm calendario sonia] [http://helmed.info/topic/crime-scene/ crime scene investigation] [http://davte.info/library/html/bmw-.htm bmw 320 d rm] [http://amohseni.info/img/styles/st-john/ st john cose fare] [http://nobinters.org/fisarmonica-castellina.htm fisarmonica castellina pasi] [http://psisemiya.com/images/small/hp-procurve/ hp procurve 2824] [http://amohseni.info/img/styles/micro-hifi/ micro hi-fi dvd cmt-dv2d] [http://nobinters.org/incontri-amatoriali.htm incontri amatoriali gratis] [http://davte.info/library/html/scythe-ncu.htm scythe ncu-2000] [http://davte.info/library/html/caricabatterie-aa.htm caricabatterie aa] [http://chaba.info/cambogia/ cambogia] [http://nobinters.org/plug-in.htm plug in dolby digital 2 nero 6 3 1 20] [http://bloprofeldi.info/lib/mediasetonline.htm mediasetonline] [http://nobinters.org/s-is.htm s2 is] [http://davte.info/library/html/sony-zeiss.htm sony zeiss] [http://davte.info/library/html/giardino-illuminazione.htm giardino illuminazione] [http://saibso.org/radeon.htm radeon 9250 256] [http://chaba.info/tecmo-bowl/ tecmo bowl] [http://amohseni.info/img/styles/giochi-pc/ giochi pc recensione] [http://amohseni.info/img/styles/energizer-a/ energizer a76] [http://davte.info/library/html/free-nude.htm free nude pictures] [http://helmed.info/topic/and-/ and 1 basket] [http://ustall.org/web/anna-popplewell.htm anna popplewell] [http://davte.info/library/html/numer-raz.htm numer raz chwila] [http://kinunia.cn/spanish-speaking.htm spanish speaking countrys] [http://saibso.org/mercedes-a.htm mercedes a 2005 mi] [http://amohseni.info/img/styles/vl-zs/ vl z500s] [http://helmed.info/topic/grey-sonia/ grey sonia] [http://ashythro.info/library/html/schiave-albanesi/ schiave albanesi com] [http://saibso.org/ysl.htm ysl 2015] [http://davte.info/library/html/the-stone.htm the stone roses. the dvd] [http://chaba.info/golpeado/ golpeado] [http://ashythro.info/library/html/mirza-part/ mirza part 2] [http://davte.info/library/html/spam-antivirus.htm spam antivirus liberi] [http://psisemiya.com/images/small/acquisti-on/ acquisti on line shopping] [http://chaba.info/amore-e/ amore e pallottole] [http://ustall.org/web/taglio-laser.htm taglio laser lamiera] [http://chaba.info/marco-filoni/ marco filoni] [http://nobinters.org/nuova-volkswagen.htm nuova volkswagen golf gti benzina auto] [http://davte.info/library/html/obsecion-de.htm obsecion de aventura] [http://amohseni.info/img/styles/decapitazione-quattrochi/ decapitazione quattrochi] [http://bloprofeldi.info/lib/spill-control.htm spill control] [http://ashythro.info/library/html/www-gruesom/ www gruesom videos com] [http://ustall.org/web/varadero.htm varadero 1000] [http://amohseni.info/img/styles/murizio-arceri/ murizio arceri] [http://davte.info/library/html/londra-hotel.htm londra hotel 4 stelle] [http://bloprofeldi.info/lib/naked-news.htm naked news in lingua italiana] [http://kinunia.cn/naomi.htm naomi] [http://psisemiya.com/images/small/colpisci-in/ colpisci in testa con un osso] [http://ustall.org/web/differenze.htm differenze] [http://ustall.org/web/evanescence-video.htm evanescence video] [http://kinunia.cn/canon-videocamere.htm canon videocamere dvd] [http://helmed.info/topic/lettore-multimediale/ lettore multimediale ipod] [http://davte.info/library/html/i-m.htm i m coming out] [http://nobinters.org/drinn.htm drinn] [http://helmed.info/topic/mute-neoprene/ mute neoprene] [http://chaba.info/iraqi-money/ iraqi money value] [http://ashythro.info/library/html/kenwood-mask/ kenwood mask] [http://ustall.org/web/chitarre-semiacustiche.htm chitarre semiacustiche] [http://ustall.org/web/software-dj.htm software dj] [http://bloprofeldi.info/lib/amstrad-dxs.htm amstrad dxs] [http://kinunia.cn/cavo-audio.htm cavo audio] [http://helmed.info/topic/emergenza-spirituale/ emergenza spirituale] [http://psisemiya.com/images/small/masterizzatore-notebook/ masterizzatore notebook] [http://saibso.org/www-rdi.htm www rdi romanian digital info] [http://nobinters.org/tv-lcd.htm tv lcd lg rz-20lz50] [http://davte.info/library/html/hub-di.htm hub di rete] [http://ustall.org/web/rocco-casalino.htm rocco casalino] [http://helmed.info/topic/npfs/ np-fs 31] [http://saibso.org/lettore-registratore.htm lettore registratore dvd vhs] [http://ashythro.info/library/html/philips-pss/ philips pss110 mp3] [http://bloprofeldi.info/lib/kettler-ab.htm kettler ab former] [http://amohseni.info/img/styles/kameleon-urc/ kameleon urc8206] [http://kinunia.cn/midi-ray.htm midi ray charles] [http://chaba.info/palle-al/ palle al balzo] [http://kinunia.cn/www-tiscali.htm www tiscali annunci] [http://chaba.info/rsmmc-dv/ rs-mmc dv da 512 mb] [http://saibso.org/jack-del.htm jack del cactus] [http://psisemiya.com/images/small/libertando-piano/ libertando piano] [http://saibso.org/miconos-alberghi.htm miconos alberghi e hotel] [http://chaba.info/donne-nude/ donne nude da inculare] [http://ashythro.info/library/html/multisala-cinelandia/ multisala cinelandia gallarate] [http://nobinters.org/storia-di.htm storia di pinocchio] [http://chaba.info/urfa/ urfa] [http://amohseni.info/img/styles/vatican-anthem/ vatican anthem] [http://nobinters.org/diaz-bartholomeu.htm diaz, bartholomeu] [http://bloprofeldi.info/lib/serial-clone.htm serial clone dvd] [http://nobinters.org/kenwood-gps.htm kenwood gps] [http://kinunia.cn/califano-la.htm califano la mia liberta] [http://davte.info/library/html/pila-cr.htm pila cr2032] [http://ustall.org/web/honda-civic.htm honda civic 1.4] [http://davte.info/library/html/sms-gratis.htm sms gratis senza registrazione] [http://nobinters.org/sms-gain.htm sms gain] [http://ashythro.info/library/html/black-eyed/ black eyed peas get the party started] [http://ustall.org/web/a-home.htm a920 home theater] [http://davte.info/library/html/www-nellyville.htm www nellyville com] [http://nobinters.org/memory-card.htm memory card lettore hard] [http://psisemiya.com/images/small/foto-sesso/ foto sesso tawnee stone] [http://kinunia.cn/pan-jabi.htm pan jabi] [http://amohseni.info/img/styles/online-il/ online il sito di gtr the ultimate racing game] [http://davte.info/library/html/es-por.htm es por ti] [http://kinunia.cn/partita-on.htm partita on line] [http://davte.info/library/html/exel.htm exel] [http://kinunia.cn/televisioni-lcd.htm televisioni lcd sony] [http://nobinters.org/apple.htm apple 23] [http://saibso.org/come-partivano.htm come partivano i lenti] [http://psisemiya.com/images/small/testo-furb/ testo furb] [http://bloprofeldi.info/lib/uomini-gay.htm uomini gay belli] [http://bloprofeldi.info/lib/poster-vendita.htm poster vendita] [http://chaba.info/batterie-cellulari/ batterie cellulari motorola] [http://bloprofeldi.info/lib/masini-e.htm masini e ti mao] [http://ustall.org/web/dj-aligator.htm dj aligator and vspishkin davaj] [http://amohseni.info/img/styles/yeti-/ yeti sports] [http://davte.info/library/html/vertigine-di.htm vertigine di una notte] [http://psisemiya.com/images/small/thrustmaster-top/ thrustmaster top gun joystick] [http://davte.info/library/html/ralph-polo.htm ralph polo] [http://kinunia.cn/wolfenstein.htm wolfenstein 3] {{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)


==[[C plus plus|C ]]==
==[[C plus plus|C++]]==
[[Category:C plus plus]]
[[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).
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
'''Compiler:''' g++ 4.0.2


#include <map>
#include <map>
Line 20: Line 20:
std::map< std::string, std::string > hash ;
std::map< std::string, std::string > hash ;
for( int i = 0 ; i < 3 ; i )
for( int i = 0 ; i < 3 ; i++ )
{
{
hash[ keys[i] ] = vals[i] ;
hash[ keys[i] ] = vals[i] ;
Line 39: Line 39:
std::map<std::string, std::string> hash;
std::map<std::string, std::string> hash;
std::transform(keys, keys 3,
std::transform(keys, keys+3,
vals,
vals,
std::inserter(hash, hash.end()),
std::inserter(hash, hash.end()),
Line 58: Line 58:
}
}
for( int i = 0; i < arg_length; i ){
for( int i = 0; i < arg_length; i++ ){
h.add( arg_keys[i], arg_values[i] );
h.add( arg_keys[i], arg_values[i] );
}
}
Line 64: Line 64:
Alternate way of adding values
Alternate way of adding values


for( int i = 0; i < arg_length; i ){
for( int i = 0; i < arg_length; i++ ){
h[ arg_keys[i] ] = arg_values[i];
h[ arg_keys[i] ] = arg_values[i];
}
}
Line 151: Line 151:
$values = array(1, 2, 3);
$values = array(1, 2, 3);
$hash = array();
$hash = array();
for ($idx = 0; $idx < count($keys); $idx ) {
for ($idx = 0; $idx < count($keys); $idx++) {
$hash[$keys[$idx]] = $values[$idx];
$hash[$keys[$idx]] = $values[$idx];
}
}

Revision as of 01:18, 18 August 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)

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 }