UDocumentation UE5.7 10.02.2026 (Source)
API documentation for Unreal Engine 5.7
SelectRandomWeighted.h
Go to the documentation of this file.
1// Copyright Epic Games, Inc. All Rights Reserved.
2
3#pragma once
4
5#include "Algo/Accumulate.h"
7#include "Math/RandomStream.h"
11
12namespace AlgoImpl
13{
14 template <typename RangeType, typename ProjectionType>
16 {
17 using WeightType = std::decay_t<TInvokeResult_T<ProjectionType, TElementType_T<RangeType>>>;
18
19 const auto SumOfAllDesires = Algo::Accumulate(Range, (WeightType)0, [&Proj](auto Acc, auto&& Elem)
20 {
21 const auto Weight = Invoke(Proj, Elem);
22 // Negative values are invalid and should be ignored
23 return Acc + (Weight < (WeightType)0 ? (WeightType)0 : Weight);
24 });
25
26 auto RandomWeightedAvg = (WeightType)(FMath::FRand() * SumOfAllDesires);
27
28 for (auto&& Elem : Forward<RangeType>(Range))
29 {
30 const auto Weight = Invoke(Proj, Elem);
31
32 // Negative- or zero-weighted elements are never chosen, and are not subtracted from the total since they are not added above.
33 if (Weight <= (WeightType)0)
34 {
35 continue;
36 }
37
39 {
40 return &Elem;
41 }
42
44 }
45
46 return nullptr;
47 }
48}
49
50namespace Algo
51{
60 template <typename RangeType, typename ProjectionType>
66}
#define UE_REWRITE
Definition Platform.h:747
AUTORTFM_INFER UE_FORCEINLINE_HINT constexpr auto Invoke(FuncType &&Func, ArgTypes &&... Args) -> decltype(((FuncType &&) Func)((ArgTypes &&) Args...))
Definition Invoke.h:44
UE_FORCEINLINE_HINT TSharedRef< CastToType, Mode > StaticCastSharedRef(TSharedRef< CastFromType, Mode > const &InSharedRef)
Definition SharedPointer.h:127
UE_INTRINSIC_CAST UE_REWRITE constexpr std::remove_reference_t< T > && MoveTemp(T &&Obj) noexcept
Definition UnrealTemplate.h:520
Definition BinarySearch.h:10
TRangePointerType< typenameTRemoveReference< RangeType >::Type >::Type SelectRandomWeightedBy(RangeType &&Range, ProjectionType Proj)
Definition SelectRandomWeighted.h:15
Definition ParallelSort.h:13
UE_REWRITE auto SelectRandomWeightedBy(RangeType &&Range, ProjectionType Proj) -> decltype(AlgoImpl::SelectRandomWeightedBy(Forward< RangeType >(Range), MoveTemp(Proj)))
Definition SelectRandomWeighted.h:61
T Accumulate(const A &Input, T Init, OpT Op)
Definition Accumulate.h:36
Definition RangePointerType.h:14