数据相关
随机打乱List元素
public static List<T> Shuffle<T>(List<T> original)
{
System.Random randomNum = new System.Random();
int index = 0;
T temp;
for (int i = 0; i < original.Count; i++)
{
index = randomNum.Next(0, original.Count - 1);
if (index != i)
{
temp = original[i];
original[i] = original[index];
original[index] = temp;
}
}
return original;
}
随机X个整数和为Y
public static List<int> xNumTotalY(int count, int targetSum)
{
List<int> numList = new List<int>();
for(int i=0;i<count - 1; ++i)
{
int min = 1;
int max = targetSum - (count - 1 - i);
int randNum = UnityEngine.Random.Range(min, max + 1);
targetSum -= randNum;
numList.Add(randNum);
}
numList.Add(targetSum);
return numList;
}
时间相关
时间戳(秒)转日期
public static DateTime timeStampToDate(long time)
{
DateTime Time = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
DateTime dateTime = Time.AddMilliseconds(time);
return dateTime;
}
获取毫秒时间戳
public static long getSecond()
{
return DateTimeOffset.Now.ToUnixTimeSeconds(); ;
}
秒转分秒
public static string sedMinTime(int sed)
{
return string.Format("{0:00}:{1:00}", (int)sed / 60, (int)sed % 60);
}
场景相关
方向转角度
public static float dirToAngle(Vector2 dir)
{
return Vector2.SignedAngle(Vector2.right, dir);
}
角度转方向
public static Vector2 angleToDir(float angle)
{
float radians = angle * Mathf.Deg2Rad;
float x = Mathf.Cos(radians);
float y = Mathf.Sin(radians);
return new Vector2(x, y);
}
算法相关
按权重随机类
class WeightedRandom<T>
{
private struct Entry
{
public double accumulatedWeight;
public T item;
}
private List<Entry> entries = new List<Entry>();
private double accumulatedWeight;
private System.Random rand = new System.Random();
public void AddEntry(T item, double weight)
{
accumulatedWeight += weight;
entries.Add(new Entry { item = item, accumulatedWeight = accumulatedWeight });
}
public T GetRandom()
{
double r = rand.NextDouble() * accumulatedWeight;
foreach (Entry entry in entries)
{
if (entry.accumulatedWeight >= r)
{
return entry.item;
}
}
return default(T); //should only happen when there are no entries
}
}