using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Pcb.Domain;
namespace Pcb.Common
{
///
/// AI验证
///
public static class AIVerification
{
///
///
///
///
///
public static bool IsAI(List points)
{
bool flag = true;
List pointx = points.Select(t => t.x).ToList();
List pointy = points.Select(t => t.y).ToList();
//标准差低于1时认定为是机器人
if (CalculateStdDev(pointy) > 1)
{
flag = false;
}
if (flag)
{
flag = Judge(CalculateSlope(points));
}
return flag;
}
///
/// 计算标准差
///
///
///
private static double CalculateStdDev(IEnumerable values)
{
double ret = 0;
if (values.Count() > 0)
{
// 计算平均数
double avg = values.Average();
// 计算各数值与平均数的差值的平方,然后求和
double sum = values.Sum(d => Math.Pow(d - avg, 2));
// 除以数量,然后开方
ret = Math.Sqrt(sum / values.Count());
}
return ret;
}
///
/// 计算斜率,返回斜率的变化率
///
private static List CalculateSlope(List source)
{
List slope = new List();
for (int i = 0; i < source.Count - 1; i++)
{
double s = (source[i + 1].y - source[i].y) / (source[i + 1].x - source[i].x);
slope.Add(s);
}
List result = new List();
for (int i = 0; i < slope.Count - 1; i++)
{
if ((slope[i] > 0 && slope[i + 1] < 0) || (slope[i] < 0 && slope[i] > 0))
{
result.Add(1);
}
else
{
result.Add(0);
}
}
return result;
}
///
/// 任意Num个连续数字之和不能超过3
///
///
/// 连续数字个数,默认为4
/// false为不通过
private static bool Judge(List rate, int num = 4)
{
bool flag = rate.Sum() < 3;
flag = rate.Count < 4;
if (!flag)
{
for (int i = 0; i < rate.Count - 3; i++)
{
double sum = 0;
for (int j = 0; j < num; j++)
{
sum += rate[i + j];
}
if (sum > 3)
{
flag = true;
break;
}
}
}
return flag;
}
}
}