Skip to content

Instantly share code, notes, and snippets.

@dialupnoises
Created January 11, 2019 03:01
Show Gist options
  • Save dialupnoises/91350a85cff004e85f66812f59ef1a39 to your computer and use it in GitHub Desktop.
Save dialupnoises/91350a85cff004e85f66812f59ef1a39 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using System.Text;
using UnityEngine;
public static class CommandCenterReplacement
{
/// <summary>
/// Returns the test value for this key and user, with different probabilities for each value.
/// For example, to have a 40-60 split between the first and second value, you'd pass probabilities as
/// { 0.4, 0.6 }
/// </summary>
public static string GetTestValue(string testKey, float[] probabilities, string[] testValues)
{
if(probabilities.Length != testValues.Length)
{
throw new Exception("Probabilities and test values must be the same length!");
}
// get a random value between 0 and sum
// https://stackoverflow.com/a/1761646/3697679
var sum = probabilities.Sum();
var currentValue = GetRandom(testKey).NextDouble() * sum;
for(var i = 0; i < probabilities.Length; i++)
{
if(currentValue < probabilities[i])
{
return testValues[i];
}
currentValue -= probabilities[i];
}
// shouldn't get here anyway
return testValues[testValues.Length - 1];
}
/// <summary>
/// Returns the test value for this key and user, with an equal probability between each value.
/// </summary>
public static string GetTestValue(string testKey, string[] testValues)
{
return testValues[GetRandom(testKey).Next(testValues.Length)];
}
/// <summary>
/// Uses the device ID and test key to create a random number generator.
/// </summary>
private static System.Random GetRandom(string testKey)
{
var bytes = Encoding.ASCII.GetBytes(SystemInfo.deviceUniqueIdentifier + testKey);
var seedBytes = new byte[] { 0, 0, 0, 0 };
// xor each group of four bytes together to get a random seed
for(var i = 0; i < bytes.Length; i++)
{
seedBytes[i % 4] ^= bytes[i];
}
// convert our bytes to an int
var seedNum = BitConverter.ToInt32(seedBytes, 0);
// create random
return new System.Random(seedNum);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment