1

I am writing a program that tells the user which juice taste to buy. I store the avaible juices in an array and the previously bought in another array. Based on how many times a taste has been bought and the time since it was last bought, each taste gets a score. The higher score the more likely it should be for that taste to be selected.

When I arrive at the step to randomly select a juice taste (that is, selecting an index in the array) I have two instances of NSMutableArray, one for the avaible tastes, one for the scores. Both arrays have 17 slots.

It might looks something like this: (only three different tastes)

@[@"Apple juice", @"Orange juice", @"Grape juice"];  // Avaible tastes array
@[19.21, 45.83, 24.84];                              // Scores array

How do I select one taste randomly from this?

Initially, I thought that each taste could have a range, starting from the previous taste's score going to the previous score + the taste's own score. Then a random number between 0 and the total score would be generated. The taste who's range matches the random number would be the one that was going to be selected, but this feels like a overly complex solution.

Is there an easier way?

Edit

By the way, it is written in Objective-C.

  • The "summing up scores" thing is the most sensible I could come up with. Don't really see how that is overly complex, either. – G. Bach Mar 22 '14 at 17:38

2 Answers2

1

On way to solve your problem is what is know as roulette wheel selection. There are a few example implementations in this other question Roulette Selection in Genetic Algorithms

Community
  • 1
  • 1
alejandrorm
  • 133
  • 6
0

Simple option, copy each item into an array multiple times, based on the weighting, and then pick a random item from the array.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • 1
    While that is simple (and will work as intended if by "random" you mean "uniformly at random" and it is guaranteed that the scores are rational numbers), but it may well be ridiculously expensive. Just assume you have two items, one with score 1, one with score 2^15. – G. Bach Mar 22 '14 at 17:37