//Make a list of possible events, every event with its own chance of happening. One of it will happen by that given chance.
//List enrties set the chance of that event to happen, chances are; (Entry-NextEntry):FirstEntry OR LastEntry:FirstEntry for the last entry! (0:>0 will NEVER happen)
//This function supports lists of at least 256 different events, integers and floats. It returns the 0-based index of the happening event. It only makes sense for longer or variable lists:
//integer event=rl([100,50]); has a 50% chance for both events (returns "0" or "1"
.//integer event=rl([100,50,2]); "0 has 50% chance, "1" hasa 48% chance, "2" has 2% chance.
//integer event=rl([100,80,50,2]); "0" has a 20% chance "1" has a 30% chance, ... you should get its applications by now.
//List must be sorted, largest first, largest can be any number, it is cast into float by default. Tested with integers but any variable-type should work.
integer log2(integer n){if (n) return llCeil(llLog10(n)/llLog10(2)); else return 1;}//this may be inaccurate for large numbers, works fine from 1 to 256, sucks for n=0.
integer rl(list l){//List Numbers set the chance of that event to happen, chances are; (Number-NextNumber):FirstNumber OR LastNumber:FirstNumber for the last number!
float r=llFrand(llList2Float(l,0));//llOwnerSay((string)llList2Float(l,0)+" "+(string)r);
if (r==0.0) return 0;//for even distribution on "=" and faster than "d=d-1".
else{
l=llListReplaceList(l,[r],0,0); //replace first number with the drawn random number
integer c=log2(llGetListLength(l));integer d=1<<
c-1);r=llList2Float(l,0);//loop integers//llOwnerSay((string)(llGetListLength(l)-1)+" needs "+(string)c+" steps and first step is "+(string)d);
do{//llOwnerSay("count "+(string)c+" entry# d "+(string)d+" has value "+(string)llList2Integer(l,d));
if(r>llList2Float(l,d)){if (c>1)d=d-(1<<
c-2)); else d=d-1; //shifting to the left, higher numbers}else{ if (c>1)d=d+(1<<
c-2)); //shifting to the right, lower numbers}}while(--c);
integer gll=llGetListLength(l)-1; //0-indexed list length, needed if list length is not 2^x.
if (d>gll) return gll; else return d;}}
//if you use this recursive you could simulate learning and decision making matrices: "Oh, that didnt work so well, therefore I willl try it with a lower chance, or something else instead, next time"
