Files
MinecraftConsoles/Minecraft.World/WeighedRandom.cpp
ModMaker101 a9be52c41a Project modernization (#630)
* Fixed boats falling and a TP glitch #266

* Replaced every C-style cast with C++ ones

* Replaced every C-style cast with C++ ones

* Fixed boats falling and a TP glitch #266

* Updated NULL to nullptr and fixing some type issues

* Modernized and fixed a few bugs

- Replaced most instances of `NULL` with `nullptr`.
- Replaced most `shared_ptr(new ...)` with `make_shared`.
- Removed the `nullptr` macro as it was interfering with the actual nullptr keyword in some instances.

* Fixing more conflicts

* Replace int loops with size_t and start work on overrides
2026-03-08 09:56:03 +07:00

72 lines
1.6 KiB
C++

#include "stdafx.h"
#include "WeighedRandom.h"
int WeighedRandom::getTotalWeight(vector<WeighedRandomItem *> *items)
{
int totalWeight = 0;
for( const auto& item : *items)
{
totalWeight += item->randomWeight;
}
return totalWeight;
}
WeighedRandomItem *WeighedRandom::getRandomItem(Random *random, vector<WeighedRandomItem *> *items, int totalWeight)
{
if (totalWeight <= 0)
{
__debugbreak();
}
int selection = random->nextInt(totalWeight);
for(const auto& item : *items)
{
selection -= item->randomWeight;
if (selection < 0)
{
return item;
}
}
return nullptr;
}
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 nullptr;
}
WeighedRandomItem *WeighedRandom::getRandomItem(Random *random, WeighedRandomItemArray items)
{
return getRandomItem(random, items, getTotalWeight(items));
}