using System; using System.Collections.Generic; using System.Linq; using Sog; using ProtoCSStruct; namespace Game { public class CommonHelper { public static int GetRandomIndex(int[] li, int sum = 0) { int weight = sum == 0 ? Sum(li, i => i) : sum, tmp = 0; var res = GameServerUtils.GetApp().Rand.Next(0, weight); for (var i = 0; i < li.Length; i++) { tmp += li[i]; if (tmp > res) { return i; } } return -1; } public struct RandomData { public RandomData(int v, int w) { value = v; weight = w; } public int value; public int weight; } public static RandomData emptyRandomData = new RandomData { value = -1, weight = 0 }; public static RandomData CalcRandomIndex(List li, int totalWeight = 0) { int weight = totalWeight == 0 ? li.Aggregate(0, (all, next) => all += next.weight) : -1; if (weight < 0) return emptyRandomData; int tmp = 0; var res = GameServerUtils.GetApp().Rand.Next(0, weight); for (var i = 0; i < li.Count; i++) { tmp += li[i].weight; if (tmp > res) { return li[i]; } } return emptyRandomData; } public static int Find(T[] ts, Func func) { for (int i = 0; i < ts.Length; i++) { if (func(ts[i])) { return i; } } return -1; } public static T[] FindAll(T[] ts, Func func) { List ret = new List(); for (int i = 0; i < ts.Length; i++) { if (func(ts[i])) { ret.Add(ts[i]); } } return ret.ToArray(); } public static T FindOne(T[] ts, Func func) { List ret = new List(); for (int i = 0; i < ts.Length; i++) { if (func(ts[i])) { return ts[i]; } } return default(T); } public static int Sum(T[] ts, Func func) { var sum = 0; for (int i = 0; i < ts.Length; i++) { sum += func(ts[i]); } return sum; } public static V[] Map(T[] ts, Func func) { V[] vs = new V[ts.Length]; for (int i = 0; i < ts.Length; i++) { vs[i] = func(ts[i]); } return vs; } public static int SumRange(Func func, int start, int end, int by = 1) { var sum = 0; for (int i = start; i < end; i += by) { sum += func(i); } return sum; } public static int MatchCount(T[] ts, Func func) { int count = 0; for (int i = 0; i < ts.Length; i++) { if (func(ts[i])) { count += 1; } } return count; } public static int MatchSum(T[] ts, Func boolFunc, Func intFunc) { int count = 0; for (int i = 0; i < ts.Length; i++) { if (boolFunc(ts[i])) { count += intFunc(ts[i]); } } return count; } } }