lundi 19 septembre 2016

Pick a random weighted element, with sample, no replacement

Given a structure representing a reward in a loot table, where a is the reward type, and 2 is an integer weighting that means that a is twice as likely to get pulled out then d.

Map{
  "a" -> 2
  "b" -> 2
  "c" -> 2
  "d" -> 1
  "e" -> 1
  "f" -> 1
}

How can I generate a sample for display purposes + a winner?

My current (pseudo) code:

list out;
foreach(entry:map){
  for(entry.value){
    out.add(a)
  }
}

Then to create a sample for display.

Collections.shuffle(out);
List display = out.stream()
  .distinct()
  .limit(8)
  .collect(Collectors.toList());

With this code, can I trust .distinct to not skew the odds, if I choose the winner by

winner = display.get(0);

I realize that getting the last element added will possibly skew the results, as after the distinct call happens, it will make it more likely to pick a number with a lower weighting.

but picking the first element of the stream should be trust worthy right? since it was chosen before .distinct had it's state inducing effect?




Aucun commentaire:

Enregistrer un commentaire