Re: Associative array

new topic     » goto parent     » topic index » view thread      » older message » newer message
petelomax said...

I can only assume you were very drunk when you wrote this, because it does not work at all.

Pete

Hum I wasn't , but forgot to change the PEU syntax into Euphoria syntax . Something as sequence a;b;c means sequence a,sequence b, sequence c . Here the converted code witch I test with Euphoria version 2.5 . That why I had to implement a insert() function .

--De var =  {{key's}{value's}}   
--cam = content adresseble memory    
function cam_key_index(sequence var, sequence key)-- binary_search   
-- Find the record in the current table that contains the given key. 
-- If the key is not found, the place in the table where the key would go  
-- if it were inserted is returned as a negative record number. 
-- A binary search is used.   
    atom lo, hi, mid, c 
    lo = 1 
    hi = length(var) 
    mid = 1 
    c = 0   
    while lo <= hi do 
        mid = floor((lo + hi) / 2) 
        c = compare(key, var[mid]) 
        if c < 0 then 
            hi = mid - 1 
        elsif c > 0 then 
            lo = mid + 1 
        else 
            return mid 
        end if 
    end while 
    -- return the position it would have, if inserted now 
    if c > 0 then 
        mid += 1 
    end if 
    return -mid 
end function 
 
global function insert(sequence org, sequence what, integer where)  
if where then  
return org[1..where]&{what}&org[where+1..length(org)] 
else 
return {what}&org[where+1..length(org)] 
end if 
end function                 
 
global function cam_store(sequence var, sequence key, sequence val) 
integer index   
if atom(key) then key={key} end if 
if length(key)>1 then  
 index=cam_key_index(var[1],key[1])  
-- printf(1,"indexs = %i key = %s \n",{index,key[1]}) 
 if index<0 then 
 index=-index-1 
 var[1]=insert(var[1],key[1],index) 
 var[2]=insert(var[2],{{},{}},index) 
 index+=1 
 end if                                
 var[2][index]=cam_store(var[2][index],key[2..length(key)],val) 
else 
 index=cam_key_index(var[1],key[1])  
-- printf(1,"indes = %i key = %s \n",{index,key[1]}) 
 if index<0 then   
 index=-index-1 
 var[1]=insert(var[1],key[1],index)  
 var[2]=insert(var[2],val,index) 
 else   
 var[2][index]=val 
 end if 
end if 
return var  
end function  
 
global function cam_fetch(sequence var, sequence key)  
integer index 
if atom(key) then key={key} end if  
for i=1 to length(key) do  
index=cam_key_index(var[1],key[i]) 
if index>0 then 
var=var[2][index]                           
else 
return 0 
end if 
end for 
return var 
end function                       

Menno .

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu