Advertisement
Guest User

Untitled

a guest
Oct 10th, 2015
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. diff --git a/src/core/Mixy.pm b/src/core/Mixy.pm
  2. index 4a09c38..9ee5338 100644
  3. --- a/src/core/Mixy.pm
  4. +++ b/src/core/Mixy.pm
  5. @@ -29,21 +29,10 @@ my role Mixy does Baggy {
  6. fail ".pick is not supported on a {self.^name}";
  7. }
  8.  
  9. - multi method roll($count = 1) {
  10. - my @pairs = self.pairs.grep: *.value > 0;
  11. - my $total := [+] @pairs.map: *.value;
  12. - my $rolls = nqp::istype($count,Num)
  13. - ?? $total min $count !! nqp::istype($count,Whatever) ?? Inf !! $count;
  14. -
  15. - sub roll-one ($ignore?){
  16. - my $rand = $total.rand;
  17. - my $seen = 0;
  18. - for @pairs -> $pair {
  19. - return $pair.key if ( $seen += $pair.value ) > $rand;
  20. - }
  21. - }
  22. -
  23. - map &roll-one, 1 .. $rolls;
  24. + multi method roll(Mixy:D:) { Rakudo::Internals.WeightedRoll(self).roll }
  25. + multi method roll(Mixy:D: $count) {
  26. + my $roller = Rakudo::Internals.WeightedRoll(self);
  27. + map { $roller.roll-one }, 1 .. $count;
  28. }
  29. }
  30.  
  31. diff --git a/src/core/Rakudo/Internals.pm b/src/core/Rakudo/Internals.pm
  32. index f46acb7..fa0d464 100644
  33. --- a/src/core/Rakudo/Internals.pm
  34. +++ b/src/core/Rakudo/Internals.pm
  35. @@ -87,6 +87,31 @@ my class Rakudo::Internals {
  36. nqp::getcurhllsym("@END_PHASERS"));
  37. for @END -> $end { $end() };
  38. }
  39. +
  40. + method WeightedRoll(\mix) {
  41. + class {
  42. + has @!pairs;
  43. + has $!total;
  44. +
  45. + method BUILD(\mix) {
  46. + $!total = 0;
  47. + for mix.pairs {
  48. + my $value := .value;
  49. + if $value > 0 {
  50. + @!pairs.push($_);
  51. + $!total = $!total + $value;
  52. + }
  53. + }
  54. + self
  55. + }
  56. + method new(\mix) { nqp::create(self).BUILD(mix) }
  57. + method roll() {
  58. + my $rand = $!total.rand;
  59. + my $seen = 0;
  60. + return .key if ( $seen = $seen + .value ) > $rand for @!pairs;
  61. + }
  62. + }.new(mix)
  63. + }
  64. }
  65.  
  66. # vim: ft=perl6 expandtab sw=4
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement