wangguan
2020-11-16 9ed56dda66d5e8f6968730a46f908dfe1357c15e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
using System;
using System.Collections.Generic;
using UnityDebug = UnityEngine.Debug;
using UnityRandom = UnityEngine.Random;
 
namespace Core.Extensions
{
    /// <summary>
    /// Extension methods for ILists
    /// </summary>
    public static class IListExtensions
    {
        static readonly Random s_SharedRandom = new Random();
 
        /// <summary>
        /// Select an item from a list using a weighted selection.
        /// </summary>
        /// <remarks>This is an O(n) operation, not constant-time like equal random selection.</remarks>
        /// <param name="elements">An <see cref="System.Collections.Generic.IList{T}" /> of elements to choose from</param>
        /// <param name="weightSum">The sum of all the weights of the elements</param>
        /// <param name="getElementWeight">A delegate to retrieve the weight of a specific element</param>
        /// <returns>An element randomly selected from <paramref name="elements" /></returns>
        public static T WeightedSelection<T>(this IList<T> elements, int weightSum, Func<T, int> getElementWeight)
        {
            int index = elements.WeightedSelectionIndex(weightSum, getElementWeight);
            return elements[index];
        }
 
        /// <summary>
        /// Select an item from a list using a weighted selection.
        /// </summary>
        /// <remarks>This is an O(n) operation, not constant-time like equal random selection.</remarks>
        /// <param name="elements">An <see cref="System.Collections.Generic.IList{T}" /> of elements to choose from</param>
        /// <param name="weightSum">The sum of all the weights of the elements</param>
        /// <param name="getElementWeight">A delegate to retrieve the weight of a specific element</param>
        /// <returns>An element randomly selected from <paramref name="elements" /></returns>
        public static T WeightedSelection<T>(this IList<T> elements, float weightSum, Func<T, float> getElementWeight)
        {
            int index = elements.WeightedSelectionIndex(weightSum, getElementWeight);
            return elements[index];
        }
 
        /// <summary>
        /// Select the index of an item from a list using a weighted selection.
        /// </summary>
        /// <remarks>This is an O(n) operation, not constant-time like equal random selection.</remarks>
        /// <param name="elements">An <see cref="System.Collections.Generic.IList{T}" /> of elements to choose from</param>
        /// <param name="weightSum">The sum of all the weights of the elements</param>
        /// <param name="getElementWeight">A delegate to retrieve the weight of a specific element</param>
        /// <returns>The index of an element randomly selected from <paramref name="elements" /></returns>
        public static int WeightedSelectionIndex<T>(this IList<T> elements, int weightSum, Func<T, int> getElementWeight)
        {
            if (weightSum <= 0)
            {
                throw new ArgumentException("WeightSum should be a positive value", "weightSum");
            }
 
            int selectionIndex = 0;
            int selectionWeightIndex = UnityRandom.Range(0, weightSum);
            int elementCount = elements.Count;
 
            if (elementCount == 0)
            {
                throw new InvalidOperationException("Cannot perform selection on an empty collection");
            }
 
            int itemWeight = getElementWeight(elements[selectionIndex]);
            while (selectionWeightIndex >= itemWeight)
            {
                selectionWeightIndex -= itemWeight;
                selectionIndex++;
 
                if (selectionIndex >= elementCount)
                {
                    throw new ArgumentException("Weighted selection exceeded indexable range. Is your weightSum correct?",
                                                "weightSum");
                }
 
                itemWeight = getElementWeight(elements[selectionIndex]);
            }
 
            return selectionIndex;
        }
 
        /// <summary>
        /// Select the index of an item from a list using a weighted selection.
        /// </summary>
        /// <remarks>This is an O(n) operation, not constant-time like equal random selection.</remarks>
        /// <param name="elements">An <see cref="System.Collections.Generic.IList{T}" /> of elements to choose from</param>
        /// <param name="weightSum">The sum of all the weights of the elements</param>
        /// <param name="getElementWeight">A delegate to retrieve the weight of a specific element</param>
        /// <returns>The index of an element randomly selected from <paramref name="elements" /></returns>
        public static int WeightedSelectionIndex<T>(this IList<T> elements, float weightSum, Func<T, float> getElementWeight)
        {
            if (weightSum <= 0)
            {
                throw new ArgumentException("WeightSum should be a positive value", "weightSum");
            }
 
            int selectionIndex = 0;
 
            double selectedWeight = s_SharedRandom.NextDouble() * weightSum;
            int elementCount = elements.Count;
 
            if (elementCount == 0)
            {
                throw new InvalidOperationException("Cannot perform selection on an empty collection");
            }
 
            double itemWeight = getElementWeight(elements[selectionIndex]);
            while (selectedWeight >= itemWeight)
            {
                selectedWeight -= itemWeight;
                selectionIndex++;
 
                if (selectionIndex >= elementCount)
                {
                    throw new ArgumentException("Weighted selection exceeded indexable range. Is your weightSum correct?",
                                                "weightSum");
                }
 
                itemWeight = getElementWeight(elements[selectionIndex]);
            }
 
            return selectionIndex;
        }
 
        /// <summary>
        /// Shuffle this List into a new array copy
        /// </summary>
        public static T[] Shuffle<T>(this IList<T> original)
        {
            int numItems = original.Count;
            T[] result = new T[numItems];
 
            for (int i = 0; i < numItems; ++i)
            {
                int j = UnityRandom.Range(0, i + 1);
 
                if (j != i)
                {
                    result[i] = result[j];
                }
 
                result[j] = original[i];
            }
 
            return result;
        }
 
        /// <summary>
        /// Goes to the next element of the list
        /// </summary>
        /// <param name="elements">An <see cref="System.Collections.Generic.IList{T}" /> of elements to choose from</param>
        /// <param name="currentIndex">The current index to be changed via reference</param>
        /// <param name="wrap">if the list should wrap</param>
        /// <typeparam name="T">The generic parameter for the list</typeparam>
        /// <returns>true if there is a next item in the list</returns>
        public static bool Next<T>(this IList<T> elements, ref int currentIndex, bool wrap = false)
        {
            int count = elements.Count;
            if (count == 0)
            {
                return false;
            }
 
            currentIndex++;
 
            if (currentIndex >= count)
            {
                if (wrap)
                {
                    currentIndex = 0;
                    return true;
                }
                currentIndex = count - 1;
                return false;
            }
 
            return true;
        }
 
        /// <summary>
        /// Goes to the previous element of the list
        /// </summary>
        /// <param name="elements">An <see cref="System.Collections.Generic.IList{T}" /> of elements to choose from</param>
        /// <param name="currentIndex">The current index to be changed via reference</param>
        /// <param name="wrap">if the list should wrap</param>
        /// <typeparam name="T">The generic parameter for the list</typeparam>
        /// <returns>true if there is a previous item in the list</returns>
        public static bool Prev<T>(this IList<T> elements, ref int currentIndex, bool wrap = false)
        {
            int count = elements.Count;
            if (count == 0)
            {
                return false;
            }
 
            currentIndex--;
 
            if (currentIndex < 0)
            {
                if (wrap)
                {
                    currentIndex = count - 1;
                    return true;
                }
                currentIndex = 0;
                return false;
            }
 
            return true;
        }
    }
}