-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomUtils.cs
More file actions
108 lines (89 loc) · 3.23 KB
/
RandomUtils.cs
File metadata and controls
108 lines (89 loc) · 3.23 KB
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
using System.Linq;
using UnityEngine;
namespace Codeavr.RandomExtensions
{
public static class RandomUtils
{
/// <summary>
/// Get random item using weights array
/// </summary>
/// <param name="array">Original array</param>
/// <param name="weights">Weights for each item in array</param>
/// <returns>Random weighted item</returns>
public static T GetWeightedRandomElement<T>(T[] array, float[] weights)
{
if (array.Length != weights.Length)
{
throw new System.ArgumentException($"{nameof(weights)}.length != {nameof(array)}.length");
}
float totalWeight = weights.Sum();
float roll = Random.value * totalWeight;
float cursor = 0;
for (var index = 0; index < array.Length; index++)
{
var item = array[index];
cursor += weights[index];
if (cursor >= roll)
{
return item;
}
}
return default;
}
/// <summary>
/// Create array with no repetitions in a row
/// </summary>
/// <param name="array">Original array</param>
/// <param name="length">Array size</param>
/// <exception cref="System.ArgumentOutOfRangeException"></exception>
public static T[] GenerateNonRepeatingRandomArray<T>(T[] array, int length)
{
if (length < 2)
{
throw new System.ArgumentOutOfRangeException(nameof(length));
}
if (array.Length < 2)
{
throw new System.ArgumentOutOfRangeException(nameof(array.Length));
}
var randomArray = new T[length];
randomArray[0] = array.PickRandom();
for (int i = 1; i < length; i++)
{
do
{
randomArray[i] = array.PickRandom();
} while (randomArray[i].Equals(randomArray[i - 1]));
}
return randomArray;
}
/// <summary>
/// Create looped array with no repetitions in a row
/// </summary>
/// <param name="array">Original array</param>
/// <param name="length">Array size</param>
/// <exception cref="System.ArgumentOutOfRangeException"></exception>
public static T[] GenerateNonRepeatingRandomLoopedArray<T>(T[] array, int length)
{
if (length < 3)
{
throw new System.ArgumentOutOfRangeException(nameof(length));
}
if (array.Length < 3)
{
throw new System.ArgumentOutOfRangeException(nameof(array.Length));
}
var randomArray = new T[length];
randomArray[0] = array.PickRandom();
for (int i = 1; i < length; i++)
{
do
{
randomArray[i] = array.PickRandom();
} while (randomArray[i].Equals(randomArray[i - 1]) ||
randomArray[i].Equals(randomArray[(i + 1) % randomArray.Length]));
}
return randomArray;
}
}
}