嗨我有一个List< decimal>包含] 0; 1]之间的值.
我想检查这些值的总和(或小计)是否等于1(或几乎).
我想检查这些值的总和(或小计)是否等于1(或几乎).
期望的结果:
>包含{0.7,0.7,0.7}的列表应返回false;
>包含{0.7,0.3,0.7}的列表应该返回true;
>包含{0.777777,0.2,0.1}的列表应返回false;
>包含{0.33333,0.33333,0.33333}的列表应返回true;
>包含{0.4,0.5,0.6,0.3}的列表应返回true.
显然,我想要的是性能成本最低的东西.
解决方法
更新 – 现在不再重复总和
试试这个
试试这个
bool isClose(IEnumerable<decimal> list,decimal epislon) { return isClose(Enumerable.Empty<decimal>(),list,list.Sum(),epislon); } // Define other methods and classes here bool isClose(IEnumerable<decimal> left,IEnumerable<decimal> right,decimal leftSum,decimal rightSum,decimal epsilon) { if (leftSum>=1-epsilon && leftSum<=1+epsilon) return true; if (leftSum>1+epsilon) return false; if (leftSum+right.Sum()< 1-epsilon) return false; if (!right.Any()) return false; for (var i=0;i<right.Count();i++) { var skip=right.Skip(i); var newItem=skip.First(); if (isClose(left.Concat(skip.Take(1)),skip.Skip(1),leftSum+newItem,rightSum-newItem,epsilon)) return true; } return false; } isClose(new[] {0.7m,0.7m,0.7m},0.001m); // returns false isClose(new[] {0.7m,0.3m,0.001m); //returns true isClose(new[] {0.777777m,0.2m,0.1m},0.001m); //returns false isClose(new[] {0.33333m,0.33333m,0.33333m},0.001m); //returns true
编辑第五次测试
isClose(new[] {0.4m,0.5m,0.6m,0.3m},0.001m); //returns true