using Apewer.Internals;
using System;
using System.Collections.Generic;
using System.Text;
namespace Apewer
{
/// 数字实用工具。
public class NumberUtility
{
#region 随机数。
/// 用于生成随机数的时钟位置。
private static int RandomSeed = 327680;
private static float RandomTimer()
{
var now = DateTime.Now;
return (float)((double)(checked((60 * now.Hour + now.Minute) * 60 + now.Second)) + (double)now.Millisecond / 1000.0);
}
private static void RandomInit()
{
float timer = RandomTimer();
int num1 = RandomSeed;
int num2 = BitConverter.ToInt32(BitConverter.GetBytes(timer), 0);
num2 = ((num2 & 65535) ^ num2 >> 16) << 8;
num1 = ((num1 & -16776961) | num2);
RandomSeed = num1;
}
/// 生成不大于 1 的随机数,最小为 0。
public static float RandomFloat(float max = 1F)
{
RandomInit();
int num1 = RandomSeed;
if ((double)max != 0.0)
{
if ((double)max < 0.0)
{
num1 = BitConverter.ToInt32(BitConverter.GetBytes(max), 0);
long vnum2 = (long)num1;
vnum2 &= unchecked((long)((ulong)-1));
num1 = checked((int)(vnum2 + (vnum2 >> 24) & 16777215L));
}
num1 = checked((int)(unchecked((long)num1) * 1140671485L + 12820163L & 16777215L));
}
RandomSeed = num1;
return (float)num1 / 16777216f;
}
/// 生成随机整数,包含最小值和最大值。
/// 最小值。
/// 最大值。
///
public static int RandomInteger(int max, int min = 0)
{
if (max < min)
{
var temp = max;
max = min;
min = temp;
}
float rate = (max - min + 1) * RandomFloat();
int result = min + (int)rate;
return result;
}
#endregion
#region Restrict 约束值范围。
/// 约束值范围,若源值不在范围中,则修改为接近的值。
public static T RestrictValue(T origin, T min, T max) where T : IComparable
{
try
{
if (min.CompareTo(max) > 0) return origin;
if (origin.CompareTo(min) < 0) return min;
if (origin.CompareTo(max) > 0) return max;
return origin;
}
catch { }
return origin;
}
/// 约束值范围,若源值不在范围中,则修改为接近的值。
public static Byte RestrictValue(Byte target, Byte min, Byte max)
{
return RestrictValue(target, min, max);
}
/// 约束值范围,若源值不在范围中,则修改为接近的值。
public static Int16 RestrictValue(Int16 target, Int16 min, Int16 max)
{
return RestrictValue(target, min, max);
}
/// 约束值范围,若源值不在范围中,则修改为接近的值。
public static Int32 RestrictValue(Int32 target, Int32 min, Int32 max)
{
return RestrictValue(target, min, max);
}
/// 约束值范围,若源值不在范围中,则修改为接近的值。
public static Int64 RestrictValue(Int64 target, Int64 min, Int64 max)
{
return RestrictValue(target, min, max);
}
/// 约束值范围,若源值不在范围中,则修改为接近的值。
public static Single RestrictValue(Single target, Single min, Single max)
{
return RestrictValue(target, min, max);
}
/// 约束值范围,若源值不在范围中,则修改为接近的值。
public static Double RestrictValue(Double target, Double min, Double max)
{
return RestrictValue(target, min, max);
}
/// 约束值范围,若源值不在范围中,则修改为接近的值。
public static Decimal RestrictValue(Decimal target, Decimal min, Decimal max)
{
return RestrictValue(target, min, max);
}
#endregion
}
}