Let’s say I have this array:
[{name: "A", works: true}, {name: "B", works: true}, {name: "C", works: false}]
I want a function to select one element of this array, with, let’s say 80% probability of getting a working element (works: true).
How could I do this elegantly? Would appreciate pseudo-code or code in any language.
(I can use underscore.js if needed, if using js)
In your situation first you are willing to toss a coin to decide if you are going to pick a working element or less. This can be done in JS with
Math.random()which returns a value in[0,1].will set value to true 80% of the times. At this point you already know which kind of element you want so you can just pick a random one and check if works or not. If it’s of the correct type return it, otherwise pick another random one.
If your list is pretty long this may require many picks, in this case you could split the list and keep two lists (working ones and not workings ones).