具有相同参数的c#函数在多次运行时返回不同的结果

Rom*_*ter 0 c# arguments return function

我有一个ac#函数,我作为一个更大的算法的一部分,我设计但是这个功能很奇怪.它使用相同的参数计算多次运行中的适应度的不同结果.我没有看到问题出在哪里.任何开明的建议都会受到欢迎.

private readonly Dictionary<int,decimal>_cache = new Dictionary<int, decimal>(); // lookup cache
    private void CalculateFitness(TimeTable timeTable)
    {                      
        const int points = 1;            

        var exams = timeTable.Exams.ToList();
        var combinations = exams.Select(x => exams.Where(y => exams.IndexOf(y) > exams.IndexOf(x))
                                                          .Select(z => new List<Exam> { x, z }))
                                                          .SelectMany(x => x);


        var clash = combinations.Where(touple => touple[0].Period.Id == touple[1].Period.Id && touple[0].Date == touple[1].Date && touple[0].Students.Intersect(touple[1].Students).Any());
        var clCount = clash.Sum(touple => touple[0].Students.Intersect(touple[1].Students).Count());            



        var score = clCount == 0 ? timeTable.Exams.Count : timeTable.Exams.Count - clCount;


        if (_cache.ContainsKey(score))
        {
            timeTable.Fitness = _cache[score];
        }
        else
        {
            timeTable.Fitness = Math.Abs(decimal.Divide(score, (timeTable.Exams.Count * points))); // Calculate Fitness 
            _cache.Add(score, timeTable.Fitness);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Bro*_*ass 6

对于相同的参数,它在多次运行时返回不同的结果

这意味着你的功能不是副作用 - 你正在改变或使用某个地方的全局状态.查找并消除这些并且函数应始终返回预期值.