Hash from two arrays: Difference between revisions

From Rosetta Code
Content added Content deleted
(Added a C++ version.)
Line 2: Line 2:


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++]]==

By strict definition a std::map is not a hash, but it provides the same functionality.

#include <map>
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] ;
}
}


==[[Perl]]==
==[[Perl]]==

Revision as of 03:48, 23 January 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.

#include <map>

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] ;
 }
}

Perl

Interpreter: Perl 5.8.8

Short

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

Mid Length

my @keys = ('a', 'b', 'c');
my @vals = (1, 2, 3);
my %hash;
$hash{$keys[$_]} = $vals[$_] for (0 .. $#keys);

Long

my @keys = ('a', 'b', 'c');
my @vals = (1, 2, 3);
my %hash;
foreach my $idx (0..$#keys){
  $hash{$keys[$idx]} = $vals[$idx];
}

Ruby

 keys=['hal',666,[1,2,3]]
 vals=['ibm','devil',123]
 hash={}
 keys.zip(vals).each {|key,val| hash[key] = val}
 #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

C#

 System.Collections.HashTable h = new System.Collections.HashTable();
 
 string[] arg_keys = {"foo","bar","val"};
 string[] arg_values = {"little", "miss", "muffet"};
   
 //I added this to just have some basic error checking
 int arg_length = arg_keys.Length == arg_values.Length ? arg_keys.Length : 0;
 
 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]; 
 }

Python

Interpreter: Python 2.5

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