Skip to content

Instantly share code, notes, and snippets.

@jubishop
Created February 4, 2010 00:48
Show Gist options
  • Save jubishop/294244 to your computer and use it in GitHub Desktop.
Save jubishop/294244 to your computer and use it in GitHub Desktop.
// $weights = array of weights
// $num = number of result desired.
// returns array of indices chosen from $weights.
function pluck($weights, $num) {
$chosen = array();
while (count($chosen) < $num) {
$sum = array_sum($weights);
$plucked = rand(1, $sum);
$count = 0;
for ($i = 0;
$i < count($weights) && $count < $plucked;
$count += $weights[$i++]);
$chosen[] = --$i;
$weights[$i] = 0;
}
return $chosen;
}
=pluck(array(123, 34, 43, 213, 2, 4, 432), 2);
class Array
def sum
inject {|sum,x| sum+x}
end
def pluck(num)
Array.new(num).fill{pluckElement}
end
def pluckElement
plucked = rand(sum) + 1
count = 0
each_with_index{|weight, i|
if (weight + count >= plucked)
slice!(i) and return i
end
count += weight
}
end
end
puts [123, 34, 43, 213, 2, 4, 432].pluck(2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment