private static Tuple <int, double, double> SimulatedAnnealingExp(Fitness value, int count) { var historicalFitnesses = Enumerable.Range(1, count).Select(f => new Fitness(f)).Reverse().ToList(); var index = historicalFitnesses.BinarySearch(value); if (index < 0) { index = ~index; } var difference = historicalFitnesses.Count - index; var proportionSimilar = (double)difference / historicalFitnesses.Count; var exp = Math.Exp(-proportionSimilar); return(new Tuple <int, double, double>(index, proportionSimilar, exp)); }
private static void Generate(int diagonalSize, int?maxAge) { var watch = Stopwatch.StartNew(); var nSquared = diagonalSize * diagonalSize; var geneSet = Enumerable.Range(1, nSquared).ToArray(); var expectedSum = diagonalSize * (nSquared + 1) / 2; var geneIndexes = Enumerable.Range(0, geneSet.Length).ToArray(); Fitness FnGetFitness(IReadOnlyList <int> genes) => GetFitness(genes, diagonalSize, expectedSum); void FnDisplay(Chromosome <int, Fitness> candidate) => Display(candidate, watch, diagonalSize); void FnMutate(List <int> genes) => Mutate(genes, geneIndexes); List <int> FnCreate() => geneSet.OrderBy(i => Rand.Random.Next(geneSet.Length)).ToList(); var optimalValue = new Fitness(0); var best = Genetic <int, Fitness> .GetBest(FnGetFitness, nSquared, optimalValue, geneSet, FnDisplay, FnMutate, FnCreate, maxAge); Assert.IsTrue(optimalValue.CompareTo(best.Fitness) <= 0); }