aboutsummaryrefslogtreecommitdiff
path: root/Minecraft.World/WeighedRandom.cpp
diff options
context:
space:
mode:
authordaoge_cmd <3523206925@qq.com>2026-03-01 12:16:08 +0800
committerdaoge_cmd <3523206925@qq.com>2026-03-01 12:16:08 +0800
commitb691c43c44ff180d10e7d4a9afc83b98551ff586 (patch)
tree3e9849222cbc6ba49f2f1fc6e5fe7179632c7390 /Minecraft.World/WeighedRandom.cpp
parentdef8cb415354ac390b7e89052a50605285f1aca9 (diff)
Initial commit
Diffstat (limited to 'Minecraft.World/WeighedRandom.cpp')
-rw-r--r--Minecraft.World/WeighedRandom.cpp72
1 files changed, 72 insertions, 0 deletions
diff --git a/Minecraft.World/WeighedRandom.cpp b/Minecraft.World/WeighedRandom.cpp
new file mode 100644
index 00000000..8839b0c5
--- /dev/null
+++ b/Minecraft.World/WeighedRandom.cpp
@@ -0,0 +1,72 @@
+#include "stdafx.h"
+#include "WeighedRandom.h"
+
+int WeighedRandom::getTotalWeight(vector<WeighedRandomItem *> *items)
+{
+ int totalWeight = 0;
+ for( AUTO_VAR(it, items->begin()); it != items->end(); it++ )
+ {
+ totalWeight += (*it)->randomWeight;
+ }
+ return totalWeight;
+}
+
+WeighedRandomItem *WeighedRandom::getRandomItem(Random *random, vector<WeighedRandomItem *> *items, int totalWeight)
+{
+ if (totalWeight <= 0)
+ {
+ __debugbreak();
+ }
+
+ int selection = random->nextInt(totalWeight);
+
+ for( AUTO_VAR(it, items->begin()); it != items->end(); it++ )
+ {
+ selection -= (*it)->randomWeight;
+ if (selection < 0)
+ {
+ return *it;
+ }
+ }
+ return NULL;
+}
+
+WeighedRandomItem *WeighedRandom::getRandomItem(Random *random, vector<WeighedRandomItem *> *items)
+{
+ return getRandomItem(random, items, getTotalWeight(items));
+}
+
+int WeighedRandom::getTotalWeight(WeighedRandomItemArray items)
+{
+ int totalWeight = 0;
+ for( unsigned int i = 0; i < items.length; i++ )
+ {
+ totalWeight += items[i]->randomWeight;
+ }
+ return totalWeight;
+}
+
+WeighedRandomItem *WeighedRandom::getRandomItem(Random *random, WeighedRandomItemArray items, int totalWeight)
+{
+ if (totalWeight <= 0)
+ {
+ __debugbreak();
+ }
+
+ int selection = random->nextInt(totalWeight);
+ for( unsigned int i = 0; i < items.length; i++ )
+ {
+ selection -= items[i]->randomWeight;
+ if (selection < 0)
+ {
+ return items[i];
+ }
+ }
+ return NULL;
+}
+
+
+WeighedRandomItem *WeighedRandom::getRandomItem(Random *random, WeighedRandomItemArray items)
+{
+ return getRandomItem(random, items, getTotalWeight(items));
+} \ No newline at end of file