M
mark4asp
Suppose I have the following code. It functions to randomly select a
city based upon the probabilities given by the key differences in the
associative array. [This is just an illustrative example]. Eg.
because the key difference between London and the previous element is
25 (40-15), London has a 25% chance of being selected.
When I call the function getAssocItem to do this I need to send in 2
arguments.
Is there a quick way to get the maximum key value in the associative
array?
PS: These array key values will always be sorted in order but may not
end with the value of 100.
cities = {15:'Berlin', 40:'London', 60:'Madrid', 80:'Paris',
100:'Rome'}
function getAssocItem(ary, maxkey) {
var z = d(maxkey);
var key;
for (key in ary)
if (key>=z)
break;
return ary[key]
}
function d(X){
return Math.floor( (X * Math.random() + 1) )
}
city based upon the probabilities given by the key differences in the
associative array. [This is just an illustrative example]. Eg.
because the key difference between London and the previous element is
25 (40-15), London has a 25% chance of being selected.
When I call the function getAssocItem to do this I need to send in 2
arguments.
Is there a quick way to get the maximum key value in the associative
array?
PS: These array key values will always be sorted in order but may not
end with the value of 100.
cities = {15:'Berlin', 40:'London', 60:'Madrid', 80:'Paris',
100:'Rome'}
function getAssocItem(ary, maxkey) {
var z = d(maxkey);
var key;
for (key in ary)
if (key>=z)
break;
return ary[key]
}
function d(X){
return Math.floor( (X * Math.random() + 1) )
}