2

I'm currently trying to create a random weighted index picker.

My goal is to randomly pick an element from an array. However, its not just as simple as doing this. Certain elements have a boosted chance of winning. This can be viewed as a sort of lottery

The data structure is as follows:

const users = [
 {userId: 1, multiplier: 0},
 {userId: 2, multiplier: 25}
 {userId: 3, multiplier: 0}
 {userId: 4, multiplier: 25}
 {userId: 5, multiplier: 15}
 {userId: 6, multiplier: 30}
 {userId: 7, multiplier: 35}
 {userId: 8, multiplier: 2}
 {userId: 8, multiplier: 7}
]

Each element of the array counts as one entry. However, the multipliers allow the user to have a higher chance of winning.

A solution which I came up with was view the multipliers as number of tickets so if a user had a multiplier of 25 then they would have 25 tickets.

However, this is very inefficient because when there are 10s of thousands of entries with many multipliers the array size grows at an incredible rate.

I'm not sure how I can make this more efficient.

My solution can be viewed here:

const users = [
 {userId: 1, multiplier: 0},
 {userId: 2, multiplier: 25}
 {userId: 3, multiplier: 0}
 {userId: 4, multiplier: 25}
 {userId: 5, multiplier: 15}
 {userId: 6, multiplier: 30}
 {userId: 7, multiplier: 35}
 {userId: 8, multiplier: 2}
 {userId: 8, multiplier: 7}
]

const potentialWinners = []

users.map((user) => {
    for(let i=0; i < user.multiplier; i++) {
        potentialWinners.push(user.userId)
    }
})

Other solutions which I have viewed seemed quite complicated and I am not great at Math so I had a hard time understanding what was happening.

They also all seem to work based off of percentages, and mine doesn't I'm not entirely sure how I can rework the multiplier system to take into account a multiplied chance of winning.

jaal kamza
  • 213
  • 4
  • 12
  • Just an observation: In the question text, you seem to be (mis-)conflating a factor (multiplier) and a percentage: they aren't the same. – jsejcksn Aug 23 '22 at 19:23
  • Hello, thanks for pointing that out. Sorry for the confusion. I'm not very gifted when it comes to maths, so I am struggling to understand the solutions provided. I suppose what I mean by "25% boosted chance of winning" is to be 25x more likely to win compared to if they didn't have a boost? I believe my original method of making them have ticketsAmount = multiplier does this. But I'm struggling to understand other solutions. – jaal kamza Aug 23 '22 at 19:30
  • multiplier 0 would mean they have no chance of being picked? – trincot Aug 23 '22 at 19:36
  • In my case multiplier `0` means they have no multiplier, but still have a ticket. People with `0` multipliers still have a base chance of `1` to win, if that makes sense? – jaal kamza Aug 23 '22 at 19:38

0 Answers0