Ark Server API (ASA) - Wiki
Loading...
Searching...
No Matches
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"
6#include "Algo/Impl/RangePointerType.h"
7#include "Math/RandomStream.h"
8#include "Templates/UnrealTemplate.h"
9#include "Traits/ElementType.h"
10#include "GenericPlatform/GenericPlatformMath.h"
11
12namespace AlgoImpl
13{
14 template <typename RangeType, typename ProjectionType>
15 typename TRangePointerType<typename TRemoveReference<RangeType>::Type>::Type SelectRandomWeightedBy(RangeType&& Range, ProjectionType Proj)
16 {
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
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{
52 /**
53 * Randomly select an element from a range of elements, weighted by a projection.
54 * The chance of any element being chosen is its weight / the sum of all the weights in the range.
55 * Negative- or zero- weighted elements will not be chosen or count toward the total.
56 *
57 * @param Range The range to select from. Can be any iterable type.
58 * @param Proj The projection to weight the random selection by. Should yield a numeric type.
59 */
60 template <typename RangeType, typename ProjectionType>
61 FORCEINLINE auto SelectRandomWeightedBy(RangeType&& Range, ProjectionType Proj)
62 -> decltype(AlgoImpl::SelectRandomWeightedBy(Forward<RangeType>(Range), MoveTemp(Proj)))
63 {
65 }
66}
#define FORCEINLINE
Definition Platform.h:644
Definition Heapify.h:12
FORCEINLINE auto SelectRandomWeightedBy(RangeType &&Range, ProjectionType Proj) -> decltype(AlgoImpl::SelectRandomWeightedBy(Forward< RangeType >(Range), MoveTemp(Proj)))
TRangePointerType< typenameTRemoveReference< RangeType >::Type >::Type SelectRandomWeightedBy(RangeType &&Range, ProjectionType Proj)