Last active
May 17, 2024 13:06
-
-
Save pppoe252110/d47a08b7472d4ccc14a92a62d2a22bdc to your computer and use it in GitHub Desktop.
A random function to determine a random item from a collection with a chance, with the chance being cast to a value between 0 and 1. Example: chance - 0.1 chance - 0.1 chance - 0.2 become chance - 0.25 chance 0.25 chance - 0.5. This makes it possible not to count a certain chance for hundreds of items in a collection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using UnityEngine; | |
public static class RandomExtension | |
{ | |
public static int ProceedValue(float random, RandomData[] data) | |
{ | |
var cumulativeSumArray = new float[data.Length]; | |
cumulativeSumArray[0] = data[0].chance; | |
for (int i = 1; i < cumulativeSumArray.Length; ++i) | |
cumulativeSumArray[i] = cumulativeSumArray[i - 1] + data[i].chance; | |
random = cumulativeSumArray[^1] * random; | |
int left = 0; | |
int right = cumulativeSumArray.Length - 1; | |
while (left < right) | |
{ | |
int mid = (left + right) / 2; | |
if (cumulativeSumArray[mid] < random) | |
left = mid + 1; | |
else | |
right = mid; | |
} | |
return left; | |
} | |
[Serializable] | |
public class RandomData | |
{ | |
[Range(0f, 1f)] | |
public float chance = 0.5f; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment