Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,5 @@
---
category:
- Data Structures
from: http://rosettacode.org/wiki/Hash_from_two_arrays
note: Basic language learning

View file

@ -0,0 +1,10 @@
;Task:
Using two Arrays of equal length, create a Hash object
where the elements from one array (the keys) are linked
to the elements of the other (the values)
;Related task:
*   [[Associative arrays/Creation]]
<br><br>

View file

@ -0,0 +1,4 @@
V keys = [a, b, c]
V values = [1, 2, 3]
V hash_ = Dict(zip(keys, values))
print(hash_)

View file

@ -0,0 +1,11 @@
# usage: awk -v list1="i ii iii" -v list2="1 2 3" -f hash2.awk
BEGIN {
if(!list1) list1="one two three"
if(!list2) list2="1 2 3"
split(list1, a);
split(list2, b);
for(i=1;i in a;i++) { c[a[i]] = b[i] };
for(i in c) print i,c[i]
}

View file

@ -0,0 +1,15 @@
package
{
public class MyClass
{
public static function main():Void
{
var hash:Object = new Object();
var keys:Array = new Array("a", "b", "c");
var values:Array = new Array(1, 2, 3);
for (var i:int = 0; i < keys.length(); i++)
hash[keys[i]] = values[i];
}
}
}

View file

@ -0,0 +1,43 @@
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;

View file

@ -0,0 +1,102 @@
#!/usr/bin/hopper
#include <hopper.h>
main:
new hash(h)
add hash(h,"chile" :: 100)
add hash(h,"argentina"::200)
add hash(h,"brasil"::300)
{"\nLongitud HASH: "},len hash(h),println
println(hash(h))
println( get value("argentina",h) )
println( get value("chile",h) )
try
println( get value("guyana",h) )
catch(e)
{"***[",e,"]: "}get str error,println
finish
println( get key(300,h) )
println( get key(100,h) )
mod value("chile",101,h)
mod key(200,"madagascar",h)
try
mod key(130,"londres",h)
println( get key(130,h) )
catch(e)
{"***[",e,"]: "}get str error,println
finish
println( get key(200,h) )
println( get value("chile",h) )
println("HASH actual: \n")
println(hash(h))
{"\nLongitud HASH: "},len hash(h),println
put after value (200,"colombia",400,h)
put value (200,"mexico",401,h)
println(hash(h))
put after key ("chile","antartida",110,h)
put key ("chile","peru",99,h)
println("HASH actual: \n")
println(hash(h))
{"\nLongitud HASH: "},len hash(h),println
del by key("brasil",h)
del by value(101,h)
{"\nLongitud HASH: "},len hash(h),println
println(hash(h))
sort hash(h)
{"\nORDENADO: \n"}println
println(hash(h))
y={} // para un stack de arreglos.
x=0,{5,5}rand array(x)
{x}push(y)
add hash(h,"arreglo 1"::x)
{"Ojalá que llueva café en el campo"}strtoutf8,push(y)
clear(x),w=0,{6,2}rand array(w)
{w}push(y)
add hash(h,"arreglo 2"::w)
clear(w)
add hash(h,"objeto",y)
println(hash(h))
println("arreglo 2?\n")
get value("arreglo 2",h)
println
println("arreglo 1?\n")
get value("arreglo 1",h)
println
/* NO PUEDES ORDENAR UN HASH QUE CONTENGA ARRAYS
PORQUE SE BLOQUEARA EL PROGRAMA:
sort hash(h)
{"\nORDENADO: \n"}println
println(hash(h)) */
println("Objeto?\n")
get value("objeto",h)
z=0,mov(z)
/* Esto fallará, porque no se puede hacer un
push de pushs*/
pop(z),println
pop(z),println
pop(z),println
{"Esto significa que no puedes meter un stack dentro de un hash\nsolo arrays de cualquier dimension"}println
/* esto está bien, porque es un stack simple
aunque contenga arreglos como elementos. */
pop(y),println
{"Dato en la última posición del stack:"}strtoutf8,{"\n"},[1:end,1:end]get(y),println
{"Esto significa que, si vas a meter arreglos dentro de un stack\nsácalos con POP antes de usarlo"}strtoutf8,println
pop(y),println
pop(y),println
pause
exit(0)

View file

@ -0,0 +1,51 @@
/* macros HASH */
#defn createhash(_X_) _X__KEY={#VOID},_X__HASH={#VOID}
#synon createhash newhash
#defn addhash(_X_,_K_,_H_) {_H_}push(_X__HASH),{_K_}push(_X__KEY)
#defn getvalue(_X_,_Y_) _Y_03Rx0W91=0,{_X_,_Y__KEY},array(1),dup,zero?do{{"getvalue: key not found"}throw(2000)}\
mov(_Y_03Rx0W91),[_Y_03Rx0W91]get(_Y__HASH),clearmark,
#defn getkey(_X_,_Y_) _Y_03Rx0W91=0,{_X_,_Y__HASH},array(1),dup,zero?do{{"getkey: value not found"}throw(2001)}\
mov(_Y_03Rx0W91),[_Y_03Rx0W91]get(_Y__KEY),clearmark,
#defn modvalue(_K_,_H_,_X_) _Y_03Rx0W91=0,{_K_,_X__KEY},array(1),dup,zero?do{{"modvalue: key not found"}throw(2002)}\
mov(_Y_03Rx0W91),[_Y_03Rx0W91]{_H_}put(_X__HASH),clearmark,
#defn modkey(_H_,_K_,_X_) _Y_03Rx0W91=0,{_H_,_X__HASH},array(1),dup,zero?do{{"modkey: value not found"}throw(2003)}\
mov(_Y_03Rx0W91),[_Y_03Rx0W91]{_K_}put(_X__KEY),clearmark,
#defn putaftervalue(_H_,_K_,_V_,_X_) _X_03Rx0W91=0,{_H_,_X__HASH},array(1),dup,zero?do{{"putaftervalue: value not found"}throw(2006)}\
plus(1),mov(_X_03Rx0W91),{_K_}{_X_03Rx0W91,_X__KEY}array(3),\
{_V_}{_X_03Rx0W91,_X__HASH}array(3)
#defn putvalue(_H_,_K_,_V_,_X_) _X_03Rx0W91=0,{_H_,_X__HASH},array(1),dup,zero?do{{"putvalue: value not found"}throw(2006)}\
mov(_X_03Rx0W91),{_K_}{_X_03Rx0W91,_X__KEY}array(3),\
{_V_}{_X_03Rx0W91,_X__HASH}array(3),
#defn putafterkey(_H_,_K_,_V_,_X_) _X_03Rx0W91=0,{_H_,_X__KEY},array(1),dup,zero?do{{"putafterkey: key not found"}throw(2007)}\
plus(1),mov(_X_03Rx0W91),{_K_}{_X_03Rx0W91,_X__KEY}array(3),\
{_V_}{_X_03Rx0W91,_X__HASH}array(3),
#defn putkey(_H_,_K_,_V_,_X_) _X_03Rx0W91=0,{_H_,_X__KEY},array(1),dup,zero?do{{"putkey: value not found"}throw(2008)}\
mov(_X_03Rx0W91),{_K_}{_X_03Rx0W91,_X__KEY}array(3),\
{_V_}{_X_03Rx0W91,_X__HASH}array(3),
#defn delbyvalue(_H_,_X_) {_H_,_X__HASH},array(1),dup,zero?do{{"delbyvalue: value not found"}throw(2004)},\
{_X__KEY},keep,array(4),{_X__HASH},array(4),clearstack
#defn delbykey(_K_,_X_) {_K_,_X__KEY},array(1),dup,zero?do{{"delbykey: key not found"}throw(2005)},\
{_X__KEY},keep,array(4),{_X__HASH},array(4),clearstack
#defn sorthash(_X_) #RAND,_LEN_#RNDV=0,_DUP_H#RNDV=_X__HASH,_DUP_K#RNDV=_X__KEY,\
{_X__KEY}keep,length,mov(_LEN_#RNDV),array(0),\
_POS_#RNDV=0,_HASH_LOOP_#RNDV:,[_LEN_#RNDV]get(_X__KEY),{_DUP_K#RNDV}array(1),\
mov(_POS_#RNDV),[_POS_#RNDV]get(_DUP_H#RNDV),[_LEN_#RNDV]put(_X__HASH),\
--_LEN_#RNDV,{_LEN_#RNDV},jnz(_HASH_LOOP_#RNDV),clear(_DUP_H#RNDV),clear(_DUP_K#RNDV)
#defn lenhash(_X_) {_X__HASH}length,
#defn hash(_X_) #RAND,_TMP_#RNDV=0,{_X__HASH,_X__KEY}catcol(_TMP_#RNDV),{_TMP_#RNDV},clear(_TMP_#RNDV),
/* Other... */
/* TRY/CATCH */
#defn try swtrap( #CATCH ),
#defn raise(_ERR_,_M_) {_M_}, throw(_ERR_),
#defn catch(_X_) jmp(#ENDCATCH), %CATCH:, clearstack,_X_=0, gettry(_X_), // gettry hace poptry internamente?
#defn finish %ENDCATCH:, popcatch
/* print... */
#defn println(_X_) #ATOM #CMPLX,{"\n"} print
#define println {"\n"}print

View file

@ -0,0 +1,8 @@
use std, array, hash
let keys = @["hexadecimal" "decimal" "octal" "binary"]
let values = @[0xa 11 014 0b1101] (: 10 11 12 13 :)
let hash = new hash of int
for each val int i from 0 to 3
hash[keys[i]] = values[i]
del hash hash

View file

@ -0,0 +1,2 @@
h: dictionary.raw flatten couple [a b c d] [1 2 3 4]
print h

View file

@ -0,0 +1,6 @@
array1 := ["two", "three", "apple"]
array2 := [2, 3, "fruit"]
hash := {}
Loop % array1.maxIndex()
hash[array1[A_Index]] := array2[A_Index]
MsgBox % hash["apple"] "`n" hash["two"]

View file

@ -0,0 +1,20 @@
DIM array1$(4) : array1$() = "0", "1", "2", "3", "4"
DIM array2$(4) : array2$() = "zero", "one", "two", "three", "four"
FOR index% = 0 TO DIM(array1$(),1)
PROCputdict(mydict$, array2$(index%), array1$(index%))
NEXT
PRINT FNgetdict(mydict$, "3")
END
DEF PROCputdict(RETURN dict$, value$, key$)
IF dict$ = "" dict$ = CHR$(0)
dict$ += key$ + CHR$(1) + value$ + CHR$(0)
ENDPROC
DEF FNgetdict(dict$, key$)
LOCAL I%, J%
I% = INSTR(dict$, CHR$(0) + key$ + CHR$(1))
IF I% = 0 THEN = "" ELSE I% += LEN(key$) + 2
J% = INSTR(dict$, CHR$(0), I%)
= MID$(dict$, I%, J% - I%)

View file

@ -0,0 +1,10 @@
two three apple:?arr1
& 2 3 fruit:?arr2
& new$hash:?H
& whl
' ( !arr1:%?k ?arr1
& !arr2:%?v ?arr2
& (H..insert)$(!k.!v)
)
& (H..forall)$out
& ;

View file

@ -0,0 +1,10 @@
zip = { keys, values |
h = [:]
keys.each_with_index { key, index |
h[key] = values[index]
}
h
}
p zip [1 2 3] [:a :b :c] #Prints [1: a, 2: b, 3: c]

View file

@ -0,0 +1,12 @@
#include <unordered_map>
#include <string>
int main()
{
std::string keys[] = { "1", "2", "3" };
std::string vals[] = { "a", "b", "c" };
std::unordered_map<std::string, std::string> hash;
for( int i = 0 ; i < 3 ; i++ )
hash[ keys[i] ] = vals[i] ;
}

View file

@ -0,0 +1,11 @@
#include <range/v3/view/zip.hpp>
#include <unordered_map>
#include <string>
int main()
{
std::string keys[] = { "1", "2", "3" };
std::string vals[] = { "foo", "bar", "baz" };
std::unordered_map<std::string, std::string> hash(ranges::view::zip(keys, vals));
}

View file

@ -0,0 +1,17 @@
static class Program
{
static void Main()
{
System.Collections.Hashtable h = new System.Collections.Hashtable();
string[] keys = { "foo", "bar", "val" };
string[] values = { "little", "miss", "muffet" };
System.Diagnostics.Trace.Assert(keys.Length == values.Length, "Arrays are not same length.");
for (int i = 0; i < keys.Length; i++)
{
h.Add(keys[i], values[i]);
}
}
}

View file

@ -0,0 +1 @@
h[keys[i]] = values[i];

View file

@ -0,0 +1,14 @@
using System.Linq;
static class Program
{
static void Main()
{
string[] keys = { "foo", "bar", "val" };
string[] values = { "little", "miss", "muffet" };
var h = keys
.Zip(values, (k, v) => (k, v))
.ToDictionary(keySelector: kv => kv.k, elementSelector: kv => kv.v);
}
}

View file

@ -0,0 +1,115 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define KeyType const char *
#define ValType int
#define HASH_SIZE 4096
// hash function useful when KeyType is char * (string)
unsigned strhashkey( const char * key, int max)
{
unsigned h=0;
unsigned hl, hr;
while(*key) {
h += *key;
hl= 0x5C5 ^ (h&0xfff00000 )>>18;
hr =(h&0x000fffff );
h = hl ^ hr ^ *key++;
}
return h % max;
}
typedef struct sHme {
KeyType key;
ValType value;
struct sHme *link;
} *MapEntry;
typedef struct he {
MapEntry first, last;
} HashElement;
HashElement hash[HASH_SIZE];
typedef void (*KeyCopyF)(KeyType *kdest, KeyType ksrc);
typedef void (*ValCopyF)(ValType *vdest, ValType vsrc);
typedef unsigned (*KeyHashF)( KeyType key, int upperBound );
typedef int (*KeyCmprF)(KeyType key1, KeyType key2);
void HashAddH( KeyType key, ValType value,
KeyCopyF copyKey, ValCopyF copyVal, KeyHashF hashKey, KeyCmprF keySame )
{
unsigned hix = (*hashKey)(key, HASH_SIZE);
MapEntry m_ent;
for (m_ent= hash[hix].first;
m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
if (m_ent) {
(*copyVal)(&m_ent->value, value);
}
else {
MapEntry last;
MapEntry hme = malloc(sizeof(struct sHme));
(*copyKey)(&hme->key, key);
(*copyVal)(&hme->value, value);
hme->link = NULL;
last = hash[hix].last;
if (last) {
// printf("Dup. hash key\n");
last->link = hme;
}
else
hash[hix].first = hme;
hash[hix].last = hme;
}
}
int HashGetH(ValType *val, KeyType key, KeyHashF hashKey, KeyCmprF keySame )
{
unsigned hix = (*hashKey)(key, HASH_SIZE);
MapEntry m_ent;
for (m_ent= hash[hix].first;
m_ent && !(*keySame)(m_ent->key,key); m_ent=m_ent->link);
if (m_ent) {
*val = m_ent->value;
}
return (m_ent != NULL);
}
void copyStr(const char**dest, const char *src)
{
*dest = strdup(src);
}
void copyInt( int *dest, int src)
{
*dest = src;
}
int strCompare( const char *key1, const char *key2)
{
return strcmp(key1, key2) == 0;
}
void HashAdd( KeyType key, ValType value )
{
HashAddH( key, value, &copyStr, &copyInt, &strhashkey, &strCompare);
}
int HashGet(ValType *val, KeyType key)
{
return HashGetH( val, key, &strhashkey, &strCompare);
}
int main()
{
static const char * keyList[] = {"red","orange","yellow","green", "blue", "violet" };
static int valuList[] = {1,43,640, 747, 42, 42};
int ix;
for (ix=0; ix<6; ix++) {
HashAdd(keyList[ix], valuList[ix]);
}
return 0;
}

View file

@ -0,0 +1,5 @@
shared void run() {
value keys = [1, 2, 3];
value items = ['a', 'b', 'c'];
value hash = map(zipEntries(keys, items));
}

View file

@ -0,0 +1 @@
(zipmap [\a \b \c] [1 2 3])

View file

@ -0,0 +1,5 @@
keys = <[apple banana orange grape]>
values = <[red yellow orange purple]>
object = new
@[keys[i]] = values[i] for i til keys.length

View file

@ -0,0 +1,4 @@
keys = ['a','b','c']
values = [1,2,3]
map = {}
map[key] = values[i] for key, i in keys

View file

@ -0,0 +1,14 @@
<cfscript>
function makeHash(keyArray, valueArray) {
var x = 1;
var result = {};
for( ; x <= ArrayLen(keyArray); x ++ ) {
result[keyArray[x]] = valueArray[x];
}
return result;
}
keyArray = ['a', 'b', 'c'];
valueArray = [1, 2, 3];
map = makeHash(keyArray, valueArray);
</cfscript>

View file

@ -0,0 +1,6 @@
(defun rosetta-code-hash-from-two-arrays (vector-1 vector-2 &key (test 'eql))
(assert (= (length vector-1) (length vector-2)))
(let ((table (make-hash-table :test test :size (length vector-1))))
(map nil (lambda (k v) (setf (gethash k table) v))
vector-1 vector-2)
table))

View file

@ -0,0 +1,7 @@
(defun rosetta-code-hash-from-two-arrays (vector-1 vector-2 &key (test 'eql))
(loop initially (assert (= (length vector-1) (length vector-2)))
with table = (make-hash-table :test test :size (length vector-1))
for k across vector-1
for v across vector-2
do (setf (gethash k table) v)
finally (return table)))

View file

@ -0,0 +1,5 @@
keys = ('a'..'z').to_a # => a, b, c ... z
vals = (1..26).to_a # => 1, 2, 3 ... 26
hash = Hash.zip(keys, vals)
p hash

View file

@ -0,0 +1,5 @@
void main() {
import std.array, std.range;
immutable hash = ["a", "b", "c"].zip([1, 2, 3]).assocArray;
}

View file

@ -0,0 +1,42 @@
program Hash_from_two_arrays;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Generics.Collections;
type
THash = TDictionary<string, Integer>;
THashHelper = class helper for THash
procedure AddItems(keys: TArray<string>; values: TArray<Integer>);
end;
{ THashHelper }
procedure THashHelper.AddItems(keys: TArray<string>; values: TArray<Integer>);
var
i: Integer;
begin
Assert(length(keys) = Length(values), 'Keys and values, must have the same size.');
for i := 0 to High(keys) do
AddOrSetValue(keys[i], values[i]);
end;
var
hash: TDictionary<string, Integer>;
i: integer;
key: string;
begin
hash := TDictionary<string, Integer>.Create();
hash.AddItems(['a', 'b', 'c'], [1, 2, 3]);
for key in hash.Keys do
Writeln(key, ' ', hash[key]);
hash.Free;
readln;
end.

View file

@ -0,0 +1,10 @@
use_namespace(rosettacode)_me();
add_ary(keysDict)_values(a,b,c);
add_ary(valsDict)_values(1,2,3);
add_dict(aDict)_map([keysDict],[valsDict]);
add_hash(aHash)_hash[valsDict]; // Keys will be new uuids
reset_namespace[];

View file

@ -0,0 +1,10 @@
use_namespace(rosettacode)_me();
add_dict(bDict);
add_dict(cDict);
add_for(i)_from(0)_lessthan()_[keysDict]_length()_inc()
with_dict(bDict)_mapkeys()_[keysDict]_at[i]_mapvals()_[valsDict]_at[i];
[cDict]_map()_[keysDict]_at[i]_[valsDict]_at[i]; // alternative shortened syntax
;
reset_namespace[];

View file

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

View file

@ -0,0 +1,10 @@
(lib 'hash)
(define H (make-hash))
(define keys '(elvis simon antoinette))
(define kvalues '("the king" "gallubert" "de gabolde d'Audan"))
(list->hash (map cons keys kvalues) H)
→ #hash:3
(hash-ref H 'elvis)
→ "the king"

View file

@ -0,0 +1,6 @@
iex(1)> keys = [:one, :two, :three]
[:one, :two, :three]
iex(2)> values = [1, 2, 3]
[1, 2, 3]
iex(3)> Enum.zip(keys, values) |> Enum.into(Map.new)
%{one: 1, three: 3, two: 2}

View file

@ -0,0 +1,3 @@
(let ((keys ["a" "b" "c"])
(values [1 2 3]))
(apply 'vector (cl-loop for i across keys for j across values collect (vector i j))))

View file

@ -0,0 +1 @@
Dictionary = dict:from_list( lists:zip([key1, key2, key3], [value1, 2, 3]) ).

View file

@ -0,0 +1 @@
HashMultiMap(Array.zip [|"foo"; "bar"; "baz"|] [|16384; 32768; 65536|], HashIdentity.Structural)

View file

@ -0,0 +1,2 @@
USING: hashtables ;
{ "one" "two" "three" } { 1 2 3 } zip >hashtable

View file

@ -0,0 +1,4 @@
keys = [ 'a', 'b', 'c', 'd' ]
values = [ 1, 2, 3, 4 ]
hash = [ => ]
for i in [ 0 : keys.len() ]: hash[ keys[ i ] ] = values[ i ]

View file

@ -0,0 +1,16 @@
class Main
{
public static Void main ()
{
keys := [1,2,3,4,5]
values := ["one", "two", "three", "four", "five"]
// create an empty map
map := [:]
// add the key-value pairs to it
keys.size.times |Int index|
{
map.add(keys[index], values[index])
}
}
}

View file

@ -0,0 +1,14 @@
Dim As String keys(1 To 5) = {"1", "2", "3", "4", "5"}
Dim As String values(1 To 5) = {"one", "two", "three", "four", "five"}
Dim As String hash(Lbound(keys) To Ubound(keys))
Dim As Integer i, temp
For i = Lbound(values) To Ubound(values)
temp = Val(keys(i))
hash(temp) = values(i)
Next i
For i = Lbound(hash) To Ubound(hash)
Print keys(i); " "; hash(i)'; " "; i
Next i
Sleep

View file

@ -0,0 +1 @@
a = new dict[["a", "b", "c"], [1, 2, 3]]

View file

@ -0,0 +1,12 @@
include "NSLog.incl"
void local fn DoIt
CFArrayRef keys = @[@"Key1",@"Key2",@"Key3",@"Key4"]
CFArrayRef values = @[@"One",@"Two",@"Three",@"O'Leary"]
CFDictionaryRef dict = fn DictionaryWithObjectsForKeys( values, keys )
NSLog(@"%@",dict)
end fn
fn DoIt
HandleEvents

View file

@ -0,0 +1,15 @@
Public Sub Main()
Dim sValue As String[] = ["Zero", "One", "Two", "Three", "Four", "Five"]
Dim sKey As String[] = [0, 1, 2, 3, 4, 5]
Dim sCol As New Collection
Dim siCount As Short
For siCount = 0 To sKey.max
sCol.Add(sValue[siCount], sKey[siCount])
Next
For siCount = 0 To sKey.max
Print Str(sicount) & " = " & sCol[siCount]
Next
End

View file

@ -0,0 +1,13 @@
package main
import "fmt"
func main() {
keys := []string{"a", "b", "c"}
vals := []int{1, 2, 3}
hash := map[string]int{}
for i, key := range keys {
hash[key] = vals[i]
}
fmt.Println(hash)
}

View file

@ -0,0 +1,6 @@
def keys = ['a','b','c']
def vals = ['aaa', 'bbb', 'ccc']
def hash = [:]
keys.eachWithIndex { key, i ->
hash[key] = vals[i]
}

View file

@ -0,0 +1 @@
List.metaClass.hash = { list -> [delegate, list].transpose().collectEntries { [(it[0]): it[1]] } }

View file

@ -0,0 +1 @@
assert (['a', 'b', 'c'].hash(['aaa', 'bbb', 'ccc'])) == [a: 'aaa', b: 'bbb', c: 'ccc']

View file

@ -0,0 +1,7 @@
LOCAL arr1 := { 6, "eight" }, arr2 := { 16, 8 }
LOCAL hash := { => }
LOCAL i, j
FOR EACH i, j IN arr1, arr2
hash[ i ] := j
NEXT

View file

@ -0,0 +1,4 @@
import Data.Map
makeMap ks vs = fromList $ zip ks vs
mymap = makeMap ['a','b','c'] [1,2,3]

View file

@ -0,0 +1,7 @@
from Algorithms import materialize, zip;
main() {
keys = [1, 2, 3];
values = ['a', 'b', 'c'];
hash = materialize( zip( key, values ), lookup );
}

View file

@ -0,0 +1,12 @@
link ximage # to format the structure
procedure main(arglist) #: demonstrate hash from 2 lists
local keylist
if *arglist = 0 then arglist := [1,2,3,4] # ensure there's a list
every put(keylist := [], "key-" || !arglist) # make keys for each entry
every (T := table())[keylist[ i := 1 to *keylist ]] := arglist[i] # create the hash table
write(ximage(T)) # show result
end

View file

@ -0,0 +1 @@
{} addKeysAndValues([:a, :b, :c], [1, 2, 3])

View file

@ -0,0 +1 @@
hash=: vals {~ keys&i.

View file

@ -0,0 +1,19 @@
keys=: 10?.100
vals=: > ;:'zero one two three four five six seven eight nine'
hash=: vals {~ keys&i.
keys
46 99 23 62 42 44 12 5 68 63
$vals
10 5
hash 46
zero
hash 99
one
hash 63 5 12 5 23
nine
seven
six
seven
two

View file

@ -0,0 +1,10 @@
import java.util.HashMap;
public static void main(String[] args){
String[] keys= {"a", "b", "c"};
int[] vals= {1, 2, 3};
HashMap<String, Integer> hash= new HashMap<String, Integer>();
for(int i= 0; i < keys.length; i++){
hash.put(keys[i], vals[i]);
}
}

View file

@ -0,0 +1,6 @@
var keys = ['a', 'b', 'c'];
var values = [1, 2, 3];
var map = {};
for(var i = 0; i < keys.length; i += 1) {
map[ keys[i] ] = values[i];
}

View file

@ -0,0 +1,7 @@
function arrToObj(keys, vals) {
var map = {};
keys.forEach(function (key, index) {
map[key] = val[index];
});
return map;
}

View file

@ -0,0 +1,6 @@
function arrToObj(keys, vals) {
return keys.reduce(function(map, key, index) {
map[key] = vals[index];
return map;
}, {});
}

View file

@ -0,0 +1,12 @@
# hash(keys) creates a JSON object with the given keys as keys
# and values taken from the input array in turn.
# "keys" must be an array of strings.
# The input array may be of any length and have values of any type,
# but only the first (keys|length) values will be used;
# the input will in effect be padded with nulls if required.
def hash(keys):
. as $values
| reduce range(0; keys|length) as $i
( {}; . + { (keys[$i]) : $values[$i] });
[1,2,3] | hash( ["a","b","c"] )

View file

@ -0,0 +1,6 @@
jq -n -f Hash_from_two_arrays.jq
{
"a": 1,
"b": 2,
"c": 3
}

View file

@ -0,0 +1,5 @@
{
"1": 10,
"2": 20,
"3": 30
}

View file

@ -0,0 +1,20 @@
/* Hash from two arrays, in Jsish */
function hashTwo(k:array, v:array):object {
var hash = {};
for (var i = 0; i < k.length; i++) hash[k[i]] = v[i];
return hash;
}
;hashTwo(['a','b','c'], [1,2,3]);
;hashTwo(['a','b'], [1,[2,4,8],3]);
;hashTwo(['a','b','c'], [1,2]);
;hashTwo([], []);
/*
=!EXPECTSTART!=
hashTwo(['a','b','c'], [1,2,3]) ==> { a:1, b:2, c:3 }
hashTwo(['a','b'], [1,[2,4,8],3]) ==> { a:1, b:[ 2, 4, 8 ] }
hashTwo(['a','b','c'], [1,2]) ==> { a:1, b:2, c:undefined }
hashTwo([], []) ==> {}
=!EXPECTEND!=
*/

View file

@ -0,0 +1,4 @@
k = ["a", "b", "c"]
v = [1, 2, 3]
Dict(ki => vi for (ki, vi) in zip(k, v))

View file

@ -0,0 +1 @@
Dict(zip(keys, values))

View file

@ -0,0 +1 @@
Dict{String,Int32}(zip(keys, values))

View file

@ -0,0 +1,10 @@
a: `zero `one `two / symbols
b: 0 1 2
d:. a,'b / create the dictionary
.((`zero;0;)
(`one;1;)
(`two;2;))
d[`one]
1

View file

@ -0,0 +1,19 @@
keys: !10 / 0..9
split:{1_'(&x=y)_ x:y,x}
vals:split["zero one two three four five six seven eight nine";" "]
s:{`$$x} / convert to symbol
d:. (s'keys),'s'vals
.((`"0";`zero;)
(`"1";`one;)
(`"2";`two;)
(`"3";`three;)
(`"4";`four;)
(`"5";`five;)
(`"6";`six;)
(`"7";`seven;)
(`"8";`eight;)
(`"9";`nine;))
$d[s 1] / leading "$" converts back to string
"one"

View file

@ -0,0 +1,8 @@
// version 1.1.0
fun main(args: Array<String>) {
val names = arrayOf("Jimmy", "Bill", "Barack", "Donald")
val ages = arrayOf(92, 70, 55, 70)
val hash = mapOf(*names.zip(ages).toTypedArray())
hash.forEach { println("${it.key.padEnd(6)} aged ${it.value}") }
}

View file

@ -0,0 +1,6 @@
(let* ((keys (list 'foo 'bar 'baz))
(vals (list '"foo data" '"bar data" '"baz data"))
(tuples (: lists zipwith
(lambda (a b) (tuple a b)) keys vals))
(my-dict (: dict from_list tuples)))
(: io format '"fetched data: ~p~n" (list (: dict fetch 'baz my-dict))))

View file

@ -0,0 +1,2 @@
: >table 2 compress -1 transpose ;
['one 'two 'three 'four] [1 2 3 4] >table

View file

@ -0,0 +1 @@
writeln toHash w/a b c d/, [1, 2, 3, 4]

View file

@ -0,0 +1,6 @@
val .new = foldfrom(
f(.hash, .key, .value) more .hash, h{.key: .value},
h{}, w/a b c d/, [1, 2, 3, 4],
)
writeln .new

View file

@ -0,0 +1,11 @@
local(
array1 = array('a', 'b', 'c'),
array2 = array(1, 2, 3),
hash = map
)
loop(#array1 -> size) => {
#hash -> insert(#array1 -> get(loop_count) = #array2 -> get(loop_count))
}
#hash

View file

@ -0,0 +1,11 @@
keys = ["a","b","c"]
values = [1,2,3]
props = [:]
cnt = keys.count
repeat with i = 1 to cnt
props[keys[i]] = values[i]
end repeat
put props
-- ["a": 1, "b": 2, "c": 3]

View file

@ -0,0 +1,12 @@
put "a,b,c" into list1
put 10,20,30 into list2
split list1 using comma
split list2 using comma
repeat with i=1 to the number of elements of list1
put list2[i] into list3[list1[i]]
end repeat
combine list3 using comma and colon
put list3
-- ouput
-- a:10,b:20,c:30

View file

@ -0,0 +1,6 @@
function(keys,values)
local t = {}
for i=1, #keys do
t[keys[i]] = values[i]
end
end

View file

@ -0,0 +1,25 @@
Module CheckAll {
Module CheckVectorType {
Dim Keys$(4), Values(4)
Keys$(0):= "one","two","three","four"
Values(0):=1,2,3,4
Inventory Dict
For i=0 to 3 {
Append Dict, Keys$(i):=Values(i)
}
Print Dict("one")+Dict("four")=Dict("two")+Dict("three") ' true
}
Module CheckVectorType1 {
Dim Keys$(4), Values$(4)
Keys$(0):= "one","two","three","four"
Values$(0):="*","**","***","****"
Inventory Dict
For i=0 to 3 {
Append Dict, Keys$(i):=Values$(i)
}
Print Dict$("one")+Dict$("four")=Dict$("two")+Dict$("three") ' true
}
CheckVectorType
CheckVectorType1
}
CheckAll

View file

@ -0,0 +1,41 @@
Module Checkit {
Function MakeHash(&a$(), &b$()) {
if dimension(a$())<>1 or dimension(b$())<>1 then Error "Only for one dimension arrays"
if len(a$())<>len(b$()) Then Error "Only for same size arrays"
start=dimension(a$(),1, 0)
end=dimension(a$(),1, 1)
start2=dimension(b$(),1, 0)
Inventory Hash
For i=start to end {
if Exist(hash, a$(i)) Then {
\\ s is a pointer to a stack object
s=hash(a$(i))
Stack s {Data i-start+start2}
} Else Append hash, a$(i):=Stack:=i-start+start2
}
=Hash
}
Module PrintKeyItems (hash, akey$, &b$()) {
\\ n=hash(akey$) ' use this if akey$ allways is a proper key
\\ and hide these two lines using \\
if not exist(hash, akey$) then Error "Key not exist"
n=Eval(hash)
For i=1 to Len(n) {
Print b$(stackitem(n,i)),
}
Print
}
Dim a$(2 to 5)
Dim b$(4 to 7)
a$(2)="A", "B","A","C"
b$(4)="A1","B1","A2", "C1"
MyHash=MakeHash(&a$(), &b$())
PrintkeyItems Myhash, "A", &b$() ' print A1 A2
PrintkeyItems Myhash, "B", &b$() ' print B1
PrintkeyItems Myhash, "C", &b$() ' print C1
}
Checkit

View file

@ -0,0 +1,15 @@
function s = StructFromArrays(allKeys, allVals)
% allKeys must be cell array of strings of valid field-names
% allVals can be cell array or array of numbers
% Assumes arrays are same size and valid types
s = struct;
if iscell(allVals)
for k = 1:length(allKeys)
s.(allKeys{k}) = allVals{k};
end
else
for k = 1:length(allKeys)
s.(allKeys{k}) = allVals(k);
end
end
end

View file

@ -0,0 +1,3 @@
A := [1, 2, 3];
B := ["one", "two", three"];
T := table( zip( `=`, A, B ) );

View file

@ -0,0 +1,7 @@
Map[(Hash[Part[#, 1]] = Part[#, 2]) &,
Transpose[{{1, 2, 3}, {"one", "two", "three"}}]]
?? Hash
->Hash[1]=one
->Hash[2]=two
->Hash[3]=three

View file

@ -0,0 +1,9 @@
keys = ["foo", "bar", "val"]
values = ["little", "miss", "muffet"]
d = {}
for i in range(keys.len-1)
d[keys[i]] = values[i]
end for
print d

View file

@ -0,0 +1,20 @@
/**
<doc><h2>Hash from two arrays, in Neko</h2></doc>
**/
var sprintf = $loader.loadprim("std@sprintf", 2)
var array_keys = $array("one",2,"three",4,"five")
var array_vals = $array("six",7,"eight",9,"zero")
var elements = $asize(array_keys)
var table = $hnew(elements)
var step = elements
while (step -= 1) >= 0 $hadd(table, $hkey(array_keys[step]), array_vals[step])
/*
$hiter accepts a hashtable and a function that accepts two args, key, val
*/
var show = function(k, v) $print("Hashed key: ", sprintf("%10d", k), " Value: ", v, "\n")
$hiter(table, show)

View file

@ -0,0 +1,16 @@
using System;
using System.Console;
using Nemerle.Collections;
using Nemerle.Collections.NCollectionsExtensions;
module AssocArray
{
Main() : void
{
def list1 = ["apples", "oranges", "bananas", "kumquats"];
def list2 = [13, 34, 12];
def inventory = Hashtable(ZipLazy(list1, list2));
foreach (item in inventory)
WriteLine("{0}: {1}", item.Key, item.Value);
}
}

View file

@ -0,0 +1,22 @@
/* NetRexx program ****************************************************
* 04.11.2012 Walter Pachl derived from REXX
**********************************************************************/
options replace format comments java crossref savelog symbols nobinary
values='triangle quadrilateral pentagon hexagon heptagon octagon' -
'nonagon decagon dodecagon'
keys ='three four five six seven eight nine ten twelve'
kcopy=keys
k='' /* initialize the arrays */
v=''
value='unknown'
Loop i=1 By 1 While kcopy>'' /* initialize the two arrays */
Parse kcopy ki kcopy; k[i]=ki
Parse values vi values; v[i]=vi
End
Loop j=1 To i-1
value[k[j]]=v[j]
End
Say 'Enter one of these words:'
Say ' 'keys
Parse Ask z
Say z '->' value[z]

View file

@ -0,0 +1,41 @@
/* NetRexx */
options replace format comments java crossref symbols nobinary
vals = [ 'zero', 'one', 'two', 'three', 'four', 'five' ]
keys = [ 'k0', 'k1', 'k2', 'k3', 'k4', 'k5' ]
hash1 = Rexx
hash2 = Map
hash1 = HashMap()
hash2 = ''
makeHash(hash1, keys, vals) -- using a Map object (overloaded method)
makeHash(hash2, keys, vals) -- using a Rexx object (overloaded method)
return
-- Using a Java collection object
method makeHash(hash = Map, keys = Rexx[], vals = Rexx[]) static
loop k_ = 0 to keys.length - 1
hash.put(keys[k_], vals[k_])
end k_
key = Rexx
loop key over hash.keySet()
say key.right(8)':' hash.get(key)
end key
say
return
-- For good measure a version using the default Rexx object as a hash (associative array)
method makeHash(hash = Rexx, keys = Rexx[], vals = Rexx[]) static
loop k_ = 0 to keys.length - 1
hash[keys[k_]] = vals[k_]
end k_
loop key over hash
say key.right(8)':' hash[key]
end key
say
return

View file

@ -0,0 +1,6 @@
import tables, sequtils
let keys = @['a','b','c']
let values = @[1, 2, 3]
let table = toTable zip(keys, values)

View file

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

View file

@ -0,0 +1,5 @@
let keys = [| "foo"; "bar"; "baz" |]
and vals = [| 16384; 32768; 65536 |]
and hash = Hashtbl.create 0;;
Array.iter2 (Hashtbl.add hash) keys vals;;

View file

@ -0,0 +1,7 @@
module StringMap = Map.Make (String);;
let keys = [ "foo"; "bar"; "baz" ]
and vals = [ 16384; 32768; 65536 ]
and map = StringMap.empty;;
let map = List.fold_right2 StringMap.add keys vals map;;

View file

@ -0,0 +1,35 @@
MODULE HashFromArrays;
IMPORT
ADT:Dictionary,
Object:Boxed;
TYPE
Key= STRING;
Value= Boxed.LongInt;
PROCEDURE Do;
VAR
a: ARRAY 128 OF Key;
b: ARRAY 128 OF Value;
hash: Dictionary.Dictionary(Key,Value);
i: INTEGER;
BEGIN
hash := NEW(Dictionary.Dictionary(Key,Value));
a[0] := "uno";
a[1] := "dos";
a[2] := "tres";
a[3] := "cuatro";
b[0] := Boxed.ParseLongInt("1");
b[1] := Boxed.ParseLongInt("2");
b[2] := Boxed.ParseLongInt("3");
b[3] := Boxed.ParseLongInt("4");
i := 0;
WHILE (i < LEN(a)) & (a[i] # NIL) DO
hash.Set(a[i],b[i]);
INC(i)
END;
END Do;
BEGIN
Do;
END HashFromArrays.

View file

@ -0,0 +1,14 @@
use Structure;
bundle Default {
class HashOfTwo {
function : Main(args : System.String[]) ~ Nil {
keys := ["1", "2", "3"];
vals := ["a", "b", "c"];
hash := StringHash->New();
each(i : vals) {
hash->Insert(keys[i], vals[i]->As(Base));
};
}
}
}

View file

@ -0,0 +1,3 @@
NSArray *keys = @[@"a", @"b", @"c"];
NSArray *values = @[@1, @2, @3];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];

View file

@ -0,0 +1,13 @@
array1 = .array~of("Rick", "Mike", "David")
array2 = .array~of("555-9862", "555-5309", "555-6666")
-- if the index items are constrained to string objects, this can
-- be a directory too.
hash = .table~new
loop i = 1 to array1~size
hash[array1[i]] = array2[i]
end
Say 'Enter a name'
Parse Pull name
Say name '->' hash[name]

View file

@ -0,0 +1,10 @@
declare
fun {ZipRecord Keys Values}
{List.toRecord unit {List.zip Keys Values MakePair}}
end
fun {MakePair A B}
A#B
end
in
{Show {ZipRecord [a b c] [1 2 3]}}

View file

@ -0,0 +1 @@
hash(key, value)=Map(matrix(#key,2,x,y,if(y==1,key[x],value[x])));

View file

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

View file

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

Some files were not shown because too many files have changed in this diff Show more