Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Weighted Random Choice
#6
here is a working weighted random choice code
Alex i borrowed a few lines from yours and adapted it to made it work for the weights.
output shows the random order and the number of times each item was chosen.
lines 23-35 are there just to show the weighted count is correct. You can remove them 

Function WeightedRandomChoice
Code:
Copy      Help
int apples pears bananas oranges 
str ss=
;apple 9
;pear 1
;banana 10
;orange 20
str s s1
int
foreach s ss
,s.trim
,if findrx(s "\d+$" 0 2 s1)<0
,,end F"line: '{s}' needs a number"
,s.findreplace(s1)
,ARRAY(str) a
,for i 0 val(s1)
,,a[]=s
for i a.len-1 -1 -1
,a.shuffle    
,_s=a[i]
,_s.trim
,out _s
,a.remove(i)
,sel _s
,,case "apple"
,,apples+1
,,case "pear"
,,pears+1
,,case "banana" 
,,bananas+1
,,case "orange"
,,oranges+1
out apples
out pears
out bananas
out oranges


Messages In This Thread
Weighted Random Choice - by sirpipthegreat - 09-04-2018, 01:28 AM
RE: Weighted Random Choice - by Start_Learning - 09-05-2018, 07:50 PM
RE: Weighted Random Choice - by sirpipthegreat - 09-05-2018, 09:05 PM
RE: Weighted Random Choice - by Kevin - 09-06-2018, 02:26 AM
RE: Weighted Random Choice - by AlexZ - 09-06-2018, 03:25 AM
RE: Weighted Random Choice - by Kevin - 09-06-2018, 06:42 AM
RE: Weighted Random Choice - by sirpipthegreat - 09-06-2018, 01:02 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)