4jcraft/targets/minecraft/util/WeighedRandom.cpp
Tropical e4883d87fc
Some checks are pending
Build (Linux, x86-64) / build-linux-amalgamate (push) Waiting to run
Build (Linux, x86-64) / build-linux-full (push) Waiting to run
Format Check / clang-format (push) Waiting to run
Release Nightly (Linux, x86-64) / release-linux (push) Waiting to run
replace __debugbreak with assert, fix full build
2026-04-07 18:58:49 -05:00

69 lines
1.8 KiB
C++

#include "minecraft/util/WeighedRandom.h"
#include <vector>
#include <cassert>
#include "app/linux/Stubs/winapi_stubs.h"
#include "java/Random.h"
int WeighedRandom::getTotalWeight(std::vector<WeighedRandomItem*>* items) {
int totalWeight = 0;
for (auto it = items->begin(); it != items->end(); it++) {
totalWeight += (*it)->randomWeight;
}
return totalWeight;
}
WeighedRandomItem* WeighedRandom::getRandomItem(
Random* random, std::vector<WeighedRandomItem*>* items, int totalWeight) {
if (totalWeight <= 0) {
assert(0);
}
int selection = random->nextInt(totalWeight);
for (auto it = items->begin(); it != items->end(); it++) {
selection -= (*it)->randomWeight;
if (selection < 0) {
return *it;
}
}
return nullptr;
}
WeighedRandomItem* WeighedRandom::getRandomItem(
Random* random, std::vector<WeighedRandomItem*>* items) {
return getRandomItem(random, items, getTotalWeight(items));
}
int WeighedRandom::getTotalWeight(
const std::vector<WeighedRandomItem*>& items) {
int totalWeight = 0;
for (unsigned int i = 0; i < items.size(); i++) {
totalWeight += items[i]->randomWeight;
}
return totalWeight;
}
WeighedRandomItem* WeighedRandom::getRandomItem(
Random* random, const std::vector<WeighedRandomItem*>& items,
int totalWeight) {
if (totalWeight <= 0) {
assert(0);
}
int selection = random->nextInt(totalWeight);
for (unsigned int i = 0; i < items.size(); i++) {
selection -= items[i]->randomWeight;
if (selection < 0) {
return items[i];
}
}
return nullptr;
}
WeighedRandomItem* WeighedRandom::getRandomItem(
Random* random, const std::vector<WeighedRandomItem*>& items) {
return getRandomItem(random, items, getTotalWeight(items));
}