Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

RandItems() - Random Items from Array, String, or between 1-MaxNum


  • Please log in to reply
1 reply to this topic
AfterLemon
  • Moderators
  • 237 posts
  • Connoisseur of Boobs
  • Last active: Jan 04 2016 11:12 PM
  • Joined: 09 Oct 2012
Accepted Inputs:
Var Containing Comma-Delimited Strings
Array*
Max Number
 
To output an amount of random numbers using 1-%Max% (inclusive) use:
Msgbox,% RandItems(10,,30)

To output array with an amount of randomized elements from another array use something like:

Arr:=["blah","ahh","har","arrh","barr","bahh","rabb","arbb","harb","brah","rabh","arrh","arrr","rahh","raaa","baaa","haaa"]

Msgbox,% st_Printarr(RandItems(10,,Arr*))
To output string with an amount of random elements from another array use:
MsgBox,% (RandItems(10,1,Arr*)

########FUNCTION#########

RandItems(NumOut,StringOut:=1,ArrOrMaxNum*){
	(ArrOrMaxNum.MaxIndex()=""&&StringOut=1?ArrOrMaxNum[1]:=NumOut:""),t:=1,O:=[]
	If((ArrOrMaxNum[1]&1!="")&&!(ArrOrMaxNum.MaxIndex()>1)){
		While(ArrOrMaxNum[1]--?1:(0,n:=SubStr(n,1,-1)))
			n.=A_Index "|"
	}else If(ArrOrMaxNum.MaxIndex()>1){
		I:=ArrOrMaxNum.MaxIndex()
		While(I--?1:(0,n:=SubStr(n,1,-1)))
			n.=ArrOrMaxNum[A_Index] "|"
	}else n:=ArrOrMaxNum[1]
	Sort,n,Random D|
	Loop,parse,n,|
		(StringOut?O.=A_LoopField "|":O[t].=A_LoopField),t++
	Until T=NumOut+1
return (O.HasKey(O.MaxIndex())?O:RTrim(O,"|"))
}
;==============================
st_printArr(array, depth:=5, indentLevel:=""){
    for k,v in Array
        list.=indentLevel "[" k "]",((IsObject(v)&&depth>1)?(list.="`n" st_printArr(v,depth-1,indentLevel "     ")):list.=" => " v),list.="`n"
return rtrim(list)
}
Note: st_PrintArr function is ONLY used to show contents of the output array.


AfterLemon
  • Moderators
  • 237 posts
  • Connoisseur of Boobs
  • Last active: Jan 04 2016 11:12 PM
  • Joined: 09 Oct 2012

Just updated this code. It now handles better, while allowing for all the same types of input and output data.