After reading your blog I came up with this idea in which you'd need double or float probabilities for perhaps extremely low chances of some items drops (like in diablo 2), my idea was that you add items with a percentage probability (0.0-1.0), but if you end up going past 1.0d it would still work.
It isn't true random but if we go by the premise, true random is not the goal anyway. Only thing is that I am not good with benchmarks, I bet this would be better for huge number of items with extremely low probabilities (as keeping an array spot for each chance would eat memory), but I have no idea which would be better for less extreme cases.
Coded it in notepad bear with that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| ShuffleBag { private java.util.ArrayList< Item > items; long drawPeriod; long drawsLeft; public class Item { public Item( String name, double percentage ) { item = name; weigth = percentage; drawsLeft = 0; timesToDraw = 0; doneDrawn = true; } public void setTimesToDraw( long timesToDraw ) { drawsLeft = timesToDraw + this.timesToDraw - drawsLeft; this.timesToDraw = timesToDraw; doneDrawn = ( drawsLeft <= 0 ); } public drawn() { --drawsLeft; if( drawsLeft <= 0 ) doneDrawn = true; } public resetDraws() { drawsLeft = timesToDraw; doneDrawn = ( drawsLeft <= 0 ); } String item; double weight; long drawsLeft; long timesToDraw; boolean doneDrawn; } addItem( String name, double percentage, boolean pack ) { Item item = new Item( name, percentage ); items.add( item ); if( pack ) pack(); } pack() { double totalWeigth = 0; double minWeight = Double.MAX_VALUE; for( Item i : items ) { totalWeigth += i.getWeight(); if( minWeight > i.getWeight() ) minWeight = i.getWeight(); } double leftoverWeight = 0.0d; if( totalWeight < 1.0d ) { leftoverWeight = 1.0d - totalWeight; totalWeight = 1.0d; }; drawPeriod = 0; for( Item i : items ) { long timesToDraw = Math.ceil( i.getWeight() / minWeight ); i.setTimesToDraw( timesToDraw ); drawPeriod += timesToDraw; } drawPeriod += Math.ceil( leftoverWeight / minWeight ); drawsLeft = drawPeriod; } String drawNext() { boolean reset = false; if( drawsLeft <= 0 ) { drawsLeft = drawPeriod; reset = true; }; long rand = RNG.getLong( 0, drawsLeft ); boolean found = false; String s = ""; long k = 0; for( Item i : items ) { if( reset ) i.resetDraws(); if( found ) continue; if( i.isDoneDrawn() ) continue; k += i.getDrawsLeft(); if( rand < k ) { s = i.getItem(); i.drawn(); --drawsLeft; found = true; if( !reset ) break; } } return s; } } |
Hmm thinking about it it would still have the problem where you get several times a low or high random number, perhaps the item list could be shuffled from time to time so the check order changed.