Page 1 of 1

Array question

Posted: Sat Jul 14, 2007 6:25 am
by kpeters
Assume an array where every key/value pair is unique.

Given the value of an array element, find the corresonding key.

Is there some nifty function for this that I as a newbie don't know or do I have to cycle through the entire array to find the match?

TIA,
Kai

Posted: Sat Jul 14, 2007 8:29 am
by Klaus
Hi Kai,

sorry, no nifty function ;-)

But you could use a nifty trick using the "combine" function to extract the "key" from the array like this:

Given "tArry" is your array and "unique_value" is the value of the unknown key you are looking for.

...
combine tArray by CR and TAB
## This will turn your array into a CR separated list of
## "key TAB value" lines
put lineoffset(TAB & "unique_value",tArray) into tLine
set itemdel to TAB
put item 1 of line tLine of tArray into finally_found_the_fricking_key
...

Et voila, now you finally found the fricking key :-)

Hope that helps.


Best from germany

Klaus

Posted: Sat Jul 14, 2007 5:41 pm
by kpeters
Thanks Klaus ~

that'll work just great for me!

Kai

Posted: Sun Jul 15, 2007 2:25 pm
by Klaus
Hi Kai,

since Rev introduced "repeat for each key tKey in tArray" in version 2.7.2,
maybe a repeat loop is a bit faster nevertheless?


Best

Klaus

Posted: Sun Jul 15, 2007 3:39 pm
by Mark
Hi Klaus and Kai,

Wouldn't that be "repeat for each element" in this case"

Best,

Mark

Posted: Sun Jul 15, 2007 4:59 pm
by Klaus
Mark wrote:Hi Klaus and Kai,

Wouldn't that be "repeat for each element" in this case"

Best,

Mark
Hi Mark,

can you retrieve the key with this? Don't think so.
Kai needs to get the "unknown" key from a "known" value.


Best

Klaus

Posted: Sun Jul 15, 2007 5:07 pm
by xApple

Code: Select all

function getKeyOfValue theArray, theValue
  repeat for each line currentKey in the keys of theArray 
    if theArray[currentKey] = theValue then return currentKey 
  end repeat 
end getKeyOfValue

Posted: Sun Jul 15, 2007 6:01 pm
by Mark
xApple's solution is fine, but just to show that it can be done with elements:

Code: Select all

on mouseUp
  -- make an array
  repeat with x = 1 to 10
    put numtochar(x+96) into myArray["k" & x]
  end repeat
  -- search for key of letter f
  put 0 into myCounter
  repeat for each element myElement in myArray
    add 1 to myCounter
    if myElement is "f" then exit repeat
  end repeat
  put line myCounter of the keys of myArray
end mouseUp
The advantage of this would be that you don't need to look up the element after getting the key first. I don't know what is faster though.

Best,

Mark

Posted: Sun Jul 15, 2007 6:29 pm
by Klaus
Hi all,

and again we proved that there are many rev-ways to skin a rev-cat :-)