I have a c# function that i have as part of a bigger algo that im designing however that function is acting weird. It is calculating different results for fitness on multiple runs with the same arguments. I do not see where the problem is in the function. Any enlightened suggestion would be welcome.
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);
}
}
That means your function is not side effect free – you are changing or using global state somewhere. Find and eliminate those and the function should always return the expected value.