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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
| <?php
class WeightedRandomApplication {
public static function gameLootSystem() { echo "=== 游戏掉落系统 ===\n"; $monsterLootTable = [ '金币' => 400, '普通装备' => 300, '稀有装备' => 200, '史诗装备' => 80, '传奇装备' => 18, '神器' => 2 ]; $drops = []; for ($i = 0; $i < 1000; $i++) { $loot = WeightedRandom::linearSelect($monsterLootTable); if (!isset($drops[$loot])) { $drops[$loot] = 0; } $drops[$loot]++; } echo "1000次击杀掉落统计:\n"; foreach ($drops as $item => $count) { $rate = ($count / 1000) * 100; $expected = ($monsterLootTable[$item] / array_sum($monsterLootTable)) * 100; echo sprintf("%-10s: 实际%.2f%% (预期%.2f%%)\n", $item, $rate, $expected); } }
public static function recommendationSystem() { echo "\n=== 商品推荐系统 ===\n"; $products = [ '热门商品A' => 100, '热门商品B' => 80, '普通商品C' => 30, '普通商品D' => 25, '冷门商品E' => 10, '新品F' => 5 ]; echo "今日推荐商品:\n"; for ($i = 0; $i < 5; $i++) { $recommended = WeightedRandom::linearSelect($products); echo "推荐位 " . ($i + 1) . ": " . $recommended . "\n"; } }
public static function lotterySystem() { echo "\n=== 抽奖活动系统 ===\n"; $prizes = [ '一等奖:iPhone' => 1, '二等奖:AirPods' => 5, '三等奖:优惠券' => 50, '参与奖:谢谢参与' => 944 ]; echo "抽奖结果:\n"; $results = []; for ($i = 0; $i < 100; $i++) { $prize = WeightedRandom::linearSelect($prizes); if (!isset($results[$prize])) { $results[$prize] = 0; } $results[$prize]++; } foreach ($results as $prize => $count) { echo $prize . ": " . $count . "次\n"; } }
public static function performanceTest() { echo "\n=== 性能测试 ===\n"; $largeWeightTable = []; for ($i = 0; $i < 1000; $i++) { $largeWeightTable["item_$i"] = mt_rand(1, 100); } $start = microtime(true); for ($i = 0; $i < 10000; $i++) { WeightedRandom::linearSelect($largeWeightTable); } $linearTime = microtime(true) - $start; $bsRandom = new BinarySearchWeightedRandom($largeWeightTable); $start = microtime(true); for ($i = 0; $i < 10000; $i++) { $bsRandom->select(); } $binaryTime = microtime(true) - $start; echo "线性扫描: " . number_format($linearTime, 4) . " 秒\n"; echo "二分查找: " . number_format($binaryTime, 4) . " 秒\n"; echo "性能提升: " . number_format(($linearTime - $binaryTime) / $linearTime * 100, 2) . "%\n"; } }
WeightedRandomApplication::gameLootSystem(); WeightedRandomApplication::recommendationSystem(); WeightedRandomApplication::lotterySystem(); WeightedRandomApplication::performanceTest();
?>
|