Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static string GetRandomValues(string input)
- {
- Regex rgx = new Regex("\\{[^\\{\\}]*\\}", RegexOptions.IgnoreCase);
- MatchCollection matches = rgx.Matches(input);
- foreach (Match match in matches)
- {
- String total = match.Value;
- total = total.Substring(1, total.Length - 1); // Removes "{" and "}"
- String[] parts = total.Split(new char[] { '|' });
- int[] indexWeights = new int[parts.Length];
- int totalWeight = 0;
- for (int i = 0; i < indexWeights.Length; i++) // Initialize
- {
- indexWeights[i] = -1;
- }
- for (int i = 0; i < parts.Length; i++) // Load set weights
- {
- String[] split = parts[i].Split(new char[] { '%' }, 2);
- if (split.Length >= 2 && int.TryParse(split[0], out int weight))
- {
- indexWeights[i] = weight;
- totalWeight += weight;
- parts[i] = split[1];
- }
- }
- if (totalWeight < 100 && totalWeight > 0) // If the weights don't need to be generated, it'll skip over this
- {
- int totalRequired = 0;
- foreach (int weights in indexWeights)
- {
- if (weights < 0)
- {
- totalRequired++;
- }
- }
- if (totalRequired > 0 && totalWeight + totalRequired <= 100) // If generating the values is possible, do it
- {
- int remainingWeight = 100 - totalWeight;
- for (int i = 0; i < parts.Length; i++) // Distribute remaining weight
- {
- if (indexWeights[i] < 0)
- {
- int weight = remainingWeight / totalRequired;
- indexWeights[i] = weight;
- totalWeight += weight;
- remainingWeight = 100 - totalWeight;
- }
- }
- }
- }
- else if (totalWeight == 0) // If the weights were not set at all or are equal to 0
- {
- for (int i = 0; i < indexWeights.Length; i++) // Set all weights to 1
- {
- indexWeights[i] = 0;
- }
- }
- foreach (int weights in indexWeights) // If any weights are unset
- {
- if (weights < 0)
- {
- return "Weights are Unset";
- }
- }
- int[] indexWeightsClone = (int[]) indexWeights.Clone();
- int cumulativeValue = 0;
- int indexChoice = 0;
- for (int i = 0; i < indexWeightsClone.Length; i++)
- {
- cumulativeValue += indexWeightsClone[i];
- indexWeightsClone[i] = cumulativeValue;
- }
- int randomChoice = UnityEngine.Random.Range(0, cumulativeValue);
- for (int i = 0; i < indexWeightsClone.Length; i++)
- {
- if (randomChoice < indexWeightsClone[i])
- {
- indexChoice = i;
- break;
- }
- }
- input.Replace(match.Value, parts[indexChoice]);
- }
- return input;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement