$rand = $k if rand($sum += $v) <= $v; # This simplifies to: # $rand = 1 if rand(1) <= 1 # this is always true. That's wrong.