Created
February 4, 2010 00:48
-
-
Save jubishop/294244 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// $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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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