예제 #1
0
        public double OnEvaluate(TChromosome specimen)
        {
            var cube        = new RubikCube(RubikCube);
            var bestFitness = double.MaxValue;

            for (int len = 0; len < specimen.Genes.Length; len++)
            {
                var move = new TMove();
                move.Decode((int)specimen.Genes[len]);
                cube.MakeMove(move);
                var fitness = cube.Evaluate();
                if (fitness < bestFitness)
                {
                    bestFitness = fitness;
                    (specimen as RubikGenome).MovesCount = len + 1;
                }
            }
            specimen.Fitness = bestFitness;
            return(bestFitness);
        }
예제 #2
0
        void Solve()
        {
            var best = new RubikGenome();

            best.Fitness = HighScore;
            foreach (var solution in Solutions)
            {
                var genome = new RubikGenome();
                var cube   = new RubikCube(RubikCube);
                for (int i = 0; i < solution.Value.Count; i++)
                {
                    var move = solution.Value[i];
                    cube.MakeMove(move);
                    genome.Genes[i] = move.Encode();
                }
                genome.Fitness = cube.Evaluate();
                if (genome.Fitness < best.Fitness)
                {
                    best = genome;
                }
            }

            if (best.Fitness >= HighScore)
            {
                TChromosome.GenesLength = 30;
                TChromosome.MinGenes    = new double[TChromosome.GenesLength];
                TChromosome.MaxGenes    = new double[TChromosome.GenesLength];
                for (int i = 0; i < TChromosome.MaxGenes.Length; i++)
                {
                    TChromosome.MaxGenes[i] = 9 * RubikCube.N;
                }
                TGA <RubikGenome> .GenerationsCount = 50;
                TGA <RubikGenome> .MutationRatio    = 0.2;
                TGA <RubikGenome> .WinnerRatio      = 0.1;
                var ga = new TGA <RubikGenome>();
                ga.Evaluate = OnEvaluate;
                ga.Progress = OnProgress;
                ga.Execute();
                best = ga.Best;

                if (best.Fitness == 0)
                {
                    SaveSolution(best);
                }
            }

            if (best.Fitness < HighScore)
            {
                Moves.Clear();
                for (int i = 0; i < best.MovesCount; i++)
                {
                    var move = new TMove();
                    move.Decode((int)best.Genes[i]);
                    Moves.Add(move);
                }

                HighScore = best.Fitness;
            }

            MoveTimer.Start();
        }